Repository: Orckestra/C1-CMS-Foundation Branch: dev Commit: cf4884bf9894 Files: 4180 Total size: 18.6 MB Directory structure: gitextract_dgapm4gz/ ├── .build/ │ ├── ReleaseCleanup.ps1 │ └── ReleaseCleanupConfiguration.xml ├── .editorconfig ├── .github/ │ └── workflows/ │ └── main.yml ├── .gitignore ├── .tern-project ├── Composite/ │ ├── AspNet/ │ │ ├── Caching/ │ │ │ ├── DonutCacheEntry.cs │ │ │ └── OutputCacheHelper.cs │ │ ├── CmsPageHttpHandler.cs │ │ ├── CmsPageSiteMapNode.cs │ │ ├── CmsPageSiteMapProvider.cs │ │ ├── CmsPagesSiteMapPlugin.cs │ │ ├── ICmsSiteMapNode.cs │ │ ├── ICmsSiteMapProvider.cs │ │ ├── ISchemaOrgSiteMapNode.cs │ │ ├── ISiteMapPlugin.cs │ │ ├── Razor/ │ │ │ ├── C1HtmlHelper.cs │ │ │ ├── CompositeC1WebPage.cs │ │ │ ├── Functions.cs │ │ │ ├── HtmlHelperExtensions.cs │ │ │ ├── NoHttpRazorContext.cs │ │ │ ├── NoHttpRazorRequest.cs │ │ │ ├── NoHttpRazorResponse.cs │ │ │ ├── RazorFunction.cs │ │ │ ├── RazorHelper.cs │ │ │ └── RazorPageTemplate.cs │ │ ├── Security/ │ │ │ ├── FileBasedFunctionEntityToken.cs │ │ │ └── StandardFunctionSecurityAncestorProvider.cs │ │ ├── SiteMapContext.cs │ │ ├── SiteMapHandler.cs │ │ ├── SiteMapNodeChangeFrequency.cs │ │ ├── UserControlFunction.cs │ │ └── WebObjectActivator.cs │ ├── C1Console/ │ │ ├── Actions/ │ │ │ ├── ActionEventSystemFacade.cs │ │ │ ├── ActionExecutorAttribute.cs │ │ │ ├── ActionExecutorFacade.cs │ │ │ ├── ActionLockingException.cs │ │ │ ├── ActionLockingFacade.cs │ │ │ ├── ActionResult.cs │ │ │ ├── AddNewTreeRefresher.cs │ │ │ ├── Data/ │ │ │ │ ├── ActionIdentifier.cs │ │ │ │ ├── DataActionTokenRegisterHandler.cs │ │ │ │ ├── DataActionTokenResolver.cs │ │ │ │ ├── DataActionTokenResolverFacade.cs │ │ │ │ ├── DataActionTokenResolverRegistry.cs │ │ │ │ ├── ProxyDataActionExecuter.cs │ │ │ │ └── ProxyDataActionToken.cs │ │ │ ├── DeleteTreeRefresher.cs │ │ │ ├── DuplicateActionToken.cs │ │ │ ├── FlowControllerAttribute.cs │ │ │ ├── FlowControllerFacade.cs │ │ │ ├── FlowControllerServicesContainer.cs │ │ │ ├── FlowHandle.cs │ │ │ ├── FlowToken.cs │ │ │ ├── FlowTokenSerializer.cs │ │ │ ├── FlowUiDefinitionBase.cs │ │ │ ├── Foundation/ │ │ │ │ ├── ActionExecutorCache.cs │ │ │ │ └── FlowExecutorCache.cs │ │ │ ├── IActionExecutionService.cs │ │ │ ├── IActionExecutor.cs │ │ │ ├── IActionExecutorSerializedParameters.cs │ │ │ ├── IElementInformationService.cs │ │ │ ├── IFlowController.cs │ │ │ ├── IFlowControllerService.cs │ │ │ ├── IFlowUiContainerType.cs │ │ │ ├── IFlowUiDefinition.cs │ │ │ ├── InlineScriptActionFacade.cs │ │ │ ├── MessageBoxActionToken.cs │ │ │ ├── NullFlow.cs │ │ │ ├── ParentTreeRefresher.cs │ │ │ ├── SpecificTreeRefresher.cs │ │ │ ├── StandardUiContainerTypes.cs │ │ │ ├── StandardUiContainerTypesSerializerHandler.cs │ │ │ ├── UpdateTreeRefresher.cs │ │ │ ├── UrlActionToken.cs │ │ │ ├── VisualFlowUiDefinitionBase.cs │ │ │ └── Workflow/ │ │ │ ├── EntityTokenLockedEntityToken.cs │ │ │ └── SecurityViolationWorkflowEntityToken.cs │ │ ├── Commands/ │ │ │ ├── ConsoleCommandFacade.cs │ │ │ ├── Foundation/ │ │ │ │ └── PluginFacades/ │ │ │ │ └── ConsoleCommandHandlerPluginFacade.cs │ │ │ ├── IConsoleCommandHandler.cs │ │ │ └── Plugins/ │ │ │ └── ConsoleCommandHandler/ │ │ │ ├── ConsoleCommandHandlerData.cs │ │ │ ├── NonConfigurableConsoleCommandHandler.cs │ │ │ └── Runtime/ │ │ │ ├── ConsoleCommandHandlerCustomFactory.cs │ │ │ ├── ConsoleCommandHandlerFactory.cs │ │ │ └── ConsoleCommandHandlerSettings.cs │ │ ├── Drawing/ │ │ │ ├── FunctionPresentation.cs │ │ │ └── ImageTemplatedBoxCreator.cs │ │ ├── Elements/ │ │ │ ├── ActionCategory.cs │ │ │ ├── ActionHandle.cs │ │ │ ├── ActionVisualizedData.cs │ │ │ ├── AttachingPoint.cs │ │ │ ├── DialogStrings.cs │ │ │ ├── Element.cs │ │ │ ├── ElementAction.cs │ │ │ ├── ElementActionActivePosition.cs │ │ │ ├── ElementActionSecurityExtensions.cs │ │ │ ├── ElementAttachingPointFacade.cs │ │ │ ├── ElementDataExchangeService.cs │ │ │ ├── ElementDragAndDropInfo.cs │ │ │ ├── ElementFacade.cs │ │ │ ├── ElementHandle.cs │ │ │ ├── ElementHookRegistratorFacade.cs │ │ │ ├── ElementInformationService.cs │ │ │ ├── ElementProviderContext.cs │ │ │ ├── ElementProviderHandle.cs │ │ │ ├── ElementProviderHelpers/ │ │ │ │ ├── AssociatedDataElementProviderHelper/ │ │ │ │ │ ├── AddAssociatedDataWorkflow.layout │ │ │ │ │ ├── AssociatedDataElementProviderHelper.cs │ │ │ │ │ ├── AssociatedDataElementProviderHelperEntityToken.cs │ │ │ │ │ └── AssociatedDataElementProviderHelperSecurityAncestorProvider.cs │ │ │ │ ├── DataGroupingProviderHelper/ │ │ │ │ │ ├── DataGroupingProviderHelper.cs │ │ │ │ │ ├── DataGroupingProviderHelperEntityToken.cs │ │ │ │ │ └── ElipsisEntityToken.cs │ │ │ │ └── VisualFunctionElementProviderHelper/ │ │ │ │ ├── Foundation/ │ │ │ │ │ └── RenderingFunctionNames.cs │ │ │ │ └── VisualFunctionElementProviderHelper.cs │ │ │ ├── ElementVisualizedData.cs │ │ │ ├── Foundation/ │ │ │ │ ├── ElementActionProviderFacade.cs │ │ │ │ ├── ElementActionProviderRegistry.cs │ │ │ │ ├── ElementActionProviderRegistryImpl.cs │ │ │ │ ├── ElementAttachingProviderFacade.cs │ │ │ │ ├── ElementAttachingProviderRegistry.cs │ │ │ │ ├── ElementAttachingProviderRegistryImpl.cs │ │ │ │ ├── ElementProviderLoader.cs │ │ │ │ ├── ElementProviderRegistry.cs │ │ │ │ ├── IElementActionProviderRegistry.cs │ │ │ │ ├── IElementAttachingProviderRegistry.cs │ │ │ │ └── PluginFacades/ │ │ │ │ ├── ElementActionProviderPluginFacade.cs │ │ │ │ ├── ElementAttachingProviderPluginFacade.cs │ │ │ │ └── ElementProviderPluginFacade.cs │ │ │ ├── IElementDataExchangeService.cs │ │ │ ├── IServiceUrlToEntityTokenMapper.cs │ │ │ ├── IUrlToEntityTokenMapper.cs │ │ │ ├── LabeledProperty.cs │ │ │ ├── LabeledPropertyList.cs │ │ │ ├── PiggybagSerializer.cs │ │ │ ├── Plugins/ │ │ │ │ ├── ElementActionProvider/ │ │ │ │ │ ├── ElementActionProviderData.cs │ │ │ │ │ ├── IElementActionProvider.cs │ │ │ │ │ ├── NonConfigurableElementActionProvider.cs │ │ │ │ │ └── Runtime/ │ │ │ │ │ ├── ElementActionProviderCustomFactory.cs │ │ │ │ │ ├── ElementActionProviderDefaultNameRetriever.cs │ │ │ │ │ ├── ElementActionProviderFactory.cs │ │ │ │ │ └── ElementActionProviderSettings.cs │ │ │ │ ├── ElementAttachingProvider/ │ │ │ │ │ ├── ElementAttachingProviderData.cs │ │ │ │ │ ├── IElementAttachingProvider.cs │ │ │ │ │ ├── IMultipleResultElementAttachingProvider.cs │ │ │ │ │ ├── NonConfigurableElementAttachingProvider.cs │ │ │ │ │ └── Runtime/ │ │ │ │ │ ├── ElementAttachingProviderCustomFactory.cs │ │ │ │ │ ├── ElementAttachingProviderDefaultNameRetriever.cs │ │ │ │ │ ├── ElementAttachingProviderFactory.cs │ │ │ │ │ └── ElementAttachingProviderSettings.cs │ │ │ │ └── ElementProvider/ │ │ │ │ ├── ElementProviderData.cs │ │ │ │ ├── HooklessElementProviderData.cs │ │ │ │ ├── ICustomSearchElementProvider.cs │ │ │ │ ├── IDataExchangingElementProvider.cs │ │ │ │ ├── IDragAndDropElementProvider.cs │ │ │ │ ├── IElementProvider.cs │ │ │ │ ├── IHooklessElementProvider.cs │ │ │ │ ├── ILabeledPropertiesElementProvider.cs │ │ │ │ ├── ILocaleAwareElementProvider.cs │ │ │ │ ├── ILocaleAwareLabeledPropertiesElementProvider.cs │ │ │ │ ├── NonConfigurableElementProvider.cs │ │ │ │ ├── NonConfigurableHooklessElementProvider.cs │ │ │ │ └── Runtime/ │ │ │ │ ├── ElementProviderCustomFactory.cs │ │ │ │ ├── ElementProviderDefaultNameRetriever.cs │ │ │ │ ├── ElementProviderFactory.cs │ │ │ │ ├── ElementProviderSettings.cs │ │ │ │ ├── HooklessElementProviderCustomFactory.cs │ │ │ │ ├── HooklessElementProviderDefaultNameRetriever.cs │ │ │ │ └── HooklessElementProviderFactory.cs │ │ │ ├── SearchToken.cs │ │ │ ├── ShowErrorElementHelper.cs │ │ │ ├── TreeLockBehavior.cs │ │ │ └── UrlToEntityTokenFacade.cs │ │ ├── Events/ │ │ │ ├── BindEntityTokenToViewQueueItem.cs │ │ │ ├── BroadcastMessageQueueItem.cs │ │ │ ├── CloseAllViewsMessageQueueItem.cs │ │ │ ├── CloseViewMessageQueueItem.cs │ │ │ ├── CollapseAndRefreshConsoleMessageQueueItem.cs │ │ │ ├── ConsoleFacade.cs │ │ │ ├── ConsoleMessageQueueFacade.cs │ │ │ ├── DialogTypeEnum.cs │ │ │ ├── DownloadFileMessageQueueItem.cs │ │ │ ├── FlushAttribute.cs │ │ │ ├── Foundation/ │ │ │ │ ├── ConsoleMessageQueue.cs │ │ │ │ ├── ConsoleMessageQueueElement.cs │ │ │ │ └── ConsoleMessageQueueElementListValueXmlSerializer.cs │ │ │ ├── GlobalEventSystemFacade.cs │ │ │ ├── IConsoleMessageQueueItem.cs │ │ │ ├── IManagementConsoleMessageService.cs │ │ │ ├── LockSystemConsoleMessageQueueItem.cs │ │ │ ├── LogEntryMessageQueueItem.cs │ │ │ ├── ManagementConsoleMessageService.cs │ │ │ ├── MessageBoxMessageQueueItem.cs │ │ │ ├── OpenExternalViewQueueItem.cs │ │ │ ├── OpenGenericViewQueueItem.cs │ │ │ ├── OpenHandledViewMessageQueueItem.cs │ │ │ ├── OpenSlideViewQueueItem.cs │ │ │ ├── OpenViewMessageQueueItem.cs │ │ │ ├── RebootConsoleMessageQueueItem.cs │ │ │ ├── RefreshTreeMessageQueueItem.cs │ │ │ ├── SaveStatusConsoleMessageQueueItem.cs │ │ │ ├── SelectElementQueueItem.cs │ │ │ └── ViewType.cs │ │ ├── Forms/ │ │ │ ├── BindablePropertyAttribute.cs │ │ │ ├── ControlValuePropertyAttribute.cs │ │ │ ├── CoreFunctions/ │ │ │ │ ├── BooleanCheckFunctionFactory.cs │ │ │ │ ├── CompositeFunctionCall.cs │ │ │ │ ├── NamedValueFunctionFactory.cs │ │ │ │ ├── NullCheckFunctionFactory.cs │ │ │ │ ├── ReplicatorFunctionFactory.cs │ │ │ │ └── StaticMethodCallFunctionFactory.cs │ │ │ ├── CoreUiControls/ │ │ │ │ ├── BaseSelectorUiControl.cs │ │ │ │ ├── BoolSelectorUiControl.cs │ │ │ │ ├── ButtonUiControl.cs │ │ │ │ ├── ButtonUiControlFactoryData.cs │ │ │ │ ├── CheckBoxUiControl.cs │ │ │ │ ├── CheckBoxUiControlFactoryData.cs │ │ │ │ ├── ContainerUiControl.cs │ │ │ │ ├── ContainerUiControlFactoryData.cs │ │ │ │ ├── DataReferenceSelectorUiControl.cs │ │ │ │ ├── DataReferenceTreeSelectorUiControl.cs │ │ │ │ ├── DateSelectorUiControl.cs │ │ │ │ ├── DebugUiControl.cs │ │ │ │ ├── DebugUiControlFactoryData.cs │ │ │ │ ├── DoubleSelectorUiControl.cs │ │ │ │ ├── EnumSelectorUiControl.cs │ │ │ │ ├── FileUploadUiControl.cs │ │ │ │ ├── FontIconSelectorUiControl.cs │ │ │ │ ├── FunctionCallDesignerUiControl.cs │ │ │ │ ├── FunctionParameterDesignerUiControl.cs │ │ │ │ ├── HeadingUiControl.cs │ │ │ │ ├── HierarchicalSelectorUiControl.cs │ │ │ │ ├── HierarchicalSelectorUiControlFactoryData.cs │ │ │ │ ├── HtmlBlobUiControl.cs │ │ │ │ ├── IContainerUiControl.cs │ │ │ │ ├── ITabbedContainerUiControl.cs │ │ │ │ ├── InfoTableUiControl.cs │ │ │ │ ├── MultiContentXhtmlEditorUiControl.cs │ │ │ │ ├── MultiSelectorUiControl.cs │ │ │ │ ├── PageReferenceSelectorUiControl.cs │ │ │ │ ├── QueryCallDefinitionsEditorUiControl.cs │ │ │ │ ├── SaveButtonUiControl.cs │ │ │ │ ├── SelectorUiControl.cs │ │ │ │ ├── SelectorUiControlFactoryData.cs │ │ │ │ ├── SvgIconSelectorUiControl.cs │ │ │ │ ├── TextEditorUiControl.cs │ │ │ │ ├── TextInputUiControl.cs │ │ │ │ ├── TextUiControl.cs │ │ │ │ ├── ToolbarButtonUiControl.cs │ │ │ │ ├── ToolbarButtonUiControlFactoryData.cs │ │ │ │ ├── TreeSelectorUiControl.cs │ │ │ │ ├── TypeFieldDesignerUiControl.cs │ │ │ │ ├── TypeSelectorUiControl.cs │ │ │ │ ├── TypeSelectorUiControlFactoryData.cs │ │ │ │ ├── XhtmlEditorUiControl.cs │ │ │ │ ├── XhtmlEditorUiControlFactoryData.cs │ │ │ │ └── XmlFunctionsDefinitionsEditorUiControl.cs │ │ │ ├── DataServices/ │ │ │ │ ├── FormDefinitionFileMarkupProvider.cs │ │ │ │ ├── Foundation/ │ │ │ │ │ └── FormBuilder.cs │ │ │ │ ├── Functions/ │ │ │ │ │ ├── GetDataFunctionFactory.cs │ │ │ │ │ └── ListDataInterfacesFunctionFactory.cs │ │ │ │ ├── IFormDefinitionFile.cs │ │ │ │ └── UiControls/ │ │ │ │ └── EmbeddedForm.cs │ │ │ ├── Flows/ │ │ │ │ ├── BindingValidationService.cs │ │ │ │ ├── FormFlowEventHandlerDelegate.cs │ │ │ │ ├── FormFlowRenderingService.cs │ │ │ │ ├── FormFlowUiDefinition.cs │ │ │ │ ├── Foundation/ │ │ │ │ │ └── PluginFacades/ │ │ │ │ │ └── UiContainerFactoryFactoryPluginFacade.cs │ │ │ │ ├── IBindingValidationService.cs │ │ │ │ ├── IBindingsProvider.cs │ │ │ │ ├── IFormEventIdentifier.cs │ │ │ │ ├── IFormFlowRenderingService.cs │ │ │ │ ├── IFormMarkupProvider.cs │ │ │ │ ├── IUiContainer.cs │ │ │ │ ├── Plugins/ │ │ │ │ │ └── UiContainerFactory/ │ │ │ │ │ ├── IUiContainerFactory.cs │ │ │ │ │ ├── NonConfigurableUiContainerFactory.cs │ │ │ │ │ ├── Runtime/ │ │ │ │ │ │ ├── UiContainerFactoryCustomFactory.cs │ │ │ │ │ │ ├── UiContainerFactoryDefaultNameRetriever.cs │ │ │ │ │ │ ├── UiContainerFactoryFactory.cs │ │ │ │ │ │ └── UiContainerFactorySettings.cs │ │ │ │ │ └── UiContainerFactoryData.cs │ │ │ │ ├── StandardEventIdentifiers.cs │ │ │ │ └── StringBasedFormMarkupProvider.cs │ │ │ ├── FormCompileException.cs │ │ │ ├── FormDefinition.cs │ │ │ ├── FormFactoryService.cs │ │ │ ├── FormKeyTagNames.cs │ │ │ ├── FormTreeCompiler.cs │ │ │ ├── FormsPropertyAttribute.cs │ │ │ ├── Foundation/ │ │ │ │ ├── FormTreeCompiler/ │ │ │ │ │ ├── CompileContext.cs │ │ │ │ │ ├── CompilePhases/ │ │ │ │ │ │ ├── BuildFromXmlPhase.cs │ │ │ │ │ │ ├── CreateProducersPhase.cs │ │ │ │ │ │ ├── EvaluatePropertiesPhase.cs │ │ │ │ │ │ ├── ExtractUiArtifactsPhase.cs │ │ │ │ │ │ └── UpdateXmlInformationPhase.cs │ │ │ │ │ ├── CompileTreeNodes/ │ │ │ │ │ │ ├── CompileTreeNode.cs │ │ │ │ │ │ ├── ElementCompileTreeNode.cs │ │ │ │ │ │ ├── PropertyCompileTreeNode.cs │ │ │ │ │ │ └── XmlSourceNodeInformation.cs │ │ │ │ │ ├── CompilerGlobals.cs │ │ │ │ │ └── PropertyAssigner.cs │ │ │ │ ├── PluginFacades/ │ │ │ │ │ ├── FunctionFactoryPluginFacade.cs │ │ │ │ │ ├── ProducerMediatorPluginFacade.cs │ │ │ │ │ └── UiControlFactoryPluginFacade.cs │ │ │ │ └── UiControl.cs │ │ │ ├── IFormChannelIdentifier.cs │ │ │ ├── ITestAutomationLocatorInformation.cs │ │ │ ├── IUiControl.cs │ │ │ ├── IValidatingUiControl.cs │ │ │ ├── Plugins/ │ │ │ │ ├── FunctionFactory/ │ │ │ │ │ ├── FunctionFactoryData.cs │ │ │ │ │ ├── IFormFunction.cs │ │ │ │ │ ├── IFunctionFactory.cs │ │ │ │ │ ├── NonConfigurableFunctionFactory.cs │ │ │ │ │ └── Runtime/ │ │ │ │ │ ├── FunctionFactoryCustomFactory.cs │ │ │ │ │ ├── FunctionFactoryDefaultNameRetriever.cs │ │ │ │ │ ├── FunctionFactoryFactory.cs │ │ │ │ │ └── FunctionFactorySettings.cs │ │ │ │ ├── ProducerMediator/ │ │ │ │ │ ├── IProducerMediator.cs │ │ │ │ │ ├── NonConfigurableProducerMediator.cs │ │ │ │ │ ├── ProducerMediatorData.cs │ │ │ │ │ └── Runtime/ │ │ │ │ │ ├── ProducerMediatorCustomFactory.cs │ │ │ │ │ ├── ProducerMediatorDefaultNameRetriever.cs │ │ │ │ │ ├── ProducerMediatorFactory.cs │ │ │ │ │ └── ProducerMediatorSettings.cs │ │ │ │ └── UiControlFactory/ │ │ │ │ ├── IUiControlFactory.cs │ │ │ │ ├── NonConfigurableUiControlFactoryAssembler.cs │ │ │ │ ├── Runtime/ │ │ │ │ │ ├── UiControlFactoryCustomFactory.cs │ │ │ │ │ ├── UiControlFactoryDefaultNameRetriever.cs │ │ │ │ │ ├── UiControlFactoryFactory.cs │ │ │ │ │ └── UiControlFactorySettings.cs │ │ │ │ └── UiControlFactoryData.cs │ │ │ ├── ReadBindingControlValueOverload.cs │ │ │ ├── RequiredValueAttribute.cs │ │ │ ├── SchemaBuilder.cs │ │ │ ├── StandardProducerMediators/ │ │ │ │ ├── BuildinProducerMediator.cs │ │ │ │ ├── BuildinProducers/ │ │ │ │ │ ├── BindProducer.cs │ │ │ │ │ ├── BindingProducer.cs │ │ │ │ │ ├── BindingsProducer.cs │ │ │ │ │ ├── EvalFuncProducer.cs │ │ │ │ │ ├── IBuildinProducer.cs │ │ │ │ │ ├── IfConditionProducer.cs │ │ │ │ │ ├── IfProducer.cs │ │ │ │ │ ├── IfWhenFalseProducer.cs │ │ │ │ │ ├── IfWhenTrueProducer.cs │ │ │ │ │ ├── LayoutProducer.cs │ │ │ │ │ └── ReadProducer.cs │ │ │ │ ├── FunctionProducerMediator.cs │ │ │ │ └── UiControlProducerMediator.cs │ │ │ └── WebChannel/ │ │ │ ├── IClickableTabPanelControl.cs │ │ │ ├── IWebUiContainer.cs │ │ │ ├── IWebUiControl.cs │ │ │ ├── WebManagementChannel.cs │ │ │ ├── WebStandardsChannel.cs │ │ │ └── WebUiHelpers.cs │ │ ├── RichContent/ │ │ │ ├── Components/ │ │ │ │ ├── Component.cs │ │ │ │ ├── ComponentChangeNotifier.cs │ │ │ │ ├── ComponentManager.cs │ │ │ │ └── IComponentProvider.cs │ │ │ └── ContainerClasses/ │ │ │ ├── AntonymContainerClassManager.cs │ │ │ ├── ContainerClassManager.cs │ │ │ └── EqualOrAntonymComparer.cs │ │ ├── Security/ │ │ │ ├── ActionToken.cs │ │ │ ├── ActionTokenSerializer.cs │ │ │ ├── AdministratorAutoCreator.cs │ │ │ ├── AuxiliarySecurityAncestorFacade.cs │ │ │ ├── AuxiliarySecurityAncestorFacadeImpl.cs │ │ │ ├── AuxiliarySecurityAncestorProviderAttribute.cs │ │ │ ├── BuildinPlugins/ │ │ │ │ ├── BuildinLoginSessionStore/ │ │ │ │ │ └── BuildinLoginSessionStore.cs │ │ │ │ └── BuildinUserPermissionDefinitionProvider/ │ │ │ │ └── BuildinUserRoleDefinitionProvider.cs │ │ │ ├── Compatibility/ │ │ │ │ └── LegacySerializedEntityTokenUpgrader.cs │ │ │ ├── ConstructorBasedUserGroupPermissionDefinition.cs │ │ │ ├── ConstructorBasedUserPermissionDefinition.cs │ │ │ ├── Cryptography/ │ │ │ │ └── Cryptographer.cs │ │ │ ├── DataHookMapper.cs │ │ │ ├── DataSecurityAncestorProvider.cs │ │ │ ├── EntityToken.cs │ │ │ ├── EntityTokenCacheFacade.cs │ │ │ ├── EntityTokenHook.cs │ │ │ ├── EntityTokenHtmlPrettyfier.cs │ │ │ ├── EntityTokenHtmlPrettyfierHelper.cs │ │ │ ├── EntityTokenSerializer.cs │ │ │ ├── EntityTokenSerializerException.cs │ │ │ ├── Foundation/ │ │ │ │ ├── HookRegistratorRegistry.cs │ │ │ │ ├── PermissionTypeFacadeCaching.cs │ │ │ │ ├── PluginFacades/ │ │ │ │ │ ├── HookRegistratorPluginFacade.cs │ │ │ │ │ ├── LoginProviderPluginFacade.cs │ │ │ │ │ ├── LoginSessionStorePluginFacade.cs │ │ │ │ │ ├── PasswordRulePluginFacade.cs │ │ │ │ │ ├── UserGroupDefinitionProviderPluginFacade.cs │ │ │ │ │ └── UserRoleDefinitionProviderPluginFacade.cs │ │ │ │ ├── RelationshipGraphLevelEnumerable.cs │ │ │ │ ├── RelationshipGraphLevelEnumerator.cs │ │ │ │ ├── SecurityAncestorFacade.cs │ │ │ │ └── SecurityAncestorProviderCache.cs │ │ │ ├── HashSigner.cs │ │ │ ├── HashValue.cs │ │ │ ├── HookingFacade.cs │ │ │ ├── HookingFacadeEventArgs.cs │ │ │ ├── HookingFacadeImpl.cs │ │ │ ├── IAuxiliarySecurityAncestorFacade.cs │ │ │ ├── IAuxiliarySecurityAncestorProvider.cs │ │ │ ├── IHookingFacade.cs │ │ │ ├── ISecurityAncestorProvider.cs │ │ │ ├── LoginResult.cs │ │ │ ├── NoSecurityEntityToken.cs │ │ │ ├── ParentsFacade.cs │ │ │ ├── PasswordPolicyFacade.cs │ │ │ ├── PermissionDescriptor.cs │ │ │ ├── PermissionType.cs │ │ │ ├── PermissionTypeFacade.cs │ │ │ ├── PermissionsFacade.cs │ │ │ ├── Plugins/ │ │ │ │ ├── HookRegistrator/ │ │ │ │ │ ├── HookRegistratorData.cs │ │ │ │ │ ├── IHookRegistrator.cs │ │ │ │ │ ├── NonConfigurableHookRegistrator.cs │ │ │ │ │ └── Runtime/ │ │ │ │ │ ├── HookRegistratorCustomFactory.cs │ │ │ │ │ ├── HookRegistratorDefaultNameRetriever.cs │ │ │ │ │ ├── HookRegistratorFactory.cs │ │ │ │ │ └── HookRegistratorSettings.cs │ │ │ │ ├── LoginProvider/ │ │ │ │ │ ├── IFormLoginProvider.cs │ │ │ │ │ ├── ILoginProvider.cs │ │ │ │ │ ├── IWindowsLoginProvider.cs │ │ │ │ │ ├── LoginProviderData.cs │ │ │ │ │ ├── NonConfigurableLoginProvider.cs │ │ │ │ │ └── Runtime/ │ │ │ │ │ ├── LoginProviderCustomFactory.cs │ │ │ │ │ ├── LoginProviderDefaultNameRetriever.cs │ │ │ │ │ ├── LoginProviderFactory.cs │ │ │ │ │ └── LoginProviderSettings.cs │ │ │ │ ├── LoginSessionStore/ │ │ │ │ │ ├── ILoginSessionStore.cs │ │ │ │ │ ├── ILoginSessionStoreRedirectedLogout.cs │ │ │ │ │ ├── INoneConfigurationBasedLoginSessionStore.cs │ │ │ │ │ ├── LoginSessionStoreData.cs │ │ │ │ │ ├── NonConfigurableLoginSessionStore.cs │ │ │ │ │ └── Runtime/ │ │ │ │ │ ├── LoginSessionStoreCustomFactory.cs │ │ │ │ │ ├── LoginSessionStoreDefaultNameRetriever.cs │ │ │ │ │ ├── LoginSessionStoreFactory.cs │ │ │ │ │ ├── LoginSessionStoreResolver.cs │ │ │ │ │ └── LoginSessionStoreSettings.cs │ │ │ │ ├── PasswordPolicy/ │ │ │ │ │ ├── IPasswordRule.cs │ │ │ │ │ ├── NonConfigurablePasswordRule.cs │ │ │ │ │ ├── PasswordRuleData.cs │ │ │ │ │ └── Runtime/ │ │ │ │ │ ├── PasswordPolicySettings.cs │ │ │ │ │ ├── PasswordRuleCustomFactory.cs │ │ │ │ │ └── PasswordRuleFactory.cs │ │ │ │ ├── UserGroupPermissionDefinitionProvider/ │ │ │ │ │ ├── IUserGroupPermissionDefinitionProvider.cs │ │ │ │ │ ├── NonConfigurableUserGroupPermissionDefinitionProvider.cs │ │ │ │ │ ├── Runtime/ │ │ │ │ │ │ ├── UserGroupPermissionDefinitionProviderCustomFactory.cs │ │ │ │ │ │ ├── UserGroupPermissionDefinitionProviderDefaultNameRetriever.cs │ │ │ │ │ │ ├── UserGroupPermissionDefinitionProviderFactory.cs │ │ │ │ │ │ └── UserGroupPermissionDefinitionProviderSettings.cs │ │ │ │ │ └── UserGroupPermissionDefinitionProviderData.cs │ │ │ │ └── UserPermissionDefinitionProvider/ │ │ │ │ ├── IUserPermissionDefinitionProvider.cs │ │ │ │ ├── NonConfigurableUserPermissionDefinitionProvider.cs │ │ │ │ ├── Runtime/ │ │ │ │ │ ├── UserPermissionDefinitionProviderCustomFactory.cs │ │ │ │ │ ├── UserPermissionDefinitionProviderDefaultNameRetriever.cs │ │ │ │ │ ├── UserPermissionDefinitionProviderFactory.cs │ │ │ │ │ └── UserPermissionDefinitionProviderSettings.cs │ │ │ │ └── UserPermissionDefinitionProviderData.cs │ │ │ ├── RefreshBeforeAfterEntityTokenFinder.cs │ │ │ ├── RefreshDeleteEntityTokenFinder.cs │ │ │ ├── RelationshipGraph.cs │ │ │ ├── RelationshipGraphLevel.cs │ │ │ ├── RelationshipGraphNode.cs │ │ │ ├── SecurityAncestorProviderAttribute.cs │ │ │ ├── SecurityAncestorProviders/ │ │ │ │ └── NoAncestorSecurityAncestorProvider.cs │ │ │ ├── SecurityResolver.cs │ │ │ ├── SecurityResult.cs │ │ │ ├── SecurityToken.cs │ │ │ ├── UserGroupFacade.cs │ │ │ ├── UserGroupPermissionDefinition.cs │ │ │ ├── UserGroupPerspectiveFacade.cs │ │ │ ├── UserLockoutReason.cs │ │ │ ├── UserPermissionDefinition.cs │ │ │ ├── UserPerspectiveFacade.cs │ │ │ ├── UserToken.cs │ │ │ ├── UserValidationFacade.cs │ │ │ └── Utilities.cs │ │ ├── Tasks/ │ │ │ ├── BaseTaskManager.cs │ │ │ ├── ITaskManager.cs │ │ │ ├── ITaskManagerFacade.cs │ │ │ ├── ITaskManagerFlowControllerService.cs │ │ │ ├── Task.cs │ │ │ ├── TaskContainer.cs │ │ │ ├── TaskManagerFacade.cs │ │ │ ├── TaskManagerFacadeImpl.cs │ │ │ └── TaskManagerFlowControllerService.cs │ │ ├── Trees/ │ │ │ ├── ActionNode.cs │ │ │ ├── AttributeDynamicValuesHelper.cs │ │ │ ├── BuildResult.cs │ │ │ ├── ConfirmActionNode.cs │ │ │ ├── CustomUrlActionNode.cs │ │ │ ├── DataElementsTreeNode.cs │ │ │ ├── DataFieldValueHelper.cs │ │ │ ├── DataFilteringTreeNode.cs │ │ │ ├── DataFolderElementsTreeNode.cs │ │ │ ├── DynamicValuesHelper.cs │ │ │ ├── FieldFilterNode.cs │ │ │ ├── FieldOrderByNode.cs │ │ │ ├── FilterNode.cs │ │ │ ├── Foundation/ │ │ │ │ ├── ActionNodeCreatorFactory.cs │ │ │ │ ├── AttachmentPoints/ │ │ │ │ │ ├── BaseAttachmentPoint.cs │ │ │ │ │ ├── BasePossibleAttachmentPoint.cs │ │ │ │ │ ├── CustomAttachmentPoint.cs │ │ │ │ │ ├── DataItemAttachmentPoint.cs │ │ │ │ │ ├── DataItemPossibleAttachmentPoint.cs │ │ │ │ │ ├── DynamicDataItemAttachmentPoint.cs │ │ │ │ │ ├── IAttachmentPoint.cs │ │ │ │ │ ├── IDataItemAttachmentPoint.cs │ │ │ │ │ ├── INamedAttachmentPoint.cs │ │ │ │ │ ├── IPossibleAttachmentPoint.cs │ │ │ │ │ └── NamedAttachmentPoint.cs │ │ │ │ ├── BuildProcessContext.cs │ │ │ │ ├── DateTimeFormater.cs │ │ │ │ ├── FactoryHelper.cs │ │ │ │ ├── FilterNodeCreatorFactory.cs │ │ │ │ ├── FolderRanges/ │ │ │ │ │ ├── BaseFolderRanges.cs │ │ │ │ │ ├── FolderRangesCreator.cs │ │ │ │ │ ├── FolderRangesFactory.cs │ │ │ │ │ ├── IFolderRange.cs │ │ │ │ │ ├── IFolderRanges.cs │ │ │ │ │ ├── IntFolderRange.cs │ │ │ │ │ ├── IntFolderRanges.cs │ │ │ │ │ ├── StringFolderRange.cs │ │ │ │ │ └── StringFolderRanges.cs │ │ │ │ ├── OrderByNodeCreatorFactory.cs │ │ │ │ ├── StringConstants.cs │ │ │ │ ├── TreeBuilder.cs │ │ │ │ ├── TreeException.cs │ │ │ │ ├── TreeNodeCreatorFactory.cs │ │ │ │ ├── TreePerspectiveEntityToken.cs │ │ │ │ └── TupleIndexer.cs │ │ │ ├── FunctionElementGeneratorTreeNode.cs │ │ │ ├── FunctionFilterNode.cs │ │ │ ├── GenericAddDataActionNode.cs │ │ │ ├── GenericDeleteDataActionNode.cs │ │ │ ├── GenericDuplicateDataActionNode.cs │ │ │ ├── GenericEditDataActionNode.cs │ │ │ ├── IEntityTokenContainingParentEntityToken.cs │ │ │ ├── ITreeFacade.cs │ │ │ ├── LeafDisplayMode.cs │ │ │ ├── MessageBoxActionNode.cs │ │ │ ├── OrderByNode.cs │ │ │ ├── ParentIdFilterNode.cs │ │ │ ├── PiggybagDataFinder.cs │ │ │ ├── PiggybagExtensionMethods.cs │ │ │ ├── ReportFunctionActionNode.cs │ │ │ ├── RootTreeNode.cs │ │ │ ├── SimpleElementTreeNode.cs │ │ │ ├── SortDirection.cs │ │ │ ├── Tree.cs │ │ │ ├── TreeAuxiliaryAncestorProvider.cs │ │ │ ├── TreeDataFieldGroupingElementEntityToken.cs │ │ │ ├── TreeElementActionProvider.cs │ │ │ ├── TreeElementAttachingProvider.cs │ │ │ ├── TreeFacade.cs │ │ │ ├── TreeFacadeImpl.cs │ │ │ ├── TreeFunctionElementGeneratorEntityToken.cs │ │ │ ├── TreeMarkupConstants.cs │ │ │ ├── TreeNode.cs │ │ │ ├── TreeNodeDynamicContext.cs │ │ │ ├── TreeNodeExtensionMethods.cs │ │ │ ├── TreeSharedRootsFacade.cs │ │ │ ├── TreeSimpleElementEntityToken.cs │ │ │ ├── ValidationError.cs │ │ │ └── WorkflowActionNode.cs │ │ ├── Users/ │ │ │ ├── IUserSettingsFacade.cs │ │ │ ├── UserSettings.cs │ │ │ ├── UserSettingsImpl.cs │ │ │ └── UserSettingsMock.cs │ │ └── Workflow/ │ │ ├── Activities/ │ │ │ ├── CancelHandleExternalEventActivity.cs │ │ │ ├── ChildWorkflowDoneHandleExternalEventActivity.cs │ │ │ ├── CloseCurrentViewActivity.cs │ │ │ ├── ConditionalSetStateActivity.cs │ │ │ ├── ConfirmDialogFormActivity.cs │ │ │ ├── CustomEvent01HandleExternalEventActivity.cs │ │ │ ├── CustomEvent02HandleExternalEventActivity.cs │ │ │ ├── CustomEvent03HandleExternalEventActivity.cs │ │ │ ├── CustomEvent04HandleExternalEventActivity.cs │ │ │ ├── CustomEvent05HandleExternalEventActivity.cs │ │ │ ├── DataDialogFormActivity.cs │ │ │ ├── DocumentFormActivity.cs │ │ │ ├── EmptyDocumentFormActivity.cs │ │ │ ├── ExecuteChildWorkflowActivity.cs │ │ │ ├── FinishHandleExternalEventActivity.cs │ │ │ ├── FormsWorkflow.cs │ │ │ ├── Foundation/ │ │ │ │ └── FormsWorkflowBindingCache.cs │ │ │ ├── NextHandleExternalEventActivity.cs │ │ │ ├── PreviewHandleExternalEventActivity.cs │ │ │ ├── PreviousHandleExternalEventActivity.cs │ │ │ ├── RerenderViewActivity.cs │ │ │ ├── SaveAndPublishHandleExternalEventActivity.cs │ │ │ ├── SaveHandleExternalEventActivity.cs │ │ │ ├── ShowConsoleMessageBoxActivity.cs │ │ │ ├── ShowFieldMessageActivity.cs │ │ │ ├── WarningDialogFormActivity.cs │ │ │ └── WizardFormActivity.cs │ │ ├── ActivityExtensionMethods.cs │ │ ├── AllowPersistingWorkflowAttribute.cs │ │ ├── EntityTokenLockAttribute.cs │ │ ├── FilePersistenceService.cs │ │ ├── FormsEventArgs.cs │ │ ├── FormsWorkflowExtensions.cs │ │ ├── Foundation/ │ │ │ ├── FormData.cs │ │ │ ├── FormsWorkflowActivityService.cs │ │ │ ├── FormsWorkflowEventService.cs │ │ │ ├── IWorkflowRuntimeProviderRegistry.cs │ │ │ ├── PluginFacades/ │ │ │ │ ├── IWorkflowRuntimeProviderPluginFacade.cs │ │ │ │ ├── WorkflowRuntimeProviderPluginFacade.cs │ │ │ │ └── WorkflowRuntimeProviderPluginFacadeImpl.cs │ │ │ ├── WorkflowRuntimeProviderRegistry.cs │ │ │ └── WorkflowRuntimeProviderRegistryImpl.cs │ │ ├── IEventHandleFilter.cs │ │ ├── IFormsWorkflowActivityService.cs │ │ ├── IFormsWorkflowEventService.cs │ │ ├── IFormsWorkflowExtension.cs │ │ ├── IWorkflowFacade.cs │ │ ├── Plugins/ │ │ │ └── WorkflowRuntimeProvider/ │ │ │ ├── IWorkflowRuntimeProvider.cs │ │ │ ├── NonConfigurableWorkflowRuntimeProvider.cs │ │ │ ├── Runtime/ │ │ │ │ ├── WorkflowRuntimeProviderCustomFactory.cs │ │ │ │ ├── WorkflowRuntimeProviderDefaultNameRetriever.cs │ │ │ │ ├── WorkflowRuntimeProviderFactory.cs │ │ │ │ └── WorkflowRuntimeProviderSettings.cs │ │ │ └── WorkflowRuntimeProviderData.cs │ │ ├── StateMachineWorkflowInstanceExtensionMethods.cs │ │ ├── WorkflowActionExecutor.cs │ │ ├── WorkflowActionToken.cs │ │ ├── WorkflowFacade.cs │ │ ├── WorkflowFacadeImpl.cs │ │ ├── WorkflowFlowController.cs │ │ ├── WorkflowFlowToken.cs │ │ └── WorkflowTaskManagerEvent.cs │ ├── Composite.FxCop │ ├── Composite.csproj │ ├── Composite.csproj.vspscc │ ├── Core/ │ │ ├── Application/ │ │ │ ├── AppDomainLocker.cs │ │ │ ├── ApplicationOfflineCheckHttpModule.cs │ │ │ ├── ApplicationOnlineHandlerFacade.cs │ │ │ ├── ApplicationOnlineHandlerFacadeImpl.cs │ │ │ ├── ApplicationStartupFacade.cs │ │ │ ├── Foundation/ │ │ │ │ ├── ApplicationStartupHandlerRegistry.cs │ │ │ │ ├── ApplicationStartupHandlerRegistryImpl.cs │ │ │ │ ├── IApplicationStartupHandlerRegistry.cs │ │ │ │ └── PluginFacades/ │ │ │ │ ├── ApplicationOnlineHandlerPluginFacade.cs │ │ │ │ └── ApplicationStartupHandlerPluginFacade.cs │ │ │ ├── GlobalFileLocker.cs │ │ │ ├── IApplicationOnlineHandlerFacade.cs │ │ │ ├── Job.cs │ │ │ ├── Plugins/ │ │ │ │ ├── ApplicationOnlineHandler/ │ │ │ │ │ ├── ApplicationOnlineHandlerData.cs │ │ │ │ │ ├── IApplicationOnlineHandler.cs │ │ │ │ │ ├── NonConfigurableApplicationOnlineHandler.cs │ │ │ │ │ └── Runtime/ │ │ │ │ │ ├── ApplicationOnlineHandlerCustomFactory.cs │ │ │ │ │ ├── ApplicationOnlineHandlerDefaultNameRetriever.cs │ │ │ │ │ ├── ApplicationOnlineHandlerFactory.cs │ │ │ │ │ └── ApplicationOnlineHandlerSettings.cs │ │ │ │ └── ApplicationStartupHandler/ │ │ │ │ ├── ApplicationStartupHandlerData.cs │ │ │ │ ├── IApplicationStartupHandler.cs │ │ │ │ ├── NonConfigurableApplicationStartupHandler.cs │ │ │ │ └── Runtime/ │ │ │ │ ├── ApplicationStartupHandlerCustomFactory.cs │ │ │ │ ├── ApplicationStartupHandlerDefaultNameRetriever.cs │ │ │ │ ├── ApplicationStartupHandlerFactory.cs │ │ │ │ └── ApplicationStartupHandlerSettings.cs │ │ │ ├── ShutdownGuard.cs │ │ │ ├── SystemGlobalSemaphore.cs │ │ │ └── TempDirectoryFacade.cs │ │ ├── Caching/ │ │ │ ├── CacheManager.cs │ │ │ ├── CachePriority.cs │ │ │ ├── CacheSettings.cs │ │ │ ├── CacheStatistic.cs │ │ │ ├── CacheType.cs │ │ │ ├── Design/ │ │ │ │ ├── LightweightCache.cs │ │ │ │ └── MixedCache.cs │ │ │ ├── FileRelatedDataCache.cs │ │ │ ├── ICache.cs │ │ │ └── RequestLifetimeCache.cs │ │ ├── Collections/ │ │ │ ├── Generic/ │ │ │ │ ├── CastEnumerable.cs │ │ │ │ ├── CastEnumerator.cs │ │ │ │ ├── DictionaryExtensionMethods.cs │ │ │ │ ├── Hashset.cs │ │ │ │ ├── Hashtable.cs │ │ │ │ ├── ReadOnlyDictionary.cs │ │ │ │ ├── ReadOnlyList.cs │ │ │ │ └── ResourceLocker.cs │ │ │ ├── INamespaceTreeBuilderLeafInfo.cs │ │ │ ├── NamespaceTreeBuilder.cs │ │ │ └── NamespaceTreeBuilderFolder.cs │ │ ├── Configuration/ │ │ │ ├── AppCodeTypeNotFoundConfigurationException.cs │ │ │ ├── BuildinPlugins/ │ │ │ │ └── GlobalSettingsProvider/ │ │ │ │ ├── BuildinCacheSettings.cs │ │ │ │ ├── BuildinCachingSettings.cs │ │ │ │ └── BuildinGlobalSettingsProvider.cs │ │ │ ├── C1Configuration.cs │ │ │ ├── Configuration.cs │ │ │ ├── ConfigurationServices.cs │ │ │ ├── FileConfigurationSource.cs │ │ │ ├── FileConfigurationSourceImplementation.cs │ │ │ ├── Foundation/ │ │ │ │ └── PluginFacades/ │ │ │ │ └── GlobalSettingsProviderPluginFacade.cs │ │ │ ├── GlobalSettingsFacade.cs │ │ │ ├── GlobalSettingsFacadeImpl.cs │ │ │ ├── ICachingSettings.cs │ │ │ ├── IGlobalSettingsFacade.cs │ │ │ ├── InstallationInformationFacade.cs │ │ │ ├── NameTypeManagerTypeConfigurationElement.cs │ │ │ ├── NameTypeManagerTypeConfigurationElementCollection.cs │ │ │ ├── Plugins/ │ │ │ │ └── GlobalSettingsProvider/ │ │ │ │ ├── GlobalSettingsProviderData.cs │ │ │ │ ├── IGlobalSettingsProvider.cs │ │ │ │ ├── NonConfigurableGlobalSettingsProvider.cs │ │ │ │ └── Runtime/ │ │ │ │ ├── GlobalSettingsProviderCustomFactory.cs │ │ │ │ ├── GlobalSettingsProviderDefaultNameRetriever.cs │ │ │ │ ├── GlobalSettingsProviderFactory.cs │ │ │ │ └── GlobalSettingsProviderSettings.cs │ │ │ ├── SimpleNameTypeConfigurationElement.cs │ │ │ ├── SimpleNameTypeConfigurationElementCollection.cs │ │ │ ├── SystemSetupFacade.cs │ │ │ └── TypeManagerTypeNameConverter.cs │ │ ├── EmptyDisposable.cs │ │ ├── Extensions/ │ │ │ ├── ByteArrayExtensionMethods.cs │ │ │ ├── DateTimeExtensionMethods.cs │ │ │ ├── DictionaryExtensionMethods.cs │ │ │ ├── ExpressionExtensionMethods.cs │ │ │ ├── HttpContextExtensionMethods.cs │ │ │ ├── IApplicationHostExtensionMethods.cs │ │ │ ├── IEnumerableExtensionMethods.cs │ │ │ ├── IQueryableExtensionMethods.cs │ │ │ ├── MethodInfoExtensionMethods.cs │ │ │ ├── PageUrlDataExtensionMethods.cs │ │ │ ├── StackTraceExtensionMethods.cs │ │ │ ├── StreamExtensionMethods.cs │ │ │ └── StringExtensionMethods.cs │ │ ├── HashingHelper.cs │ │ ├── IMailer.cs │ │ ├── IO/ │ │ │ ├── C1Directory.cs │ │ │ ├── C1DirectoryInfo.cs │ │ │ ├── C1File.cs │ │ │ ├── C1FileInfo.cs │ │ │ ├── C1FileStream.cs │ │ │ ├── C1FileSystemInfo.cs │ │ │ ├── C1FileSystemWatcher.cs │ │ │ ├── C1StreamReader.cs │ │ │ ├── C1StreamWriter.cs │ │ │ ├── C1WaitForChangedResult.cs │ │ │ ├── DirectoryUtils.cs │ │ │ ├── FileUtils.cs │ │ │ ├── Foundation/ │ │ │ │ └── PluginFacades/ │ │ │ │ └── IOProviderPluginFacade.cs │ │ │ ├── IOFacade.cs │ │ │ ├── MimeTypeInfo.cs │ │ │ ├── PathUtil.cs │ │ │ ├── Plugins/ │ │ │ │ └── IOProvider/ │ │ │ │ ├── IC1Configuration.cs │ │ │ │ ├── IC1Directory.cs │ │ │ │ ├── IC1DirectoryInfo.cs │ │ │ │ ├── IC1File.cs │ │ │ │ ├── IC1FileInfo.cs │ │ │ │ ├── IC1FileStream.cs │ │ │ │ ├── IC1FileSystemWatcher.cs │ │ │ │ ├── IC1StreamReader.cs │ │ │ │ ├── IC1StreamWriter.cs │ │ │ │ ├── IIOProvider.cs │ │ │ │ ├── IOProviderData.cs │ │ │ │ ├── NonConfigurableIOProvider.cs │ │ │ │ └── Runtime/ │ │ │ │ ├── IOProviderCustomFactory.cs │ │ │ │ ├── IOProviderDefaultNameRetriever.cs │ │ │ │ ├── IOProviderFactory.cs │ │ │ │ └── IOProviderSettings.cs │ │ │ ├── ReparsePointUtils.cs │ │ │ ├── StreamUtils.cs │ │ │ └── Zip/ │ │ │ ├── IZipFileSystem.cs │ │ │ └── ZipFileSystem.cs │ │ ├── Implementation/ │ │ │ ├── C1ConfigurationImplementation.cs │ │ │ ├── C1DirectoryImplementation.cs │ │ │ ├── C1DirectoryInfoImplementation.cs │ │ │ ├── C1FileImplementation.cs │ │ │ ├── C1FileInfoImplementation.cs │ │ │ ├── C1FileStreamImplementation.cs │ │ │ ├── C1FileSystemWatcherImplementation.cs │ │ │ ├── C1StreamReaderImplementation.cs │ │ │ ├── C1StreamWriterImplementation.cs │ │ │ ├── DataConnectionBase.cs │ │ │ ├── DataConnectionImplementation.cs │ │ │ ├── DataEventsImplementation.cs │ │ │ ├── ImplementationContainer.cs │ │ │ ├── ImplementationFactory.cs │ │ │ ├── LogImplementation.cs │ │ │ ├── PackageLicenseHelperImplementation.cs │ │ │ ├── PackageUtilsImplementation.cs │ │ │ ├── PageDataConnectionImplementation.cs │ │ │ ├── SitemapNavigatorImplementation.cs │ │ │ └── StatelessDataConnectionImplementation.cs │ │ ├── Instrumentation/ │ │ │ ├── DisposableResourceTracer.cs │ │ │ ├── Foundation/ │ │ │ │ ├── IPerformanceCounterProviderRegistry.cs │ │ │ │ ├── NoopTimerProfiler.cs │ │ │ │ ├── PerformanceCounterProviderRegistry.cs │ │ │ │ ├── PerformanceCounterProviderRegistryImpl.cs │ │ │ │ └── PluginFacades/ │ │ │ │ └── PerformanceCounterProviderPluginFacade.cs │ │ │ ├── IPerformanceCounterFacade.cs │ │ │ ├── IPerformanceCounterToken.cs │ │ │ ├── LogExecutionTime.cs │ │ │ ├── Measurement.cs │ │ │ ├── PerformanceCounterFacade.cs │ │ │ ├── PerformanceCounterFacadeImpl.cs │ │ │ ├── Plugin/ │ │ │ │ ├── IPerformanceCounterProvider.cs │ │ │ │ ├── NonConfigurablePerformanceCounterProvider.cs │ │ │ │ ├── PerformanceCounterProviderData.cs │ │ │ │ └── Runtime/ │ │ │ │ ├── PerformanceCounterProviderCustomFactory.cs │ │ │ │ ├── PerformanceCounterProviderDefaultNameRetriever.cs │ │ │ │ ├── PerformanceCounterProviderFactory.cs │ │ │ │ └── PerformanceCounterProviderSettings.cs │ │ │ ├── Profiler.cs │ │ │ ├── ProfilerReport.cs │ │ │ ├── TimerProfiler.cs │ │ │ └── TimerProfilerFacade.cs │ │ ├── Linq/ │ │ │ ├── ExpressionBuilder.cs │ │ │ ├── ExpressionCreator.cs │ │ │ ├── ExpressionExtensionMethods.cs │ │ │ ├── ExpressionExtractor.cs │ │ │ ├── ExpressionHelper.cs │ │ │ ├── ExpressionVisitors/ │ │ │ │ ├── CacheKeyBuilderExpressionVisitor.cs │ │ │ │ └── FindFirstParameterExpressionVisitor.cs │ │ │ ├── Extensions.cs │ │ │ ├── PropertyInfoValueCollectioncs.cs │ │ │ ├── TypeExtensions.cs │ │ │ └── TypeHelpers.cs │ │ ├── Localization/ │ │ │ ├── LocalizationFacade.cs │ │ │ ├── LocalizationParser.cs │ │ │ └── LocalizationXmlConstants.cs │ │ ├── Log.cs │ │ ├── Logging/ │ │ │ ├── DebugLoggingScope.cs │ │ │ ├── ILog.cs │ │ │ ├── LogEntry.cs │ │ │ ├── LogLevel.cs │ │ │ ├── LogManager.cs │ │ │ ├── LoggingService.cs │ │ │ └── NullLogTraceListener.cs │ │ ├── PackageSystem/ │ │ │ ├── Foundation/ │ │ │ │ ├── InstalledPackageInformationSerializerHandler.cs │ │ │ │ ├── PackageManagerInstallProcessSerializerHandler.cs │ │ │ │ ├── PackageManagerUninstallProcessSerializerHandler.cs │ │ │ │ ├── PackageServerFacadeImplCache.cs │ │ │ │ ├── PackageSystemSettings.cs │ │ │ │ ├── SystemLockingType.cs │ │ │ │ ├── VersionStringHelper.cs │ │ │ │ └── XmlHelper.cs │ │ │ ├── IPackageFragmentInstaller.cs │ │ │ ├── IPackageFragmentUninstaller.cs │ │ │ ├── IPackageInstaller.cs │ │ │ ├── IPackageInstallerUninstallerFactory.cs │ │ │ ├── IPackageServerFacade.cs │ │ │ ├── IPackageUninstaller.cs │ │ │ ├── InstalledPackageInformation.cs │ │ │ ├── LicenseDefinitionManager.cs │ │ │ ├── LicenseDefinitionUtils.cs │ │ │ ├── LicenseServerFacade.cs │ │ │ ├── PackageAssemblyHandler.cs │ │ │ ├── PackageDescription.cs │ │ │ ├── PackageFragmentInstallers/ │ │ │ │ ├── BasePackageFragmentInstaller.cs │ │ │ │ ├── BasePackageFragmentUninstaller.cs │ │ │ │ ├── ConfigurationTransformationPackageFragmentInstaller.cs │ │ │ │ ├── ConfigurationTransformationPackageFragmentUninstaller.cs │ │ │ │ ├── DataPackageFragmentInstaller.cs │ │ │ │ ├── DataPackageFragmentUninstaller.cs │ │ │ │ ├── DataTypePackageFragmentInstaller.cs │ │ │ │ ├── DataTypePackageFragmentUninstaller.cs │ │ │ │ ├── DllPackageFragmentInstaller.cs │ │ │ │ ├── DllPackageFragmentUninstaller.cs │ │ │ │ ├── DynamicDataTypePackageFragmentInstaller.cs │ │ │ │ ├── DynamicDataTypePackageFragmentUninstaller.cs │ │ │ │ ├── FileModifyPackageFragmentInstaller.cs │ │ │ │ ├── FileModifyPackageFragmentUninstaller.cs │ │ │ │ ├── FilePackageFragmentInstaller.cs │ │ │ │ ├── FilePackageFragmentUninstaller.cs │ │ │ │ ├── FileXslTransformationPackageFragmentInstaller.cs │ │ │ │ ├── FileXslTransformationPackageFragmentUninstaller.cs │ │ │ │ ├── LocalePackageFragmentInstaller.cs │ │ │ │ ├── LocalePackageFragmentUninstaller.cs │ │ │ │ ├── PackageFragmentValidationExtension.cs │ │ │ │ ├── PackageLicenseFragmentInstaller.cs │ │ │ │ ├── PackageLicenseFragmentUninstaller.cs │ │ │ │ ├── PackageVersionBumperFragmentInstaller.cs │ │ │ │ ├── PackageVersionBumperFragmentUninstaller.cs │ │ │ │ ├── UserGroupUserAdderFragmentInstaller.cs │ │ │ │ ├── UserGroupUserAdderFragmentUninstaller.cs │ │ │ │ ├── XmlFileMergePackageFragmentInstaller.cs │ │ │ │ └── XmlFileMergePackageFragmentUninstaller.cs │ │ │ ├── PackageFragmentValidationResult.cs │ │ │ ├── PackageFragmentValidationResultType.cs │ │ │ ├── PackageInformation.cs │ │ │ ├── PackageInstaller.cs │ │ │ ├── PackageInstallerContext.cs │ │ │ ├── PackageInstallerUninstallerFactory.cs │ │ │ ├── PackageLicenseDefinition.cs │ │ │ ├── PackageLicenseHelper.cs │ │ │ ├── PackageManager.cs │ │ │ ├── PackageManagerInstallProcess.cs │ │ │ ├── PackageManagerUninstallProcess.cs │ │ │ ├── PackageServerFacade.cs │ │ │ ├── PackageServerFacadeImpl.cs │ │ │ ├── PackageServerFacadeLocalMock.cs │ │ │ ├── PackageSystemServices.cs │ │ │ ├── PackageUninstaller.cs │ │ │ ├── PackageUninstallerContext.cs │ │ │ ├── PackageUtils.cs │ │ │ └── WebServiceClient/ │ │ │ ├── LicenseDefinitionServiceSoapClient.cs │ │ │ └── Reference.cs │ │ ├── PageTemplates/ │ │ │ ├── Foundation/ │ │ │ │ ├── IPageTemplateProviderRegistry.cs │ │ │ │ ├── PageTemplateProviderRegistry.cs │ │ │ │ ├── PageTemplateProviderRegistryImpl.cs │ │ │ │ └── PluginFacade/ │ │ │ │ └── PageTemplateProviderPluginFacade.cs │ │ │ ├── IPageRenderer.cs │ │ │ ├── IPageTemplate.cs │ │ │ ├── IPageTemplateProvider.cs │ │ │ ├── ISharedCodePageTemplateProvider.cs │ │ │ ├── PageContentToRender.cs │ │ │ ├── PageTemplateDescriptor.cs │ │ │ ├── PageTemplateEntityToken.cs │ │ │ ├── PageTemplateFacade.cs │ │ │ ├── PlaceholderAttribute.cs │ │ │ ├── PlaceholderDescriptor.cs │ │ │ ├── Plugins/ │ │ │ │ ├── NonConfigurablePageTemplateProvider.cs │ │ │ │ ├── PageTemplateProviderData.cs │ │ │ │ └── Runtime/ │ │ │ │ ├── PageTemplateProviderCustomFactory.cs │ │ │ │ ├── PageTemplateProviderDefaultNameRetriever.cs │ │ │ │ ├── PageTemplateProviderFactory.cs │ │ │ │ └── PageTemplateProviderSettings.cs │ │ │ ├── SharedFile.cs │ │ │ └── TemplateDefinitionHelper.cs │ │ ├── Parallelization/ │ │ │ ├── AsyncLock.cs │ │ │ ├── Foundation/ │ │ │ │ ├── IParallelizationProviderRegistry.cs │ │ │ │ ├── ParallelizationProviderRegistry.cs │ │ │ │ └── ParallelizationProviderRegistryImpl.cs │ │ │ ├── IndexEnumerator.cs │ │ │ ├── ParallelFacade.cs │ │ │ └── Plugins/ │ │ │ └── Runtime/ │ │ │ └── ParallelizationProviderSettings.cs │ │ ├── ResourceSystem/ │ │ │ ├── Foundation/ │ │ │ │ ├── PluginFacades/ │ │ │ │ │ └── ResourceProviderPluginFacade.cs │ │ │ │ └── ResourceProviderRegistry.cs │ │ │ ├── IIconResourceSystemFacade.cs │ │ │ ├── IconResourceSystemFacade.cs │ │ │ ├── IconResourceSystemFacadeImpl.cs │ │ │ ├── Icons/ │ │ │ │ ├── BuildInIconProviderName.cs │ │ │ │ ├── CommonCommandIcons.cs │ │ │ │ └── CommonElementIcons.cs │ │ │ ├── LocalizationFiles.cs │ │ │ ├── LocalizationFiles.tt │ │ │ ├── Plugins/ │ │ │ │ └── ResourceProvider/ │ │ │ │ ├── ILocalizationProvider.cs │ │ │ │ ├── IResourceProvider.cs │ │ │ │ ├── IStringResourceProvider.cs │ │ │ │ ├── NonConfigurableResourceProvider.cs │ │ │ │ ├── ResourceProviderData.cs │ │ │ │ └── Runtime/ │ │ │ │ ├── ResourceProviderCustomFactory.cs │ │ │ │ ├── ResourceProviderDefaultNameRetriever.cs │ │ │ │ ├── ResourceProviderFactory.cs │ │ │ │ └── ResourceProviderSettings.cs │ │ │ ├── ResourceHandle.cs │ │ │ └── StringResourceSystemFacade.cs │ │ ├── Routing/ │ │ │ ├── AttributeBasedRoutingHelper.cs │ │ │ ├── DataReferenceRelativeRouteToPredicateMapper.cs │ │ │ ├── DataUrlCollisionException.cs │ │ │ ├── DataUrls.cs │ │ │ ├── DefaultRelativeRouteToPredicateMapper.cs │ │ │ ├── Foundation/ │ │ │ │ └── PluginFacades/ │ │ │ │ ├── PageUrlProviderPluginFacade.cs │ │ │ │ └── UrlFormattersPluginFacade.cs │ │ │ ├── HostnameBindingsFacade.cs │ │ │ ├── IDataUrlMapper.cs │ │ │ ├── IInternalUrlConverter.cs │ │ │ ├── IInternalUrlProvider.cs │ │ │ ├── IMediaUrlProvider.cs │ │ │ ├── IRelativeRouteToPredicateMapper.cs │ │ │ ├── InternalUrls.cs │ │ │ ├── MediaUrlData.cs │ │ │ ├── MediaUrls.cs │ │ │ ├── PageNotFoundRoute.cs │ │ │ ├── PageUrlData.cs │ │ │ ├── PageUrls.cs │ │ │ ├── Pages/ │ │ │ │ ├── C1PageRoute.cs │ │ │ │ ├── C1PageRouteHander.cs │ │ │ │ ├── SeoFriendlyRedirectHttpHandler.cs │ │ │ │ └── SeoFriendlyRedirectRouteHandler.cs │ │ │ ├── Plugins/ │ │ │ │ ├── PageUrlsProviders/ │ │ │ │ │ ├── IPageUrlBuilder.cs │ │ │ │ │ ├── IPageUrlProvider.cs │ │ │ │ │ ├── PageUrlSet.cs │ │ │ │ │ └── Runtime/ │ │ │ │ │ ├── NonConfigurablePageUrlProvider.cs │ │ │ │ │ ├── PageUrlProviderCustomFactory.cs │ │ │ │ │ ├── PageUrlProviderData.cs │ │ │ │ │ └── PageUrlProviderFactory.cs │ │ │ │ ├── Runtime/ │ │ │ │ │ └── UrlsConfiguration.cs │ │ │ │ └── UrlFormatters/ │ │ │ │ ├── IUrlFormatter.cs │ │ │ │ └── Runtime/ │ │ │ │ ├── NonConfigurableUrlFormatter.cs │ │ │ │ ├── UrlFormatterCustomFactory.cs │ │ │ │ ├── UrlFormatterData.cs │ │ │ │ └── UrlFormatterFactory.cs │ │ │ ├── Routes.cs │ │ │ ├── UrlKind.cs │ │ │ └── UrlSpace.cs │ │ ├── Serialization/ │ │ │ ├── CodeGeneration/ │ │ │ │ ├── Foundation/ │ │ │ │ │ └── ISerializer.cs │ │ │ │ ├── PropertySerializerManager.cs │ │ │ │ └── PropertySerializerTypeCodeGenerator.cs │ │ │ ├── CompositeCollectionValueXmlSerializer.cs │ │ │ ├── CompositeJsonSerializer.cs │ │ │ ├── CompositeSerializationBinder.cs │ │ │ ├── ISerializerHandler.cs │ │ │ ├── ISerializerHandlerFacade.cs │ │ │ ├── IValueXmlSerializer.cs │ │ │ ├── IXmlSerializer.cs │ │ │ ├── PrettyPrinter.cs │ │ │ ├── PropertySerializerHandler.cs │ │ │ ├── SerializationFacade.cs │ │ │ ├── SerializerHandlerAttribute.cs │ │ │ ├── SerializerHandlerFacade.cs │ │ │ ├── SerializerHandlerFacadeImpl.cs │ │ │ ├── SerializerHandlerValueXmlSerializer.cs │ │ │ ├── StringConversionServices.cs │ │ │ ├── SystemCollectionValueXmlSerializer.cs │ │ │ ├── SystemPrimitivValueXmlSerializer.cs │ │ │ ├── SystemSerializableValueXmlSerializer.cs │ │ │ ├── SystemTypesValueXmlSerializer.cs │ │ │ └── XmlSerializer.cs │ │ ├── ServiceLocator.cs │ │ ├── SmtpMailer.cs │ │ ├── Sql/ │ │ │ └── SqlConnectionManager.cs │ │ ├── Threading/ │ │ │ ├── ThreadCultureScope.cs │ │ │ ├── ThreadDataManager.cs │ │ │ ├── ThreadDataManagerData.cs │ │ │ ├── ThreadManager.cs │ │ │ └── TwoPhaseFileLock.cs │ │ ├── Types/ │ │ │ ├── AssemblyExtensionMethods.cs │ │ │ ├── AssemblyFacade.cs │ │ │ ├── AssemblyLocationExtensions.cs │ │ │ ├── BuildinPlugins/ │ │ │ │ └── BuildinTypeManagerTypeHandler/ │ │ │ │ └── BuildinTypeManagerTypeHandler.cs │ │ │ ├── CSharpCodeProviderFactory.cs │ │ │ ├── CodeCompatibilityChecker.cs │ │ │ ├── CodeGenerationBuilder.cs │ │ │ ├── CodeGenerationCommon.cs │ │ │ ├── CodeGenerationHelper.cs │ │ │ ├── CodeGenerationManager.cs │ │ │ ├── CompatibilityCheckResult.cs │ │ │ ├── DataReferenceLabelPair.cs │ │ │ ├── DynamicBuildManagerTypeCache.cs │ │ │ ├── ExtendedNullable.cs │ │ │ ├── Foundation/ │ │ │ │ ├── AssemblyFilenameCollection.cs │ │ │ │ ├── CompileUnitBaseTypeProber.cs │ │ │ │ └── PluginFacades/ │ │ │ │ ├── ITypeManagerTypeHandlerPluginFacade.cs │ │ │ │ ├── TypeManagerTypeHandlerPluginFacade.cs │ │ │ │ └── TypeManagerTypeHandlerPluginFacadeImpl.cs │ │ │ ├── GenericComparer.cs │ │ │ ├── ICodeProvider.cs │ │ │ ├── ITypeManager.cs │ │ │ ├── KeyValuePair.cs │ │ │ ├── NameTypePair.cs │ │ │ ├── Pair.cs │ │ │ ├── Plugins/ │ │ │ │ └── TypeManagerTypeHandler/ │ │ │ │ ├── ITypeManagerTypeHandler.cs │ │ │ │ ├── NonConfigurableTypeManagerTypeHandler.cs │ │ │ │ ├── Runtime/ │ │ │ │ │ ├── TypeManagerTypeHandlerCustomFactory.cs │ │ │ │ │ ├── TypeManagerTypeHandlerDefaultNameRetriever.cs │ │ │ │ │ ├── TypeManagerTypeHandlerFactory.cs │ │ │ │ │ └── TypeManagerTypeHandlerSettings.cs │ │ │ │ └── TypeManagerTypeHandlerData.cs │ │ │ ├── PrimitiveTypes.cs │ │ │ ├── StaticReflection.cs │ │ │ ├── TypeExtensionMethods.cs │ │ │ ├── TypeLocator.cs │ │ │ ├── TypeManager.cs │ │ │ ├── TypeManagerImpl.cs │ │ │ ├── ValueTypeConverter.cs │ │ │ └── ValueTypeConverterHelperAttribute.cs │ │ ├── UrlBuilder.cs │ │ ├── WebClient/ │ │ │ ├── Ajax/ │ │ │ │ ├── AjaxResponseHttpModule.cs │ │ │ │ └── AjaxStream.cs │ │ │ ├── ApplicationLevelEventHandlers.cs │ │ │ ├── BrowserRender.cs │ │ │ ├── BuildManagerHelper.cs │ │ │ ├── Captcha/ │ │ │ │ ├── Captcha.cs │ │ │ │ ├── CaptchaConfiguration.cs │ │ │ │ ├── Encryption.cs │ │ │ │ └── ImageCreator.cs │ │ │ ├── ConsoleInfo.cs │ │ │ ├── ControlCompilerService.cs │ │ │ ├── CookieHandler.cs │ │ │ ├── ErrorServices.cs │ │ │ ├── FlowMediators/ │ │ │ │ ├── ActionExecutionMediator.cs │ │ │ │ ├── ActionExecutionService.cs │ │ │ │ ├── FormFlowRendering/ │ │ │ │ │ ├── FormFlowRenderingService.cs │ │ │ │ │ ├── FormFlowUiDefinitionRenderer.cs │ │ │ │ │ └── IFormFlowWebRenderingService.cs │ │ │ │ ├── TreeServicesFacade.cs │ │ │ │ ├── ViewTransitionHelper.cs │ │ │ │ └── WebFlowUiMediator.cs │ │ │ ├── FlowPage.cs │ │ │ ├── FunctionBoxRouteHandler.cs │ │ │ ├── FunctionCallEditor/ │ │ │ │ ├── FunctionCallEditorStateSimple.cs │ │ │ │ ├── FunctionMarkupHelper.cs │ │ │ │ ├── IFunctionCallEditorState.cs │ │ │ │ └── TreeHelper.cs │ │ │ ├── FunctionUiHelper.cs │ │ │ ├── HttpModules/ │ │ │ │ ├── AdministrativeAuthorizationHttpModule.cs │ │ │ │ ├── AdministrativeCultureSetterHttpModule.cs │ │ │ │ ├── AdministrativeDataScopeSetterHttpModule.cs │ │ │ │ ├── AdministrativeResponseFilterHttpModule.cs │ │ │ │ └── Utf8StringTransformationStream.cs │ │ │ ├── Logging/ │ │ │ │ └── WFC/ │ │ │ │ ├── ILogService.cs │ │ │ │ ├── LogEntry.cs │ │ │ │ └── LogService.cs │ │ │ ├── Media/ │ │ │ │ ├── DefaultImageFileFormatProvider.cs │ │ │ │ ├── IImageFileFormatProvider.cs │ │ │ │ ├── ImageFormatProviders.cs │ │ │ │ ├── ImageResizer.cs │ │ │ │ ├── ImageSizeReader.cs │ │ │ │ ├── ResizingAction.cs │ │ │ │ └── ResizingOptions.cs │ │ │ ├── MediaUrlHelper.cs │ │ │ ├── PageStructureRpc.cs │ │ │ ├── PageUrlHelper.cs │ │ │ ├── PhantomJs/ │ │ │ │ ├── PhantomServer.cs │ │ │ │ ├── RenderPreviewRequest.cs │ │ │ │ ├── RenderingResult.cs │ │ │ │ └── RenderingResultStatus.cs │ │ │ ├── Presentation/ │ │ │ │ ├── CssRequestHandler.cs │ │ │ │ ├── OutputTransformationManager.cs │ │ │ │ └── ViewServices.cs │ │ │ ├── Renderings/ │ │ │ │ ├── CultureExtrator.cs │ │ │ │ ├── Data/ │ │ │ │ │ ├── DataXhtmlRenderingServices.cs │ │ │ │ │ ├── IDataXhtmlRenderer.cs │ │ │ │ │ ├── KeyTemplatedXhtmlRendererAttribute.cs │ │ │ │ │ ├── XhtmlRendererProviderAttribute.cs │ │ │ │ │ ├── XhtmlRenderingEncodingEnum.cs │ │ │ │ │ └── XhtmlRenderingTypeEnum.cs │ │ │ │ ├── Foundation/ │ │ │ │ │ ├── IRenderingResponseHandlerRegistry.cs │ │ │ │ │ ├── PluginFacades/ │ │ │ │ │ │ └── RenderingResponseHandlerPluginFacade.cs │ │ │ │ │ ├── RenderingResponseHandlerRegistry.cs │ │ │ │ │ └── RenderingResponseHandlerRegistryImpl.cs │ │ │ │ ├── FunctionPreview.cs │ │ │ │ ├── INonCachebleRequestHostnameMapper.cs │ │ │ │ ├── IRenderingResponseHandlerFacade.cs │ │ │ │ ├── Page/ │ │ │ │ │ ├── IPageContentFilter.cs │ │ │ │ │ ├── IXElementToControlMapper.cs │ │ │ │ │ ├── PageAssociationScopeEnum.cs │ │ │ │ │ ├── PagePreviewBuilder.cs │ │ │ │ │ ├── PagePreviewContext.cs │ │ │ │ │ ├── PageRenderer.cs │ │ │ │ │ ├── PageStructureInfo.cs │ │ │ │ │ ├── RenderingReason.cs │ │ │ │ │ ├── XElementToAspNetExtensions.cs │ │ │ │ │ └── XEmbeddedControlMapper.cs │ │ │ │ ├── Plugins/ │ │ │ │ │ └── RenderingResponseHandler/ │ │ │ │ │ ├── IDataRenderingResponseHandler.cs │ │ │ │ │ ├── IRenderingResponseHandler.cs │ │ │ │ │ ├── NonConfigurableHookRegistrator.cs │ │ │ │ │ ├── RenderingResponseHandlerData.cs │ │ │ │ │ └── Runtime/ │ │ │ │ │ ├── RenderingResponseHandlerCustomFactory.cs │ │ │ │ │ ├── RenderingResponseHandlerDefaultNameRetriever.cs │ │ │ │ │ ├── RenderingResponseHandlerFactory.cs │ │ │ │ │ └── RenderingResponseHandlerSettings.cs │ │ │ │ ├── RenderingContext.cs │ │ │ │ ├── RenderingElementNames.cs │ │ │ │ ├── RenderingResponseHandlerFacade.cs │ │ │ │ ├── RenderingResponseHandlerFacadeImpl.cs │ │ │ │ ├── RenderingResponseHandlerResult.cs │ │ │ │ ├── RequestInterceptorHttpModule.cs │ │ │ │ └── Template/ │ │ │ │ ├── PageTemplateFeatureFacade.cs │ │ │ │ ├── TemplateInfo.cs │ │ │ │ └── TemplatePlaceholdersInfo.cs │ │ │ ├── ScriptHandler.cs │ │ │ ├── ScriptLoader.cs │ │ │ ├── Services/ │ │ │ │ ├── ConsoleMessageService/ │ │ │ │ │ ├── ActionTypeEnum.cs │ │ │ │ │ ├── BindEntityTokenToViewParams.cs │ │ │ │ │ ├── BroadcastMessageParams.cs │ │ │ │ │ ├── CloseAllViewsParams.cs │ │ │ │ │ ├── CloseViewParams.cs │ │ │ │ │ ├── ConsoleAction.cs │ │ │ │ │ ├── ConsoleMessageServiceFacade.cs │ │ │ │ │ ├── DialogTypeEnum.cs │ │ │ │ │ ├── DownloadFileParams.cs │ │ │ │ │ ├── GetMessagesResult.cs │ │ │ │ │ ├── LogEntryParams.cs │ │ │ │ │ ├── LogLevelEnum.cs │ │ │ │ │ ├── MessageBoxParams.cs │ │ │ │ │ ├── OpenExternalViewParams.cs │ │ │ │ │ ├── OpenGenericViewParams.cs │ │ │ │ │ ├── OpenSlideViewParams.cs │ │ │ │ │ ├── OpenViewDefinitionParams.cs │ │ │ │ │ ├── OpenViewParams.cs │ │ │ │ │ ├── RefreshTreeParams.cs │ │ │ │ │ ├── SaveStatusParams.cs │ │ │ │ │ ├── SelectElementParams.cs │ │ │ │ │ └── ViewTypeEnum.cs │ │ │ │ ├── LocalizationServiceObjects/ │ │ │ │ │ ├── ClientLocale.cs │ │ │ │ │ ├── ClientLocales.cs │ │ │ │ │ └── PageLocale.cs │ │ │ │ ├── SecurityServiceObjets/ │ │ │ │ │ ├── EntityPermissionDetails.cs │ │ │ │ │ └── UserPermissions.cs │ │ │ │ ├── TreeServiceObjects/ │ │ │ │ │ ├── ClientAction.cs │ │ │ │ │ ├── ClientActionCategory.cs │ │ │ │ │ ├── ClientBrowserViewSettings.cs │ │ │ │ │ ├── ClientElement.cs │ │ │ │ │ ├── ClientElementChangeDescriptor.cs │ │ │ │ │ ├── ClientLabeledProperty.cs │ │ │ │ │ ├── ClientProviderNameEntityTokenClientElementsTriple.cs │ │ │ │ │ ├── ClientProviderNameEntityTokenPair.cs │ │ │ │ │ ├── ExtensionMethods/ │ │ │ │ │ │ ├── ElementActionExtensionMethods.cs │ │ │ │ │ │ └── ElementExtensionMethods.cs │ │ │ │ │ ├── RefreshChildrenInfo.cs │ │ │ │ │ └── RefreshChildrenParams.cs │ │ │ │ ├── WampRouter/ │ │ │ │ │ ├── IRpcService.cs │ │ │ │ │ ├── IWampEventHandler.cs │ │ │ │ │ ├── UserNameBasedAuthenticationFactory.cs │ │ │ │ │ ├── UserNameBasedAuthorizer.cs │ │ │ │ │ ├── UserNameBasedCookieAuthenticationFactory.cs │ │ │ │ │ ├── UserNameBasedCookieAuthenticator.cs │ │ │ │ │ ├── WampLogger.cs │ │ │ │ │ ├── WampRouteWrapper.cs │ │ │ │ │ ├── WampRouter.cs │ │ │ │ │ ├── WampRouterFacade.cs │ │ │ │ │ └── WampRouterResolverRegistry.cs │ │ │ │ └── WysiwygEditor/ │ │ │ │ ├── MarkupTransformationServices.cs │ │ │ │ └── PageTemplatePreview.cs │ │ │ ├── Setup/ │ │ │ │ ├── SetupServiceFacade.cs │ │ │ │ └── WebServiceClient/ │ │ │ │ └── Reference.cs │ │ │ ├── StandardPlugins/ │ │ │ │ └── SessionStateProviders/ │ │ │ │ └── DefaultSessionStateProvider/ │ │ │ │ ├── DefaultSessionStateProvider.cs │ │ │ │ ├── ISessionStateEntry.cs │ │ │ │ ├── SerializationUtil.cs │ │ │ │ └── XmlSerializationWrapper.cs │ │ │ ├── State/ │ │ │ │ ├── ISessionStateProvider.cs │ │ │ │ ├── Runtime/ │ │ │ │ │ ├── SessionStateProviderCustomFactory.cs │ │ │ │ │ ├── SessionStateProviderFactory.cs │ │ │ │ │ └── SessionStateProviderSettings.cs │ │ │ │ └── StateManager.cs │ │ │ ├── StyleLoader.cs │ │ │ ├── TemplatePreviewRouteHandler.cs │ │ │ ├── UiControlLib/ │ │ │ │ ├── BindingUpdatePanel.cs │ │ │ │ ├── CheckBox.cs │ │ │ │ ├── ClickButton.cs │ │ │ │ ├── ComboBox.cs │ │ │ │ ├── DataInput.cs │ │ │ │ ├── DocumentDirtyEvent.cs │ │ │ │ ├── Feedback.cs │ │ │ │ ├── FieldMessage.cs │ │ │ │ ├── Foundation/ │ │ │ │ │ ├── BaseControl.cs │ │ │ │ │ └── ClientAttributes.cs │ │ │ │ ├── Generic.cs │ │ │ │ ├── HtmlEncodedPlaceHolder.cs │ │ │ │ ├── PostBackDialog.cs │ │ │ │ ├── Selector.cs │ │ │ │ ├── TextArea.cs │ │ │ │ ├── TextBox.cs │ │ │ │ ├── ToolbarButton.cs │ │ │ │ └── TreeNode.cs │ │ │ ├── UrlString.cs │ │ │ ├── UrlUtils.cs │ │ │ ├── XhtmlPage.cs │ │ │ └── XsltServices.cs │ │ └── Xml/ │ │ ├── LimitedDepthXmlWriter.cs │ │ ├── Namespaces.cs │ │ ├── UriResolver.cs │ │ ├── XAttributeUtils.cs │ │ ├── XDocumentUtils.cs │ │ ├── XElementUtils.cs │ │ ├── XNodeExtensionMethods.cs │ │ ├── XhtmlDocument.cs │ │ ├── XhtmlErrorFormatter.cs │ │ ├── XhtmlPrettifier.cs │ │ ├── XhtmlWriter.cs │ │ ├── XmlDocumentUtil.cs │ │ ├── XmlReaderUtils.cs │ │ ├── XmlSchemaSetUtils.cs │ │ ├── XmlSerializationHelper.cs │ │ ├── XmlUtils.cs │ │ ├── XmlWriterUtils.cs │ │ ├── XslCompiledTransformUtils.cs │ │ └── XsltExtensionDefinition.cs │ ├── Data/ │ │ ├── AutoUpdatebleAttribute.cs │ │ ├── BuildNewHandlerAttribute.cs │ │ ├── Caching/ │ │ │ ├── Cache.cs │ │ │ ├── CachedTable.cs │ │ │ ├── CachingEnumerator.cs │ │ │ ├── CachingQueryable.cs │ │ │ ├── DataCachingFacade.cs │ │ │ ├── Foundation/ │ │ │ │ ├── CachingQueryableCache.cs │ │ │ │ └── ChangeSourceExpressionVisitor.cs │ │ │ ├── ICachingQueryable.cs │ │ │ ├── TableVersion.cs │ │ │ └── WeakRefCache.cs │ │ ├── CachingAttribute.cs │ │ ├── CodeGeneratedAttribute.cs │ │ ├── DataAssociationAttribute.cs │ │ ├── DataAttributeFacade.cs │ │ ├── DataConnection.cs │ │ ├── DataEntityToken.cs │ │ ├── DataEntityTokenExtensions.cs │ │ ├── DataEventArgs.cs │ │ ├── DataEventHandler.cs │ │ ├── DataEventSystemFacade.cs │ │ ├── DataEvents.cs │ │ ├── DataFacade.cs │ │ ├── DataFacadeImpl.cs │ │ ├── DataIconFacade.cs │ │ ├── DataIdKeyFacade.cs │ │ ├── DataIdKeyFacadeImpl.cs │ │ ├── DataIdSerializer.cs │ │ ├── DataInterceptor.cs │ │ ├── DataKeyPropertyCollection.cs │ │ ├── DataKeyPropertyCollectionExtensionMethods.cs │ │ ├── DataLocalizationFacade.cs │ │ ├── DataLocalizationFacadeImpl.cs │ │ ├── DataMetaDataFacade.cs │ │ ├── DataPropertyValueCollection.cs │ │ ├── DataProviderCopier.cs │ │ ├── DataReference.cs │ │ ├── DataReferenceFacade.cs │ │ ├── DataScope.cs │ │ ├── DataScopeAttribute.cs │ │ ├── DataScopeIdentifier.cs │ │ ├── DataScopeManager.cs │ │ ├── DataScopeServicesFacade.cs │ │ ├── DataSerializerHandler.cs │ │ ├── DataServiceScopeManager.cs │ │ ├── DataSourceId.cs │ │ ├── DataTypeTypesManager.cs │ │ ├── DefaultFieldRandomStringValueAttribute.cs │ │ ├── DefaultFieldValueAttribute.cs │ │ ├── DynamicTypes/ │ │ │ ├── Configuration/ │ │ │ │ └── XmlConfigurationExtensionMethods.cs │ │ │ ├── DataAssociationDescriptor.cs │ │ │ ├── DataFieldDescriptor.cs │ │ │ ├── DataFieldDescriptorCollection.cs │ │ │ ├── DataFieldDescriptorValueXmlSerializer.cs │ │ │ ├── DataFieldFormRenderingProfile.cs │ │ │ ├── DataFieldIdEqualityComparer.cs │ │ │ ├── DataFieldNameCollection.cs │ │ │ ├── DataFieldTreeOrderingProfile.cs │ │ │ ├── DataTypeChangeDescriptor.cs │ │ │ ├── DataTypeDescriptor.cs │ │ │ ├── DataTypeDescriptorFormsHelper.cs │ │ │ ├── DataTypeDescriptorValueXmlSerializer.cs │ │ │ ├── DataTypeIndex.cs │ │ │ ├── DataTypeValidationRegistry.cs │ │ │ ├── DataTypeValidator.cs │ │ │ ├── DataUrlProfile.cs │ │ │ ├── Debug/ │ │ │ │ └── DynamicTempTypeCreator.cs │ │ │ ├── DefaultValue.cs │ │ │ ├── DynamicTypeManager.cs │ │ │ ├── DynamicTypeManagerImpl.cs │ │ │ ├── DynamicTypeMarkupServices.cs │ │ │ ├── Foundation/ │ │ │ │ ├── DynamicTypeReflectionFacade.cs │ │ │ │ ├── DynamicTypesAlternateFormFacade.cs │ │ │ │ ├── DynamicTypesCustomFormFacade.cs │ │ │ │ └── ReflectionBasedDataTypeDescriptorBuilder.cs │ │ │ ├── IDynamicTypeManager.cs │ │ │ ├── NameValidation.cs │ │ │ ├── ParseDefinitionFileException.cs │ │ │ ├── SearchProfile.cs │ │ │ ├── StoreFieldType.cs │ │ │ ├── TypeUpdateVersionException.cs │ │ │ └── UpdateDataTypeDescriptor.cs │ │ ├── FieldPositionAttribute.cs │ │ ├── ForeignKeyAttribute.cs │ │ ├── ForeignPropertyInfo.cs │ │ ├── FormRenderingProfileAttribute.cs │ │ ├── Foundation/ │ │ │ ├── CodeGeneratedAttribute.cs │ │ │ ├── CodeGeneration/ │ │ │ │ ├── DataWrapperClassCodeProvider.cs │ │ │ │ ├── DataWrapperCodeGenerator.cs │ │ │ │ ├── DataWrapperGenerator.cs │ │ │ │ ├── EmptyDataClassBase.cs │ │ │ │ ├── EmptyDataClassCodeGenerator.cs │ │ │ │ └── EmptyDataClassCodeProvider.cs │ │ │ ├── DataAssociationRegistry.cs │ │ │ ├── DataExpressionBuilder.cs │ │ │ ├── DataFacadeQueryable.cs │ │ │ ├── DataFacadeQueryableExpressionVisitor.cs │ │ │ ├── DataFacadeQueryableGathererExpressionVisitor.cs │ │ │ ├── DataFacadeReflectionCache.cs │ │ │ ├── DataInterfaceAutoUpdater.cs │ │ │ ├── DataProviderRegistry.cs │ │ │ ├── DataProviderRegistryImpl.cs │ │ │ ├── DataReferenceRegistry.cs │ │ │ ├── DataStoreExistenceVerifier.cs │ │ │ ├── DataStoreExistenceVerifierImpl.cs │ │ │ ├── DataWrappingFacade.cs │ │ │ ├── EmptyDataClassTypeManager.cs │ │ │ ├── IDataFacadeQueryable.cs │ │ │ ├── IDataProviderRegistry.cs │ │ │ ├── IDataStoreExistenceVerifier.cs │ │ │ ├── PluginFacades/ │ │ │ │ └── DataProviderPluginFacade.cs │ │ │ ├── ProcessControllerRegistry.cs │ │ │ ├── ProcessControllerSettings.cs │ │ │ └── SelectMethodInfoCache.cs │ │ ├── GeneratedTypes/ │ │ │ ├── GeneratedTypesFacade.cs │ │ │ ├── GeneratedTypesFacadeImpl.cs │ │ │ ├── GeneratedTypesHelper.cs │ │ │ ├── IGeneratedTypesFacade.cs │ │ │ ├── InterfaceCodeGenerator.cs │ │ │ ├── InterfaceCodeManager.cs │ │ │ └── InterfaceCodeProvider.cs │ │ ├── GlobalDataTypeFacade.cs │ │ ├── GroupByPriorityAttribute.cs │ │ ├── Hierarchy/ │ │ │ ├── DataAncestorFacade.cs │ │ │ ├── DataAncestorProviderAttribute.cs │ │ │ ├── DataAncestorProviders/ │ │ │ │ ├── NoAncestorDataAncestorProvider.cs │ │ │ │ ├── PageDataAncestorProvider.cs │ │ │ │ └── PropertyDataAncestorProvider.cs │ │ │ ├── Foundation/ │ │ │ │ └── DataAncestorProviderCache.cs │ │ │ └── IDataAncestorProvider.cs │ │ ├── IBuildNewHandler.cs │ │ ├── IChangeHistory.cs │ │ ├── ICreationHistory.cs │ │ ├── IData.cs │ │ ├── IDataExtensions.cs │ │ ├── IDataFacade.cs │ │ ├── IDataId.cs │ │ ├── IDataIdExtensions.cs │ │ ├── IDataIdKeyFacade.cs │ │ ├── IDataLocalizationFacade.cs │ │ ├── IDataReference.cs │ │ ├── IDataWrapper.cs │ │ ├── IPageData.cs │ │ ├── IPageFolderData.cs │ │ ├── IPageMetaData.cs │ │ ├── ImmutableFieldIdAttribute.cs │ │ ├── ImmutableTypeIdAttribute.cs │ │ ├── IndexAttribute.cs │ │ ├── IndexDirection.cs │ │ ├── InternalUrlAttribute.cs │ │ ├── KeyPropertyNameAttribute.cs │ │ ├── LabelPropertyNameAttribute.cs │ │ ├── LocalizationScopeManager.cs │ │ ├── NewInstanceDefaultFieldValueAttribute.cs │ │ ├── NotReferenceable.cs │ │ ├── PageDataConnection.cs │ │ ├── PageFolderFacade.cs │ │ ├── PageManager.cs │ │ ├── PageMetaDataDescription.cs │ │ ├── PageMetaDataFacade.cs │ │ ├── PageNode.cs │ │ ├── PageRenderingHistory.cs │ │ ├── PageUrl.cs │ │ ├── PhysicalStoreFieldType.cs │ │ ├── Plugins/ │ │ │ └── DataProvider/ │ │ │ ├── DataInterfaceValidator.cs │ │ │ ├── DataProviderConfigurationServices.cs │ │ │ ├── DataProviderContext.cs │ │ │ ├── DataProviderData.cs │ │ │ ├── IDataProvider.cs │ │ │ ├── IDynamicDataProvider.cs │ │ │ ├── IFileSystemDataProvider.cs │ │ │ ├── IGeneratedTypesDataProvider.cs │ │ │ ├── ILocalizedDataProvider.cs │ │ │ ├── ISupportCaching.cs │ │ │ ├── IWritableDataProvider.cs │ │ │ ├── NonConfigurableDataProvider.cs │ │ │ ├── Runtime/ │ │ │ │ ├── DataProviderCustomFactory.cs │ │ │ │ ├── DataProviderDefaultNameRetriever.cs │ │ │ │ ├── DataProviderFactory.cs │ │ │ │ └── DataProviderSettings.cs │ │ │ ├── Streams/ │ │ │ │ ├── FileChangeNotificator.cs │ │ │ │ ├── FileSystemFileBase.cs │ │ │ │ ├── FileSystemFileStreamManager.cs │ │ │ │ └── TransactionFileSystemFileStreamManager.cs │ │ │ └── TransformQueryable/ │ │ │ └── TransformQueryable.cs │ │ ├── ProcessControlled/ │ │ │ ├── ActionIconResourceHandleAttribute.cs │ │ │ ├── ActionRoleProviderAttribute.cs │ │ │ ├── ActionTokenProviderAttribute.cs │ │ │ ├── IActionRoleProvider.cs │ │ │ ├── IActionTokenProvider.cs │ │ │ ├── ILocalizeProcessController.cs │ │ │ ├── ILocalizedControlled.cs │ │ │ ├── IProcessControlled.cs │ │ │ ├── IProcessController.cs │ │ │ ├── IPublishControlled.cs │ │ │ ├── IPublishControlledAuxiliary.cs │ │ │ ├── IPublishProcessController.cs │ │ │ ├── IgnoreActionAttribute.cs │ │ │ ├── ProcessControllerAttributesFacade.cs │ │ │ ├── ProcessControllerFacade.cs │ │ │ ├── ProcessControllers/ │ │ │ │ ├── DummyProcessControllers/ │ │ │ │ │ └── PublishDummyProcessController.cs │ │ │ │ ├── GenericLocalizeProcessController/ │ │ │ │ │ └── GenericLocalizeProcessController.cs │ │ │ │ └── GenericPublishProcessController/ │ │ │ │ ├── GenericPublishProcessController.cs │ │ │ │ ├── GenericPublishProcessControllerActionType.cs │ │ │ │ └── GenericPublishProcessDynamicActionTokens.cs │ │ │ └── PublishControlledAuxiliaryAttribute.cs │ │ ├── ProcessControllerTypeAttribute.cs │ │ ├── PublicationScope.cs │ │ ├── PublishScheduling/ │ │ │ └── PublishScheduleHelper.cs │ │ ├── RelevantToUserTypeAttribute.cs │ │ ├── RouteDateSegmentAttribute.cs │ │ ├── RouteSegmentAttribute.cs │ │ ├── SearchFacetAttribute.cs │ │ ├── SearchableFieldAttribute.cs │ │ ├── SearchableTypeAttribute.cs │ │ ├── SitemapNavigator.cs │ │ ├── SitemapScope.cs │ │ ├── StoreEventArgs.cs │ │ ├── StoreEventHandler.cs │ │ ├── StoreFieldTypeAttribute.cs │ │ ├── StoreSortOrderAttribute.cs │ │ ├── Streams/ │ │ │ ├── CachedMemoryStream.cs │ │ │ ├── FileStreamManagerAttribute.cs │ │ │ ├── FileStreamManagerLocator.cs │ │ │ └── IFileStreamManager.cs │ │ ├── TitleAttribute.cs │ │ ├── Transactions/ │ │ │ └── TransactionsFacade.cs │ │ ├── TreeOrderingProfileAttribute.cs │ │ ├── Types/ │ │ │ ├── ExtensionMethods/ │ │ │ │ ├── IFileExtensions.cs │ │ │ │ ├── IMediaFileExtensions.cs │ │ │ │ ├── IMediaFileFolderExtensions.cs │ │ │ │ └── Use_parent_namespace.txt │ │ │ ├── Foundation/ │ │ │ │ ├── ExceptingSerializerHandler.cs │ │ │ │ └── PagePublishControlledAuxiliary.cs │ │ │ ├── ICompositionContainer.cs │ │ │ ├── ICustomFunctionCallEditorMapping.cs │ │ │ ├── IDataItemTreeAttachmentPoint.cs │ │ │ ├── IDynamicTypeFormDefinitionFile.cs │ │ │ ├── IFile.cs │ │ │ ├── IFileBuildNewHandler.cs │ │ │ ├── IFileServices.cs │ │ │ ├── IFlowInformation.cs │ │ │ ├── IFolderWhiteList.cs │ │ │ ├── IHostnameBinding.cs │ │ │ ├── IImageFile.cs │ │ │ ├── IInlineFunction.cs │ │ │ ├── IInlineFunctionAssemblyReference.cs │ │ │ ├── ILockingInformation.cs │ │ │ ├── IMediaFile.cs │ │ │ ├── IMediaFileData.cs │ │ │ ├── IMediaFileFolder.cs │ │ │ ├── IMediaFileStore.cs │ │ │ ├── IMediaFolderData.cs │ │ │ ├── IMethodBasedFunctionInfo.cs │ │ │ ├── INamedFunctionCall.cs │ │ │ ├── IPackageServerSource.cs │ │ │ ├── IPage.cs │ │ │ ├── IPageFolderDefinition.cs │ │ │ ├── IPageMetaDataDefinition.cs │ │ │ ├── IPagePlaceholderContent.cs │ │ │ ├── IPagePublishSchedule.cs │ │ │ ├── IPageStructure.cs │ │ │ ├── IPageTemplateFile.cs │ │ │ ├── IPageType.cs │ │ │ ├── IPageTypeDateFolderTypeLink.cs │ │ │ ├── IPageTypeDefaultPageContent.cs │ │ │ ├── IPageTypeMetaDataTypeLink.cs │ │ │ ├── IPageTypePageTemplateRestriction.cs │ │ │ ├── IPageTypeParentRestriction.cs │ │ │ ├── IPageTypeTreeLink.cs │ │ │ ├── IPageUnpublishSchedule.cs │ │ │ ├── IParameter.cs │ │ │ ├── IPublishSchedule.cs │ │ │ ├── ISchedule.cs │ │ │ ├── ISearchEngineOptimizationKeyword.cs │ │ │ ├── ISqlConnection.cs │ │ │ ├── ISqlFunctionInfo.cs │ │ │ ├── ISystemActiveLocale.cs │ │ │ ├── ITaskItem.cs │ │ │ ├── IUnpublishSchedule.cs │ │ │ ├── IUrlConfiguration.cs │ │ │ ├── IUser.cs │ │ │ ├── IUserActiveLocale.cs │ │ │ ├── IUserActivePerspective.cs │ │ │ ├── IUserConsoleInformation.cs │ │ │ ├── IUserDeveloperSettings.cs │ │ │ ├── IUserFormLogin.cs │ │ │ ├── IUserGroup.cs │ │ │ ├── IUserGroupActiveLocale.cs │ │ │ ├── IUserGroupActivePerspective.cs │ │ │ ├── IUserGroupPermissionDefinition.cs │ │ │ ├── IUserGroupPermissionDefinitionPermissionType.cs │ │ │ ├── IUserPasswordHistory.cs │ │ │ ├── IUserPermissionDefinition.cs │ │ │ ├── IUserPermissionDefinitionPermissionType.cs │ │ │ ├── IUserSettings.cs │ │ │ ├── IUserUserGroupRelation.cs │ │ │ ├── IVersioned.cs │ │ │ ├── IVisualFunction.cs │ │ │ ├── IXmlPageTemplate.cs │ │ │ ├── IXsltFile.cs │ │ │ ├── IXsltFunction.cs │ │ │ ├── MediaFileDataAncesorProvider.cs │ │ │ ├── PageInsertPosition.cs │ │ │ ├── PageServices.cs │ │ │ ├── StoreIdFilter/ │ │ │ │ ├── Foundation/ │ │ │ │ │ ├── IStoreIdFilterQueryable.cs │ │ │ │ │ ├── StoreIdFilterQueryableCache.cs │ │ │ │ │ ├── StoreIdFilterQueryableChangeSourceExpressionVisitor.cs │ │ │ │ │ └── StoreIdFilterQueryableExpressionVisitor.cs │ │ │ │ └── StoreIdFilterQueryable.cs │ │ │ ├── TypeVersionAttribute.cs │ │ │ └── VersionedDataHelperContract.cs │ │ ├── UserTypeEnum.cs │ │ ├── Validation/ │ │ │ ├── ClientValidationRuleFacade.cs │ │ │ ├── ClientValidationRuleFacadeImpl.cs │ │ │ ├── ClientValidationRuleSerializerHandler.cs │ │ │ ├── ClientValidationRules/ │ │ │ │ ├── ClientValidationRule.cs │ │ │ │ ├── NotNullClientValidationRule.cs │ │ │ │ ├── RegexClientValidationRule.cs │ │ │ │ └── StringLengthClientValidationRule.cs │ │ │ ├── ConstructorBasedPropertyValidatorBuilder.cs │ │ │ ├── DataValidationResult.cs │ │ │ ├── DataValidationResults.cs │ │ │ ├── Foundation/ │ │ │ │ ├── ClientValidationRuleTranslatorRegistry.cs │ │ │ │ ├── ClientValidationRuleTranslatorRegistryImpl.cs │ │ │ │ ├── IClientValidationRuleTranslatorRegistry.cs │ │ │ │ └── PluginFacades/ │ │ │ │ ├── ClientValidationRuleTranslatorPluginFacade.cs │ │ │ │ ├── ClientValidationRuleTranslatorPluginFacadeImpl.cs │ │ │ │ └── IClientValidationRuleTranslatorPluginFacade.cs │ │ │ ├── IClientValidationRuleFacade.cs │ │ │ ├── IPropertyValidatorBuilder.cs │ │ │ ├── IValidationFacade.cs │ │ │ ├── Plugins/ │ │ │ │ └── ClientValidationRuleTranslator/ │ │ │ │ ├── ClientValidationRuleTranslatorData.cs │ │ │ │ ├── IClientValidationRuleTranslator.cs │ │ │ │ ├── NonConfigurableClientValidationRuleTranslator.cs │ │ │ │ └── Runtime/ │ │ │ │ ├── ClientValidationRuleTranslatorCustomFactory.cs │ │ │ │ ├── ClientValidationRuleTranslatorDefaultNameRetriever.cs │ │ │ │ ├── ClientValidationRuleTranslatorFactory.cs │ │ │ │ └── ClientValidationRuleTranslatorSettings.cs │ │ │ ├── PropertyValidatorBuilder.cs │ │ │ ├── ValidationFacade.cs │ │ │ ├── ValidationFacadeImpl.cs │ │ │ └── Validators/ │ │ │ ├── DecimalPrecisionValidator.cs │ │ │ ├── DecimalPrecisionValidatorAttribute.cs │ │ │ ├── DecimalRangeValidatorAttribute.cs │ │ │ ├── GuidNotEmptyAttribute.cs │ │ │ ├── GuidNotEmptyValidator.cs │ │ │ ├── IntegerRangeValidatorAttribute.cs │ │ │ ├── LazyFunctionProviedPropertyAttribute.cs │ │ │ ├── LazyFunctionProviedPropertyValidator.cs │ │ │ ├── NullDateTimeRangeValidatorAttribute.cs │ │ │ ├── NullDecimalRangeValidatorAttribute.cs │ │ │ ├── NullIntegerRangeValidatorAttribute.cs │ │ │ ├── NullStringLengthValidator.cs │ │ │ ├── NullStringLengthValidatorAttribute.cs │ │ │ ├── PasswordValidator.cs │ │ │ ├── PasswordValidatorAttribute.cs │ │ │ ├── RegexValidatorAttribute.cs │ │ │ ├── StringLengthValidatorAttribute.cs │ │ │ └── StringSizeValidatorAttribute.cs │ │ └── VersionKeyPropertyName.cs │ ├── Functions/ │ │ ├── AttributeBasedRoutedDataUrlMapper.cs │ │ ├── BaseFunctionRuntimeTreeNode.cs │ │ ├── BaseParameterRuntimeTreeNode.cs │ │ ├── BaseRuntimeTreeNode.cs │ │ ├── BaseRuntimeTreeNodeValueXmlSerializer.cs │ │ ├── BaseValueProvider.cs │ │ ├── ConstantObjectParameterRuntimeTreeNode.cs │ │ ├── ConstantParameterRuntimeTreeNode.cs │ │ ├── ConstantValueProvider.cs │ │ ├── DynamicMethodHelper.cs │ │ ├── Forms/ │ │ │ ├── FunctionParameterElementProducer.cs │ │ │ ├── FunctionParameterProducer.cs │ │ │ ├── FunctionProducer.cs │ │ │ ├── FunctionProducerMediator.cs │ │ │ └── IFunctionProducer.cs │ │ ├── Foundation/ │ │ │ ├── FunctionContainer.cs │ │ │ ├── FunctionTreeConfigurationNames.cs │ │ │ ├── IMetaFunctionProviderRegistry.cs │ │ │ ├── MetaFunctionContainer.cs │ │ │ ├── MetaFunctionProviderRegistry.cs │ │ │ ├── MetaFunctionProviderRegistryImpl.cs │ │ │ ├── PluginFacades/ │ │ │ │ ├── FunctionProviderPluginFacade.cs │ │ │ │ ├── FunctionWrapper.cs │ │ │ │ ├── WidgetFunctionProviderPluginFacade.cs │ │ │ │ ├── WidgetFunctionWrapper.cs │ │ │ │ └── XslExtensionsProviderPluginFacade.cs │ │ │ ├── WidgetFunctionContainer.cs │ │ │ └── XslExtensionsProviderRegistry.cs │ │ ├── FunctionAttribute.cs │ │ ├── FunctionCallEditorManager.cs │ │ ├── FunctionCallEditorSettings.cs │ │ ├── FunctionContextContainer.cs │ │ ├── FunctionEventSystemFacade.cs │ │ ├── FunctionFacade.cs │ │ ├── FunctionParameterAttribute.cs │ │ ├── FunctionParameterDescriptionAttribute.cs │ │ ├── FunctionParameterIgnoreAttribute.cs │ │ ├── FunctionParameterRuntimeTreeNode.cs │ │ ├── FunctionRuntimeTreeNode.cs │ │ ├── FunctionTreeBuilder.cs │ │ ├── FunctionValueProvider.cs │ │ ├── HelpDefinition.cs │ │ ├── ICompoundFunction.cs │ │ ├── IDowncastableFunction.cs │ │ ├── IDynamicFunction.cs │ │ ├── IFunction.cs │ │ ├── IFunctionInitializationInfo.cs │ │ ├── IFunctionResultToXEmbedableMapper.cs │ │ ├── IMetaFunction.cs │ │ ├── IMetaFunctionExtensionMethods.cs │ │ ├── IRoutedDataUrlMapper.cs │ │ ├── IWidgetFunction.cs │ │ ├── Inline/ │ │ │ ├── InlineFunction.cs │ │ │ ├── InlineFunctionCreateMethodErrorHandler.cs │ │ │ ├── InlineFunctionHelper.cs │ │ │ ├── NotLoadedInlineFunction.cs │ │ │ └── StringInlineFunctionCreateMethodErrorHandler.cs │ │ ├── ManagedParameters/ │ │ │ ├── ManagedParameterDefinition.cs │ │ │ └── ManagedParameterManager.cs │ │ ├── NamedFunctionCall.cs │ │ ├── NamedFunctionCallValueXmlSerializer.cs │ │ ├── NoValueValueProvider.cs │ │ ├── ParameterList.cs │ │ ├── ParameterProfile.cs │ │ ├── PathInfoRoutedDataUrlMapper.cs │ │ ├── Plugins/ │ │ │ ├── FunctionProvider/ │ │ │ │ ├── FunctionNotifier.cs │ │ │ │ ├── FunctionProviderData.cs │ │ │ │ ├── IDynamicTypeFunctionProvider.cs │ │ │ │ ├── IFunctionProvider.cs │ │ │ │ ├── NonConfigurableFunctionProvider.cs │ │ │ │ └── Runtime/ │ │ │ │ ├── FunctionProviderCustomFactory.cs │ │ │ │ ├── FunctionProviderDefaultNameRetriever.cs │ │ │ │ ├── FunctionProviderFactory.cs │ │ │ │ └── FunctionProviderSettings.cs │ │ │ ├── WidgetFunctionProvider/ │ │ │ │ ├── IDynamicTypeWidgetFunctionProvider.cs │ │ │ │ ├── IWidgetFunctionProvider.cs │ │ │ │ ├── NonConfigurableWidgetFunctionProvider.cs │ │ │ │ ├── Runtime/ │ │ │ │ │ ├── WidgetFunctionProviderCustomFactory.cs │ │ │ │ │ ├── WidgetFunctionProviderDefaultNameRetriever.cs │ │ │ │ │ ├── WidgetFunctionProviderFactory.cs │ │ │ │ │ └── WidgetFunctionProviderSettings.cs │ │ │ │ ├── WidgetFunctionNotifier.cs │ │ │ │ └── WidgetFunctionProviderData.cs │ │ │ └── XslExtensionsProvider/ │ │ │ ├── IXslExtensionsProvider.cs │ │ │ ├── Runtime/ │ │ │ │ ├── XslExtensionsProviderCustomFactory.cs │ │ │ │ ├── XslExtensionsProviderFactory.cs │ │ │ │ └── XslExtensionsProviderSettings.cs │ │ │ └── XslExtensionsProviderData.cs │ │ ├── RoutedData.cs │ │ ├── StandardFunctionSecurityAncestorProvider.cs │ │ ├── StandardFunctions.cs │ │ ├── StandardWidgetFunctions.cs │ │ ├── WidgetFunctionProvider.cs │ │ ├── WidgetFunctionRuntimeTreeNode.cs │ │ ├── XElementParameterRuntimeTreeNode.cs │ │ └── XslExtensionsManager.cs │ ├── GlobalInitializerFacade.cs │ ├── Plugins/ │ │ ├── Application/ │ │ │ ├── ApplicationOnlineHandlers/ │ │ │ │ └── AspNetApplicationOnlineHandler/ │ │ │ │ └── AspNetApplicationOnlineHandler.cs │ │ │ └── ApplicationStartupHandlers/ │ │ │ └── AttributeBasedApplicationStartupHandler/ │ │ │ └── AttributeBasedApplicationStartupHandler.cs │ │ ├── Commands/ │ │ │ └── ConsoleCommandHandlers/ │ │ │ ├── BrowseUrl.cs │ │ │ ├── ConsoleCommandHelper.cs │ │ │ ├── FocusData.cs │ │ │ └── FocusElement.cs │ │ ├── Components/ │ │ │ ├── ComponentProviderSettings.cs │ │ │ ├── ComponentTags/ │ │ │ │ └── TagManager.cs │ │ │ ├── ComponentsEndpoint/ │ │ │ │ ├── ComponentsEndpoint.cs │ │ │ │ └── ComponentsResponseMessage.cs │ │ │ └── FileBasedComponentProvider/ │ │ │ └── FileBasedComponentProvider.cs │ │ ├── Data/ │ │ │ └── DataProviders/ │ │ │ ├── Common/ │ │ │ │ ├── PropertyNameMappingConfigurationElement.cs │ │ │ │ └── PropertyNameMappingConfigurationElementCollection.cs │ │ │ ├── FileSystemDataProvider/ │ │ │ │ ├── FileSystemDataProvider.cs │ │ │ │ └── Foundation/ │ │ │ │ ├── FileSystemFile.cs │ │ │ │ ├── FileSystemFileDataId.cs │ │ │ │ └── FileSystemFileGenerator.cs │ │ │ ├── FileSystemMediaFileProvider/ │ │ │ │ ├── FileSystemMediaFile.cs │ │ │ │ ├── FileSystemMediaFileFolder.cs │ │ │ │ └── FileSystemMediaFileProvider.cs │ │ │ ├── MSSqlServerDataProvider/ │ │ │ │ ├── CodeGeneration/ │ │ │ │ │ ├── DataContextAssembler.cs │ │ │ │ │ ├── DataContextBase.cs │ │ │ │ │ ├── DataContextClassGenerator.cs │ │ │ │ │ ├── DataIdClassGenerator.cs │ │ │ │ │ ├── EntityBaseClassGenerator.cs │ │ │ │ │ ├── EntityClassGenerator.cs │ │ │ │ │ ├── EntityClassesFieldNames.cs │ │ │ │ │ ├── EntityCodeGeneratorHelper.cs │ │ │ │ │ ├── IEntity.cs │ │ │ │ │ ├── ISqlDataContext.cs │ │ │ │ │ ├── SqlDataContextHelperClass.cs │ │ │ │ │ ├── SqlDataProviderCodeBuilder.cs │ │ │ │ │ ├── SqlDataProviderCodeProvider.cs │ │ │ │ │ ├── SqlDataProviderHelperGenerator.cs │ │ │ │ │ └── SqlProviderCodeGenerator.cs │ │ │ │ ├── Foundation/ │ │ │ │ │ ├── DynamicTypesCommon.cs │ │ │ │ │ ├── InterfaceConfigurationManipulator.cs │ │ │ │ │ ├── NamesCreator.cs │ │ │ │ │ ├── RequireTransactionScope.cs │ │ │ │ │ ├── SqlDataProviderStoreManipulator.cs │ │ │ │ │ ├── SqlDataTypeStoreTable.cs │ │ │ │ │ ├── SqlDataTypeStoreTableKey.cs │ │ │ │ │ └── SqlLoggerTextWriter.cs │ │ │ │ ├── ISqlDataProviderHelper.cs │ │ │ │ ├── Sql/ │ │ │ │ │ ├── ISqlTableInformation.cs │ │ │ │ │ ├── ISqlTableInformationStore.cs │ │ │ │ │ ├── SqlColumnInformation.cs │ │ │ │ │ ├── SqlTableInformation.cs │ │ │ │ │ ├── SqlTableInformationStore.cs │ │ │ │ │ └── SqlTableInformationStoreImpl.cs │ │ │ │ ├── SqlDataProvider.cs │ │ │ │ ├── SqlDataProvider_Stores.cs │ │ │ │ ├── SqlDataTypeStore.cs │ │ │ │ ├── SqlDataTypeStoreDataScope.cs │ │ │ │ └── SqlDataTypeStoresContainer.cs │ │ │ ├── MediaFileProvider/ │ │ │ │ ├── MediaFile.cs │ │ │ │ ├── MediaFileFolder.cs │ │ │ │ └── MediaFileProvider.cs │ │ │ ├── VirtualImageFileProvider/ │ │ │ │ ├── VirtualImageFile.cs │ │ │ │ ├── VirtualImageFileProvider.cs │ │ │ │ ├── VirtualImageFileQueryable.cs │ │ │ │ └── VirtualImageFileQueryableVisitor.cs │ │ │ └── XmlDataProvider/ │ │ │ ├── CodeGeneration/ │ │ │ │ ├── DataIdClassGenerator.cs │ │ │ │ ├── DataProviderHelperBase.cs │ │ │ │ ├── DataProviderHelperClassGenerator.cs │ │ │ │ ├── DataWrapperClassGenerator.cs │ │ │ │ ├── GeneretedClassesMethodCache.cs │ │ │ │ ├── XmlDataProviderCodeBuilder.cs │ │ │ │ ├── XmlDataProviderCodeProvider.cs │ │ │ │ └── XmlProviderCodeGenerator.cs │ │ │ ├── Foundation/ │ │ │ │ ├── FileRecord.cs │ │ │ │ ├── InterfaceConfigurationManipulator.cs │ │ │ │ ├── NamesCreator.cs │ │ │ │ ├── TransactionRollbackHandler.cs │ │ │ │ ├── ValidationHelper.cs │ │ │ │ ├── XmlDataProviderDocumentCache.cs │ │ │ │ ├── XmlDataProviderDocumentWriter.cs │ │ │ │ └── XmlDataProviderStoreManipulator.cs │ │ │ ├── IXElementWrapper.cs │ │ │ ├── IXmlDataProviderHelper.cs │ │ │ ├── XmlDataProvider.cs │ │ │ ├── XmlDataProvider_CRUD.cs │ │ │ ├── XmlDataProvider_Stores.cs │ │ │ ├── XmlDataTypeStore.cs │ │ │ ├── XmlDataTypeStoreCreator.cs │ │ │ ├── XmlDataTypeStoreDataScope.cs │ │ │ └── XmlDataTypeStoresContainer.cs │ │ ├── Elements/ │ │ │ ├── ElementProviders/ │ │ │ │ ├── AllFunctionsElementProvider/ │ │ │ │ │ ├── AllFunctionsElementProvider.cs │ │ │ │ │ ├── AllFunctionsProviderActionExecutor.cs │ │ │ │ │ ├── DocumentFunctionsActionToken.cs │ │ │ │ │ ├── FunctionInfoActionExecutor.cs │ │ │ │ │ ├── FunctionInfoActionToken.cs │ │ │ │ │ └── StandardFunctionAuxiliarySecurityAncestorProvider.cs │ │ │ │ ├── BaseFunctionProviderElementProvider/ │ │ │ │ │ ├── BaseFunctionFolderElementEntityToken.cs │ │ │ │ │ ├── BaseFunctionFolderElementEntityTokenExtensions.cs │ │ │ │ │ ├── BaseFunctionFolderElementEntityTokenSecurityAncestorProvider.cs │ │ │ │ │ ├── BaseFunctionProviderElementProvider.cs │ │ │ │ │ └── IFunctionTreeBuilderLeafInfo.cs │ │ │ │ ├── DeveloperApplicationProvider/ │ │ │ │ │ ├── DeveloperApplicationProvider.cs │ │ │ │ │ └── DeveloperApplicationProviderEntityToken.cs │ │ │ │ ├── GeneratedDataTypesElementProvider/ │ │ │ │ │ ├── DeleteDataWorkflow.layout │ │ │ │ │ ├── EditFormWorkflow.layout │ │ │ │ │ ├── GeneratedDataTypesElementDynamicActionTokens.cs │ │ │ │ │ ├── GeneratedDataTypesElementProvider.cs │ │ │ │ │ ├── GeneratedDataTypesElementProviderRootEntityToken.cs │ │ │ │ │ ├── GeneratedDataTypesElementProviderSecurityAncestorProvider.cs │ │ │ │ │ ├── GeneratedDataTypesElementProviderTypeEntityToken.cs │ │ │ │ │ ├── IGeneratedTypeWhiteList.cs │ │ │ │ │ └── ViewUnpublishedItemsActionToken.cs │ │ │ │ ├── LocalizationElementProvider/ │ │ │ │ │ ├── LocalizationElementProvider.cs │ │ │ │ │ └── LocalizationElementProviderRootEntityToken.cs │ │ │ │ ├── MediaFileProviderElementProvider/ │ │ │ │ │ ├── EditMediaFileTextContentWorkflow.layout │ │ │ │ │ ├── MediaFileProviderElementProvider.cs │ │ │ │ │ ├── MediaFileProviderEntityTokenSecurityAncestorProvider.cs │ │ │ │ │ ├── MediaFileSearchToken.cs │ │ │ │ │ ├── MediaRootFolderProviderEntityToken.cs │ │ │ │ │ ├── WorkflowMediaFile.cs │ │ │ │ │ └── ZipMediaFileExtractor.cs │ │ │ │ ├── MethodBasedFunctionProviderElementProvider/ │ │ │ │ │ ├── MethodBasedFunctionAttribute.cs │ │ │ │ │ └── MethodBasedFunctionProviderElementProvider.cs │ │ │ │ ├── PackageElementProvider/ │ │ │ │ │ ├── ClearServerCacheActionExecutor.cs │ │ │ │ │ ├── ClearServerCacheActionToken.cs │ │ │ │ │ ├── InstallLocalPackageWorkflow.cs │ │ │ │ │ ├── InstallLocalPackageWorkflow.designer.cs │ │ │ │ │ ├── InstallRemotePackageWorkflow.cs │ │ │ │ │ ├── InstallRemotePackageWorkflow.designer.cs │ │ │ │ │ ├── PackageElementProvider.cs │ │ │ │ │ ├── PackageElementProviderAvailablePackagesFolderEntityToken.cs │ │ │ │ │ ├── PackageElementProviderAvailablePackagesGroupFolderEntityToken.cs │ │ │ │ │ ├── PackageElementProviderAvailablePackagesItemEntityToken.cs │ │ │ │ │ ├── PackageElementProviderInstalledPackageFolderEntityToken.cs │ │ │ │ │ ├── PackageElementProviderInstalledPackageGroupFolderEntityToken.cs │ │ │ │ │ ├── PackageElementProviderInstalledPackageItemEntityToken.cs │ │ │ │ │ ├── PackageElementProviderInstalledPackageLocalPackagesFolderEntityToken.cs │ │ │ │ │ ├── PackageElementProviderPackageSourcesFolderEntityToken.cs │ │ │ │ │ ├── PackageElementProviderPackageSourcesItemEntityToken.cs │ │ │ │ │ ├── PackageElementProviderRootEntityToken.cs │ │ │ │ │ └── WorkflowHelper.cs │ │ │ │ ├── PageElementProvider/ │ │ │ │ │ ├── LocalOrdering/ │ │ │ │ │ │ ├── DisplayLocalOrderingActionExecutor.cs │ │ │ │ │ │ └── DisplayLocalOrderingActionToken.cs │ │ │ │ │ ├── PageAddActionExecuter.cs │ │ │ │ │ ├── PageAddActionToken.cs │ │ │ │ │ ├── PageElementDynamicActionTokens.cs │ │ │ │ │ ├── PageElementProvider.cs │ │ │ │ │ ├── PageElementProviderActionTokenProvider.cs │ │ │ │ │ ├── PageElementProviderEntityToken.cs │ │ │ │ │ ├── PageSearchToken.cs │ │ │ │ │ └── ViewUnpublishedItemsActionToken.cs │ │ │ │ ├── PageTemplateElementProvider/ │ │ │ │ │ ├── PageTemplateElementProvider.cs │ │ │ │ │ ├── PageTemplateRootEntityToken.cs │ │ │ │ │ ├── SharedCodeFileEntityToken.cs │ │ │ │ │ └── SharedCodeFolderEntityToken.cs │ │ │ │ ├── PageTemplateFeatureElementProvider/ │ │ │ │ │ ├── PageTemplateFeatureElementProvider.cs │ │ │ │ │ └── PageTemplateFeatureEntityToken.cs │ │ │ │ ├── RazorFunctionElementProvider/ │ │ │ │ │ └── RazorFunctionElementProvider.cs │ │ │ │ ├── SqlFunctionElementProvider/ │ │ │ │ │ ├── SqlFunctionProviderElementProvider.cs │ │ │ │ │ ├── SqlFunctionProviderEntityTokenSecurityAncestorProvider.cs │ │ │ │ │ ├── SqlFunctionProviderFolderEntityToken.cs │ │ │ │ │ └── SqlFunctionProviderRootEntityToken.cs │ │ │ │ ├── UserControlFunctionElementProvider/ │ │ │ │ │ └── UserControlFunctionElementProvider.cs │ │ │ │ ├── UserElementProvider/ │ │ │ │ │ ├── ActiveLocalesFormsHelper.cs │ │ │ │ │ ├── ActivePerspectiveFormsHelper.cs │ │ │ │ │ ├── GlobalPermissionsFormsHelper.cs │ │ │ │ │ ├── UserElementProvider.cs │ │ │ │ │ ├── UserElementProviderEntityToken.cs │ │ │ │ │ ├── UserElementProviderGroupEntityToken.cs │ │ │ │ │ ├── UserElementProviderGroupEntityTokenSecurityAncestorProvider.cs │ │ │ │ │ └── UserGroupsFormsHelper.cs │ │ │ │ ├── UserGroupElementProvider/ │ │ │ │ │ ├── UserGroupElementProvider.cs │ │ │ │ │ └── UserGroupElementProviderRootEntityToken.cs │ │ │ │ ├── VirtualElementProvider/ │ │ │ │ │ ├── AttachProviderVirtualElement.cs │ │ │ │ │ ├── BaseElementConfigurationElement.cs │ │ │ │ │ ├── BaseElementNode.cs │ │ │ │ │ ├── FolderElementConfigurationElement.cs │ │ │ │ │ ├── FolderElementNode.cs │ │ │ │ │ ├── PlaceholderVirtualElement.cs │ │ │ │ │ ├── ProviderHookingElementConfigurationElement.cs │ │ │ │ │ ├── ProviderHookingElementNode.cs │ │ │ │ │ ├── SimpleVirtualElement.cs │ │ │ │ │ ├── VirtualElementConfigurationElement.cs │ │ │ │ │ ├── VirtualElementProvider.cs │ │ │ │ │ ├── VirtualElementProviderEntityToken.cs │ │ │ │ │ └── VirtualElementProviderSecurityAncestorProvider.cs │ │ │ │ ├── VisualFunctionProviderElementProvider/ │ │ │ │ │ ├── DeleteVisualFunctionWorkflow.layout │ │ │ │ │ ├── EditVisualFunctionWorkflow.layout │ │ │ │ │ └── VisualFunctionProviderElementProvider.cs │ │ │ │ ├── WebsiteFileElementProvider/ │ │ │ │ │ ├── WebsiteEntity.cs │ │ │ │ │ ├── WebsiteFile.cs │ │ │ │ │ ├── WebsiteFileElementProvider.cs │ │ │ │ │ ├── WebsiteFileElementProviderEntityToken.cs │ │ │ │ │ ├── WebsiteFileElementProviderRootEntityToken.cs │ │ │ │ │ ├── WebsiteFileEntityTokenSecurityAncestorProvider.cs │ │ │ │ │ ├── WebsiteFileSearchToken.cs │ │ │ │ │ └── WebsiteFolder.cs │ │ │ │ └── XsltBasedFunctionProviderElementProvider/ │ │ │ │ ├── DeleteXsltFunctionWorkflow.layout │ │ │ │ ├── EditXsltFunctionWorkflow.layout │ │ │ │ ├── FlowUiQueryMarkupHelper.cs │ │ │ │ └── XsltBasedFunctionProviderElementProvider.cs │ │ │ └── UrlToEntityToken/ │ │ │ ├── DataUrlToEntityTokenMapper.cs │ │ │ ├── MediaUrlToEntityTokenMapper.cs │ │ │ ├── ServerLogUrlToEntityTokenMapper.cs │ │ │ └── WebsiteFileUrlToEntityTokenMapper.cs │ │ ├── Forms/ │ │ │ └── WebChannel/ │ │ │ ├── CustomUiControls/ │ │ │ │ └── TemplatedPageContentEditorUiControlFactory.cs │ │ │ ├── Foundation/ │ │ │ │ └── UserControlUtils.cs │ │ │ ├── UiContainerFactories/ │ │ │ │ ├── Base/ │ │ │ │ │ ├── BaseTemplatedUiContainerFactory.cs │ │ │ │ │ └── ITemplatedUiContainerFactoryData.cs │ │ │ │ ├── TemplatedUiContainer.cs │ │ │ │ ├── TemplatedUiContainerBase.cs │ │ │ │ └── TemplatedUiContainerFactory.cs │ │ │ └── UiControlFactories/ │ │ │ ├── Base/ │ │ │ │ ├── BaseTemplatedUiControlFactory.cs │ │ │ │ ├── ITemplatedUiControlFactoryData.cs │ │ │ │ └── UserControlBase.cs │ │ │ ├── TemplatedBoolSelectorUiControlFactory.cs │ │ │ ├── TemplatedButtonUiControlFactory.cs │ │ │ ├── TemplatedCheckBoxUiControlFactory.cs │ │ │ ├── TemplatedContainerUiControlFactory.cs │ │ │ ├── TemplatedDataReferenceSelectorUiControlFactory.cs │ │ │ ├── TemplatedDataReferenceTreeSelectorUiControlFactory.cs │ │ │ ├── TemplatedDateTimeSelectorUiControlFactory.cs │ │ │ ├── TemplatedDoubleSelectorUiControlFactory.cs │ │ │ ├── TemplatedEnumSelectorUiControlFactory.cs │ │ │ ├── TemplatedFileUploadUiControlFactory.cs │ │ │ ├── TemplatedFontIconSelectorUiControlFactory.cs │ │ │ ├── TemplatedFunctionParameterDesignerUiControlFactory.cs │ │ │ ├── TemplatedHeadingUiControlFactory.cs │ │ │ ├── TemplatedHierarchicalSelectorUiControlFactory.cs │ │ │ ├── TemplatedHtmlBlobUiControlFactory.cs │ │ │ ├── TemplatedInfoTableUiControlFactory.cs │ │ │ ├── TemplatedMultiContentXhtmlEditorUiControlFactory.cs │ │ │ ├── TemplatedNamedFunctionCallsDesignerUiControlFactory.cs │ │ │ ├── TemplatedPageReferenceSelectorUiControlFactory.cs │ │ │ ├── TemplatedPreviewTabPanelUiControlFactory.cs │ │ │ ├── TemplatedQueryCallDefinitionsEditorUiControlFactory.cs │ │ │ ├── TemplatedSaveButtonUiControlFactory.cs │ │ │ ├── TemplatedSelectorUiControlFactory.cs │ │ │ ├── TemplatedSvgIconSelectorUiControlFactory.cs │ │ │ ├── TemplatedTextEditorUiControlFactory.cs │ │ │ ├── TemplatedTextInputUiControlFactory.cs │ │ │ ├── TemplatedTextUiControlFactory.cs │ │ │ ├── TemplatedToolbarButtonUiControlFactory.cs │ │ │ ├── TemplatedTreelSelectorUiControlFactory.cs │ │ │ ├── TemplatedTypeFieldDesignerUiControlFactory.cs.cs │ │ │ ├── TemplatedTypeSelectorUiControlFactory.cs │ │ │ ├── TemplatedXhtmlEditorUiControlFactory.cs │ │ │ ├── UserControlBasedUiControlFactory.cs │ │ │ ├── WebDebugUiControlFactory.cs │ │ │ └── WebEmbeddedFormUiControlFactory.cs │ │ ├── Functions/ │ │ │ ├── FunctionProviders/ │ │ │ │ ├── CodeBasedFunctionProvider/ │ │ │ │ │ ├── CodeBasedFunction.cs │ │ │ │ │ ├── CodeBasedFunctionEntityToken.cs │ │ │ │ │ ├── CodeBasedFunctionProvider.cs │ │ │ │ │ └── CodeBasedFunctionRegistry.cs │ │ │ │ ├── FileBasedFunctionProvider/ │ │ │ │ │ ├── FileBasedFunction.cs │ │ │ │ │ ├── FileBasedFunctionProvider.cs │ │ │ │ │ ├── FunctionBasedFunctionProviderHelper.cs │ │ │ │ │ ├── FunctionParameter.cs │ │ │ │ │ ├── IParameterWidgetsProvider.cs │ │ │ │ │ └── NotLoadedFileBasedFunction.cs │ │ │ │ ├── MethodBasedFunctionProvider/ │ │ │ │ │ ├── MethodBasedDefaultValueAttribute.cs │ │ │ │ │ ├── MethodBasedFunction.cs │ │ │ │ │ ├── MethodBasedFunctionProvider.cs │ │ │ │ │ └── NotLoadedMethodBasedFunction.cs │ │ │ │ ├── RazorFunctionProvider/ │ │ │ │ │ ├── RazorBasedFunction.cs │ │ │ │ │ ├── RazorFunctionProvider.cs │ │ │ │ │ ├── RazorFunctionProviderAssembler.cs │ │ │ │ │ └── RazorFunctionProviderData.cs │ │ │ │ ├── SqlFunctionProvider/ │ │ │ │ │ ├── SqlFunction.cs │ │ │ │ │ └── SqlFunctionProvider.cs │ │ │ │ ├── StandardFunctionProvider/ │ │ │ │ │ ├── AspNet/ │ │ │ │ │ │ └── LoadUserControlFunction.cs │ │ │ │ │ ├── Constant/ │ │ │ │ │ │ ├── BooleanFunction.cs │ │ │ │ │ │ ├── DateTimeFunction.cs │ │ │ │ │ │ ├── DecimalFunction.cs │ │ │ │ │ │ ├── GuidFunction.cs │ │ │ │ │ │ ├── IntegerFunction.cs │ │ │ │ │ │ ├── StringFunction.cs │ │ │ │ │ │ └── XhtmlDocumentFunction.cs │ │ │ │ │ ├── Foundation/ │ │ │ │ │ │ ├── DowncastableStandardFunctionBase.cs │ │ │ │ │ │ ├── EntityTokenFactory.cs │ │ │ │ │ │ ├── StandardFunctionBase.cs │ │ │ │ │ │ └── StandardFunctionParameterProfile.cs │ │ │ │ │ ├── IDataGenerated/ │ │ │ │ │ │ ├── AddDataInstance.cs │ │ │ │ │ │ ├── DataInstanceHelper.cs │ │ │ │ │ │ ├── DeleteDataInstance.cs │ │ │ │ │ │ ├── Filter/ │ │ │ │ │ │ │ ├── ActivePageReferenceFilter.cs │ │ │ │ │ │ │ ├── CompoundFilter.cs │ │ │ │ │ │ │ ├── DataReferenceFilter.cs │ │ │ │ │ │ │ ├── FieldPredicatesFilter.cs │ │ │ │ │ │ │ └── Foundation/ │ │ │ │ │ │ │ └── ListPropertyNamesHelper.cs │ │ │ │ │ │ ├── GetDataReference.cs │ │ │ │ │ │ ├── GetNullableDataReference.cs │ │ │ │ │ │ ├── GetXml.cs │ │ │ │ │ │ ├── GetXmlCachePriority.cs │ │ │ │ │ │ └── UpdateDataInstance.cs │ │ │ │ │ ├── Mail/ │ │ │ │ │ │ └── SendMailFunction.cs │ │ │ │ │ ├── Media/ │ │ │ │ │ │ └── MediaFolderFilterFunction.cs │ │ │ │ │ ├── Pages/ │ │ │ │ │ │ ├── GetForeignPageInfoFunction.cs │ │ │ │ │ │ ├── GetPageIdFunction.cs │ │ │ │ │ │ ├── SitemapFunction.cs │ │ │ │ │ │ └── SitemapXmlFunction.cs │ │ │ │ │ ├── StandardFunctionProvider.cs │ │ │ │ │ ├── StandardFunctionProviderEntityToken.cs │ │ │ │ │ ├── Utils/ │ │ │ │ │ │ ├── Caching/ │ │ │ │ │ │ │ └── PageObjectCacheFunction.cs │ │ │ │ │ │ ├── Compare/ │ │ │ │ │ │ │ ├── AreEqualFunction.cs │ │ │ │ │ │ │ └── IsLessThanFunction.cs │ │ │ │ │ │ ├── Configuration/ │ │ │ │ │ │ │ └── AppSettingsValueFunction.cs │ │ │ │ │ │ ├── Date/ │ │ │ │ │ │ │ ├── AddDaysFunction.cs │ │ │ │ │ │ │ └── NowFunction.cs │ │ │ │ │ │ ├── Dictionary/ │ │ │ │ │ │ │ ├── EnumerableToDictionary.cs │ │ │ │ │ │ │ └── XElementsToDictionaryFunction.cs │ │ │ │ │ │ ├── GetInputParameterFunction.cs │ │ │ │ │ │ ├── Globalization/ │ │ │ │ │ │ │ ├── AllCultures.cs │ │ │ │ │ │ │ └── CurrentCulture.cs │ │ │ │ │ │ ├── Guid/ │ │ │ │ │ │ │ └── NewGuid.cs │ │ │ │ │ │ ├── Integer/ │ │ │ │ │ │ │ └── IntSum.cs │ │ │ │ │ │ ├── ParseStringToObject.cs │ │ │ │ │ │ ├── Predicates/ │ │ │ │ │ │ │ ├── BoolEqualsPredicateFunction.cs │ │ │ │ │ │ │ ├── DateTimeEqualsPredicateFunction.cs │ │ │ │ │ │ │ ├── DateTimeGreaterThanPredicateFunction.cs │ │ │ │ │ │ │ ├── DateTimeLessThanPredicateFunction.cs │ │ │ │ │ │ │ ├── DecimalEqualsPredicateFunction.cs │ │ │ │ │ │ │ ├── DecimalGreaterThanPredicateFunction.cs │ │ │ │ │ │ │ ├── DecimalLessThanPredicateFunction.cs │ │ │ │ │ │ │ ├── GuidEqualsPredicateFunction.cs │ │ │ │ │ │ │ ├── GuidInCommaSeparatedListPredicateFunction.cs │ │ │ │ │ │ │ ├── IntegerEqualsPredicateFunction.cs │ │ │ │ │ │ │ ├── IntegerGreaterThanPredicateFunction.cs │ │ │ │ │ │ │ ├── IntegerLessThanPredicateFunction.cs │ │ │ │ │ │ │ ├── NullableBoolEqualsPredicateFunction.cs │ │ │ │ │ │ │ ├── NullableBoolNoValuePredicateFunction.cs │ │ │ │ │ │ │ ├── NullableDateTimeEqualsPredicateFunction.cs │ │ │ │ │ │ │ ├── NullableDateTimeGreaterThanPredicateFunction.cs │ │ │ │ │ │ │ ├── NullableDateTimeLessThanPredicateFunction.cs │ │ │ │ │ │ │ ├── NullableDateTimeNoValuePredicateFunction.cs │ │ │ │ │ │ │ ├── NullableDecimalEqualsPredicateFunction.cs │ │ │ │ │ │ │ ├── NullableDecimalNoValuePredicateFunction.cs │ │ │ │ │ │ │ ├── NullableGuidEqualsPredicateFunction.cs │ │ │ │ │ │ │ ├── NullableGuidNoValuePredicateFunction.cs │ │ │ │ │ │ │ ├── NullableIntegerEqualsPredicateFunction.cs │ │ │ │ │ │ │ ├── NullableIntegerNoValuePredicateFunction.cs │ │ │ │ │ │ │ ├── StringContainsPredicateFunction.cs │ │ │ │ │ │ │ ├── StringEndsWithPredicateFunction.cs │ │ │ │ │ │ │ ├── StringEqualsPredicateFunction.cs │ │ │ │ │ │ │ ├── StringInCommaSeparatedListPredicateFunction.cs │ │ │ │ │ │ │ ├── StringInListPredicateFunction.cs │ │ │ │ │ │ │ ├── StringNoValuePredicateFunction.cs │ │ │ │ │ │ │ └── StringStartsWithPredicateFunction.cs │ │ │ │ │ │ ├── String/ │ │ │ │ │ │ │ ├── Format.cs │ │ │ │ │ │ │ ├── Join.cs │ │ │ │ │ │ │ ├── JoinTwo.cs │ │ │ │ │ │ │ └── Split.cs │ │ │ │ │ │ └── Validation/ │ │ │ │ │ │ ├── DecimalPrecisionValidationFunction.cs │ │ │ │ │ │ ├── IntegerRangeValidationFunction.cs │ │ │ │ │ │ ├── NotNullValidationFunction.cs │ │ │ │ │ │ ├── PasswordValidationFunction.cs │ │ │ │ │ │ ├── RegexValidationFunction.cs │ │ │ │ │ │ └── StringLengthValidationFunction.cs │ │ │ │ │ ├── Web/ │ │ │ │ │ │ ├── Client/ │ │ │ │ │ │ │ ├── BrowserPlatformFunction.cs │ │ │ │ │ │ │ ├── BrowserStringFunction.cs │ │ │ │ │ │ │ ├── BrowserTypeFunction.cs │ │ │ │ │ │ │ ├── BrowserVersionFunction.cs │ │ │ │ │ │ │ ├── EcmaScriptVersionFunction.cs │ │ │ │ │ │ │ ├── IsCrawlerFunction.cs │ │ │ │ │ │ │ └── IsMobileDeviceFunction.cs │ │ │ │ │ │ ├── Html/ │ │ │ │ │ │ │ └── Template/ │ │ │ │ │ │ │ ├── CommonMetaTagsFunction.cs │ │ │ │ │ │ │ ├── HtmlTitleValueFunction.cs │ │ │ │ │ │ │ ├── LangAttributeFunction.cs │ │ │ │ │ │ │ ├── MetaDescriptionValueFunction.cs │ │ │ │ │ │ │ └── PageTemplateFeatureFunction.cs │ │ │ │ │ │ ├── Request/ │ │ │ │ │ │ │ ├── CookieValueFunction.cs │ │ │ │ │ │ │ ├── FormPostBoolValueFunction.cs │ │ │ │ │ │ │ ├── FormPostDecimalValueFunction.cs │ │ │ │ │ │ │ ├── FormPostGuidValueFunction.cs │ │ │ │ │ │ │ ├── FormPostIntegerValueFunction.cs │ │ │ │ │ │ │ ├── FormPostValueFunction.cs │ │ │ │ │ │ │ ├── FormPostXmlFormattedDateTimeValueFunction.cs │ │ │ │ │ │ │ ├── PathInfoFunction.cs │ │ │ │ │ │ │ ├── PathInfoGuidFunction.cs │ │ │ │ │ │ │ ├── PathInfoIntFunction.cs │ │ │ │ │ │ │ ├── QueryStringBoolValueFunction.cs │ │ │ │ │ │ │ ├── QueryStringDecimalValueFunction.cs │ │ │ │ │ │ │ ├── QueryStringGuidValueFunction.cs │ │ │ │ │ │ │ ├── QueryStringIntegerValueFunction.cs │ │ │ │ │ │ │ ├── QueryStringValueFunction.cs │ │ │ │ │ │ │ ├── QueryStringXmlFormattedDateTimeValueFunction.cs │ │ │ │ │ │ │ ├── RegisterPathInfoUsageFunction.cs │ │ │ │ │ │ │ └── SessionVariableFunction.cs │ │ │ │ │ │ ├── Response/ │ │ │ │ │ │ │ ├── RedirectFunction.cs │ │ │ │ │ │ │ ├── SetCookieValueFunction.cs │ │ │ │ │ │ │ ├── SetServerPageCacheDuration.cs │ │ │ │ │ │ │ └── SetSessionVariableFunction.cs │ │ │ │ │ │ └── Server/ │ │ │ │ │ │ ├── ApplicationPath.cs │ │ │ │ │ │ ├── ApplicationVariableFunction.cs │ │ │ │ │ │ └── ServerVariableFunction.cs │ │ │ │ │ ├── Xml/ │ │ │ │ │ │ ├── LoadFileFunction.cs │ │ │ │ │ │ ├── LoadUrlFunction.cs │ │ │ │ │ │ └── LoadXhtmlFileFunction.cs │ │ │ │ │ └── Xslt/ │ │ │ │ │ └── Extensions/ │ │ │ │ │ ├── DateFormattingXsltExtensionsFunction.cs │ │ │ │ │ ├── GlobalizationXsltExtensionsFunction.cs │ │ │ │ │ └── MarkupParserXsltExtensionsFunction.cs │ │ │ │ ├── UserControlFunctionProvider/ │ │ │ │ │ ├── UserControlBasedFunction.cs │ │ │ │ │ ├── UserControlFunctionProvider.cs │ │ │ │ │ ├── UserControlFunctionProviderAssembler.cs │ │ │ │ │ └── UserControlFunctionProviderData.cs │ │ │ │ ├── VisualFunctionProvider/ │ │ │ │ │ ├── RenderingHelper.cs │ │ │ │ │ └── VisualFunctionProvider.cs │ │ │ │ └── XsltBasedFunctionProvider/ │ │ │ │ ├── RenderHelper.cs │ │ │ │ └── XsltBasedFunctionProvider.cs │ │ │ ├── WidgetFunctionProviders/ │ │ │ │ └── StandardWidgetFunctionProvider/ │ │ │ │ ├── Bool/ │ │ │ │ │ ├── BoolSelectorWidgetFuntion.cs │ │ │ │ │ └── CheckBoxWidgetFuntion.cs │ │ │ │ ├── DataReference/ │ │ │ │ │ ├── DataReferenceSelectorWidgetFunction.cs │ │ │ │ │ ├── GetOptionsCommon.cs │ │ │ │ │ ├── HomePageSelectorWidgetFunction.cs │ │ │ │ │ ├── NullableDataReferenceSelectorWidgetFunction.cs │ │ │ │ │ ├── NullablePageReferenceSelectorWidgetFunction.cs │ │ │ │ │ ├── PageReferenceSelectorWidgetFunction.cs │ │ │ │ │ └── PageReferenceSelectorWidgetFunctionBase.cs │ │ │ │ ├── Date/ │ │ │ │ │ ├── DateSelectorWidgetFunction.cs │ │ │ │ │ └── DateTimeSelectorWidgetFunction.cs │ │ │ │ ├── Decimal/ │ │ │ │ │ └── DecimalTextBoxWidgetFuntion.cs │ │ │ │ ├── Foundation/ │ │ │ │ │ ├── CompositeWidgetFunctionBase.cs │ │ │ │ │ ├── EntityTokenFactory.cs │ │ │ │ │ └── FormFunctionMarkupBuilder.cs │ │ │ │ ├── Guid/ │ │ │ │ │ └── GuidTextBoxWidgetFuntion.cs │ │ │ │ ├── ImageSelectorWidgetFunction.cs │ │ │ │ ├── Integer/ │ │ │ │ │ └── IntegerTextBoxWidgetFuntion.cs │ │ │ │ ├── MediaFileSelectorWidgetFunction.cs │ │ │ │ ├── MediaFolderSelectorWidget.cs │ │ │ │ ├── SelectorWidgetFunction.cs │ │ │ │ ├── StandardWidgetFunctionProvider.cs │ │ │ │ ├── StandardWidgetFunctionProviderEntityToken.cs │ │ │ │ ├── String/ │ │ │ │ │ ├── DataIdMultiSelectorWidgetFunction.cs │ │ │ │ │ ├── FontIconSelectorWidgetFuntion.cs │ │ │ │ │ ├── HierarchicalSelectorWidgetFunction.cs │ │ │ │ │ ├── SelectorWidgetFunction.cs │ │ │ │ │ ├── TextAreaWidgetFunction.cs │ │ │ │ │ ├── TextBoxWidgetFuntion.cs │ │ │ │ │ ├── TreeSelectorWidgetFunction.cs │ │ │ │ │ ├── UrlComboBoxWidgetFunction.cs │ │ │ │ │ └── VisualXhtmlEditorWidgetFuntion.cs │ │ │ │ ├── Type/ │ │ │ │ │ └── DataTypeSelectorWidgetFunction.cs │ │ │ │ ├── Utils/ │ │ │ │ │ ├── ConsoleIconSelectorWidgetFuntion.cs │ │ │ │ │ ├── FormMarkupWidgetFuntion.cs │ │ │ │ │ └── SvgIconSelectorWidgetFuntion.cs │ │ │ │ └── XhtmlDocument/ │ │ │ │ └── VisualXhtmlEditorWidgetFuntion.cs │ │ │ └── XslExtensionsProviders/ │ │ │ ├── CaptchaXslExtension.cs │ │ │ ├── ConfigBasedXslExtensionsProvider/ │ │ │ │ ├── ConfigBasedXslExtensionsProvider.cs │ │ │ │ └── ConfigBasedXslExtensionsProviderData.cs │ │ │ └── StandardExtension.cs │ │ ├── GlobalSettings/ │ │ │ └── GlobalSettingsProviders/ │ │ │ └── ConfigBasedGlobalSettingsProvider.cs │ │ ├── IO/ │ │ │ └── IOProviders/ │ │ │ └── LocalIOProvider/ │ │ │ ├── LocalC1Configuration.cs │ │ │ ├── LocalC1Directory.cs │ │ │ ├── LocalC1DirectoryInfo.cs │ │ │ ├── LocalC1File.cs │ │ │ ├── LocalC1FileInfo.cs │ │ │ ├── LocalC1FileStream.cs │ │ │ ├── LocalC1FileSystemWatcher.cs │ │ │ ├── LocalC1StreamReader.cs │ │ │ ├── LocalC1StreamWriter.cs │ │ │ └── LocalIOProvider.cs │ │ ├── Instrumentation/ │ │ │ └── PerformanceCounterProviders/ │ │ │ ├── NoPerformanceCounterProvider/ │ │ │ │ └── NoPerformanceCounterProvider.cs │ │ │ └── WindowsPerformanceCounterProvider/ │ │ │ ├── PerformanceCounterInstaller.cs │ │ │ ├── PerformanceNames.cs │ │ │ └── WindowsPerformanceCounterProvider.cs │ │ ├── Logging/ │ │ │ └── LogTraceListeners/ │ │ │ ├── FileLogTraceListener/ │ │ │ │ ├── CircullarList.cs │ │ │ │ ├── CurrentFileReader.cs │ │ │ │ ├── FileLogTraceListener.cs │ │ │ │ ├── FileLogger.cs │ │ │ │ ├── LogFileInfo.cs │ │ │ │ ├── LogFileReader.cs │ │ │ │ ├── LogReaderHelper.cs │ │ │ │ └── PlainFileReader.cs │ │ │ ├── ManagementConsoleLogTracer/ │ │ │ │ └── ManagementConsoleLogTracer.cs │ │ │ └── SystemDiagnosticsTrace/ │ │ │ └── SystemDiagnosticsTraceBridge.cs │ │ ├── PageTemplates/ │ │ │ ├── Common/ │ │ │ │ ├── CachedTemplateInformation.cs │ │ │ │ └── TemplateParsingHelper.cs │ │ │ ├── MasterPages/ │ │ │ │ ├── CompilationHelper.cs │ │ │ │ ├── Controls/ │ │ │ │ │ ├── Functions/ │ │ │ │ │ │ ├── Function.cs │ │ │ │ │ │ ├── LazyParameterRuntimeTreeNode.cs │ │ │ │ │ │ ├── Markup.cs │ │ │ │ │ │ ├── Param.cs │ │ │ │ │ │ ├── ParamCollection.cs │ │ │ │ │ │ ├── ParamObjectConverter.cs │ │ │ │ │ │ ├── ParamTagControlBuilder.cs │ │ │ │ │ │ └── StringToObjectConverter.cs │ │ │ │ │ └── Rendering/ │ │ │ │ │ ├── Description.cs │ │ │ │ │ ├── DescriptionMetaTag.cs │ │ │ │ │ ├── PageTemplateFeature.cs │ │ │ │ │ ├── Render.cs │ │ │ │ │ └── Title.cs │ │ │ │ ├── MasterPageBase.cs │ │ │ │ ├── MasterPagePageRenderer.cs │ │ │ │ ├── MasterPagePageTemplate.cs │ │ │ │ ├── MasterPagePageTemplateDescriptor.cs │ │ │ │ ├── MasterPagePageTemplateProvider.cs │ │ │ │ ├── MasterPagePageTemplateProviderData.cs │ │ │ │ ├── MasterPageRenderingInfo.cs │ │ │ │ └── SharedMasterPage.cs │ │ │ ├── Razor/ │ │ │ │ ├── RazorPageRenderer.cs │ │ │ │ ├── RazorPageTemplateDescriptor.cs │ │ │ │ ├── RazorPageTemplateProvider.cs │ │ │ │ ├── RazorPageTemplateProviderAssembler.cs │ │ │ │ ├── RazorPageTemplateProviderData.cs │ │ │ │ ├── SharedRazorFile.cs │ │ │ │ └── TemplateRenderingInfo.cs │ │ │ └── XmlPageTemplates/ │ │ │ ├── XmlPageRenderer.cs │ │ │ ├── XmlPageTemplateDescriptor.cs │ │ │ ├── XmlPageTemplateProvider.cs │ │ │ └── XmlPageTemplateProviderData.cs │ │ ├── ResourceSystem/ │ │ │ ├── AggregationLocalizationProvider/ │ │ │ │ └── AggregationLocalizationProvider.cs │ │ │ ├── PropertyResourceProvider/ │ │ │ │ └── PropertyResourceProvider.cs │ │ │ ├── XmlLocalizationProvider/ │ │ │ │ └── XmlLocalizationProvider.cs │ │ │ └── XmlStringResourceProvider/ │ │ │ └── XmlStringResourceProvider.cs │ │ ├── Routing/ │ │ │ ├── Hostnames/ │ │ │ │ └── FormFunctions.cs │ │ │ ├── InternalUrlConverters/ │ │ │ │ ├── DataInternalUrlConverter.cs │ │ │ │ ├── MediaInternalUrlConverter.cs │ │ │ │ └── PageInternalUrlConverter.cs │ │ │ ├── InternalUrlProviders/ │ │ │ │ └── DataInternalUrlProvider.cs │ │ │ ├── MediaUrlProviders/ │ │ │ │ └── DefaultMediaUrlProvider.cs │ │ │ ├── Pages/ │ │ │ │ ├── DefaultPageUrlProvider.cs │ │ │ │ └── PageUrlBuilder.cs │ │ │ └── UrlFormatters/ │ │ │ ├── StringReplaceUrlFormatter.cs │ │ │ └── ToLowerCaseUrlFormatter.cs │ │ ├── Search/ │ │ │ └── Endpoint/ │ │ │ ├── ConsoleSearchPageStructure.cs │ │ │ ├── ConsoleSearchQuery.cs │ │ │ ├── ConsoleSearchResult.cs │ │ │ └── ConsoleSearchRpcService.cs │ │ ├── Security/ │ │ │ ├── HookRegistrators/ │ │ │ │ └── ElementHookRegistrator/ │ │ │ │ └── ElementHookRegistrator.cs │ │ │ ├── LoginProviderPlugins/ │ │ │ │ ├── ConfigBasedFormLoginProvider/ │ │ │ │ │ └── ConfigBasedFormLoginProvider.cs │ │ │ │ ├── DataBasedFormLoginProvider/ │ │ │ │ │ ├── DataBasedFormLoginProvider.cs │ │ │ │ │ └── UserFormLoginManager.cs │ │ │ │ └── ValidateAllWindowsLoginProvider/ │ │ │ │ └── ValidateAllWindowsLoginProvider.cs │ │ │ ├── LoginSessionStores/ │ │ │ │ ├── HttpContextBasedLoginSessionStore/ │ │ │ │ │ └── HttpContextBasedLoginSessionStore.cs │ │ │ │ └── WampContextBasedLoginSessionStore/ │ │ │ │ └── WampContextBasedBasedLoginSessionStore.cs │ │ │ ├── PasswordRules/ │ │ │ │ ├── DifferentCharacterGroups/ │ │ │ │ │ └── DifferentCharacterGroupsPasswordRule.cs │ │ │ │ ├── DoNotUseUserName/ │ │ │ │ │ └── DoNotUseUserNamePasswordRule.cs │ │ │ │ ├── EnforcePasswordHistory/ │ │ │ │ │ └── EnforcePasswordHistoryPasswordRule.cs │ │ │ │ └── MinimumLength/ │ │ │ │ └── MinimumLengthPasswordRule.cs │ │ │ ├── UserGroupPermissionDefinitionProvider/ │ │ │ │ └── DataBasedUserGroupPermissionDefinitionProvider/ │ │ │ │ └── DataBasedUserGroupPermissionDefinitionProvider.cs │ │ │ └── UserPermissionDefinitionProvider/ │ │ │ ├── ConfigBasedUserPermissionDefinitionProvider/ │ │ │ │ └── ConfigBasedUserPermissionDefinitionProvider.cs │ │ │ └── DataBaseUserPermissionDefinitionProvider/ │ │ │ └── DataBaseUserPermissionDefinitionProvider.cs │ │ ├── Types/ │ │ │ └── TypeManagerTypeHandler/ │ │ │ ├── AspNetBuildManagerTypeManagerTypeHandler/ │ │ │ │ └── AspNetBuildManagerTypeManagerTypeHandler.cs │ │ │ ├── DynamicBuildManagerTypeManagerTypeHandler/ │ │ │ │ └── DynamicBuildManagerTypeManagerTypeHandler.cs │ │ │ └── SystemTypeManagerTypeHandler/ │ │ │ └── SystemTypeManagerTypeHandler.cs │ │ ├── Validation/ │ │ │ └── ClientValidationRuleTranslators/ │ │ │ └── StandardClientValidationRuleTranslator/ │ │ │ └── StandardClientValidationRuleTranslator.cs │ │ └── Workflow/ │ │ └── WorkflowRuntimeProviders/ │ │ └── StandardWorkflowRuntimeProvider/ │ │ └── StandardWorkflowRuntimeProvider.cs │ ├── Properties/ │ │ ├── AssemblyInfo.cs │ │ └── SharedAssemblyInfo.cs │ ├── RuntimeInformation.cs │ ├── Search/ │ │ ├── Crawling/ │ │ │ ├── DataFieldProcessors/ │ │ │ │ ├── DateTimeDataFieldProcessor.cs │ │ │ │ ├── FileNameDataFieldProcessor.cs │ │ │ │ ├── MediaTagsDataFieldProcessor.cs │ │ │ │ ├── MimeTypeDataFieldProcessor.cs │ │ │ │ └── PublicationStatusDataFieldProcessor.cs │ │ │ ├── DataTypeSearchReflectionHelper.cs │ │ │ ├── DefaultDataFieldProcessor.cs │ │ │ ├── DocumentFieldNames.cs │ │ │ ├── EntityTokenSecurityHelper.cs │ │ │ ├── IDataFieldProcessor.cs │ │ │ ├── IDataFieldProcessorProvider.cs │ │ │ ├── IDocumentFieldProvider.cs │ │ │ ├── ISearchDocumentBuilderExtension.cs │ │ │ ├── SearchDocumentBuilder.cs │ │ │ └── XhtmlCrawlingHelper.cs │ │ ├── DocumentField.cs │ │ ├── DocumentSources/ │ │ │ ├── BuiltInTypesDocumentSourceProvider.cs │ │ │ ├── CmsPageDocumentSource.cs │ │ │ ├── DataChangesIndexNotifier.cs │ │ │ ├── DataTypeDocumentSource.cs │ │ │ ├── DataTypesDocumentSourceProvider.cs │ │ │ ├── IndexUpdateActionContainer.cs │ │ │ └── MediaLibraryDocumentSource.cs │ │ ├── IDocumentSourceListener.cs │ │ ├── ISearchDocumentSource.cs │ │ ├── ISearchDocumentSourceProvider.cs │ │ ├── ISearchIndexUpdater.cs │ │ ├── ISearchProvider.cs │ │ ├── SearchDocument.cs │ │ ├── SearchFacade.cs │ │ ├── SearchQuery.cs │ │ └── SearchResult.cs │ ├── Verify.cs │ └── packages.config ├── Composite.Workflows/ │ ├── C1Console/ │ │ ├── Actions/ │ │ │ └── Workflows/ │ │ │ ├── EntityTokenLockedWorkflow.cs │ │ │ ├── EntityTokenLockedWorkflow.designer.cs │ │ │ ├── EntityTokenLockedWorkflow.layout │ │ │ ├── FlowInformationScavengerWorkflow.cs │ │ │ ├── FlowInformationScavengerWorkflow.designer.cs │ │ │ ├── FlowInformationScavengerWorkflow.layout │ │ │ ├── SecurityViolationWorkflow.cs │ │ │ ├── SecurityViolationWorkflow.designer.cs │ │ │ └── SecurityViolationWorkflow.layout │ │ ├── Elements/ │ │ │ └── ElementProviderHelpers/ │ │ │ └── AssociatedDataElementProviderHelper/ │ │ │ ├── AddAssociatedDataWorkflow.cs │ │ │ ├── AddAssociatedDataWorkflow.designer.cs │ │ │ ├── AddAssociatedDataWorkflow.layout │ │ │ ├── AddDataFolderExWorkflow.cs │ │ │ ├── AddDataFolderExWorkflow.designer.cs │ │ │ ├── AddDataFolderExWorkflow.layout │ │ │ ├── AddMetaDataWorkflow.cs │ │ │ ├── AddMetaDataWorkflow.designer.cs │ │ │ ├── AddMetaDataWorkflow.layout │ │ │ ├── DeleteAssociatedDataWorkflow.cs │ │ │ ├── DeleteAssociatedDataWorkflow.designer.cs │ │ │ ├── DeleteAssociatedDataWorkflow.layout │ │ │ ├── DeleteDataFolderWorkflow.cs │ │ │ ├── DeleteDataFolderWorkflow.designer.cs │ │ │ ├── DeleteDataFolderWorkflow.layout │ │ │ ├── DeleteMetaDataWorkflow.cs │ │ │ ├── DeleteMetaDataWorkflow.designer.cs │ │ │ ├── DeleteMetaDataWorkflow.layout │ │ │ ├── EditAssociatedDataWorkflow.cs │ │ │ ├── EditAssociatedDataWorkflow.designer.cs │ │ │ ├── EditAssociatedDataWorkflow.layout │ │ │ ├── EditMetaDataWorkflow.cs │ │ │ ├── EditMetaDataWorkflow.designer.cs │ │ │ └── EditMetaDataWorkflow.layout │ │ ├── Events/ │ │ │ └── Workflows/ │ │ │ ├── UserConsoleInformationScavengerWorkflow.cs │ │ │ ├── UserConsoleInformationScavengerWorkflow.designer.cs │ │ │ └── UserConsoleInformationScavengerWorkflow.layout │ │ ├── Scheduling/ │ │ │ ├── BaseSchedulerWorkflow.cs │ │ │ ├── BaseSchedulerWorkflow.designer.cs │ │ │ ├── DataPublishSchedulerWorkflow.cs │ │ │ ├── DataUnpublishSchedulerWorkflow.cs │ │ │ ├── PagePublishSchedulerWorkflow.cs │ │ │ ├── PageUnpublishSchedulerWorkflow.cs │ │ │ └── PublishControlledHelper.cs │ │ ├── Tools/ │ │ │ ├── SendMessageToConsolesWorkflow.cs │ │ │ ├── SendMessageToConsolesWorkflow.designer.cs │ │ │ ├── SendMessageToConsolesWorkflow.layout │ │ │ ├── SetTimeZoneWorkflow.cs │ │ │ └── SetTimeZoneWorkflow.designer.cs │ │ ├── Trees/ │ │ │ └── Workflows/ │ │ │ ├── AddApplicationWorkflow.cs │ │ │ ├── AddApplicationWorkflow.designer.cs │ │ │ ├── AddApplicationWorkflow.layout │ │ │ ├── AddTreeDefinitionWorkflow.cs │ │ │ ├── AddTreeDefinitionWorkflow.designer.cs │ │ │ ├── AddTreeDefinitionWorkflow.layout │ │ │ ├── ConfirmActionWorkflow.cs │ │ │ ├── ConfirmActionWorkflow.designer.cs │ │ │ ├── ConfirmActionWorkflow.layout │ │ │ ├── DeleteTreeDefinitionWorkflow.cs │ │ │ ├── DeleteTreeDefinitionWorkflow.designer.cs │ │ │ ├── DeleteTreeDefinitionWorkflow.layout │ │ │ ├── EditTreeDefinitionWorkflow.cs │ │ │ ├── EditTreeDefinitionWorkflow.designer.cs │ │ │ ├── EditTreeDefinitionWorkflow.layout │ │ │ ├── GenericAddDataWorkflow.cs │ │ │ ├── GenericAddDataWorkflow.designer.cs │ │ │ ├── GenericAddDataWorkflow.layout │ │ │ ├── GenericDeleteDataWorkflow.cs │ │ │ ├── GenericDeleteDataWorkflow.designer.cs │ │ │ ├── GenericDeleteDataWorkflow.layout │ │ │ ├── GenericEditDataWorkflow.cs │ │ │ ├── GenericEditDataWorkflow.designer.cs │ │ │ ├── GenericEditDataWorkflow.layout │ │ │ ├── LocalizeDataWorkflow.cs │ │ │ ├── LocalizeDataWorkflow.designer.cs │ │ │ ├── LocalizeDataWorkflow.layout │ │ │ ├── RemoveApplicationWorkflow.cs │ │ │ ├── RemoveApplicationWorkflow.designer.cs │ │ │ ├── RemoveApplicationWorkflow.layout │ │ │ ├── ReportFunctionActionWorkflow.cs │ │ │ ├── ReportFunctionActionWorkflow.designer.cs │ │ │ └── ReportFunctionActionWorkflow.layout │ │ └── Users/ │ │ └── Workflows/ │ │ ├── ChangeOwnActiveLocaleWorkflow.cs │ │ ├── ChangeOwnActiveLocaleWorkflow.designer.cs │ │ ├── ChangeOwnActiveLocaleWorkflow.layout │ │ ├── ChangeOwnCultureWorkflow.cs │ │ ├── ChangeOwnCultureWorkflow.designer.cs │ │ ├── ChangeOwnForeignLocaleWorkflow.cs │ │ ├── ChangeOwnForeignLocaleWorkflow.designer.cs │ │ ├── ChangeOwnForeignLocaleWorkflow.layout │ │ ├── ChangeOwnPasswordWorkflow.cs │ │ └── ChangeOwnPasswordWorkflow.designer.cs │ ├── Composite.Workflows.csproj │ ├── Composite.Workflows.csproj.vspscc │ ├── Plugins/ │ │ └── Elements/ │ │ └── ElementProviders/ │ │ ├── AllFunctionsElementProvider/ │ │ │ ├── FunctionTesterWorkflow.cs │ │ │ ├── FunctionTesterWorkflow.designer.cs │ │ │ └── FunctionTesterWorkflow.layout │ │ ├── Common/ │ │ │ ├── BaseFunctionWorkflow.cs │ │ │ ├── KeyFieldHelper.cs │ │ │ └── PageTemplateHelper.cs │ │ ├── GeneratedDataTypesElementProvider/ │ │ │ ├── AddNewCompositionTypeWorkflow.cs │ │ │ ├── AddNewCompositionTypeWorkflow.designer.cs │ │ │ ├── AddNewCompositionTypeWorkflow.layout │ │ │ ├── AddNewDataWorkflow.Designer.cs │ │ │ ├── AddNewDataWorkflow.cs │ │ │ ├── AddNewDataWorkflow.layout │ │ │ ├── AddNewInterfaceTypeWorkflow.cs │ │ │ ├── AddNewInterfaceTypeWorkflow.designer.cs │ │ │ ├── AddNewInterfaceTypeWorkflow.layout │ │ │ ├── AddTypeToWhiteListWorkflow.cs │ │ │ ├── AddTypeToWhiteListWorkflow.designer.cs │ │ │ ├── AddTypeToWhiteListWorkflow.layout │ │ │ ├── DeleteAggregationTypeWorkflow.cs │ │ │ ├── DeleteAggregationTypeWorkflow.designer.cs │ │ │ ├── DeleteAggregationTypeWorkflow.layout │ │ │ ├── DeleteCompositionTypeWorkflow.cs │ │ │ ├── DeleteCompositionTypeWorkflow.designer.cs │ │ │ ├── DeleteCompositionTypeWorkflow.layout │ │ │ ├── DeleteDataWorkflow.cs │ │ │ ├── DeleteDataWorkflow.designer.cs │ │ │ ├── DeleteDataWorkflow.layout │ │ │ ├── DeleteInterfaceTypeWorkflow.cs │ │ │ ├── DeleteInterfaceTypeWorkflow.designer.cs │ │ │ ├── DeleteInterfaceTypeWorkflow.layout │ │ │ ├── DisableTypeLocalizationWorkflow.cs │ │ │ ├── DisableTypeLocalizationWorkflow.designer.cs │ │ │ ├── DisableTypeLocalizationWorkflow.layout │ │ │ ├── EditCompositionTypeWorkflow.cs │ │ │ ├── EditCompositionTypeWorkflow.designer.cs │ │ │ ├── EditCompositionTypeWorkflow.layout │ │ │ ├── EditDataWorkflow.Designer.cs │ │ │ ├── EditDataWorkflow.cs │ │ │ ├── EditDataWorkflow.layout │ │ │ ├── EditFormWorkflow.cs │ │ │ ├── EditFormWorkflow.designer.cs │ │ │ ├── EditInterfaceTypeWorkflow.Designer.cs │ │ │ ├── EditInterfaceTypeWorkflow.cs │ │ │ ├── EditInterfaceTypeWorkflow.layout │ │ │ ├── EnableTypeLocalizationWorkflow.cs │ │ │ ├── EnableTypeLocalizationWorkflow.designer.cs │ │ │ ├── EnableTypeLocalizationWorkflow.layout │ │ │ ├── LocalizeDataWorkflow.cs │ │ │ ├── LocalizeDataWorkflow.designer.cs │ │ │ ├── LocalizeDataWorkflow.layout │ │ │ ├── RemoveTypeFromWhiteListWorkflow.cs │ │ │ ├── RemoveTypeFromWhiteListWorkflow.designer.cs │ │ │ └── RemoveTypeFromWhiteListWorkflow.layout │ │ ├── LocalizationElementProvider/ │ │ │ ├── AddSystemLocaleWorkflow.cs │ │ │ ├── AddSystemLocaleWorkflow.designer.cs │ │ │ ├── AddSystemLocaleWorkflow.layout │ │ │ ├── DefineDefaultActiveLocaleWorkflow.cs │ │ │ ├── DefineDefaultActiveLocaleWorkflow.designer.cs │ │ │ ├── DefineDefaultActiveLocaleWorkflow.layout │ │ │ ├── EditSystemLocaleWorkflow.cs │ │ │ ├── EditSystemLocaleWorkflow.designer.cs │ │ │ ├── EditSystemLocaleWorkflow.layout │ │ │ ├── RemoveSystemLocaleWorkflow.cs │ │ │ ├── RemoveSystemLocaleWorkflow.designer.cs │ │ │ └── RemoveSystemLocaleWorkflow.layout │ │ ├── MediaFileProviderElementProvider/ │ │ │ ├── AddMediaZipFileWorkflow.Designer.cs │ │ │ ├── AddMediaZipFileWorkflow.cs │ │ │ ├── AddMediaZipFileWorkflow.layout │ │ │ ├── AddNewMediaFileWorkflow.Designer.cs │ │ │ ├── AddNewMediaFileWorkflow.cs │ │ │ ├── AddNewMediaFileWorkflow.layout │ │ │ ├── AddNewMediaFolderWorkflow.Designer.cs │ │ │ ├── AddNewMediaFolderWorkflow.cs │ │ │ ├── AddNewMediaFolderWorkflow.layout │ │ │ ├── DeleteMediaFileWorkflow.Designer.cs │ │ │ ├── DeleteMediaFileWorkflow.cs │ │ │ ├── DeleteMediaFileWorkflow.layout │ │ │ ├── DeleteMediaFolderWorkflow.Designer.cs │ │ │ ├── DeleteMediaFolderWorkflow.cs │ │ │ ├── DeleteMediaFolderWorkflow.layout │ │ │ ├── EditMediaFileContentWorkflow.cs │ │ │ ├── EditMediaFileContentWorkflow.designer.cs │ │ │ ├── EditMediaFileContentWorkflow.layout │ │ │ ├── EditMediaFileTextContentWorkflow.cs │ │ │ ├── EditMediaFileTextContentWorkflow.designer.cs │ │ │ ├── EditMediaFileWorkflow.Designer.cs │ │ │ ├── EditMediaFileWorkflow.cs │ │ │ ├── EditMediaFileWorkflow.layout │ │ │ ├── EditMediaFolderWorkflow.Designer.cs │ │ │ ├── EditMediaFolderWorkflow.cs │ │ │ ├── EditMediaFolderWorkflow.layout │ │ │ ├── UploadNewMediaFileWorkflow.Designer.cs │ │ │ ├── UploadNewMediaFileWorkflow.cs │ │ │ └── UploadNewMediaFileWorkflow.layout │ │ ├── MethodBasedFunctionProviderElementProvider/ │ │ │ ├── AddInlineFunctionWorkflow.Designer.cs │ │ │ ├── AddInlineFunctionWorkflow.cs │ │ │ ├── AddInlineFunctionWorkflow.layout │ │ │ ├── AddNewMethodBasedFunctionWorkflow.Designer.cs │ │ │ ├── AddNewMethodBasedFunctionWorkflow.cs │ │ │ ├── AddNewMethodBasedFunctionWorkflow.layout │ │ │ ├── DeleteInlineFunctionWorkflow.cs │ │ │ ├── DeleteInlineFunctionWorkflow.designer.cs │ │ │ ├── DeleteInlineFunctionWorkflow.layout │ │ │ ├── DeleteMethodBasedFunctionWorkflow.Designer.cs │ │ │ ├── DeleteMethodBasedFunctionWorkflow.cs │ │ │ ├── DeleteMethodBasedFunctionWorkflow.layout │ │ │ ├── EditInlineFunctionWorkflow.cs │ │ │ ├── EditInlineFunctionWorkflow.designer.cs │ │ │ ├── EditInlineFunctionWorkflow.layout │ │ │ ├── EditMethodBasedFunctionWorkflow.Designer.cs │ │ │ ├── EditMethodBasedFunctionWorkflow.cs │ │ │ └── EditMethodBasedFunctionWorkflow.layout │ │ ├── PackageElementProvider/ │ │ │ ├── AddPackageSourceWorkflow.cs │ │ │ ├── AddPackageSourceWorkflow.designer.cs │ │ │ ├── AddPackageSourceWorkflow.layout │ │ │ ├── DeletePackageSourceWorkflow.cs │ │ │ ├── DeletePackageSourceWorkflow.designer.cs │ │ │ ├── DeletePackageSourceWorkflow.layout │ │ │ ├── InstallLocalPackageWorkflow.cs │ │ │ ├── InstallLocalPackageWorkflow.designer.cs │ │ │ ├── InstallLocalPackageWorkflow.layout │ │ │ ├── InstallRemotePackageWorkflow.cs │ │ │ ├── InstallRemotePackageWorkflow.designer.cs │ │ │ ├── InstallRemotePackageWorkflow.layout │ │ │ ├── UninstallLocalPackageWorkflow.cs │ │ │ ├── UninstallLocalPackageWorkflow.designer.cs │ │ │ ├── UninstallLocalPackageWorkflow.layout │ │ │ ├── UninstallRemotePackageWorkflow.cs │ │ │ ├── UninstallRemotePackageWorkflow.designer.cs │ │ │ ├── UninstallRemotePackageWorkflow.layout │ │ │ ├── ViewAvailablePackageInfoWorkflowWorkflow.cs │ │ │ ├── ViewAvailablePackageInfoWorkflowWorkflow.designer.cs │ │ │ ├── ViewAvailablePackageInfoWorkflowWorkflow.layout │ │ │ ├── ViewInstalledPackageInfoWorkflow.cs │ │ │ ├── ViewInstalledPackageInfoWorkflow.designer.cs │ │ │ └── ViewInstalledPackageInfoWorkflow.layout │ │ ├── PageElementProvider/ │ │ │ ├── AddNewPageWorkflow.Designer.cs │ │ │ ├── AddNewPageWorkflow.cs │ │ │ ├── AddNewPageWorkflow.layout │ │ │ ├── DeletePageWorkflow.Designer.cs │ │ │ ├── DeletePageWorkflow.cs │ │ │ ├── DeletePageWorkflow.layout │ │ │ ├── DeletePageWorkflow.rules │ │ │ ├── EditPageWorkflow.Designer.cs │ │ │ ├── EditPageWorkflow.cs │ │ │ ├── EditPageWorkflow.layout │ │ │ ├── LocalizePageWorkflow.cs │ │ │ ├── LocalizePageWorkflow.designer.cs │ │ │ ├── LocalizePageWorkflow.layout │ │ │ ├── UnLocalizePageWorkflow.cs │ │ │ ├── UnLocalizePageWorkflow.designer.cs │ │ │ ├── UnLocalizePageWorkflow.layout │ │ │ ├── UndoUnpublishedChangesWorkflow.cs │ │ │ ├── UndoUnpublishedChangesWorkflow.designer.cs │ │ │ └── UndoUnpublishedChangesWorkflow.layout │ │ ├── PageTemplateElementProvider/ │ │ │ ├── AddNewMasterPagePageTemplateWorkflow.Designer.cs │ │ │ ├── AddNewMasterPagePageTemplateWorkflow.cs │ │ │ ├── AddNewMasterPagePageTemplateWorkflow.layout │ │ │ ├── AddNewPageTemplateWorkflow.Designer.cs │ │ │ ├── AddNewPageTemplateWorkflow.cs │ │ │ ├── AddNewPageTemplateWorkflow.layout │ │ │ ├── AddNewRazorPageTemplateWorkflow.Designer.cs │ │ │ ├── AddNewRazorPageTemplateWorkflow.cs │ │ │ ├── AddNewRazorPageTemplateWorkflow.layout │ │ │ ├── AddNewXmlPageTemplateWorkflow.Designer.cs │ │ │ ├── AddNewXmlPageTemplateWorkflow.cs │ │ │ ├── DeletePageTemplateWorkflow.Designer.cs │ │ │ ├── DeletePageTemplateWorkflow.cs │ │ │ ├── DeletePageTemplateWorkflow.layout │ │ │ ├── EditMasterPageWorkflow.cs │ │ │ ├── EditMasterPageWorkflow.designer.cs │ │ │ ├── EditMasterPageWorkflow.layout │ │ │ ├── EditRazorPageTemplateWorkflow.cs │ │ │ ├── EditRazorPageTemplateWorkflow.designer.cs │ │ │ ├── EditRazorPageTemplateWorkflow.layout │ │ │ ├── EditSharedCodeFileWorkflow.cs │ │ │ ├── EditSharedCodeFileWorkflow.designer.cs │ │ │ ├── EditSharedCodeFileWorkflow.layout │ │ │ ├── EditXmlPageTemplateWorkflow.Designer.cs │ │ │ └── EditXmlPageTemplateWorkflow.cs │ │ ├── PageTemplateFeatureElementProvider/ │ │ │ ├── AddPageTemplateFeatureWorkflow.cs │ │ │ ├── AddPageTemplateFeatureWorkflow.designer.cs │ │ │ ├── AddPageTemplateFeatureWorkflow.layout │ │ │ ├── DeletePageTemplateFeatureWorkflow.cs │ │ │ ├── DeletePageTemplateFeatureWorkflow.designer.cs │ │ │ ├── DeletePageTemplateFeatureWorkflow.layout │ │ │ ├── EditPageTemplateFeatureWorkflow.cs │ │ │ ├── EditPageTemplateFeatureWorkflow.designer.cs │ │ │ ├── EditTreeDefinitionWorkflow.layout │ │ │ ├── TogglePageTemplateFeatureEditorWorkflow.cs │ │ │ ├── TogglePageTemplateFeatureEditorWorkflow.designer.cs │ │ │ └── TogglePageTemplateFeatureEditorWorkflow.layout │ │ ├── PageTypeElementProvider/ │ │ │ ├── AddNewPageTypeWorkflow.cs │ │ │ ├── AddNewPageTypeWorkflow.designer.cs │ │ │ ├── AddNewPageTypeWorkflow.layout │ │ │ ├── AddPageTypeDefaultPageContentWorkflow.cs │ │ │ ├── AddPageTypeDefaultPageContentWorkflow.designer.cs │ │ │ ├── AddPageTypeDefaultPageContentWorkflow.layout │ │ │ ├── AddPageTypeMetaDataFieldWorkflow.cs │ │ │ ├── AddPageTypeMetaDataFieldWorkflow.designer.cs │ │ │ ├── AddPageTypeMetaDataFieldWorkflow.layout │ │ │ ├── DeletePageTypeMetaDataFieldWorkflow.cs │ │ │ ├── DeletePageTypeMetaDataFieldWorkflow.designer.cs │ │ │ ├── DeletePageTypeMetaDataFieldWorkflow.layout │ │ │ ├── DeletePageTypeWorkflow.cs │ │ │ ├── DeletePageTypeWorkflow.designer.cs │ │ │ ├── DeletePageTypeWorkflow.layout │ │ │ ├── EditPageTypeDefaultPageContentWorkflow.cs │ │ │ ├── EditPageTypeDefaultPageContentWorkflow.designer.cs │ │ │ ├── EditPageTypeDefaultPageContentWorkflow.layout │ │ │ ├── EditPageTypeMetaDataFieldWorkflow.cs │ │ │ ├── EditPageTypeMetaDataFieldWorkflow.designer.cs │ │ │ ├── EditPageTypeMetaDataFieldWorkflow.layout │ │ │ ├── EditPageTypeWorkflow.cs │ │ │ ├── EditPageTypeWorkflow.designer.cs │ │ │ └── EditPageTypeWorkflow.layout │ │ ├── RazorFunctionProviderElementProvider/ │ │ │ ├── AddNewRazorFunctionWorkflow.Designer.cs │ │ │ ├── AddNewRazorFunctionWorkflow.cs │ │ │ ├── AddNewRazorFunctionWorkflow.layout │ │ │ ├── DeleteRazorFunctionWorkflow.Designer.cs │ │ │ ├── DeleteRazorFunctionWorkflow.cs │ │ │ ├── DeleteRazorFunctionWorkflow.layout │ │ │ ├── EditRazorFunctionWorkflow.cs │ │ │ └── EditRazorFunctionWorkflow.designer.cs │ │ ├── SqlFunctionElementProvider/ │ │ │ ├── AddNewSqlConnectionWorkflow.Designer.cs │ │ │ ├── AddNewSqlConnectionWorkflow.cs │ │ │ ├── AddNewSqlConnectionWorkflow.layout │ │ │ ├── AddNewSqlFunctionProviderWorkflow.Designer.cs │ │ │ ├── AddNewSqlFunctionProviderWorkflow.cs │ │ │ ├── AddNewSqlFunctionProviderWorkflow.layout │ │ │ ├── DeleteSqlConnectionWorkflow.Designer.cs │ │ │ ├── DeleteSqlConnectionWorkflow.cs │ │ │ ├── DeleteSqlConnectionWorkflow.layout │ │ │ ├── DeleteSqlFunctionProviderWorkflow.Designer.cs │ │ │ ├── DeleteSqlFunctionProviderWorkflow.cs │ │ │ ├── DeleteSqlFunctionProviderWorkflow.layout │ │ │ ├── EditSqlConnectionWorkflow.Designer.cs │ │ │ ├── EditSqlConnectionWorkflow.cs │ │ │ ├── EditSqlConnectionWorkflow.layout │ │ │ ├── EditSqlFunctionProviderWorkflow.Designer.cs │ │ │ ├── EditSqlFunctionProviderWorkflow.cs │ │ │ └── EditSqlFunctionProviderWorkflow.layout │ │ ├── UserControlFunctionProviderElementProvider/ │ │ │ ├── AddNewUserControlFunctionWorkflow.Designer.cs │ │ │ ├── AddNewUserControlFunctionWorkflow.cs │ │ │ ├── AddNewUserControlFunctionWorkflow.layout │ │ │ ├── DeleteUserControlFunctionWorkflow.Designer.cs │ │ │ ├── DeleteUserControlFunctionWorkflow.cs │ │ │ ├── DeleteUserControlFunctionWorkflow.layout │ │ │ ├── EditUserControlFunctionWorkflow.cs │ │ │ └── EditUserControlFunctionWorkflow.designer.cs │ │ ├── UserElementProvider/ │ │ │ ├── AddNewUserWorkflow.cs │ │ │ ├── AddNewUserWorkflow.designer.cs │ │ │ ├── AddNewUserWorkflow.layout │ │ │ ├── DeleteUserWorkflow.cs │ │ │ ├── DeleteUserWorkflow.designer.cs │ │ │ ├── DeleteUserWorkflow.layout │ │ │ ├── EditUserWorkflow.cs │ │ │ ├── EditUserWorkflow.designer.cs │ │ │ └── EditUserWorkflow.layout │ │ ├── UserGroupElementProvider/ │ │ │ ├── AddNewUserGroupWorkflow.Designer.cs │ │ │ ├── AddNewUserGroupWorkflow.cs │ │ │ ├── AddNewUserGroupWorkflow.layout │ │ │ ├── DeleteUserGroupWorkflow.cs │ │ │ ├── DeleteUserGroupWorkflow.designer.cs │ │ │ ├── DeleteUserGroupWorkflow.layout │ │ │ ├── EditUserGroupWorkflow.cs │ │ │ ├── EditUserGroupWorkflow.designer.cs │ │ │ └── EditUserGroupWorkflow.layout │ │ ├── VisualFunctionProviderElementProvider/ │ │ │ ├── AddNewVisualFunctionWorkflow.cs │ │ │ ├── AddNewVisualFunctionWorkflow.designer.cs │ │ │ ├── AddNewVisualFunctionWorkflow.layout │ │ │ ├── DeleteVisualFunctionWorkflow.cs │ │ │ ├── DeleteVisualFunctionWorkflow.designer.cs │ │ │ ├── EditVisualFunctionWorkflow.cs │ │ │ ├── EditVisualFunctionWorkflow.designer.cs │ │ │ └── EditVisualFunctionWorkflow.layout │ │ ├── WebsiteFileElementProvider/ │ │ │ ├── AddNewWebsiteFileWorkflow.cs │ │ │ ├── AddNewWebsiteFileWorkflow.designer.cs │ │ │ ├── AddNewWebsiteFileWorkflow.layout │ │ │ ├── AddNewWebsiteFolderWorkflow.cs │ │ │ ├── AddNewWebsiteFolderWorkflow.designer.cs │ │ │ ├── AddNewWebsiteFolderWorkflow.layout │ │ │ ├── AddWebsiteFolderToWhiteListWorkflow.cs │ │ │ ├── AddWebsiteFolderToWhiteListWorkflow.designer.cs │ │ │ ├── DeleteWebsiteFileWorkflow.cs │ │ │ ├── DeleteWebsiteFileWorkflow.designer.cs │ │ │ ├── DeleteWebsiteFileWorkflow.layout │ │ │ ├── DeleteWebsiteFolderWorkflow.cs │ │ │ ├── DeleteWebsiteFolderWorkflow.designer.cs │ │ │ ├── DeleteWebsiteFolderWorkflow.layout │ │ │ ├── EditWebsiteFileTextContentWorkflow.cs │ │ │ ├── EditWebsiteFileTextContentWorkflow.designer.cs │ │ │ ├── EditWebsiteFileTextContentWorkflow.layout │ │ │ ├── RemoveWebsiteFolderFromWhiteListWorkflow.cs │ │ │ ├── RemoveWebsiteFolderFromWhiteListWorkflow.designer.cs │ │ │ ├── UploadAndExtractZipFileWorkflow.Designer.cs │ │ │ ├── UploadAndExtractZipFileWorkflow.cs │ │ │ ├── UploadAndExtractZipFileWorkflow.layout │ │ │ ├── UploadWebsiteFileWorkflow.cs │ │ │ ├── UploadWebsiteFileWorkflow.designer.cs │ │ │ └── UploadWebsiteFileWorkflow.layout │ │ └── XsltBasedFunctionProviderElementProvider/ │ │ ├── AddNewXsltFunctionWorkflow.Designer.cs │ │ ├── AddNewXsltFunctionWorkflow.cs │ │ ├── AddNewXsltFunctionWorkflow.layout │ │ ├── Common.cs │ │ ├── DeleteXsltFunctionWorkflow.Designer.cs │ │ ├── DeleteXsltFunctionWorkflow.cs │ │ ├── EditXsltFunctionWorkflow.Designer.cs │ │ ├── EditXsltFunctionWorkflow.cs │ │ └── EditXsltFunctionWorkflow.layout │ ├── Properties/ │ │ └── AssemblyInfo.cs │ └── packages.config ├── CompositeC1.sln ├── Install.ps1 ├── Package.ConsoleComponents.nuspec ├── Package.nuspec ├── README.md ├── Website/ │ ├── .bowerrc │ ├── .eslintignore │ ├── .eslintrc.json │ ├── .npmignore │ ├── Composite/ │ │ ├── CompileScripts.xml │ │ ├── GenerateIconSprite.aspx │ │ ├── GenerateIconSprite.aspx.cs │ │ ├── Login.aspx │ │ ├── Login.aspx.cs │ │ ├── Login.aspx.designer.cs │ │ ├── Welcome.js │ │ ├── app.aspx │ │ ├── applets/ │ │ │ └── custom_rhino.jar │ │ ├── base.css │ │ ├── blank.aspx │ │ ├── compile.aspx │ │ ├── console/ │ │ │ ├── README.txt │ │ │ ├── Tree.xml │ │ │ ├── access/ │ │ │ │ ├── postFrame.js │ │ │ │ ├── requestJSON.js │ │ │ │ ├── utils.js │ │ │ │ ├── wampClient.js │ │ │ │ └── wampTest.js │ │ │ ├── components/ │ │ │ │ ├── colors.js │ │ │ │ ├── container/ │ │ │ │ │ ├── ConnectDialog.js │ │ │ │ │ ├── ConnectDockPanel.js │ │ │ │ │ ├── ConnectFormPanel.js │ │ │ │ │ ├── ConnectLogPanel.js │ │ │ │ │ ├── ConnectSearchPage.js │ │ │ │ │ ├── ConnectTabPanel.js │ │ │ │ │ └── ConnectToolbarFrame.js │ │ │ │ └── presentation/ │ │ │ │ ├── ActionButton.js │ │ │ │ ├── Checkbox.js │ │ │ │ ├── CheckboxGroup.js │ │ │ │ ├── DataField.js │ │ │ │ ├── DataFieldLabel.js │ │ │ │ ├── DataFieldWrapper.js │ │ │ │ ├── Dialog.js │ │ │ │ ├── Fieldset.js │ │ │ │ ├── FormTab.js │ │ │ │ ├── HelpIcon.js │ │ │ │ ├── Icon.js │ │ │ │ ├── Input.js │ │ │ │ ├── LogPanel.js │ │ │ │ ├── Palette.js │ │ │ │ ├── ScrollBox.js │ │ │ │ ├── SearchFacets.js │ │ │ │ ├── SearchPage.js │ │ │ │ ├── SearchResults.js │ │ │ │ ├── Select.js │ │ │ │ ├── Spritesheet.js │ │ │ │ ├── SwitchPanel.js │ │ │ │ ├── TabBar.js │ │ │ │ ├── TextArea.js │ │ │ │ ├── Toolbar.js │ │ │ │ └── ToolbarFrame.js │ │ │ ├── console.js │ │ │ ├── iconIndex.js │ │ │ ├── index.html │ │ │ ├── index.prod.html │ │ │ └── state/ │ │ │ ├── actions/ │ │ │ │ ├── fetchFromProvider.js │ │ │ │ ├── fireAction.js │ │ │ │ ├── loadAndOpen.js │ │ │ │ ├── logs.js │ │ │ │ ├── pageDefs.js │ │ │ │ └── values.js │ │ │ ├── initState.js │ │ │ ├── normalizingSchema.js │ │ │ ├── observers.js │ │ │ ├── reducers/ │ │ │ │ ├── activity.js │ │ │ │ ├── dataFields.js │ │ │ │ ├── definitions.js │ │ │ │ ├── dialog.js │ │ │ │ ├── layout.js │ │ │ │ ├── logs.js │ │ │ │ ├── options.js │ │ │ │ └── providers.js │ │ │ ├── selectors/ │ │ │ │ ├── dialogSelector.js │ │ │ │ ├── formSelector.js │ │ │ │ ├── layoutSelector.js │ │ │ │ ├── logSelector.js │ │ │ │ ├── pageSelector.js │ │ │ │ ├── paletteDialogSelector.js │ │ │ │ ├── searchSelector.js │ │ │ │ ├── tabSelector.js │ │ │ │ ├── toolbarPropsSelector.js │ │ │ │ └── toolbarSelector.js │ │ │ └── store.js │ │ ├── content/ │ │ │ ├── branding/ │ │ │ │ ├── about-company.inc │ │ │ │ ├── brand-main.inc │ │ │ │ ├── company-logo-branded.inc │ │ │ │ ├── company-logo.inc │ │ │ │ ├── includes.inc │ │ │ │ ├── logo-branded.inc │ │ │ │ ├── logo.inc │ │ │ │ ├── start-page-content.inc │ │ │ │ └── start-page-js.inc │ │ │ ├── dialogs/ │ │ │ │ ├── about/ │ │ │ │ │ ├── About.js │ │ │ │ │ ├── about.aspx │ │ │ │ │ └── about.css │ │ │ │ ├── functions/ │ │ │ │ │ ├── EditFunctionCallDialogPageBinding.js │ │ │ │ │ ├── editFunctionCall.aspx │ │ │ │ │ ├── editFunctionCall.aspx.cs │ │ │ │ │ └── editFunctionCall.aspx.designer.cs │ │ │ │ ├── imageeditor/ │ │ │ │ │ └── scaleimage/ │ │ │ │ │ ├── ScaleImageDialogPageBinding.js │ │ │ │ │ └── scaleimage.aspx │ │ │ │ ├── multiselector/ │ │ │ │ │ ├── MultiSelectorDialogPageBinding.js │ │ │ │ │ └── multiselectordialog.aspx │ │ │ │ ├── options/ │ │ │ │ │ ├── OptionsDialogPageBinding.js │ │ │ │ │ └── options.aspx │ │ │ │ ├── postback/ │ │ │ │ │ ├── PostBackDialogPageBinding.js │ │ │ │ │ └── postbackdialog.aspx │ │ │ │ ├── save/ │ │ │ │ │ ├── SaveAllDialogPageBinding.js │ │ │ │ │ └── saveall.aspx │ │ │ │ ├── standard/ │ │ │ │ │ ├── StandardDialogPageBinding.js │ │ │ │ │ └── standard.aspx │ │ │ │ ├── systemtrees/ │ │ │ │ │ ├── DetailedPastePageBinding.js │ │ │ │ │ └── detailedpaste.aspx │ │ │ │ ├── tests/ │ │ │ │ │ ├── autoheight/ │ │ │ │ │ │ └── autoheightdialog.aspx │ │ │ │ │ ├── datadialog/ │ │ │ │ │ │ └── datadialog.aspx │ │ │ │ │ ├── fixedheight/ │ │ │ │ │ │ └── fixedheightdialog.aspx │ │ │ │ │ ├── forcefitness/ │ │ │ │ │ │ ├── forcefitness-advanced.aspx │ │ │ │ │ │ ├── forcefitness-basic.aspx │ │ │ │ │ │ ├── forcefitness-windowed-content.aspx │ │ │ │ │ │ └── forcefitness-windowed.aspx │ │ │ │ │ ├── multipage/ │ │ │ │ │ │ ├── page1.aspx │ │ │ │ │ │ └── page2.aspx │ │ │ │ │ ├── subpageforcefitness/ │ │ │ │ │ │ ├── child.aspx │ │ │ │ │ │ └── parent.aspx │ │ │ │ │ ├── subpages/ │ │ │ │ │ │ ├── sub1.aspx │ │ │ │ │ │ ├── sub2.aspx │ │ │ │ │ │ ├── sub3.aspx │ │ │ │ │ │ ├── sub4.aspx │ │ │ │ │ │ └── subpagedialog.aspx │ │ │ │ │ ├── textcontent/ │ │ │ │ │ │ └── textcontent.aspx │ │ │ │ │ └── wizard/ │ │ │ │ │ ├── wizard1.aspx │ │ │ │ │ ├── wizard2.aspx │ │ │ │ │ ├── wizard3.aspx │ │ │ │ │ └── wizard4.aspx │ │ │ │ ├── translations/ │ │ │ │ │ ├── TranslationsDialogPageBinding.js │ │ │ │ │ └── translations.aspx │ │ │ │ ├── treeselector/ │ │ │ │ │ ├── TreeSelectorDialogPageBinding.js │ │ │ │ │ ├── TreeSelectorToolBarBinding.js │ │ │ │ │ ├── treeselector.aspx │ │ │ │ │ └── treeselector.css │ │ │ │ ├── util/ │ │ │ │ │ └── comparestrings/ │ │ │ │ │ ├── CompareStringsDialogPageBinding.js │ │ │ │ │ ├── comparestrings.aspx │ │ │ │ │ ├── comparestrings.css │ │ │ │ │ ├── comparestringscontent.css │ │ │ │ │ └── comparestringscontent.html │ │ │ │ ├── webservices/ │ │ │ │ │ ├── WebServiceErrorDialogPageBinding.js │ │ │ │ │ ├── error.aspx │ │ │ │ │ └── error.css │ │ │ │ └── wysiwygeditor/ │ │ │ │ ├── VisualEditorDialogPageBinding.js │ │ │ │ ├── errors/ │ │ │ │ │ ├── ContentErrorDialogPageBinding.js │ │ │ │ │ └── contenterror.aspx │ │ │ │ ├── mozsecuritynote/ │ │ │ │ │ └── mozsecuritynote.aspx │ │ │ │ ├── visualeditordialog.css │ │ │ │ └── wysiwygeditordialog.aspx │ │ │ ├── flow/ │ │ │ │ ├── FlowUICompleted.css │ │ │ │ ├── FlowUICompleted.js │ │ │ │ ├── FlowUICompletedPageBinding.js │ │ │ │ ├── FlowUi.aspx │ │ │ │ ├── FlowUi.aspx.cs │ │ │ │ ├── FlowUi.aspx.designer.cs │ │ │ │ ├── FlowUiCompleted.aspx │ │ │ │ └── FlowUiCompletedDialog.aspx │ │ │ ├── forms/ │ │ │ │ ├── Administrative/ │ │ │ │ │ ├── AddAssociatedDataWorkflowTypeSelection.xml │ │ │ │ │ ├── AddAssociatedTypeAddExisting.xml │ │ │ │ │ ├── AddAssociatedTypeAddExistingSelectForeignKey.xml │ │ │ │ │ ├── AddAssociatedTypeAddingTypeSelection.xml │ │ │ │ │ ├── AddAssociatedTypeAssociationTypeSelection.xml │ │ │ │ │ ├── AddAssociatedTypeCompositionScopeSelection.xml │ │ │ │ │ ├── AddAssociatedTypeFinalInfo.xml │ │ │ │ │ ├── AddAssociatedTypeLevelsScopeSelection.xml │ │ │ │ │ ├── AddDataFolderCreateNewType.xml │ │ │ │ │ ├── AddDataFolderExSelectType.xml │ │ │ │ │ ├── AddDataFolderSelectType.xml │ │ │ │ │ ├── AddMediaFileStep1.xml │ │ │ │ │ ├── AddMediaFileStep2.xml │ │ │ │ │ ├── AddMetaDataCreateFieldGroup.xml │ │ │ │ │ ├── AddMetaDataNoTargetDataWarning.xml │ │ │ │ │ ├── AddMetaDataSelectType.xml │ │ │ │ │ ├── AddNewCompositionTypeStep1.xml │ │ │ │ │ ├── AddNewInterfaceTypeStep1.xml │ │ │ │ │ ├── AddNewMediaFolder.xml │ │ │ │ │ ├── AddNewMethodBasedFunctionStep1.xml │ │ │ │ │ ├── AddNewMethodBasedFunctionStep2.xml │ │ │ │ │ ├── AddNewMethodBasedFunctionStep3.xml │ │ │ │ │ ├── AddNewPageStep1.xml │ │ │ │ │ ├── AddNewPageStep2.xml │ │ │ │ │ ├── AddNewRazorFunction.xml │ │ │ │ │ ├── AddNewSqlFunction.xml │ │ │ │ │ ├── AddNewSqlFunctionConnection.xml │ │ │ │ │ ├── AddNewUserControlFunction.xml │ │ │ │ │ ├── AddNewUserStep1.xml │ │ │ │ │ ├── AddNewVisualFunctionStep1.xml │ │ │ │ │ ├── AddNewVisualFunctionStep2.xml │ │ │ │ │ ├── AddNewXsltFunctionStep1.xml │ │ │ │ │ ├── AddPageHostNameBindings.xml │ │ │ │ │ ├── AddSystemLocaleStep1.xml │ │ │ │ │ ├── AddZipMediaFile.xml │ │ │ │ │ ├── AllFunctionsElementProviderSearchForm.xml │ │ │ │ │ ├── ChangeOwnCulture.xml │ │ │ │ │ ├── ChangeOwnCultureConfirmReboot.xml │ │ │ │ │ ├── ChangeOwnForeignLocaleNoOrOneActiveLocale.xml │ │ │ │ │ ├── ChangeOwnForeignLocaleStep1.xml │ │ │ │ │ ├── ChangeOwnPassword.xml │ │ │ │ │ ├── CreateNewAssociatedTypeStep1.xml │ │ │ │ │ ├── DeleteAggregationTypeStep1.xml │ │ │ │ │ ├── DeleteAssociatedTypeDataStep1.xml │ │ │ │ │ ├── DeleteCompositionTypeStep1.xml │ │ │ │ │ ├── DeleteDataFolderConfirm.xml │ │ │ │ │ ├── DeleteDataFolderConfirmDeletingRelatedData.xml │ │ │ │ │ ├── DeleteGeneratedDataStep1.xml │ │ │ │ │ ├── DeleteGeneratedDataStep2.xml │ │ │ │ │ ├── DeleteGeneratedInteraceStep1.xml │ │ │ │ │ ├── DeleteMediaFile.xml │ │ │ │ │ ├── DeleteMediaFileConfirmRemovingRelatedData.xml │ │ │ │ │ ├── DeleteMediaFolder.xml │ │ │ │ │ ├── DeleteMediaFolderConfirmDeletingRelatedData.xml │ │ │ │ │ ├── DeleteMetaDataConfirm.xml │ │ │ │ │ ├── DeletePageStep1.xml │ │ │ │ │ ├── DeletePageStep2.xml │ │ │ │ │ ├── DeletePageStep3.xml │ │ │ │ │ ├── DeletePageTemplateStep1.xml │ │ │ │ │ ├── DeletePage_ConfirmAllVersionsDeletion.xml │ │ │ │ │ ├── DeleteRazorFunctionConfirm.xml │ │ │ │ │ ├── DeleteUserControlFunctionConfirm.xml │ │ │ │ │ ├── DeleteUserStep1.xml │ │ │ │ │ ├── DeleteVisualFunctionStep1.xml │ │ │ │ │ ├── DeleteXsltFunctionConfirm.xml │ │ │ │ │ ├── DisableTypeLocalizationStep1.xml │ │ │ │ │ ├── DisableTypeLocalizationStep2.xml │ │ │ │ │ ├── EditCompositionTypeStep1.xml │ │ │ │ │ ├── EditDynamicTypeFormMarkup.xml │ │ │ │ │ ├── EditInterfaceTypeStep1.xml │ │ │ │ │ ├── EditMediaFile.xml │ │ │ │ │ ├── EditMediaFileTextContent.xml │ │ │ │ │ ├── EditMediaFolder.xml │ │ │ │ │ ├── EditMetaDataSelectType.xml │ │ │ │ │ ├── EditMetaData_EditDefinition.xml │ │ │ │ │ ├── EditMetaData_NoDefaultValuesNeeded.xml │ │ │ │ │ ├── EditMetaData_SelectDefinition.xml │ │ │ │ │ ├── EditMethodBasedFunction.xml │ │ │ │ │ ├── EditPage.xml │ │ │ │ │ ├── EditRazorFunction.xml │ │ │ │ │ ├── EditSqlFunction.xml │ │ │ │ │ ├── EditSqlFunctionConnection.xml │ │ │ │ │ ├── EditSystemLocaleEdit.xml │ │ │ │ │ ├── EditUserControlFunction.xml │ │ │ │ │ ├── EditUserStep1.xml │ │ │ │ │ ├── EditVisualFunction.xml │ │ │ │ │ ├── EditXsltFunction.xml │ │ │ │ │ ├── ElementKeywordSearch.xml │ │ │ │ │ ├── EnableTypeLocalizationNoLocales.xml │ │ │ │ │ ├── EnableTypeLocalizationStep1.xml │ │ │ │ │ ├── EnableTypeLocalizationStep2.xml │ │ │ │ │ ├── EnableTypeLocalizationStep3.xml │ │ │ │ │ ├── EntityTokenLockedStep1.xml │ │ │ │ │ ├── FunctionTesterEditFunction.xml │ │ │ │ │ ├── Hostnames.xml │ │ │ │ │ ├── InlineFunctionAddFunctionStep1.xml │ │ │ │ │ ├── InlineFunctionDeleteFunction.xml │ │ │ │ │ ├── InlineFunctionEditFunction.xml │ │ │ │ │ ├── LocalizeData.xml │ │ │ │ │ ├── MethodBasedFunctionProviderElementProviderDeleteStep1.xml │ │ │ │ │ ├── PackageElementProviderAddPackageSourceStep1.xml │ │ │ │ │ ├── PackageElementProviderAddPackageSourceStep2.xml │ │ │ │ │ ├── PackageElementProviderConfirmLicense.xml │ │ │ │ │ ├── PackageElementProviderDeletePackageSourceStep1.xml │ │ │ │ │ ├── PackageElementProviderInstallLocalPackageShowError.xml │ │ │ │ │ ├── PackageElementProviderInstallLocalPackageStep1.xml │ │ │ │ │ ├── PackageElementProviderInstallLocalPackageStep2.xml │ │ │ │ │ ├── PackageElementProviderInstallLocalPackageStep3.xml │ │ │ │ │ ├── PackageElementProviderInstallRemotePackageShowError.xml │ │ │ │ │ ├── PackageElementProviderInstallRemotePackageStep1.xml │ │ │ │ │ ├── PackageElementProviderInstallRemotePackageStep2.xml │ │ │ │ │ ├── PackageElementProviderInstallRemotePackageStep3.xml │ │ │ │ │ ├── PackageElementProviderInstallRemotePackageStep4.xml │ │ │ │ │ ├── PackageElementProviderInstallRemotePackageStep5.xml │ │ │ │ │ ├── PackageElementProviderUninstallLocalPackageShowError.xml │ │ │ │ │ ├── PackageElementProviderUninstallLocalPackageStep1.xml │ │ │ │ │ ├── PackageElementProviderUninstallLocalPackageStep2.xml │ │ │ │ │ ├── PackageElementProviderUninstallLocalPackageStep3.xml │ │ │ │ │ ├── PackageElementProviderUninstallRemotePackageShowError.xml │ │ │ │ │ ├── PackageElementProviderUninstallRemotePackageShowUnregistreError.xml │ │ │ │ │ ├── PackageElementProviderUninstallRemotePackageStep1.xml │ │ │ │ │ ├── PackageElementProviderUninstallRemotePackageStep2.xml │ │ │ │ │ ├── PackageElementProviderUninstallRemotePackageStep3.xml │ │ │ │ │ ├── PackageElementProviderViewAvailablePackageInformation.xml │ │ │ │ │ ├── PackageElementProviderViewAvailablePackageInformationToolbar.xml │ │ │ │ │ ├── PackageElementProviderViewInstalledPackageInformation.xml │ │ │ │ │ ├── PackageElementProviderViewInstalledPackageInformationToolbar.xml │ │ │ │ │ ├── PageTemplate/ │ │ │ │ │ │ ├── AddNewMasterPagePageTemplate.xml │ │ │ │ │ │ ├── AddNewPageTemplate.xml │ │ │ │ │ │ ├── AddNewRazorPageTemplate.xml │ │ │ │ │ │ ├── AddNewXmlPageTemplate.xml │ │ │ │ │ │ ├── EditMasterPage.xml │ │ │ │ │ │ ├── EditRazorTemplate.xml │ │ │ │ │ │ └── EditXmlPageTemplate.xml │ │ │ │ │ ├── PageTemplateFeature/ │ │ │ │ │ │ ├── Add.xml │ │ │ │ │ │ ├── Delete.xml │ │ │ │ │ │ ├── EditMarkup.xml │ │ │ │ │ │ └── EditVisual.xml │ │ │ │ │ ├── PageTypeAddPageType.xml │ │ │ │ │ ├── PageTypeAddPageTypeDefaultPageContent.xml │ │ │ │ │ ├── PageTypeAddPageTypeMetaDataFieldStep1.xml │ │ │ │ │ ├── PageTypeDeletePageTypeConfirm.xml │ │ │ │ │ ├── PageTypeDeletePageTypeMetaDataFieldConfirm.xml │ │ │ │ │ ├── PageTypeDeletePageTypePagesRefering.xml │ │ │ │ │ ├── PageTypeEditPageType.xml │ │ │ │ │ ├── PageTypeEditPageTypeDefaultPageContent.xml │ │ │ │ │ ├── PageTypeEditPageTypeMetaDataField.xml │ │ │ │ │ ├── RemoveAssociatedTypeFinalInfo.xml │ │ │ │ │ ├── RemoveAssociatedTypeSelectAssociationType.xml │ │ │ │ │ ├── RemoveAssociatedTypeSelectRuleName.xml │ │ │ │ │ ├── RemoveAssociatedTypeSelectType.xml │ │ │ │ │ ├── RemovePageHostNameBindings.xml │ │ │ │ │ ├── RemoveSystemLocaleAbort.xml │ │ │ │ │ ├── RemoveSystemLocaleStep2.xml │ │ │ │ │ ├── ReportFunctionAction.xml │ │ │ │ │ ├── SecurityViolationStep1.xml │ │ │ │ │ ├── SendMessageToConsoles_EnterMessage.xml │ │ │ │ │ ├── SetTimeZone_select.xml │ │ │ │ │ ├── SqlFunctionElementProviderDeleteSqlConnection.xml │ │ │ │ │ ├── SqlFunctionElementProviderDeleteSqlFunction.xml │ │ │ │ │ ├── TreeAddApplication.xml │ │ │ │ │ ├── TreeAddTreeDefinition.xml │ │ │ │ │ ├── TreeConfirmActionConfirm.xml │ │ │ │ │ ├── TreeDeleteTreeDefinition.xml │ │ │ │ │ ├── TreeEditDefinition.xml │ │ │ │ │ ├── TreeGenericDeleteConfirm.xml │ │ │ │ │ ├── TreeGenericDeleteConfirmDeletingRelatedData.xml │ │ │ │ │ ├── TreeLocalizeData.xml │ │ │ │ │ ├── TreeRemoveApplication.xml │ │ │ │ │ ├── UploadMediaFile.xml │ │ │ │ │ ├── UploadNewMediaFile.xml │ │ │ │ │ ├── UrlConfiguration.xml │ │ │ │ │ ├── UserGroupElementProviderAddNewUserGroupStep1.xml │ │ │ │ │ ├── UserGroupElementProviderDeleteUserGroupStep1.xml │ │ │ │ │ ├── UserGroupElementProviderEditUserGroupStep1.xml │ │ │ │ │ ├── VisualFunctionElementProviderHelperAddNewStep1.xml │ │ │ │ │ ├── VisualFunctionElementProviderHelperDeleteStep1.xml │ │ │ │ │ ├── VisualFunctionElementProviderHelperEdit.xml │ │ │ │ │ ├── VisualFunctionElementProviderHelperSelect.xml │ │ │ │ │ ├── WebsiteFileElementProviderAddNewFile.xml │ │ │ │ │ ├── WebsiteFileElementProviderAddNewFolder.xml │ │ │ │ │ ├── WebsiteFileElementProviderDeleteFile.xml │ │ │ │ │ ├── WebsiteFileElementProviderDeleteFolder.xml │ │ │ │ │ ├── WebsiteFileElementProviderEditTextContentFile.xml │ │ │ │ │ ├── WebsiteFileElementProviderUploadAndExtractZipFile.xml │ │ │ │ │ ├── WebsiteFileElementProviderUploadNewWebsiteFile.xml │ │ │ │ │ └── WebsiteFileElementProviderUploadNewWebsiteFileConfirm.xml │ │ │ │ └── AdministrativeTemplates/ │ │ │ │ ├── ConfirmDialog.xml │ │ │ │ ├── DataDialog.xml │ │ │ │ ├── Document.xml │ │ │ │ ├── EmptyDocument.xml │ │ │ │ └── Wizard.xml │ │ │ ├── misc/ │ │ │ │ ├── editors/ │ │ │ │ │ ├── codemirroreditor/ │ │ │ │ │ │ ├── bindings/ │ │ │ │ │ │ │ ├── SourceEditorFindAndReplaceToolBarButtonBinding.js │ │ │ │ │ │ │ ├── SourceEditorFormatToolBarButtonBinding.js │ │ │ │ │ │ │ ├── SourceEditorInsertToolbarButtonBinding.js │ │ │ │ │ │ │ ├── SourceEditorPageBinding.js │ │ │ │ │ │ │ ├── SourceEditorToggleWordWrapToolbarButtonBinding.js │ │ │ │ │ │ │ └── SourceEditorToolBarBinding.js │ │ │ │ │ │ ├── codemirror.aspx │ │ │ │ │ │ ├── codemirror.css │ │ │ │ │ │ ├── codemirror.js │ │ │ │ │ │ ├── codemirroreditor.aspx │ │ │ │ │ │ ├── codemirroreditor.css │ │ │ │ │ │ ├── codemirrorfindandreplace.aspx │ │ │ │ │ │ ├── codemirrorfindandreplace.js │ │ │ │ │ │ └── theme/ │ │ │ │ │ │ └── composite.css │ │ │ │ │ ├── functioncalleditor/ │ │ │ │ │ │ ├── bindings/ │ │ │ │ │ │ │ ├── FieldsButtonDataBinding.js │ │ │ │ │ │ │ ├── FunctionEditorPageBinding.js │ │ │ │ │ │ │ └── ToolBarButtonDataBindingAddNew.js │ │ │ │ │ │ ├── functioncalleditor.aspx │ │ │ │ │ │ ├── functioncalleditor.aspx.cs │ │ │ │ │ │ ├── functioncalleditor.aspx.designer.cs │ │ │ │ │ │ ├── functioneditor-sample-function.xml │ │ │ │ │ │ ├── functioneditortree.xslt │ │ │ │ │ │ └── out.tmp.xml │ │ │ │ │ ├── resxeditor/ │ │ │ │ │ │ ├── Bindings/ │ │ │ │ │ │ │ └── RowContainerBinding.js │ │ │ │ │ │ ├── resxeditor.aspx │ │ │ │ │ │ ├── resxeditor.aspx.cs │ │ │ │ │ │ ├── resxeditor.aspx.designer.cs │ │ │ │ │ │ └── resxeditor.css │ │ │ │ │ └── visualeditor/ │ │ │ │ │ ├── bindings/ │ │ │ │ │ │ ├── BlockSelectorBinding.js │ │ │ │ │ │ ├── ClassNameSelectorBinding.js │ │ │ │ │ │ ├── FormatSelectorBinding.js │ │ │ │ │ │ ├── TemplateTreeBinding.js │ │ │ │ │ │ ├── VisualEditorBoxBinding.js │ │ │ │ │ │ ├── VisualEditorInsertPlusFieldsToolBarButtonBinding.js │ │ │ │ │ │ ├── VisualEditorInsertToolbarButtonBinding.js │ │ │ │ │ │ ├── VisualEditorPageBinding.js │ │ │ │ │ │ ├── VisualEditorPropertiesToolBarGroupBinding.js │ │ │ │ │ │ ├── VisualEditorSimpleToolBarBinding.js │ │ │ │ │ │ ├── VisualEditorStatusBarBinding.js │ │ │ │ │ │ └── VisualEditorToolBarBinding.js │ │ │ │ │ ├── ie.css │ │ │ │ │ ├── includes/ │ │ │ │ │ │ ├── toolbaradvanced.inc │ │ │ │ │ │ └── toolbarsimple.inc │ │ │ │ │ ├── scripts/ │ │ │ │ │ │ └── Format.js │ │ │ │ │ ├── tinymce/ │ │ │ │ │ │ └── plugins/ │ │ │ │ │ │ ├── compositecharmap/ │ │ │ │ │ │ │ ├── CharMapDialogPageBinding.js │ │ │ │ │ │ │ ├── charmap.aspx │ │ │ │ │ │ │ └── charmap.css │ │ │ │ │ │ ├── compositeimage/ │ │ │ │ │ │ │ ├── ImageDialogPageBinding.js │ │ │ │ │ │ │ ├── image.aspx │ │ │ │ │ │ │ └── image.css │ │ │ │ │ │ ├── compositelink/ │ │ │ │ │ │ │ ├── LinkDialogPageBinding.js │ │ │ │ │ │ │ └── link.aspx │ │ │ │ │ │ ├── compositeplugin/ │ │ │ │ │ │ │ └── TinyDialogPageBinding.js │ │ │ │ │ │ ├── compositesearchandreplace/ │ │ │ │ │ │ │ ├── VisualSearchAndReplace.js │ │ │ │ │ │ │ └── visualsearchandreplace.aspx │ │ │ │ │ │ ├── compositetable/ │ │ │ │ │ │ │ ├── TableCellDialogPageBinding.js │ │ │ │ │ │ │ ├── TableDialogPageBinding.js │ │ │ │ │ │ │ ├── TableMergeCellsDialogPageBinding.js │ │ │ │ │ │ │ ├── TableRowDialogPageBinding.js │ │ │ │ │ │ │ ├── cell.aspx │ │ │ │ │ │ │ ├── merge.aspx │ │ │ │ │ │ │ ├── row.aspx │ │ │ │ │ │ │ └── table.aspx │ │ │ │ │ │ └── compositetext/ │ │ │ │ │ │ ├── TextDialogPageBinding.js │ │ │ │ │ │ ├── text.aspx │ │ │ │ │ │ └── text.css │ │ │ │ │ ├── tinymce.aspx │ │ │ │ │ ├── visualeditor.aspx │ │ │ │ │ ├── visualeditor.css │ │ │ │ │ └── visualeditor.js │ │ │ │ ├── errors/ │ │ │ │ │ ├── ServerErrorDialogPageBinding.js │ │ │ │ │ ├── ServerErrorPageBinding.js │ │ │ │ │ ├── error.aspx │ │ │ │ │ ├── error.css │ │ │ │ │ ├── error_dialog.aspx │ │ │ │ │ ├── licenseviolation.aspx │ │ │ │ │ └── licenseviolation_dialog.aspx │ │ │ │ ├── gatekeeper/ │ │ │ │ │ ├── AllUsersAllowedFiles/ │ │ │ │ │ │ └── PreLoginPage.css │ │ │ │ │ └── PreLoginPageTemplate.ascx │ │ │ │ ├── preview/ │ │ │ │ │ ├── StopPageBinding.js │ │ │ │ │ ├── error.aspx │ │ │ │ │ ├── error.css │ │ │ │ │ ├── stop.aspx │ │ │ │ │ └── stop.css │ │ │ │ ├── stage/ │ │ │ │ │ ├── stagedeck.aspx │ │ │ │ │ └── stagedeck.css │ │ │ │ └── viewers/ │ │ │ │ └── sourcecodeviewer/ │ │ │ │ ├── viewsourcecontent.aspx │ │ │ │ ├── viewsourcecontent.css │ │ │ │ └── viewsourcecontent.js │ │ │ └── views/ │ │ │ ├── browser/ │ │ │ │ ├── BrowserAddressBarBinding.js │ │ │ │ ├── BrowserPageBinding.js │ │ │ │ ├── BrowserTabBoxBinding.js │ │ │ │ ├── BrowserToolBarBinding.js │ │ │ │ ├── LanguageSelectorBinding.js │ │ │ │ ├── browser.aspx │ │ │ │ ├── browser.css │ │ │ │ └── deviceoptions.xml │ │ │ ├── datatypedescriptor/ │ │ │ │ ├── ToXml.aspx │ │ │ │ ├── ToXml.aspx.cs │ │ │ │ └── ToXml.aspx.designer.cs │ │ │ ├── dev/ │ │ │ │ ├── developer/ │ │ │ │ │ ├── Developer.js │ │ │ │ │ ├── developer.aspx │ │ │ │ │ └── tests/ │ │ │ │ │ ├── fields/ │ │ │ │ │ │ ├── all/ │ │ │ │ │ │ │ ├── fields.aspx │ │ │ │ │ │ │ └── fieldsframe.aspx │ │ │ │ │ │ ├── checkboxes.aspx │ │ │ │ │ │ ├── datainputs.aspx │ │ │ │ │ │ ├── htmldatadialog.aspx │ │ │ │ │ │ ├── lazybindings.aspx │ │ │ │ │ │ ├── nonframework.aspx │ │ │ │ │ │ ├── nulltreeselector.aspx │ │ │ │ │ │ ├── postbackfun.aspx │ │ │ │ │ │ ├── radiogroups.aspx │ │ │ │ │ │ ├── relations.aspx │ │ │ │ │ │ ├── selectors.aspx │ │ │ │ │ │ ├── sourceeditors.aspx │ │ │ │ │ │ ├── sourcodeeditorbug/ │ │ │ │ │ │ │ ├── testA.html │ │ │ │ │ │ │ ├── testB.html │ │ │ │ │ │ │ └── testC.html │ │ │ │ │ │ ├── specialdatainputs.aspx │ │ │ │ │ │ ├── textboxes.aspx │ │ │ │ │ │ ├── visualeditors.aspx │ │ │ │ │ │ └── wyswiwygeditors.aspx │ │ │ │ │ └── ui/ │ │ │ │ │ ├── TreeTest.js │ │ │ │ │ ├── buttons.aspx │ │ │ │ │ ├── c1functions.aspx │ │ │ │ │ ├── c1functions.html │ │ │ │ │ ├── crawlers.aspx │ │ │ │ │ ├── crawlers.js │ │ │ │ │ ├── dmitryfun.aspx │ │ │ │ │ ├── dmitryfun.aspx.cs │ │ │ │ │ ├── domevents.aspx │ │ │ │ │ ├── focus.aspx │ │ │ │ │ ├── icons.aspx │ │ │ │ │ ├── iebug.aspx │ │ │ │ │ ├── memory.aspx │ │ │ │ │ ├── menus.aspx │ │ │ │ │ ├── pageeditorfull.aspx │ │ │ │ │ ├── persistance.aspx │ │ │ │ │ ├── sourcecodeviewers.aspx │ │ │ │ │ ├── special.aspx │ │ │ │ │ ├── special.css │ │ │ │ │ ├── splitboxes.aspx │ │ │ │ │ ├── style.aspx │ │ │ │ │ ├── style1.css │ │ │ │ │ ├── style2.css │ │ │ │ │ ├── tabboxes.aspx │ │ │ │ │ ├── trees.aspx │ │ │ │ │ ├── updatemanager/ │ │ │ │ │ │ ├── UpdateManagerTestPageBinding.js │ │ │ │ │ │ ├── tests/ │ │ │ │ │ │ │ ├── mothfun1.xml │ │ │ │ │ │ │ └── mothfun2.xml │ │ │ │ │ │ └── updatemanager.aspx │ │ │ │ │ └── xmleditor.jar │ │ │ │ ├── flushadmin/ │ │ │ │ │ ├── Default.aspx │ │ │ │ │ ├── Default.aspx.cs │ │ │ │ │ └── Default.aspx.designer.cs │ │ │ │ ├── icons/ │ │ │ │ │ └── svg/ │ │ │ │ │ ├── sprite.cshtml │ │ │ │ │ └── web.config │ │ │ │ ├── systemlog/ │ │ │ │ │ ├── SystemLogPageBinding.js │ │ │ │ │ ├── systemlog.aspx │ │ │ │ │ ├── systemlog.css │ │ │ │ │ ├── systemlogoutput.aspx │ │ │ │ │ └── systemlogoutput.css │ │ │ │ └── viewsource/ │ │ │ │ ├── ViewSourcePageBinding.js │ │ │ │ ├── blank.html │ │ │ │ ├── viewsource.aspx │ │ │ │ ├── viewsource.css │ │ │ │ ├── viewsourcecontent.css │ │ │ │ ├── viewsourcecontent.html │ │ │ │ └── viewsourcecontent.js │ │ │ ├── editors/ │ │ │ │ ├── imageeditor/ │ │ │ │ │ ├── ImageEditor.js │ │ │ │ │ ├── ImageEditorAction.js │ │ │ │ │ ├── ImageEditorActions.js │ │ │ │ │ ├── bindings/ │ │ │ │ │ │ ├── ImageBoxBinding.js │ │ │ │ │ │ ├── ImageCursorBinding.js │ │ │ │ │ │ ├── ImageEditorPageBinding.js │ │ │ │ │ │ ├── ImageScrollBoxBinding.js │ │ │ │ │ │ ├── ImageSelectionBinding.js │ │ │ │ │ │ ├── ImageStageBinding.js │ │ │ │ │ │ ├── ImageToolBoxBinding.js │ │ │ │ │ │ └── ImageToolBoxDraggerBinding.js │ │ │ │ │ ├── imageeditor.aspx │ │ │ │ │ └── imageeditor.css │ │ │ │ └── permissioneditor/ │ │ │ │ ├── PermissionEditorGridBinding.js │ │ │ │ ├── PermissionEditorHeadBinding.js │ │ │ │ ├── PermissionEditorPageBinding.js │ │ │ │ └── permissioneditor.aspx │ │ │ ├── functiondoc/ │ │ │ │ ├── FunctionDocumentation-print.css │ │ │ │ ├── FunctionDocumentation.aspx │ │ │ │ ├── FunctionDocumentation.aspx.cs │ │ │ │ ├── FunctionDocumentation.aspx.designer.cs │ │ │ │ └── FunctionDocumentation.css │ │ │ ├── functioninfo/ │ │ │ │ ├── ShowFunctionInfo.aspx │ │ │ │ ├── ShowFunctionInfo.aspx.cs │ │ │ │ ├── ShowFunctionInfo.aspx.designer.cs │ │ │ │ └── ShowFunctionInfo.css │ │ │ ├── generic/ │ │ │ │ ├── GenericPageBinding.js │ │ │ │ └── generic.aspx │ │ │ ├── help/ │ │ │ │ ├── HelpPageBinding.js │ │ │ │ └── help.aspx │ │ │ ├── log/ │ │ │ │ ├── log.aspx │ │ │ │ ├── log.aspx.cs │ │ │ │ ├── log.aspx.designer.cs │ │ │ │ └── log.css │ │ │ ├── publishworkflowstatus/ │ │ │ │ ├── ViewUnpublishedItems.aspx │ │ │ │ ├── ViewUnpublishedItems.aspx.cs │ │ │ │ ├── ViewUnpublishedItems.css │ │ │ │ ├── ViewUnpublishedItems.xslt │ │ │ │ └── bindings/ │ │ │ │ ├── SortButtonBinding.js │ │ │ │ └── UnpublishedPageBinding.js │ │ │ ├── relationshipgraph/ │ │ │ │ ├── Default.aspx │ │ │ │ ├── Default.aspx.cs │ │ │ │ ├── Default.aspx.designer.cs │ │ │ │ ├── ShowRelationshipOrientedGraph.aspx │ │ │ │ ├── ShowRelationshipOrientedGraph.aspx.cs │ │ │ │ └── ShowRelationshipOrientedGraph.aspx.designer.cs │ │ │ ├── search/ │ │ │ │ ├── SearchPageBinding.js │ │ │ │ ├── search.aspx │ │ │ │ └── search.css │ │ │ ├── seoassist/ │ │ │ │ ├── bindings/ │ │ │ │ │ └── SEOAssistantPageBinding.js │ │ │ │ ├── scripts/ │ │ │ │ │ ├── SEODOMParser.js │ │ │ │ │ └── SEOResult.js │ │ │ │ ├── seoassist.aspx │ │ │ │ └── seoassist.css │ │ │ ├── showelementinformation/ │ │ │ │ ├── Default.aspx │ │ │ │ ├── Default.aspx.cs │ │ │ │ └── Default.aspx.designer.cs │ │ │ ├── simplesearch/ │ │ │ │ └── SimpleSearch.cshtml │ │ │ ├── start/ │ │ │ │ ├── GetStartPage.ashx │ │ │ │ ├── StartPageBinding.js │ │ │ │ └── start.aspx │ │ │ └── systemview/ │ │ │ └── systemview.aspx │ │ ├── controls/ │ │ │ ├── AppInitializerControl.ascx │ │ │ ├── AppInitializerControl.ascx.cs │ │ │ ├── AppInitializerControl.ascx.designer.cs │ │ │ ├── BrandingSnippet.ascx │ │ │ ├── CodePressControl.ascx │ │ │ ├── CodePressControl.ascx.cs │ │ │ ├── CodePressControl.ascx.designer.cs │ │ │ ├── FieldGroupControl.ascx │ │ │ ├── FieldGroupControl.ascx.cs │ │ │ ├── FieldGroupControl.ascx.designer.cs │ │ │ ├── FormsControls/ │ │ │ │ ├── FormUiContainerTemplates/ │ │ │ │ │ ├── DataDialogExecutionContainer.ascx │ │ │ │ │ ├── DataDialogExecutionContainer.ascx.cs │ │ │ │ │ ├── DataDialogExecutionContainer.ascx.designer.cs │ │ │ │ │ ├── DocumentExecutionContainer.ascx │ │ │ │ │ ├── DocumentExecutionContainer.ascx.cs │ │ │ │ │ ├── DocumentExecutionContainer.ascx.designer.cs │ │ │ │ │ ├── EmptyDocumentExecutionContainer.ascx │ │ │ │ │ ├── EmptyDocumentExecutionContainer.ascx.cs │ │ │ │ │ ├── EmptyDocumentExecutionContainer.ascx.designer.cs │ │ │ │ │ ├── FormUIStandardDialogs/ │ │ │ │ │ │ ├── ConfirmDialogExecutionContainer.ascx │ │ │ │ │ │ ├── ConfirmDialogExecutionContainer.ascx.cs │ │ │ │ │ │ ├── ConfirmDialogExecutionContainer.ascx.designer.cs │ │ │ │ │ │ ├── WarningDialogExecutionContainer.ascx │ │ │ │ │ │ ├── WarningDialogExecutionContainer.ascx.cs │ │ │ │ │ │ └── WarningDialogExecutionContainer.ascx.designer.cs │ │ │ │ │ ├── WizardExecutionContainer.ascx │ │ │ │ │ ├── WizardExecutionContainer.ascx.cs │ │ │ │ │ └── WizardExecutionContainer.ascx.designer.cs │ │ │ │ ├── FormUiControlTemplates/ │ │ │ │ │ ├── BoolSelectors/ │ │ │ │ │ │ ├── BoolSelector.ascx │ │ │ │ │ │ └── CheckBox.ascx │ │ │ │ │ ├── Buttons/ │ │ │ │ │ │ ├── CancelButton.ascx │ │ │ │ │ │ ├── FinishButton.ascx │ │ │ │ │ │ ├── NextButton.ascx │ │ │ │ │ │ ├── OkButton.ascx │ │ │ │ │ │ ├── PreviewPanel.ascx │ │ │ │ │ │ ├── PreviousButton.ascx │ │ │ │ │ │ ├── SaveAsButton.ascx │ │ │ │ │ │ ├── SaveButton.ascx │ │ │ │ │ │ ├── ToolbarButton.ascx │ │ │ │ │ │ └── WizardCancelButton.ascx │ │ │ │ │ ├── Containers/ │ │ │ │ │ │ ├── ConfirmDialogCanvas.ascx │ │ │ │ │ │ ├── DialogCanvas.ascx │ │ │ │ │ │ ├── DialogToolbar.ascx │ │ │ │ │ │ ├── DocumentBody.ascx │ │ │ │ │ │ ├── FieldGroup.ascx │ │ │ │ │ │ ├── InfoBox.ascx │ │ │ │ │ │ ├── PlaceHolder.ascx │ │ │ │ │ │ ├── TabPanels.ascx │ │ │ │ │ │ └── Toolbar.ascx │ │ │ │ │ ├── Customized/ │ │ │ │ │ │ ├── PageContentEditor.ascx │ │ │ │ │ │ ├── PageContentEditor.ascx.cs │ │ │ │ │ │ └── PageContentEditor.ascx.designer.cs │ │ │ │ │ ├── DateTimeSelectors/ │ │ │ │ │ │ ├── DateSelector.ascx │ │ │ │ │ │ └── DateSelector.ascx.cs │ │ │ │ │ ├── DeveloperTools/ │ │ │ │ │ │ ├── FunctionCallsDesigner.Function.TreeBinding.js │ │ │ │ │ │ ├── FunctionCallsDesigner.UiTree.xsl │ │ │ │ │ │ ├── FunctionCallsDesigner.Widget.TreeBinding.js │ │ │ │ │ │ ├── FunctionCallsDesigner.ascx │ │ │ │ │ │ ├── FunctionCallsDesigner.ascx.cs │ │ │ │ │ │ ├── FunctionCallsDesigner.css │ │ │ │ │ │ ├── FunctionParameterDesigner.ascx │ │ │ │ │ │ ├── FunctionParameterDesigner.ascx.cs │ │ │ │ │ │ ├── FunctionParameterDesigner.ascx.designer.cs │ │ │ │ │ │ ├── FunctionParameterEditor.aspx │ │ │ │ │ │ ├── FunctionParameterEditor.aspx.cs │ │ │ │ │ │ ├── FunctionParameterEditor.aspx.designer.cs │ │ │ │ │ │ ├── FunctionParameterEditor.css │ │ │ │ │ │ ├── MarkupEditor.ascx │ │ │ │ │ │ ├── SqlEditor.ascx │ │ │ │ │ │ ├── TextEditor.ascx │ │ │ │ │ │ ├── TypeFieldDesigner.ascx │ │ │ │ │ │ ├── TypeFieldDesigner.ascx.cs │ │ │ │ │ │ ├── TypeFieldDesigner.ascx.designer.cs │ │ │ │ │ │ ├── TypeFieldDesigner.css │ │ │ │ │ │ └── XsltEditor.ascx │ │ │ │ │ ├── EnumSelectors/ │ │ │ │ │ │ └── EnumSelector.ascx │ │ │ │ │ ├── FileUploaders/ │ │ │ │ │ │ └── FileUpload.ascx │ │ │ │ │ ├── RichContent/ │ │ │ │ │ │ ├── InlineXhtmlEditor.ascx │ │ │ │ │ │ ├── MultiContentXhtmlEditor.ascx │ │ │ │ │ │ ├── MultiContentXhtmlEditor.ascx.cs │ │ │ │ │ │ ├── MultiContentXhtmlEditor.ascx.designer.cs │ │ │ │ │ │ └── XhtmlEditor.ascx │ │ │ │ │ ├── Selectors/ │ │ │ │ │ │ ├── ComboBox.ascx │ │ │ │ │ │ ├── DataReferenceSelector.ascx │ │ │ │ │ │ ├── DataReferenceTreeSelector.ascx │ │ │ │ │ │ ├── DoubleKeySelector.ascx │ │ │ │ │ │ ├── FontIconSelector.ascx │ │ │ │ │ │ ├── HierarchicalSelector.ascx │ │ │ │ │ │ ├── MultiKeySelector.ascx │ │ │ │ │ │ ├── PageSelector.ascx │ │ │ │ │ │ ├── Selector.ascx │ │ │ │ │ │ ├── SvgIconSelector.ascx │ │ │ │ │ │ ├── TreeSelector.ascx │ │ │ │ │ │ └── UrlComboBox.ascx │ │ │ │ │ ├── Text/ │ │ │ │ │ │ ├── Heading.ascx │ │ │ │ │ │ ├── HtmlBlob.ascx │ │ │ │ │ │ ├── InfoTable.ascx │ │ │ │ │ │ ├── InfoTable.css │ │ │ │ │ │ ├── LongText.ascx │ │ │ │ │ │ └── Text.ascx │ │ │ │ │ ├── TextInput/ │ │ │ │ │ │ ├── TextArea.ascx │ │ │ │ │ │ └── TextBox.ascx │ │ │ │ │ └── TypeSelectors/ │ │ │ │ │ └── TypeSelector.ascx │ │ │ │ └── Helpers/ │ │ │ │ ├── StyleFileLoaderControl.ascx │ │ │ │ ├── StyleFileLoaderControl.ascx.cs │ │ │ │ └── StyleFileLoaderControl.ascx.designer.cs │ │ │ ├── HttpHeadersControl.ascx │ │ │ ├── HttpHeadersControl.ascx.cs │ │ │ ├── HttpHeadersControl.ascx.designer.cs │ │ │ ├── Misc/ │ │ │ │ ├── MarkupInOutView.ascx │ │ │ │ ├── MarkupInOutView.ascx.cs │ │ │ │ ├── MarkupInOutView.ascx.designer.cs │ │ │ │ └── MarkupInOutView.css │ │ │ ├── Razor/ │ │ │ │ └── RazorLayout.cshtml │ │ │ ├── RegisterOutputTransformation.ascx │ │ │ ├── RegisterOutputTransformation.ascx.cs │ │ │ ├── RegisterOutputTransformation.ascx.designer.cs │ │ │ ├── ScriptLoaderControl.ascx │ │ │ ├── ScriptLoaderControl.ascx.cs │ │ │ ├── ScriptLoaderControl.ascx.designer.cs │ │ │ ├── StageDeckControl.ascx │ │ │ ├── StageDeckControl.ascx.cs │ │ │ ├── StageDeckControl.ascx.designer.cs │ │ │ ├── StyleLoaderControl.ascx │ │ │ ├── StyleLoaderControl.ascx.cs │ │ │ └── StyleLoaderControl.ascx.designer.cs │ │ ├── dead.aspx │ │ ├── default.aspx │ │ ├── default.js │ │ ├── develop.aspx │ │ ├── extensions/ │ │ │ ├── BACKUP/ │ │ │ │ └── compositec1/ │ │ │ │ ├── chrome/ │ │ │ │ │ └── content/ │ │ │ │ │ ├── CompositeC1.js │ │ │ │ │ ├── compositec1.css │ │ │ │ │ └── compositec1.xul │ │ │ │ ├── chrome.manifest │ │ │ │ ├── compositec1.txt │ │ │ │ ├── compositec1.xpi │ │ │ │ └── install.rdf │ │ │ └── compositec1/ │ │ │ ├── chrome/ │ │ │ │ └── content/ │ │ │ │ ├── CompositeC1.js │ │ │ │ ├── compositec1.css │ │ │ │ └── compositec1.xul │ │ │ ├── chrome.manifest │ │ │ ├── compositec1.xpi │ │ │ └── install.rdf │ │ ├── favicon.inc │ │ ├── grunt.html │ │ ├── grunt.inc │ │ ├── help/ │ │ │ ├── help.ashx │ │ │ ├── help.css │ │ │ ├── help.js │ │ │ └── help.xsl │ │ ├── images/ │ │ │ ├── loading.svg.ashx │ │ │ └── logo.xcf │ │ ├── localization/ │ │ │ ├── Composite.C1Console.SecurityViolation.en-us.xml │ │ │ ├── Composite.C1Console.Trees.en-us.xml │ │ │ ├── Composite.C1Console.Users.en-us.xml │ │ │ ├── Composite.Core.PackageSystem.PackageFragmentInstallers.en-us.xml │ │ │ ├── Composite.Cultures.en-us.xml │ │ │ ├── Composite.EntityTokenLocked.en-us.xml │ │ │ ├── Composite.GeneratedTypes.en-us.xml │ │ │ ├── Composite.Management.en-us.xml │ │ │ ├── Composite.NameValidation.en-us.xml │ │ │ ├── Composite.Permissions.en-us.xml │ │ │ ├── Composite.Plugins.AllFunctionsElementProvider.en-us.xml │ │ │ ├── Composite.Plugins.Components.en-us.xml │ │ │ ├── Composite.Plugins.GeneratedDataTypesElementProvider.en-us.xml │ │ │ ├── Composite.Plugins.GenericPublishProcessController.en-us.xml │ │ │ ├── Composite.Plugins.LocalizationElementProvider.en-us.xml │ │ │ ├── Composite.Plugins.MasterPagePageTemplate.en-us.xml │ │ │ ├── Composite.Plugins.MethodBasedFunctionProviderElementProvider.en-us.xml │ │ │ ├── Composite.Plugins.PackageElementProvider.en-us.xml │ │ │ ├── Composite.Plugins.PageElementProvider.en-us.xml │ │ │ ├── Composite.Plugins.PageTemplateElementProvider.en-us.xml │ │ │ ├── Composite.Plugins.PageTemplateFeatureElementProvider.en-us.xml │ │ │ ├── Composite.Plugins.PageTypeElementProvider.en-us.xml │ │ │ ├── Composite.Plugins.RazorFunction.en-us.xml │ │ │ ├── Composite.Plugins.RazorPageTemplate.en-us.xml │ │ │ ├── Composite.Plugins.SqlFunction.en-us.xml │ │ │ ├── Composite.Plugins.StandardFunctions.en-us.xml │ │ │ ├── Composite.Plugins.TimezoneAbbreviations.en-us.xml │ │ │ ├── Composite.Plugins.TimezoneDisplayNames.en-us.xml │ │ │ ├── Composite.Plugins.UserControlFunction.en-us.xml │ │ │ ├── Composite.Plugins.UserGroupElementProvider.en-us.xml │ │ │ ├── Composite.Plugins.VisualFunction.en-us.xml │ │ │ ├── Composite.Plugins.WebsiteFileElementProvider.en-us.xml │ │ │ ├── Composite.Plugins.XsltBasedFunction.en-us.xml │ │ │ ├── Composite.Search.en-us.xml │ │ │ ├── Composite.Web.FormControl.FunctionCallsDesigner.en-us.xml │ │ │ ├── Composite.Web.FormControl.FunctionParameterDesigner.en-us.xml │ │ │ ├── Composite.Web.FormControl.TypeFieldDesigner.en-us.xml │ │ │ ├── Composite.Web.PageBrowser.en-us.xml │ │ │ ├── Composite.Web.SEOAssistant.en-us.xml │ │ │ ├── Composite.Web.SourceEditor.en-us.xml │ │ │ ├── Composite.Web.VisualEditor.en-us.xml │ │ │ ├── MimeTypes.en-us.xml │ │ │ └── Orckestra.Tools.UrlConfiguration.en-us.xml │ │ ├── login.inc │ │ ├── ping.ashx │ │ ├── postback.aspx │ │ ├── postback.css │ │ ├── postback.js │ │ ├── schemas/ │ │ │ ├── FormsControls/ │ │ │ │ ├── AspNetManagement__www_composite_net_ns_management_bindingforms_internal_ui_controls_lib_1_0.xsd │ │ │ │ ├── AspNetManagement__www_composite_net_ns_management_bindingforms_std_ui_controls_lib_1_0.xsd │ │ │ │ ├── GenerateDynamicSchemas.aspx │ │ │ │ ├── GenerateDynamicSchemas.aspx.cs │ │ │ │ ├── GenerateDynamicSchemas.aspx.designer.cs │ │ │ │ ├── bindingforms10.xsd │ │ │ │ └── functions__www_composite_net_ns_management_bindingforms_std_function_lib_1_0.xsd │ │ │ ├── Functions/ │ │ │ │ └── Function.xsd │ │ │ ├── Trees/ │ │ │ │ └── Tree.xsd │ │ │ ├── default.aspx │ │ │ ├── default.aspx.cs │ │ │ └── default.aspx.designer.cs │ │ ├── scripts/ │ │ │ └── source/ │ │ │ ├── folder-info-readme.txt │ │ │ ├── page/ │ │ │ │ ├── data/ │ │ │ │ │ └── DataManager.js │ │ │ │ ├── document/ │ │ │ │ │ ├── DocumentCrawler.js │ │ │ │ │ ├── DocumentManager.js │ │ │ │ │ └── DocumentUpdatePlugin.js │ │ │ │ ├── updates/ │ │ │ │ │ ├── AttributesUpdate.js │ │ │ │ │ ├── ReplaceUpdate.js │ │ │ │ │ ├── SiblingUpdate.js │ │ │ │ │ ├── Update.js │ │ │ │ │ ├── UpdateAssistant.js │ │ │ │ │ ├── UpdateManager.js │ │ │ │ │ └── UpdatePlugin.js │ │ │ │ └── window/ │ │ │ │ ├── WindowAssistant.js │ │ │ │ └── WindowManager.js │ │ │ └── top/ │ │ │ ├── core/ │ │ │ │ ├── Application.js │ │ │ │ ├── BroadcastMessages.js │ │ │ │ ├── Client.js │ │ │ │ ├── Commands.js │ │ │ │ ├── Constants.js │ │ │ │ ├── ContextContainer.js │ │ │ │ ├── Cookies.js │ │ │ │ ├── Dialog.js │ │ │ │ ├── DialogButton.js │ │ │ │ ├── Download.js │ │ │ │ ├── EventBroadcaster.js │ │ │ │ ├── ImageProvider.js │ │ │ │ ├── Installation.js │ │ │ │ ├── Interfaces.js │ │ │ │ ├── KeyMaster.js │ │ │ │ ├── Keyboard.js │ │ │ │ ├── KickStart.js │ │ │ │ ├── License.DEPRECATED.js │ │ │ │ ├── LocalStore.js │ │ │ │ ├── Localization.js │ │ │ │ ├── MessageQueue.js │ │ │ │ ├── MimeTypes.js │ │ │ │ ├── Persistance.js │ │ │ │ ├── Preferences.js │ │ │ │ ├── Prism.js │ │ │ │ ├── Resolver.js │ │ │ │ ├── SearchTokens.js │ │ │ │ ├── Snippets.js │ │ │ │ ├── StandardEventHandler.js │ │ │ │ ├── StatusBar.js │ │ │ │ ├── StringBundle.js │ │ │ │ ├── Templates.js │ │ │ │ ├── Types.js │ │ │ │ ├── Uri.js │ │ │ │ ├── Validator.js │ │ │ │ └── ViewDefinitions.js │ │ │ ├── css/ │ │ │ │ ├── CSSComputer.js │ │ │ │ └── CSSUtil.js │ │ │ ├── dev/ │ │ │ │ ├── SystemDebug.js │ │ │ │ ├── SystemLogger.js │ │ │ │ ├── SystemPerformance.DEPRECATED.js │ │ │ │ └── SystemTimer.js │ │ │ ├── dom/ │ │ │ │ ├── DOMEvents.js │ │ │ │ ├── DOMFormatter.js │ │ │ │ ├── DOMSerializer.js │ │ │ │ ├── DOMUtil.js │ │ │ │ ├── XMLParser.js │ │ │ │ ├── XPathResolver.js │ │ │ │ └── XSLTransformer.js │ │ │ ├── interfaces/ │ │ │ │ ├── IAcceptable.js │ │ │ │ ├── IActionListener.js │ │ │ │ ├── IActivatable.js │ │ │ │ ├── IActivationAware.js │ │ │ │ ├── IBroadcastListener.js │ │ │ │ ├── IContextContainerBinding.js │ │ │ │ ├── ICrawlerHandler.js │ │ │ │ ├── IDOMHandler.js │ │ │ │ ├── IData.js │ │ │ │ ├── IDialogResponseHandler.js │ │ │ │ ├── IDragHandler.js │ │ │ │ ├── IDraggable.js │ │ │ │ ├── IEditorControlBinding.js │ │ │ │ ├── IEventListener.js │ │ │ │ ├── IFit.js │ │ │ │ ├── IFlexible.js │ │ │ │ ├── IFocusable.js │ │ │ │ ├── IImageProfile.js │ │ │ │ ├── IKeyEventHandler.js │ │ │ │ ├── ILabel.js │ │ │ │ ├── ILoadHandler.js │ │ │ │ ├── IMenuContainer.js │ │ │ │ ├── IResizeHandler.js │ │ │ │ ├── ISourceEditorComponent.js │ │ │ │ ├── IUpdateHandler.js │ │ │ │ ├── IWysiwygEditorComponent.js │ │ │ │ ├── IWysiwygEditorContentChangeHandler.js │ │ │ │ └── IWysiwygEditorNodeChangeHandler.js │ │ │ ├── namespaces/ │ │ │ │ └── Namespaces.js │ │ │ ├── proxies/ │ │ │ │ ├── ConfigurationService.js │ │ │ │ ├── ConsoleMessageQueueService.js │ │ │ │ ├── DiffService.js │ │ │ │ ├── EditorConfigurationService.js │ │ │ │ ├── FlowControllerService.js │ │ │ │ ├── FunctionService.js │ │ │ │ ├── InstallationService.js │ │ │ │ ├── LocalizationService.js │ │ │ │ ├── LoginService.js │ │ │ │ ├── MarkupFormatService.js │ │ │ │ ├── PageService.js │ │ │ │ ├── PageTemplateService.js │ │ │ │ ├── ReadyService.js │ │ │ │ ├── SEOService.js │ │ │ │ ├── SecurityService.js │ │ │ │ ├── SetupService.js │ │ │ │ ├── SourceValidationService.js │ │ │ │ ├── StringService.js │ │ │ │ ├── TreeService.js │ │ │ │ └── XhtmlTransformationsService.js │ │ │ ├── schema/ │ │ │ │ ├── Schema.js │ │ │ │ ├── SchemaComplexType.js │ │ │ │ ├── SchemaDefinition.js │ │ │ │ ├── SchemaElementType.js │ │ │ │ ├── SchemaSimpleType.js │ │ │ │ └── SchemaType.js │ │ │ ├── services/ │ │ │ │ ├── WebServiceOperation.js │ │ │ │ ├── WebServiceProxy.js │ │ │ │ └── WebServiceResolver.js │ │ │ ├── soap/ │ │ │ │ ├── SOAPDecoder.js │ │ │ │ ├── SOAPEncoder.js │ │ │ │ ├── SOAPFault.js │ │ │ │ ├── SOAPMessage.js │ │ │ │ ├── SOAPRequest.js │ │ │ │ └── SOAPRequestResponse.js │ │ │ ├── system/ │ │ │ │ ├── System.js │ │ │ │ ├── SystemAction.js │ │ │ │ └── SystemNode.js │ │ │ ├── ui/ │ │ │ │ ├── UserInterface.js │ │ │ │ ├── UserInterfaceMapping.js │ │ │ │ ├── bindings/ │ │ │ │ │ ├── Binding.js │ │ │ │ │ ├── balloons/ │ │ │ │ │ │ ├── BalloonBinding.js │ │ │ │ │ │ └── BalloonSetBinding.js │ │ │ │ │ ├── bindingmappings/ │ │ │ │ │ │ └── BindingMappingSetBinding.js │ │ │ │ │ ├── block/ │ │ │ │ │ │ └── BlockBinding.js │ │ │ │ │ ├── branding/ │ │ │ │ │ │ └── BrandSnippetBinding.js │ │ │ │ │ ├── broadcasters/ │ │ │ │ │ │ ├── BroadcasterBinding.js │ │ │ │ │ │ └── BroadcasterSetBinding.js │ │ │ │ │ ├── buttons/ │ │ │ │ │ │ ├── ButtonBinding.js │ │ │ │ │ │ ├── ButtonStateManager.js │ │ │ │ │ │ ├── checkbutton/ │ │ │ │ │ │ │ └── CheckButtonBinding.js │ │ │ │ │ │ ├── clickbutton/ │ │ │ │ │ │ │ └── ClickButtonBinding.js │ │ │ │ │ │ ├── combobutton/ │ │ │ │ │ │ │ ├── ComboBoxBinding.js │ │ │ │ │ │ │ ├── SelectorButtonBinding.js │ │ │ │ │ │ │ └── ToolBarComboButtonBinding.js │ │ │ │ │ │ ├── radiobutton/ │ │ │ │ │ │ │ ├── RadioButtonBinding.js │ │ │ │ │ │ │ └── RadioGroupBinding.js │ │ │ │ │ │ ├── toolboxbutton/ │ │ │ │ │ │ │ └── ToolBoxToolBarButtonBinding.js │ │ │ │ │ │ └── viewbutton/ │ │ │ │ │ │ ├── SlideInButtonBinding.js │ │ │ │ │ │ └── ViewButtonBinding.js │ │ │ │ │ ├── controls/ │ │ │ │ │ │ ├── ControlBinding.js │ │ │ │ │ │ ├── ControlBoxBinding.js │ │ │ │ │ │ └── ControlGroupBinding.js │ │ │ │ │ ├── cover/ │ │ │ │ │ │ ├── CoverBinding.js │ │ │ │ │ │ └── UncoverBinding.js │ │ │ │ │ ├── cursors/ │ │ │ │ │ │ └── CursorBinding.js │ │ │ │ │ ├── data/ │ │ │ │ │ │ ├── DataBinding.js │ │ │ │ │ │ ├── DataBindingMap.js │ │ │ │ │ │ ├── dialogs/ │ │ │ │ │ │ │ ├── DataDialogBinding.js │ │ │ │ │ │ │ ├── DataInputButtonBinding.js │ │ │ │ │ │ │ ├── DataInputDialogBinding.js │ │ │ │ │ │ │ ├── HTMLDataDialogBinding.js │ │ │ │ │ │ │ ├── MultiSelectorDataDialogBinding.js │ │ │ │ │ │ │ ├── NullPostBackDataDialogBinding.js │ │ │ │ │ │ │ ├── NullPostBackDataDialogSelectorBinding.js │ │ │ │ │ │ │ ├── PostBackDataDialogBinding.js │ │ │ │ │ │ │ ├── StringDataDialogBinding.js │ │ │ │ │ │ │ ├── TreeSelectorDialogBinding.js │ │ │ │ │ │ │ ├── UrlInputDialogBinding.js │ │ │ │ │ │ │ └── ViewDefinitionPostBackDataDialogBinding.js │ │ │ │ │ │ ├── editors/ │ │ │ │ │ │ │ ├── EditorDataBinding.js │ │ │ │ │ │ │ ├── FunctionEditorDataBinding.js │ │ │ │ │ │ │ └── ParameterEditorDataBinding.js │ │ │ │ │ │ ├── keyboard/ │ │ │ │ │ │ │ ├── DataInputBinding.js │ │ │ │ │ │ │ ├── EditorTextBoxBinding.js │ │ │ │ │ │ │ ├── IEEditorTextBoxBinding.js │ │ │ │ │ │ │ ├── MozEditorTextBoxBinding.js │ │ │ │ │ │ │ ├── TextBoxBinding.BACKUP.js │ │ │ │ │ │ │ └── TextBoxBinding.js │ │ │ │ │ │ ├── lazy/ │ │ │ │ │ │ │ ├── LazyBindingBinding.js │ │ │ │ │ │ │ └── LazyBindingSetBinding.js │ │ │ │ │ │ ├── misc/ │ │ │ │ │ │ │ └── FilePickerBinding.js │ │ │ │ │ │ ├── radiocheck/ │ │ │ │ │ │ │ ├── CheckBoxBinding.js │ │ │ │ │ │ │ ├── CheckBoxGroupBinding.js │ │ │ │ │ │ │ ├── CheckTreeBinding.js │ │ │ │ │ │ │ ├── CheckTreeNodeBinding.js │ │ │ │ │ │ │ ├── RadioDataBinding.js │ │ │ │ │ │ │ └── RadioDataGroupBinding.js │ │ │ │ │ │ └── selectors/ │ │ │ │ │ │ ├── DataInputSelectorBinding.js │ │ │ │ │ │ ├── HierarchicalSelectorBinding.js │ │ │ │ │ │ ├── MultiSelectorBinding.js │ │ │ │ │ │ ├── SelectorBinding.js │ │ │ │ │ │ ├── SelectorBindingSelection.js │ │ │ │ │ │ └── SimpleSelectorBinding.js │ │ │ │ │ ├── decks/ │ │ │ │ │ │ ├── DeckBinding.js │ │ │ │ │ │ └── DecksBinding.js │ │ │ │ │ ├── dialogs/ │ │ │ │ │ │ ├── DialogBinding.js │ │ │ │ │ │ ├── DialogBodyBinding.js │ │ │ │ │ │ ├── DialogBorderBinding.js │ │ │ │ │ │ ├── DialogControlBinding.js │ │ │ │ │ │ ├── DialogCoverBinding.js │ │ │ │ │ │ ├── DialogHeadBinding.js │ │ │ │ │ │ ├── DialogSetBinding.js │ │ │ │ │ │ ├── DialogTitleBarBinding.js │ │ │ │ │ │ ├── DialogTitleBarBodyBinding.js │ │ │ │ │ │ └── DialogTitleBarPopupBinding.js │ │ │ │ │ ├── docks/ │ │ │ │ │ │ ├── DockBinding.js │ │ │ │ │ │ ├── DockPanelBinding.js │ │ │ │ │ │ ├── DockPanelsBinding.js │ │ │ │ │ │ ├── DockTabBinding.js │ │ │ │ │ │ ├── DockTabPopupBinding.js │ │ │ │ │ │ ├── DockTabsBinding.js │ │ │ │ │ │ └── DockTabsButtonBinding.js │ │ │ │ │ ├── editors/ │ │ │ │ │ │ ├── EditorBinding.js │ │ │ │ │ │ ├── EditorClickButtonBinding.js │ │ │ │ │ │ ├── EditorMenuItemBinding.js │ │ │ │ │ │ ├── EditorPopupBinding.js │ │ │ │ │ │ ├── EditorSelectorBinding.js │ │ │ │ │ │ ├── EditorToolBarButtonBinding.js │ │ │ │ │ │ ├── codemirroreditor/ │ │ │ │ │ │ │ ├── CodeMirrorEditorBinding.js │ │ │ │ │ │ │ └── CodeMirrorEditorPopupBinding.js │ │ │ │ │ │ └── visualeditor/ │ │ │ │ │ │ ├── VisualEditorBinding.js │ │ │ │ │ │ ├── VisualEditorFieldGroupConfiguration.js │ │ │ │ │ │ ├── VisualEditorFormattingConfiguration.js │ │ │ │ │ │ ├── VisualEditorPopupBinding.js │ │ │ │ │ │ └── multieditor/ │ │ │ │ │ │ ├── VisualMultiEditorBinding.js │ │ │ │ │ │ └── VisualMultiTemplateEditorBinding.js │ │ │ │ │ ├── errors/ │ │ │ │ │ │ └── ErrorBinding.js │ │ │ │ │ ├── explorer/ │ │ │ │ │ │ ├── ExplorerBinding.js │ │ │ │ │ │ ├── ExplorerMenuBinding.js │ │ │ │ │ │ ├── ExplorerPopupBinding.js │ │ │ │ │ │ ├── ExplorerToolBarBinding.js │ │ │ │ │ │ └── ExplorerToolBarButtonBinding.js │ │ │ │ │ ├── fields/ │ │ │ │ │ │ ├── FieldBinding.js │ │ │ │ │ │ ├── FieldDataBinding.js │ │ │ │ │ │ ├── FieldDescBinding.js │ │ │ │ │ │ ├── FieldGroupBinding.js │ │ │ │ │ │ ├── FieldHelpBinding.js │ │ │ │ │ │ ├── FieldsBinding.js │ │ │ │ │ │ └── ResolverContainerBinding.js │ │ │ │ │ ├── flexboxes/ │ │ │ │ │ │ ├── FlexBoxBinding.js │ │ │ │ │ │ ├── FlexBoxCrawler.js │ │ │ │ │ │ └── ScrollBoxBinding.js │ │ │ │ │ ├── focus/ │ │ │ │ │ │ ├── FocusBinding.js │ │ │ │ │ │ └── FocusCrawler.js │ │ │ │ │ ├── genericview/ │ │ │ │ │ │ ├── AddressBarBinding.js │ │ │ │ │ │ ├── GenericViewBinding.js │ │ │ │ │ │ └── PathBinding.js │ │ │ │ │ ├── keys/ │ │ │ │ │ │ └── KeySetBinding.js │ │ │ │ │ ├── labels/ │ │ │ │ │ │ ├── LabelBinding.js │ │ │ │ │ │ └── TextBinding.js │ │ │ │ │ ├── localization/ │ │ │ │ │ │ └── LocalizationSelectorBinding.js │ │ │ │ │ ├── localstore/ │ │ │ │ │ │ ├── LocalStoreBinding.js │ │ │ │ │ │ └── LocalStoreWindowBinding.js │ │ │ │ │ ├── menus/ │ │ │ │ │ │ ├── MenuBarBinding.js │ │ │ │ │ │ ├── MenuBinding.js │ │ │ │ │ │ ├── MenuBodyBinding.js │ │ │ │ │ │ ├── MenuContainerBinding.js │ │ │ │ │ │ ├── MenuGroupBinding.js │ │ │ │ │ │ ├── MenuItemBinding.js │ │ │ │ │ │ └── MenuPopupBinding.js │ │ │ │ │ ├── pages/ │ │ │ │ │ │ ├── DialogPageBinding.js │ │ │ │ │ │ ├── DialogPageBodyBinding.js │ │ │ │ │ │ ├── EditorPageBinding.js │ │ │ │ │ │ ├── MarkupAwarePageBinding.js │ │ │ │ │ │ ├── PageBinding.js │ │ │ │ │ │ ├── ResponsePageBinding.js │ │ │ │ │ │ └── WizardPageBinding.js │ │ │ │ │ ├── persistance/ │ │ │ │ │ │ └── PersistanceBinding.js │ │ │ │ │ ├── popups/ │ │ │ │ │ │ ├── PopupBinding.js │ │ │ │ │ │ ├── PopupBodyBinding.js │ │ │ │ │ │ └── PopupSetBinding.js │ │ │ │ │ ├── progressbar/ │ │ │ │ │ │ └── ProgressBarBinding.js │ │ │ │ │ ├── request/ │ │ │ │ │ │ └── RequestBinding.js │ │ │ │ │ ├── response/ │ │ │ │ │ │ └── ResponseBinding.js │ │ │ │ │ ├── roots/ │ │ │ │ │ │ ├── RootBinding.js │ │ │ │ │ │ └── StyleBinding.js │ │ │ │ │ ├── splitboxes/ │ │ │ │ │ │ ├── SplitBoxBinding.js │ │ │ │ │ │ ├── SplitPanelBinding.js │ │ │ │ │ │ └── SplitterBinding.js │ │ │ │ │ ├── stage/ │ │ │ │ │ │ ├── StageBinding.js │ │ │ │ │ │ ├── StageContainerBinding.js │ │ │ │ │ │ ├── StageCrawler.js │ │ │ │ │ │ ├── abstractions/ │ │ │ │ │ │ │ ├── StageBoxAbstraction.js │ │ │ │ │ │ │ └── StageBoxHandlerAbstraction.js │ │ │ │ │ │ ├── decks/ │ │ │ │ │ │ │ ├── StageDeckBinding.js │ │ │ │ │ │ │ ├── StageDeckRootBinding.js │ │ │ │ │ │ │ └── StageDecksBinding.js │ │ │ │ │ │ ├── dialogs/ │ │ │ │ │ │ │ ├── FitnessCrawler.js │ │ │ │ │ │ │ ├── StageDialogBinding.js │ │ │ │ │ │ │ └── StageDialogSetBinding.js │ │ │ │ │ │ ├── menus/ │ │ │ │ │ │ │ ├── StageMenuBarBinding.js │ │ │ │ │ │ │ └── StageViewMenuItemBinding.js │ │ │ │ │ │ ├── splitboxes/ │ │ │ │ │ │ │ ├── StageSplitBoxBinding.js │ │ │ │ │ │ │ ├── StageSplitPanelBinding.js │ │ │ │ │ │ │ ├── StageSplitterBinding.js │ │ │ │ │ │ │ └── StageSplitterBodyBinding.js │ │ │ │ │ │ └── statusbar/ │ │ │ │ │ │ └── StageStatusBarBinding.js │ │ │ │ │ ├── start/ │ │ │ │ │ │ └── StartMenuItemBinding.js │ │ │ │ │ ├── system/ │ │ │ │ │ │ ├── SystemPageBinding.js │ │ │ │ │ │ ├── SystemToolBarBinding.js │ │ │ │ │ │ ├── SystemTreeBinding.js │ │ │ │ │ │ ├── SystemTreeNodeBinding.js │ │ │ │ │ │ └── SystemTreePopupBinding.js │ │ │ │ │ ├── tabboxes/ │ │ │ │ │ │ ├── TabBinding.js │ │ │ │ │ │ ├── TabBoxBinding.js │ │ │ │ │ │ ├── TabPanelBinding.js │ │ │ │ │ │ ├── TabPanelsBinding.js │ │ │ │ │ │ ├── TabsBinding.js │ │ │ │ │ │ └── TabsButtonBinding.js │ │ │ │ │ ├── theatre/ │ │ │ │ │ │ └── TheatreBinding.js │ │ │ │ │ ├── toolbars/ │ │ │ │ │ │ ├── DialogToolBarBinding.js │ │ │ │ │ │ ├── ToolBarBinding.js │ │ │ │ │ │ ├── ToolBarBodyBinding.js │ │ │ │ │ │ ├── ToolBarButtonBinding.js │ │ │ │ │ │ ├── ToolBarGroupBinding.js │ │ │ │ │ │ └── ToolBarLabelBinding.js │ │ │ │ │ ├── trees/ │ │ │ │ │ │ ├── TreeBinding.js │ │ │ │ │ │ ├── TreeBodyBinding.js │ │ │ │ │ │ ├── TreeContentBinding.js │ │ │ │ │ │ ├── TreeCrawler.js │ │ │ │ │ │ ├── TreeNodeBinding.js │ │ │ │ │ │ └── TreePositionIndicatorBinding.js │ │ │ │ │ ├── viewers/ │ │ │ │ │ │ └── SourceCodeViewerBinding.js │ │ │ │ │ ├── views/ │ │ │ │ │ │ ├── SlideInViewBinding.js │ │ │ │ │ │ ├── ViewBinding.js │ │ │ │ │ │ └── ViewSetBinding.js │ │ │ │ │ └── windows/ │ │ │ │ │ ├── PreviewWindowBinding.js │ │ │ │ │ ├── WindowBinding.js │ │ │ │ │ └── WindowBindingHighlightNodeCrawler.js │ │ │ │ ├── utilities/ │ │ │ │ │ ├── Action.js │ │ │ │ │ ├── Animation.js │ │ │ │ │ ├── BindingAcceptor.BACKUP.js │ │ │ │ │ ├── BindingAcceptor.js │ │ │ │ │ ├── BindingBoxObject.js │ │ │ │ │ ├── BindingDragger.js │ │ │ │ │ ├── BindingFinder.js │ │ │ │ │ ├── BindingParser.js │ │ │ │ │ ├── BindingSerializer.js │ │ │ │ │ ├── Dimension.js │ │ │ │ │ ├── Geometry.js │ │ │ │ │ ├── ImageProfile.js │ │ │ │ │ ├── Point.js │ │ │ │ │ └── crawlers/ │ │ │ │ │ ├── BindingCrawler.js │ │ │ │ │ ├── Crawler.js │ │ │ │ │ ├── ElementCrawler.js │ │ │ │ │ └── NodeCrawler.js │ │ │ │ └── viewdefinitions/ │ │ │ │ ├── DialogViewDefinition.js │ │ │ │ ├── HostedViewDefinition.js │ │ │ │ ├── SystemViewDefinition.js │ │ │ │ └── ViewDefinition.js │ │ │ └── util/ │ │ │ ├── List.js │ │ │ ├── LocalStorage.js │ │ │ ├── Map.js │ │ │ └── SystemNodeList.js │ │ ├── services/ │ │ │ ├── Admin/ │ │ │ │ ├── DownloadFile.ashx │ │ │ │ └── HighlightJs/ │ │ │ │ ├── LICENSE │ │ │ │ ├── highlight.pack.js │ │ │ │ ├── readme.txt │ │ │ │ └── vs.css │ │ │ ├── Configuration/ │ │ │ │ └── ConfigurationService.asmx │ │ │ ├── ConsoleMessageQueue/ │ │ │ │ └── ConsoleMessageQueueServices.asmx │ │ │ ├── FlowController/ │ │ │ │ └── FlowControllerServices.asmx │ │ │ ├── Installation/ │ │ │ │ └── InstallationService.asmx │ │ │ ├── Localization/ │ │ │ │ └── LocalizationService.asmx │ │ │ ├── LogService/ │ │ │ │ └── LogService.svc │ │ │ ├── Login/ │ │ │ │ └── Login.asmx │ │ │ ├── Media/ │ │ │ │ ├── ImageManipulator.ashx │ │ │ │ └── Upload.ashx │ │ │ ├── Page/ │ │ │ │ └── PageService.asmx │ │ │ ├── Ready/ │ │ │ │ └── ReadyService.asmx │ │ │ ├── SearchEngineOptimizationKeyword/ │ │ │ │ └── SearchEngineOptimizationKeyword.asmx │ │ │ ├── Setup/ │ │ │ │ ├── SetupService.asmx │ │ │ │ └── web.config │ │ │ ├── SourceEditor/ │ │ │ │ ├── MarkupFormatService.asmx │ │ │ │ └── SourceValidationService.asmx │ │ │ ├── StringResource/ │ │ │ │ ├── DiffService.asmx │ │ │ │ └── StringService.asmx │ │ │ ├── Tree/ │ │ │ │ ├── SecurityServices.asmx │ │ │ │ └── TreeServices.asmx │ │ │ └── WysiwygEditor/ │ │ │ ├── ConfigurationServices.asmx │ │ │ ├── ControlConfiguration.xsl │ │ │ ├── FieldImage.ashx │ │ │ ├── FunctionService.asmx │ │ │ ├── PageTemplate.asmx │ │ │ ├── XhtmlTransformations.asmx │ │ │ └── getconfig.ashx │ │ ├── styles/ │ │ │ └── default/ │ │ │ ├── _helpers.less │ │ │ ├── _mixins.less │ │ │ ├── _normalize.less │ │ │ ├── _variables.less │ │ │ ├── balloons.less │ │ │ ├── base.less │ │ │ ├── bindingmappings.less │ │ │ ├── branding.less │ │ │ ├── broadcasters.less │ │ │ ├── buttons.less │ │ │ ├── controls.less │ │ │ ├── cursors.less │ │ │ ├── decks.less │ │ │ ├── dialogs/ │ │ │ │ ├── dialog-multiselector.less │ │ │ │ ├── dialogs.less │ │ │ │ └── dialogvignette.less │ │ │ ├── docks.less │ │ │ ├── editors.less │ │ │ ├── errors.less │ │ │ ├── explorer.less │ │ │ ├── fields/ │ │ │ │ ├── calendar.less │ │ │ │ ├── checkbox.less │ │ │ │ ├── datadialog.less │ │ │ │ ├── fields-base.less │ │ │ │ ├── filepicker.less │ │ │ │ ├── radio.less │ │ │ │ ├── selectors.less │ │ │ │ ├── textbox.less │ │ │ │ └── urlinputdialog.less │ │ │ ├── forms.less │ │ │ ├── icons.less │ │ │ ├── keys.less │ │ │ ├── labels.less │ │ │ ├── lazybindings.less │ │ │ ├── menubar.less │ │ │ ├── menus.less │ │ │ ├── oldUI-fixes.less │ │ │ ├── pages.less │ │ │ ├── popups.less │ │ │ ├── rtl.less │ │ │ ├── sourcecodeviewers.less │ │ │ ├── splash.less │ │ │ ├── splitboxes.less │ │ │ ├── tabboxes.less │ │ │ ├── tables.less │ │ │ ├── texts.less │ │ │ ├── titlebars.less │ │ │ ├── toolbars/ │ │ │ │ ├── codemirror-editor.less │ │ │ │ ├── dialog.less │ │ │ │ ├── document-toolbar.less │ │ │ │ ├── nav-toolbar.less │ │ │ │ ├── pagetemplates.less │ │ │ │ ├── statusbar.less │ │ │ │ ├── system.less │ │ │ │ ├── toolbars-base.less │ │ │ │ └── visual-editor.less │ │ │ ├── trees/ │ │ │ │ ├── genericview-tree.less │ │ │ │ └── trees-base.less │ │ │ ├── updatepanels.less │ │ │ └── views.less │ │ ├── templates/ │ │ │ ├── PageTemplates/ │ │ │ │ ├── MasterPage.cs.txt │ │ │ │ ├── MasterPage.txt │ │ │ │ ├── RazorPageTemplate.txt │ │ │ │ └── XmlPageTemplate.xml │ │ │ ├── defaultstagedeck.xml │ │ │ ├── grayscalefilter.xml │ │ │ ├── matrixbindingelement.xml │ │ │ ├── soapenvelope.xml │ │ │ ├── sourcecodeeditor/ │ │ │ │ ├── cs.txt │ │ │ │ ├── css.txt │ │ │ │ ├── html.txt │ │ │ │ ├── js.txt │ │ │ │ ├── sql.txt │ │ │ │ ├── xml.txt │ │ │ │ └── xsl.txt │ │ │ ├── sourceeditor/ │ │ │ │ └── popup.xml │ │ │ ├── storagetemplates/ │ │ │ │ └── persistance.xml │ │ │ ├── updatemanagertest/ │ │ │ │ ├── advanced.txt │ │ │ │ ├── basic.txt │ │ │ │ └── forms.txt │ │ │ ├── wysiwygeditor/ │ │ │ │ └── popup.xml │ │ │ └── wysiwygeditorplugins/ │ │ │ ├── mediaflashoptions.xml │ │ │ ├── mediaquicktimeoptions.xml │ │ │ ├── mediashockwaveoptions.xml │ │ │ └── mediawinmediaoptions.xml │ │ ├── top.aspx │ │ ├── top.aspx.cs │ │ ├── top.aspx.designer.cs │ │ ├── top.css │ │ ├── transformations/ │ │ │ ├── WysiwygEditor_StructuredContentToTinyContent.xsl │ │ │ ├── WysiwygEditor_TinyContentToStructuredContent.xsl │ │ │ ├── defaultfilters/ │ │ │ │ ├── finalizefilter.xsl │ │ │ │ ├── masterfilter.xsl │ │ │ │ └── structurefilter.xsl │ │ │ ├── page_profiler.xslt │ │ │ └── viewsource-xml.xsl │ │ ├── unknownbrowser.aspx │ │ ├── unsecure.aspx │ │ ├── unsecure.css │ │ ├── unsecure.js │ │ ├── unsupported.aspx │ │ ├── updated.aspx │ │ ├── updated.js │ │ ├── web.config │ │ ├── webauthorization.config │ │ ├── welcome.css │ │ ├── welcome.inc │ │ └── welcome.xsl │ ├── DebugBuild.Web.config │ ├── Global.asax │ ├── ReleaseBuild.Global.asax │ ├── ReleaseBuild.Web.config │ ├── ReleaseCleanupConfiguration.xml │ ├── Renderers/ │ │ ├── Captcha.ashx │ │ ├── FileNotFoundHandler.ashx │ │ ├── FunctionPreview.ashx │ │ ├── Page.aspx │ │ ├── Page.aspx.cs │ │ ├── ShowMedia.ashx │ │ └── TemplatePreview.ashx │ ├── WebSite.csproj │ ├── WebSite.csproj.user │ ├── WebSite.csproj.vspscc │ ├── bower.json │ ├── default.aspx │ ├── gruntfile.js │ ├── jspm.config.js │ ├── package.json │ ├── packages.config │ ├── robots.txt │ └── test/ │ ├── e2e/ │ │ ├── .editorconfig │ │ ├── ApiLang/ │ │ │ └── Notepad++/ │ │ │ ├── Nightwatch.UDL.xml │ │ │ ├── installation.txt │ │ │ └── nightwatch.xml │ │ ├── README.md │ │ ├── commands/ │ │ │ ├── assertBrowserContains.js │ │ │ ├── assertBrowserContainsAttribute.js │ │ │ ├── assertBrowserContainsWithXpath.js │ │ │ ├── assertFieldValue.js │ │ │ ├── assertTreeNodeHasChild.js │ │ │ ├── assertTreeNodeHasNoChild.js │ │ │ ├── assertTreeNodeIsEmpty.js │ │ │ ├── assertTreeNodeIsNotEmpty.js │ │ │ ├── clickDataBySibilings.js │ │ │ ├── clickDialogButton.js │ │ │ ├── clickInFrame.js │ │ │ ├── clickLabel.js │ │ │ ├── clickSave.js │ │ │ ├── clickText.js │ │ │ ├── closeDocumentTab.js │ │ │ ├── doubleClickSelector.js │ │ │ ├── enterFrame.js │ │ │ ├── installCommercialPackage.js │ │ │ ├── installLocalPackage.js │ │ │ ├── installLocale.js │ │ │ ├── installPackage.js │ │ │ ├── installWebsite.js │ │ │ ├── leaveFrame.js │ │ │ ├── logOut.js │ │ │ ├── openTreeNode.js │ │ │ ├── replaceContent.js │ │ │ ├── replaceTextInCodeMirror.js │ │ │ ├── rightClickSelector.js │ │ │ ├── selectActionFromToolbar.js │ │ │ ├── selectContentTab.js │ │ │ ├── selectDocumentTab.js │ │ │ ├── selectFrame.js │ │ │ ├── selectFrameWithXpath.js │ │ │ ├── selectPerspective.js │ │ │ ├── selectTreeNodeAction.js │ │ │ ├── setFieldValue.js │ │ │ ├── setFieldValueInFieldGroup.js │ │ │ ├── setFileFieldValue.js │ │ │ ├── submitFormData.js │ │ │ ├── switchContentTab.js │ │ │ ├── topFrame.js │ │ │ ├── uninstallLocalPackage.js │ │ │ ├── uninstallLocale.js │ │ │ ├── uninstallPackage.js │ │ │ ├── waitForDialog.js │ │ │ ├── waitForDialogClosed.js │ │ │ ├── waitForFrameLoad.js │ │ │ └── waitForFrameLoadwithXpath.js │ │ ├── globals.js │ │ ├── pageObjects/ │ │ │ ├── appWindow.js │ │ │ ├── content.js │ │ │ ├── editor.js │ │ │ ├── login.js │ │ │ ├── startScreen.js │ │ │ └── systemView.js │ │ ├── reset.js │ │ └── suite/ │ │ ├── 000_setup/ │ │ │ └── installSite.js │ │ ├── 010_setupPackages/ │ │ │ ├── installSQLPackage.js │ │ │ └── installVerboseLoggingPackage.js │ │ ├── 100_login/ │ │ │ ├── normalMode.js │ │ │ └── procedure.js │ │ ├── 200_startScreen/ │ │ │ ├── display.js │ │ │ └── logged-in.js │ │ ├── 300_appWindow/ │ │ │ ├── has-elements.js │ │ │ └── stages.js │ │ ├── components/ │ │ │ ├── componentsFunctionSetParam.js │ │ │ ├── componentsXhtml.js │ │ │ ├── function-set-params.xml │ │ │ └── xhtml-Simple.xml │ │ ├── content/ │ │ │ ├── browseTree.js │ │ │ ├── multiEditor.js │ │ │ └── singleEditor.js │ │ ├── data/ │ │ │ └── CreateGlobalDataTypes.js │ │ ├── duplicate/ │ │ │ ├── Duplicate.js │ │ │ ├── DuplicatePagesWithAction.js │ │ │ ├── DuplicatePagesWithData.js │ │ │ ├── DuplicatePagesWithMetaData.js │ │ │ ├── DuplicatePagesWithMetaDataOnType.js │ │ │ └── DuplicateTreeAction.js │ │ ├── locales/ │ │ │ └── InstallUninstallWebsiteLanguage.js │ │ ├── packages/ │ │ │ ├── InstallUninstallExtranet.js │ │ │ ├── InstallUninstallLocalPackage.js │ │ │ ├── InstallUninstallPackageCreator.js │ │ │ └── UninstallInstallYouTube.js │ │ ├── website-zip-upload-extract/ │ │ │ └── UploadAndExtractZip.js │ │ └── zzz_starterSites/ │ │ ├── InstallSiteWithOtherLanguage.js │ │ └── InstallStarterSites.js │ └── unit/ │ ├── coverage.js │ ├── helpers/ │ │ ├── StatelessWrapper.js │ │ ├── TestComponent.js │ │ ├── emulateDom.js │ │ ├── expect.js │ │ ├── moduleLoader.js │ │ ├── ui.js │ │ └── unexpected-immutable.js │ ├── runner.js │ ├── suite/ │ │ ├── access/ │ │ │ └── requestJSON.spec.js │ │ ├── state/ │ │ │ ├── _setup.js │ │ │ ├── actions/ │ │ │ │ ├── fetchFromProvider.spec.js │ │ │ │ ├── fireAction.spec.js │ │ │ │ ├── loadAndOpen.spec.js │ │ │ │ ├── logs.spec.js │ │ │ │ ├── pageDefs.spec.js │ │ │ │ └── values.spec.js │ │ │ ├── initState.spec.js │ │ │ ├── observers.spec.js │ │ │ ├── reducers/ │ │ │ │ ├── activity.spec.js │ │ │ │ ├── dataFields.spec.js │ │ │ │ ├── definitions.spec.js │ │ │ │ ├── dialog.spec.js │ │ │ │ ├── layout.spec.js │ │ │ │ ├── logs.spec.js │ │ │ │ ├── options.spec.js │ │ │ │ └── providers.spec.js │ │ │ └── store.spec.js │ │ └── view/ │ │ ├── _setup.js │ │ ├── container/ │ │ │ ├── ConnectDialog.spec.js │ │ │ ├── ConnectDockPanel.spec.js │ │ │ ├── ConnectFormPanel.spec.js │ │ │ ├── ConnectLogPanel.spec.js │ │ │ ├── ConnectSearchPage.spec.js │ │ │ ├── ConnectTabPanel.spec.js │ │ │ └── ConnectToolbarFrame.spec.js │ │ └── presentation/ │ │ ├── ActionButton.spec.js │ │ ├── CheckboxGroup.spec.js │ │ ├── DataField.spec.js │ │ ├── Dialog.spec.js │ │ ├── Fieldset.spec.js │ │ ├── FormTab.spec.js │ │ ├── HelpIcon.spec.js │ │ ├── Icon.spec.js │ │ ├── LogPanel.spec.js │ │ ├── Palette.spec.js │ │ ├── SearchFacets.spec.js │ │ ├── SearchPage.spec.js │ │ ├── SearchResults.spec.js │ │ ├── SwitchPanel.spec.js │ │ ├── TabBar.spec.js │ │ ├── Toolbar.spec.js │ │ └── ToolbarFrame.spec.js │ └── suite.js ├── license.txt └── nightwatch.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .build/ReleaseCleanup.ps1 ================================================ param ( [string]$cleanupTargetName, [string]$cleanupDirectory ) Write-Host "ReleaseCleanup script started..." # This script deletes/rename files according to rules in ReleaseCleanupConfiguration.xml - it is used by automated builds if(-not($cleanupTargetName)) { Throw "You must supply a value for -cleanupTargetName - matching a target name in ReleaseCleanupConfiguration.xml" } if(-not($cleanupDirectory)) { Throw "You must supply a value for -cleanupDirectory - this is the path where cleaning will be taking place" } $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition [xml]$xml = Get-Content (Join-Path $scriptPath "ReleaseCleanupConfiguration.xml") $targetItems = $xml.SelectNodes("/Configuration/Target[@name='" + $cleanupTargetName + "']/*/*[@path]") Foreach ($fileNode in $targetItems) { $relPath = $fileNode.Attributes["path"].Value $fullPath = Join-Path $cleanupDirectory $relPath if (($fileNode.Attributes["rename-find"]) -and ($fileNode.Attributes["rename-replace"]) ) { # if rename Write-Host "Handling $fullPath for renaming" $findString = $fileNode.Attributes["rename-find"].Value.Replace("\","/") $replaceString = $fileNode.Attributes["rename-replace"].Value $matches = Get-ChildItem -Path $fullPath -Recurse if ($matches.length -eq 0) { Write-Warning "Pattern matched 0 files - probably you should remove it from ReleaseCleanupConfiguration.xml in repo" } Foreach ($match in $matches) { $name = $match.FullName.Replace("\","/") $newName = $name.Replace($findString.Replace("\","/"), $replaceString) #ensure dir $newDirPath = Split-Path -Path $newName if (-not (Test-Path($newDirPath))) { New-Item -ItemType Directory -Force -Path $newDirPath } Move-Item $match -Destination $newName -Force } } else { # assume delete otherwise Write-Host "Handling $fullPath for deletion" if (($fileNode.Name -eq "Directory") -and (Test-Path $fullPath)) { Remove-Item -LiteralPath $fullPath -Force -Recurse } else { $matches = Get-ChildItem -Path $fullPath -Recurse if ($matches.length -eq 0) { Write-Warning "Pattern matched 0 files - probably you should remove it from ReleaseCleanupConfiguration.xml in repo" } $matches | Where-Object { Test-Path($_) } | Remove-Item -Force -Recurse } } } ================================================ FILE: .build/ReleaseCleanupConfiguration.xml ================================================ ================================================ FILE: .editorconfig ================================================ # EditorConfig is awesome: http://EditorConfig.org root = true [*] indent_style = tab charset = utf-8 trim_trailing_whitespace = true [*.{cs,asmx,ashx,asax}] indent_style = space indent_size = 4 [*.md] trim_trailing_whitespace = false ================================================ FILE: .github/workflows/main.yml ================================================ # This is a basic workflow to help you get started with Actions name: CI # Controls when the action will run. on: issues: types: [opened] # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: # This workflow contains a single job called "build" build: # The type of runner that the job will run on runs-on: ubuntu-latest # Steps represent a sequence of tasks that will be executed as part of the job steps: - uses: danhellem/github-actions-issue-to-work-item@master env: ado_token: "2fkdmowxykpxbjdesotpjddpvzodif5rd5vdsfrpxxsgrhuwmyiq" github_token: "df9367d03c44f7cbae7cf24cbc20766fc165d4df" ado_organization: "orckestra001" ado_project: "OrckestraCommerce" ado_area_path: "OrckestraCommerce" ado_iteration_path: "OrckestraCommerce" ado_wit: "Issue" ado_new_state: "New" ado_active_state: "Active" ado_close_state: "Closed" ado_bypassrules: true ================================================ FILE: .gitignore ================================================ /.vs /Composite/bin /Composite/obj /Composite.Workflows/bin /Composite.Workflows/obj /Website/App_Data /Website/App_GlobalResources /Website/bower_components /Website/bin /Website/obj /Website/Composite/InstalledPackages /Website/Composite/scripts/compressed /Website/Composite/styles/styles.* /Website/Composite/content/forms/InstalledPackages /Website/Composite/lib /Website/Composite/console.js /Website/Composite/console.js.map /Website/Frontend /Website/node_modules /Website/jspm_packages /Website/coverage /Website/Composite/images/sprite.svg /Website/Composite/console/icons.svg /Website/Views /Website/Web.config /Website/test/e2e/screenshots/ /Website/Blog*.ashx /Website/Newsletter.ashx /Bin/Composite.dll /Bin/Composite.Workflows.dll /Packages/ selenium-debug.log /Website/test/e2e/reports/ GitCommitInfo.cs /Website/Composite/content/misc/editors/visualeditor/tinymce/plugins/autolink/plugin.min.js /Website/Composite/content/misc/editors/visualeditor/tinymce/plugins/lists/plugin.min.js /Website/Composite/content/misc/editors/visualeditor/tinymce/plugins/paste/plugin.min.js /Website/Composite/content/misc/editors/visualeditor/tinymce/plugins/table/plugin.min.js /Website/Composite/content/misc/editors/visualeditor/tinymce/skins/lightgray/fonts/tinymce.woff /Website/Composite/content/misc/editors/visualeditor/tinymce/skins/lightgray/fonts/tinymce.ttf /Website/Composite/content/misc/editors/visualeditor/tinymce/skins/lightgray/fonts/tinymce.svg /Website/Composite/content/misc/editors/visualeditor/tinymce/skins/lightgray/fonts/tinymce.eot /Website/Composite/content/misc/editors/visualeditor/tinymce/skins/lightgray/fonts/tinymce-small.woff /Website/Composite/content/misc/editors/visualeditor/tinymce/skins/lightgray/fonts/tinymce-small.ttf /Website/Composite/content/misc/editors/visualeditor/tinymce/skins/lightgray/fonts/tinymce-small.svg /Website/Composite/content/misc/editors/visualeditor/tinymce/skins/lightgray/fonts/tinymce-small.eot /Website/Composite/content/misc/editors/visualeditor/tinymce/tinymce.min.js /Website/Composite/content/misc/editors/visualeditor/tinymce/skins/lightgray/skin.min.css /Website/Composite/content/misc/editors/visualeditor/tinymce/skins/lightgray/skin.ie7.min.css /Website/Composite/content/misc/editors/visualeditor/tinymce/skins/lightgray/img/trans.gif /Website/Composite/content/misc/editors/visualeditor/tinymce/skins/lightgray/img/object.gif /Website/Composite/content/misc/editors/visualeditor/tinymce/skins/lightgray/img/loader.gif /Website/Composite/content/misc/editors/visualeditor/tinymce/skins/lightgray/img/anchor.gif /Website/Composite/content/misc/editors/visualeditor/tinymce/skins/lightgray/content.min.css /Website/Composite/content/misc/editors/visualeditor/tinymce/skins/lightgray/content.inline.min.css ================================================ FILE: .tern-project ================================================ { "ecmaVersion": 6, "libs": [], "plugins": {} } ================================================ FILE: Composite/AspNet/Caching/DonutCacheEntry.cs ================================================ using Composite.Core.Routing.Pages; using System; using System.Collections.Generic; using System.Web; using System.Web.Caching; using System.Xml.Linq; namespace Composite.AspNet.Caching { [Serializable] internal class DonutCacheEntry { private XDocument _document; public DonutCacheEntry() { } public DonutCacheEntry(HttpContext context, XDocument document) { Document = new XDocument(document); var headers = context.Response.Headers; var headersCopy = new List(headers.Count); foreach (var name in headers.AllKeys) { headersCopy.Add(new HeaderElement(name, headers[name])); } OutputHeaders = headersCopy; PathInfoUsed = C1PageRoute.PathInfoUsed; } public XDocument Document { get => new XDocument(_document); set => _document = value; } public bool PathInfoUsed { get; set; } public IReadOnlyCollection OutputHeaders { get; set; } } } ================================================ FILE: Composite/AspNet/Caching/OutputCacheHelper.cs ================================================ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Reflection; using System.Runtime.Caching; using System.Text; using System.Web; using System.Web.Caching; using System.Web.Configuration; using System.Web.Hosting; using System.Web.UI; namespace Composite.AspNet.Caching { internal static class OutputCacheHelper { private const string CacheProfileName = "C1Page"; private static readonly FieldInfo CacheabilityFieldInfo; private static readonly Dictionary _outputCacheProfiles; static OutputCacheHelper() { CacheabilityFieldInfo = typeof(HttpCachePolicy).GetField("_cacheability", BindingFlags.Instance | BindingFlags.NonPublic); var section = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath) .GetSection("system.web/caching/outputCacheSettings"); if (section is OutputCacheSettingsSection settings) { _outputCacheProfiles = settings.OutputCacheProfiles.OfType() .ToDictionary(_ => _.Name); } } /// /// Returns true and sets the cache key value for the current request if /// ASP.NET full page caching is enabled. /// /// /// /// public static bool TryGetCacheKey(HttpContext context, out string cacheKey) { var cacheProfile = _outputCacheProfiles[CacheProfileName]; if (!cacheProfile.Enabled || cacheProfile.Duration <= 0 || !(cacheProfile.Location == (OutputCacheLocation) (-1) /* Unspecified */ || cacheProfile.Location == OutputCacheLocation.Any || cacheProfile.Location == OutputCacheLocation.Server || cacheProfile.Location == OutputCacheLocation.ServerAndClient)) { cacheKey = null; return false; } var request = context.Request; var sb = new StringBuilder(1 + request.Path.Length + (request.PathInfo ?? "").Length ); sb.Append(request.HttpMethod[0]).Append(request.Path).Append(request.PathInfo); if (cacheProfile.VaryByCustom != null) { string custom = context.ApplicationInstance.GetVaryByCustomString(context, cacheProfile.VaryByCustom); sb.Append("c").Append(custom); } if (!string.IsNullOrEmpty(cacheProfile.VaryByParam)) { var filter = GetVaryByFilter(cacheProfile.VaryByParam); AppendParameters(sb, "Q", request.QueryString, filter); if (request.HttpMethod == "POST") { AppendParameters(sb, "F", request.Form, filter); } } if (!string.IsNullOrEmpty(cacheProfile.VaryByHeader)) { var filter = GetVaryByFilter(cacheProfile.VaryByHeader); AppendParameters(sb, "H", request.Headers, filter); } cacheKey = sb.ToString(); return true; } private static Func GetVaryByFilter(string varyBy) { if (varyBy == "*") { return parameter => true; } var list = varyBy.Split(';'); return parameter => list.Contains(parameter); } private static void AppendParameters(StringBuilder sb, string cacheKeyDelimiter, NameValueCollection collection, Func filter) { foreach (string key in collection.OfType().Where(filter)) { sb.Append(cacheKeyDelimiter).Append(key).Append("=").Append(collection[key]); } } public static DonutCacheEntry GetFromCache(HttpContext context, string cacheKey) { var provider = GetCacheProvider(context); if (provider == null) { return MemoryCache.Default.Get(cacheKey) as DonutCacheEntry; } return provider.Get(cacheKey) as DonutCacheEntry; } public static void AddToCache(HttpContext context, string cacheKey, DonutCacheEntry entry) { var provider = GetCacheProvider(context); if (provider == null) { MemoryCache.Default.Add(cacheKey, entry, new CacheItemPolicy { SlidingExpiration = TimeSpan.FromSeconds(60) }); return; } provider.Add(cacheKey, entry, DateTime.UtcNow.AddSeconds(60)); } static OutputCacheProvider GetCacheProvider(HttpContext context) { var cacheName = context.ApplicationInstance.GetOutputCacheProviderName(context); return cacheName != "AspNetInternalProvider" ? OutputCache.Providers?[cacheName] : null; } public static bool ResponseCacheable(HttpContext context) { if (context.Response.StatusCode != 200) { return false; } var cacheability = GetPageCacheability(context); return cacheability > HttpCacheability.NoCache; } private static HttpCacheability GetPageCacheability(HttpContext context) => (HttpCacheability)CacheabilityFieldInfo.GetValue(context.Response.Cache); public static void InitializeFullPageCaching(HttpContext context) { using (var page = new CacheableEmptyPage()) { page.ProcessRequest(context); } } private class CacheableEmptyPage : Page { protected override void FrameworkInitialize() { base.FrameworkInitialize(); // That's an equivalent of having <%@ OutputCache CacheProfile="C1Page" %> // on an *.aspx page InitOutputCache(new OutputCacheParameters { CacheProfile = CacheProfileName }); } } } } ================================================ FILE: Composite/AspNet/CmsPageHttpHandler.cs ================================================ using System.Web; using System.Xml.Linq; using Composite.AspNet.Caching; using Composite.Core; using Composite.Core.Configuration; using Composite.Core.Instrumentation; using Composite.Core.PageTemplates; using Composite.Core.Routing.Pages; using Composite.Core.WebClient.Renderings; using Composite.Core.WebClient.Renderings.Page; using Composite.Core.Xml; namespace Composite.AspNet { /// /// Renders page templates without building a Web Form's control tree. /// Contains a custom implementation of "donut caching". /// internal class CmsPageHttpHandler: IHttpHandler { public void ProcessRequest(HttpContext context) { OutputCacheHelper.InitializeFullPageCaching(context); using (var renderingContext = RenderingContext.InitializeFromHttpContext()) { bool cachingEnabled = false; string cacheKey = null; DonutCacheEntry cacheEntry = null; bool consoleUserLoggedIn = Composite.C1Console.Security.UserValidationFacade.IsLoggedIn(); // "Donut caching" is enabled for logged in users, only if profiling is enabled as well. if (!renderingContext.CachingDisabled && (!consoleUserLoggedIn || renderingContext.ProfilingEnabled)) { cachingEnabled = OutputCacheHelper.TryGetCacheKey(context, out cacheKey); if (cachingEnabled) { using (Profiler.Measure("Cache lookup")) { cacheEntry = OutputCacheHelper.GetFromCache(context, cacheKey); } } } XDocument document; var functionContext = PageRenderer.GetPageRenderFunctionContextContainer(); bool allFunctionsExecuted = false; bool preventResponseCaching = false; if (cacheEntry != null) { document = cacheEntry.Document; foreach (var header in cacheEntry.OutputHeaders) { context.Response.Headers[header.Name] = header.Value; } if(cacheEntry.PathInfoUsed) { C1PageRoute.RegisterPathInfoUsage(); } // Making sure this response will not go to the output cache preventResponseCaching = true; } else { if (renderingContext.RunResponseHandlers()) { return; } var renderer = PageTemplateFacade.BuildPageRenderer(renderingContext.Page.TemplateId); var slimRenderer = (ISlimPageRenderer) renderer; using (Profiler.Measure($"{nameof(ISlimPageRenderer)}.Render")) { document = slimRenderer.Render(renderingContext.PageContentToRender, functionContext); } allFunctionsExecuted = PageRenderer.ExecuteCacheableFunctions(document.Root, functionContext); if (cachingEnabled && !allFunctionsExecuted && OutputCacheHelper.ResponseCacheable(context)) { preventResponseCaching = true; if (!functionContext.ExceptionsSuppressed) { using (Profiler.Measure("Adding to cache")) { OutputCacheHelper.AddToCache(context, cacheKey, new DonutCacheEntry(context, document)); } } } } if (!allFunctionsExecuted) { using (Profiler.Measure("Executing embedded functions")) { PageRenderer.ExecuteEmbeddedFunctions(document.Root, functionContext); } } using (Profiler.Measure("Resolving page fields")) { PageRenderer.ResolvePageFields(document, renderingContext.Page); } string xhtml; if (document.Root.Name == RenderingElementNames.Html) { var xhtmlDocument = new XhtmlDocument(document); PageRenderer.ProcessXhtmlDocument(xhtmlDocument, renderingContext.Page); PageRenderer.ProcessDocumentHead(xhtmlDocument); xhtml = xhtmlDocument.ToString(); } else { xhtml = document.ToString(); } if (renderingContext.PreRenderRedirectCheck()) { return; } xhtml = renderingContext.ConvertInternalLinks(xhtml); if (GlobalSettingsFacade.PrettifyPublicMarkup) { xhtml = renderingContext.FormatXhtml(xhtml); } var response = context.Response; // Disabling ASP.NET cache if there's a logged-in user if (consoleUserLoggedIn || preventResponseCaching) { using (preventResponseCaching ? Profiler.Measure("CmsPageHttpHandler: Disabling HTTP caching as at least one of the functions is not cacheable") : EmptyDisposable.Instance) { context.Response.Cache.SetCacheability(HttpCacheability.NoCache); } } // Inserting performance profiling information if (renderingContext.ProfilingEnabled) { xhtml = renderingContext.BuildProfilerReport(); response.ContentType = "text/xml"; } response.Write(xhtml); } } public bool IsReusable => true; } } ================================================ FILE: Composite/AspNet/CmsPageSiteMapNode.cs ================================================ using System; using System.Globalization; using System.Web; using Composite.Core.Routing; using Composite.Data; using Composite.Data.Types; namespace Composite.AspNet { /// /// Represents an instance in a sitemap. /// public class CmsPageSiteMapNode : SiteMapNode, ICmsSiteMapNode, ISchemaOrgSiteMapNode { private int? _depth; /// public CultureInfo Culture { get; protected set; } /// public int? Priority { get; protected set; } /// /// Gets the current page. /// public IPage Page { get; } /// /// Gets or sets the depth. /// /// /// The depth. /// public int Depth { get { if (_depth == null) { var depth = 0; var id = Page.Id; const int maxDepth = 1000; using (new DataScope(Page.DataSourceId.PublicationScope, Page.DataSourceId.LocaleScope)) { while (id != Guid.Empty && depth < maxDepth) { depth++; id = PageManager.GetParentId(id); } if (depth == maxDepth) { throw new InvalidOperationException("Endless page loop"); } } _depth = depth; } return _depth.Value; } protected set => _depth = value; } /// public DateTime LastModified { get; } /// public SiteMapNodeChangeFrequency? ChangeFrequency { get; protected set; } /// /// Gets or sets the document title. /// /// /// The document title. /// public string DocumentTitle { get; } /// /// Initializes a new instance of the class. /// /// The provider. /// The page. public CmsPageSiteMapNode(SiteMapProvider provider, IPage page) : base(provider, page.Id.ToString(), PageUrls.BuildUrl(page), page.MenuTitle, page.Description) { Page = page; DocumentTitle = page.Title; LastModified = page.ChangeDate; Priority = 5; Culture = page.DataSourceId.LocaleScope; } /// public bool Equals(CmsPageSiteMapNode obj) { return Key == obj.Key && Culture.Equals(obj.Culture); } /// public override bool Equals(object obj) { var pageSiteMapNode = obj as CmsPageSiteMapNode; if (pageSiteMapNode != null) { return Equals(pageSiteMapNode); } return base.Equals(obj); } /// public override SiteMapNode Clone() { return new CmsPageSiteMapNode(this.Provider, Page); } /// public override int GetHashCode() { return Key.GetHashCode() ^ Culture.GetHashCode(); } /// public static bool operator ==(CmsPageSiteMapNode a, CmsPageSiteMapNode b) { if (Object.ReferenceEquals(a, b)) { return true; } if ((object)a == null || (object)b == null) { return false; } return a.Equals(b); } /// public static bool operator !=(CmsPageSiteMapNode a, CmsPageSiteMapNode b) { return !(a == b); } } } ================================================ FILE: Composite/AspNet/CmsPageSiteMapProvider.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using Composite.Core; using Composite.Data; namespace Composite.AspNet { /// /// Implementation of which returns nodes returned by registered . /// public class CmsPageSiteMapProvider : SiteMapProvider, ICmsSiteMapProvider { private static readonly SiteMapNodeCollection EmptyCollection = SiteMapNodeCollection.ReadOnly(new SiteMapNodeCollection()); private readonly List _plugins; /// public override SiteMapNode CurrentNode { get { var context = HttpContext.Current; var node = ResolveSiteMapNode(context) ?? FindSiteMapNode(context); return SecurityTrimNode(node); } } /// public override SiteMapProvider RootProvider => ParentProvider?.RootProvider ?? this; /// public override SiteMapNode RootNode => SecurityTrimNode(GetRootNodeCore()); /// public CmsPageSiteMapProvider() { _plugins = ServiceLocator.GetServices().ToList(); } /// public override SiteMapNode FindSiteMapNode(HttpContext context) { var contextBase = new HttpContextWrapper(context); foreach (var plugin in _plugins) { var node = plugin.FindSiteMapNode(this, contextBase); if (node != null) { return SecurityTrimNode(node); } } return null; } /// public override SiteMapNode FindSiteMapNodeFromKey(string key) { foreach (var plugin in _plugins) { var node = plugin.FindSiteMapNodeFromKey(this, key); if (node != null) { return SecurityTrimNode(node); } } return null; } /// public override SiteMapNodeCollection GetChildNodes(SiteMapNode node) { Verify.ArgumentNotNull(node, nameof(node)); var childNodes = _plugins.SelectMany(plugin => plugin.GetChildNodes(node) ?? Enumerable.Empty()).ToList(); childNodes = SecurityTrimList(childNodes); if (!childNodes.Any()) { return EmptyCollection; } return new SiteMapNodeCollection(childNodes.ToArray()); } /// public override SiteMapNode GetParentNode(SiteMapNode node) { Verify.ArgumentNotNull(node, nameof(node)); SiteMapNode parentNode = null; foreach (var plugin in _plugins) { parentNode = plugin.GetParentNode(node); if (parentNode != null) { break; } } return SecurityTrimNode(parentNode); } /// protected override SiteMapNode GetRootNodeCore() { var siteMapContext = SiteMapContext.Current; var rootPage = siteMapContext?.RootPage; if (rootPage == null) { var homePageId = SitemapNavigator.CurrentHomePageId; if (homePageId == Guid.Empty) { var context = HttpContext.Current; if (context == null) { homePageId = PageManager.GetChildrenIDs(Guid.Empty).FirstOrDefault(); } else { using (var data = new DataConnection()) { var pageNode = data.SitemapNavigator.GetPageNodeByHostname(context.Request.Url.Host); homePageId = pageNode?.Id ?? Guid.Empty; } } } if (homePageId != Guid.Empty) { rootPage = PageManager.GetPageById(homePageId); } } if (rootPage == null) { return null; } var node = new CmsPageSiteMapNode(this, rootPage); return SecurityTrimNode(node); } /// public ICollection GetRootNodes() { var list = new List(); foreach (var rootPageId in PageManager.GetChildrenIDs(Guid.Empty)) { foreach (var culture in DataLocalizationFacade.ActiveLocalizationCultures) { using (new DataScope(culture)) { var page = PageManager.GetPageById(rootPageId); if (page != null) { list.Add(new CmsPageSiteMapNode(this, page)); } } } } return SecurityTrimList(list); } /// public override SiteMapNode FindSiteMapNode(string rawUrl) { foreach (var plugin in _plugins) { var node = plugin.FindSiteMapNode(this, rawUrl); if (node != null) { return SecurityTrimNode(node); } } return null; } /// public override bool IsAccessibleToUser(HttpContext ctx, SiteMapNode node) { var ctxBase = new HttpContextWrapper(ctx); return _plugins.All(plugin => plugin.IsAccessibleToUser(ctxBase, node)); } private T SecurityTrimNode(T node) where T : SiteMapNode { if (node == null) { return null; } if (SecurityTrimmingEnabled) { var context = HttpContext.Current; if (!node.IsAccessibleToUser(context)) { return null; } } return node; } private List SecurityTrimList(List list) where T : SiteMapNode { if (list == null) { return null; } if (SecurityTrimmingEnabled && list.Count > 0) { var context = HttpContext.Current; return list.Where(child => child.IsAccessibleToUser(context)).ToList(); } return list; } } } ================================================ FILE: Composite/AspNet/CmsPagesSiteMapPlugin.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using Composite.Core.Extensions; using Composite.Core.Routing; using Composite.Core.WebClient.Renderings.Page; using Composite.Data; using Composite.Data.Types; namespace Composite.AspNet { /// public class CmsPagesSiteMapPlugin : ISiteMapPlugin { /// public List GetChildNodes(SiteMapNode node) { var pageSiteMapNode = node as CmsPageSiteMapNode; if (pageSiteMapNode != null) { using (new DataScope(pageSiteMapNode.Culture)) { var pageChildNodes = PageManager.GetChildrenIDs(pageSiteMapNode.Page.Id) .Select(PageManager.GetPageById) .Where(p => p != null) .Select(p => new CmsPageSiteMapNode(node.Provider, p)) .OfType() .ToList(); return pageChildNodes; } } return null; } /// public SiteMapNode GetParentNode(SiteMapNode node) { var pageSiteMapNode = node as CmsPageSiteMapNode; if (pageSiteMapNode != null) { IPage parentPage = null; using (new DataScope(pageSiteMapNode.Culture)) { var parentPageId = PageManager.GetParentId(pageSiteMapNode.Page.Id); if (parentPageId != Guid.Empty) { parentPage = PageManager.GetPageById(parentPageId); } } if (parentPage != null) { return new CmsPageSiteMapNode(node.Provider, parentPage); } return node.Provider.ParentProvider?.GetParentNode(node); } return null; } /// public SiteMapNode FindSiteMapNode(SiteMapProvider provider, HttpContextBase context) { var key = PageRenderer.CurrentPageId.ToString(); return FindSiteMapNodeFromKey(provider, key); } /// public SiteMapNode FindSiteMapNode(SiteMapProvider provider, string rawUrl) { var pageUrl = PageUrls.ParseUrl(rawUrl); if (pageUrl == null || !String.IsNullOrEmpty(pageUrl.PathInfo)) { return null; } var page = pageUrl.GetPage(); if (page == null) { return null; } return new CmsPageSiteMapNode(provider, page); } /// public SiteMapNode FindSiteMapNodeFromKey(SiteMapProvider provider, string key) { if (Guid.TryParse(key, out var pageId)) { var page = PageManager.GetPageById(pageId); if (page != null) { return new CmsPageSiteMapNode(provider, page); } } return null; } /// public bool IsAccessibleToUser(HttpContextBase context, SiteMapNode node) { return true; } } } ================================================ FILE: Composite/AspNet/ICmsSiteMapNode.cs ================================================ using System.Globalization; using System.Web; namespace Composite.AspNet { /// /// Used as an extension to when building a ASP.NET sitemap based on cms pages. /// public interface ICmsSiteMapNode { /// /// Gets the culture to which the site map node belongs. /// /// /// The culture. /// CultureInfo Culture { get; } } } ================================================ FILE: Composite/AspNet/ICmsSiteMapProvider.cs ================================================ using System.Collections.Generic; namespace Composite.AspNet { /// /// An inteface for getting site map data required for rendering /Sitemap.xml file. /// public interface ICmsSiteMapProvider { /// /// Gets the root nodes. /// ICollection GetRootNodes(); } } ================================================ FILE: Composite/AspNet/ISchemaOrgSiteMapNode.cs ================================================ using System; using System.Web; namespace Composite.AspNet { /// /// Provides infomation that is used as an addition to when generating sitemap xml file. /// See https://www.sitemaps.org for details /// public interface ISchemaOrgSiteMapNode { /// /// Gets the last modification time. /// /// /// The last modification time. /// DateTime LastModified { get; } /// /// Gets the change frequency. /// /// /// The change frequency. /// SiteMapNodeChangeFrequency? ChangeFrequency { get; } /// /// Gets the priority. /// /// /// The priority. /// int? Priority { get; } } } ================================================ FILE: Composite/AspNet/ISiteMapPlugin.cs ================================================ using System.Collections.Generic; using System.Web; namespace Composite.AspNet { /// /// Defines the contract for a plugin to interact with to provide and handle security trimming /// public interface ISiteMapPlugin { /// /// Retrieves the child nodes of a specific . /// /// /// List GetChildNodes(SiteMapNode node); /// /// Retrieves the parent node of a specific object. /// /// /// SiteMapNode GetParentNode(SiteMapNode node); /// /// Retrieves a object that represents a page. /// /// /// /// SiteMapNode FindSiteMapNode(SiteMapProvider provider, string rawUrl); /// /// Retrieves a object based on . /// /// /// /// SiteMapNode FindSiteMapNode(SiteMapProvider provider, HttpContextBase context); /// /// Retrieves a object based on a specified key. /// /// /// /// SiteMapNode FindSiteMapNodeFromKey(SiteMapProvider provider, string key); /// /// Retrieves a Boolean value indicating whether the specified object can be viewed by the user in the specified context. /// /// /// /// bool IsAccessibleToUser(HttpContextBase context, SiteMapNode node); } } ================================================ FILE: Composite/AspNet/Razor/C1HtmlHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.WebPages.Html; using System.Xml.Linq; using Composite.Core.Types; using Composite.Core.WebClient.Media; using Composite.Core.WebClient.Renderings.Template; using Composite.Data; using Composite.Data.Types; using Composite.Functions; namespace Composite.AspNet.Razor { /// /// Extension object to be used in Razor code /// public class C1HtmlHelper { private readonly HtmlHelper _helper; /// /// Initializes a new instance of the class. /// /// The helper. public C1HtmlHelper(HtmlHelper helper) { _helper = helper; } /// /// Returns a URL for a specific C1 page /// /// The page. /// public IHtmlString PageUrl(IPage page) { return PageUrl(page.Id); } /// /// Returns a URL for a specific C1 page /// /// The page. /// public IHtmlString PageUrl(DataReference page) { return PageUrl(((Guid) page.KeyValue)); } /// /// Returns a URL for a specific C1 page /// /// The page. /// The querystring object. /// public IHtmlString PageUrl(IPage page, object querystring) { return PageUrl(page.Id, querystring); } /// /// Returns a URL for a specific C1 page /// /// The page. /// An object which properties' values will be passes as query string. /// public IHtmlString PageUrl(IPage page, IDictionary querystring) { return PageUrl(page.Id, querystring); } /// /// Returns a URL for a specific C1 page /// /// The page id. /// The querystring. /// public IHtmlString PageUrl(string pageId, object querystring = null) { return PageUrl(new Guid(pageId), querystring); } /// /// Returns a URL for a specific C1 page /// /// The page id. /// public IHtmlString PageUrl(Guid pageId) { return PageUrl(pageId, null); } /// /// Returns a URL for a specific C1 page /// /// The page id. /// The querystring. /// public IHtmlString PageUrl(Guid pageId, object querystring) { var dict = Functions.ObjectToDictionary(querystring); return PageUrl(pageId, dict); } /// /// Returns a URL for a specific C1 page /// /// The page id. /// The querystring. /// public IHtmlString PageUrl(string pageId, IDictionary querystring) { return PageUrl(new Guid(pageId), querystring); } /// /// Returns a URL for a specific C1 page /// /// The page id. /// The querystring. /// public IHtmlString PageUrl(Guid pageId, IDictionary querystring) { string relativeUrl = "~/page(" + pageId + ")"; string absoluteUrl = VirtualPathUtility.ToAbsolute(relativeUrl); if (querystring != null && querystring.Keys.Count > 0) { absoluteUrl += "?" + SerializeQueryString(querystring); } return _helper.Raw(absoluteUrl); } /// /// Returns a media url. /// /// The media file. /// public IHtmlString MediaUrl(IMediaFile mediaFile) { return MediaUrl(mediaFile.KeyPath); } /// /// Returns a media url. /// /// The media file. /// public IHtmlString MediaUrl(DataReference mediaFile) { return MediaUrl((string) mediaFile.KeyValue); } /// /// Returns a media url. /// /// The media file. /// public IHtmlString MediaUrl(NullableDataReference mediaFile) { if (!mediaFile.IsSet) { return null; } return MediaUrl((string) mediaFile.KeyValue); } /// /// Returns a media url. /// /// The image file. /// public IHtmlString MediaUrl(DataReference image) { return MediaUrl((string)image.KeyValue); } /// /// Returns a media url. /// /// The image file. /// public IHtmlString MediaUrl(NullableDataReference image) { if (!image.IsSet) { return null; } return MediaUrl((string)image.KeyValue); } /// /// Returns a media url. /// /// The image file. /// The resizing options. /// public IHtmlString MediaUrl(DataReference image, ResizingOptions resizingOptions) { return MediaUrl((string) image.KeyValue, resizingOptions); } /// /// Returns a media url. /// /// The image file. /// The resizing options. /// public IHtmlString MediaUrl(IImageFile image, ResizingOptions resizingOptions) { return MediaUrl(image.KeyPath, resizingOptions); } /// /// Returns a media url. /// /// The media file. /// The querystring. /// public IHtmlString MediaUrl(IMediaFile mediaFile, object querystring) { return MediaUrl(mediaFile.KeyPath, querystring); } /// /// Returns a media url. /// /// The media file. /// The querystring. /// public IHtmlString MediaUrl(IMediaFile mediaFile, IDictionary querystring) { return MediaUrl(mediaFile.KeyPath, querystring); } /// /// Returns a media url. /// /// Id of a media file. /// The querystring. /// public IHtmlString MediaUrl(Guid mediaId, object querystring = null) { return MediaUrl(mediaId.ToString(), querystring); } /// /// Returns a media url. /// /// Id of a media file. /// The querystring. /// public IHtmlString MediaUrl(Guid mediaId, IDictionary querystring) { return MediaUrl(mediaId.ToString(), querystring); } /// /// Returns a media url. /// /// The keyPath property of a media item. /// The querystring. /// public IHtmlString MediaUrl(string keyPath, object querystring = null) { var dict = Functions.ObjectToDictionary(querystring); return MediaUrl(keyPath, dict); } /// /// Returns a media url. /// /// The keyPath property of a media item. /// The querystring. /// public IHtmlString MediaUrl(string keyPath, IDictionary querystring) { string relativeUrl = "~/media(" + keyPath + ")"; string absoluteUrl = VirtualPathUtility.ToAbsolute(relativeUrl); if (querystring != null && querystring.Keys.Count > 0) { absoluteUrl += "?" + SerializeQueryString(querystring); } return _helper.Raw(absoluteUrl); } /// /// Returns a media url. /// /// Image's KeyPath field value. /// The resizing options. /// public IHtmlString MediaUrl(string keyPath, ResizingOptions resizingOptions) { string relativeUrl = "~/media(" + keyPath + ")"; string absoluteUrl = VirtualPathUtility.ToAbsolute(relativeUrl); string queryString = resizingOptions.ToString(); if (!string.IsNullOrEmpty(queryString)) { absoluteUrl += "?" + queryString.Replace("&", "&"); } return _helper.Raw(absoluteUrl); } private static string SerializeQueryString(IDictionary querystring) { return String.Join("&", querystring.Select(kvp => HttpUtility.UrlEncode(kvp.Key) + "=" + HttpUtility.UrlEncode(kvp.Value.ToString()))); } /// /// Renders the specified XNode. /// /// The XNode. /// public IHtmlString Markup(XNode xNode) { if (xNode == null) { return null; } // TODO: optimize so XNode doesn't get serialized/deserialized return _helper.Raw(xNode.ToString()); } /// /// Includes a named Page Template Feature. Page Template Feature are managed in '~/App_Data/PageTemplateFeatures' /// or via the C1 Console's Layout perspective. They contain html and functional snippets. /// /// Name of the Page Template Feature to include. Names do not include an extension. /// public IHtmlString GetPageTemplateFeature(string featureName) { XElement documentRoot = PageTemplateFeatureFacade.GetPageTemplateFeature(featureName).Root; return _helper.Raw(documentRoot.ToString()); } /// /// Renders the specified XNode-s. /// /// The collection of XNode objects. /// public IHtmlString Markup(IEnumerable xNodes) { if (xNodes == null) { return null; } // TODO: optimize so XNode-s don't get serialized/deserialized var sb = new StringBuilder(); foreach (var xNode in xNodes) { if (xNode == null) continue; sb.Append(xNode.ToString()); } return _helper.Raw(sb.ToString()); } /// /// Executes a C1 Function. /// /// Function name. /// [Obsolete("Use Function method directly on the Razor page")] public IHtmlString Function(string name) { return Function(name, null); } /// /// Executes a C1 Function. /// /// Function name. /// The parameters. /// [Obsolete("Use Function method directly on the Razor page")] public IHtmlString Function(string name, object parameters) { return Function(name, Functions.ObjectToDictionary(parameters)); } /// /// Executes a C1 Function. /// /// Function name. /// The parameters. /// [Obsolete("Use Function method directly on the Razor page")] public IHtmlString Function(string name, IDictionary parameters) { return Function(name, parameters, new FunctionContextContainer()); } /// /// Executes a C1 Function. /// /// Function name. /// The parameters. /// The function context container /// public IHtmlString Function(string name, IDictionary parameters, FunctionContextContainer functionContext) { object result = Functions.ExecuteFunction(name, parameters, functionContext); if (result is Control) { return EmbedControl(result, functionContext); } return ConvertFunctionResult(result); } private static IHtmlString EmbedControl(object result, FunctionContextContainer functionContext) { if (functionContext == null) { throw new ArgumentNullException("functionContext", "Failed to insert UserControl without FunctionContextContainer"); } if (functionContext.XEmbedableMapper == null) { throw new ArgumentException("Failed to insert UserControl. functionContextContainer.XEmbedableMapper is null", "functionContext"); } XNode resultNode; if (!functionContext.XEmbedableMapper.TryMakeXEmbedable(functionContext, result, out resultNode)) { throw new InvalidOperationException("Failed to insert control. Type: " + result.GetType()); } return new HtmlString(resultNode.ToString()); } private static IHtmlString ConvertFunctionResult(object result) { var resultAsString = ValueTypeConverter.Convert(result); if (resultAsString != null) { return new HtmlString(resultAsString); } throw new InvalidOperationException("Function doesn't return string value"); } } } ================================================ FILE: Composite/AspNet/Razor/CompositeC1WebPage.cs ================================================ using System; using System.Web; using System.Web.WebPages; using System.Xml.Linq; using Composite.Data; using System.Threading; using System.Collections.Generic; using System.Linq; using Composite.Core.Extensions; using Composite.Functions; namespace Composite.AspNet.Razor { /// /// Defines a C1 CMS razor control /// public abstract class CompositeC1WebPage : WebPage, IDisposable { private bool _disposed; private DataConnection _data; private List _childPages = new List(); /// /// Initializes a new instance of the class. /// protected CompositeC1WebPage() { _data = new DataConnection(); } /// /// Gets a object. /// public DataConnection Data { get { var result = _data ?? (WebPageContext.Current?.Page as CompositeC1WebPage)?.Data; Verify.IsNotNull(result, nameof(DataConnection) + " instance has already been disposed"); return result; } } /// /// Gets a object. /// public SitemapNavigator Sitemap => Data.SitemapNavigator; /// /// Gets the home page node. /// public PageNode HomePageNode => Sitemap.CurrentHomePageNode; /// /// Gets the current page node. /// public PageNode CurrentPageNode => Sitemap.CurrentPageNode; /// /// Includes a named Page Template Feature. Page Template Feature are managed in '~/App_Data/PageTemplateFeatures' /// or via the C1 Console's Layout perspective. They contain html and functional snippets. /// /// Name of the Page Template Feature to include. Names do not include an extension. /// public IHtmlString PageTemplateFeature(string featureName) { return Html.C1().GetPageTemplateFeature(featureName); } /// /// Renders the specified XNode. /// /// The XNode. /// public IHtmlString Markup(XNode xNode) { return Html.C1().Markup(xNode); } /// /// Gets to letter ISO Language Name representing the pages language - use this like <html lang="@Lang" /> /// public string Lang => Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName; /// /// Gets the function context container. /// public FunctionContextContainer FunctionContextContainer => GetFunctionContext(); /// /// Executes a C1 Function. /// /// Function name. /// public IHtmlString Function(string name) { return Function(name, null); } /// /// Executes a C1 Function. /// /// Function name. /// The parameters. /// public IHtmlString Function(string name, object parameters) { return Function(name, Functions.ObjectToDictionary(parameters)); } /// /// Executes a C1 Function. /// /// Function name. /// The parameters. /// /// The FunctionContextContainer used to execute the function. /// public IHtmlString Function(string name, object parameters, FunctionContextContainer functionContextContainer) { return Function(name, Functions.ObjectToDictionary(parameters), functionContextContainer); } /// /// Executes a C1 Function. /// /// Function name. /// The parameters. /// public IHtmlString Function(string name, IDictionary parameters) { return Function(name, parameters, GetFunctionContext()); } /// /// Executes a C1 Function. /// /// Function name. /// The parameters. /// The FunctionContextContainer used to execute the function. /// public IHtmlString Function(string name, IDictionary parameters, FunctionContextContainer functionContextContainer) { return Html.C1().Function(name, parameters, functionContextContainer); } private FunctionContextContainer GetFunctionContext() { if (!PageData.ContainsKey(RazorHelper.PageContext_FunctionContextContainer)) { return null; } return PageData[RazorHelper.PageContext_FunctionContextContainer]; } /// protected override void ConfigurePage(WebPageBase parentPage) { base.ConfigurePage(parentPage); if (parentPage is CompositeC1WebPage parentC1Page) { if (parentC1Page._childPages == null) { parentC1Page._childPages = new List(); } parentC1Page._childPages.Add(this); } } /// public override void ExecutePageHierarchy() { base.ExecutePageHierarchy(); _data.Dispose(); _data = null; } /// public void Dispose() { Dispose(true); #if LeakCheck GC.SuppressFinalize(this); #endif } /// protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { (_childPages as IEnumerable)?.Reverse().ForEach(c => c.Dispose()); _data?.Dispose(); } _disposed = true; } #if LeakCheck private string stack = Environment.StackTrace; /// ~CompositeC1WebPage() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); Dispose(false); } #endif } } ================================================ FILE: Composite/AspNet/Razor/Functions.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using Composite.Functions; using Composite.Core.Extensions; namespace Composite.AspNet.Razor { /// /// Utility class for working with C1 functions from Razor code /// public static class Functions { /// /// Executes the function. /// /// The name. public static object ExecuteFunction(string name) { return ExecuteFunction(name, null); } /// /// Executes the function. /// /// The name. /// The parameters. /// public static object ExecuteFunction(string name, object parameters) { return ExecuteFunction(name, ObjectToDictionary(parameters)); } /// /// Executes the function. /// /// The name. /// The parameters. /// public static object ExecuteFunction(string name, IDictionary parameters) { return ExecuteFunction(name, parameters, new FunctionContextContainer()); } /// /// Executes the function. /// /// The name. /// The parameters. /// The function context container /// public static object ExecuteFunction(string name, IDictionary parameters, FunctionContextContainer functionContextContainer) { IFunction function; if (!FunctionFacade.TryGetFunction(out function, name)) { throw new InvalidOperationException("Failed to load function '{0}'".FormatWith(name)); } functionContextContainer = functionContextContainer ?? new FunctionContextContainer(); return FunctionFacade.Execute(function, parameters, functionContextContainer); } /// /// Builds a dictionary for object properties' values. /// /// The instance. /// public static IDictionary ObjectToDictionary(object instance) { if (instance == null) { return null; } var dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(instance)) { object obj = descriptor.GetValue(instance); dictionary.Add(descriptor.Name, obj); } return dictionary; } } } ================================================ FILE: Composite/AspNet/Razor/HtmlHelperExtensions.cs ================================================ using System.Web.WebPages.Html; namespace Composite.AspNet.Razor { /// /// Add C1 specific extension methods for Razor functions /// public static class HtmlHelperExtensions { /// /// Exposes C1 specific functionality /// /// /// public static C1HtmlHelper C1(this HtmlHelper helper) { return new C1HtmlHelper(helper); } } } ================================================ FILE: Composite/AspNet/Razor/NoHttpRazorContext.cs ================================================ using System; using System.Collections; using System.Web; using System.Web.Instrumentation; using System.Web.WebPages.Scope; namespace Composite.AspNet.Razor { internal class NoHttpRazorContext : HttpContextBase { private readonly IDictionary _items = new Hashtable(); private readonly HttpRequestBase _request = new NoHttpRazorRequest(); private readonly HttpResponseBase _response = new NoHttpRazorResponse(); private readonly PageInstrumentationService _pageInstrumentation = new PageInstrumentationService(); public override IDictionary Items => _items; public override HttpRequestBase Request => _request; public override HttpResponseBase Response => _response; public override PageInstrumentationService PageInstrumentation => _pageInstrumentation; public override HttpServerUtilityBase Server => throw new NotSupportedException("Usage of 'Server' isn't supported without HttpContext. Use System.Web.HttpUtility for [html|url] [encoding|decoding]"); public override object GetService(Type serviceType) { return null; } public NoHttpRazorContext() { ScopeStorage.CurrentProvider = new StaticScopeStorageProvider(); } } } ================================================ FILE: Composite/AspNet/Razor/NoHttpRazorRequest.cs ================================================ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Web; using System.Web.Hosting; namespace Composite.AspNet.Razor { internal class NoHttpRazorRequest : HttpRequestBase { private NameValueCollection _form; private NameValueCollection _queryString; private NameValueCollection _headers; private NameValueCollection _params; private NameValueCollection _serverVariables; private HttpCookieCollection _cookies; private HttpBrowserCapabilitiesBase _browser; public override string ApplicationPath => HostingEnvironment.ApplicationVirtualPath; public override string PhysicalApplicationPath => HostingEnvironment.ApplicationPhysicalPath; public override HttpBrowserCapabilitiesBase Browser => _browser ?? (_browser = new HttpBrowserCapabilitiesWrapper(new HttpBrowserCapabilities { Capabilities = new Dictionary() })); public override HttpCookieCollection Cookies => _cookies ?? (_cookies = new HttpCookieCollection()); public override bool IsLocal => false; public override NameValueCollection Form => _form ?? (_form = new NameValueCollection()); public override NameValueCollection Headers => _headers ?? (_headers = new NameValueCollection()); public override string HttpMethod => "GET"; public override bool IsAuthenticated => false; public override bool IsSecureConnection => false; public override string this[string key] => null; public override NameValueCollection Params => _params ?? (_params = new NameValueCollection()); public override string PathInfo => null; public override NameValueCollection QueryString => _queryString ?? (_queryString = new NameValueCollection()); public override string RequestType { get => HttpMethod; set => throw new NotSupportedException(); } public override NameValueCollection ServerVariables => _serverVariables ?? (_serverVariables = new NameValueCollection()); public override string UserAgent => ""; } } ================================================ FILE: Composite/AspNet/Razor/NoHttpRazorResponse.cs ================================================ using System.Collections.Specialized; using System.Web; namespace Composite.AspNet.Razor { internal class NoHttpRazorResponse : HttpResponseBase { private NameValueCollection _headers; private HttpCookieCollection _cookies; public override HttpCookieCollection Cookies => _cookies ?? (_cookies = new HttpCookieCollection()); public override NameValueCollection Headers => _headers ?? (_headers = new NameValueCollection()); } } ================================================ FILE: Composite/AspNet/Razor/RazorFunction.cs ================================================ using System; using System.Collections.Generic; using Composite.Core.Xml; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.FileBasedFunctionProvider; namespace Composite.AspNet.Razor { /// /// Base class for c1 functions based on razor /// public abstract class RazorFunction : CompositeC1WebPage, IParameterWidgetsProvider { /// /// Gets the function description. Override this to make a custom description. /// /// ///public override string FunctionDescription ///{ /// get { return "Will show recent Twitter activity for a given keyword."; } ///} /// public virtual string FunctionDescription => string.Empty; /// /// Gets the return type. By default this is XhtmlDocument (html). Override this to set another return type, like string or XElement. /// /// ///public override Type FunctionReturnType ///{ /// get { return typeof(string); } ///} /// public virtual Type FunctionReturnType => typeof (XhtmlDocument); /// /// Determines whether the function output can be cached. /// public virtual bool PreventFunctionOutputCaching => false; /// public virtual IDictionary GetParameterWidgets() { return null; } } } ================================================ FILE: Composite/AspNet/Razor/RazorHelper.cs ================================================ using System; using System.IO; using System.Text; using System.Web; //using System.Web.Instrumentation; using System.Web.WebPages; using System.Xml; using System.Xml.Linq; //using Composite.Core.Extensions; //using Composite.Core.IO; using Composite.Core.Types; using Composite.Core.Xml; using Composite.Functions; namespace Composite.AspNet.Razor { /// /// Exposes method to execute razor pages. /// public static class RazorHelper { internal static readonly string PageContext_FunctionContextContainer = "C1.FunctionContextContainer"; /// /// Executes the razor page. /// /// The virtual path. /// Delegate to set the parameters. /// The type of the result. /// The function context container /// public static object ExecuteRazorPage( string virtualPath, Action setParameters, Type resultType, FunctionContextContainer functionContextContainer) { WebPageBase webPage = null; try { webPage = WebPageBase.CreateInstanceFromVirtualPath(virtualPath); return ExecuteRazorPage(webPage, setParameters, resultType, functionContextContainer); } finally { if (webPage is IDisposable) { (webPage as IDisposable).Dispose(); } } } /// /// Executes the razor page. /// /// The web page. /// Delegate to set the parameters. /// The type of the result. /// The function context container /// public static object ExecuteRazorPage( WebPageBase webPage, Action setParameters, Type resultType, FunctionContextContainer functionContextContainer) { HttpContext currentContext = HttpContext.Current; var startPage = StartPage.GetStartPage(webPage, "_PageStart", new[] { "cshtml" }); // IEnumerable pageExecutionListeners; HttpContextBase httpContext; if (currentContext == null) { httpContext = new NoHttpRazorContext(); // pageExecutionListeners = new PageExecutionListener[0]; } else { httpContext = new HttpContextWrapper(currentContext); // pageExecutionListeners = httpContext.PageInstrumentation.ExecutionListeners; } var pageContext = new WebPageContext(httpContext, webPage, startPage); if (functionContextContainer != null) { pageContext.PageData.Add(PageContext_FunctionContextContainer, functionContextContainer); } if (setParameters != null) { setParameters(webPage); } var sb = new StringBuilder(); using (var writer = new StringWriter(sb)) { //// PageExecutionContext enables "Browser Link" support //var pageExecutionContext = new PageExecutionContext //{ // TextWriter = writer, // VirtualPath = PathUtil.Resolve(webPage.VirtualPath), // StartPosition = 0, // IsLiteral = true //}; //pageExecutionListeners.ForEach(l => l.BeginContext(pageExecutionContext)); webPage.ExecutePageHierarchy(pageContext, writer); //pageExecutionListeners.ForEach(l => l.EndContext(pageExecutionContext)); } string output = sb.ToString(); if (resultType == typeof(XhtmlDocument)) { if (string.IsNullOrWhiteSpace(output)) return new XhtmlDocument(); try { return XhtmlDocument.ParseXhtmlFragment(output); } catch (XmlException ex) { string[] codeLines = output.Split(new [] { Environment.NewLine, "\n" }, StringSplitOptions.None); XhtmlErrorFormatter.EmbedSourceCodeInformation(ex, codeLines, ex.LineNumber); throw; } } return ValueTypeConverter.Convert(output, resultType); } /// /// Executes the razor page. /// /// The result type. /// The virtual path. /// Delegate to set the parameters. /// The function context container. /// public static ResultType ExecuteRazorPage( string virtualPath, Action setParameters, FunctionContextContainer functionContextContainer = null) where ResultType: class { return (ResultType) ExecuteRazorPage(virtualPath, setParameters, typeof(ResultType), functionContextContainer); } } } ================================================ FILE: Composite/AspNet/Razor/RazorPageTemplate.cs ================================================ using System; using System.Web; using Composite.Core.PageTemplates; using Composite.Core.Xml; namespace Composite.AspNet.Razor { /// /// Base class for a razor control that represends a C1 page tempalte /// public abstract class RazorPageTemplate : CompositeC1WebPage, IPageTemplate { /// /// Override this method and set and . /// public abstract void Configure(); /// /// Gets or sets the page template id. You should set this in your Configure() method override. /// public Guid TemplateId { get; protected set; } /// /// Gets or sets the page template title. You should set this in your Configure() method override. /// public string TemplateTitle { get; protected set; } } } ================================================ FILE: Composite/AspNet/Security/FileBasedFunctionEntityToken.cs ================================================ using System; using Composite.C1Console.Security; using Newtonsoft.Json; namespace Composite.AspNet.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(StandardFunctionSecurityAncestorProvider))] public class FileBasedFunctionEntityToken : EntityToken { private readonly string _id; /// public override string Id { get { return _id; } } private readonly string _source; /// public override string Source { get { return _source; } } /// public override string Type { get { return String.Empty; } } /// /// Gets the name of the function provider. /// /// /// The name of the function provider. /// [JsonIgnore] public string FunctionProviderName { get { return Source; } } /// /// Gets the name of the function. /// /// /// The name of the function. /// [JsonIgnore] public string FunctionName { get { return Id; } } /// /// Initializes a new instance of the class. /// /// Name of the function provider. /// Full name of the function. public FileBasedFunctionEntityToken(string functionProviderName, string functionFullName) { _source = functionProviderName; _id = functionFullName; } /// public override string Serialize() { return DoSerialize(); } /// public static EntityToken Deserialize(string serializedEntityToken) { string type; string source; string id; DoDeserialize(serializedEntityToken, out type, out source, out id); return new FileBasedFunctionEntityToken(source, id); } } } ================================================ FILE: Composite/AspNet/Security/StandardFunctionSecurityAncestorProvider.cs ================================================ using System.Collections.Generic; using System.Linq; using Composite.C1Console.Security; using Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider; namespace Composite.AspNet.Security { internal class StandardFunctionSecurityAncestorProvider : ISecurityAncestorProvider { public IEnumerable GetParents(EntityToken entityToken) { string fullname = entityToken.Id; if (fullname.Contains('.')) { fullname = fullname.Remove(fullname.LastIndexOf('.')); } string id = BaseFunctionProviderElementProvider.CreateId(fullname, "AllFunctionsElementProvider"); yield return new BaseFunctionFolderElementEntityToken(id); } } } ================================================ FILE: Composite/AspNet/SiteMapContext.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Data.Types; using Composite.Core.Caching; namespace Composite.AspNet { /// /// Allows switching context of SiteMap /// public class SiteMapContext: IDisposable { /// /// Gets the root page. /// public IPage RootPage { get; private set; } /// /// Initializes a new instance of the class. /// /// The root page. public SiteMapContext(IPage rootPage) { RootPage = rootPage; SiteMapStack.Push(this); } /// /// Gets the current SiteMapContext. Can be null. /// /// /// The current context. /// public static SiteMapContext Current { get { var currentStack = SiteMapStack; return currentStack.Any() ? currentStack.Peek() : null; } } /// public void Dispose() { var top = SiteMapStack.Pop(); Verify.That(object.ReferenceEquals(top, this), "SiteMapContext weren't disposed properly"); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~SiteMapContext() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif private static Stack SiteMapStack { get { return RequestLifetimeCache.GetCachedOrNew>("SiteMapContext:Stack"); } } } } ================================================ FILE: Composite/AspNet/SiteMapHandler.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Web; using System.Xml; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.WebClient; using Composite.Data; using Composite.Data.Types; namespace Composite.AspNet { /// /// Handles requests to XML Sitemaps: */sitemap.xml /// public class SiteMapHandler : IHttpHandler { private const string SiteMapNamespace = "http://www.sitemaps.org/schemas/sitemap/0.9"; private Uri _requestUrl; bool IHttpHandler.IsReusable => false; void IHttpHandler.ProcessRequest(HttpContext context) { _requestUrl = context.Request.Url; context.Response.ContentType = "text/xml"; context.Response.ContentEncoding = Encoding.UTF8; var provider = SiteMap.Provider; if (!(provider is ICmsSiteMapProvider)) { throw new NotSupportedException("Configured sitemap provider is not supported"); } var writer = XmlWriter.Create(context.Response.OutputStream, new XmlWriterSettings {Encoding = Encoding.UTF8, Indent = true}); writer.WriteStartDocument(); if (IsRootRequest(context.Request.RawUrl)) { var rootNodes = ((ICmsSiteMapProvider)provider).GetRootNodes(); if (rootNodes.Count > 1) { WriteSiteMapList(writer, rootNodes); } else { var rootNode = rootNodes.FirstOrDefault(); if (rootNode != null) { using (new DataScope(rootNode.Culture)) { WriteFullSiteMap(writer, provider); } } } } else { IPage rootPage = ExtractRootPageFromSiteMapUrl(context.Request.RawUrl); if(rootPage == null) { Write404(context.Response); return; } using(new SiteMapContext(rootPage)) { WriteFullSiteMap(writer, provider); } } writer.WriteEndDocument(); writer.Flush(); } private IPage ExtractRootPageFromSiteMapUrl(string relativeUrl) { Verify.That(relativeUrl.StartsWith(UrlUtils.PublicRootPath, StringComparison.OrdinalIgnoreCase), "Incorrect url prefix"); string[] requestParts = relativeUrl.Substring(UrlUtils.PublicRootPath.Length) .Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries); Verify.That(requestParts.Length > 0, "error parsing url"); string languageCode = requestParts[0]; string urlTitle = requestParts.Length > 2 ? requestParts[1] : string.Empty; CultureInfo culture = GetActiveCulture(languageCode); if(culture == null) { return null; } using(new DataScope(PublicationScope.Published, culture)) { foreach(Guid rootPageId in PageManager.GetChildrenIDs(Guid.Empty)) { var page = PageManager.GetPageById(rootPageId); if (page == null) continue; if(string.Equals(urlTitle, page.UrlTitle, StringComparison.OrdinalIgnoreCase)) { return page; } } } return null; } private void Write404(HttpResponse response) { response.Clear(); response.StatusCode = 404; } private CultureInfo GetActiveCulture(string languageCode) { return DataLocalizationFacade.ActiveLocalizationCultures .FirstOrDefault(culture => culture.Name.Equals(languageCode, StringComparison.OrdinalIgnoreCase)); } private bool MatchHostname(IHostnameBinding binding) { var host = _requestUrl.Host; if (binding.Hostname == host) { return true; } return binding.Aliases .Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries) .Any(alias => alias == host); } private void WriteSiteMapList(XmlWriter writer, IEnumerable rootNodes) { writer.WriteStartElement("sitemapindex", SiteMapNamespace); List bindings; using (var data = new DataConnection()) { bindings = data.Get().ToList(); } foreach (var node in rootNodes) { string urlTitle = null; using(new DataScope(PublicationScope.Published, node.Culture)) { IPage page = PageManager.GetPageById(node.Page.Id); if(page != null) { urlTitle = page.UrlTitle; } } IHostnameBinding binding = FindMatchingBinding(node, bindings); writer.WriteStartElement("sitemap"); writer.WriteStartElement("loc"); string hostnameUrl; if (binding == null || MatchHostname(binding)) { hostnameUrl = "{0}://{1}{2}".FormatWith( _requestUrl.Scheme, _requestUrl.Host, _requestUrl.IsDefaultPort ? string.Empty : ":" + _requestUrl.Port); } else { hostnameUrl = $"{(binding.EnforceHttps ? "https" : "http")}://{binding.Hostname}"; } writer.WriteString(hostnameUrl + "{0}/{1}{2}/sitemap.xml".FormatWith( UrlUtils.PublicRootPath, node.Culture, urlTitle.IsNullOrEmpty() ? string.Empty : "/" + urlTitle)); writer.WriteEndElement(); writer.WriteEndElement(); } writer.WriteEndElement(); } private IHostnameBinding FindMatchingBinding(CmsPageSiteMapNode sitemapNode, List bindings) { Guid homePageId = Guid.Parse(sitemapNode.Key); string cultureName = sitemapNode.Culture.Name; var bestMatch = FindMatch(bindings, homePageId, cultureName); if (bestMatch != null) { return bestMatch; } string defaultCulture = DataLocalizationFacade.DefaultLocalizationCulture.Name; var secondBestMatch = FindMatch(bindings, homePageId, defaultCulture); if (secondBestMatch != null) { return secondBestMatch; } return bindings.OrderBy(b => b.Hostname).FirstOrDefault(h => h.HomePageId == homePageId); } private IHostnameBinding FindMatch(IEnumerable bindings, Guid homePageId, string cultureName) { return bindings.Where(h => h.HomePageId == homePageId && h.Culture == cultureName) .SingleOrDefaultOrException("There are multiple hostname bindings refering to the same home page id '{0}' and the same culture '{1}'", homePageId, cultureName); } private void WriteFullSiteMap(XmlWriter writer, SiteMapProvider provider) { writer.WriteStartElement("urlset", SiteMapNamespace); WriteElement(writer, provider.RootNode, new HashSet()); writer.WriteEndElement(); } private bool IsRootRequest(string relativeUrl) { return string.Equals(relativeUrl, UrlUtils.PublicRootPath + "/sitemap.xml", StringComparison.OrdinalIgnoreCase); } private void WriteElement(XmlWriter writer, SiteMapNode node, HashSet alreadyVisitedNodes) { if (alreadyVisitedNodes.Contains(node.Key)) { Log.LogError(nameof(SiteMapHandler), $"Loop in sitemap nodes detected. Node key: '{node.Key}'"); return; } alreadyVisitedNodes.Add(node.Key); writer.WriteStartElement("url"); writer.WriteStartElement("loc"); writer.WriteString($"{_requestUrl.Scheme}://{_requestUrl.Host}{node.Url}"); writer.WriteEndElement(); if (node is ISchemaOrgSiteMapNode schemaOrgSiteMapNode) { var lastEdited = schemaOrgSiteMapNode.LastModified; writer.WriteStartElement("lastmod"); writer.WriteString(lastEdited.ToUniversalTime().ToString("u").Replace(" ", "T")); writer.WriteEndElement(); var changeFrequency = schemaOrgSiteMapNode.ChangeFrequency; if (changeFrequency.HasValue) { writer.WriteStartElement("changefreq"); writer.WriteString(changeFrequency.Value.ToString().ToLowerInvariant()); writer.WriteEndElement(); } var priority = schemaOrgSiteMapNode.Priority; if (priority.HasValue) { if (priority > 1 && priority < 10) { writer.WriteStartElement("priority"); writer.WriteString(((decimal)priority.Value / 10).ToString("0.0", CultureInfo.InvariantCulture)); writer.WriteEndElement(); } } } writer.WriteEndElement(); foreach (SiteMapNode child in node.ChildNodes) { WriteElement(writer, child, alreadyVisitedNodes); } } } } ================================================ FILE: Composite/AspNet/SiteMapNodeChangeFrequency.cs ================================================ namespace Composite.AspNet { /// /// ChangeFrequence of a SiteMapNode /// public enum SiteMapNodeChangeFrequency { /// Always = 0, /// Hourly = 1, /// Daily = 2, /// Weekly = 3, /// Monthly = 4, /// Yearly = 5, /// Never = 6 } } ================================================ FILE: Composite/AspNet/UserControlFunction.cs ================================================ using System.Collections.Generic; using System.Web.UI; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.FileBasedFunctionProvider; namespace Composite.AspNet { /// /// Base class for a UserControls that represents a C1 function /// public abstract class UserControlFunction : UserControl, IParameterWidgetsProvider { /// /// Gets the function description. /// public virtual string FunctionDescription { get { return string.Empty; } } /// /// Gets or sets Function Context Container /// public FunctionContextContainer FunctionContextContainer { get; set; } /// public virtual IDictionary GetParameterWidgets() { return null; } } } ================================================ FILE: Composite/AspNet/WebObjectActivator.cs ================================================ using System; using Microsoft.Extensions.DependencyInjection; namespace Composite.AspNet { internal class WebObjectActivator : IServiceProvider { private readonly IServiceProvider _inner; public WebObjectActivator(IServiceProvider inner) { _inner = inner; } public object GetService(Type serviceType) { var service = _inner.GetService(serviceType); // Multiple types from System.Web.dll have internal constructors // Ignoring those types to have a better debugging experience if (service == null && serviceType.Assembly != typeof(System.Web.IHttpModule).Assembly) { try { service = ActivatorUtilities.CreateInstance(_inner, serviceType); } catch (InvalidOperationException) { } } return service ?? Activator.CreateInstance(serviceType, true); } } } ================================================ FILE: Composite/C1Console/Actions/ActionEventSystemFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.C1Console.Security; using Composite.C1Console.Events; namespace Composite.C1Console.Actions { internal class BeforeActionEventArgs : EventArgs { public BeforeActionEventArgs(EntityToken entityToken, ActionToken actionToken) { this.EntityToken = entityToken; this.ActionToken = actionToken; } public EntityToken EntityToken { get; private set; } public ActionToken ActionToken { get; private set; } } internal class AfterActionEventArgs : EventArgs { public AfterActionEventArgs(EntityToken entityToken, ActionToken actionToken, FlowToken flowToken) { this.EntityToken = entityToken; this.ActionToken = actionToken; this.FlowToken = flowToken; } public EntityToken EntityToken { get; private set; } public ActionToken ActionToken { get; private set; } public FlowToken FlowToken { get; private set; } } internal static class ActionEventSystemFacade { internal delegate void OnBeforeActionExecutionDelegate(BeforeActionEventArgs actionEventArgs); internal delegate void OnAfterActionExecutionDelegate(AfterActionEventArgs actionEventArgs); private static OnBeforeActionExecutionDelegate _onBeforeActionExecutionDelegates = null; private static OnAfterActionExecutionDelegate _onAfterActionExecutionDelegates = null; static ActionEventSystemFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static void SubscribeToOnBeforeActionExecution(OnBeforeActionExecutionDelegate onBeforeActionExecutionDelegate) { Verify.ArgumentNotNull(onBeforeActionExecutionDelegate, "onBeforeActionExecutionDelegate"); _onBeforeActionExecutionDelegates += onBeforeActionExecutionDelegate; } public static void UnsubscribeToOnBeforeActionExecution(OnBeforeActionExecutionDelegate onBeforeActionExecutionDelegate) { Verify.ArgumentNotNull(onBeforeActionExecutionDelegate, "onBeforeActionExecutionDelegate"); _onBeforeActionExecutionDelegates -= onBeforeActionExecutionDelegate; } public static void SubscribeToOnAfterActionExecution(OnAfterActionExecutionDelegate onAfterActionExecutionDelegate) { Verify.ArgumentNotNull(onAfterActionExecutionDelegate, "onAfterActionExecutionDelegate"); _onAfterActionExecutionDelegates += onAfterActionExecutionDelegate; } public static void UnsubscribeToOnAfterActionExecution(OnAfterActionExecutionDelegate onAfterActionExecutionDelegate) { Verify.ArgumentNotNull(onAfterActionExecutionDelegate, "onAfterActionExecutionDelegate"); _onAfterActionExecutionDelegates -= onAfterActionExecutionDelegate; } internal static void FireOnBeforeActionExecution(EntityToken entityToken, ActionToken actionToken) { if (_onBeforeActionExecutionDelegates != null) { _onBeforeActionExecutionDelegates(new BeforeActionEventArgs(entityToken, actionToken)); } } internal static void FireOnAfterActionExecution(EntityToken entityToken, ActionToken actionToken, FlowToken flowToken) { if (_onAfterActionExecutionDelegates != null) { _onAfterActionExecutionDelegates(new AfterActionEventArgs(entityToken, actionToken, flowToken)); } } private static void Flush() { _onBeforeActionExecutionDelegates = null; _onAfterActionExecutionDelegates = null; } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } } } ================================================ FILE: Composite/C1Console/Actions/ActionExecutorAttribute.cs ================================================ using System; namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AttributeUsageAttribute(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public sealed class ActionExecutorAttribute : Attribute { private Type _actionExecutorType; /// public ActionExecutorAttribute(Type actionExecutorType) { _actionExecutorType = actionExecutorType; } /// public Type ActionExecutorType { get { return _actionExecutorType; } } } } ================================================ FILE: Composite/C1Console/Actions/ActionExecutorFacade.cs ================================================ //#warning REMARK THIS!!! //#define NO_SECURITY using System; using System.Collections.Generic; using System.Web; using Composite.C1Console.Actions.Foundation; using Composite.C1Console.Actions.Workflows; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.C1Console.Tasks; using Composite.C1Console.Workflow; using Composite.Core; namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ActionExecutorFacade { /// public static FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { return Execute(entityToken, actionToken, flowControllerServicesContainer, null); } /// public static FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer, TaskManagerEvent taskManagerEvent) { if (entityToken == null) throw new ArgumentNullException("entityToken"); if (actionToken == null) throw new ArgumentNullException("actionToken"); AddEntityTokenToContext(entityToken); string username = UserValidationFacade.GetUsername(); #if NO_SECURITY #else HookingFacade.EnsureInitialization(); IEnumerable userPermissionDefinitions = PermissionTypeFacade.GetUserPermissionDefinitions(username); IEnumerable userGroupPermissionDefinitions = PermissionTypeFacade.GetUserGroupPermissionDefinitions(username); SecurityResult securityResult = SecurityResolver.Resolve(UserValidationFacade.GetUserToken(), actionToken, entityToken, userPermissionDefinitions, userGroupPermissionDefinitions); if (securityResult != SecurityResult.Allowed && !(entityToken is SecurityViolationWorkflowEntityToken)) { return ExecuteSecurityViolation(actionToken, entityToken, flowControllerServicesContainer); } #endif bool ignoreLocking = actionToken.IsIgnoreEntityTokenLocking(); if (!ignoreLocking && ActionLockingFacade.IsLocked(entityToken)) { return ExecuteEntityTokenLocked(actionToken, entityToken, flowControllerServicesContainer); } IActionExecutor actionExecutor = ActionExecutorCache.GetActionExecutor(actionToken); ActionEventSystemFacade.FireOnBeforeActionExecution(entityToken, actionToken); FlowToken flowToken; using (TaskContainer taskContainer = TaskManagerFacade.CreateNewTasks(entityToken, actionToken, taskManagerEvent)) { ITaskManagerFlowControllerService taskManagerService = null; if (flowControllerServicesContainer.GetService(typeof(ITaskManagerFlowControllerService)) == null) { taskManagerService = new TaskManagerFlowControllerService(taskContainer); flowControllerServicesContainer.AddService(taskManagerService); } try { if (actionExecutor is IActionExecutorSerializedParameters) { string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken); string serializedActionToken = ActionTokenSerializer.Serialize(actionToken); flowToken = Execute(actionExecutor as IActionExecutorSerializedParameters, serializedEntityToken, serializedActionToken, actionToken, flowControllerServicesContainer); } else { flowToken = Execute(actionExecutor, entityToken, actionToken, flowControllerServicesContainer); } } finally { if (taskManagerService != null) { flowControllerServicesContainer.RemoveService(taskManagerService); } } taskContainer.SetOnIdleTaskManagerEvent(new FlowTaskManagerEvent(flowToken)); taskContainer.UpdateTasksWithFlowToken(flowToken); taskContainer.SaveTasks(); } ActionEventSystemFacade.FireOnAfterActionExecution(entityToken, actionToken, flowToken); IManagementConsoleMessageService managementConsoleMessageService = flowControllerServicesContainer .GetService(); if (managementConsoleMessageService != null) { FlowControllerFacade.RegisterNewFlowInformation(flowToken, entityToken, actionToken, managementConsoleMessageService.CurrentConsoleId); } else { Log.LogWarning(nameof(ActionExecutorFacade), "Missing ManagementConsoleMessageService, can not register the flow"); } return flowToken; } internal const string HttpContextItem_EntityToken = "EntityToken"; private static void AddEntityTokenToContext(EntityToken entityToken) { var httpContext = HttpContext.Current; if (httpContext == null) return; httpContext.Items[HttpContextItem_EntityToken] = entityToken; } /// public static FlowToken ExecuteEntityTokenLocked(ActionToken lockedActionToken, EntityToken lockedEntityToken, FlowControllerServicesContainer flowControllerServicesContainer) { EntityToken entityToken = new EntityTokenLockedEntityToken( ActionLockingFacade.LockedBy(lockedEntityToken), ActionTokenSerializer.Serialize(lockedActionToken), EntityTokenSerializer.Serialize(lockedEntityToken) ); WorkflowActionToken actionToken = new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Actions.Workflows.EntityTokenLockedWorkflow")); return Execute(entityToken, actionToken, flowControllerServicesContainer); } /// public static FlowToken ExecuteSecurityViolation(ActionToken actionToken, EntityToken entityToken, FlowControllerServicesContainer flowControllerServicesContainer) { EntityToken newEntityToken = new SecurityViolationWorkflowEntityToken(); WorkflowActionToken newActionToken = new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Actions.Workflows.SecurityViolationWorkflow")); return Execute(newEntityToken, newActionToken, flowControllerServicesContainer); } private static FlowToken Execute(IActionExecutorSerializedParameters actionExecutor, string serializedEntityToken, string serializedActionToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { FlowToken result = actionExecutor.Execute(serializedEntityToken, serializedActionToken, actionToken, flowControllerServicesContainer); return result ?? new NullFlowToken(); } private static FlowToken Execute(IActionExecutor actionExecutor, EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { FlowToken result = actionExecutor.Execute(entityToken, actionToken, flowControllerServicesContainer); return result ?? new NullFlowToken(); } } } ================================================ FILE: Composite/C1Console/Actions/ActionLockingException.cs ================================================ using System; namespace Composite.C1Console.Actions { internal sealed class ActionLockingException : Exception { public ActionLockingException(string message) : base(message) { } } } ================================================ FILE: Composite/C1Console/Actions/ActionLockingFacade.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using Composite.C1Console.Security; using Composite.Core; using Composite.Data; using Composite.Data.Types; namespace Composite.C1Console.Actions { /// /// /// [EditorBrowsable(EditorBrowsableState.Never)] public static class ActionLockingFacade { private static readonly string LogTitle = typeof(ActionLockingFacade).Name; private static Dictionary _lockingInformations = null; private static readonly object _lock = new object(); private static readonly IFormatter _ownerIdFormatter = new BinaryFormatter(); private static void EnsureInitialization() { using (GlobalInitializerFacade.CoreIsInitializedScope) { lock (_lock) { if (_lockingInformations == null) { DoInitialize(); } } } } /// /// /// /// /// Should be serializable public static void AcquireLock(EntityToken entityToken, object ownerId) { using (GlobalInitializerFacade.CoreIsInitializedScope) { EnsureInitialization(); AddLockingInformation(entityToken, ownerId); } } /// /// /// /// /// Should be serializable public static void ChangeLockOwner(EntityToken entityToken, object newOwnerId) { using (GlobalInitializerFacade.CoreIsInitializedScope) { EnsureInitialization(); UpdateLockingInformation(entityToken, newOwnerId); } } /// /// /// /// /// Should be serializable public static void ReleaseLock(EntityToken entityToken, object ownerId) { using (GlobalInitializerFacade.CoreIsInitializedScope) { EnsureInitialization(); string lockKey = GetLockKey(entityToken); RemoveLockingInformation(lockKey, ownerId); } } /// /// /// /// Should be serializable public static void ReleaseAllLocks(object ownerId) { using (GlobalInitializerFacade.CoreIsInitializedScope) { EnsureInitialization(); List lockKeys = (from li in _lockingInformations where object.Equals(li.Value.OwnerId, ownerId) select li.Key).ToList(); foreach (string lockKey in lockKeys) { RemoveLockingInformation(lockKey, ownerId); } } } /// /// /// /// Entity token to check if it is locked. /// True if the given entityToken is locked public static bool IsLocked(EntityToken entityToken) { using (GlobalInitializerFacade.CoreIsInitializedScope) { EnsureInitialization(); string lockKey = GetLockKey(entityToken); return _lockingInformations.ContainsKey(lockKey); } } /// /// /// /// Entity token to check if it is locked. /// Returns the name of the user who has locked the given entity token. Null if no one has a lock on it. public static string LockedBy(EntityToken entityToken) { using (GlobalInitializerFacade.CoreIsInitializedScope) { EnsureInitialization(); string lockKey = GetLockKey(entityToken); LockingInformation lockingInformation; if (!_lockingInformations.TryGetValue(lockKey, out lockingInformation)) { return null; } return lockingInformation.Username; } } /// /// /// public static IDisposable Locker { get { return new LockerToken(); } } internal static void ReleaseAll(string username) { using (GlobalInitializerFacade.CoreIsInitializedScope) { EnsureInitialization(); List> itemsToRemove = (from info in _lockingInformations where info.Value.Username == username select new Tuple(info.Key, info.Value.OwnerId)).ToList(); foreach (var item in itemsToRemove) { RemoveLockingInformation(item.Item1, item.Item2); } } } /// /// This is a "non-safe" release of a lock. For safe use, use ReleaseLock /// /// public static void RemoveLock(EntityToken entityToken) { using (GlobalInitializerFacade.CoreIsInitializedScope) { EnsureInitialization(); string lockKey = GetLockKey(entityToken); if (_lockingInformations.ContainsKey(lockKey)) { RemoveLockingInformation(lockKey, _lockingInformations[lockKey].OwnerId); } } } private static void DoInitialize() { using (GlobalInitializerFacade.CoreIsInitializedScope) { Log.LogVerbose("RGB(194, 252, 131)ActionLockingFacade", "----------========== Initializing EntityToken Locks ==========----------"); int startTime = Environment.TickCount; if (_lockingInformations == null) { _lockingInformations = new Dictionary(); LoadLockingInformation(); } int endTime = Environment.TickCount; Log.LogVerbose("RGB(194, 252, 131)ActionLockingFacade", string.Format("----------========== Done initializing EntityToken Locks ({0} ms ) ==========----------", endTime - startTime)); } } private static void LoadLockingInformation() { List lockingInformations = DataFacade.GetData().ToList(); List lockingInformationsToDelete = new List(); foreach (ILockingInformation lockingInformation in lockingInformations) { object ownerId = DeserializeOwnerId(lockingInformation.SerializedOwnerId); LockingInformation li = new LockingInformation { OwnerId = ownerId, Username = lockingInformation.Username }; try { _lockingInformations.Add(lockingInformation.LockKey, li); } catch (Exception) { // Removing broken locking information (Ex. dead data source ids) /MRJ lockingInformationsToDelete.Add(lockingInformation.Id); } } foreach (Guid id in lockingInformationsToDelete) { DataFacade.Delete(f => f.Id == id); } } private static void AddLockingInformation(EntityToken entityToken, object ownerId) { string lockKey = GetLockKey(entityToken); LockingInformation lockingInformation; if (_lockingInformations.TryGetValue(lockKey, out lockingInformation)) { if (object.Equals(lockingInformation.OwnerId, ownerId)) { // NO OP: The owner may acquire a lock multiple times return; } // This will only happen if an entity token subclass is not rightly implemented throw new ActionLockingException("This item is used by another user, try again."); } lockingInformation = new LockingInformation { Username = UserValidationFacade.GetUsername(), OwnerId = ownerId }; string serializedOwnerId = SerializeOwnerId(lockingInformation.OwnerId); ILockingInformation li = DataFacade.BuildNew(); li.Id = Guid.NewGuid(); li.LockKey = lockKey; li.SerializedOwnerId = serializedOwnerId; li.Username = lockingInformation.Username; DataFacade.AddNew(li); _lockingInformations.Add(lockKey, lockingInformation); } private static void UpdateLockingInformation(EntityToken entityToken, object newOwnerId) { string lockKey = GetLockKey(entityToken); LockingInformation lockingInformation; if (!_lockingInformations.TryGetValue(lockKey, out lockingInformation)) throw new InvalidOperationException("LockingInformation record missing"); ILockingInformation lockingInformationDataItem = DataFacade.GetData(). Single(f => f.LockKey == lockKey); lockingInformationDataItem.SerializedOwnerId = SerializeOwnerId(newOwnerId); DataFacade.Update(lockingInformationDataItem); lockingInformation.OwnerId = newOwnerId; } private static void RemoveLockingInformation(string lockKey, object ownerId) { LockingInformation lockingInformation; if (!_lockingInformations.TryGetValue(lockKey, out lockingInformation)) return; if (Equals(lockingInformation.OwnerId, ownerId)) { _lockingInformations.Remove(lockKey); } string serializedOwnerId = SerializeOwnerId(ownerId); ILockingInformation lockingInformationDataItem = DataFacade.GetData() .SingleOrDefault(f => f.LockKey == lockKey && f.SerializedOwnerId == serializedOwnerId); if (lockingInformationDataItem == null) { Log.LogWarning(LogTitle, "Failed to find entity token lock. EntityToken: " + lockKey); return; } DataFacade.Delete(lockingInformationDataItem); } private static string SerializeOwnerId(object ownerId) { using (MemoryStream ms = new MemoryStream()) { _ownerIdFormatter.Serialize(ms, ownerId); byte[] bytes = ms.ToArray(); string serializedOwnerId = Convert.ToBase64String(bytes); return serializedOwnerId; } } internal static object DeserializeOwnerId(string serializedOwnerId) { byte[] bytes = Convert.FromBase64String(serializedOwnerId); using (MemoryStream ms = new MemoryStream(bytes)) { return _ownerIdFormatter.Deserialize(ms); } } private sealed class LockingInformation { public string Username { get; set; } public object OwnerId { get; set; } } private static void Lock() { bool success = false; Monitor.TryEnter(_lock, TimeSpan.FromMinutes(1), ref success); if (!success) { throw new InvalidOperationException("Failed to obtain a required resource lock. Aborting to avoid system deadlocks."); } } private static void Exit() { Monitor.Exit(_lock); } private static string GetLockKey(EntityToken entityToken) { string lockKey = entityToken.Serialize(); if (entityToken is DataEntityToken) { var dataEntityToken = entityToken as DataEntityToken; if (dataEntityToken.DataSourceId != null && dataEntityToken.DataSourceId.LocaleScope != null) { lockKey = lockKey + dataEntityToken.DataSourceId.LocaleScope.ToString(); } } return lockKey; } private sealed class LockerToken : IDisposable { internal LockerToken() { using (GlobalInitializerFacade.CoreNotLockedScope) { ActionLockingFacade.Lock(); } } public void Dispose() { ActionLockingFacade.Exit(); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~LockerToken() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } } ================================================ FILE: Composite/C1Console/Actions/ActionResult.cs ================================================ namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ActionResult { /// public ActionResultResponseType ResponseType { get; set; } /// public string Url { get; set; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum ActionResultResponseType { /// None, /// OpenDocument, /// OpenModalDialog } } ================================================ FILE: Composite/C1Console/Actions/AddNewTreeRefresher.cs ================================================ using System; using Composite.C1Console.Events; using Composite.Core; using Composite.C1Console.Security; namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class AddNewTreeRefresher { private readonly FlowControllerServicesContainer _flowControllerServicesContainer; private readonly RelationshipGraph _beforeGraph; private RelationshipGraph _afterGraph; private bool _postRefreshMessegesCalled; /// public AddNewTreeRefresher(EntityToken parentEntityToken, FlowControllerServicesContainer flowControllerServicesContainer) { Verify.ArgumentNotNull(parentEntityToken, "parentEntityToken"); Verify.ArgumentNotNull(flowControllerServicesContainer, "flowControllerServicesContainer"); _beforeGraph = new RelationshipGraph(parentEntityToken, RelationshipGraphSearchOption.Both, false, false); _flowControllerServicesContainer = flowControllerServicesContainer; } /// [Obsolete("Use PostRefreshMessages instead")] public void PostRefreshMesseges(EntityToken newChildEntityToken) { PostRefreshMessages(newChildEntityToken); } /// public void PostRefreshMessages(EntityToken newChildEntityToken) { Verify.ArgumentNotNull(newChildEntityToken, "newChildEntityToken"); Verify.That(!_postRefreshMessegesCalled, "Only one PostRefreshMessages call is allowed"); _postRefreshMessegesCalled = true; _afterGraph = new RelationshipGraph(newChildEntityToken, RelationshipGraphSearchOption.Both, false, false); IManagementConsoleMessageService messageService = _flowControllerServicesContainer.GetService(); foreach (EntityToken entityToken in RefreshBeforeAfterEntityTokenFinder.FindEntityTokens(_beforeGraph, _afterGraph)) { messageService.RefreshTreeSection(entityToken); Log.LogVerbose("AddNewTreeRefresher", $"Refreshing EntityToken: Type = {entityToken.Type}, Source = {entityToken.Source}, Id = {entityToken.Id}, EntityTokenType = {entityToken.GetType()}"); } } } } ================================================ FILE: Composite/C1Console/Actions/Data/ActionIdentifier.cs ================================================ using System; using System.Collections.Generic; using System.Text; using Composite.C1Console.Security; using Composite.Core.Serialization; namespace Composite.C1Console.Actions.Data { /// /// A container for Action Types /// public class ActionIdentifier { private const string ActionIdentifierKey = "_ActionIdentifier_"; private readonly string _value; private ActionIdentifier(string identifier) { _value = identifier; } /// public static ActionIdentifier Edit => new ActionIdentifier("Edit"); /// public static ActionIdentifier Add => new ActionIdentifier("Add"); /// public static ActionIdentifier Delete => new ActionIdentifier("Delete"); /// public static ActionIdentifier SendToDraft => new ActionIdentifier("SendToDraft"); /// public static ActionIdentifier SendForApproval => new ActionIdentifier("SendForApproval"); /// public static ActionIdentifier SendForPublication => new ActionIdentifier("SendForPublication"); /// public static ActionIdentifier Publish => new ActionIdentifier("Publish"); /// public static ActionIdentifier Unpublish => new ActionIdentifier("Unpublish"); /// public static ActionIdentifier Undo => new ActionIdentifier("Undo"); /// public static ActionIdentifier Duplicate => new ActionIdentifier("Duplicate"); /// public IEnumerable Permissions() { if (this == Add) { yield return PermissionType.Add; } if (this == Edit) { yield return PermissionType.Edit; } if (this == Delete) { yield return PermissionType.Delete; } if (this == Publish) { yield return PermissionType.Publish; } if (this == Unpublish) { yield return PermissionType.Publish; } if (this == SendForApproval) { yield return PermissionType.Edit; } if (this == SendForPublication) { yield return PermissionType.Approve; } if (this == SendToDraft) { yield return PermissionType.Edit; yield return PermissionType.Approve; yield return PermissionType.Publish; } if (this == Undo) { yield return PermissionType.Edit; } if (this == Duplicate) { yield return PermissionType.Add; } } /// public override int GetHashCode() { return _value.GetHashCode(); } /// public override bool Equals(object obj) { return Equals(obj as ActionIdentifier); } /// public bool Equals(ActionIdentifier obj) { return obj == this; } /// public static bool operator ==(ActionIdentifier a1, ActionIdentifier a2) { return a1?._value == a2?._value; } /// public static bool operator !=(ActionIdentifier a1, ActionIdentifier a2) { return !(a1 == a2); } /// public string Serialize() { var stringBuilder = new StringBuilder(); StringConversionServices.SerializeKeyValuePair(stringBuilder, ActionIdentifierKey, _value); return stringBuilder.ToString(); } /// public static ActionIdentifier Deserialize(string serializedData) { Dictionary dic = StringConversionServices.ParseKeyValueCollection(serializedData); if (!dic.TryGetValue(ActionIdentifierKey, out string value)) { throw new ArgumentException($"The serialized data does not contain '{ActionIdentifierKey}'", nameof(serializedData)); } string serializedType = StringConversionServices.DeserializeValueString(value); return new ActionIdentifier(serializedType); } /// public override string ToString() => _value; } } ================================================ FILE: Composite/C1Console/Actions/Data/DataActionTokenRegisterHandler.cs ================================================ using System; using Composite.C1Console.Security; using Composite.Data; namespace Composite.C1Console.Actions.Data { abstract class DataActionTokenRegisterHandler { public abstract ActionToken GetActionToken(IData data); public abstract bool Check(Type type,IData data, ActionIdentifier actionIdentifier); } class DataActionTokenRegisterHandler : DataActionTokenRegisterHandler where T : IData { private readonly Func _actionTokenFunc; private readonly ActionIdentifier _actionIdentifier; private readonly Func _actionValidPredicate; public DataActionTokenRegisterHandler(ActionIdentifier actionIdentifier, Func dataActionToken) { _actionTokenFunc = dataActionToken; _actionIdentifier = actionIdentifier; } public DataActionTokenRegisterHandler(ActionIdentifier actionIdentifier, Func dataActionToken, Func actionValidPredicate) : this(actionIdentifier, dataActionToken) { _actionValidPredicate = actionValidPredicate; } public override ActionToken GetActionToken(IData data) { return _actionTokenFunc((T)data); } public override bool Check(Type type, IData data, ActionIdentifier actionIdentifier) { if (_actionIdentifier == actionIdentifier) { if (type == typeof(T)) { if (_actionValidPredicate == null || _actionValidPredicate((T) data)) { return true; } } } return false; } } } ================================================ FILE: Composite/C1Console/Actions/Data/DataActionTokenResolver.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Security; using Composite.Data; namespace Composite.C1Console.Actions.Data { /// public class DataActionTokenResolver { static List _defaultActions; static List _conditionalActions; /// /// Use this to assign a deafult action to a certain data type /// /// /// /// public void RegisterDefault(ActionIdentifier actionIdentifier, Func dataActionToken) where T : IData { Verify.ArgumentNotNull(actionIdentifier, nameof(actionIdentifier)); Verify.ArgumentNotNull(dataActionToken, nameof(dataActionToken)); if (_defaultActions == null) { _defaultActions = new List(); } _defaultActions.Add(new DataActionTokenRegisterHandler(actionIdentifier, dataActionToken)); } /// /// Use this to assaign an action to a certain data type if a certain condition met /// /// /// /// /// public void RegisterConditional(ActionIdentifier actionIdentifier, Func actionValidPredicate, Func dataActionToken) where T : IData { Verify.ArgumentNotNull(actionIdentifier, nameof(actionIdentifier)); Verify.ArgumentNotNull(actionValidPredicate, nameof(actionValidPredicate)); Verify.ArgumentNotNull(dataActionToken, nameof(dataActionToken)); if (_conditionalActions == null) { _conditionalActions = new List(); } _conditionalActions.Add(new DataActionTokenRegisterHandler(actionIdentifier, dataActionToken, actionValidPredicate)); } /// public ActionToken Resolve(IData data, ActionIdentifier actionIdentifier) { var interfaces = GetOrderedInterfaces(data.DataSourceId.InterfaceType); foreach (var type in interfaces) { var conditionalAction = _conditionalActions?.FirstOrDefault(f => f.Check(type, data, actionIdentifier)); if (conditionalAction != null) { var actionToken = conditionalAction.GetActionToken(data); if (actionToken == null) { throw new InvalidOperationException($"Conditional action token is null. Type: '{type.FullName}', action type: '{conditionalAction.GetType().FullName}'"); } return actionToken; } } return ResolveDefault(data, actionIdentifier); } /// /// Resolves a default action of the given type for a given data item /// /// The data item /// The action identifier /// public ActionToken ResolveDefault(IData data, ActionIdentifier actionIdentifier) { var interfaceType = data.DataSourceId.InterfaceType; var interfaces = GetOrderedInterfaces(interfaceType); foreach (var type in interfaces) { var defaultAction = _defaultActions?.LastOrDefault(f => f.Check(type, data, actionIdentifier)); if (defaultAction != null) { var actionToken = defaultAction.GetActionToken(data); if (actionToken == null) { throw new InvalidOperationException($"Default action token is null. Type: '{type.FullName}', default action type: '{defaultAction.GetType().FullName}'"); } return actionToken; } } throw new InvalidOperationException($"No default action token is found. Searched for type: '{interfaceType}', Registered types: '{string.Join(", ",interfaces.Select(_ => _.FullName))}'"); } private static List GetOrderedInterfaces(Type dataType) { var result = new List { dataType }; result.AddRange(dataType.GetInterfaces().OrderByDescending(f => f.GetInterfaces().Length)); return result; } } } ================================================ FILE: Composite/C1Console/Actions/Data/DataActionTokenResolverFacade.cs ================================================ using System; using Composite.C1Console.Security; using Composite.Core; using Composite.Data; using Microsoft.Extensions.DependencyInjection; namespace Composite.C1Console.Actions.Data { /// /// Use this to access the service that has DataActionTokenResolver to register your actions /// public static class DataActionTokenResolverFacade { /// public static ActionToken Resolve(IData data, ActionIdentifier actionIdentifier) { return GetDataActionTokenResolverService().Resolve(data, actionIdentifier); } /// public static ActionToken ResolveDefault(IData data, ActionIdentifier actionIdentifier) { return GetDataActionTokenResolverService().ResolveDefault(data, actionIdentifier); } /// /// Use this to assign a deafult action to a certain data type /// /// /// /// public static void RegisterDefault(ActionIdentifier actionIdentifier, Func dataActionToken) where T : IData { GetDataActionTokenResolverService().RegisterDefault(actionIdentifier, dataActionToken); } /// /// Use this to assaign an action to a certain data type if a certain condition met /// /// /// /// /// public static void RegisterConditional(ActionIdentifier actionIdentifier, Func actionValidPredicate, Func dataActionToken) where T : IData { GetDataActionTokenResolverService().RegisterConditional(actionIdentifier, actionValidPredicate, dataActionToken); } private static DataActionTokenResolver GetDataActionTokenResolverService() { return ServiceLocator.GetService(); } } } ================================================ FILE: Composite/C1Console/Actions/Data/DataActionTokenResolverRegistry.cs ================================================ using Microsoft.Extensions.DependencyInjection; namespace Composite.C1Console.Actions.Data { internal static class DataActionTokenResolverRegistry { internal static void AddDataActionTokenResolver(this IServiceCollection serviceCollection) { serviceCollection.Add(ServiceDescriptor.Singleton(new DataActionTokenResolver())); } } } ================================================ FILE: Composite/C1Console/Actions/Data/ProxyDataActionExecuter.cs ================================================ using System; using Composite.C1Console.Security; using Composite.Core; using Composite.Data; namespace Composite.C1Console.Actions.Data { /// public class ProxyDataActionExecuter : IActionExecutorSerializedParameters { /// public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { return Execute(EntityTokenSerializer.Serialize(entityToken), ActionTokenSerializer.Serialize(actionToken), actionToken, flowControllerServicesContainer); } /// public FlowToken Execute(string serializedEntityToken, string serializedActionToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { DataEntityToken dataEntityToken = (DataEntityToken)EntityTokenSerializer.Deserialize(serializedEntityToken); IData data = dataEntityToken.Data; Verify.IsNotNull(data, "Failed to get the data from an entity token"); var actionIdentifier = ((ProxyDataActionToken)actionToken).ActionIdentifier; var action = DataActionTokenResolverFacade.Resolve(data, actionIdentifier); if (action == null) { throw new InvalidOperationException($"Failed to resolve action '{actionToken?.ToString() ?? "null"}'"); } return ActionExecutorFacade.Execute(dataEntityToken, action, flowControllerServicesContainer); } } } ================================================ FILE: Composite/C1Console/Actions/Data/ProxyDataActionToken.cs ================================================ using System; using System.Collections.Generic; using System.Text; using Composite.C1Console.Security; using Composite.Core.Serialization; namespace Composite.C1Console.Actions.Data { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ActionExecutor(typeof(ProxyDataActionExecuter))] public class ProxyDataActionToken : ActionToken { private readonly ActionIdentifier _actionIdentifier; private readonly IEnumerable _permissionTypes; /// public ProxyDataActionToken( ActionIdentifier actionIdentifier) { _actionIdentifier = actionIdentifier; } /// public ProxyDataActionToken(ActionIdentifier actionIdentifier, IEnumerable permissionTypes) : this(actionIdentifier) { _permissionTypes = permissionTypes; } /// public ActionIdentifier ActionIdentifier => _actionIdentifier; /// public bool DoIgnoreEntityTokenLocking { get; set;} /// public override bool IgnoreEntityTokenLocking => DoIgnoreEntityTokenLocking; /// public override IEnumerable PermissionTypes => _permissionTypes ?? _actionIdentifier.Permissions(); /// public override string Serialize() { StringBuilder stringBuilder = new StringBuilder(); StringConversionServices.SerializeKeyValuePair(stringBuilder, "_ActionIdentifier_", ActionIdentifier.Serialize()); StringConversionServices.SerializeKeyValuePair(stringBuilder, "_PermissionTypes_", PermissionTypes.SerializePermissionTypes()); StringConversionServices.SerializeKeyValuePair(stringBuilder, "_DoIgnoreEntityTokenLocking_", DoIgnoreEntityTokenLocking); return stringBuilder.ToString(); } /// public static ActionToken Deserialize(string serializedData) { Dictionary dic = StringConversionServices.ParseKeyValueCollection(serializedData); if (!dic.ContainsKey("_ActionIdentifier_") || !dic.ContainsKey("_PermissionTypes_") ) { throw new ArgumentException($"The {nameof(serializedData)} is not a serialized {nameof(ProxyDataActionToken)}", nameof(serializedData)); } string serializedType = StringConversionServices.DeserializeValueString(dic["_ActionIdentifier_"]); string permissionTypesString = StringConversionServices.DeserializeValueString(dic["_PermissionTypes_"]); bool doIgnoreEntityTokenLocking = StringConversionServices.DeserializeValueBool(dic["_DoIgnoreEntityTokenLocking_"]); var result = new ProxyDataActionToken(ActionIdentifier.Deserialize(serializedType), permissionTypesString.DesrializePermissionTypes()) {DoIgnoreEntityTokenLocking = doIgnoreEntityTokenLocking}; return result; } } } ================================================ FILE: Composite/C1Console/Actions/DeleteTreeRefresher.cs ================================================ using System; using Composite.C1Console.Events; using Composite.Core.Logging; using Composite.C1Console.Security; using Composite.Core; namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DeleteTreeRefresher { private readonly RelationshipGraph _beforeGraph; private readonly FlowControllerServicesContainer _flowControllerServicesContainer; private bool _postRefreshMessagesCalled; /// public DeleteTreeRefresher(EntityToken beforeDeleteEntityToken, FlowControllerServicesContainer flowControllerServicesContainer) { Verify.ArgumentNotNull(beforeDeleteEntityToken, "beforeDeleteEntityToken"); Verify.ArgumentNotNull(flowControllerServicesContainer, "flowControllerServicesContainer"); _beforeGraph = new RelationshipGraph(beforeDeleteEntityToken, RelationshipGraphSearchOption.Both); _flowControllerServicesContainer = flowControllerServicesContainer; } /// [Obsolete("Use PostRefreshMessages instead")] public void PostRefreshMesseges() { PostRefreshMessages(false); } /// [Obsolete("Use PostRefreshMessages instead")] public void PostRefreshMesseges(bool skipBeforeDeleteEntityToken) { PostRefreshMessages(skipBeforeDeleteEntityToken); } /// public void PostRefreshMessages(bool skipBeforeDeleteEntityToken = false) { if (_postRefreshMessagesCalled) { throw new InvalidOperationException("Only one PostRefreshMessages call is allowed"); } _postRefreshMessagesCalled = true; IManagementConsoleMessageService messageService = _flowControllerServicesContainer.GetService(); foreach (EntityToken entityToken in RefreshDeleteEntityTokenFinder.FindEntityTokens(_beforeGraph, skipBeforeDeleteEntityToken)) { messageService.RefreshTreeSection(entityToken); } } } } ================================================ FILE: Composite/C1Console/Actions/DuplicateActionToken.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text.RegularExpressions; using Composite.C1Console.Security; using Composite.C1Console.Events; using Composite.C1Console.Trees; using Composite.C1Console.Users; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes.Foundation; using Composite.Data.Hierarchy; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.Types; using Composite.Plugins.Commands.ConsoleCommandHandlers; namespace Composite.C1Console.Actions { /// /// Action to duplicate data /// [ActionExecutor(typeof(DuplicateActionExecuter))] public sealed class DuplicateActionToken : ActionToken { /// public override IEnumerable PermissionTypes => new[] { PermissionType.Add }; /// public static ActionToken Deserialize(string serializedData) { return new DuplicateActionToken(); } } internal class DuplicateActionExecuter : IActionExecutor { /// public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { return Execute(EntityTokenSerializer.Serialize(entityToken), ActionTokenSerializer.Serialize(actionToken), actionToken, flowControllerServicesContainer); } /// public FlowToken Execute(string serializedEntityToken, string serializedActionToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { var dataEntityToken = (DataEntityToken)EntityTokenSerializer.Deserialize(serializedEntityToken); var data = dataEntityToken.Data; Verify.IsNotNull(data, "Failed to get the data from an entity token"); using (new DataScope(DataScopeIdentifier.Administrated)) { var treeRefresher = new AddNewTreeRefresher(dataEntityToken,flowControllerServicesContainer); var newData = (IData)StaticReflection.GetGenericMethodInfo(() => CloneData((IData)null)) .MakeGenericMethod(data.DataSourceId.InterfaceType).Invoke(this, new object[] { data }); var consoleId = flowControllerServicesContainer.GetService().CurrentConsoleId; ConsoleCommandHelper.SelectConsoleElementWithoutPerspectiveChange(consoleId, newData.GetDataEntityToken()); treeRefresher.PostRefreshMessages(dataEntityToken); } return null; } private static readonly Func IsRootPage = f => f.GetParent() == null; private IData CloneData(T data) where T : class, IData { IData newdata = DataFacade.BuildNew(); var dataProperties = typeof(T).GetPropertiesRecursively(); foreach (var propertyInfo in dataProperties.Where(f => f.CanWrite)) { if (typeof(T).GetPhysicalKeyProperties().Contains(propertyInfo) && propertyInfo.PropertyType == typeof(Guid)) { propertyInfo.SetValue(newdata, Guid.NewGuid()); } else { propertyInfo.SetValue(newdata, propertyInfo.GetValue(data)); } } var page = data as IPage; if (page != null) { if (IsRootPage(page)) { SetNewValue(page, newdata, dataProperties.First(p => p.Name == nameof(IPage.Title))); } else if (!SetNewValue(page, newdata, dataProperties.First(p => p.Name == nameof(IPage.MenuTitle)))) { SetNewValue(page, newdata, dataProperties.First(p => p.Name == nameof(IPage.Title))); } SetNewValue(page, newdata, dataProperties.First(p => p.Name == nameof(IPage.UrlTitle)), isUrl:true); PageInsertPosition.After(page.Id).CreatePageStructure(newdata as IPage, page.GetParentId()); } else { var labelProperty = typeof(T).GetProperty( DynamicTypeReflectionFacade.GetLabelPropertyName(typeof(T))); if (labelProperty != null && labelProperty.PropertyType == typeof(string)) { SetNewValue(data, newdata, labelProperty); } } if (newdata is IPublishControlled) { (newdata as IPublishControlled).PublicationStatus = GenericPublishProcessController.Draft; } if (newdata is ILocalizedControlled) { (newdata as ILocalizedControlled).SourceCultureName = UserSettings.ActiveLocaleCultureInfo.Name; } newdata = DataFacade.AddNew(newdata); if (data is IPage) { CopyPageData(data as IPage, newdata as IPage); } return newdata; } private bool SetNewValue( IData sourceData, IData newData, PropertyInfo property ,bool isUrl=false) where T : class, IData { var value = isUrl? (string)property.GetValue(sourceData): GetStringWithoutCopyOf((string) property.GetValue(sourceData)); var storeFieldType = property.GetCustomAttributes(typeof(StoreFieldTypeAttribute),true).FirstOrDefault(); var maxLength = (storeFieldType as StoreFieldTypeAttribute)?.StoreFieldType.MaximumLength; if (!isUrl && value.IsNullOrEmpty()) return false; for (var count = 1;; count++) { var str = GenerateCopyOfName(value, count, maxLength, isUrl); if (DataFacade.GetData().Any(GetLambda(property, str))) continue; property.SetValue(newData, str); break; } return true; } private Expression> GetLambda(PropertyInfo labelProperty, string labelValue) { var p = Expression.Parameter(typeof(T)); var propertry = Expression.Property(p, labelProperty.Name); var body = Expression.Equal(propertry, Expression.Constant(labelValue)); return Expression.Lambda>(body, p); } private static string GetStringWithoutCopyOf(string source) { Regex regexInstance = new Regex(StringResourceSystemFacade.GetString("Composite.Management", "Duplication.Text").Replace("{0}","").Replace("{count}", @"(\(.*\))*")); return regexInstance.Replace(source, ""); } private string GenerateCopyOfName(string source, int count, int? maxLength, bool isUrl=false ) { if (isUrl) { if (!source.IsNullOrEmpty()) { return string.Join("-", source, count.ToString()); } var numberInString = count == 1 ? "" : count.ToString(); return $"Copy{numberInString}-of"; } Func copyText = i => StringResourceSystemFacade.GetString("Composite.Management", "Duplication.Text") .Replace("{count}", i == 1 ? "" : $"({i})"); var result = string.Format(copyText(count), source); return (maxLength!=null)?result.Substring(0, Math.Min(result.Length, maxLength.Value)):result; } internal void CopyPageData(IPage sourcePage, IPage newPage) { Guid sourcePageId = sourcePage.Id; Guid newPageId = newPage.Id; Guid sourceVersionId = sourcePage.VersionId; Guid newVersionId = newPage.VersionId; var newPlaceholders = new List(); var placeholders = DataFacade.GetData(false) .Where(ph => ph.PageId == sourcePageId && ph.VersionId == sourceVersionId) .ToList(); foreach (var placeholderContent in placeholders) { var newPlaceholder = DataFacade.BuildNew(); newPlaceholder.PageId = newPageId; newPlaceholder.PlaceHolderId = placeholderContent.PlaceHolderId; newPlaceholder.Content = placeholderContent.Content; newPlaceholder.VersionId = newVersionId; newPlaceholders.Add(newPlaceholder); } DataFacade.AddNew(newPlaceholders); var sourceMetaData = sourcePage.GetMetaData().Cast() .Where(d => d.VersionId == sourceVersionId); foreach (var metaDataItem in sourceMetaData) { var metaDataType = metaDataItem.DataSourceId.InterfaceType; var typeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(metaDataType.GetImmutableTypeId()); var definition = PageMetaDataFacade.GetMetaDataDefinition(sourcePageId, metaDataItem.GetTypeTitle()); var newDataItem = (IPageMetaData)DataFacade.BuildNew(metaDataType); var properties = metaDataType.GetPropertiesRecursively().ToDictionary(p => p.Name); foreach (var field in typeDescriptor.Fields) { var propertyInfo = properties[field.Name]; propertyInfo.SetValue(newDataItem, propertyInfo.GetValue(metaDataItem)); } newDataItem.VersionId = newVersionId; newDataItem.Id = Guid.NewGuid(); newDataItem.PageId = newPageId; newDataItem.PublicationStatus = GenericPublishProcessController.Draft; newDataItem = (IPageMetaData)DataFacade.AddNew((IData)newDataItem); if (definition != null) { string title = newDataItem.GetTypeTitle(); newPage.AddMetaDataDefinition(title, title, newDataItem.GetImmutableTypeId(), definition.MetaDataContainerId); } } List selectableTreeIds = TreeFacade.AllTrees.Where( tree => tree.HasAttachmentPoints(sourcePage.GetDataEntityToken())) .Where(tree => !tree.HasAttachmentPoints(newPage.GetDataEntityToken())) .Select(tree => tree.TreeId).ToList(); foreach (var selectableTreeId in selectableTreeIds) { TreeFacade.AddPersistedAttachmentPoint(selectableTreeId, newPage.DataSourceId.InterfaceType, newPage.DataSourceId.GetKeyValue()); } foreach (var dataFolderType in sourcePage.GetDefinedFolderTypes()) { newPage.AddFolderDefinition(dataFolderType); } } } } ================================================ FILE: Composite/C1Console/Actions/FlowControllerAttribute.cs ================================================ using System; namespace Composite.C1Console.Actions { [AttributeUsageAttribute(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] internal sealed class FlowControllerAttribute : Attribute { private Type _flowControllerType; public FlowControllerAttribute(Type flowControllerType) { _flowControllerType = flowControllerType; } public Type FlowControllerType { get { return _flowControllerType; } } } } ================================================ FILE: Composite/C1Console/Actions/FlowControllerFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Workflow.Runtime; using Composite.C1Console.Actions.Foundation; using Composite.Core; using Composite.Core.Extensions; using Composite.Data; using Composite.Data.Types; using Composite.Core.Configuration; using Composite.Core.Logging; using Composite.C1Console.Security; using Composite.C1Console.Users; using Composite.C1Console.Workflow; namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class FlowControllerFacade { private static readonly string LogTitle = typeof (FlowControllerFacade).Name; private static TimeSpan? _timeout = null; private static bool _initialized = false; private static object _lock = new object(); /// public static void Initialize() { WorkflowFacade.RunWhenInitialized(() => { lock (_lock) { if (_initialized == false) { WorkflowInstance workflowInstance = WorkflowFacade.CreateNewWorkflow(WorkflowFacade.GetWorkflowType("Composite.C1Console.Actions.Workflows.FlowInformationScavengerWorkflow")); workflowInstance.Start(); WorkflowFacade.RunWorkflow(workflowInstance); Log.LogVerbose(LogTitle, "Flow scavenger started"); _initialized = true; } } }); } /// public static IFlowUiDefinition GetCurrentUiDefinition(FlowToken flowToken, FlowControllerServicesContainer flowControllerServicesContainer) { if (flowToken == null) throw new ArgumentNullException("flowToken"); IFlowController flowExecutor = FlowControllerCache.GetFlowController(flowToken, flowControllerServicesContainer); IFlowUiDefinition flowResult = flowExecutor.GetCurrentUiDefinition(flowToken); if (flowResult == null) { flowResult = new NullFlowUiDefinition(); } return flowResult; } /// public static void CancelFlow(FlowToken flowToken) { if (flowToken == null) throw new ArgumentNullException("flowToken"); IFlowController flowExecutor = FlowControllerCache.GetFlowController(flowToken, new FlowControllerServicesContainer()); flowExecutor.CancelFlow(flowToken); } /// public static void CancelFlowsByConsoleId(string consoleId) { List serializedFlowTokens = (from f in DataFacade.GetData() where f.ConsoleId == consoleId select f.SerializedFlowToken).ToList(); foreach (string serializedFlowToken in serializedFlowTokens) { FlowToken flowToken = FlowTokenSerializer.Deserialize(serializedFlowToken); CancelFlow(flowToken); } } /// public static IEnumerable GetFlowTokensByUsername(string username) { List serializedFlowTokens = (from f in DataFacade.GetData() where f.Username == username select f.SerializedFlowToken).ToList(); foreach (string serializedFlowToken in serializedFlowTokens) { FlowToken flowToken = FlowTokenSerializer.Deserialize(serializedFlowToken); yield return flowToken; } } /// public static IEnumerable GetConsoleIdsByUsername(string username) { List consoleIds = (from f in DataFacade.GetData() where f.Username == username select f.ConsoleId).ToList(); return consoleIds; } /// public static void FlowComplete(FlowToken flowToken) { UnregisterFlowInformation(flowToken); } internal static void RegisterNewFlowInformation(FlowToken flowToken, EntityToken entityToken, ActionToken actionToken, string consoleId) { IFlowInformation flowInformation = DataFacade.BuildNew(); flowInformation.Id = Guid.NewGuid(); flowInformation.Username = UserSettings.Username; flowInformation.ConsoleId = consoleId; flowInformation.SerializedFlowToken = FlowTokenSerializer.Serialize(flowToken); flowInformation.SerializedEntityToken = EntityTokenSerializer.Serialize(entityToken); flowInformation.SerializedActionToken = ActionTokenSerializer.Serialize(actionToken); flowInformation.TimeStamp = DateTime.Now; DataFacade.AddNew(flowInformation); } internal static void UnregisterFlowInformation(FlowToken flowToken) { string serializedFlowToken = FlowTokenSerializer.Serialize(flowToken); DataFacade.Delete(f => f.SerializedFlowToken == serializedFlowToken); } /// public static void Scavenge() { Log.LogVerbose(LogTitle, "Starting scavenger run"); List flowInformations = DataFacade.GetData().ToList(); // NOTE: Low performance implementation foreach (IFlowInformation flowInformation in flowInformations) { TimeSpan timeSpan = DateTime.Now - flowInformation.TimeStamp; if (timeSpan > Timeout) { FlowToken flowToken = null; string flowTokenStr; try { flowToken = FlowTokenSerializer.Deserialize(flowInformation.SerializedFlowToken); flowTokenStr = flowToken.ToString(); } catch(Exception) { flowTokenStr = flowInformation.SerializedFlowToken ?? string.Empty; if(flowTokenStr.Length > 200) { flowTokenStr = flowTokenStr.Substring(0, 200); } } Log.LogVerbose(LogTitle, "Scavenging flow started by username '{0}', flow = '{1}'".FormatWith(flowInformation.Username, flowTokenStr)); DataFacade.Delete(flowInformation); if (flowToken != null) { FlowControllerFacade.CancelFlow(flowToken); } } } } private static TimeSpan Timeout { get { if (_timeout.HasValue == false) { _timeout = GlobalSettingsFacade.WorkflowTimeout; } return _timeout.Value; } } } } ================================================ FILE: Composite/C1Console/Actions/FlowControllerServicesContainer.cs ================================================ using System; using System.Collections.Generic; using Composite.Core.Extensions; namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class FlowControllerServicesContainer { private readonly Dictionary> _services = new Dictionary>(); /// public FlowControllerServicesContainer() { } /// public FlowControllerServicesContainer(params IFlowControllerService[] services) { foreach (var service in services) { AddService(service); } } // Creates a new service container and initialized it with the services from servicesContainerToClone. /// public FlowControllerServicesContainer(FlowControllerServicesContainer servicesContainerToClone) { _services = new Dictionary>(servicesContainerToClone._services); } /// public void AddService(IFlowControllerService flowControllerService) { Type type = flowControllerService.GetType(); foreach (Type interfaceType in type.GetInterfaces()) { List list = _services.GetOrAdd(interfaceType, () => new List()); list.Add(flowControllerService); } } /// public void RemoveService(IFlowControllerService flowControllerService) { Type type = flowControllerService.GetType(); foreach (Type interfaceType in type.GetInterfaces()) { if (!_services.TryGetValue(interfaceType, out var list)) throw new InvalidOperationException(); list.Remove(flowControllerService); } } /// /// Returns a concrete service interface, if available. Sample service interfaces are: /// - Composite.C1Console.Events.IManagementConsoleMessageService /// - Composite.C1Console.Actions.IActionExecutionService /// - Composite.C1Console.Forms.Flows.IFormFlowRenderingService /// - Composite.C1Console.Actions.IElementInformationService /// /// /// public T GetService() where T : IFlowControllerService { return (T)GetService(typeof(T)); } /// public IFlowControllerService GetService(Type serviceType) { if (!_services.TryGetValue(serviceType, out var list)) { return null; } if (list.Count > 1) { throw new InvalidOperationException($"More than one service of type '{serviceType}' was added"); } return (IFlowControllerService)list[0]; } } } ================================================ FILE: Composite/C1Console/Actions/FlowHandle.cs ================================================ using System; using System.Collections.Generic; using System.Reflection; using System.Text; using Composite.Core.Serialization; using Composite.Core.Types; namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class FlowHandle { private FlowToken _flowToken; private string _serializedData = null; /// public FlowHandle(FlowToken FlowToken) { _flowToken = FlowToken; } /// public FlowToken FlowToken { get { return _flowToken; } } /// public static FlowHandle Deserialize(string serializedFlowHandle) { Dictionary dic = StringConversionServices.ParseKeyValueCollection(serializedFlowHandle); if ((dic.ContainsKey("_flowTokenType_") == false) || (dic.ContainsKey("_flowToken_") == false)) { throw new ArgumentException("The serializedFlowHandle is not a serialized flow handle", "serializedFlowHandle"); } string flowTokenTypeString = StringConversionServices.DeserializeValueString(dic["_flowTokenType_"]); string flowTokenString = StringConversionServices.DeserializeValueString(dic["_flowToken_"]); Type flowTokenType = TypeManager.GetType(flowTokenTypeString); MethodInfo methodInfo = flowTokenType.GetMethod("Deserialize", BindingFlags.Public | BindingFlags.Static); if (methodInfo == null || !(typeof(FlowToken).IsAssignableFrom(methodInfo.ReturnType))) { throw new InvalidOperationException(string.Format("The flow token '{0}' is missing a public static Deserialize method taking a string as parameter and returning an '{1}'", flowTokenType, typeof(FlowToken))); } FlowToken flowToken; try { flowToken = (FlowToken)methodInfo.Invoke(null, new object[] { flowTokenString }); } catch (Exception ex) { throw new InvalidOperationException(string.Format("The flow token '{0}' is missing a public static Deserialize method taking a string as parameter and returning an '{1}'", flowTokenType, typeof(FlowToken)), ex); } if (flowToken == null) { throw new InvalidOperationException(string.Format("public static Deserialize method taking a string as parameter and returning an '{0}' on the flow token '{1}' did not return an object", flowTokenType, typeof(FlowToken))); } return new FlowHandle(flowToken); } /// public string Serialize() { return ToString(); } /// public override string ToString() { if (_serializedData == null) { StringBuilder sb = new StringBuilder(); StringConversionServices.SerializeKeyValuePair(sb, "_flowTokenType_", TypeManager.SerializeType(_flowToken.GetType())); StringConversionServices.SerializeKeyValuePair(sb, "_flowToken_", _flowToken.Serialize()); _serializedData = sb.ToString(); } return _serializedData; } } } ================================================ FILE: Composite/C1Console/Actions/FlowToken.cs ================================================ namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class FlowToken { /// public virtual string Serialize() { return ""; } } } ================================================ FILE: Composite/C1Console/Actions/FlowTokenSerializer.cs ================================================ using System; using System.Collections.Generic; using System.Reflection; using System.Security; using System.Text; using Composite.C1Console.Security; using Composite.Core.Serialization; using Composite.Core.Types; namespace Composite.C1Console.Actions { internal static class FlowTokenSerializer { public static string Serialize(FlowToken flowToken) { return Serialize(flowToken, false); } public static string Serialize(FlowToken flowToken, bool includeHashValue) { if (flowToken == null) throw new ArgumentNullException("flowToken"); StringBuilder sb = new StringBuilder(); StringConversionServices.SerializeKeyValuePair(sb, "flowTokenType", TypeManager.SerializeType(flowToken.GetType())); string serializedFlowToken = flowToken.Serialize(); StringConversionServices.SerializeKeyValuePair(sb, "flowToken", serializedFlowToken); if (includeHashValue) { StringConversionServices.SerializeKeyValuePair(sb, "flowTokenHash", HashSigner.GetSignedHash(serializedFlowToken).Serialize()); } return sb.ToString(); } public static FlowToken Deserialize(string serialziedFlowToken) { return Deserialize(serialziedFlowToken, false); } public static FlowToken Deserialize(string serialziedFlowToken, bool includeHashValue) { if (string.IsNullOrEmpty(serialziedFlowToken)) throw new ArgumentNullException("serialziedFlowToken"); Dictionary dic = StringConversionServices.ParseKeyValueCollection(serialziedFlowToken); if ((dic.ContainsKey("flowTokenType") == false) || (dic.ContainsKey("flowToken") == false) || ((includeHashValue) && (dic.ContainsKey("flowTokenHash") == false))) { throw new ArgumentException("The serialziedFlowToken is not a serialized flowToken", "serialziedFlowToken"); } string flowTokenTypeString = StringConversionServices.DeserializeValueString(dic["flowTokenType"]); string flowTokenString = StringConversionServices.DeserializeValueString(dic["flowToken"]); if (includeHashValue) { string flowTokenHash = StringConversionServices.DeserializeValueString(dic["flowTokenHash"]); HashValue hashValue = HashValue.Deserialize(flowTokenHash); if (HashSigner.ValidateSignedHash(flowTokenString, hashValue) == false) { throw new SecurityException("Serialized flow token is tampered"); } } Type flowType = TypeManager.GetType(flowTokenTypeString); MethodInfo methodInfo = flowType.GetMethod("Deserialize", BindingFlags.Public | BindingFlags.Static); if (methodInfo == null || !(typeof(FlowToken).IsAssignableFrom(methodInfo.ReturnType))) { throw new InvalidOperationException(string.Format("The flow token {0} is missing a public static Deserialize method taking a string as parameter and returning an {1}", flowType, typeof(FlowToken))); } FlowToken flowToken; try { flowToken = (FlowToken)methodInfo.Invoke(null, new object[] { flowTokenString }); } catch (Exception ex) { throw new InvalidOperationException(string.Format("The flow token {0} is missing a public static Deserialize method taking a string as parameter and returning an {1}", flowType, typeof(FlowToken)), ex); } if (flowToken == null) { throw new InvalidOperationException(string.Format("public static Deserialize method taking a string as parameter and returning an {1} on the flow token {0} did not return an object", flowType, typeof(FlowToken))); } return flowToken; } } } ================================================ FILE: Composite/C1Console/Actions/FlowUiDefinitionBase.cs ================================================ namespace Composite.C1Console.Actions { internal abstract class FlowUiDefinitionBase : IFlowUiDefinition { public abstract IFlowUiContainerType UiContainerType { get; protected set; } } } ================================================ FILE: Composite/C1Console/Actions/Foundation/ActionExecutorCache.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Events; using Composite.Core.Logging; using Composite.C1Console.Security; namespace Composite.C1Console.Actions.Foundation { internal static class ActionExecutorCache { private static Dictionary _actionExecutorCache = new Dictionary(); private static object _lock = new object(); static ActionExecutorCache() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlush); } public static IActionExecutor GetActionExecutor(ActionToken actionToken) { if (actionToken == null) throw new ArgumentNullException("actionToken"); IActionExecutor actionExecutor; if (_actionExecutorCache.TryGetValue(actionToken.GetType(), out actionExecutor) == false) { object[] attributes = actionToken.GetType().GetCustomAttributes(typeof(ActionExecutorAttribute), true); if (attributes.Length == 0) throw new InvalidOperationException(string.Format("Missing {0} attribute on the flow token {1}", typeof(ActionExecutorAttribute), actionToken.GetType())); ActionExecutorAttribute attribute = (ActionExecutorAttribute)attributes[0]; if (attribute.ActionExecutorType == null) throw new InvalidOperationException(string.Format("Action executor type can not be null on the action token {0}", actionToken.GetType())); if (typeof(IActionExecutor).IsAssignableFrom(attribute.ActionExecutorType) == false) throw new InvalidOperationException(string.Format("Action executor {0} should implement the interface {1}", attribute.ActionExecutorType, typeof(IActionExecutor))); actionExecutor = (IActionExecutor)Activator.CreateInstance(attribute.ActionExecutorType); _actionExecutorCache.Add(actionToken.GetType(), actionExecutor); } return actionExecutor; } private static void Flush() { _actionExecutorCache = new Dictionary(); } private static void OnFlush(FlushEventArgs args) { Flush(); } } } ================================================ FILE: Composite/C1Console/Actions/Foundation/FlowExecutorCache.cs ================================================ using System; using System.Collections.Concurrent; using Composite.C1Console.Events; namespace Composite.C1Console.Actions.Foundation { internal static class FlowControllerCache { private static readonly ConcurrentDictionary _flowControllerCache = new ConcurrentDictionary(); static FlowControllerCache() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } public static IFlowController GetFlowController(FlowToken flowToken, FlowControllerServicesContainer flowControllerServicesContainer) { Verify.ArgumentNotNull(flowToken, "flowToken"); Type flowTokenType = flowToken.GetType(); return _flowControllerCache.GetOrAdd(flowTokenType, type => { object[] attributes = type.GetCustomAttributes(typeof(FlowControllerAttribute), true); Verify.That(attributes.Length > 0, "Missing '{0}' attribute on the flow token '{1}'", typeof(FlowControllerAttribute), type); FlowControllerAttribute attribute = (FlowControllerAttribute) attributes[0]; Verify.IsNotNull(attribute.FlowControllerType, "Flow controller type can not be null on the action token '{0}'", type); Verify.That(typeof(IFlowController).IsAssignableFrom(attribute.FlowControllerType), "Flow controller '{0}' should implement the interface '{1}'", attribute.FlowControllerType, typeof(IFlowController)); var flowController = (IFlowController) Activator.CreateInstance(attribute.FlowControllerType); flowController.ServicesContainer = flowControllerServicesContainer; return flowController; }); } private static void Flush() { _flowControllerCache.Clear(); } } } ================================================ FILE: Composite/C1Console/Actions/IActionExecutionService.cs ================================================ using Composite.C1Console.Security; using Composite.C1Console.Tasks; namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IActionExecutionService : IFlowControllerService { /// void Execute(EntityToken entityToken, ActionToken actionToken, TaskManagerEvent taskManagerEvent); } } ================================================ FILE: Composite/C1Console/Actions/IActionExecutor.cs ================================================ using Composite.C1Console.Security; namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IActionExecutor { /// FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer); } } ================================================ FILE: Composite/C1Console/Actions/IActionExecutorSerializedParameters.cs ================================================ using Composite.C1Console.Security; namespace Composite.C1Console.Actions { internal interface IActionExecutorSerializedParameters : IActionExecutor { FlowToken Execute(string serializedEntityToken, string serializedActionToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer); } } ================================================ FILE: Composite/C1Console/Actions/IElementInformationService.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Composite.C1Console.Actions { internal interface IElementInformationService : IFlowControllerService { string ProviderName { get; } Dictionary Piggyback { get; } } } ================================================ FILE: Composite/C1Console/Actions/IFlowController.cs ================================================ namespace Composite.C1Console.Actions { internal interface IFlowController { /// /// Set by the the system (mediator) /// FlowControllerServicesContainer ServicesContainer { set; } IFlowUiDefinition GetCurrentUiDefinition(FlowToken flowToken); void CancelFlow(FlowToken flowToken); } } ================================================ FILE: Composite/C1Console/Actions/IFlowControllerService.cs ================================================ using Composite.Core.Logging; using Composite.C1Console.Security; namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IFlowControllerService { } } ================================================ FILE: Composite/C1Console/Actions/IFlowUiContainerType.cs ================================================  namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IFlowUiContainerType { /// string ContainerName { get; } /// ActionResultResponseType ActionResultResponseType { get; } } } ================================================ FILE: Composite/C1Console/Actions/IFlowUiDefinition.cs ================================================  namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IFlowUiDefinition { } } ================================================ FILE: Composite/C1Console/Actions/InlineScriptActionFacade.cs ================================================ using System; using System.Collections.Generic; using System.Text; using Composite.C1Console.Security; using Composite.Core.WebClient.FlowMediators; using Composite.Core.Serialization; using Composite.C1Console.Elements; namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class InlineScriptActionFacade { /// public static string GetInlineElementActionScriptCode(EntityToken entityToken, ActionToken actionToken) { return GetInlineElementActionScriptCode(entityToken, actionToken, new Dictionary()); } /// public static string GetInlineElementActionScriptCode(EntityToken entityToken, ActionToken actionToken, Dictionary piggyBag) { StringBuilder sb = new StringBuilder(); StringConversionServices.SerializeKeyValuePair(sb, "EntityToken", EntityTokenSerializer.Serialize(entityToken, false)); StringConversionServices.SerializeKeyValuePair(sb, "ActionToken", ActionTokenSerializer.Serialize(actionToken, true)); StringConversionServices.SerializeKeyValuePair(sb, "PiggyBag", PiggybagSerializer.Serialize(piggyBag)); string scriptAction = string.Format(@"SystemAction.invokeInlineAction(""{0}"");", Convert.ToBase64String(Encoding.UTF8.GetBytes(sb.ToString()))); return scriptAction; } /// public static void ExecuteElementScriptAction(string serializedScriptAction, string consoleId) { string scriptAction = Encoding.UTF8.GetString(Convert.FromBase64String(serializedScriptAction)); Dictionary dic = StringConversionServices.ParseKeyValueCollection(scriptAction); if ((dic["EntityToken"] == null) || (dic["ActionToken"] == null) || (dic["PiggyBag"] == null)) throw new ArgumentException("Wrong format", "serializedScriptAction"); string serializedEntityToken = StringConversionServices.DeserializeValueString(dic["EntityToken"]); string serializedActionToken = StringConversionServices.DeserializeValueString(dic["ActionToken"]); string serializedPiggyBag = StringConversionServices.DeserializeValueString(dic["PiggyBag"]); TreeServicesFacade.ExecuteElementAction( "DUMMY", serializedEntityToken, serializedPiggyBag, serializedActionToken, consoleId); } } } ================================================ FILE: Composite/C1Console/Actions/MessageBoxActionToken.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.C1Console.Security; using Composite.C1Console.Events; using Composite.Core.Serialization; namespace Composite.C1Console.Actions { internal sealed class MessageBoxActionTokenActionExecutor : IActionExecutor { public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { MessageBoxActionToken messageBoxActionToken = (MessageBoxActionToken)actionToken; IManagementConsoleMessageService managementConsoleMessageService = flowControllerServicesContainer.GetService(); managementConsoleMessageService.ShowMessage(messageBoxActionToken.DialogType, messageBoxActionToken.Title, messageBoxActionToken.Message); return null; } } /// /// To add a message box action /// [ActionExecutor(typeof(MessageBoxActionTokenActionExecutor))] public sealed class MessageBoxActionToken : ActionToken { private readonly List _permissionTypes; /// /// To add a message box action /// /// /// /// public MessageBoxActionToken(string title, string message, DialogType dialogType) :this(title, message, dialogType, new List() { PermissionType.Add, PermissionType.Administrate, PermissionType.Approve, PermissionType.Delete, PermissionType.Edit, PermissionType.Publish, PermissionType.Read }) { } /// public MessageBoxActionToken(string title, string message, DialogType dialogType, List permissionTypes) { _permissionTypes = permissionTypes; this.Title = title; this.Message = message; this.DialogType = dialogType; } /// public string Title { get; private set; } /// public string Message { get; private set; } /// public DialogType DialogType { get; private set; } /// public override IEnumerable PermissionTypes { get { return _permissionTypes; } } /// public override string Serialize() { StringBuilder sb = new StringBuilder(); StringConversionServices.SerializeKeyValuePair(sb, "Title", this.Title); StringConversionServices.SerializeKeyValuePair(sb, "Message", this.Message); StringConversionServices.SerializeKeyValuePair(sb, "DialogType", this.DialogType.ToString()); StringConversionServices.SerializeKeyValuePair(sb, "PermissionTypes", _permissionTypes.SerializePermissionTypes()); return sb.ToString(); } /// public static ActionToken Deserialize(string serializedData) { Dictionary dic = StringConversionServices.ParseKeyValueCollection(serializedData); return new MessageBoxActionToken ( StringConversionServices.DeserializeValueString(dic["Title"]), StringConversionServices.DeserializeValueString(dic["Message"]), (DialogType)Enum.Parse(typeof(DialogType), StringConversionServices.DeserializeValueString(dic["DialogType"])), StringConversionServices.DeserializeValueString(dic["PermissionTypes"]).DesrializePermissionTypes().ToList() ); } } } ================================================ FILE: Composite/C1Console/Actions/NullFlow.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Text; namespace Composite.C1Console.Actions { [FlowController(typeof(NullFlowController))] internal class NullFlowToken : FlowToken { public static FlowToken Deserialize(string serialized) { return new NullFlowToken(); } } internal class NullFlowController : IFlowController { public FlowControllerServicesContainer ServicesContainer { set { } } public IFlowUiDefinition GetCurrentUiDefinition(FlowToken flowToken) { return new NullFlowUiDefinition(); } public void CancelFlow(FlowToken flowToken) { } } internal class NullFlowUiDefinition : FlowUiDefinitionBase { public NullFlowUiDefinition() { this.UiContainerType = StandardUiContainerTypes.Null; } public override IFlowUiContainerType UiContainerType { get; protected set; } } } ================================================ FILE: Composite/C1Console/Actions/ParentTreeRefresher.cs ================================================ using System; using System.Linq; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.Core; using Composite.Core.Linq; namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ParentTreeRefresher { private bool _postRefreshMessagesCalled; private readonly FlowControllerServicesContainer _flowControllerServicesContainer; /// public ParentTreeRefresher(FlowControllerServicesContainer flowControllerServicesContainer) { Verify.ArgumentNotNull(flowControllerServicesContainer, "flowControllerServicesContainer"); _flowControllerServicesContainer = flowControllerServicesContainer; } /// [Obsolete("Use PostRefreshMessages instead")] public void PostRefreshMesseges(EntityToken childEntityToken) { PostRefreshMessages(childEntityToken); } /// [Obsolete("Use PostRefreshMessages instead")] public void PostRefreshMesseges(EntityToken childEntityToken, int parentLevel) { PostRefreshMessages(childEntityToken, parentLevel); } /// /// Posts refresh messages to the ancestors of the specified entityToken /// /// /// 1 means the first parent, 2 means the second, etc. public void PostRefreshMessages(EntityToken childEntityToken, int parentLevel = 1) { Verify.ArgumentNotNull(childEntityToken, "childEntityToken"); if (_postRefreshMessagesCalled) { throw new InvalidOperationException("Only one PostRefreshMessages call is allowed"); } _postRefreshMessagesCalled = true; RelationshipGraph relationshipGraph = new RelationshipGraph(childEntityToken, RelationshipGraphSearchOption.Both); var levels = relationshipGraph.Levels.Evaluate(); if (levels.Count <= parentLevel) { return; } RelationshipGraphLevel relationshipGraphLevel = levels.ElementAt(parentLevel); IManagementConsoleMessageService messageService = _flowControllerServicesContainer.GetService(); foreach (EntityToken entityToken in relationshipGraphLevel.AllEntities) { messageService.RefreshTreeSection(entityToken); Log.LogVerbose(this.GetType().Name, "Refreshing EntityToken: Type = {0}, Source = {1}, Id = {2}, EntityTokenType = {3}", entityToken.Type, entityToken.Source, entityToken.Id, entityToken.GetType()); } } } } ================================================ FILE: Composite/C1Console/Actions/SpecificTreeRefresher.cs ================================================ using System; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.Core; namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class SpecificTreeRefresher { private bool _postRefreshMessagesCalled = false; private readonly FlowControllerServicesContainer _flowControllerServicesContainer; /// public SpecificTreeRefresher(FlowControllerServicesContainer flowControllerServicesContainer) { Verify.ArgumentNotNull(flowControllerServicesContainer, "flowControllerServicesContainer"); _flowControllerServicesContainer = flowControllerServicesContainer; } /// [Obsolete("Use PostRefreshMessages instead")] public void PostRefreshMesseges(EntityToken specificEntityToken) { PostRefreshMessages(specificEntityToken); } /// public void PostRefreshMessages(EntityToken specificEntityToken) { Verify.ArgumentNotNull(specificEntityToken, "specificEntityToken"); if (_postRefreshMessagesCalled) { throw new InvalidOperationException("Only one PostRefreshMessages call is allowed"); } IManagementConsoleMessageService messageService = _flowControllerServicesContainer.GetService(); messageService.RefreshTreeSection(specificEntityToken); Log.LogVerbose(GetType().Name, "Refreshing EntityToken: Type = {0}, Source = {1}, Id = {2}, EntityTokenType = {3}", specificEntityToken.Type, specificEntityToken.Source, specificEntityToken.Id, specificEntityToken.GetType()); } } } ================================================ FILE: Composite/C1Console/Actions/StandardUiContainerTypes.cs ================================================ using Composite.Core.Serialization; namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class StandardUiContainerTypes { /// public static IFlowUiContainerType Document { get { return _document; } } /// public static IFlowUiContainerType EmptyDocument { get { return _emptyDocument; } } /// public static IFlowUiContainerType Wizard { get { return _wizard; } } /// public static IFlowUiContainerType DataDialog { get { return _dataDialog; } } /// public static IFlowUiContainerType ConfirmDialog { get { return _confirmDialog; } } /// public static IFlowUiContainerType WarningDialog { get { return _warningDialog; } } /// public static IFlowUiContainerType Null { get { return _null; } } private static DocumentUiContainer _document = new DocumentUiContainer(); private static EmptyDocumentUiContainer _emptyDocument = new EmptyDocumentUiContainer(); private static WizardUiContainer _wizard = new WizardUiContainer(); private static DataDialogUiContainer _dataDialog = new DataDialogUiContainer(); private static ConfirmDialogUiContainer _confirmDialog = new ConfirmDialogUiContainer(); private static WarningDialogUiContainer _warningDialog = new WarningDialogUiContainer(); private static NullUiContainer _null = new NullUiContainer(); [SerializerHandler(typeof(StandardUiContainerTypesSerializerHandler))] private class DocumentUiContainer : IFlowUiContainerType { internal DocumentUiContainer() { } string IFlowUiContainerType.ContainerName { get { return "Document"; } } ActionResultResponseType IFlowUiContainerType.ActionResultResponseType { get { return ActionResultResponseType.OpenDocument; } } } [SerializerHandler(typeof(StandardUiContainerTypesSerializerHandler))] private class EmptyDocumentUiContainer : IFlowUiContainerType { internal EmptyDocumentUiContainer() { } string IFlowUiContainerType.ContainerName { get { return "EmptyDocument"; } } ActionResultResponseType IFlowUiContainerType.ActionResultResponseType { get { return ActionResultResponseType.OpenDocument; } } } [SerializerHandler(typeof(StandardUiContainerTypesSerializerHandler))] private class WizardUiContainer : IFlowUiContainerType { internal WizardUiContainer() { } string IFlowUiContainerType.ContainerName { get { return "Wizard"; } } ActionResultResponseType IFlowUiContainerType.ActionResultResponseType { get { return ActionResultResponseType.OpenModalDialog; } } } [SerializerHandler(typeof(StandardUiContainerTypesSerializerHandler))] private class DataDialogUiContainer : IFlowUiContainerType { internal DataDialogUiContainer() { } string IFlowUiContainerType.ContainerName { get { return "DataDialog"; } } ActionResultResponseType IFlowUiContainerType.ActionResultResponseType { get { return ActionResultResponseType.OpenModalDialog; } } } [SerializerHandler(typeof(StandardUiContainerTypesSerializerHandler))] private class ConfirmDialogUiContainer : IFlowUiContainerType { internal ConfirmDialogUiContainer() { } string IFlowUiContainerType.ContainerName { get { return "ConfirmDialog"; } } ActionResultResponseType IFlowUiContainerType.ActionResultResponseType { get { return ActionResultResponseType.OpenModalDialog; } } } [SerializerHandler(typeof(StandardUiContainerTypesSerializerHandler))] private class WarningDialogUiContainer : IFlowUiContainerType { internal WarningDialogUiContainer() { } string IFlowUiContainerType.ContainerName { get { return "WarningDialog"; } } ActionResultResponseType IFlowUiContainerType.ActionResultResponseType { get { return ActionResultResponseType.OpenModalDialog; } } } [SerializerHandler(typeof(StandardUiContainerTypesSerializerHandler))] private class NullUiContainer : IFlowUiContainerType { internal NullUiContainer() { } string IFlowUiContainerType.ContainerName { get { return "Null"; } } ActionResultResponseType IFlowUiContainerType.ActionResultResponseType { get { return ActionResultResponseType.None; } } } } } ================================================ FILE: Composite/C1Console/Actions/StandardUiContainerTypesSerializerHandler.cs ================================================ using System; using Composite.Core.Serialization; namespace Composite.C1Console.Actions { internal sealed class StandardUiContainerTypesSerializerHandler : ISerializerHandler { public string Serialize(object objectToSerialize) { IFlowUiContainerType flowUiContainerType = (IFlowUiContainerType)objectToSerialize; if ((flowUiContainerType.ContainerName != "Document") && (flowUiContainerType.ContainerName != "EmptyDocument") && (flowUiContainerType.ContainerName != "Wizard") && (flowUiContainerType.ContainerName != "DataDialog") && (flowUiContainerType.ContainerName != "ConfirmDialog") && (flowUiContainerType.ContainerName != "WarningDialog") && (flowUiContainerType.ContainerName != "Null")) { throw new NotSupportedException(); } return flowUiContainerType.ContainerName; } public object Deserialize(string serializedObject) { switch (serializedObject) { case "Document": return StandardUiContainerTypes.Document; case "EmptyDocument": return StandardUiContainerTypes.EmptyDocument; case "Wizard": return StandardUiContainerTypes.Wizard; case "DataDialog": return StandardUiContainerTypes.DataDialog; case "ConfirmDialog": return StandardUiContainerTypes.ConfirmDialog; case "WarningDialog": return StandardUiContainerTypes.WarningDialog; case "Null": return StandardUiContainerTypes.Null; default: throw new NotSupportedException(); } } } } ================================================ FILE: Composite/C1Console/Actions/UpdateTreeRefresher.cs ================================================ using System; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.Core; namespace Composite.C1Console.Actions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class UpdateTreeRefresher { private readonly FlowControllerServicesContainer _flowControllerServicesContainer; private readonly RelationshipGraph _beforeGraph; private RelationshipGraph _afterGraph; private bool _postRefreshMessagesCalled; /// public UpdateTreeRefresher(EntityToken beforeUpdateEntityToken, FlowControllerServicesContainer flowControllerServicesContainer) { Verify.ArgumentNotNull(beforeUpdateEntityToken, "beforeUpdateEntityToken"); Verify.ArgumentNotNull(flowControllerServicesContainer, "flowControllerServicesContainer"); _beforeGraph = new RelationshipGraph(beforeUpdateEntityToken, RelationshipGraphSearchOption.Both, false, false); _flowControllerServicesContainer = flowControllerServicesContainer; } /// [Obsolete("Use PostRefreshMessages instead")] public void PostRefreshMesseges(EntityToken afterUpdateEntityToken) { PostRefreshMessages(afterUpdateEntityToken); } /// public void PostRefreshMessages(EntityToken afterUpdateEntityToken) { if (_postRefreshMessagesCalled) { throw new InvalidOperationException("Only one PostRefreshMessages call is allowed"); } _postRefreshMessagesCalled = true; _afterGraph = new RelationshipGraph(afterUpdateEntityToken, RelationshipGraphSearchOption.Both, false, false); IManagementConsoleMessageService messageService = _flowControllerServicesContainer.GetService(); foreach (EntityToken entityToken in RefreshBeforeAfterEntityTokenFinder.FindEntityTokens(_beforeGraph, _afterGraph)) { messageService.RefreshTreeSection(entityToken); Log.LogVerbose(this.GetType().Name, "Refreshing EntityToken: Type = {0}, Source = {1}, Id = {2}, EntityTokenType = {3}", entityToken.Type, entityToken.Source, entityToken.Id, entityToken.GetType()); } } } } ================================================ FILE: Composite/C1Console/Actions/UrlActionToken.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security; using Composite.C1Console.Events; using System.Web; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; namespace Composite.C1Console.Actions { /// /// To add a custom URL action /// [ActionExecutor(typeof(UrlActionTokenActionExecutor))] public sealed class UrlActionToken : ActionToken { /// /// To add a custom URL action /// /// /// /// public UrlActionToken(string label, string url, IEnumerable permissionTypes) : this(label, DefaultIcon, url, permissionTypes) { } /// /// To add a custom URL action /// /// /// /// /// public UrlActionToken(string label, ResourceHandle icon, string url, IEnumerable permissionTypes) { Label = label; Url = url; PermissionTypes = permissionTypes; Icon = icon; } /// public string Label { get; } /// public string Url { get; } /// public override IEnumerable PermissionTypes { get; } /// public ResourceHandle Icon { get; } /// public override string Serialize() { return $"{Label}·{Url}·{PermissionTypes.SerializePermissionTypes()}·{Icon.ResourceNamespace}·{Icon.ResourceName}"; } private static ResourceHandle DefaultIcon => new ResourceHandle(BuildInIconProviderName.ProviderName, "page"); /// public static ActionToken Deserialize(string serializedData) { string[] s = serializedData.Split('·'); var icon = s.Length == 5 ? new ResourceHandle(s[3], s[4]) : DefaultIcon; return new UrlActionToken(s[0], icon, s[1], s[2].DesrializePermissionTypes()); } } internal sealed class UrlActionTokenActionExecutor : IActionExecutor { public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { UrlActionToken urlActionToken = (UrlActionToken)actionToken; string currentConsoleId = flowControllerServicesContainer.GetService().CurrentConsoleId; string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken); string url = urlActionToken.Url; string extendedUrl = $"{url}{(url.Contains("?") ? "&" : "?")}EntityToken={HttpUtility.UrlEncode(serializedEntityToken)}"; if (extendedUrl.IndexOf("consoleId", StringComparison.OrdinalIgnoreCase) == -1) { extendedUrl = $"{extendedUrl}&consoleId={currentConsoleId}"; } ConsoleMessageQueueFacade.Enqueue( new OpenViewMessageQueueItem { Url = extendedUrl, ViewId = Guid.NewGuid().ToString(), ViewType = ViewType.Main, Label = urlActionToken.Label, IconResourceHandle = urlActionToken.Icon }, currentConsoleId); return null; } } } ================================================ FILE: Composite/C1Console/Actions/VisualFlowUiDefinitionBase.cs ================================================  namespace Composite.C1Console.Actions { internal abstract class VisualFlowUiDefinitionBase : FlowUiDefinitionBase { public virtual string ContainerLabel { get; protected set; } } } ================================================ FILE: Composite/C1Console/Actions/Workflow/EntityTokenLockedEntityToken.cs ================================================ using Composite.C1Console.Security; using Newtonsoft.Json; namespace Composite.C1Console.Actions.Workflows { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] // This is a dummy token, no elements using this token exists! public sealed class EntityTokenLockedEntityToken : EntityToken { private string _lockedByUsername; private string _serializedLockedActionToken; private string _serializedLockedEntityToken; private ActionToken _lockedActionToken = null; private EntityToken _lockedEntityToken = null; /// public EntityTokenLockedEntityToken(string lockedByUsername, string serializedLockedActionToken, string serializedLockedEntityToken) { _lockedByUsername = lockedByUsername; _serializedLockedActionToken = serializedLockedActionToken; _serializedLockedEntityToken = serializedLockedEntityToken; } /// [JsonIgnore] public string LockedByUsername { get { return _lockedByUsername; } } /// [JsonIgnore] public ActionToken LockedActionToken { get { if (_lockedActionToken == null) { _lockedActionToken = ActionTokenSerializer.Deserialize(_serializedLockedActionToken); } return _lockedActionToken; } } /// [JsonIgnore] public EntityToken LockedEntityToken { get { if (_lockedEntityToken == null) { _lockedEntityToken = EntityTokenSerializer.Deserialize(_serializedLockedEntityToken); } return _lockedEntityToken; } } /// public override string Type { get { return _lockedByUsername; } } /// public override string Source { get { return _serializedLockedActionToken; } } /// public override string Id { get { return _serializedLockedEntityToken; } } /// public override string Serialize() { return DoSerialize(); } /// public static EntityToken Deserialize(string serializedEntityToken) { string type, source, id; DoDeserialize(serializedEntityToken, out type, out source, out id); return new EntityTokenLockedEntityToken(type, source, id); } } } ================================================ FILE: Composite/C1Console/Actions/Workflow/SecurityViolationWorkflowEntityToken.cs ================================================ using Composite.C1Console.Security; namespace Composite.C1Console.Actions.Workflows { internal sealed class SecurityViolationWorkflowEntityToken : EntityToken { public override string Type { get { return ""; } } public override string Source { get { return ""; } } public override string Id { get { return "SecurityViolationWorkflowEntityToken"; } } public override string Serialize() { return DoSerialize(); } public static EntityToken Deserialize(string serializedEntityToken) { return new SecurityViolationWorkflowEntityToken(); } } } ================================================ FILE: Composite/C1Console/Commands/ConsoleCommandFacade.cs ================================================ using Composite.C1Console.Commands.Foundation.PluginFacades; namespace Composite.C1Console.Commands { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ConsoleCommandFacade { /// /// Handles a console command. /// /// The console Id. /// The command name. /// The command payload. public static void HandleConsoleCommand(string consoleId, string commandName, string commandPayload) { Verify.ArgumentNotNullOrEmpty(consoleId, "consoleId"); Verify.ArgumentNotNullOrEmpty(commandName, "commandName"); if (!ConsoleCommandHandlerPluginFacade.HasConfiguration()) { return; } var handler = ConsoleCommandHandlerPluginFacade.GetConsoleCommandHandler(commandName); if (handler == null) { return; } handler.HandleConsoleCommand(consoleId, commandPayload); } } } ================================================ FILE: Composite/C1Console/Commands/Foundation/PluginFacades/ConsoleCommandHandlerPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using Composite.C1Console.Commands.Plugins.ConsoleCommandHandler.Runtime; using Composite.C1Console.Events; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; namespace Composite.C1Console.Commands.Foundation.PluginFacades { class ConsoleCommandHandlerPluginFacade { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.DoInitializeResources); static ConsoleCommandHandlerPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } internal static IConsoleCommandHandler GetConsoleCommandHandler(string pluginName) { IConsoleCommandHandler plugin; var resources = _resourceLocker.Resources; if (!resources.ConsoleCommandHandlers.TryGetValue(pluginName, out plugin)) { return null; } return plugin; } private static ConsoleCommandHandlerSettings GetSettings() { var configuration = ConfigurationServices.ConfigurationSource; if (configuration == null) return null; return configuration.GetSection(ConsoleCommandHandlerSettings.SectionName) as ConsoleCommandHandlerSettings; } public static bool HasConfiguration() { return GetSettings() != null; } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", ConsoleCommandHandlerSettings.SectionName), ex); } private sealed class Resources { ConsoleCommandHandlerFactory Factory { get; set; } public IReadOnlyDictionary ConsoleCommandHandlers { get; private set; } public static void DoInitializeResources(Resources resources) { var settings = GetSettings(); if (settings == null) return; try { var factory = resources.Factory = new ConsoleCommandHandlerFactory(); resources.ConsoleCommandHandlers = settings.ConsoleCommandHandlers.ToDictionary(data => data.Name, data => factory.Create(data.Name)); } catch (Exception ex) { if (!(ex is ArgumentException) && !(ex is ConfigurationErrorsException)) throw; HandleConfigurationError(ex); } } } } } ================================================ FILE: Composite/C1Console/Commands/IConsoleCommandHandler.cs ================================================ using Composite.C1Console.Commands.Plugins.ConsoleCommandHandler.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Commands { /// /// Handles hash based deep links to C1 CMS console (/Composite/top.aspx#<command name>;<command payload> ) /// [CustomFactory(typeof(ConsoleCommandHandlerCustomFactory))] public interface IConsoleCommandHandler { /// /// Executes certain actions on console load /// /// The console id. /// The command payplod. void HandleConsoleCommand(string consoleId, string commandPayload); } } ================================================ FILE: Composite/C1Console/Commands/Plugins/ConsoleCommandHandler/ConsoleCommandHandlerData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Commands.Plugins.ConsoleCommandHandler { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ConfigurationElementType(typeof(NonConfigurableConsoleCommandHandler))] public class ConsoleCommandHandlerData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/C1Console/Commands/Plugins/ConsoleCommandHandler/NonConfigurableConsoleCommandHandler.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.C1Console.Commands.Plugins.ConsoleCommandHandler { [Assembler(typeof(NonConfigurableConsoleCommandHandlerAssembler))] internal sealed class NonConfigurableConsoleCommandHandler : ConsoleCommandHandlerData { } internal sealed class NonConfigurableConsoleCommandHandlerAssembler : IAssembler { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IConsoleCommandHandler Assemble(IBuilderContext context, ConsoleCommandHandlerData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IConsoleCommandHandler)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/C1Console/Commands/Plugins/ConsoleCommandHandler/Runtime/ConsoleCommandHandlerCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Commands.Plugins.ConsoleCommandHandler.Runtime { internal class ConsoleCommandHandlerCustomFactory : AssemblerBasedCustomFactory { protected override ConsoleCommandHandlerData GetConfiguration(string name, IConfigurationSource configurationSource) { const string sectionName = ConsoleCommandHandlerSettings.SectionName; var settings = (ConsoleCommandHandlerSettings)configurationSource.GetSection(sectionName); if (settings == null) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", sectionName)); } return settings.ConsoleCommandHandlers.Get(name); } } } ================================================ FILE: Composite/C1Console/Commands/Plugins/ConsoleCommandHandler/Runtime/ConsoleCommandHandlerFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Commands.Plugins.ConsoleCommandHandler.Runtime { internal sealed class ConsoleCommandHandlerFactory : NameTypeFactoryBase { public ConsoleCommandHandlerFactory(): base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/C1Console/Commands/Plugins/ConsoleCommandHandler/Runtime/ConsoleCommandHandlerSettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Commands.Plugins.ConsoleCommandHandler.Runtime { internal class ConsoleCommandHandlerSettings : SerializableConfigurationSection { public const string SectionName = "Composite.C1Console.Commands.Plugins.ConsoleCommandHandlerConfiguration"; private const string _elem_ConsoleCommandHandlers = "ConsoleCommandHandlers"; [ConfigurationProperty(_elem_ConsoleCommandHandlers)] public NameTypeManagerTypeConfigurationElementCollection ConsoleCommandHandlers { get { return (NameTypeManagerTypeConfigurationElementCollection)base[_elem_ConsoleCommandHandlers]; } } } } ================================================ FILE: Composite/C1Console/Drawing/FunctionPresentation.cs ================================================ using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Web; using System.Web.Hosting; using Composite.Core.IO; using Composite.Core.ResourceSystem; using Composite.Core.WebClient; namespace Composite.C1Console.Drawing { internal static class FunctionPresentation { public static void GenerateFunctionBoxWithPreview( HttpContext context, string functionTitle, Bitmap previewImage, bool showEditButton, Stream outputStream) { using (var header = new FunctionHeader(functionTitle, false, showEditButton)) { var headerSize = header.HeaderSize; Size totalSize = new Size(Math.Max(header.HeaderSize.Width, previewImage.Width), headerSize.Height + previewImage.Height); using (var bitmap = new Bitmap(totalSize.Width, totalSize.Height)) using (var graphics = Graphics.FromImage(bitmap)) { header.DrawHeader(bitmap, graphics, totalSize.Width); Point previewImageOffset = new Point( (Math.Max(totalSize.Width - 10, previewImage.Width) - previewImage.Width) / 2, headerSize.Height); // Preview image graphics.DrawImage(previewImage, previewImageOffset); // Image outline using (var brush = new HatchBrush(HatchStyle.LargeCheckerBoard, Color.FromArgb(190, 190, 190), Color.Transparent)) using (var pen = new Pen(brush)) { graphics.DrawRectangle(pen, new Rectangle(previewImageOffset, new Size(previewImage.Width - 1, previewImage.Height - 1))); } context.Response.ContentType = "image/png"; context.Response.Cache.SetExpires(DateTime.Now.AddDays(10)); string tempFileName = Path.GetTempFileName(); try { // Saving to a temporary file, as Image.Save() sometimes on a not seekable stream throws // an "A generic error occurred in GDI+." exception bitmap.Save(tempFileName, ImageFormat.Png); context.Response.WriteFile(tempFileName); context.Response.Flush(); } finally { C1File.Delete(tempFileName); } } } } public static void GenerateFunctionBoxWithText( HttpContext context, string functionTitle, bool isWarning, bool showEditButton, ICollection lines, Stream outputStream) { using (var header = new FunctionHeader(functionTitle, isWarning, showEditButton)) { var headerSize = header.HeaderSize; const int minTextAreaWidth = 350; const int leftPadding = 14, rightPadding = 10, topPadding = 12, bottomPadding = 10; var linesTrimmed = lines.Take(20).ToList(); using (var textFont = new Font("Helvetica", 9.5f, FontStyle.Regular)) { int lineHeight = MeasureText("Text", textFont).Height; Size totalSize = new Size(Math.Max(headerSize.Width, minTextAreaWidth), headerSize.Height + topPadding + lineHeight * linesTrimmed.Count + bottomPadding); using (var bitmap = new Bitmap(totalSize.Width, totalSize.Height)) using (var graphics = Graphics.FromImage(bitmap)) { graphics.Clear(Color.White); header.DrawHeader(bitmap, graphics, totalSize.Width); using(var solidBrush = new SolidBrush(Color.Gray)) for (int i = 0; i < linesTrimmed.Count; i++) { var line = linesTrimmed[i]; int lineY = headerSize.Height + topPadding + i * lineHeight; int maxLineWidth = totalSize.Width - leftPadding - rightPadding; string croppedLine = CropLineToFitMaxWidth(line, textFont, maxLineWidth); graphics.DrawString(croppedLine, textFont, solidBrush, leftPadding, lineY); } // Text outline using (var pen = new Pen(isWarning ? Color.Red : Color.Gray)) { graphics.DrawRectangle(pen, new Rectangle(0, headerSize.Height, totalSize.Width - 1, totalSize.Height - headerSize.Height - 1)); } context.Response.ContentType = "image/png"; context.Response.Cache.SetExpires(DateTime.Now.AddDays(10)); string tempFileName = Path.GetTempFileName(); try { // Saving to a temporary file, as Image.Save() sometimes on a not seekable stream throws // an "A generic error occurred in GDI+." exception bitmap.Save(tempFileName, ImageFormat.Png); context.Response.WriteFile(tempFileName); context.Response.Flush(); } finally { C1File.Delete(tempFileName); } } } } } public static Size MeasureText(string text, Font font) { using (var b = new Bitmap(1, 1)) using (var g = Graphics.FromImage(b)) { SizeF sizeF = g.MeasureString(text, font); return new Size((int)Math.Ceiling(sizeF.Width), (int)Math.Ceiling(sizeF.Height)); } } private static string CropLineToFitMaxWidth(string line, Font textFont, int maxLineWidth) { if (line.Length <= 10 || MeasureText(line, textFont).Width <= maxLineWidth) return line; if (line.Length > 250) { line = line.Substring(250); } return CropLineToFitMaxWidth(line.Substring(0, line.Length - 5) + "...", textFont, maxLineWidth); } private static void MakeBlackTransparent(Bitmap bitmap, Rectangle rect) { for (int x = 0; x < rect.Width; x++) { for (int y = 0; y < rect.Height; y++) { int totalX = rect.X + x; int totalY = rect.Y + y; var color = bitmap.GetPixel(totalX, totalY); if (color.R != 255 || color.G != 255 || color.B != 255) { int alpha = (color.R + color.G + color.B) / 3; bitmap.SetPixel(totalX, totalY, Color.FromArgb(alpha, 255, 255, 255)); } } } } private class FunctionHeader: IDisposable { const int HeaderHeight = 60; private const int TitleAndEditSpacing = 25; private readonly int _headerWidth; private readonly Font _titleFont; private readonly Font _buttonFont; private readonly string _title; readonly string _editLabel = LocalizationFiles.Composite_Web_VisualEditor.Function_Edit; private readonly Point _titlePosition; private Size _titleSize; private Size _editLabelSize; private readonly Image _functionIcon; private readonly bool _isWarning; private readonly bool _showEditButton; private static readonly string FunctionIconPath = GetIconPath("images/function.png"); private static readonly string EditFunctionIconPath = GetIconPath("images/editfunction.png"); private static readonly string WarningIconPath = GetIconPath("images/warning.png"); private static string GetIconPath(string relativePath) { return HostingEnvironment.MapPath(UrlUtils.ResolveAdminUrl(relativePath)); } private Image SafeImageFromFile(string path) { using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { var img = Bitmap.FromStream(fs); return img; } } public FunctionHeader(string title, bool isWarning, bool showEditButton) { _title = title; _showEditButton = showEditButton; _titleFont = new Font("Helvetica", 12.0f, FontStyle.Regular); _buttonFont = new Font("Helvetica", 9.0f, FontStyle.Bold); _titleSize = MeasureText(_title, _titleFont); _isWarning = isWarning; _functionIcon = SafeImageFromFile(_isWarning ? WarningIconPath : FunctionIconPath); int leftPadding = 15; _titlePosition = new Point(leftPadding + _functionIcon.Width, (HeaderHeight - _titleSize.Height) / 2); int editButtonSizeWithPaddings = 0; if (showEditButton) { _editLabelSize = MeasureText(_editLabel, _buttonFont); editButtonSizeWithPaddings = _editLabelSize.Width + 45; } _headerWidth = _titlePosition.X + _titleSize.Width + editButtonSizeWithPaddings + TitleAndEditSpacing; MinimumWidth = _titlePosition.X + editButtonSizeWithPaddings; } public int MinimumWidth { get; private set; } public Size HeaderSize { get { return new Size(_headerWidth, HeaderHeight); } } public void DrawHeader(Bitmap bitmap, Graphics graphics, int bitmapWidth) { using (var whiteBrush = new SolidBrush(Color.White)) { graphics.FillRectangle(whiteBrush, 0, 0, bitmapWidth, HeaderHeight); } // Function icon var functionIconRec = new Rectangle(10, (HeaderHeight - _functionIcon.Height) / 2, _functionIcon.Width, _functionIcon.Height); graphics.DrawImage(_functionIcon, functionIconRec); // Title using (var solidBrush = new SolidBrush(_isWarning ? Color.Red : Color.Black)) { graphics.DrawString(_title, _titleFont, solidBrush, _titlePosition); } if (!_isWarning) { // Making the icon and the label transparent MakeBlackTransparent(bitmap, functionIconRec); var textSize = MeasureText(_title, _titleFont); var textRec = new Rectangle(_titlePosition.X, _titlePosition.Y, textSize.Width, textSize.Height); MakeBlackTransparent(bitmap, textRec); } // "Edit" label if (_showEditButton) { DrawTransparentEditButton(bitmap, graphics, bitmapWidth); } } private void DrawTransparentEditButton(Bitmap bitmap, Graphics graphics, int bitmapWidth) { Point editLabelPosition = new Point(bitmapWidth - TitleAndEditSpacing - _editLabelSize.Width, (HeaderHeight - _editLabelSize.Height) / 2); using (var whiteBrush = new SolidBrush(Color.White)) { graphics.FillRectangle(whiteBrush, editLabelPosition.X - 50, 0, bitmapWidth - editLabelPosition.X + 50, HeaderHeight); } using (var solidBrush = new SolidBrush(Color.Black)) { graphics.DrawString(_editLabel, _buttonFont, solidBrush, editLabelPosition); } int editFunctionIconY; Size editFunctionIconSize; const int labelRightPadding = 5; // Edit function "pen" icon using (var icon = (Bitmap)SafeImageFromFile(EditFunctionIconPath)) { editFunctionIconSize = icon.Size; editFunctionIconY = (HeaderHeight - icon.Height) / 2; graphics.DrawImage(icon, editLabelPosition.X - icon.Width, editFunctionIconY); // Mirroring 5 px of the "pen" icon for (int x = 0; x < 5; x++) { for (int y = 0; y < icon.Height; y++) { bitmap.SetPixel(editLabelPosition.X + _editLabelSize.Width + labelRightPadding + x, editFunctionIconY + y, icon.GetPixel(4 - x, y)); } } var borderColor = icon.GetPixel(10, 0); using (var pen = new Pen(borderColor)) { // Top line for edit function link graphics.DrawLine(pen, editLabelPosition.X, editFunctionIconY, editLabelPosition.X + _editLabelSize.Width + labelRightPadding, editFunctionIconY); // Bottom line for edit function link int bottomLineY = editFunctionIconY + icon.Height - 1; graphics.DrawLine(pen, editLabelPosition.X, bottomLineY, editLabelPosition.X + _editLabelSize.Width + labelRightPadding, bottomLineY); } } // Making the "Edit" button transparent var editFuncRect = new Rectangle(editLabelPosition.X - editFunctionIconSize.Width, editFunctionIconY, editFunctionIconSize.Width + _editLabelSize.Width + labelRightPadding + 5, editFunctionIconSize.Height); MakeBlackTransparent(bitmap, editFuncRect); } public void Dispose() { _titleFont.Dispose(); _buttonFont.Dispose(); _functionIcon.Dispose(); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~FunctionHeader() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } } ================================================ FILE: Composite/C1Console/Drawing/ImageTemplatedBoxCreator.cs ================================================ using System; using System.Linq; using System.Drawing; using System.Collections.Generic; namespace Composite.C1Console.Drawing { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ImageTemplatedBoxCreator { private Point _topLeftResize; private Point _bottomRightResize; private readonly Bitmap _templateBitmap; private TitleItem _titleItem; private WrappedTextItem _wrappedTextItem; private TextLinesItem _textLinesItem; private ImageItem _topRightIconItem; private ImageItem _image; private int _width; private int _height; private Bitmap _currentBitmap; /// public ImageTemplatedBoxCreator(Bitmap templateBitmap, Point topLeftResize, Point bottomRightResize) { _topLeftResize = topLeftResize; _bottomRightResize = bottomRightResize; _templateBitmap = templateBitmap; this.LinePadding = 3; this.SeparatorChar = ' '; this.MaxWidth = 700; this.MinWidth = 200; this.MinHeight = 50; } #region Simple properties /// public int MinWidth { get; set; } /// public int MaxWidth { get; set; } /// public int MinHeight { get; set; } /// public int LinePadding { get; set; } /// public char SeparatorChar { get; set; } #endregion /// public void SetTitle(string title, Size topLeftPadding, Size bottomRightPadding, Color fontColor, string fontFamilyName, float fontSize, FontStyle fontStyle) { _titleItem = new TitleItem(title, topLeftPadding, bottomRightPadding, fontColor, fontFamilyName, fontSize, fontStyle); } /// public void SetWrappedText(string text, Point topLeftPadding, Point bottomRightPadding, Color fontColor, string fontFamilyName, float fontSize, FontStyle fontStyle) { _textLinesItem = null; _wrappedTextItem = new WrappedTextItem(text, topLeftPadding, bottomRightPadding, fontColor, fontFamilyName, fontSize, fontStyle); } /// public void SetTextLines(ICollection lines, Size topLeftPadding, Size bottomRightPadding, Color fontColor, string fontFamilyName, float fontSize, FontStyle fontStyle) { _wrappedTextItem = null; _textLinesItem = new TextLinesItem(lines, topLeftPadding, bottomRightPadding, fontColor, fontFamilyName, fontSize, fontStyle); } /// public void SetIcon(Bitmap icon, Size topLeftPadding, Size bottomRightPadding) { _topRightIconItem = new ImageItem(icon, topLeftPadding, bottomRightPadding); } /// public void SetPreviewImage(Bitmap previewImage, Size topLeftPadding, Size bottomRightPadding) { _image = new ImageItem(previewImage, topLeftPadding, bottomRightPadding); } /// public Bitmap CreateBitmap() { CalculateWidthAndHeight(); _currentBitmap = new Bitmap(_templateBitmap, new Size(_width, _height)); DrawImage(_width, _height); using (Graphics graphics = Graphics.FromImage(_currentBitmap)) { if (_topRightIconItem != null) { Point point = new Point(_width - _topRightIconItem.BottomRightPadding.Width - _topRightIconItem.Image.Width, _topRightIconItem.BottomRightPadding.Height); graphics.DrawImage(_topRightIconItem.Image, point); } if (_titleItem != null) { int counter = 0; using (var solidBrush = new SolidBrush(_titleItem.FontColor)) foreach (string line in _titleItem.Lines) { int x = _titleItem.TopLeftPadding.Width; int y = _titleItem.TopLeftPadding.Height + counter * (this.LinePadding + _titleItem.LineHeight); graphics.DrawString(line, _titleItem.Font, solidBrush, x, y); counter++; } //graphics.DrawString(_titleItem.Title, _titleItem.Font, new SolidBrush(_titleItem.FontColor), _titleItem.TopLeftPadding.X, _titleItem.TopLeftPadding.Y); } int titleHeightWidthPadding = (_titleItem != null) ? _titleItem.HeightWidthPadding : 0; if (_wrappedTextItem != null) { int counter = 0; using (var solidBrush = new SolidBrush(_wrappedTextItem.FontColor)) foreach (string line in _wrappedTextItem.Lines) { int x = _wrappedTextItem.TopLeftPadding.X; int y = _wrappedTextItem.TopLeftPadding.Y + counter * (this.LinePadding + _wrappedTextItem.LineHeight) + titleHeightWidthPadding; graphics.DrawString(line, _wrappedTextItem.Font, solidBrush, x, y); counter++; } } else if (_textLinesItem != null) { int counter = 0; using (var solidBrush = new SolidBrush(_textLinesItem.FontColor)) foreach (string line in _textLinesItem.Lines) { int x = _textLinesItem.TopLeftPadding.Width; int y = _textLinesItem.TopLeftPadding.Height + counter * (this.LinePadding + _textLinesItem.LineHeight) + titleHeightWidthPadding; graphics.DrawString(line, _textLinesItem.Font, solidBrush, x, y); counter++; } } } return _currentBitmap; } private void CalculateWidthAndHeight() { int width = MinWidth; int height = MinHeight; using (Graphics graphics = Graphics.FromImage(_templateBitmap)) { int titleHeightWithPadding = 0; if (_titleItem != null) { // SplitLine(width - _wrappedTextItem.TopLeftPadding.X - _wrappedTextItem.BottomRightPadding.X, _wrappedTextItem.Text, _wrappedTextItem.Font, _wrappedTextItem.TopLeftPadding.Y, out textWidth, out lineHeight); SizeF titleSize = graphics.MeasureString(_titleItem.Title, _titleItem.Font); int titleWidth = (int)titleSize.Width + _titleItem.TopLeftPadding.Width + _titleItem.BottomRightPadding.Width; if (_topRightIconItem != null) { titleWidth += _topRightIconItem.GetBoxSize().Width; } int titleHeight; if (titleWidth > this.MaxWidth) { int lineHeight; _titleItem.Lines = SplitLine(this.MaxWidth - _titleItem.PaddingSize.Width, _titleItem.Title, _titleItem.Font, _titleItem.TopLeftPadding.Height, out titleWidth, out lineHeight); _titleItem.LineHeight = lineHeight; width = this.MaxWidth; titleHeight = _titleItem.Lines.Count * _titleItem.LineHeight + (_titleItem.Lines.Count - 1) * this.LinePadding + _titleItem.PaddingSize.Width; if (titleHeight > height) { height = titleHeight; } } else { _titleItem.Lines = new List { _titleItem.Title }; _titleItem.LineHeight = (int)titleSize.Height; titleHeight = (int)titleSize.Height + _titleItem.PaddingSize.Height; width = titleWidth; } if (titleHeight > height) { height = titleHeight; } titleHeightWithPadding = titleHeight + this.LinePadding; _titleItem.HeightWidthPadding = titleHeightWithPadding; } if (_wrappedTextItem != null) { int textWidth, lineHeight; _wrappedTextItem.Lines = SplitLine(width - _wrappedTextItem.TopLeftPadding.X - _wrappedTextItem.BottomRightPadding.X, _wrappedTextItem.Text, _wrappedTextItem.Font, _wrappedTextItem.TopLeftPadding.Y + titleHeightWithPadding, out textWidth, out lineHeight); _wrappedTextItem.LineHeight = lineHeight; textWidth += _wrappedTextItem.TopLeftPadding.X + _wrappedTextItem.BottomRightPadding.X; if (textWidth > width) { width = textWidth; } int textHeight = _wrappedTextItem.Lines.Count * _wrappedTextItem.LineHeight + (_wrappedTextItem.Lines.Count - 1) * this.LinePadding + _wrappedTextItem.TopLeftPadding.Y + _wrappedTextItem.BottomRightPadding.Y + titleHeightWithPadding; if (textHeight > height) { height = textHeight; } } else if (_textLinesItem != null) { foreach (string line in _textLinesItem.Lines) { SizeF lineSize = graphics.MeasureString(line, _textLinesItem.Font); int lineWidth = (int)lineSize.Width + _textLinesItem.TopLeftPadding.Width + _textLinesItem.BottomRightPadding.Width; if (lineWidth > width) { width = lineWidth; } _textLinesItem.LineHeight = (int)lineSize.Height; } int textHeight = _textLinesItem.Lines.Count * _textLinesItem.LineHeight + (_textLinesItem.Lines.Count - 1) * this.LinePadding + _textLinesItem.TopLeftPadding.Height + _textLinesItem.BottomRightPadding.Height; if (textHeight > height) { height = textHeight; } } if (_image != null) { height = Math.Max(height, _image.GetBoxSize().Height); width = Math.Max(width, _image.GetBoxSize().Width); } if (_topRightIconItem != null) { int iconHeight = _topRightIconItem.GetBoxSize().Height; if (iconHeight > height) { height = iconHeight; } } } _width = width; _height = height; } private List SplitLine(int currentWidth, string text, Font font, int offsetY, out int newWidth, out int lineHeight) { newWidth = currentWidth; lineHeight = 0; List lines = new List(); string[] words = text.Split(this.SeparatorChar); using (Graphics graphics = Graphics.FromImage(_templateBitmap)) { foreach (string word in words) { SizeF size = graphics.MeasureString(word, font); if ((int)size.Width > newWidth) { newWidth = (int)size.Width; } lineHeight = (int)size.Height; } int index = 0; string currentLine = ""; int currentAdjustedWidth = AdjustedWidth(lines.Count + 1, newWidth, offsetY, lineHeight); while (index < words.Length) { string newLine; if (currentLine == "") { newLine = words[index]; } else { newLine = string.Format("{0}{1}{2}", currentLine, this.SeparatorChar, words[index]); } SizeF size = graphics.MeasureString(newLine, font); if ((int)size.Width < currentAdjustedWidth) { currentLine = newLine; index++; } else { lines.Add(currentLine); currentLine = ""; currentAdjustedWidth = AdjustedWidth(lines.Count + 1, newWidth, offsetY, lineHeight); } } lines.Add(currentLine); } return lines; } /// public int AdjustedWidth(int currentLineNumber, int width, int offsetY, int lineHeight) { if (_topRightIconItem == null) return width; int lineTop = (currentLineNumber - 1) * (lineHeight + this.LinePadding) + offsetY; int lineBottom = lineTop + lineHeight; int iconTop = _topRightIconItem.TopLeftPadding.Height; int iconBottom = _topRightIconItem.GetBoxSize().Height; if ((lineTop >= iconTop) && (lineBottom <= iconBottom)) { return width - _topRightIconItem.GetBoxSize().Width; } return width; } private void DrawImage(int width, int height) { int topBorder = _topLeftResize.Y; int bottomBorder = _templateBitmap.Height - _bottomRightResize.Y; int leftBorder = _topLeftResize.X; int rightBorder = _templateBitmap.Width - _bottomRightResize.X; int newRightOffset = width - rightBorder; int newBottomOffset = height - bottomBorder; // Top left cornor DrawCornor(leftBorder, topBorder, 0, 0, 0, 0); // Top right cornor DrawCornor(rightBorder, topBorder, _bottomRightResize.X, 0, newRightOffset, 0); // Bottom left cornor DrawCornor(leftBorder, bottomBorder, 0, _bottomRightResize.Y, 0, newBottomOffset); // Bottom right cornor DrawCornor(rightBorder, bottomBorder, _bottomRightResize.X, _bottomRightResize.Y, newRightOffset, newBottomOffset); DrawHorizontalSide(width - leftBorder - rightBorder, topBorder, _topLeftResize.X, 0, leftBorder, 0); DrawHorizontalSide(width - leftBorder - rightBorder, bottomBorder, _topLeftResize.X, _bottomRightResize.Y, leftBorder, height - bottomBorder); DrawVerticalSide(leftBorder, height - topBorder - bottomBorder, 0, _topLeftResize.Y, 0, topBorder); DrawVerticalSide(rightBorder, height - topBorder - bottomBorder, _bottomRightResize.X, _topLeftResize.Y, width - rightBorder, topBorder); DrawInner(width - leftBorder - rightBorder, height - topBorder - bottomBorder, _topLeftResize.X, _topLeftResize.Y, leftBorder, topBorder); if (_image != null) { using (Graphics g = Graphics.FromImage(_currentBitmap)) { g.DrawImage(_image.Image, new Point(_image.TopLeftPadding)); } } } private void DrawCornor(int width, int height, int originalOffsetX, int originalOffsetY, int newOffsetX, int newOffsetY) { for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { Color color = _templateBitmap.GetPixel(x + originalOffsetX, y + originalOffsetY); _currentBitmap.SetPixel(x + newOffsetX, y + newOffsetY, color); } } } private void DrawHorizontalSide(int width, int height, int originalOffsetX, int originalOffsetY, int newOffsetX, int newOffsetY) { for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { Color color = _templateBitmap.GetPixel(originalOffsetX, y + originalOffsetY); _currentBitmap.SetPixel(x + newOffsetX, y + newOffsetY, color); } } } private void DrawVerticalSide(int width, int height, int originalOffsetX, int originalOffsetY, int newOffsetX, int newOffsetY) { for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { Color color = _templateBitmap.GetPixel(x + originalOffsetX, originalOffsetY); _currentBitmap.SetPixel(x + newOffsetX, y + newOffsetY, color); } } } private void DrawInner(int width, int height, int originalOffsetX, int originalOffsetY, int newOffsetX, int newOffsetY) { Color color = _templateBitmap.GetPixel(originalOffsetX, originalOffsetY); using (Graphics g = Graphics.FromImage(_currentBitmap)) using (var solidBrush = new SolidBrush(color)) { g.FillRectangle(solidBrush, newOffsetX, newOffsetY, width, height); } } private sealed class TitleItem : PaddedItem { public TitleItem(string title, Size topLeftPadding, Size bottomRightPadding, Color fontColor, string fontFamilyName, float fontSize, FontStyle fontStyle) : base(topLeftPadding, bottomRightPadding) { this.Title = title; this.FontColor = fontColor; this.Font = new Font(fontFamilyName, fontSize, fontStyle); } public string Title { get; private set; } public List Lines { get; set; } public int LineHeight { get; set; } public int HeightWidthPadding { get; set; } public Color FontColor { get; private set; } public Font Font { get; private set; } public override Size GetInnerDimentions() { throw new NotImplementedException(); // graphics //return new Size(0, Lines.Count * LineHeight + (Lines.Count - 1) * this.LinePadding; } } private sealed class WrappedTextItem { public WrappedTextItem(string text, Point topLeftPadding, Point bottomRightPadding, Color fontColor, string fontFamilyName, float fontSize, FontStyle fontStyle) { this.Text = text; this.TopLeftPadding = topLeftPadding; this.BottomRightPadding = bottomRightPadding; this.FontColor = fontColor; this.Font = new Font(fontFamilyName, fontSize, fontStyle); } public string Text { get; private set; } public List Lines { get; set; } public int LineHeight { get; set; } public Point TopLeftPadding { get; private set; } public Point BottomRightPadding { get; private set; } public Color FontColor { get; private set; } public Font Font { get; private set; } } private sealed class TextLinesItem { public TextLinesItem(ICollection lines, Size topLeftPadding, Size bottomRightPadding, Color fontColor, string fontFamilyName, float fontSize, FontStyle fontStyle) { this.Lines = lines; this.TopLeftPadding = topLeftPadding; this.BottomRightPadding = bottomRightPadding; this.FontColor = fontColor; this.Font = new Font(fontFamilyName, fontSize, fontStyle); } public ICollection Lines { get; private set; } public int LineHeight { get; set; } public Size TopLeftPadding { get; private set; } public Size BottomRightPadding { get; private set; } public Color FontColor { get; private set; } public Font Font { get; private set; } } private abstract class PaddedItem { public PaddedItem(Size topLeftPadding, Size bottomRightPadding) { this.TopLeftPadding = topLeftPadding; this.BottomRightPadding = bottomRightPadding; } public abstract Size GetInnerDimentions(); public Size TopLeftPadding { get; private set; } public Size BottomRightPadding { get; private set; } public Size PaddingSize { get { return new Size(TopLeftPadding.Width + BottomRightPadding.Width, TopLeftPadding.Height + BottomRightPadding.Height); } } public Size GetBoxSize() { var innerDimensions = GetInnerDimentions(); return new Size(innerDimensions.Width + TopLeftPadding.Width + BottomRightPadding.Width, innerDimensions.Height + TopLeftPadding.Height + BottomRightPadding.Height); } } private sealed class ImageItem : PaddedItem { public ImageItem(Bitmap icon, Size topRightPadding, Size bottomLeftPadding) : base(topRightPadding, bottomLeftPadding) { this.Image = icon; } public Bitmap Image { get; private set; } public override Size GetInnerDimentions() { return Image.Size; } } } } ================================================ FILE: Composite/C1Console/Elements/ActionCategory.cs ================================================ using System; namespace Composite.C1Console.Elements { /// /// Enumeration of different types of actions. If in doupt use 'Other'. /// public enum ActionType { /// /// The action will enable the user to edit the element. /// Edit, /// /// The action will enable the user to add a child element. /// Add, /// /// The action will enable the user to delete the element. /// Delete, /// /// The action will enable the user to get a report, manage meta dtata or other non add/edit/delete actions /// Other, /// /// The action will should only appear in debug builds, where the C1 Console is running in developer mode. Normal users are very unlikely to ever see this action. /// DeveloperMode } /// /// The priority/relevance of an action group. Use 'PrimaryHigh' if actions in this group are the most relevant actions available. Otherwise use another value to move actions down in menus. /// public enum ActionGroupPriority { /// /// Use this when actions in the group are of the outmost importance/relevance, like 'Edit Page' og a page. /// PrimaryHigh = 0, /// /// Use this when actions in the group are primary for the element it is attached to, but not used very often. /// PrimaryMedium = 1, /// /// Use this when actions in the group are primary for the element it is attached to, but very seldom not used. /// PrimaryLow = 2, /// /// Use this when actions in the group are often used and relevant (but not primary) for the element it is attached to. /// TargetedAppendHigh = 10, /// /// Use this when actions in the group are used and relevant (but not primary) for the element it is attached to. /// TargetedAppendMedium = 11, /// /// Use this when actions in the group are seldom used and relevant (but not primary) for the element it is attached to. /// TargetedAppendLow = 12, /// /// Use this when actions in the group are attached to elements in general, without specific relevance to those elements. /// GeneralAppendHigh = 20, /// /// Use this when actions in the group are attached to elements in general, without specific relevance to those elements. /// GeneralAppendMedium = 21, /// /// Use this when actions in the group are attached to elements in general, without specific relevance to those elements. /// GeneralAppendLow = 22 } /// /// Actions may have a checkbox associated with them, indicating it they are turned on or not or uncheckable. /// public enum ActionCheckedStatus { /// /// The action can not be checked/unchecked. This is typical default behaviour of an action. /// Uncheckable, /// /// The action is unchecked and can be checked. /// Unchecked, /// /// The action is checked and can be unchecked. /// Checked } /// /// Define a priority/relevance and optional named group for an action. The priority/relevance influence the position of the action in menus. /// public sealed class ActionGroup { /// /// Initializes a new instance. /// /// the priority/relecance of the action in relation to the element it is attached to public ActionGroup(ActionGroupPriority priority) { if (priority!=ActionGroupPriority.PrimaryHigh) { throw new ArgumentException("Unnamed action groups must be called with the PrimaryHigh priority. They serve as a way do deliver common core tasks, like 'delete'. Specify a group name if this is not a core action."); } this.Name = ""; this.Priority = priority; } /// /// Initializes a new instance with a custom named group. /// /// A name of your choosing. If this name is used by multiple actions they may be bundled into the same group. /// the priority/relecance of the action in relation to the element it is attached to public ActionGroup(string name, ActionGroupPriority priority) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("Parameter 'name' must have a value"); } if (priority == ActionGroupPriority.PrimaryHigh) { throw new ArgumentException("Named action groups can not be called with the PrimaryHigh priority. They serve as a way do deliver non-core tasks, like 'search'."); } this.Name = name; this.Priority = priority; } /// /// The custom name of the group. An empty string if the group is not named. /// public string Name { get; set; } /// /// Priority/relevance of the action. /// public ActionGroupPriority Priority { get; set; } } /// /// Define the location of an action in menus. Actions can be grouped by type (add,edit,delete,other) and in primary and secondary. /// public sealed class ActionLocation { /// /// A primary action, adding data. This will make the action show up between add and delete, next to other add actions (if any). /// public readonly static ActionLocation AddPrimaryActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh) }; /// /// A primary action, editing data. This will make the action show up as one of the first, next to other edit actions (if any). /// public readonly static ActionLocation EditPrimaryActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh) }; /// /// A primary action, deleting data. This will make the action show up after edit and add actions, next to other delete actions (if any). /// public readonly static ActionLocation DeletePrimaryActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh) }; /// /// A primary action, doing something besides from add, edit and delete. This can be a view/report actions etc. /// public readonly static ActionLocation OtherPrimaryActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = true, ActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh) }; /// public ActionLocation() { this.ActionGroup = new ActionGroup("Common tasks", ActionGroupPriority.GeneralAppendLow); this.ActionType = ActionType.Other; } /// /// Where the action should be grouped. Grouping is typically based on a priority, but can be a unique named group you define. /// If your action is a primary action for the element it is attacted to you should ensure the ActionGroupPriorty is set to PrimaryHigh. /// The lower priority, the lower in a menu list the action will appear. /// public ActionGroup ActionGroup { get; set; } /// /// Declare what type of action this is: Edit, Add, Delete, Other. You may also use 'DeveloperMode' which will hide the action when the C1 Console run in normal operations mode. /// public ActionType ActionType { get; set; } /// /// Set to true if your action is important enough to be shown in the toolbar. If this is a very specialized command, consider not showing it in the toolbar. /// public bool IsInToolbar { get; set; } /// /// Not implemented at client level. Setting this to true will have no effect. /// public bool IsInFolder { get; set; } /// /// Not implemented at client level. Setting a folder name will have no effect. /// public string FolderName { get; set; } /// /// Bundle actions behind a drop down button. If multiple actions on an element share ActionBundle value, they can be compounded in the client UI. /// public string ActionBundle { get; set; } } } ================================================ FILE: Composite/C1Console/Elements/ActionHandle.cs ================================================ using Composite.C1Console.Security; namespace Composite.C1Console.Elements { /// /// A handle to an action - a unique and serializable way to identify actions. /// public sealed class ActionHandle { private readonly ActionToken _actionToken; private string _serializedActionToken; /// /// Constructs a new instance. /// /// public ActionHandle(ActionToken actionToken) { _actionToken = actionToken; } /// /// represented by this handle. /// public ActionToken ActionToken => _actionToken; private string SerializedActionToken { get { if (_serializedActionToken == null) { _serializedActionToken = _actionToken.Serialize(); } return _serializedActionToken; } } /// public override bool Equals(object obj) => Equals(obj as ActionHandle); /// public bool Equals(ActionHandle actionHandle) { if (actionHandle == null) return false; return this.SerializedActionToken == actionHandle.SerializedActionToken; } /// public override int GetHashCode() { return this.SerializedActionToken.GetHashCode(); } } } ================================================ FILE: Composite/C1Console/Elements/ActionVisualizedData.cs ================================================ using Composite.Core.ResourceSystem; namespace Composite.C1Console.Elements { /// /// Describe how an action should appear visually (label, icon). /// public sealed class ActionVisualizedData { /// /// Constructs a new instance /// public ActionVisualizedData() { this.ActionCheckedStatus = ActionCheckedStatus.Uncheckable; ActivePositions = ElementActionActivePosition.NavigatorTree; } /// /// Constructs a new instance, cloning an existing instance. /// /// public ActionVisualizedData(ActionVisualizedData copy) { this.ActionLocation = copy.ActionLocation; this.Disabled = copy.Disabled; this.Icon = copy.Icon; this.Label = copy.Label; this.ToolTip = copy.ToolTip; this.ActionCheckedStatus = copy.ActionCheckedStatus; this.ActivePositions = copy.ActivePositions; } /// /// Controls if a check box should be shown next to the action command, and if this checkbox is checked. /// public ActionCheckedStatus ActionCheckedStatus { get; set; } /// /// Label of the action /// public string Label { get; set; } /// /// When disabled, the action will be shown but grayed out and cannot be invoked. /// public bool Disabled { get; set; } /// /// The action's icon /// public ResourceHandle Icon { get; set; } /// /// The action's tool tip /// public string ToolTip { get; set; } /// /// Where the action should show up, relative to other actions. /// public ActionLocation ActionLocation { get; set; } /// /// The string to be shown in a confirm dialog when executing the action for multiple elements. /// public DialogStrings BulkExecutionDialog { get; set; } /// /// Where the action should be shown - when elements are shown in a selection tree (as opposed to the normal navigation tree) some actions may be desired. /// Default is ElementActionActivePosition.NavigatorTree only. /// public ElementActionActivePosition ActivePositions { get; set; } /// public override string ToString() { return Label; } } } ================================================ FILE: Composite/C1Console/Elements/AttachingPoint.cs ================================================ using System; using Composite.Plugins.Elements.ElementProviders.VirtualElementProvider; using Composite.C1Console.Security; using Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider; namespace Composite.C1Console.Elements { /// /// Expose ElementTokens for common C1 Console perspectives and folders /// public sealed class AttachingPoint { private const string BuildInVirtualElementProviderName = "VirtualElementProvider"; private static readonly AttachingPoint _rootPerspectiveAttachingPoint = VirtualElementAttachingPoint("ID01"); private static readonly AttachingPoint _contentPerspectiveAttachingPoint = VirtualElementAttachingPoint("ContentPerspective"); private static readonly AttachingPoint _contentPerspectiveWebsiteItemsAttachingPoint = new AttachingPoint { EntityTokenType = typeof(GeneratedDataTypesElementProviderRootEntityToken), Id = "GlobalDataTypeFolder", Source = "GlobalDataOnlyGeneratedDataTypesElementProvider" }; private static readonly AttachingPoint _mediaPerspectiveAttachingPoint = VirtualElementAttachingPoint("MediaPerspective"); private static readonly AttachingPoint _dataPerspectiveAttachingPoint = VirtualElementAttachingPoint("DatasPerspective"); private static readonly AttachingPoint _designPerspectiveAttachingPoint = VirtualElementAttachingPoint("DesignPerspective"); private static readonly AttachingPoint _functionPerspectiveAttachingPoint = VirtualElementAttachingPoint("FunctionsPerspective"); private static readonly AttachingPoint _systemPerspectiveAttachingPoint = VirtualElementAttachingPoint("SystemPerspective"); /// /// Attaching point for the C1 Console Root /// public static AttachingPoint PerspectivesRoot { get { return _rootPerspectiveAttachingPoint; } } /// /// Attaching point for the C1 Console Content perspective /// public static AttachingPoint ContentPerspective { get { return _contentPerspectiveAttachingPoint; } } /// /// Attaching point for the Website Items folder in the C1 Console Content perspective /// public static AttachingPoint ContentPerspectiveWebsiteItems { get { return _contentPerspectiveWebsiteItemsAttachingPoint; } } /// /// Attaching point for the C1 Console Media perspective /// /// public static AttachingPoint MediaPerspective { get { return _mediaPerspectiveAttachingPoint; } } /// /// Attaching point for the C1 Console Data perspective /// public static AttachingPoint DataPerspective { get { return _dataPerspectiveAttachingPoint; } } /// public static AttachingPoint DesignPerspective { get { return _designPerspectiveAttachingPoint; } } /// /// Attaching point for the C1 Console Layout perspective /// public static AttachingPoint LayoutPerspective { get { return _designPerspectiveAttachingPoint; } } /// /// Attaching point for the C1 Console Function perspective /// public static AttachingPoint FunctionPerspective { get { return _functionPerspectiveAttachingPoint; } } /// /// Attaching point for the C1 Console System perspective /// public static AttachingPoint SystemPerspective { get { return _systemPerspectiveAttachingPoint; } } private EntityToken _entityToken; internal AttachingPoint(EntityToken entityToken = null) { _entityToken = entityToken; } internal AttachingPoint(AttachingPoint attachingPoint) { _entityToken = attachingPoint._entityToken; EntityTokenType = attachingPoint.EntityTokenType; Id = attachingPoint.Id; Source = attachingPoint.Source; } internal Type EntityTokenType { get; set; } internal string Id { get; set; } internal string Source { get; set; } /// /// The for this attachment point /// public EntityToken EntityToken { get { if (_entityToken == null) { if (this.EntityTokenType == typeof(VirtualElementProviderEntityToken)) { _entityToken = new VirtualElementProviderEntityToken(BuildInVirtualElementProviderName, this.Id); } else if (this.EntityTokenType == typeof(GeneratedDataTypesElementProviderRootEntityToken)) { _entityToken = new GeneratedDataTypesElementProviderRootEntityToken(this.Source, this.Id); } else { Verify.IsNotNull(EntityTokenType, "EntityTokenType is null"); throw new InvalidOperationException("Invalid entity token type: " + EntityTokenType.FullName); } } return _entityToken; } } internal static AttachingPoint VirtualElementAttachingPoint(string elementId, string source = BuildInVirtualElementProviderName) { return new AttachingPoint { EntityTokenType = typeof(VirtualElementProviderEntityToken), Id = elementId, Source = source }; } } } ================================================ FILE: Composite/C1Console/Elements/DialogStrings.cs ================================================ using System; namespace Composite.C1Console.Elements { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class DialogStrings { /// public string Title { get; set; } /// public string Text { get; set; } } } ================================================ FILE: Composite/C1Console/Elements/Element.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Core.Logging; namespace Composite.C1Console.Elements { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Flags] public enum ElementExternalActionAdding { /// AllowGlobal = 1, /// AllowProcessController = 2, /// AllowManageUserPermissions = 4 } internal static class ElementExternalActionAddingExtensions { public static ElementExternalActionAdding Remove(this ElementExternalActionAdding currentValue, ElementExternalActionAdding valueToRemove) { if ((currentValue & valueToRemove) == valueToRemove) { currentValue = currentValue ^ valueToRemove; } return currentValue; } } /// /// Define a tree element to be displayed in the C1 Console tree structure /// [DebuggerDisplay("{VisualData.Label}")] public sealed class Element { private ElementHandle _elementHandle; private List _elementActions = new List(); private Dictionary _propertyBag = new Dictionary(); private Element() { this.MovabilityInfo = new ElementDragAndDropInfo(); this.ElementExternalActionAdding = ElementExternalActionAdding.AllowGlobal | ElementExternalActionAdding.AllowProcessController | ElementExternalActionAdding.AllowManageUserPermissions; this.TreeLockBehavior = TreeLockBehavior.Normal; } /// /// Constructs a new from the given . /// /// public Element(ElementHandle elementHandle) : this() { if (elementHandle == null) throw new ArgumentNullException("elementHandle"); _elementHandle = elementHandle; } /// /// Constructs a new from the given and . /// /// /// public Element(ElementHandle elementHandle, ElementVisualizedData visualData) : this() { if (elementHandle == null) throw new ArgumentNullException("elementHandle"); if (visualData == null) throw new ArgumentNullException("visualData"); _elementHandle = elementHandle; this.VisualData = visualData; } /// /// Constructs a new from the given and . /// /// /// public Element(ElementHandle elementHandle, ElementDragAndDropInfo movabilityInfo) : this() { if (elementHandle == null) throw new ArgumentNullException("elementHandle"); if (movabilityInfo == null) throw new ArgumentNullException("movabilityInfo"); _elementHandle = elementHandle; this.MovabilityInfo = movabilityInfo; } /// /// Constructs a new from the given , and . /// /// /// /// public Element(ElementHandle elementHandle, ElementVisualizedData visualData, ElementDragAndDropInfo movabilityInfo) : this() { if (elementHandle == null) throw new ArgumentNullException("elementHandle"); if (visualData == null) throw new ArgumentNullException("visualData"); if (movabilityInfo == null) throw new ArgumentNullException("movabilityInfo"); _elementHandle = elementHandle; this.VisualData = visualData; this.MovabilityInfo = movabilityInfo; } /// /// The for this Element. /// public ElementHandle ElementHandle { get { return _elementHandle; } } /// /// The for this Element. /// public ElementVisualizedData VisualData { get; set; } /// /// The for this Element. /// public ElementDragAndDropInfo MovabilityInfo { get; private set; } /// public bool IsLocaleAware { get; set; } /// /// Custom properties to attach to this Element /// public Dictionary PropertyBag { get { return _propertyBag; } } /// public string TagValue { get; set; } /// public TreeLockBehavior TreeLockBehavior { get; set; } #region Action methods /// public ElementExternalActionAdding ElementExternalActionAdding { get; set; } /// public int ActionCount { get { return _elementActions.Count; } } internal void AddWorkflowAction(string workflowType, IEnumerable permissionType, ActionVisualizedData visualizedData) { Type type = WorkflowFacade.GetWorkflowType(workflowType); this.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(type, permissionType))) { VisualData = visualizedData }); } /// /// Add an action to the element /// /// The action to add public void AddAction(ElementAction elementAction) { Verify.ArgumentNotNull(elementAction, "elementAction"); if (_elementActions.Contains(elementAction) == false) { _elementActions.Add(elementAction); } else { LoggingService.LogWarning("Element", string.Format("An action with the same action token type '{0}' and same serialized string '{1}' has already been added", elementAction.ActionHandle.ActionToken.GetType(), elementAction.ActionHandle.ActionToken.Serialize())); } } /// /// Add one or more actions to the element /// /// The actions to add public void AddAction(IEnumerable elementActions) { Verify.ArgumentNotNull(elementActions, "elementActions"); foreach (ElementAction elementAction in elementActions) { AddAction(elementAction); } } /// /// Remove an action from the element /// /// The action to remove public void RemoveAction(ElementAction elementAction) { if (elementAction == null) throw new ArgumentNullException("elementAction"); _elementActions.Remove(elementAction); } internal void RemoveMovabilityInfo() { MovabilityInfo = new ElementDragAndDropInfo(); } /// /// Actions declared on this element /// public IEnumerable Actions { get { return _elementActions; } } #endregion /// public override bool Equals(object obj) { return Equals(obj as Element); } /// public bool Equals(Element element) { if (element == null) return false; return element.ElementHandle.EntityToken.Equals(this.ElementHandle.EntityToken); } /// public override int GetHashCode() { return this.ElementHandle.EntityToken.GetHashCode(); } } } ================================================ FILE: Composite/C1Console/Elements/ElementAction.cs ================================================ using Composite.C1Console.Security; namespace Composite.C1Console.Elements { /// /// Define an action you can attach to an . /// public sealed class ElementAction { /// /// Constructs a new instance. /// /// public ElementAction(ActionHandle actionHandle) { Verify.ArgumentNotNull(actionHandle, nameof(actionHandle)); ActionHandle = actionHandle; } /// /// Constructs a new instance. /// /// public ElementAction(ActionToken actionToken): this(new ActionHandle(actionToken)) { } /// /// The action handle /// public ActionHandle ActionHandle { get; } /// /// The visual representation (label, icon) of the action /// public ActionVisualizedData VisualData { get; set; } /// public string TagValue { get; set; } /// public override int GetHashCode() => this.ActionHandle.GetHashCode(); } } ================================================ FILE: Composite/C1Console/Elements/ElementActionActivePosition.cs ================================================ using System; namespace Composite.C1Console.Elements { /// /// Where an action should be shown visually. One or more may be selected. /// [Flags] public enum ElementActionActivePosition { /// /// Available in the C1 Consoles default navigation tree. /// NavigatorTree = 1, /// /// Available in trees used for item selection (typically shown via pop ups). /// SelectorTree = 2, } } ================================================ FILE: Composite/C1Console/Elements/ElementActionSecurityExtensions.cs ================================================ //#warning REMARK THIS!!! //#define NO_SECURITY using System; using System.Collections.Generic; using Composite.C1Console.Security; using Composite.Core.Linq; using Composite.Plugins.Elements.ElementProviders.PageElementProvider; namespace Composite.C1Console.Elements { /// /// Extension methods related to security on element actions. /// public static class ElementActionSecurityExtensions { /// /// Will filter actions (according to current users permissions) attached on the elements /// /// Elements to filder /// New sequence of elements, with actions filtered public static IEnumerable FilterElementsAndActions(this IEnumerable elements) { Verify.ArgumentNotNull(elements, nameof(elements)); #if NO_SECURITY return elements; #else UserToken userToken = UserValidationFacade.GetUserToken(); var userPermissionDefinitions = PermissionTypeFacade.GetUserPermissionDefinitions(userToken.Username).Evaluate(); var userGroupPermissionDefinition = PermissionTypeFacade.GetUserGroupPermissionDefinitions(userToken.Username).Evaluate(); return elements .FilterElements(userToken, userPermissionDefinitions, userGroupPermissionDefinition) .FilterActions(userToken, userPermissionDefinitions, userGroupPermissionDefinition); #endif } internal static IEnumerable FilterElements(this IEnumerable elements) { #if NO_SECURITY return elements; #endif var userToken = UserValidationFacade.GetUserToken(); var userPermissions = PermissionTypeFacade.GetUserPermissionDefinitions(userToken.Username).Evaluate(); var userGroupPermissions = PermissionTypeFacade.GetUserGroupPermissionDefinitions(userToken.Username).Evaluate(); return FilterElements(elements, userToken, userPermissions, userGroupPermissions); } internal static IEnumerable FilterElements(this IEnumerable elements, UserToken userToken, ICollection userPermissionDefinitions, ICollection userGroupPermissionDefinition) { Verify.ArgumentNotNull(elements, nameof(elements)); #if NO_SECURITY return elements; #else foreach (Element element in elements) { if (PermissionTypeFacade.IsSubBrachContainingPermissionTypes(userToken, element.ElementHandle.EntityToken, userPermissionDefinitions, userGroupPermissionDefinition)) { yield return element; } } #endif } internal static IEnumerable FilterActions(this IEnumerable elements) { #if NO_SECURITY return elements; #endif var userToken = UserValidationFacade.GetUserToken(); var userPermissions = PermissionTypeFacade.GetUserPermissionDefinitions(userToken.Username).Evaluate(); var userGroupPermissions = PermissionTypeFacade.GetUserGroupPermissionDefinitions(userToken.Username).Evaluate(); return FilterActions(elements, userToken, userPermissions, userGroupPermissions); } internal static IEnumerable FilterActions(this IEnumerable elements, UserToken userToken, ICollection userPermissionDefinitions, ICollection userGroupPermissionDefinition) { Verify.ArgumentNotNull(elements, nameof(elements)); #if NO_SECURITY return elements; #else foreach (var element in elements) { var actionsToRemove = new List(); foreach (ElementAction elementAction in element.Actions) { if (SecurityResolver.Resolve(userToken, elementAction.ActionHandle.ActionToken, element.ElementHandle.EntityToken, userPermissionDefinitions, userGroupPermissionDefinition) == SecurityResult.Disallowed) { actionsToRemove.Add(elementAction); } } foreach (ElementAction elementAction in actionsToRemove) { element.RemoveAction(elementAction); } // Drag & drop security if (element.MovabilityInfo != null) { if (SecurityResolver.Resolve(userToken, new DragAndDropActionToken(), element.ElementHandle.EntityToken, userPermissionDefinitions, userGroupPermissionDefinition) == SecurityResult.Disallowed) { element.RemoveMovabilityInfo(); } } yield return element; } #endif } } } ================================================ FILE: Composite/C1Console/Elements/ElementAttachingPointFacade.cs ================================================ using Composite.C1Console.Security; using Composite.Plugins.Elements.ElementProviders.VirtualElementProvider; namespace Composite.C1Console.Elements { /// public static class ElementAttachingPointFacade { /// public static bool IsAttachingPoint(EntityToken entityToken, AttachingPoint attachingPoint) { return attachingPoint.Id == entityToken.Id && attachingPoint.Source == entityToken.Source && attachingPoint.EntityTokenType == entityToken.GetType(); } /// public static bool IsAttachingPoint(EntityToken leftEntityToken, EntityToken rightEntityToken) { return leftEntityToken.GetType() == rightEntityToken.GetType() && leftEntityToken.Id == rightEntityToken.Id && leftEntityToken.Type == rightEntityToken.Type && leftEntityToken.Source == rightEntityToken.Source; } /// public static AttachingPoint GetAttachingPoint(EntityToken entityToken) { if (entityToken is VirtualElementProviderEntityToken) { return AttachingPoint.VirtualElementAttachingPoint(entityToken.Id, entityToken.Source); } if (IsAttachingPoint(entityToken, AttachingPoint.ContentPerspectiveWebsiteItems)) { return AttachingPoint.ContentPerspectiveWebsiteItems; } return null; } } } ================================================ FILE: Composite/C1Console/Elements/ElementDataExchangeService.cs ================================================ using System; using Composite.C1Console.Elements.Foundation.PluginFacades; namespace Composite.C1Console.Elements { internal sealed class ElementDataExchangeService : IElementDataExchangeService { public ElementDataExchangeService(string elementProviderName) { this.ElementProviderName = elementProviderName; } private string ElementProviderName { get; set; } public object GetData(string name) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name"); return ElementFacade.GetData(new ElementProviderHandle(this.ElementProviderName), name); } } } ================================================ FILE: Composite/C1Console/Elements/ElementDragAndDropInfo.cs ================================================ using System; using System.Collections.Generic; namespace Composite.C1Console.Elements { /// /// Details describing how this element may be dragged or accept dragged elements /// public sealed class ElementDragAndDropInfo { private List _dropHashTypeIdentifiers = null; /// /// Constructs a new instance. /// internal ElementDragAndDropInfo() { this.DragType = null; this.SupportsIndexedPosition = false; } /// /// Constructs a new instance. /// /// Declare what this element is in terms of drag and drop by declaring a . /// Element providers accepting drag and drop of this type will accept this. public ElementDragAndDropInfo(Type movabilityType) { this.DragType = movabilityType; } /// /// Identifies a type of element in relation to movability. Used in conjunction with the AdoptTypeAcceptList. /// Use the MovabilitySubType to distinguish sub types. /// public Type DragType { get; set; } /// /// Optional. If the element provider presents data from multiple sources that can not exchange data and you /// can not communicate a unique source using a Type alone, use this field to distinguish the source. /// public string DragSubType { get; set; } /// public bool SupportsIndexedPosition { get; set; } /// public void AddDropType(Type acceptMovabilityType) { this.AddDropType(acceptMovabilityType, ""); } /// public void AddDropType(Type acceptMovabilityType, string acceptMovabilitySubType) { if (_dropHashTypeIdentifiers == null) _dropHashTypeIdentifiers = new List(); _dropHashTypeIdentifiers.Add(BuildHashedTypeIdentifier(acceptMovabilityType, acceptMovabilitySubType)); } internal string GetHashedTypeIdentifier() { return BuildHashedTypeIdentifier(this.DragType, this.DragSubType); } internal List GetDropHashTypeIdentifiers() { return _dropHashTypeIdentifiers; } private static string BuildHashedTypeIdentifier(Type type, string subType) { return string.Format("{0}:{1}:{2}", type.Name, subType, type.AssemblyQualifiedName.GetHashCode()); } } } ================================================ FILE: Composite/C1Console/Elements/ElementFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml; using Composite.Core.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Elements.Foundation; using Composite.C1Console.Elements.Foundation.PluginFacades; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.C1Console.Forms.DataServices; using Composite.C1Console.Forms.Flows; using Composite.C1Console.Security; using Composite.Core; using Composite.Core.Logging; using Composite.Core.Instrumentation; using Composite.Plugins.Elements.ElementProviders.VirtualElementProvider; namespace Composite.C1Console.Elements { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ElementFacade { private static IEnumerable _perspectiveEntityTokens; /// public static IEnumerable GetRoots(SearchToken searchToken) { return GetRoots(ElementProviderRegistry.RootElementProviderName, searchToken, true, false); } /// public static IEnumerable GetRoots(ElementProviderHandle elementProviderHandle, SearchToken searchToken) { if (elementProviderHandle == null) throw new ArgumentNullException("elementProviderHandle"); return GetRoots(elementProviderHandle.ProviderName, searchToken, true, false); } /// public static IEnumerable GetChildren(ElementHandle elementHandle, SearchToken searchToken) { if (elementHandle == null) throw new ArgumentNullException("elementHandle"); return GetChildren(elementHandle, searchToken, true, false); } /// public static IEnumerable GetLabeledProperties(ElementHandle elementHandle) { if (elementHandle == null) throw new ArgumentNullException("elementHandle"); return ElementProviderPluginFacade.GetLabeledProperties(elementHandle.ProviderName, elementHandle.EntityToken); } /// public static bool ContainsLocalizedData(ElementProviderHandle elementProviderHandle) { if (elementProviderHandle == null) throw new ArgumentNullException("elementProviderHandle"); if (ElementProviderPluginFacade.IsLocaleAwareElementProvider(elementProviderHandle.ProviderName) == false) return false; return ElementProviderPluginFacade.ContainsLocalizedData(elementProviderHandle.ProviderName); } /// public static IEnumerable GetForeignRoots(SearchToken searchToken) { return GetRoots(ElementProviderRegistry.RootElementProviderName, searchToken, true, true); } /// public static IEnumerable GetForeignRoots(ElementProviderHandle elementProviderHandle, SearchToken searchToken) { if (elementProviderHandle == null) throw new ArgumentNullException("elementProviderHandle"); return GetRoots(elementProviderHandle.ProviderName, searchToken, true, true); } /// public static IEnumerable GetForeignChildren(ElementHandle elementHandle, SearchToken searchToken) { if (elementHandle == null) throw new ArgumentNullException("elementHandle"); return GetChildren(elementHandle, searchToken, true, true); } /// public static IEnumerable GetForeignLabeledProperties(ElementHandle elementHandle) { if (elementHandle == null) throw new ArgumentNullException("elementHandle"); if (ElementProviderPluginFacade.IsLocaleAwareElementProvider(elementHandle.ProviderName)) { return ElementProviderPluginFacade.GetForeignLabeledProperties(elementHandle.ProviderName, elementHandle.EntityToken); } return ElementProviderPluginFacade.GetLabeledProperties(elementHandle.ProviderName, elementHandle.EntityToken); } /// public static object GetData(ElementProviderHandle elementProviderHandle, string dataName) { if (elementProviderHandle == null) throw new ArgumentNullException("elementProviderHandle"); if (string.IsNullOrEmpty(dataName)) throw new ArgumentNullException("dataName"); return ElementProviderPluginFacade.GetData(elementProviderHandle.ProviderName, dataName); } /// public static bool ExecuteElementDraggedAndDropped(ElementHandle draggedElementHandle, ElementHandle newParentElementHandle, int dropIndex, bool isCopy, FlowControllerServicesContainer draggedElementFlowControllerServicesContainer) { if (draggedElementHandle == null) throw new ArgumentNullException("draggedElementHandle"); if (newParentElementHandle == null) throw new ArgumentNullException("newParentElementHandle"); if (draggedElementFlowControllerServicesContainer == null) throw new ArgumentNullException("draggedElementFlowControllerServicesContainer"); if (draggedElementHandle.Equals(newParentElementHandle)) { LoggingService.LogError("ElementFacade", "ExecuteElementDraggedAndDropped on the same element is not allowed"); return false; } DragAndDropType dragAndDropType = DragAndDropType.Move; if (isCopy) { dragAndDropType = DragAndDropType.Copy; } return ElementProviderPluginFacade.OnElementDraggedAndDropped(draggedElementHandle.ProviderName, draggedElementHandle.EntityToken, newParentElementHandle.EntityToken, dropIndex, dragAndDropType, draggedElementFlowControllerServicesContainer); } /// public static SearchToken GetNewSearchToken(ElementHandle elementHandle) { if (elementHandle == null) throw new ArgumentNullException("elementHandle"); SearchToken searchToken; if (ElementProviderPluginFacade.GetNewSearchToken(elementHandle.ProviderName, elementHandle.EntityToken, out searchToken) == false) { return new SearchToken(); } return searchToken; } /// public static XmlReader GetSearchFormMarkup(ElementHandle elementHandle) { if (elementHandle == null) throw new ArgumentNullException("elementHandle"); XmlReader formDefinition; if (ElementProviderPluginFacade.GetSearchFormDefinition(elementHandle.ProviderName, elementHandle.EntityToken, out formDefinition) == false) { IFormMarkupProvider markupProvider = new FormDefinitionFileMarkupProvider("/Administrative/ElementKeywordSearch.xml"); return markupProvider.GetReader(); } return formDefinition; } /// public static Dictionary GetSearchFormBindings(ElementHandle elementHandle) { if (elementHandle == null) throw new ArgumentNullException("elementHandle"); Dictionary bindings; if (ElementProviderPluginFacade.GetSearchFormBindings(elementHandle.ProviderName, elementHandle.EntityToken, out bindings) == false) { return new Dictionary(); } return bindings; } /// public static IEnumerable GetRootsWithNoSecurity() { return GetRoots(ElementProviderRegistry.RootElementProviderName, null, false, false); } /// public static IEnumerable GetRootsWithNoSecurity(ElementProviderHandle elementProviderHandle, SearchToken searchToken) { if (elementProviderHandle == null) throw new ArgumentNullException("elementProviderHandle"); return GetRoots(elementProviderHandle.ProviderName, searchToken, false, false); } /// public static IEnumerable GetPerspectiveElements(bool performSecurityCheck) { IEnumerable rootElementHandles = GetRoots(ElementProviderRegistry.RootElementProviderName, null, performSecurityCheck, false).Select(f => f.ElementHandle); foreach (ElementHandle rootElementHandle in rootElementHandles) { IEnumerable perspectiveElements = GetChildren(rootElementHandle, null, performSecurityCheck, false); foreach (Element perspectiveElement in perspectiveElements) { yield return perspectiveElement; } } } /// public static IEnumerable GetPerspectiveElementsWithNoSecurity() { return GetPerspectiveElements(false); } internal static bool IsPerspectiveEntityToken(EntityToken entityToken) { if (!(entityToken is VirtualElementProviderEntityToken)) { return false; } if (_perspectiveEntityTokens == null) { _perspectiveEntityTokens = GetPerspectiveElementsWithNoSecurity().Select(e => e.ElementHandle.EntityToken).ToList(); } return _perspectiveEntityTokens.Contains(entityToken); } internal static bool IsLocaleAwareElementProvider(ElementProviderHandle elementProviderHandle) { if (elementProviderHandle == null) throw new ArgumentNullException("elementProviderHandle"); return ElementProviderPluginFacade.IsLocaleAwareElementProvider(elementProviderHandle.ProviderName); } private static IEnumerable GetRoots(string providerName, SearchToken searchToken, bool performSecurityCheck, bool useForeign) { if (providerName == null) throw new ArgumentNullException("providerName"); IEnumerable roots; try { if (!useForeign || !ElementProviderPluginFacade.IsLocaleAwareElementProvider(providerName)) { roots = ElementProviderPluginFacade.GetRoots(providerName, searchToken).ToList(); } else { roots = ElementProviderPluginFacade.GetForeignRoots(providerName, searchToken).ToList(); } } catch (Exception ex) when (providerName != ElementProviderRegistry.RootElementProviderName) { Log.LogError(nameof(ElementFacade), $"Failed to get root elements for element provider '{providerName}'"); Log.LogError(nameof(ElementFacade), ex); return Enumerable.Empty(); } if (performSecurityCheck) { roots = roots.FilterElements(); } ElementActionProviderFacade.AddActions(roots, providerName); if (performSecurityCheck) { return roots.FilterActions(); } return roots; } private static IEnumerable GetChildrenFromProvider(ElementHandle elementHandle, SearchToken searchToken, bool useForeign) { if (ElementProviderRegistry.ElementProviderNames.Contains(elementHandle.ProviderName)) { if (!useForeign || !ElementProviderPluginFacade.IsLocaleAwareElementProvider(elementHandle.ProviderName)) { return ElementProviderPluginFacade.GetChildren(elementHandle.ProviderName, elementHandle.EntityToken, searchToken); } return ElementProviderPluginFacade.GetForeignChildren(elementHandle.ProviderName, elementHandle.EntityToken, searchToken); } if (ElementAttachingProviderRegistry.ElementAttachingProviderNames.Contains(elementHandle.ProviderName)) { return ElementAttachingProviderPluginFacade.GetChildren(elementHandle.ProviderName, elementHandle.EntityToken, elementHandle.Piggyback); } throw new InvalidOperationException($"No element provider named '{elementHandle.ProviderName}' found"); } private static IEnumerable GetChildren(ElementHandle elementHandle, SearchToken searchToken, bool performSecurityCheck, bool useForeign) { Verify.ArgumentNotNull(elementHandle, nameof(elementHandle)); var performanceToken = PerformanceCounterFacade.BeginElementCreation(); var children = GetChildrenFromProvider(elementHandle, searchToken, useForeign).Evaluate(); var originalChildren = children; children = ElementAttachingProviderFacade.AttachElements(elementHandle.EntityToken, elementHandle.Piggyback, children).Evaluate(); int totalElementCount = children.Count; if (performSecurityCheck) { children = children.FilterElements().Evaluate(); } // Evaluating HasChildren for not attached elements foreach (Element element in originalChildren) { if (children.Contains(element) && !element.VisualData.HasChildren) { element.VisualData.HasChildren = ElementAttachingProviderFacade.HaveCustomChildElements(element.ElementHandle.EntityToken, element.ElementHandle.Piggyback); } } ElementActionProviderFacade.AddActions(children, elementHandle.ProviderName); if (performSecurityCheck) { children = children.FilterActions().Evaluate(); } PerformanceCounterFacade.EndElementCreation(performanceToken, children.Count, totalElementCount); return children; } } } ================================================ FILE: Composite/C1Console/Elements/ElementHandle.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security; namespace Composite.C1Console.Elements { /// /// An "identity token" which identifies a specific element from a specific provider. /// public sealed class ElementHandle { private readonly string _providerName; private readonly EntityToken _entityToken; private string _serializedPiggyback = null; Dictionary _piggyback = null; /// /// Constructs a new ElementHandle /// /// /// public ElementHandle(string providerName, EntityToken entityToken) : this(providerName, entityToken, (string)null) { } /// /// Constructs a new ElementHandle /// /// /// /// public ElementHandle(string providerName, EntityToken entityToken, Dictionary piggyback) { Verify.ArgumentNotNull(piggyback, "piggyback"); _providerName = providerName; _entityToken = entityToken; _piggyback = piggyback; } /// /// Constructs a new ElementHandle /// /// /// /// public ElementHandle(string providerName, EntityToken entityToken, string piggyback) { if (piggyback == null) { piggyback = string.Empty; } _providerName = providerName; _entityToken = entityToken; _serializedPiggyback = piggyback; } /// /// Name of provider this ElementHandle originate from /// public string ProviderName { get { return _providerName; } } /// /// The entity token of the element /// public EntityToken EntityToken { get { return _entityToken; } } /// /// Custom values appended to this ElementHandle /// public Dictionary Piggyback { get { if (_piggyback == null) { string serialized = _serializedPiggyback; Verify.IsNotNull(serialized, "Serialized state is NULL"); _piggyback = PiggybagSerializer.Deserialize(_serializedPiggyback); } return _piggyback; } } /// public string SerializedPiggyback { get { if (_serializedPiggyback == null) { _serializedPiggyback = PiggybagSerializer.Serialize(this.Piggyback); } return _serializedPiggyback; } } /// public override bool Equals(object obj) { return Equals(obj as ElementHandle); } /// public bool Equals(ElementHandle elementHandle) { if (elementHandle == null) return false; if ((elementHandle.EntityToken.Equals(this.EntityToken) == false) || (elementHandle.ProviderName != this.ProviderName)) return false; if (elementHandle.Piggyback.Count != this.Piggyback.Count) return false; foreach (KeyValuePair kvp in elementHandle.Piggyback) { string value; if (this.Piggyback.TryGetValue(kvp.Key, out value) == false) return false; if (kvp.Value != value) return false; } return true; } /// public override int GetHashCode() { int hashCode = this._providerName.GetHashCode() ^ _entityToken.GetHashCode(); foreach (KeyValuePair kvp in this.Piggyback) { hashCode ^= kvp.Key.GetHashCode(); hashCode ^= kvp.Value.GetHashCode(); } return hashCode; } } } ================================================ FILE: Composite/C1Console/Elements/ElementHookRegistratorFacade.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Security; using Composite.C1Console.Elements.Foundation; using Composite.C1Console.Elements.Foundation.PluginFacades; using Composite.Core; namespace Composite.C1Console.Elements { internal static class ElementHookRegistratorFacade { private static readonly string LogTitle = typeof (ElementHookRegistratorFacade).Name; public static IEnumerable GetHooks() { int tt1 = System.Environment.TickCount; var hooks = new List(); foreach (string providerName in ElementProviderRegistry.ElementProviderNames) { if (!ElementProviderRegistry.IsProviderHookingProvider(providerName)) continue; int t1 = System.Environment.TickCount; hooks.AddRange(ElementProviderPluginFacade.GetHooks(providerName)); int t2 = System.Environment.TickCount; Log.LogVerbose(LogTitle, "Time for {0}: {1} ms", providerName, t2 - t1); } int tt2 = System.Environment.TickCount; Log.LogVerbose(LogTitle, "Total time for: {0} ms", tt2 - tt1); return hooks; } } } ================================================ FILE: Composite/C1Console/Elements/ElementInformationService.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Actions; namespace Composite.C1Console.Elements { internal class ElementInformationService : IElementInformationService { private ElementHandle _elementHandle; public ElementInformationService(ElementHandle elementHandle) { _elementHandle = elementHandle; } public string ProviderName { get { return _elementHandle.ProviderName; } } public Dictionary Piggyback { get { return _elementHandle.Piggyback; } } } } ================================================ FILE: Composite/C1Console/Elements/ElementProviderContext.cs ================================================ using Composite.C1Console.Security; namespace Composite.C1Console.Elements { /// /// Context assigned to element providers when they are constructed. Contains a helper method for constructing a provider specific and the configuation based name of the provider. /// public sealed class ElementProviderContext { private string _providerName; /// /// Constructs a new instance of /// /// Name of the provider public ElementProviderContext(string providerName) { _providerName = providerName; } /// /// Created a provider instance (based on name) specific for a given , making it possible to tie an entiry token to a specific provider instance. /// /// /// public ElementHandle CreateElementHandle(EntityToken entityToken) { return new ElementHandle(_providerName, entityToken); } /// /// The name if the provider instance. This name typically originate from configuration. A given provider type may exist as multiple instances, but all with have a unique name. /// public string ProviderName { get { return _providerName; } } } } ================================================ FILE: Composite/C1Console/Elements/ElementProviderHandle.cs ================================================ using System; using System.Text; using System.Collections.Generic; using Composite.Core.Serialization; namespace Composite.C1Console.Elements { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ElementProviderHandle { private string _serializedData = null; /// public ElementProviderHandle(string providerName) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); this.ProviderName = providerName; } /// public string ProviderName { get; private set; } /// public string Serialize() { return ToString(); } /// public static ElementProviderHandle Deserialize(string serializedElementHandle) { Dictionary dic = StringConversionServices.ParseKeyValueCollection(serializedElementHandle); if (dic.ContainsKey("_providerName_") == false) { throw new ArgumentException("The serializedElementProviderHandle is not a serialized element provider handle", "serializedElementProviderHandle"); } string providerName = StringConversionServices.DeserializeValueString(dic["_providerName_"]); return new ElementProviderHandle(providerName); } /// public override string ToString() { if (_serializedData == null) { StringBuilder sb = new StringBuilder(); StringConversionServices.SerializeKeyValuePair(sb, "_providerName_", ProviderName); _serializedData = sb.ToString(); } return _serializedData; } } } ================================================ FILE: Composite/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/AddAssociatedDataWorkflow.layout ================================================ ================================================ FILE: Composite/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/AssociatedDataElementProviderHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.C1Console.Actions.Data; using Composite.C1Console.Elements.ElementProviderHelpers.DataGroupingProviderHelper; using Composite.C1Console.Security; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.Core.Routing; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.Types; using Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { internal sealed class AssociatedDataElementProviderHelper : IAuxiliarySecurityAncestorProvider where T : class, IData { internal delegate void HooksChangedCallbackDelegate(); private readonly ElementProviderContext _elementProviderContext; private EntityToken _rootEntityToken; private bool _addVisualFunctionActions; private ResourceHandle AddDataAssociationTypeIcon { get { return GetIconHandle("dataassociation-add-association"); } } private ResourceHandle EditDataAssociationTypeIcon { get { return GetIconHandle("dataassociation-edit-association"); } } private ResourceHandle RemoveDataAssociationTypeIcon { get { return GetIconHandle("dataassociation-remove-association"); } } public static ResourceHandle LocalizeDataTypeIcon { get { return GetIconHandle("generated-type-localize"); } } public static ResourceHandle DelocalizeDataTypeIcon { get { return GetIconHandle("generated-type-delocalize"); } } private ResourceHandle DataAssociationOpenIcon { get { return GetIconHandle("dataassociation-rootfolder-open"); } } private ResourceHandle DataAssociationClosedIcon { get { return GetIconHandle("dataassociation-rootfolder-closed"); } } private ResourceHandle InterfaceOpenIcon { get { return GetIconHandle("data-interface-open"); } } private ResourceHandle InterfaceClosedIcon { get { return GetIconHandle("data-interface-closed"); } } private ResourceHandle AddAssociatedDataIcon { get { return GetIconHandle("associated-data-add"); } } private ResourceHandle EditAssociatedDataIcon { get { return GetIconHandle("associated-data-edit"); } } private ResourceHandle DeleteAssociatedDataIcon { get { return GetIconHandle("associated-data-delete"); } } private ResourceHandle DuplicateAssociatedDataIcon { get { return GetIconHandle("copy"); } } public static ResourceHandle LocalizeDataIcon { get { return GetIconHandle("generated-type-data-localize"); } } public static readonly Dictionary DataIconLookup; internal static readonly PermissionType[] AddAssociatedTypePermissionTypes = { PermissionType.Configure, PermissionType.Administrate }; internal static readonly PermissionType[] EditAssociatedTypePermissionTypes = { PermissionType.Configure, PermissionType.Administrate }; internal static readonly PermissionType[] RemoveAssociatedTypePermissionTypes = { PermissionType.Configure, PermissionType.Administrate }; private static readonly PermissionType[] _addAssociatedDataPermissionTypes = { PermissionType.Add }; private static readonly PermissionType[] _editAssociatedDataPermissionTypes = { PermissionType.Edit }; private static readonly PermissionType[] _deleteAssociatedDataPermissionTypes = { PermissionType.Delete }; private static readonly PermissionType[] _localizeDataPermissionTypes = { PermissionType.Add }; private static readonly ActionGroup AppendedActionGroup = new ActionGroup("Associated data", ActionGroupPriority.TargetedAppendMedium); private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); private readonly DataGroupingProviderHelper.DataGroupingProviderHelper _dataGroupingProviderHelper; static AssociatedDataElementProviderHelper() { DataIconLookup = new Dictionary { {GenericPublishProcessController.Draft, DataIconFacade.DataDraftIcon}, {GenericPublishProcessController.AwaitingApproval, DataIconFacade.DataAwaitingApprovalIcon}, {GenericPublishProcessController.AwaitingPublication, DataIconFacade.DataAwaitingPublicationIcon}, {GenericPublishProcessController.Published, DataIconFacade.DataPublishedIcon} }; } public AssociatedDataElementProviderHelper(ElementProviderContext elementProviderContext, EntityToken rootEntityToken, bool addVisualFunctionActions) { _elementProviderContext = elementProviderContext ?? throw new ArgumentNullException(nameof(elementProviderContext)); _rootEntityToken = rootEntityToken ?? throw new ArgumentNullException(nameof(rootEntityToken)); _addVisualFunctionActions = addVisualFunctionActions; _dataGroupingProviderHelper = new DataGroupingProviderHelper.DataGroupingProviderHelper(elementProviderContext) { OnOwnsType = type => typeof (IPageFolderData).IsAssignableFrom(type) || typeof(IPageDataFolder).IsAssignableFrom(type), OnCreateLeafElement = this.CreateElement, OnCreateDisabledLeafElement = data => ShowForeignElement(data, false), OnCreateGhostedLeafElement = data => ShowForeignElement(data, true), OnGetRootParentEntityToken = this.GetParentEntityToken, OnGetLeafsFilter = this.GetLeafsFilter, OnGetPayload = this.GetPayload }; AuxiliarySecurityAncestorFacade.AddAuxiliaryAncestorProvider(this); } private string GetPayload(EntityToken entityToken) { return GetPageId(entityToken).ToString(); } private Func GetLeafsFilter(EntityToken parentEntityToken) { Guid pageId = GetPageId(parentEntityToken); return data => (data as IPageRelatedData).PageId == pageId; } private Guid GetPageId(EntityToken entityToken) { if (entityToken is DataGroupingProviderHelperEntityToken dataGroupingEntityToken) { if(dataGroupingEntityToken.Payload.IsNullOrEmpty()) { return Guid.Empty; } return new Guid(dataGroupingEntityToken.Payload); } if(entityToken is AssociatedDataElementProviderHelperEntityToken pageFolderElementEntityToken) { return new Guid(pageFolderElementEntityToken.Id); } if(entityToken is DataEntityToken dataEntityToken) { return (dataEntityToken.Data as IPageRelatedData).PageId; } throw new InvalidOperationException($"Unexpected entity token type '{entityToken.GetType().FullName}'"); } private EntityToken GetParentEntityToken(Type interfaceType, EntityToken entityToken) { Verify.ArgumentNotNull(entityToken, "entityToken"); Guid pageId = GetPageId(entityToken); if(pageId == Guid.Empty) { return null; } return new AssociatedDataElementProviderHelperEntityToken( TypeManager.SerializeType(typeof (IPage)), _elementProviderContext.ProviderName, pageId.ToString(), TypeManager.SerializeType(interfaceType)); } /// /// Call this method to add actions to the element which represents the data of type T /// /// /// Null is allowed public void AttachElementActions(Element associatedDataElement, T data) { associatedDataElement.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper.AddDataFolderExWorkflow"), AddAssociatedTypePermissionTypes) { Payload = TypeManager.SerializeType(typeof(T)), DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddDataFolderTypeLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddDataFolderTypeToolTip"), Icon = this.AddDataAssociationTypeIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = false, ActionGroup = AppendedActionGroup } } }); associatedDataElement.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper.AddMetaDataWorkflow"), AddAssociatedTypePermissionTypes) { Payload = TypeManager.SerializeType(typeof(T)), DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataTypeLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataTypeToolTip"), Icon = this.AddDataAssociationTypeIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = false, ActionGroup = AppendedActionGroup } } }); associatedDataElement.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper.EditMetaDataWorkflow"), EditAssociatedTypePermissionTypes) { DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.EditMetaDataTypeLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.EditMetaDataTypeToolTip"), Icon = this.EditDataAssociationTypeIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = false, ActionGroup = AppendedActionGroup } } }); associatedDataElement.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper.DeleteMetaDataWorkflow"), RemoveAssociatedTypePermissionTypes))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.RemoveMetaDataTypeLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.RemoveMetaDataTypeToolTip"), Icon = this.RemoveDataAssociationTypeIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = false, ActionGroup = AppendedActionGroup } } }); } public bool HasChildren(T data) { return PageFolderFacade.HasFolderDefinitions((IPage)data); } public List GetChildren(T data, EntityToken parentEntityToken) { var children = new List(); PropertyInfo idPropertyInfo = typeof(T).GetKeyProperties()[0]; foreach (Type type in PageFolderFacade.GetDefinedFolderTypes((IPage)data).OrderBy(t => t.Name)) { var entityToken = new AssociatedDataElementProviderHelperEntityToken( TypeManager.SerializeType(typeof(T)), _elementProviderContext.ProviderName, ValueTypeConverter.Convert(idPropertyInfo.GetValue(data, null)), TypeManager.SerializeType(type) ); DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(type); var element = new Element(_elementProviderContext.CreateElementHandle(entityToken)) { VisualData = new ElementVisualizedData { Label = dataTypeDescriptor.Title ?? type.Name, ToolTip = dataTypeDescriptor.Title ?? type.Name, Icon = this.InterfaceClosedIcon, OpenedIcon = this.InterfaceOpenIcon, HasChildren = true // This is sat to always true to boost performance. } }; element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper.DeleteDataFolderWorkflow"), RemoveAssociatedTypePermissionTypes))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.RemoveAssociatedTypeLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.RemoveAssociatedTypeToolTip"), Icon = this.RemoveDataAssociationTypeIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = false, ActionGroup = AppendedActionGroup } } }); AddAddAssociatedDataAction(element, true); children.Add(element); } return children; } public List GetChildren(AssociatedDataElementProviderHelperEntityToken entityToken, bool includeForeignFolders) { IData data = entityToken.GetDataList().FirstOrDefault(); Type interfaceType = TypeManager.TryGetType(entityToken.Payload); if (data == null) return new List(); if (interfaceType == null) return new List(); return _dataGroupingProviderHelper.GetRootGroupFolders(interfaceType, entityToken, includeForeignFolders).ToList(); } public List GetChildren(DataGroupingProviderHelperEntityToken entityToken, bool includeForeignFolders) { return _dataGroupingProviderHelper.GetGroupChildren(entityToken, includeForeignFolders).ToList(); } public Dictionary> GetParents(IEnumerable entityTokens) { var result = new Dictionary>(); foreach (EntityToken entityToken in entityTokens) { var dataEntityToken = entityToken as DataEntityToken; if (dataEntityToken.Data == null) continue; Type interfaceType = dataEntityToken.InterfaceType; if (!PageFolderFacade.GetAllFolderTypes().Contains(interfaceType)) continue; IData data = dataEntityToken.Data; IPage referencedPage = PageFolderFacade.GetReferencedPage(data); if (referencedPage == null) continue; // TODO: check this branch result.Add(entityToken, new [] { new AssociatedDataElementProviderHelperEntityToken( TypeManager.SerializeType(typeof(T)), _elementProviderContext.ProviderName, ValueTypeConverter.Convert(referencedPage.Id), TypeManager.SerializeType(interfaceType)) }); } return result; } private Element CreateElement(IData data) { string label = data.GetLabel(); var element = new Element(_elementProviderContext.CreateElementHandle(data.GetDataEntityToken())) { VisualData = new ElementVisualizedData { Label = label, ToolTip = label, HasChildren = false, Icon = data is IPublishControlled publishedControlled ? DataIconLookup[publishedControlled.PublicationStatus] : DataIconFacade.DataPublishedIcon } }; AddEditAssociatedDataAction(element); AddDeleteAssociatedDataAction(element); AddDuplicateAssociatedDataAction(element); if (InternalUrls.DataTypeSupported(data.DataSourceId.InterfaceType)) { var dataReference = data.ToDataReference(); if (DataUrls.CanBuildUrlForData(dataReference)) { string internalUrl = InternalUrls.TryBuildInternalUrl(dataReference); if (internalUrl != null) { element.PropertyBag.Add("Uri", internalUrl); } } } return element; } private Element ShowForeignElement(IData data, bool enabled) { string label = string.Format("{0} ({1})", data.GetLabel(true), DataLocalizationFacade.GetCultureTitle(UserSettings.ForeignLocaleCultureInfo)); EntityToken entityToken = data.GetDataEntityToken(); if (enabled) { var element = new Element(_elementProviderContext.CreateElementHandle(entityToken)) { VisualData = new ElementVisualizedData { Label = label, ToolTip = label, HasChildren = false, Icon = DataIconFacade.DataGhostedIcon, IsDisabled = false } }; element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.LocalizeDataWorkflow"), _localizeDataPermissionTypes) { Payload = "Pagefolder" })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.LocalizeData"), ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.LocalizeDataToolTip"), Icon = GeneratedDataTypesElementProvider.LocalizeDataIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); return element; } return new Element(_elementProviderContext.CreateElementHandle(entityToken)) { VisualData = new ElementVisualizedData { Label = label, ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.DisabledData"), HasChildren = false, Icon = DataIconFacade.DataDisabledIcon, IsDisabled = true } }; } #region Action methods private void AddAddAssociatedDataAction(Element element, bool isInToolbar) { element.AddWorkflowAction("Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper.AddAssociatedDataWorkflow", _addAssociatedDataPermissionTypes, new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddAssociatedDataLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddAssociatedDataToolTip"), Icon = this.AddAssociatedDataIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = isInToolbar, ActionGroup = AppendedActionGroup } }); } private void AddEditAssociatedDataAction(Element element) { element.AddWorkflowAction("Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper.EditAssociatedDataWorkflow", _editAssociatedDataPermissionTypes, new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.EditAssociatedDataLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.EditAssociatedDataToolTip"), Icon = this.EditAssociatedDataIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } }); } private void AddDeleteAssociatedDataAction(Element element) { element.AddWorkflowAction("Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper.DeleteAssociatedDataWorkflow", _deleteAssociatedDataPermissionTypes, new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.DeleteAssociatedDataLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.DeleteAssociatedDataToolTip"), Icon = this.DeleteAssociatedDataIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } }); } private void AddDuplicateAssociatedDataAction(Element element) { element.AddAction(new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.Duplicate, _addAssociatedDataPermissionTypes))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.DuplicateAssociatedDataLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.DuplicateAssociatedDataToolTip"), Icon = this.DuplicateAssociatedDataIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); } #endregion private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } } } ================================================ FILE: Composite/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/AssociatedDataElementProviderHelperEntityToken.cs ================================================ using System; using System.Collections.Generic; using Composite.Data; using Composite.C1Console.Security; using Composite.Core; using Composite.Core.Serialization; using Composite.Core.Types; using Newtonsoft.Json; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(AssociatedDataElementProviderHelperSecurityAncestorProvider))] public sealed class AssociatedDataElementProviderHelperEntityToken : EntityToken { private readonly string _providerName; private int _hashCode = 0; /// [JsonConstructor] public AssociatedDataElementProviderHelperEntityToken(string type, string providerName, string id, string payload) { Type = type; _providerName = providerName; Id = id; this.Payload = payload; } /// public override string Type { get; } /// [JsonProperty(PropertyName = "providerName")] public override string Source => _providerName; /// public override string Id { get; } /// public string Payload { get; private set; } /// public Type GetInterfaceType() { Type type = TypeManager.GetType(this.Type); return type; } /// public IData GetData() { Type type = TypeManager.GetType(this.Type); object id = ValueTypeConverter.Convert(this.Id, type.GetKeyProperties()[0].PropertyType); IData data = DataFacade.TryGetDataByUniqueKey(type, id); return data; } /// public IEnumerable GetDataList() { Type type = TypeManager.GetType(this.Type); object id = ValueTypeConverter.Convert(this.Id, type.GetKeyProperties()[0].PropertyType); var datas = DataFacade.TryGetDataVersionsByUniqueKey(type, id); return datas; } /// public override string Serialize() { return CompositeJsonSerializer.Serialize(this); } /// public static EntityToken Deserialize(string serializedEntityToken) { EntityToken entityToken; if (CompositeJsonSerializer.IsJsonSerialized(serializedEntityToken)) { entityToken = CompositeJsonSerializer .Deserialize(serializedEntityToken); } else { entityToken = DeserializeLegacy(serializedEntityToken); Log.LogVerbose(nameof(AssociatedDataElementProviderHelperEntityToken), entityToken.GetType().FullName); } return entityToken; } /// public static EntityToken DeserializeLegacy(string serializedEntityToken) { string type, source, id; Dictionary dic; DoDeserialize(serializedEntityToken, out type, out source, out id, out dic); if (dic.ContainsKey("_Payload_") == false) { throw new ArgumentException("The serializedEntityToken is not a serialized entity token", "serializedEntityToken"); } string payload = StringConversionServices.DeserializeValueString(dic["_Payload_"]); return new AssociatedDataElementProviderHelperEntityToken(type, source, id, payload); } /// public override bool Equals(object obj) { return base.Equals(obj) && (obj as AssociatedDataElementProviderHelperEntityToken).Payload == this.Payload; } /// public override int GetHashCode() { if (_hashCode == 0) { _hashCode = this.GetType().GetHashCode() ^ this.Source.GetHashCode() ^ this.Type.GetHashCode() ^ this.Id.GetHashCode() ^ this.Payload.GetHashCode(); } return _hashCode; } } } ================================================ FILE: Composite/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/AssociatedDataElementProviderHelperSecurityAncestorProvider.cs ================================================ using System.Collections.Generic; using System.Linq; using Composite.Data; using Composite.C1Console.Security; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { internal sealed class AssociatedDataElementProviderHelperSecurityAncestorProvider : ISecurityAncestorProvider { public IEnumerable GetParents(EntityToken entityToken) { var castedEntityToken = (AssociatedDataElementProviderHelperEntityToken)entityToken; var dataItem = castedEntityToken.GetDataList().FirstOrDefault(); // Data item may not exist in current language return dataItem != null ? new[] { dataItem.GetDataEntityToken() } : Enumerable.Empty(); } } } ================================================ FILE: Composite/C1Console/Elements/ElementProviderHelpers/DataGroupingProviderHelper/DataGroupingProviderHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.C1Console.Security; using Composite.C1Console.Users; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.Types; namespace Composite.C1Console.Elements.ElementProviderHelpers.DataGroupingProviderHelper { internal sealed class DataGroupingProviderHelper : IAuxiliarySecurityAncestorProvider { private const int MaxElementsToShow = 1000; private readonly ElementProviderContext _elementProviderContext; private readonly string _undefinedLabelValue; private static readonly MethodInfo GenericCastMethodInfo = StaticReflection.GetGenericMethodInfo(() => DataGroupingProviderHelper.Cast(null)); public DataGroupingProviderHelper(ElementProviderContext elementProviderContext) { _elementProviderContext = elementProviderContext; _undefinedLabelValue = StringResourceSystemFacade.GetString("Composite.Plugins.GeneratedDataTypesElementProvider", "UndefinedLabelTemplate"); this.FolderOpenIcon = GetIconHandle("datagroupinghelper-folder-open"); this.FolderClosedIcon = GetIconHandle("datagroupinghelper-folder-closed"); this.OnCreateLeafElement = d => new Element(_elementProviderContext.CreateElementHandle(d.GetDataEntityToken())); this.OnGetDataScopeIdentifier = t => DataScopeIdentifier.Administrated; this.OnAddActions = (e, p) => e; AuxiliarySecurityAncestorFacade.AddAuxiliaryAncestorProvider(this); AuxiliarySecurityAncestorFacade.AddAuxiliaryAncestorProvider(this); DataEventSystemFacade.SubscribeToDataAfterUpdate(typeof(IData), (sender, args) => { if (!OnOwnsType(args.DataType)) return; var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(args.DataType); IEnumerable groupingDataFieldDescriptors = from dfd in dataTypeDescriptor.Fields where dfd.GroupByPriority != 0 orderby dfd.GroupByPriority select dfd; if (groupingDataFieldDescriptors.Any()) { EntityTokenCacheFacade.ClearCache(args.Data.GetDataEntityToken()); } }, false); } public ResourceHandle FolderOpenIcon { get; set; } public ResourceHandle FolderClosedIcon { get; set; } public Func OnCreateLeafElement { get; set; } public Func OnCreateGhostedLeafElement { get; set; } public Func OnCreateDisabledLeafElement { get; set; } public Func OnGetDataScopeIdentifier { get; set; } public Func OnOwnsType { get; set; } public Func OnGetRootParentEntityToken { get; set; } public Func OnAddActions { get; set; } public Func> OnGetLeafsFilter { get; set; } public Func OnGetPayload { get; set; } public Dictionary> GetParents(IEnumerable entityTokens) { var result = new Dictionary>(); foreach (EntityToken entityToken in entityTokens) { if (entityToken is DataGroupingProviderHelperEntityToken groupingEntityToken) { var parent = GetGroupingEntityTokenParent(groupingEntityToken); if (parent != null) { result.Add(entityToken, new [] { parent }); } continue; } if (entityToken is DataEntityToken dataEntityToken) { var parent = GetDataEntityTokenParent(dataEntityToken); if (parent != null) { result.Add(entityToken, new[] { parent }); } } } return result; } private EntityToken GetGroupingEntityTokenParent(DataGroupingProviderHelperEntityToken groupingEntityToken) { Type type = TypeManager.TryGetType(groupingEntityToken.Type); if (groupingEntityToken.GroupingValues.Count == 1) { return OnGetRootParentEntityToken(type, groupingEntityToken); } var newGroupingParentEntityToken = new DataGroupingProviderHelperEntityToken(groupingEntityToken.Type) { Payload = this.OnGetPayload(groupingEntityToken), GroupingValues = new Dictionary() }; foreach (var kvp in groupingEntityToken.GroupingValues.Take(groupingEntityToken.GroupingValues.Count - 1)) { newGroupingParentEntityToken.GroupingValues.Add(kvp.Key, NormalizeGroupingValue(kvp.Value)); } return newGroupingParentEntityToken; } private EntityToken GetDataEntityTokenParent(DataEntityToken dataEntityToken) { Type interfaceType = dataEntityToken.InterfaceType; if (!OnOwnsType(interfaceType)) { return null; } var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(interfaceType); IEnumerable groupingDataFieldDescriptors = from dfd in dataTypeDescriptor.Fields where dfd.GroupByPriority != 0 orderby dfd.GroupByPriority select dfd; if (!groupingDataFieldDescriptors.Any()) { return OnGetRootParentEntityToken(interfaceType, dataEntityToken); } IData data = dataEntityToken.Data; var parentToken = new DataGroupingProviderHelperEntityToken(dataEntityToken.Type) { Payload = this.OnGetPayload(dataEntityToken), GroupingValues = new Dictionary() }; foreach (DataFieldDescriptor dfd in groupingDataFieldDescriptors) { PropertyInfo propertyInfo = interfaceType.GetPropertiesRecursively().Single(f => f.Name == dfd.Name); object value = propertyInfo.GetValue(data, null); parentToken.GroupingValues.Add(propertyInfo.Name, NormalizeGroupingValue(value)); } return parentToken; } private static object NormalizeGroupingValue(object value) { return (value as DateTime?)?.Date ?? value; } public IEnumerable GetRootGroupFolders(Type interfaceType, EntityToken parentEntityToken) { return GetRootGroupFolders(interfaceType, parentEntityToken, false); } public IEnumerable GetRootGroupFolders(Type interfaceType, EntityToken parentEntityToken, bool includeForeignFolders) { DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(interfaceType); IEnumerable groupingDataFieldDescriptors = from dfd in dataTypeDescriptor.Fields where dfd.GroupByPriority != 0 orderby dfd.GroupByPriority select dfd; using (new DataScope(this.OnGetDataScopeIdentifier(interfaceType))) { if (groupingDataFieldDescriptors.Count() != 0) { ValidateGroupByPriorities(interfaceType, groupingDataFieldDescriptors); DataFieldDescriptor firstDataFieldDescriptor = groupingDataFieldDescriptors.First(); PropertyInfo propertyInfo = interfaceType.GetPropertiesRecursively().Single(f => f.Name == firstDataFieldDescriptor.Name); List elements = GetRootGroupFolders(interfaceType, parentEntityToken, firstDataFieldDescriptor, propertyInfo).ToList(); if (firstDataFieldDescriptor.ForeignKeyReferenceTypeName != null) { elements = (firstDataFieldDescriptor.TreeOrderingProfile.OrderDescending ? elements.OrderByDescending(f => f.VisualData.Label) : elements.OrderBy(f => f.VisualData.Label)).ToList(); } if (includeForeignFolders) { using (new DataScope(UserSettings.ForeignLocaleCultureInfo)) { elements.AddRange(GetRootGroupFolders(interfaceType, parentEntityToken, firstDataFieldDescriptor, propertyInfo)); } } return elements.Distinct(); } else { Func filter = null; if (this.OnGetLeafsFilter != null) { filter = this.OnGetLeafsFilter(parentEntityToken); } List elements = GetRootGroupFoldersFoldersLeafs(interfaceType, filter, false).ToList(); bool listingLimitReached = elements.Count == MaxElementsToShow; var labelFieldDescriptor = dataTypeDescriptor.Fields.FirstOrDefault(f => f.Name == dataTypeDescriptor.LabelFieldName); if (labelFieldDescriptor?.ForeignKeyReferenceTypeName != null && labelFieldDescriptor.TreeOrderingProfile.OrderPriority.HasValue) { elements = (labelFieldDescriptor.TreeOrderingProfile.OrderDescending ? elements.OrderByDescending(f => f.VisualData.Label) : elements.OrderBy(f => f.VisualData.Label)).ToList(); } if (!listingLimitReached && includeForeignFolders) { using (new DataScope(UserSettings.ForeignLocaleCultureInfo)) { elements.AddRange(GetRootGroupFoldersFoldersLeafs(interfaceType, filter, true)); } elements = elements.Distinct().Take(MaxElementsToShow).ToList(); } if (elements.Count == MaxElementsToShow) { elements.Add(GetElipsisElement(parentEntityToken, MaxElementsToShow)); } return elements; } } } private IEnumerable GetRootGroupFolders(Type interfaceType, EntityToken parentEntityToken, DataFieldDescriptor firstDataFieldDescriptor, PropertyInfo propertyInfo) { Func filter = OnGetLeafsFilter?.Invoke(parentEntityToken); IQueryable queryable = GetFilteredData(interfaceType, filter); var expressionBuilder = new ExpressionBuilder(interfaceType, queryable); IQueryable resultQueryable = expressionBuilder. Distinct(). OrderBy(propertyInfo, true, firstDataFieldDescriptor.TreeOrderingProfile.OrderDescending). Select(propertyInfo, true). CreateQuery(); var propertyInfoValueCollection = new PropertyInfoValueCollection(); return CreateGroupFolderElements(interfaceType, firstDataFieldDescriptor, resultQueryable, parentEntityToken, propertyInfoValueCollection); } private static IQueryable Cast(IQueryable queryable) { return queryable.Cast(); } public static IQueryable OrderData(IQueryable source, Type interfaceType) { var typeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(interfaceType); List orderFields = typeDescriptor.Fields.Where(f => f.TreeOrderingProfile.OrderPriority.HasValue).OrderBy(f => f.TreeOrderingProfile.OrderPriority).ToList(); if (orderFields.Any()) { IOrderedQueryable ordered = source.OrderBy(interfaceType, orderFields.First().Name, orderFields.First().TreeOrderingProfile.OrderDescending); foreach (DataFieldDescriptor field in orderFields.Skip(1)) { ordered = ordered.ThenBy(interfaceType, field.Name, field.TreeOrderingProfile.OrderDescending); } return ordered; } if (!string.IsNullOrEmpty(typeDescriptor.LabelFieldName)) { return source.OrderBy(interfaceType, typeDescriptor.LabelFieldName); } return source; } private IEnumerable GetRootGroupFoldersFoldersLeafs(Type interfaceType, Func filter, bool isForeign) { Func func = isForeign ? OnCreateGhostedLeafElement : OnCreateLeafElement; IQueryable source = DataFacade.GetData(interfaceType); IQueryable orderedData = OrderData(source, interfaceType); List data; if (filter == null) { data = ((IQueryable) orderedData).Take(MaxElementsToShow).ToList(); } else { data = ((IQueryable) orderedData).Evaluate().Where(filter).ToList(); } foreach (IData item in data) { Element element = GetDataFromCorrectScope(item, func, OnCreateDisabledLeafElement, isForeign); if (element != null) { yield return element; } } } private Element GetElipsisElement(EntityToken parentEntityToken, int elementsShown) { var element = new Element(new ElementHandle(_elementProviderContext.ProviderName, new ElipsisEntityToken(parentEntityToken))) { VisualData = new ElementVisualizedData { Label = LocalizationFiles.Composite_Management.Website_App_LimitedElementsShown(elementsShown.ToString()), ToolTip = "", Icon = GetIconHandle("warning"), OpenedIcon = null, HasChildren = false } }; return element; } public IEnumerable GetGroupChildren(DataGroupingProviderHelperEntityToken groupEntityToken) { return GetGroupChildren(groupEntityToken, false); } public IEnumerable GetGroupChildren(DataGroupingProviderHelperEntityToken groupEntityToken, bool includeForeignFolders) { Type interfaceType = TypeManager.GetType(groupEntityToken.Type); var propertyInfoValueCollection = new PropertyInfoValueCollection(); foreach (var kvp in groupEntityToken.GroupingValues) { PropertyInfo propertyInfo = interfaceType.GetPropertiesRecursively().Single(f => f.Name == kvp.Key); propertyInfoValueCollection.AddPropertyValue(propertyInfo, kvp.Value); } var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(interfaceType); DataFieldDescriptor groupingDataFieldDescriptor = (from dfd in dataTypeDescriptor.Fields where dfd.GroupByPriority == groupEntityToken.GroupingValues.Count + 1 select dfd).SingleOrDefault(); if (groupingDataFieldDescriptor != null && propertyInfoValueCollection.PropertyValues.Any(f => f.Key.Name == groupingDataFieldDescriptor.Name)) { // Grouping ordering has ben changed, at the moment the best thing we can do its to return no elements // TODO: This class and the whole attach element provider stuff should be redone return Enumerable.Empty(); } Func filter = null; if (this.OnGetLeafsFilter != null) { filter = this.OnGetLeafsFilter(groupEntityToken); } using (new DataScope(this.OnGetDataScopeIdentifier(interfaceType))) { if (groupingDataFieldDescriptor != null) { PropertyInfoValueCollection propertyInfoValueCol = propertyInfoValueCollection.Clone(); List elements = GetGroupChildrenFolders(groupEntityToken, interfaceType, filter, groupingDataFieldDescriptor, propertyInfoValueCol).ToList(); if (groupingDataFieldDescriptor.ForeignKeyReferenceTypeName != null) { elements = (groupingDataFieldDescriptor.TreeOrderingProfile.OrderDescending ? elements.OrderByDescending(f => f.VisualData.Label) : elements.OrderBy(f => f.VisualData.Label)).ToList(); } if (includeForeignFolders) { using (new DataScope(UserSettings.ForeignLocaleCultureInfo)) { PropertyInfoValueCollection foreignPropertyInfoValueCol = propertyInfoValueCollection.Clone(); elements.AddRange(GetGroupChildrenFolders(groupEntityToken, interfaceType, filter, groupingDataFieldDescriptor, foreignPropertyInfoValueCol)); } } return elements.Distinct(); } else { PropertyInfoValueCollection propertyInfoValueCol = propertyInfoValueCollection.Clone(); List elements = GetGroupChildrenLeafs(interfaceType, filter, propertyInfoValueCol, false).ToList(); if (!dataTypeDescriptor.Fields.Any(f => f.TreeOrderingProfile.OrderPriority.HasValue && f.ForeignKeyReferenceTypeName == null)) { var labelFieldDescriptor = dataTypeDescriptor.Fields.FirstOrDefault(f => f.Name == dataTypeDescriptor.LabelFieldName); if (labelFieldDescriptor?.ForeignKeyReferenceTypeName != null) { elements = (labelFieldDescriptor.TreeOrderingProfile.OrderDescending ? elements.OrderByDescending(f => f.VisualData.Label) : elements.OrderBy(f => f.VisualData.Label)).ToList(); } } if (includeForeignFolders) { using (new DataScope(UserSettings.ForeignLocaleCultureInfo)) { PropertyInfoValueCollection foreignPropertyInfoValueCol = propertyInfoValueCollection.Clone(); elements.AddRange(GetGroupChildrenLeafs(interfaceType, filter, foreignPropertyInfoValueCol, true)); } } return elements.Distinct(); } } } private IEnumerable GetGroupChildrenFolders(DataGroupingProviderHelperEntityToken groupEntityToken, Type interfaceType, Func filter, DataFieldDescriptor groupingDataFieldDescriptor, PropertyInfoValueCollection propertyInfoValueCollection) { IQueryable queryable = GetFilteredData(interfaceType, filter); ExpressionBuilder expressionBuilder = new ExpressionBuilder(interfaceType, queryable); PropertyInfo selectPropertyInfo = interfaceType.GetPropertiesRecursively(f => f.Name == groupingDataFieldDescriptor.Name).Single(); IQueryable resultQueryable = expressionBuilder. Where(propertyInfoValueCollection, true). OrderBy(selectPropertyInfo, true, groupingDataFieldDescriptor.TreeOrderingProfile.OrderDescending). Select(selectPropertyInfo, true). Distinct(). CreateQuery(); return CreateGroupFolderElements(interfaceType, groupingDataFieldDescriptor, resultQueryable, groupEntityToken, propertyInfoValueCollection); } private IEnumerable GetGroupChildrenLeafs(Type interfaceType, Func filter, PropertyInfoValueCollection propertyInfoValueCollection, bool isForeign) { IQueryable queryable = GetFilteredData(interfaceType, filter); queryable = OrderData(queryable, interfaceType); ExpressionBuilder expressionBuilder = new ExpressionBuilder(interfaceType, queryable); IQueryable resultQueryable = expressionBuilder. Where(propertyInfoValueCollection, true). CreateQuery(); List datas = resultQueryable.ToDataList(); Func func = OnCreateLeafElement; if (isForeign) { func = OnCreateGhostedLeafElement; } foreach (IData data in datas) { Element element = GetDataFromCorrectScope(data, func, OnCreateDisabledLeafElement, isForeign); if (element != null) { yield return element; } } } private static IQueryable GetFilteredData(Type interfaceType, Func filter) { IQueryable queryable = DataFacade.GetData(interfaceType); if (filter == null) return queryable; var dataQueryable = ((IQueryable) queryable).Where(filter).AsQueryable(); return GenericCastMethodInfo .MakeGenericMethod(interfaceType) .Invoke(null, new object[] { dataQueryable }) as IQueryable; } private static Element GetDataFromCorrectScope(IData data, Func createElementFunc, Func createDisabledElementFunc, bool isForeign) { if (isForeign) { if (!data.IsTranslatable()) { return createDisabledElementFunc(data); } IData translationSource = data.GetTranslationSource(); return createElementFunc(translationSource); } return createElementFunc(data); } public IEnumerable CreateHooks(Type interfaceType, EntityToken parentEntityToken) { throw new NotImplementedException(); } private IEnumerable CreateGroupFolderElements(Type interfaceType, DataFieldDescriptor dataFieldDescriptor, IQueryable queryable, EntityToken parentEntityToken, PropertyInfoValueCollection propertyInfoValueCollection) { PropertyInfo propertyInfo = interfaceType.GetPropertiesRecursively().Single(f => f.Name == dataFieldDescriptor.Name); foreach (object obj in queryable) { var entityToken = new DataGroupingProviderHelperEntityToken(TypeManager.SerializeType(interfaceType)) { Payload = this.OnGetPayload(parentEntityToken), GroupingValues = new Dictionary() }; foreach (var kvp in propertyInfoValueCollection.PropertyValues) { entityToken.GroupingValues.Add(kvp.Key.Name, kvp.Value); } entityToken.GroupingValues.Add(propertyInfo.Name, obj); var element = new Element(_elementProviderContext.CreateElementHandle(entityToken)); string label = obj?.ToString() ?? string.Format(_undefinedLabelValue, dataFieldDescriptor.Name); if (obj is DateTime dt) { label = dt.ToString("yyyy-MM-dd"); } if (obj != null && dataFieldDescriptor.ForeignKeyReferenceTypeName != null) { Type refType = TypeManager.GetType(dataFieldDescriptor.ForeignKeyReferenceTypeName); IData data = typeof(IVersioned).IsAssignableFrom(refType) ? DataFacade.TryGetDataVersionsByUniqueKey(refType, obj).FirstOrDefault() : DataFacade.TryGetDataByUniqueKey(refType, obj); if (data != null) { label = data.GetLabel(); } } element.VisualData = new ElementVisualizedData { Label = label, ToolTip = label, HasChildren = true, Icon = this.FolderClosedIcon, OpenedIcon = this.FolderOpenIcon }; PropertyInfoValueCollection propertyInfoValueCollectionCopy = propertyInfoValueCollection.Clone(); propertyInfoValueCollectionCopy.AddPropertyValue(propertyInfo, obj); yield return this.OnAddActions(element, propertyInfoValueCollectionCopy); } } private static void ValidateGroupByPriorities(Type interfaceType, IEnumerable groupingDataFieldDescriptors) { int i = 1; foreach (DataFieldDescriptor dataFieldDescriptor in groupingDataFieldDescriptors) { if (dataFieldDescriptor.GroupByPriority != i) { throw new InvalidOperationException($"Group by priority not correct for the type '{interfaceType}'"); } i++; } } private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } } } ================================================ FILE: Composite/C1Console/Elements/ElementProviderHelpers/DataGroupingProviderHelper/DataGroupingProviderHelperEntityToken.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Web; using Composite.C1Console.Security; using Composite.C1Console.Security.SecurityAncestorProviders; using Composite.Core.Serialization; using Composite.Core.Types; using Composite.Core.Extensions; namespace Composite.C1Console.Elements.ElementProviderHelpers.DataGroupingProviderHelper { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(NoAncestorSecurityAncestorProvider))] public sealed class DataGroupingProviderHelperEntityToken : EntityToken { private const string _magicNullValue = "·NULL·"; private string _type; private string _payload; /// public DataGroupingProviderHelperEntityToken(string type) { _type = type; } /// public override string Type { get { return _type; } } /// public override string Source { get { return ""; } } /// public override string Id { get { return ""; } } /// public Dictionary GroupingValues { get; set; } /// public string Payload { get { return _payload; } set { _payload = value; } } /// [Obsolete("Use 'Type' property instead.")] public string SerializedTypeName { get { return Type; } } /// public override string Serialize() { StringBuilder sb = new StringBuilder(); DoSerialize(sb); if (!_payload.IsNullOrEmpty()) { StringConversionServices.SerializeKeyValuePair(sb, "Payload", _payload, typeof(string)); } foreach (var kvp in this.GroupingValues.SortByKeys()) { if (kvp.Value != null) { StringConversionServices.SerializeKeyValuePair(sb, kvp.Key, kvp.Value, kvp.Value.GetType()); } else { StringConversionServices.SerializeKeyValuePair(sb, kvp.Key, _magicNullValue, typeof(string)); } } return sb.ToString(); } /// public static EntityToken Deserialize(string serializedEntityToken) { string type, source, id; Dictionary dic; DoDeserialize(serializedEntityToken, out type, out source, out id, out dic); var entityToken = new DataGroupingProviderHelperEntityToken(type); if (dic.ContainsKey("Payload")) { entityToken._payload = dic["Payload"]; } entityToken.GroupingValues = new Dictionary(); Type dataType = TypeManager.GetType(type); List propertyInfos = dataType.GetPropertiesRecursively(); foreach (var kvp in dic) { PropertyInfo propertyInfo = propertyInfos.Where(f => f.Name == kvp.Key).SingleOrDefault(); if (propertyInfo == null) continue; object value = null; if (kvp.Value != _magicNullValue) { value = StringConversionServices.DeserializeValue(kvp.Value, propertyInfo.PropertyType); } entityToken.GroupingValues.Add(kvp.Key, value); } return entityToken; } /// public override int GetHashCode() { int hashCode = this.Id.GetHashCode() ^ this.Type.GetHashCode() ^ this.Source.GetHashCode(); foreach (var kvp in this.GroupingValues.SortByKeys()) { hashCode ^= kvp.Key.GetHashCode(); if (kvp.Value != null) { hashCode ^= kvp.Value.GetHashCode(); } } return hashCode; } /// public override string OnGetExtraPrettyHtml() { StringBuilder sb = new StringBuilder(); foreach (var kvp in this.GroupingValues.SortByKeys()) { sb.Append("" + kvp.Key + " = " + HttpUtility.HtmlEncode(kvp.Value) + "
"); } return sb.ToString(); } } } ================================================ FILE: Composite/C1Console/Elements/ElementProviderHelpers/DataGroupingProviderHelper/ElipsisEntityToken.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Security; using Newtonsoft.Json; namespace Composite.C1Console.Elements.ElementProviderHelpers.DataGroupingProviderHelper { [SecurityAncestorProvider(typeof(ElipsisSecurityAncestorProvider))] internal class ElipsisEntityToken: EntityToken { private EntityToken _parentEntityToken; private readonly string _serializedParentEntityToken; public ElipsisEntityToken(EntityToken parentEntityToken) { _parentEntityToken = parentEntityToken; _serializedParentEntityToken = EntityTokenSerializer.Serialize(parentEntityToken, false); } /// public ElipsisEntityToken(string serializedParentEntityToken) { _serializedParentEntityToken = serializedParentEntityToken; } /// public override string Type => _serializedParentEntityToken; /// public override string Source => ""; /// public override string Id => ""; /// [JsonIgnore] public EntityToken ParentEntityToken { get { if (_parentEntityToken == null) { _parentEntityToken = EntityTokenSerializer.Deserialize(_serializedParentEntityToken); } return _parentEntityToken; } } /// public EntityToken GetParentEntityToken() { return this.ParentEntityToken; } /// public override string Serialize() { return DoSerialize(); } /// public static EntityToken Deserialize(string serializedEntityToken) { string type, source, id; DoDeserialize(serializedEntityToken, out type, out source, out id); return new ElipsisEntityToken(type); } } internal class ElipsisSecurityAncestorProvider: ISecurityAncestorProvider { public IEnumerable GetParents(EntityToken entityToken) { if (entityToken is ElipsisEntityToken) { return new [] {(entityToken as ElipsisEntityToken).GetParentEntityToken()}; } return null; } } } ================================================ FILE: Composite/C1Console/Elements/ElementProviderHelpers/VisualFunctionElementProviderHelper/Foundation/RenderingFunctionNames.cs ================================================ namespace Composite.C1Console.Elements.ElementProviderHelpers.VisualFunctionElementProviderHelper.Foundation { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class RenderingFunctionNames { /// public string Name { get; set; } /// public string Namespace { get; set; } /// public string CompositName { get; set; } } } ================================================ FILE: Composite/C1Console/Elements/ElementProviderHelpers/VisualFunctionElementProviderHelper/VisualFunctionElementProviderHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Data; using Composite.Data.Types; using Composite.Core.Extensions; using Composite.Core.ResourceSystem.Icons; using Composite.Core.Types; using Composite.C1Console.Workflow; using Composite.Core.ResourceSystem; using Composite.C1Console.Elements.ElementProviderHelpers.VisualFunctionElementProviderHelper.Foundation; namespace Composite.C1Console.Elements.ElementProviderHelpers.VisualFunctionElementProviderHelper { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class VisualFunctionElementProviderHelper { private ResourceHandle AddRenderingFunctionIcon { get { return GetIconHandle("visual-function-add"); } } private ResourceHandle EditRenderingFunctionIcon { get { return GetIconHandle("visual-function-edit"); } } private ResourceHandle DeleteRenderingFunctionIcon { get { return GetIconHandle("visual-function-delete"); } } private static readonly ActionGroup AppendedActionGroup = new ActionGroup("Visual Functions", ActionGroupPriority.TargetedAppendMedium); private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); /// public static IEnumerable GetRenderingFunctions(Type interfaceType) { string serializedType = TypeManager.SerializeType(interfaceType); var functions = (from wrf in DataFacade.GetData() where wrf.TypeManagerName == serializedType select new { Name = wrf.Name, Namespace = wrf.Namespace }).ToList(); IEnumerable renderingFunctins = from fun in functions select new RenderingFunctionNames { Name = fun.Name, Namespace = fun.Namespace, CompositName = StringExtensionMethods.CreateNamespace(fun.Namespace, fun.Name, '.') }; return renderingFunctins.OrderBy(f => f.CompositName); } /// public static IVisualFunction GetVisualFunction(RenderingFunctionNames renderingFunctionNames) { IVisualFunction function = (from wrf in DataFacade.GetData() where wrf.Name == renderingFunctionNames.Name && wrf.Namespace == renderingFunctionNames.Namespace select wrf).FirstOrDefault(); return function; } /// public void AttachElementActions(IEnumerable elements) { foreach (Element element in elements) { DataEntityToken dataEntityToken = element.ElementHandle.EntityToken as DataEntityToken; if (dataEntityToken != null) { element.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Elements.ElementProviderHelpers.VisualFunctionElementProviderHelper.AddVisualFunctionWorkflow")))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "VisualFunctionElementProviderHelper.AddNewLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "VisualFunctionElementProviderHelper.AddNewToolTip"), Icon = this.AddRenderingFunctionIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = false, ActionGroup = AppendedActionGroup } } }); if (GetRenderingFunctions(dataEntityToken.Data.DataSourceId.InterfaceType).Count() > 0) { element.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Elements.ElementProviderHelpers.VisualFunctionElementProviderHelper.SelectVisualFunctionWorkflow")) { Payload = "Edit" })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "VisualFunctionElementProviderHelper.EditLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "VisualFunctionElementProviderHelper.EditToolTip"), Icon = this.EditRenderingFunctionIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = false, ActionGroup = AppendedActionGroup } } }); element.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Elements.ElementProviderHelpers.VisualFunctionElementProviderHelper.SelectVisualFunctionWorkflow")) { Payload = "Delete" })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "VisualFunctionElementProviderHelper.DeleteLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "VisualFunctionElementProviderHelper.DeleteToolTip"), Icon = this.DeleteRenderingFunctionIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = AppendedActionGroup } } }); } } } } private ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } } } ================================================ FILE: Composite/C1Console/Elements/ElementVisualizedData.cs ================================================ using Composite.Core.ResourceSystem; namespace Composite.C1Console.Elements { /// /// Describe an elements visual appearance /// public sealed class ElementVisualizedData { /// /// Label to be shown in tree /// public string Label { get; set; } /// /// If this element has (may have) chrildren. When true navigation for opening the element will be provided. /// public bool HasChildren { get; set; } /// /// When true the element will be shown in the UI but in a grayed out way with all actions disabled /// public bool IsDisabled { get; set; } /// /// The icon of the element (when closed) /// public ResourceHandle Icon { get; set; } /// /// The icon of the element when open (when children are shown) /// public ResourceHandle OpenedIcon { get; set; } /// /// Tooltip for the element - typically shown when hovering the element /// public string ToolTip { get; set; } /// /// Having a common ElementBundle across elements will make the client bundle them up as a single node, and allow the user to select a specific element via a drop down, showing individual BundleElementName values /// public string ElementBundle { get; set; } /// /// When bundling elements this field is used to identify this specific element for selection /// public string BundleElementName { get; set; } } } ================================================ FILE: Composite/C1Console/Elements/Foundation/ElementActionProviderFacade.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web; using Composite.C1Console.Actions; using Composite.C1Console.Elements.Foundation.PluginFacades; using Composite.C1Console.Elements.Plugins.ElementActionProvider; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.Core; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.Core.WebClient; using Composite.Data; using Composite.Data.ProcessControlled; namespace Composite.C1Console.Elements.Foundation { #region ManageUserPermissions internal sealed class ManageUserPermissionsActionExecutor : IActionExecutor { public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { string currentConsoleId = flowControllerServicesContainer.GetService().CurrentConsoleId; string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken); Dictionary viewArguments = new Dictionary(); viewArguments.Add("serializedEntityToken", serializedEntityToken); ConsoleMessageQueueFacade.Enqueue(new OpenHandledViewMessageQueueItem(EntityTokenSerializer.Serialize(entityToken, true), "Composite.Management.PermissionEditor", viewArguments), currentConsoleId); return null; } } [ActionExecutor(typeof(ManageUserPermissionsActionExecutor))] internal sealed class ManageUserPermissionsActionToken : ActionToken { private static PermissionType[] _permissionTypes = new PermissionType[] { PermissionType.Administrate }; public override IEnumerable PermissionTypes { get { return _permissionTypes; } } public override string Serialize() { return "ManageUserPermissions"; } public static ActionToken Deserialize(string serializedData) { return new ManageUserPermissionsActionToken(); } } #endregion #region ShowGraph internal sealed class RelationshipGraphActionExecutor : IActionExecutor { public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { string currentConsoleId = flowControllerServicesContainer.GetService().CurrentConsoleId; string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken); if (actionToken.Serialize() == "ShowGraph") { string url = string.Format("{0}?EntityToken={1}", UrlUtils.ResolveAdminUrl("content/views/relationshipgraph/Default.aspx"), System.Web.HttpUtility.UrlEncode(serializedEntityToken)); ConsoleMessageQueueFacade.Enqueue(new OpenViewMessageQueueItem { Url = url, ViewId = Guid.NewGuid().ToString(), ViewType = ViewType.Main, Label = "Show graph..." }, currentConsoleId); } else if (actionToken.Serialize() == "ShowOrientedGraph") { Guid id = Guid.NewGuid(); string filename = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.TempDirectory), string.Format("{0}.RelationshipGraph", id)); C1File.WriteAllLines(filename, new string[] { serializedEntityToken }); string url = string.Format("{0}?Id={1}", UrlUtils.ResolveAdminUrl("content/views/relationshipgraph/ShowRelationshipOrientedGraph.aspx"), id); ConsoleMessageQueueFacade.Enqueue(new OpenViewMessageQueueItem { Url = url, ViewId = Guid.NewGuid().ToString(), ViewType = ViewType.Main, Label = "Show graph..." }, currentConsoleId); } return null; } } [ActionExecutor(typeof(RelationshipGraphActionExecutor))] internal sealed class RelationshipGraphActionToken : ActionToken { private static PermissionType[] _permissionTypes = new PermissionType[] { PermissionType.Administrate }; private string _type; public RelationshipGraphActionToken(string type) { _type = type; } public override IEnumerable PermissionTypes { get { return _permissionTypes; } } public override string Serialize() { return _type; } public static ActionToken Deserialize(string serializedData) { return new RelationshipGraphActionToken(serializedData); } } #endregion #region ShowElementInformation internal sealed class ShowElementInformationActionExecutor : IActionExecutor { public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { string currentConsoleId = flowControllerServicesContainer.GetService().CurrentConsoleId; string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken); StringBuilder sb = new StringBuilder(); var elementInformationService = flowControllerServicesContainer.GetService(); if (elementInformationService != null) { Dictionary piggybag = elementInformationService.Piggyback; foreach (var kvp in piggybag) { Core.Serialization.StringConversionServices.SerializeKeyValuePair(sb, kvp.Key, kvp.Value); } } Guid id = Guid.NewGuid(); string filename = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.TempDirectory), string.Format("{0}.showinfo", id)); C1File.WriteAllLines(filename, new string[] { serializedEntityToken, sb.ToString() }); string url = string.Format("{0}?PiggyBagId={1}", UrlUtils.ResolveAdminUrl("content/views/showelementinformation/Default.aspx"), id); ConsoleMessageQueueFacade.Enqueue(new OpenViewMessageQueueItem { Url = url, ViewId = Guid.NewGuid().ToString(), ViewType = ViewType.Main, Label = "Show Element Information..." }, currentConsoleId); return null; } } [ActionExecutor(typeof(ShowElementInformationActionExecutor))] internal sealed class ShowElementInformationActionToken : ActionToken { private static PermissionType[] _permissionTypes = new PermissionType[] { PermissionType.Administrate }; public override IEnumerable PermissionTypes { get { return _permissionTypes; } } public override string Serialize() { return "ShowElementInformation"; } public static ActionToken Deserialize(string serializedData) { return new ShowElementInformationActionToken(); } } #endregion #region Search internal sealed class SearchActionExecutor : IActionExecutor { public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { SearchActionToken searchActionToken = (SearchActionToken)actionToken; string currentConsoleId = flowControllerServicesContainer.GetService().CurrentConsoleId; string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken); string viewId = Guid.NewGuid().ToString(); string url = UrlUtils.ResolveAdminUrl(string.Format("content/dialogs/treesearch/treeSearchForm.aspx?ProviderName={0}&EntityToken={1}&ViewId={2}&ConsoleId={3}", HttpUtility.UrlEncode(searchActionToken.ProviderName), HttpUtility.UrlEncode(serializedEntityToken), HttpUtility.UrlEncode(viewId), HttpUtility.UrlEncode(currentConsoleId))); ConsoleMessageQueueFacade.Enqueue( new OpenViewMessageQueueItem { Url = url, ViewId = viewId, ViewType = ViewType.ModalDialog, Label = StringResourceSystemFacade.GetString("Composite.Management", "RelationshipGraphActionExecutor.SearchElements"), ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "RelationshipGraphActionExecutor.SearchElementsToolTip"), IconResourceHandle = CommonElementIcons.Question }, currentConsoleId); return null; } } [ActionExecutor(typeof(SearchActionExecutor))] internal sealed class SearchActionToken : ActionToken { private const string _serializePrefix = "Search:"; internal SearchActionToken(string providerName) { this.ProviderName = providerName; } internal string ProviderName { get; private set; } public override IEnumerable PermissionTypes { get { yield break; } } public override string Serialize() { return _serializePrefix + this.ProviderName; } public static ActionToken Deserialize(string serializedData) { if (serializedData.StartsWith(_serializePrefix) == false) throw new ArgumentException("Serialized data is not in correct format."); string providerName = serializedData.Remove(0, _serializePrefix.Length); return new SearchActionToken(providerName); } } #endregion internal static class ElementActionProviderFacade { private static readonly ActionGroup AppendedActionGroup = new ActionGroup("Common tasks", ActionGroupPriority.GeneralAppendMedium); private static ResourceHandle ManageSecurityIcon { get { return GetIconHandle("security-manage-permissions"); } } private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } public static void AddActions(IEnumerable elements, string providerName) { string manageUserPermissionsOnBranchLabel = StringResourceSystemFacade.GetString("Composite.Management", "ManageUserPermissions.ManageUserPermissionsOnBranchLabel"); string manageUserPermissionsItemLabel = StringResourceSystemFacade.GetString("Composite.Management", "ManageUserPermissions.ManageUserPermissionsOnItemLabel"); string manageUserPermissionsToolTip = StringResourceSystemFacade.GetString("Composite.Management", "ManageUserPermissions.ManageUserPermissionsToolTip"); string relationshipGraphLabel = StringResourceSystemFacade.GetString("Composite.Management", "RelationshipGraphActionExecutor.ShowGraph"); string relationshipGraphToolTip = StringResourceSystemFacade.GetString("Composite.Management", "RelationshipGraphActionExecutor.ShowGraphToolTip"); string relationshipOrientedGraphLabel = StringResourceSystemFacade.GetString("Composite.Management", "RelationshipGraphActionExecutor.ShowOrientedGraph"); string relationshipOrientedGraphToolTip = StringResourceSystemFacade.GetString("Composite.Management", "RelationshipGraphActionExecutor.ShowOrientedGraphToolTip"); string showElementInformationLabel = StringResourceSystemFacade.GetString("Composite.Management", "ShowElementInformationActionExecutor.ShowElementInformation.Label"); string showElementInformationToolTip = StringResourceSystemFacade.GetString("Composite.Management", "ShowElementInformationActionExecutor.ShowElementInformation.ToolTip"); IEnumerable elementActionProviderNames = ElementActionProviderRegistry.ElementActionProviderNames; if (elementActionProviderNames == null) { const string message = "Failed to load one of the element action providers"; Log.LogCritical("ElementActionProviderFacade", message); return; } foreach (Element element in elements) { AddBuildinActions(providerName, manageUserPermissionsOnBranchLabel, manageUserPermissionsItemLabel, manageUserPermissionsToolTip, relationshipGraphLabel, relationshipGraphToolTip, relationshipOrientedGraphLabel, relationshipOrientedGraphToolTip, showElementInformationLabel, showElementInformationToolTip, element); if ((element.ElementExternalActionAdding & ElementExternalActionAdding.AllowGlobal) == ElementExternalActionAdding.AllowGlobal) { foreach (string elementActionProviderName in elementActionProviderNames) { try { IEnumerable actions = ElementActionProviderPluginFacade.GetActions(elementActionProviderName, element.ElementHandle.EntityToken); element.AddAction(actions); } catch (Exception ex) { Log.LogCritical("ElementActionProviderFacade", string.Format("Failed to add actions from the element action provider named '{0}'", elementActionProviderName)); Log.LogCritical("ElementActionProviderFacade", ex); } } foreach (var elementActionProvider in ServiceLocator.GetServices()) { try { var actions = elementActionProvider.GetActions(element.ElementHandle.EntityToken); element.AddAction(actions); } catch (Exception ex) { Log.LogCritical(nameof(ElementActionProviderFacade), $"Failed to add actions from the element action provider '{elementActionProvider.GetType()}'"); Log.LogCritical(nameof(ElementActionProviderFacade), ex); } } } } } private static void AddBuildinActions(string providerName, string manageUserPermissionsOnBranchLabel, string manageUserPermissionsItemLabel, string manageUserPermissionsToolTip, string relationshipGraphLabel, string relationshipGraphToolTip, string relationshipOrientedGraphLabel, string relationshipOrientedGraphToolTip, string showElementInformationLabel, string showElementInformationToolTip, Element element) { if ((element.ElementExternalActionAdding & ElementExternalActionAdding.AllowGlobal) == ElementExternalActionAdding.AllowGlobal) { element.AddAction(new ElementAction(new ActionHandle(new RelationshipGraphActionToken("ShowGraph"))) { VisualData = new ActionVisualizedData { Label = relationshipGraphLabel, ToolTip = relationshipGraphToolTip, Icon = Composite.Core.ResourceSystem.Icons.CommonElementIcons.Nodes, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.DeveloperMode, IsInFolder = false, IsInToolbar = false, ActionGroup = AppendedActionGroup } } }); element.AddAction(new ElementAction(new ActionHandle(new RelationshipGraphActionToken("ShowOrientedGraph"))) { VisualData = new ActionVisualizedData { Label = relationshipOrientedGraphLabel, ToolTip = relationshipOrientedGraphToolTip, Icon = Composite.Core.ResourceSystem.Icons.CommonElementIcons.Nodes, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.DeveloperMode, IsInFolder = false, IsInToolbar = false, ActionGroup = AppendedActionGroup } } }); element.AddAction(new ElementAction(new ActionHandle(new ShowElementInformationActionToken())) { VisualData = new ActionVisualizedData { Label = showElementInformationLabel, ToolTip = showElementInformationToolTip, Icon = Composite.Core.ResourceSystem.Icons.CommonElementIcons.Search, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.DeveloperMode, IsInFolder = false, IsInToolbar = false, ActionGroup = AppendedActionGroup } } }); //element.AddAction(new ElementAction(new ActionHandle(new SearchActionToken(providerName))) //{ // VisualData = new ActionVisualizedData // { // Label = StringResourceSystemFacade.GetString("Composite.Management", "RelationshipGraphActionExecutor.Search"), // ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "RelationshipGraphActionExecutor.SearchToolTip"), // Icon = Composite.Core.ResourceSystem.Icons.CommonCommandIcons.Search, // Disabled = false, // ActionLocation = new ActionLocation // { // ActionType = ActionType.Other, // IsInFolder = false, // IsInToolbar = false, // ActionGroup = AppendedActionGroup // } // } //}); if (RuntimeInformation.IsDebugBuild) { } } if ((element.ElementExternalActionAdding & ElementExternalActionAdding.AllowManageUserPermissions) == ElementExternalActionAdding.AllowManageUserPermissions) { if (!element.Actions.Any(f => f.ActionHandle.ActionToken is ManageUserPermissionsActionToken)) // Fixing problem with the buggy virtual element provider { element.AddAction(new ElementAction(new ActionHandle(new ManageUserPermissionsActionToken())) { VisualData = new ActionVisualizedData { Label = (element.VisualData.HasChildren ? manageUserPermissionsOnBranchLabel : manageUserPermissionsItemLabel), ToolTip = manageUserPermissionsToolTip, Icon = ManageSecurityIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = false, ActionGroup = AppendedActionGroup } } }); } } if ((element.ElementExternalActionAdding & ElementExternalActionAdding.AllowProcessController) == ElementExternalActionAdding.AllowProcessController) { if (element.ElementHandle.EntityToken is DataEntityToken) { DataEntityToken token = (DataEntityToken)element.ElementHandle.EntityToken; Type elementProviderType; if (ElementProviderRegistry.ElementProviderNames.Contains(providerName)) { elementProviderType = ElementProviderRegistry.GetElementProviderType(providerName); } else { elementProviderType = ElementAttachingProviderRegistry.GetElementProviderType(providerName); } List actions = ProcessControllerFacade.GetActions(token.Data, elementProviderType); foreach (ElementAction action in actions) { element.AddAction(action); } } } } } } ================================================ FILE: Composite/C1Console/Elements/Foundation/ElementActionProviderRegistry.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Events; namespace Composite.C1Console.Elements.Foundation { internal static class ElementActionProviderRegistry { private static IElementActionProviderRegistry _implementation = new ElementActionProviderRegistryImpl(); internal static IElementActionProviderRegistry Implementation { get { return _implementation; } set { _implementation = value; } } static ElementActionProviderRegistry() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static IEnumerable ElementActionProviderNames { get { return _implementation.ElementActionProviderNames; } } private static void OnFlushEvent(FlushEventArgs args) { _implementation.OnFlush(); } } } ================================================ FILE: Composite/C1Console/Elements/Foundation/ElementActionProviderRegistryImpl.cs ================================================ using System.Collections.Generic; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.C1Console.Elements.Plugins.ElementActionProvider; using Composite.C1Console.Elements.Plugins.ElementActionProvider.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Elements.Foundation { internal sealed class ElementActionProviderRegistryImpl : IElementActionProviderRegistry { private ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); public IEnumerable ElementActionProviderNames { get { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.ElementProviderNames; } } } public void OnFlush() { _resourceLocker.ResetInitialization(); } private static IConfigurationSource GetConfiguration() { IConfigurationSource source = ConfigurationServices.ConfigurationSource; if (null == source) { throw new ConfigurationErrorsException(string.Format("No configuration source specified")); } return source; } private sealed class Resources { public List ElementProviderNames; public static void Initialize(Resources resources) { IConfigurationSource configurationSource = GetConfiguration(); ElementActionProviderSettings settings = configurationSource.GetSection(ElementActionProviderSettings.SectionName) as ElementActionProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration", ElementActionProviderSettings.SectionName)); } resources.ElementProviderNames = new List(); foreach (ElementActionProviderData data in settings.ElementActionProviderPlugins) { resources.ElementProviderNames.Add(data.Name); } } } } } ================================================ FILE: Composite/C1Console/Elements/Foundation/ElementAttachingProviderFacade.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security; using Composite.C1Console.Elements.Foundation.PluginFacades; using Composite.C1Console.Elements.Plugins.ElementAttachingProvider; using Composite.Core.Extensions; namespace Composite.C1Console.Elements.Foundation { internal static class ElementAttachingProviderFacade { public static bool HaveCustomChildElements(EntityToken parentEntityToken, Dictionary piggybag) { foreach (string providerName in ElementAttachingProviderRegistry.ElementAttachingProviderNames) { bool result = ElementAttachingProviderPluginFacade.HaveCustomChildElements(providerName, parentEntityToken, piggybag); if (result) { return true; } } return false; } public static IEnumerable AttachElements(EntityToken parentEntityToken, Dictionary piggybag, IEnumerable currentElements) { var topResults = new List(); var bottomResults = new List(); foreach (string providerName in ElementAttachingProviderRegistry.ElementAttachingProviderNames) { if (!ElementAttachingProviderPluginFacade.IsMultipleResultElementAttachingProvider(providerName)) { var result = ElementAttachingProviderPluginFacade.GetAlternateElementList(providerName, parentEntityToken, piggybag); if (result?.Elements == null) continue; if (result.Position == ElementAttachingProviderPosition.Top) { topResults.Add(result); } else if (result.Position == ElementAttachingProviderPosition.Bottom) { bottomResults.Add(result); } } else { var results = ElementAttachingProviderPluginFacade.GetAlternateElementLists(providerName, parentEntityToken, piggybag); if (results == null) continue; foreach (ElementAttachingProviderResult result in results) { if (result?.Elements == null) continue; if (result.Position == ElementAttachingProviderPosition.Top) { topResults.Add(result); } else if (result.Position == ElementAttachingProviderPosition.Bottom) { bottomResults.Add(result); } } } } Comparison sortMethod = (r1, r2) => r2.PositionPriority - r1.PositionPriority; topResults.Sort(sortMethod); bottomResults.Sort(sortMethod); IEnumerable topElements = null; foreach (var result in topResults) { topElements = topElements.ConcatOrDefault(result.Elements); } IEnumerable bottomElements = null; foreach (var result in bottomResults) { bottomElements = bottomElements.ConcatOrDefault(result.Elements); } return topElements .ConcatOrDefault(currentElements) .ConcatOrDefault(bottomElements); } } } ================================================ FILE: Composite/C1Console/Elements/Foundation/ElementAttachingProviderRegistry.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Events; using System; namespace Composite.C1Console.Elements.Foundation { internal static class ElementAttachingProviderRegistry { private static IElementAttachingProviderRegistry _implementation = new ElementAttachingProviderRegistryImpl(); internal static IElementAttachingProviderRegistry Implementation { get { return _implementation; } set { _implementation = value; } } static ElementAttachingProviderRegistry() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static IEnumerable ElementAttachingProviderNames { get { return _implementation.ElementAttachingProviderNames; } } public static Type GetElementProviderType(string elementProviderName) { return _implementation.GetElementProviderType(elementProviderName); } private static void OnFlushEvent(FlushEventArgs args) { _implementation.OnFlush(); } } } ================================================ FILE: Composite/C1Console/Elements/Foundation/ElementAttachingProviderRegistryImpl.cs ================================================ using System.Collections.Generic; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.C1Console.Elements.Plugins.ElementAttachingProvider; using Composite.C1Console.Elements.Plugins.ElementAttachingProvider.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using System; namespace Composite.C1Console.Elements.Foundation { internal sealed class ElementAttachingProviderRegistryImpl : IElementAttachingProviderRegistry { private ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); public IEnumerable ElementAttachingProviderNames { get { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.ElementProviderNames.Keys; } } } public Type GetElementProviderType(string elementProviderName) { if (string.IsNullOrEmpty(elementProviderName)) throw new ArgumentNullException("elementProviderName"); Type type; using (_resourceLocker.ReadLocker) { if (_resourceLocker.Resources.ElementProviderNames.TryGetValue(elementProviderName, out type) == false) { throw new ArgumentException(string.Format("The element provider named '{0}' does not exist", elementProviderName)); } return type; } } public void OnFlush() { _resourceLocker.ResetInitialization(); } private static IConfigurationSource GetConfiguration() { IConfigurationSource source = ConfigurationServices.ConfigurationSource; if (null == source) { throw new ConfigurationErrorsException(string.Format("No configuration source specified")); } return source; } private sealed class Resources { public Dictionary ElementProviderNames; public static void Initialize(Resources resources) { IConfigurationSource configurationSource = GetConfiguration(); ElementAttachingProviderSettings settings = configurationSource.GetSection(ElementAttachingProviderSettings.SectionName) as ElementAttachingProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration", ElementAttachingProviderSettings.SectionName)); } resources.ElementProviderNames = new Dictionary(); foreach (ElementAttachingProviderData data in settings.ElementAttachingProviderPlugins) { resources.ElementProviderNames.Add(data.Name, data.Type); } } } } } ================================================ FILE: Composite/C1Console/Elements/Foundation/ElementProviderLoader.cs ================================================ using Composite.C1Console.Elements.Foundation.PluginFacades; namespace Composite.C1Console.Elements.Foundation { internal static class ElementProviderLoader { public static void LoadAllProviders() { LoadAllElementProviders(); LoadAllAttachingProviders(); } private static void LoadAllElementProviders() { var rootProvider = ElementProviderPluginFacade.GetElementProvider(ElementProviderRegistry.RootElementProviderName); foreach (string name in ElementProviderRegistry.ElementProviderNames) { var provider = ElementProviderPluginFacade.GetElementProvider(name); } } private static void LoadAllAttachingProviders() { foreach (string name in ElementAttachingProviderRegistry.ElementAttachingProviderNames) { var provider = ElementAttachingProviderPluginFacade.GetElementAttachingProvider(name); } } } } ================================================ FILE: Composite/C1Console/Elements/Foundation/ElementProviderRegistry.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.C1Console.Elements.Plugins.ElementProvider.Runtime; using Composite.C1Console.Events; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Elements.Foundation { internal static class ElementProviderRegistry { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); static ElementProviderRegistry() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static string RootElementProviderName { get { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.RootElementProviderName; } } } public static IEnumerable ElementProviderNames { get { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.ElementProviderNames.Keys; } } } public static Type GetElementProviderType(string elementProviderName) { if (string.IsNullOrEmpty(elementProviderName)) throw new ArgumentNullException("elementProviderName"); Type type; using (_resourceLocker.ReadLocker) { if (_resourceLocker.Resources.ElementProviderNames.TryGetValue(elementProviderName, out type) == false) { throw new ArgumentException(string.Format("The element provider named '{0}' does not exist", elementProviderName)); } return type; } } public static bool IsProviderHookingProvider(string elementProviderName) { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.HookingProviderNames.Contains(elementProviderName); } } private static IConfigurationSource GetConfiguration() { IConfigurationSource source = ConfigurationServices.ConfigurationSource; if (null == source) { throw new ConfigurationErrorsException(string.Format("No configuration source specified")); } return source; } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private sealed class Resources { public string RootElementProviderName; public Dictionary ElementProviderNames; public List HookingProviderNames; public static void Initialize(Resources resources) { IConfigurationSource configurationSource = GetConfiguration(); ElementProviderSettings settings = configurationSource.GetSection(ElementProviderSettings.SectionName) as ElementProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration", ElementProviderSettings.SectionName)); } resources.RootElementProviderName = settings.RootProviderName; resources.ElementProviderNames = new Dictionary(); resources.HookingProviderNames = new List(); foreach (HooklessElementProviderData data in settings.ElementProviderPlugins) { resources.ElementProviderNames.Add(data.Name, data.Type); #pragma warning disable 612 if ((data is ElementProviderData)) { resources.HookingProviderNames.Add(data.Name); } #pragma warning restore 612 } } } } } ================================================ FILE: Composite/C1Console/Elements/Foundation/IElementActionProviderRegistry.cs ================================================ using System.Collections.Generic; namespace Composite.C1Console.Elements.Foundation { internal interface IElementActionProviderRegistry { IEnumerable ElementActionProviderNames { get; } void OnFlush(); } } ================================================ FILE: Composite/C1Console/Elements/Foundation/IElementAttachingProviderRegistry.cs ================================================ using System; using System.Collections.Generic; namespace Composite.C1Console.Elements.Foundation { internal interface IElementAttachingProviderRegistry { IEnumerable ElementAttachingProviderNames { get; } Type GetElementProviderType(string elementProviderName); void OnFlush(); } } ================================================ FILE: Composite/C1Console/Elements/Foundation/PluginFacades/ElementActionProviderPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Reflection; using Composite.Core.Collections.Generic; using Composite.C1Console.Elements.Plugins.ElementActionProvider; using Composite.C1Console.Elements.Plugins.ElementActionProvider.Runtime; using Composite.C1Console.Events; using Composite.C1Console.Security; namespace Composite.C1Console.Elements.Foundation.PluginFacades { internal static class ElementActionProviderPluginFacade { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); static ElementActionProviderPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static IEnumerable GetActions(string providerName, EntityToken entityToken) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); IElementActionProvider elementActionProvider = GetElementActionProvider(providerName); return elementActionProvider.GetActions(entityToken); } private static IElementActionProvider GetElementActionProvider(string providerName) { IElementActionProvider provider; if (_resourceLocker.Resources.ProviderCache.TryGetValue(providerName, out provider) == false) { try { provider = _resourceLocker.Resources.Factory.Create(providerName); using (_resourceLocker.Locker) { if (_resourceLocker.Resources.ProviderCache.ContainsKey(providerName) == false) { _resourceLocker.Resources.ProviderCache.Add(providerName, provider); } } } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } catch (TargetInvocationException ex) { HandleConfigurationError(ex); } } return provider; } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", ElementActionProviderSettings.SectionName), ex); } private sealed class Resources { public ElementActionProviderFactory Factory { get; set; } public Dictionary ProviderCache { get; set; } public static void Initialize(Resources resources) { try { resources.Factory = new ElementActionProviderFactory(); } catch (NullReferenceException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } catch (TargetInvocationException ex) { HandleConfigurationError(ex); } resources.ProviderCache = new Dictionary(); } } } } ================================================ FILE: Composite/C1Console/Elements/Foundation/PluginFacades/ElementAttachingProviderPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.C1Console.Elements.Plugins.ElementAttachingProvider; using Composite.C1Console.Elements.Plugins.ElementAttachingProvider.Runtime; using Composite.C1Console.Events; using Composite.C1Console.Security; namespace Composite.C1Console.Elements.Foundation.PluginFacades { internal static class ElementAttachingProviderPluginFacade { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); static ElementAttachingProviderPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static bool HaveCustomChildElements(string providerName, EntityToken parentEntityToken, Dictionary piggybag) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); IElementAttachingProvider elementAttachingProvider = GetElementAttachingProvider(providerName); bool result = elementAttachingProvider.HaveCustomChildElements(parentEntityToken, piggybag); return result; } public static ElementAttachingProviderResult GetAlternateElementList(string providerName, EntityToken parentEntityToken, Dictionary piggybag) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); IElementAttachingProvider elementAttachingProvider = GetElementAttachingProvider(providerName); ElementAttachingProviderResult result = elementAttachingProvider.GetAlternateElementList(parentEntityToken, piggybag); return result; } public static IEnumerable GetAlternateElementLists(string providerName, EntityToken parentEntityToken, Dictionary piggybag) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); var elementAttachingProvider = (IMultipleResultElementAttachingProvider)GetElementAttachingProvider(providerName); IEnumerable result = elementAttachingProvider.GetAlternateElementLists(parentEntityToken, piggybag); return result; } public static IEnumerable GetChildren(string providerName, EntityToken parentEntityToken, Dictionary piggybag) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); IElementAttachingProvider elementAttachingProvider = GetElementAttachingProvider(providerName); IEnumerable result = elementAttachingProvider.GetChildren(parentEntityToken, piggybag); return result; } public static bool IsMultipleResultElementAttachingProvider(string providerName) { return GetElementAttachingProvider(providerName) is IMultipleResultElementAttachingProvider; } internal static IElementAttachingProvider GetElementAttachingProvider(string providerName) { IElementAttachingProvider provider; if (_resourceLocker.Resources.ProviderCache.TryGetValue(providerName, out provider) == false) { try { provider = _resourceLocker.Resources.Factory.Create(providerName); provider.Context = new ElementProviderContext(providerName); using (_resourceLocker.Locker) { if (_resourceLocker.Resources.ProviderCache.ContainsKey(providerName) == false) { _resourceLocker.Resources.ProviderCache.Add(providerName, provider); } } } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } return provider; } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException($"Failed to load the configuration section '{ElementAttachingProviderSettings.SectionName}' from the configuration.", ex); } private sealed class Resources { public ElementAttachingProviderFactory Factory { get; set; } public Dictionary ProviderCache { get; set; } public static void Initialize(Resources resources) { try { resources.Factory = new ElementAttachingProviderFactory(); } catch (NullReferenceException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } resources.ProviderCache = new Dictionary(); } } } } ================================================ FILE: Composite/C1Console/Elements/Foundation/PluginFacades/ElementProviderPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Xml; using Composite.C1Console.Actions; using Composite.Core.Collections.Generic; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.C1Console.Elements.Plugins.ElementProvider.Runtime; using Composite.C1Console.Events; using Composite.C1Console.Security; namespace Composite.C1Console.Elements.Foundation.PluginFacades { internal static class ElementProviderPluginFacade { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); static ElementProviderPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } public static IEnumerable GetRoots(string providerName, SearchToken seachToken) { Verify.ArgumentNotNullOrEmpty(providerName, nameof(providerName)); IEnumerable roots = GetElementProvider(providerName).GetRoots(seachToken); return roots ?? Enumerable.Empty(); } public static IEnumerable GetChildren(string providerName, EntityToken entityToken, SearchToken seachToken) { Verify.ArgumentNotNullOrEmpty(providerName, nameof(providerName)); Verify.ArgumentNotNull(entityToken, nameof(entityToken)); IEnumerable children = GetElementProvider(providerName).GetChildren(entityToken, seachToken); return children ?? Enumerable.Empty(); } public static IEnumerable GetLabeledProperties(string providerName, EntityToken entityToken) { Verify.ArgumentNotNullOrEmpty(providerName, nameof(providerName)); Verify.ArgumentNotNull(entityToken, nameof(entityToken)); ILabeledPropertiesElementProvider labledElementProvider = GetElementProvider(providerName) as ILabeledPropertiesElementProvider; if (labledElementProvider == null) throw new ArgumentException($"The Element Provider identified by the specified provider name does not implement {typeof(ILabeledPropertiesElementProvider)}"); IEnumerable properties = labledElementProvider.GetLabeledProperties(entityToken); return properties ?? Enumerable.Empty(); } #pragma warning disable 612 public static List GetHooks(string providerName) { Verify.ArgumentNotNullOrEmpty(providerName, nameof(providerName)); IElementProvider provider = GetElementProvider(providerName) as IElementProvider; if (provider == null) throw new ArgumentException($"The Element Provider identified by the specified provider name does not implement {typeof(IElementProvider)}"); List hooks = provider.GetHooks(); return hooks ?? new List(); } #pragma warning restore 612 public static bool ContainsLocalizedData(string providerName) { Verify.ArgumentNotNullOrEmpty(providerName, nameof(providerName)); var provider = GetElementProvider(providerName) as ILocaleAwareElementProvider; if (provider == null) throw new ArgumentException($"The Element Provider identified by the specified provider name does not implement {typeof(ILocaleAwareElementProvider)}"); return provider.ContainsLocalizedData; } public static IEnumerable GetForeignRoots(string providerName, SearchToken seachToken) { Verify.ArgumentNotNullOrEmpty(providerName, nameof(providerName)); ILocaleAwareElementProvider provider = GetElementProvider(providerName) as ILocaleAwareElementProvider; if (provider == null) throw new ArgumentException($"The Element Provider identified by the specified provider name does not implement {typeof(ILocaleAwareElementProvider)}"); return provider.GetForeignRoots(seachToken); } public static IEnumerable GetForeignChildren(string providerName, EntityToken entityToken, SearchToken seachToken) { Verify.ArgumentNotNullOrEmpty(providerName, nameof(providerName)); Verify.ArgumentNotNull(entityToken, nameof(entityToken)); var provider = GetElementProvider(providerName) as ILocaleAwareElementProvider; if (provider == null) throw new ArgumentException($"The Element Provider identified by the specified provider name does not implement {typeof(ILocaleAwareElementProvider)}"); return provider.GetForeignChildren(entityToken, seachToken); } public static IEnumerable GetForeignLabeledProperties(string providerName, EntityToken entityToken) { Verify.ArgumentNotNullOrEmpty(providerName, nameof(providerName)); ILocaleAwareLabeledPropertiesElementProvider provider = GetElementProvider(providerName) as ILocaleAwareLabeledPropertiesElementProvider; if (provider == null) throw new ArgumentException($"The Element Provider identified by the specified provider name does not implement {typeof(ILocaleAwareElementProvider)}"); return provider.GetForeignLabeledProperties(entityToken); } public static object GetData(string providerName, string dataName) { Verify.ArgumentNotNullOrEmpty(providerName, nameof(providerName)); Verify.ArgumentNotNullOrEmpty(dataName, nameof(dataName)); IDataExchangingElementProvider provider = GetElementProvider(providerName) as IDataExchangingElementProvider; if (provider == null) throw new ArgumentException($"The Element Provider identified by the specified provider name does not implement {typeof(IDataExchangingElementProvider)}"); return provider.GetData(dataName); } public static bool GetNewSearchToken(string providerName, EntityToken entityToken, out SearchToken searchToken) { Verify.ArgumentNotNullOrEmpty(providerName, nameof(providerName)); Verify.ArgumentNotNull(entityToken, nameof(entityToken)); var provider = GetElementProvider(providerName) as ICustomSearchElementProvider; if (provider == null) { searchToken = null; return false; } searchToken = provider.GetNewSearchToken(entityToken); return true; } public static bool GetSearchFormDefinition(string providerName, EntityToken entityToken, out XmlReader formDefinition) { Verify.ArgumentNotNullOrEmpty(providerName, nameof(providerName)); Verify.ArgumentNotNull(entityToken, nameof(entityToken)); var provider = GetElementProvider(providerName) as ICustomSearchElementProvider; if (provider == null) { formDefinition = null; return false; } formDefinition = provider.GetSearchFormDefinition(entityToken); return true; } public static bool GetSearchFormBindings(string providerName, EntityToken entityToken, out Dictionary bindings) { Verify.ArgumentNotNullOrEmpty(providerName, nameof(providerName)); Verify.ArgumentNotNull(entityToken, nameof(entityToken)); var provider = GetElementProvider(providerName) as ICustomSearchElementProvider; if (provider == null) { bindings = null; return false; } bindings = provider.GetSearchFormBindings(entityToken); return true; } public static bool OnElementDraggedAndDropped(string providerName, EntityToken draggedEntityToken, EntityToken newParentEntityToken, int dropIndex, DragAndDropType dragAndDropType, FlowControllerServicesContainer draggedElementFlowControllerServicesContainer) { Verify.ArgumentNotNullOrEmpty(providerName, nameof(providerName)); Verify.ArgumentNotNull(draggedEntityToken, nameof(draggedEntityToken)); Verify.ArgumentNotNull(newParentEntityToken, nameof(newParentEntityToken)); Verify.ArgumentNotNull(draggedElementFlowControllerServicesContainer, nameof(draggedElementFlowControllerServicesContainer)); var provider = GetElementProvider(providerName) as IDragAndDropElementProvider; if (provider == null) throw new ArgumentException($"The Element Provider identified byu the specified provider name does not implement {typeof(IDragAndDropElementProvider)}"); return provider.OnElementDraggedAndDropped(draggedEntityToken, newParentEntityToken, dropIndex, dragAndDropType, draggedElementFlowControllerServicesContainer); } public static bool IsLocaleAwareElementProvider(string providerName) { var elementProvider = GetElementProvider(providerName) as ILocaleAwareElementProvider; return elementProvider != null; } internal static IHooklessElementProvider GetElementProvider(string providerName) { IHooklessElementProvider provider; if (!_resourceLocker.Resources.ProviderCache.TryGetValue(providerName, out provider)) { try { if (ElementProviderRegistry.IsProviderHookingProvider(providerName)) { provider = _resourceLocker.Resources.Factory.Create(providerName); } else { provider = _resourceLocker.Resources.HooklessFactory.Create(providerName); } provider.Context = new ElementProviderContext(providerName); using (_resourceLocker.Locker) { if (!_resourceLocker.Resources.ProviderCache.ContainsKey(providerName)) { _resourceLocker.Resources.ProviderCache.Add(providerName, provider); } } } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } return provider; } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException($"Failed to load the configuration section '{ElementProviderSettings.SectionName}' from the configuration.", ex); } private sealed class Resources { public ElementProviderFactory Factory { get; private set; } public HooklessElementProviderFactory HooklessFactory { get; private set; } public Dictionary ProviderCache { get; private set; } public static void Initialize(Resources resources) { try { resources.Factory = new ElementProviderFactory(); resources.HooklessFactory = new HooklessElementProviderFactory(); } catch (NullReferenceException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } resources.ProviderCache = new Dictionary(); } } } } ================================================ FILE: Composite/C1Console/Elements/IElementDataExchangeService.cs ================================================ using Composite.C1Console.Actions; namespace Composite.C1Console.Elements { internal interface IElementDataExchangeService : IFlowControllerService { object GetData(string name); } } ================================================ FILE: Composite/C1Console/Elements/IServiceUrlToEntityTokenMapper.cs ================================================ using Composite.C1Console.Security; namespace Composite.C1Console.Elements { /// /// Allows Data Scope Services to Add or Clean their parameters to or from the URL and update a entity token with their associate properties /// public interface IServiceUrlToEntityTokenMapper { /// /// Gets a URL and Returns the url with parametres associated with an entity token, or original URL if current entity token does not support this kind of entity token. /// /// The url. /// The entity token. /// A URL that will display the data item - this can be an "internal" URL which is later transformed by a IInternalUrlConverter. Intended for public consumption. string ProcessUrl(string url, EntityToken entityToken); /// /// Updates an entity token according to a url. /// /// The url. /// The entity token. /// EntityToken TryGetEntityToken(string url, ref EntityToken entityToken); /// /// Gets a url and cleans it up from its parameters. /// /// The url. /// string CleanUrl(ref string url); } } ================================================ FILE: Composite/C1Console/Elements/IUrlToEntityTokenMapper.cs ================================================ using System; using Composite.C1Console.Security; namespace Composite.C1Console.Elements { /// /// Allows associating C1 console tree elements with a url for public consumption (TryGetURL) and for the C1 console browser (TryGetBrowserViewSettings) /// public interface IUrlToEntityTokenMapper { /// /// Returns a url associated with an entity token, or null if current entity token does not support this kind of entity token. /// /// The entity token. /// A URL that will display the data item - this can be an "internal" URL which is later transformed by a IInternalUrlConverter. Intended for public consumption. string TryGetUrl(EntityToken entityToken); /// /// For use in the C1 Console explorer's browser - returns url and tooling options associated with an entity token, or null if current entity token does not support this kind of entity token. /// /// The entity token. /// When true (and element has draft/published content) the published version is desired /// BrowserViewSettings directing how the C1 Console Brorser should behave (what URL to show and if tooling should be available). BrowserViewSettings TryGetBrowserViewSettings(EntityToken entityToken, bool showPublishedView); /// /// Returns an entity token associated with a url, or null if current does not support this kind of entity token. /// /// The url. /// EntityToken TryGetEntityToken(string url); } /// /// Describes a browser view - URL and if tooling should be active. /// public sealed class BrowserViewSettings { /// /// Constructs a new instance on the BrowserViewSettings class. /// public BrowserViewSettings() { } /// /// Constructs a new instance on the BrowserViewSettings class. /// /// Url to load in browser /// True if tooling (view, SEO tools etc) should be active for URL public BrowserViewSettings(string url, bool toolingOn) { if (string.IsNullOrEmpty(url)) throw new ArgumentException("URL not set", "url"); Url = url; ToolingOn = toolingOn; } /// /// Url to load in browser /// public string Url { get; set; } /// /// True if tooling (view, SEO tools etc) should be active for URL /// public bool ToolingOn { get; set; } } } ================================================ FILE: Composite/C1Console/Elements/LabeledProperty.cs ================================================  namespace Composite.C1Console.Elements { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class LabeledProperty { /// /// Initializes a new instance of the LabeledProperty class and sets the label to the specified name. /// /// /// public LabeledProperty(string name, string value) : this (name, name, value ) { } /// /// Initializes a new instance of the LabeledProperty class. /// /// /// /// public LabeledProperty(string name, string label, string value) { this.Name = name; this.Label = label; this.Value = value; } /// /// The name of the property. The name is constant across cultures and is intended as an id other systems can use. /// public string Name { get; set; } /// /// The label the user should see. /// public string Label { get; set; } /// /// The value of the property /// public string Value { get; set; } } } ================================================ FILE: Composite/C1Console/Elements/LabeledPropertyList.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Composite.C1Console.Elements { internal class LabeledPropertyList : IEnumerable { private List _list = new List(); public void Add(string name, string value) { _list.Add(new LabeledProperty(name, value)); } public void Add(string name, object value) { _list.Add(new LabeledProperty(name, value.ToString())); } public void Add(string name, string label, string value) { _list.Add(new LabeledProperty(name, label, value)); } public void Add(string name, string label, object value) { _list.Add(new LabeledProperty(name, label, value.ToString())); } public IEnumerator GetEnumerator() { return _list.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _list.GetEnumerator(); } } } ================================================ FILE: Composite/C1Console/Elements/PiggybagSerializer.cs ================================================ using System.Collections.Generic; using System.Text; using Composite.Core.Serialization; namespace Composite.C1Console.Elements { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PiggybagSerializer { /// public static string Serialize(Dictionary piggybag) { var sb = new StringBuilder(); foreach (KeyValuePair kvp in piggybag) { StringConversionServices.SerializeKeyValuePair(sb, kvp.Key, kvp.Value); } return sb.ToString(); } /// public static Dictionary Deserialize(string serializedPiggybag) { Dictionary piggyback = new Dictionary(); Dictionary dic = StringConversionServices.ParseKeyValueCollection(serializedPiggybag); foreach (var kvp in dic) { piggyback.Add(kvp.Key, StringConversionServices.DeserializeValueString(kvp.Value)); } return piggyback; } } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementActionProvider/ElementActionProviderData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Elements.Plugins.ElementActionProvider { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ConfigurationElementType(typeof(NonConfigurableElementActionProvider))] public class ElementActionProviderData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementActionProvider/IElementActionProvider.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Elements.Plugins.ElementActionProvider.Runtime; using Composite.C1Console.Security; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementActionProvider { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [CustomFactory(typeof(ElementActionProviderCustomFactory))] [ConfigurationNameMapper(typeof(ElementActionProviderDefaultNameRetriever))] public interface IElementActionProvider { /// IEnumerable GetActions(EntityToken entityToken); } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementActionProvider/NonConfigurableElementActionProvider.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementActionProvider { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Assembler(typeof(NonConfigurableElementActionProviderAssembler))] public class NonConfigurableElementActionProvider : ElementActionProviderData { } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class NonConfigurableElementActionProviderAssembler : IAssembler { /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IElementActionProvider Assemble(IBuilderContext context, ElementActionProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IElementActionProvider)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementActionProvider/Runtime/ElementActionProviderCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementActionProvider.Runtime { internal sealed class ElementActionProviderCustomFactory : AssemblerBasedCustomFactory { protected override ElementActionProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { ElementActionProviderSettings settings = configurationSource.GetSection(ElementActionProviderSettings.SectionName) as ElementActionProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", ElementActionProviderSettings.SectionName)); } return settings.ElementActionProviderPlugins.Get(name); } } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementActionProvider/Runtime/ElementActionProviderDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementActionProvider.Runtime { internal sealed class ElementActionProviderDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementActionProvider/Runtime/ElementActionProviderFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementActionProvider.Runtime { internal sealed class ElementActionProviderFactory : NameTypeFactoryBase { public ElementActionProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementActionProvider/Runtime/ElementActionProviderSettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Elements.Plugins.ElementActionProvider.Runtime { internal sealed class ElementActionProviderSettings : SerializableConfigurationSection { public const string SectionName = "Composite.C1Console.Elements.Plugins.ElementActionProviderConfiguration"; private const string _elementActionProviderPluginsProperty = "ElementActionProviderPlugins"; [ConfigurationProperty(_elementActionProviderPluginsProperty)] public NameTypeManagerTypeConfigurationElementCollection ElementActionProviderPlugins { get { return (NameTypeManagerTypeConfigurationElementCollection)base[_elementActionProviderPluginsProperty]; } } } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementAttachingProvider/ElementAttachingProviderData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Elements.Plugins.ElementAttachingProvider { /// [ConfigurationElementType(typeof(NonConfigurableElementAttachingProvider))] public class ElementAttachingProviderData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementAttachingProvider/IElementAttachingProvider.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Elements.Plugins.ElementAttachingProvider.Runtime; using Composite.C1Console.Security; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementAttachingProvider { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum ElementAttachingProviderPosition { /// /// At the top /// Top = 0, /// /// At the bottom /// Bottom = 1 } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ElementAttachingProviderResult { /// public ElementAttachingProviderResult() { this.Position = ElementAttachingProviderPosition.Bottom; } /// /// IF this is null, then the hole result is ignored /// public IEnumerable Elements { get; set; } /// public ElementAttachingProviderPosition Position { get; set; } /// /// This is used if more than one element attaching provider is adding elements. /// Bigger is higher. /// public int PositionPriority { get; set; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [CustomFactory(typeof(ElementAttachingProviderCustomFactory))] [ConfigurationNameMapper(typeof(ElementAttachingProviderDefaultNameRetriever))] public interface IElementAttachingProvider { /// /// The system will supply an ElementProviderContext to the provider /// to use for creating ElementHandles /// ElementProviderContext Context { set; } /// /// This is only called when rendering root nodes. Used to switch HasChildren from false to true. /// /// /// /// /// bool HaveCustomChildElements(EntityToken parentEntityToken, Dictionary piggybag); /// /// If null is returned, the result is ignored /// /// /// /// ElementAttachingProviderResult GetAlternateElementList(EntityToken parentEntityToken, Dictionary piggybag); /// IEnumerable GetChildren(EntityToken parentEntityToken, Dictionary piggybag); } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementAttachingProvider/IMultipleResultElementAttachingProvider.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Security; namespace Composite.C1Console.Elements.Plugins.ElementAttachingProvider { internal interface IMultipleResultElementAttachingProvider : IElementAttachingProvider { /// /// If null is returned, the result is ignored /// /// /// /// IEnumerable GetAlternateElementLists(EntityToken parentEntityToken, Dictionary piggybag); } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementAttachingProvider/NonConfigurableElementAttachingProvider.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementAttachingProvider { /// [Assembler(typeof(NonConfigurableElementAttachingProviderAssembler))] public class NonConfigurableElementAttachingProvider : ElementAttachingProviderData { } internal sealed class NonConfigurableElementAttachingProviderAssembler : IAssembler { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IElementAttachingProvider Assemble(IBuilderContext context, ElementAttachingProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IElementAttachingProvider)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementAttachingProvider/Runtime/ElementAttachingProviderCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementAttachingProvider.Runtime { internal sealed class ElementAttachingProviderCustomFactory : AssemblerBasedCustomFactory { protected override ElementAttachingProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { ElementAttachingProviderSettings settings = configurationSource.GetSection(ElementAttachingProviderSettings.SectionName) as ElementAttachingProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", ElementAttachingProviderSettings.SectionName)); } return settings.ElementAttachingProviderPlugins.Get(name); } } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementAttachingProvider/Runtime/ElementAttachingProviderDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementAttachingProvider.Runtime { internal sealed class ElementAttachingProviderDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementAttachingProvider/Runtime/ElementAttachingProviderFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementAttachingProvider.Runtime { internal sealed class ElementAttachingProviderFactory : NameTypeFactoryBase { public ElementAttachingProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementAttachingProvider/Runtime/ElementAttachingProviderSettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Elements.Plugins.ElementAttachingProvider.Runtime { internal sealed class ElementAttachingProviderSettings : SerializableConfigurationSection { public const string SectionName = "Composite.C1Console.Elements.Plugins.ElementAttachingProviderConfiguration"; private const string _elementAttachingProviderPluginsProperty = "ElementAttachingProviderPlugins"; [ConfigurationProperty(_elementAttachingProviderPluginsProperty)] public NameTypeManagerTypeConfigurationElementCollection ElementAttachingProviderPlugins { get { return (NameTypeManagerTypeConfigurationElementCollection)base[_elementAttachingProviderPluginsProperty]; } } } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/ElementProviderData.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using System.ComponentModel; namespace Composite.C1Console.Elements.Plugins.ElementProvider { /// /// /// [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete] [ConfigurationElementType(typeof(NonConfigurableElementProvider))] public class ElementProviderData : HooklessElementProviderData { } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/HooklessElementProviderData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using System.ComponentModel; namespace Composite.C1Console.Elements.Plugins.ElementProvider { /// /// /// [EditorBrowsable(EditorBrowsableState.Never)] [ConfigurationElementType(typeof(NonConfigurableHooklessElementProvider))] public class HooklessElementProviderData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/ICustomSearchElementProvider.cs ================================================ using System.Xml; using Composite.C1Console.Security; using System.Collections.Generic; namespace Composite.C1Console.Elements.Plugins.ElementProvider { internal interface ICustomSearchElementProvider : IHooklessElementProvider { SearchToken GetNewSearchToken(EntityToken entityToken); XmlReader GetSearchFormDefinition(EntityToken entityToken); Dictionary GetSearchFormBindings(EntityToken entityToken); } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/IDataExchangingElementProvider.cs ================================================  namespace Composite.C1Console.Elements.Plugins.ElementProvider { internal interface IDataExchangingElementProvider : IHooklessElementProvider { object GetData(string name); } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/IDragAndDropElementProvider.cs ================================================ using Composite.C1Console.Actions; using Composite.C1Console.Security; namespace Composite.C1Console.Elements.Plugins.ElementProvider { /// /// You can implement this interface on your element provider to handle the "drag and drop" event. /// public interface IDragAndDropElementProvider : IHooklessElementProvider { /// /// Invoked when an element is dropped /// /// The of the element being dragged /// The of the element receiving the dragged item /// The index (position) the element was dropped /// The type identifying the drang and drop action /// handle that let you communicate to client via services (like popping a dialog) /// True is action completed as expected and tree should be updated on the client bool OnElementDraggedAndDropped(EntityToken draggedEntityToken, EntityToken newParentEntityToken, int dropIndex, DragAndDropType dragAndDropType, FlowControllerServicesContainer draggedElementFlowControllerServicesContainer); } /// /// Specifies the kind of action that should happen on drop /// public enum DragAndDropType { /// /// The element is moved /// Move, /// /// The element is copied /// Copy } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/IElementProvider.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Elements.Plugins.ElementProvider.Runtime; using Composite.C1Console.Security; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementProvider { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Use interfaces IElementAttachingProvider and IAuxiliarySecurityAncestorProvider instead")] [CustomFactory(typeof(ElementProviderCustomFactory))] [ConfigurationNameMapper(typeof(ElementProviderDefaultNameRetriever))] public interface IElementProvider : IHooklessElementProvider { /// /// Hooks are not affected by searches. /// /// List GetHooks(); } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/IHooklessElementProvider.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Elements.Plugins.ElementProvider.Runtime; using Composite.C1Console.Security; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementProvider { /// /// This interface is implemented by element providers - plug-ins that can decorate the C1 Console tree structure with elements. /// [CustomFactory(typeof(HooklessElementProviderCustomFactory))] [ConfigurationNameMapper(typeof(HooklessElementProviderDefaultNameRetriever))] public interface IHooklessElementProvider { /// /// The system will supply an ElementProviderContext to the provider /// to use for creating -s /// ElementProviderContext Context { set; } /// /// Gets the provider's root elements /// /// /// If this is null the provider should not do any filtering. If this is not null the provider /// should do the appropriate filtering on its elements. /// If the provider does not want to be a part of a search and this variable is not null, /// the provider should return an empty list /// /// Root elements IEnumerable GetRoots(SearchToken seachToken); /// /// Gets the children of a given element /// /// The parent element of the elements to return /// /// If this is null the provider should not do any filtering. If this is not null the provider /// should do the appropriate filtering on its elements. /// If the provider does not want to be a part of a search and this variable is not null, /// the provider should return an empty list /// /// Child elements IEnumerable GetChildren(EntityToken entityToken, SearchToken seachToken); } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/ILabeledPropertiesElementProvider.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Security; namespace Composite.C1Console.Elements.Plugins.ElementProvider { internal interface ILabeledPropertiesElementProvider : IHooklessElementProvider { IEnumerable GetLabeledProperties(EntityToken entityToken); } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/ILocaleAwareElementProvider.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.C1Console.Security; // The namespace is wrong but is left for backwards compatibility namespace Composite.C1Console.Elements { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface ILocaleAwareElementProvider : IHooklessElementProvider { /// bool ContainsLocalizedData { get; } /// IEnumerable GetForeignRoots(SearchToken searchToken); /// IEnumerable GetForeignChildren(EntityToken entityToken, SearchToken searchToken); } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/ILocaleAwareLabeledPropertiesElementProvider.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Security; namespace Composite.C1Console.Elements.Plugins.ElementProvider { internal interface ILocaleAwareLabeledPropertiesElementProvider : ILocaleAwareElementProvider { IEnumerable GetForeignLabeledProperties(EntityToken entityToken); } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/NonConfigurableElementProvider.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; using System.ComponentModel; namespace Composite.C1Console.Elements.Plugins.ElementProvider { #pragma warning disable 612 /// /// /// [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete] [Assembler(typeof(NonConfigurableElementProviderAssembler))] public class NonConfigurableElementProvider : ElementProviderData { } /// /// /// [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete] public sealed class NonConfigurableElementProviderAssembler : IAssembler { /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IElementProvider Assemble(IBuilderContext context, ElementProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IElementProvider)Activator.CreateInstance(objectConfiguration.Type); } } #pragma warning restore 612 } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/NonConfigurableHooklessElementProvider.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementProvider { [Assembler(typeof(NonConfigurableHooklessElementProviderAssembler))] internal class NonConfigurableHooklessElementProvider : HooklessElementProviderData { } internal sealed class NonConfigurableHooklessElementProviderAssembler : IAssembler { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IHooklessElementProvider Assemble(IBuilderContext context, HooklessElementProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IHooklessElementProvider)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/Runtime/ElementProviderCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementProvider.Runtime { #pragma warning disable 612 internal sealed class ElementProviderCustomFactory : AssemblerBasedCustomFactory { protected override ElementProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { ElementProviderSettings settings = configurationSource.GetSection(ElementProviderSettings.SectionName) as ElementProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", ElementProviderSettings.SectionName)); } return (ElementProviderData)settings.ElementProviderPlugins.Get(name); } } #pragma warning restore 612 } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/Runtime/ElementProviderDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementProvider.Runtime { internal sealed class ElementProviderDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/Runtime/ElementProviderFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementProvider.Runtime { #pragma warning disable 612 internal sealed class ElementProviderFactory : NameTypeFactoryBase { public ElementProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } } #pragma warning restore 612 } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/Runtime/ElementProviderSettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Elements.Plugins.ElementProvider.Runtime { internal sealed class ElementProviderSettings : SerializableConfigurationSection { public const string SectionName = "Composite.C1Console.Elements.Plugins.ElementProviderConfiguration"; private const string _rootProviderNameProperty = "rootProviderName"; [ConfigurationProperty(_rootProviderNameProperty, IsRequired = true)] public string RootProviderName { get { return (string)base[_rootProviderNameProperty]; } set { base[_rootProviderNameProperty] = value; } } private const string _elementProviderPluginsProperty = "ElementProviderPlugins"; [ConfigurationProperty(_elementProviderPluginsProperty)] public NameTypeManagerTypeConfigurationElementCollection ElementProviderPlugins { get { return (NameTypeManagerTypeConfigurationElementCollection)base[_elementProviderPluginsProperty]; } } } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/Runtime/HooklessElementProviderCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementProvider.Runtime { internal sealed class HooklessElementProviderCustomFactory : AssemblerBasedCustomFactory { protected override HooklessElementProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { ElementProviderSettings settings = configurationSource.GetSection(ElementProviderSettings.SectionName) as ElementProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", ElementProviderSettings.SectionName)); } return settings.ElementProviderPlugins.Get(name); } } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/Runtime/HooklessElementProviderDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementProvider.Runtime { internal sealed class HooklessElementProviderDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/C1Console/Elements/Plugins/ElementProvider/Runtime/HooklessElementProviderFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Elements.Plugins.ElementProvider.Runtime { internal sealed class HooklessElementProviderFactory : NameTypeFactoryBase { public HooklessElementProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/C1Console/Elements/SearchToken.cs ================================================ using System; using Composite.Core.Extensions; using Composite.Core.Serialization; using Composite.Core.Types; namespace Composite.C1Console.Elements { /// /// Class that describe a element provider search. Sub class this for more specific fields. As a minimum a Keyword is present. /// public class SearchToken { /// /// Keyword to search for /// public string Keyword { get; set; } /// /// Serializes this instance /// /// String representation public string Serialize() { return CompositeJsonSerializer.SerializeObject(this); } /// /// Deserializes a search token /// /// String representation of searchtoken /// Deserialized SearchToken public static SearchToken Deserialize( string serializedSearchToken ) { Verify.ArgumentNotNullOrEmpty(serializedSearchToken, nameof(serializedSearchToken)); if (serializedSearchToken.StartsWith("{")) { return CompositeJsonSerializer.Deserialize(serializedSearchToken); } return DeserializeLegacy(serializedSearchToken); } private static SearchToken DeserializeLegacy(string serializedSearchToken) { Verify.ArgumentNotNullOrEmpty(serializedSearchToken, nameof(serializedSearchToken)); Verify.ArgumentCondition(serializedSearchToken.IndexOf('|') > -1, nameof(serializedSearchToken), "Malformed serializedSearchToken - must be formated like '|'"); string[] parts = serializedSearchToken.Split('|'); string className = parts[0]; string serializedSearchTokenWithoutClassName = parts[1]; Type searchTokenType = TypeManager.GetType(className); SearchToken searchToken = (SearchToken)SerializationFacade.Deserialize(searchTokenType, serializedSearchTokenWithoutClassName); return searchToken; } } internal static class SeachTokenExtensionMethods { /// /// This method return true if the is NOT null and the keyword is NOT null or empty /// /// /// public static bool IsValidKeyword(this SearchToken searchToken) { return searchToken != null && !searchToken.Keyword.IsNullOrEmpty(); } } } ================================================ FILE: Composite/C1Console/Elements/ShowErrorElementHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.C1Console.Security; using Composite.Core.ResourceSystem; using Composite.C1Console.Actions; namespace Composite.C1Console.Elements { internal static class ShowErrorElementHelper { public static Element CreateErrorElement(string label, string toolTip, string message) { Element errorElement = new Element(new ElementHandle("DUMMYPROVIDER", new NoSecurityEntityToken())) { VisualData = new ElementVisualizedData { Label = label, ToolTip = toolTip, Icon = ResourceHandle.BuildIconFromDefaultProvider("close"), OpenedIcon = ResourceHandle.BuildIconFromDefaultProvider("close"), HasChildren = false } }; errorElement.AddAction(new ElementAction(new ActionHandle(new MessageBoxActionToken( label, message, C1Console.Events.DialogType.Error ))) { VisualData = new ActionVisualizedData() { Label = label, ToolTip = toolTip, Icon = ResourceHandle.BuildIconFromDefaultProvider("close"), ActionLocation = ActionLocation.OtherPrimaryActionLocation } }); return errorElement; } } } ================================================ FILE: Composite/C1Console/Elements/TreeLockBehavior.cs ================================================ namespace Composite.C1Console.Elements { /// /// When client is searching through elements to find the element with the given entity token, /// the client should disregard elements with TreeLockBehavior = None and continue searching. /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum TreeLockBehavior { /// None, /// Normal } } ================================================ FILE: Composite/C1Console/Elements/UrlToEntityTokenFacade.cs ================================================ using System.Collections.Concurrent; using System.Linq; using Composite.C1Console.Security; using Composite.Core; using Composite.Core.Extensions; namespace Composite.C1Console.Elements { /// /// Associates C1 console tree elements with a url to be used for public consumption or showing in the C1 console browser. /// public static class UrlToEntityTokenFacade { private const string LogTitle = nameof(UrlToEntityTokenFacade); private static readonly ConcurrentBag _mappers = new ConcurrentBag(); private static readonly ConcurrentBag _serviceMappers = new ConcurrentBag(); /// /// Returns a url associated with an entity token, or null if current entity token does not support this kind of entity token. /// /// The entity token. /// URL for public consumption public static string TryGetUrl(EntityToken entityToken) { var theUrl = _mappers.Select(mapper => mapper.TryGetUrl(entityToken)).FirstOrDefault(url => url != null); return ProcessUrlWithServiceMappers(theUrl, entityToken); } /// /// Returns a url / tooling settings associated with an entity token to be used in the C1 Console browser, or null if current entity token does not support this kind of entity token. /// /// The entity token. /// When true will show a published version of the page/data item. /// URL for public consumption public static BrowserViewSettings TryGetBrowserViewSettings(EntityToken entityToken, bool showPublishedView) { var theBrowserSetting = _mappers.Select(mapper => mapper.TryGetBrowserViewSettings(entityToken, showPublishedView)) .FirstOrDefault(settings => settings?.Url != null); if (theBrowserSetting == null) return null; var originalUrl = theBrowserSetting.Url; theBrowserSetting.Url = ProcessUrlWithServiceMappers(originalUrl, entityToken); return theBrowserSetting; } private static string ProcessUrlWithServiceMappers(string url, EntityToken entityToken) { _serviceMappers.ForEach(service => { url = service.ProcessUrl(url, entityToken); }); return url; } /// /// Returns an entity token associated with a url, or null if current does not support this kind of entity token. /// /// The url. /// public static EntityToken TryGetEntityToken(string url) { var originalUrl = url; _serviceMappers.Select(sm => sm.CleanUrl(ref url)); var baseEntityToken = _mappers.Select(mapper => mapper.TryGetEntityToken(url)).FirstOrDefault(entityToken => entityToken != null); _serviceMappers.Select(sm => sm.TryGetEntityToken(originalUrl, ref baseEntityToken)); return baseEntityToken; } /// /// Register an implementation of /// /// public static void Register(IUrlToEntityTokenMapper mapper) { Verify.ArgumentNotNull(mapper, nameof(mapper)); if (_mappers.Count > 100) { Log.LogWarning(LogTitle, "More than 100 implementations of {0}-s registered: possible memory leak. Registered type: {1}", nameof(IUrlToEntityTokenMapper), mapper.GetType().FullName); return; } _mappers.Add(mapper); } /// /// Register an implementation of /// /// public static void Register(IServiceUrlToEntityTokenMapper serviceMapper) { Verify.ArgumentNotNull(serviceMapper, nameof(serviceMapper)); if (_serviceMappers.Count > 100) { Log.LogWarning(LogTitle, "More than 100 implementations of {0}-s registered: possible memory leak. Registered type: {1}", nameof(IServiceUrlToEntityTokenMapper), serviceMapper.GetType().FullName); return; } _serviceMappers.Add(serviceMapper); } } } ================================================ FILE: Composite/C1Console/Events/BindEntityTokenToViewQueueItem.cs ================================================ using System; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class BindEntityTokenToViewQueueItem : IConsoleMessageQueueItem { /// public string ViewId { get; set; } /// public string EntityToken { get; set; } } } ================================================ FILE: Composite/C1Console/Events/BroadcastMessageQueueItem.cs ================================================ using System; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class BroadcastMessageQueueItem : IConsoleMessageQueueItem { /// public string Name { get; set; } /// public string Value { get; set; } } } ================================================ FILE: Composite/C1Console/Events/CloseAllViewsMessageQueueItem.cs ================================================ using System; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class CloseAllViewsMessageQueueItem : IConsoleMessageQueueItem { /// public string Reason { get; set; } } } ================================================ FILE: Composite/C1Console/Events/CloseViewMessageQueueItem.cs ================================================ using System; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class CloseViewMessageQueueItem : IConsoleMessageQueueItem { /// public string ViewId { get; set; } } } ================================================ FILE: Composite/C1Console/Events/CollapseAndRefreshConsoleMessageQueueItem.cs ================================================ using System; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class CollapseAndRefreshConsoleMessageQueueItem : IConsoleMessageQueueItem { } } ================================================ FILE: Composite/C1Console/Events/ConsoleFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Workflow.Runtime; using Composite.Core; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.Core.Configuration; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ConsoleClosedEventArgs : EventArgs { /// public ConsoleClosedEventArgs(string consoleId) { this.ConsoleId = consoleId; } /// public string ConsoleId { get; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ConsoleFacade { private static readonly string LogTitle = nameof(ConsoleFacade); /// public delegate void ConsoleClosedEventDelegate(ConsoleClosedEventArgs args); private static TimeSpan? _timeout; private static bool _initialized; private static readonly object _lock = new object(); private static event ConsoleClosedEventDelegate _consoleClosedEvent; /// public static void Initialize() { WorkflowFacade.RunWhenInitialized(() => { lock (_lock) { if (!_initialized) { WorkflowInstance workflowInstance = WorkflowFacade.CreateNewWorkflow(WorkflowFacade.GetWorkflowType("Composite.C1Console.Events.Workflows.UserConsoleInformationScavengerWorkflow")); workflowInstance.Start(); WorkflowFacade.RunWorkflow(workflowInstance); if (RuntimeInformation.IsDebugBuild) { Log.LogVerbose(LogTitle, "Scavenger started"); } _initialized = true; } } }); } /// /// Flush code MAY NOT do ANY kind of re-initialization. /// /// public static void SubscribeToConsoleClosedEvent(ConsoleClosedEventDelegate eventDelegate) { _consoleClosedEvent += eventDelegate; } /// public static void UnsubscribeFromConsoleClosedEvent(ConsoleClosedEventDelegate eventDelegate) { _consoleClosedEvent -= eventDelegate; } /// public static void CloseConsole(string consoleId) { UnregisterConsole(UserSettings.Username, consoleId); } /// public static IEnumerable GetConsoleIdsByUsername(string username) { return (from d in DataFacade.GetData() where d.Username == username select d.ConsoleId).ToList(); } internal static void RegisterConsole(string username, string consoleId) { using(GlobalInitializerFacade.CoreIsInitializedScope) lock (_lock) { IUserConsoleInformation userConsoleInformation = (from d in DataFacade.GetData() where d.Username == username && d.ConsoleId == consoleId select d).FirstOrDefault(); if (userConsoleInformation == null) { Log.LogVerbose(LogTitle, $"New console registred by '{username}' id = '{consoleId}'"); userConsoleInformation = DataFacade.BuildNew(); userConsoleInformation.Id = Guid.NewGuid(); userConsoleInformation.Username = username; userConsoleInformation.ConsoleId = consoleId; userConsoleInformation.TimeStamp = DateTime.Now; DataFacade.AddNew(userConsoleInformation); } else { userConsoleInformation.TimeStamp = DateTime.Now; DataFacade.Update(userConsoleInformation); } } } internal static void UnregisterConsole(string username, string consoleId) { lock (_lock) { List userConsoleInformations = (from d in DataFacade.GetData() where d.Username == username && d.ConsoleId == consoleId select d).ToList(); foreach (IUserConsoleInformation userConsoleInformation in userConsoleInformations) { Log.LogVerbose(LogTitle, "Console unregistred by '{0}' id = '{1}'", userConsoleInformation.Username, userConsoleInformation.ConsoleId); DataFacade.Delete(userConsoleInformation); FireConsoleClosedEvent(userConsoleInformation.ConsoleId); } } } /// public static void Scavenge() { if(RuntimeInformation.IsDebugBuild) { Log.LogVerbose(LogTitle, "Starting scavenger run"); } using(GlobalInitializerFacade.CoreIsInitializedScope) // Holding this lock in order to avoid deadlocks lock (_lock) { DateTime now = DateTime.Now; List userConsoleInformations = (from d in DataFacade.GetData() select d).ToList(); foreach (IUserConsoleInformation userConsoleInformation in userConsoleInformations) { if (now - userConsoleInformation.TimeStamp > Timeout) { Log.LogWarning(LogTitle, "The console '{0}' owned by the user '{1}' timed out, closing it", userConsoleInformation.ConsoleId, userConsoleInformation.Username); DataFacade.Delete(userConsoleInformation); FireConsoleClosedEvent(userConsoleInformation.ConsoleId); } } } } private static TimeSpan Timeout => _timeout ?? (_timeout = GlobalSettingsFacade.ConsoleTimeout).Value; private static void FireConsoleClosedEvent(string consoleId) { lock (_lock) { _consoleClosedEvent?.Invoke(new ConsoleClosedEventArgs(consoleId)); } } } } ================================================ FILE: Composite/C1Console/Events/ConsoleMessageQueueFacade.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Events.Foundation; using Composite.Core.Configuration; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ConsoleMessageQueueFacade { private static ConsoleMessageQueue _messageQeueue = new ConsoleMessageQueue(GlobalSettingsFacade.ConsoleMessageQueueItemSecondToLive); // Dont add flush / initialize to this class. We do not want console messages to get lost. /// /// /// /// /// null or empty string is a broardcast public static void Enqueue(IConsoleMessageQueueItem consoleMessageQueueItem, string receiverConsoleId) { if (consoleMessageQueueItem == null) throw new ArgumentNullException("consoleMessageQueueItem"); _messageQeueue.Enqueue(consoleMessageQueueItem, receiverConsoleId); } /// public static IEnumerable GetQueueElements(int currentConsoleCounter, string consoleId) { return _messageQeueue.GetQueueElements(currentConsoleCounter, consoleId); } /// public static int GetLatestMessageNumber(string consoleId) { return _messageQeueue.GetLatestMessageNumber(consoleId); } /// public static int CurrentChangeNumber { get { return _messageQeueue.CurrentQueueItemNumber; } } /// public static void DoDebugSerializationToFileSystem() { _messageQeueue.DoDebugSerializationToFileSystem(); } } } ================================================ FILE: Composite/C1Console/Events/DialogTypeEnum.cs ================================================  namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum DialogType { /// Message, /// Question, /// Warning, /// Error } } ================================================ FILE: Composite/C1Console/Events/DownloadFileMessageQueueItem.cs ================================================ using Composite.Core.ResourceSystem; using System; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class DownloadFileMessageQueueItem : IConsoleMessageQueueItem { /// public DownloadFileMessageQueueItem(string urlToDownload) { this.Url = urlToDownload; } /// public string Url { get; set; } } } ================================================ FILE: Composite/C1Console/Events/FlushAttribute.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Composite.C1Console.Events { /// /// This attribute registres a method that can be called to make a local flush /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Class)] public class FlushAttribute : Attribute { /// /// /// /// The name of the method to call when doing a local flush. Must be of type: static void() public FlushAttribute(string methodName) { this.MethodName = methodName; } /// public string MethodName { get; private set; } } } ================================================ FILE: Composite/C1Console/Events/Foundation/ConsoleMessageQueue.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Xml.Linq; using Composite.Core; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.Serialization; using Composite.Core.Xml; namespace Composite.C1Console.Events.Foundation { internal sealed class ConsoleMessageQueue { private const string MessageQueueFileName = "ConsoleMessages.xml"; private int _queueItemCounter = 1; private readonly object _lock = new object(); private readonly TimeSpan _timeInterval; private List _elements = new List(); private string MessageQueueFilePath { get; set; } private readonly Timer _timer; public ConsoleMessageQueue(int secondsForItemToLive) { string directory = PathUtil.Resolve(GlobalSettingsFacade.SerializedConsoleMessagesDirectory); if (!C1Directory.Exists(directory)) C1Directory.CreateDirectory(directory); MessageQueueFilePath = Path.Combine(directory, MessageQueueFileName); _timeInterval = new TimeSpan(0, 0, secondsForItemToLive); DeserializeMessagesFromFileSystem(); _timer = new Timer(OnWeed, null, new TimeSpan(0, 0, 0), _timeInterval); } /// /// /// /// /// null or empty string is a broardcast public void Enqueue(IConsoleMessageQueueItem queueItem, string receiverConsoleId) { if (queueItem == null) throw new ArgumentNullException("queueItem"); if (receiverConsoleId == "") receiverConsoleId = null; lock (_lock) { var queueElement = new ConsoleMessageQueueElement { ReceiverConsoleId = receiverConsoleId, QueueItemNumber = ++_queueItemCounter, EnqueueTime = DateTime.Now, QueueItem = queueItem }; _elements.Add(queueElement); SerializeMessagesToFileSystem(); } } public IEnumerable GetQueueElements(int currentConsoleCounter, string consoleId) { lock (_lock) { if (consoleId == null) { return (from element in _elements where element.QueueItemNumber > currentConsoleCounter orderby element.QueueItemNumber select element).ToList(); } return (from element in _elements where element.QueueItemNumber > currentConsoleCounter && (element.ReceiverConsoleId == consoleId || element.ReceiverConsoleId == null) orderby element.QueueItemNumber select element).ToList(); } } public int GetLatestMessageNumber(string consoleId) { Verify.ArgumentNotNull(consoleId, "consoleId"); lock (_lock) { for (int i = _elements.Count - 1; i >= 0; i--) { string receiverConsoleId = _elements[i].ReceiverConsoleId; if (receiverConsoleId == null || receiverConsoleId == consoleId) { return _elements[i].QueueItemNumber; } } } return 0; } public int CurrentQueueItemNumber { get { lock (_lock) { return _queueItemCounter; } } } private void OnWeed(object obj) { lock (_lock) { CleanOutOldMessages(_elements); } } private void CleanOutOldMessages(List listToClean) { if (listToClean == null) return; DateTime now = DateTime.Now; int count = listToClean.Count(element => element.EnqueueTime + _timeInterval < now); if (count > 0) { listToClean.RemoveRange(0, count); } } public void DoDebugSerializationToFileSystem() { SerializeMessagesToFileSystem(true); } private void SerializeMessagesToFileSystem(bool forDebug = false) { lock (_lock) { if (_elements != null && _elements.Count > 0) { IXmlSerializer xmlSerializer = GetMessageListXmlSerializer(); XElement serializedMessages = xmlSerializer.Serialize(_elements.GetType(), _elements); string serializedConsoleMessagesDir = PathUtil.Resolve((forDebug ? GlobalSettingsFacade.TempDirectory : GlobalSettingsFacade.SerializedConsoleMessagesDirectory)); string queueElementsXmlFilePath = Path.Combine(serializedConsoleMessagesDir, MessageQueueFileName); serializedMessages.SaveToPath(queueElementsXmlFilePath); } } } private void DeserializeMessagesFromFileSystem() { lock (_lock) { if (!C1File.Exists(MessageQueueFilePath)) return; XElement serializedMessages; try { serializedMessages = XElementUtils.Load(MessageQueueFilePath); } catch (Exception) { return; } IXmlSerializer xmlSerializer = GetMessageListXmlSerializer(); _elements = xmlSerializer.Deserialize(serializedMessages) as List; if (_elements == null) _elements = new List(); CleanOutOldMessages(_elements); if (_elements.Any()) { _queueItemCounter = _elements.Max(f => f.QueueItemNumber); } } } private static void LogMessageQueue(IEnumerable messageQueue, string title = null) { if (title != null) Log.LogInformation("ConsoleMessageQueue", title); foreach (ConsoleMessageQueueElement element in messageQueue) { Log.LogInformation("ConsoleMessageQueue", string.Format("Message: ItemNumber: {0}, Type: {1}", element.QueueItemNumber, element.QueueItem.GetType().Name)); } } private static IXmlSerializer GetMessageListXmlSerializer() { IXmlSerializer xmlSerializer = new XmlSerializer(new IValueXmlSerializer[] { new SystemPrimitivValueXmlSerializer(), new SerializerHandlerValueXmlSerializer(), new ConsoleMessageQueueElementListValueXmlSerializer(), new SystemCollectionValueXmlSerializer(), new SystemTypesValueXmlSerializer(), new SystemSerializableValueXmlSerializer()}); return xmlSerializer; } } } ================================================ FILE: Composite/C1Console/Events/Foundation/ConsoleMessageQueueElement.cs ================================================ using System; namespace Composite.C1Console.Events.Foundation { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ConsoleMessageQueueElement { /// public string ReceiverConsoleId { get; internal set; } /// public int QueueItemNumber { get; internal set; } /// public DateTime EnqueueTime { get; internal set; } /// public IConsoleMessageQueueItem QueueItem { get; internal set; } } } ================================================ FILE: Composite/C1Console/Events/Foundation/ConsoleMessageQueueElementListValueXmlSerializer.cs ================================================ using System; using System.Linq; using System.Xml.Linq; using Composite.Core.Serialization; using System.Collections.Generic; using Composite.Core.Logging; namespace Composite.C1Console.Events.Foundation { internal sealed class ConsoleMessageQueueElementListValueXmlSerializer : IValueXmlSerializer { public bool TrySerialize(Type objectToSerializeType, object objectToSerialize, IXmlSerializer xmlSerializer, out XElement serializedList) { if (objectToSerializeType == null) throw new ArgumentNullException("objectToSerializeType"); if (xmlSerializer == null) throw new ArgumentNullException("xmlSerializer"); serializedList = null; if (objectToSerializeType != typeof(List)) return false; List queueElements = objectToSerialize as List; serializedList = new XElement("ConsoleMessageQueueElements"); if (queueElements != null) { foreach (ConsoleMessageQueueElement queueElement in queueElements) { XElement serializedQueueItem = xmlSerializer.Serialize(queueElement.QueueItem.GetType(), queueElement.QueueItem); XElement serializedElement = new XElement("QueueElement", new XAttribute("time", queueElement.EnqueueTime), new XAttribute("number", queueElement.QueueItemNumber), new XAttribute("itemtype", queueElement.QueueItem.GetType()), serializedQueueItem); if (string.IsNullOrEmpty(queueElement.ReceiverConsoleId) == false) { serializedElement.Add(new XAttribute("console", queueElement.ReceiverConsoleId)); } serializedList.Add(serializedElement); } } return true; } public bool TryDeserialize(XElement serializedObject, IXmlSerializer xmlSerializer, out object deserializedObject) { if (serializedObject == null) throw new ArgumentNullException("serializedObject"); if (xmlSerializer == null) throw new ArgumentNullException("xmlSerializer"); deserializedObject = null; if (serializedObject.Name.LocalName != "ConsoleMessageQueueElements") return false; List queueElements = new List(); foreach (XElement queueElement in serializedObject.Elements()) { ConsoleMessageQueueElement result = new ConsoleMessageQueueElement(); result.EnqueueTime = DateTime.Parse(queueElement.Attribute("time").Value); result.QueueItemNumber = Int32.Parse(queueElement.Attribute("number").Value); if (queueElement.Attribute("console") != null) result.ReceiverConsoleId = queueElement.Attribute("console").Value; try { result.QueueItem = (IConsoleMessageQueueItem)xmlSerializer.Deserialize(queueElement.Elements().First()); } catch (Exception ex) { string errorInfo = string.Format("Deserialization of message #{0} failed with an '{1}' exception - the message has been dropped. Details: '{2}'", queueElement.Attribute("number").Value, ex.GetType().Name, ex.Message); // pad queue to ensure sequence. LoggingService.LogWarning("ConsoleMessageQueue", errorInfo); result.QueueItem = new LogEntryMessageQueueItem { Level = LogLevel.Error, Message = errorInfo, Sender = this.GetType() }; } queueElements.Add(result); } deserializedObject = queueElements; return true; } } } ================================================ FILE: Composite/C1Console/Events/GlobalEventSystemFacade.cs ================================================ using System; using Composite.Core; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class FlushEventArgs : EventArgs { } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class PostFlushEventArgs : EventArgs { } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ShutDownEventArgs : EventArgs { } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class PrepareForShutDownEventArgs : EventArgs { } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class GlobalEventSystemFacade { private static readonly string LogTitle = "RGB(255, 128, 255)GlobalEventSystemFacade"; /// public delegate void FlushEventDelegate(FlushEventArgs args); /// public delegate void PostFlushEventDelegate(PostFlushEventArgs args); /// public delegate void ShutDownEventDelegate(ShutDownEventArgs args); /// public delegate void PrepareForShutDownEventDelegate(PrepareForShutDownEventArgs args); /// public delegate void DesignChangeEventDelegate(); private static event FlushEventDelegate _flushEvent; private static event PostFlushEventDelegate _postFlushEvent; private static event ShutDownEventDelegate _shutDownEvent; private static event PrepareForShutDownEventDelegate _prepareForShutDownEvent; /// /// Occurs when elements related to frontend appearance have changed. F.e. css styling changed, or function's rendering changed. /// public static event DesignChangeEventDelegate OnDesignChange; /// /// Flush code MAY NOT do ANY kind of re-initialization. /// /// public static void SubscribeToFlushEvent(FlushEventDelegate eventDelegate) { _flushEvent += eventDelegate; } /// public static void SubscribeToPostFlushEvent(PostFlushEventDelegate eventDelegate) { _postFlushEvent += eventDelegate; } /// public static void UnsubscribeFromFlushEvent(FlushEventDelegate eventDelegate) { _flushEvent -= eventDelegate; } /// public static void FlushTheSystem() { FlushTheSystem(false); } internal static void FlushTheSystem(bool waitForHooksInitialization) { GlobalInitializerFacade.ReinitializeTheSystem( delegate() { FireFlushEvent(); // LoadDynamicTypesInformation(); FirePostFlushEvent(); }, waitForHooksInitialization); } private static void FireFlushEvent() { if (_flushEvent != null) { Log.LogVerbose(LogTitle, "----------========== Firing Flush Events ==========----------"); int startTime = Environment.TickCount; FlushEventDelegate flushEvent = _flushEvent; flushEvent(new FlushEventArgs()); int endTime = Environment.TickCount; Log.LogVerbose(LogTitle, string.Format("----------========== Done firing Flush Events ({0} ms ) ==========----------", endTime - startTime)); } } private static void FirePostFlushEvent() { if (_postFlushEvent != null) { Log.LogVerbose(LogTitle, "----------========== Firing Post Flush Events ==========----------"); int startTime = Environment.TickCount; PostFlushEventDelegate postFlushEvent = _postFlushEvent; postFlushEvent(new PostFlushEventArgs()); int endTime = Environment.TickCount; Log.LogVerbose(LogTitle, string.Format("----------========== Done firing Post Flush Events ({0} ms ) ==========----------", endTime - startTime)); } } /// public static void SubscribeToPrepareForShutDownEvent(PrepareForShutDownEventDelegate eventDelegate) { _prepareForShutDownEvent += eventDelegate; } /// public static void SubscribeToShutDownEvent(ShutDownEventDelegate eventDelegate) { _shutDownEvent += eventDelegate; } /// public static void UnsubscribeFromPrepareForShutDownEvent(PrepareForShutDownEventDelegate eventDelegate) { _prepareForShutDownEvent -= eventDelegate; } /// public static void UnsubscribeFromShutDownEvent(ShutDownEventDelegate eventDelegate) { _shutDownEvent -= eventDelegate; } /// public static void PrepareForShutDown() { if(_prepareForShutDownEvent != null) { _prepareForShutDownEvent(new PrepareForShutDownEventArgs()); } } /// public static void ShutDownTheSystem() { GlobalInitializerFacade.UninitializeTheSystem(FireShutDownEvent); } private static void FireShutDownEvent() { if (_shutDownEvent != null) { Log.LogVerbose(LogTitle, "----------========== Firing Shut Down Events ==========----------"); int startTime = Environment.TickCount; ShutDownEventDelegate shutDownEvent = _shutDownEvent; shutDownEvent(new ShutDownEventArgs()); int endTime = Environment.TickCount; Log.LogVerbose(LogTitle, string.Format("----------========== Done firing Shut Down Events ({0} ms ) ==========----------", endTime - startTime)); } } /// public static void FireDesignChangeEvent() { var handler = OnDesignChange; if (handler != null) { handler(); } } } } ================================================ FILE: Composite/C1Console/Events/IConsoleMessageQueueItem.cs ================================================ namespace Composite.C1Console.Events { /// /// A message that is send to C1 console client /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IConsoleMessageQueueItem { } } ================================================ FILE: Composite/C1Console/Events/IManagementConsoleMessageService.cs ================================================ using System; using Composite.C1Console.Actions; using Composite.Core.Logging; using Composite.C1Console.Security; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IManagementConsoleMessageService : IFlowControllerService { /// void CloseCurrentView(); /// void RefreshTreeSection(EntityToken entityToken); /// void ShowMessage(DialogType dialogType, string title, string message); /// void ShowGlobalMessage(DialogType dialogType, string title, string message); /// void ShowLogEntry(Type sender, Exception exception); /// void ShowLogEntry(Type sender, LogLevel logLevel, string message); /// bool HasView { get; } /// bool CloseCurrentViewRequested { get; } /// string CurrentConsoleId { get; } /// void RebootConsole(); /// void CollapseAndRefresh(); /// void LockSystem(); /// void BroadcastMessage(string name, string value); /// void SaveStatus(bool succeeded); /// void BindEntityTokenToView(string entityToken); /// void SelectElement(string entityToken); } } ================================================ FILE: Composite/C1Console/Events/LockSystemConsoleMessageQueueItem.cs ================================================ using System; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class LockSystemConsoleMessageQueueItem : IConsoleMessageQueueItem { } } ================================================ FILE: Composite/C1Console/Events/LogEntryMessageQueueItem.cs ================================================ using System; using Composite.Core.Logging; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class LogEntryMessageQueueItem : IConsoleMessageQueueItem { /// public Type Sender { get; set; } /// public LogLevel Level { get; set; } /// public string Message { get; set; } } } ================================================ FILE: Composite/C1Console/Events/ManagementConsoleMessageService.cs ================================================ using System; using System.Text; using Composite.Core.Configuration; using Composite.Core.Logging; using Composite.C1Console.Security; namespace Composite.C1Console.Events { internal sealed class ManagementConsoleMessageService : IManagementConsoleMessageService { private bool _closeCurrentViewRequested = false; public ManagementConsoleMessageService(string consoleId) { if (consoleId == null) throw new ArgumentNullException("consoleId"); this.ConsoleId = consoleId; } public ManagementConsoleMessageService(string consoleId, string viewId) { if (consoleId == null) throw new ArgumentNullException("consoleId"); this.ConsoleId = consoleId; this.ViewId = viewId; } private string ConsoleId { get; set; } private string ViewId { get; set; } public bool HasView { get { return (string.IsNullOrEmpty(this.ViewId) == false); } } public void CloseCurrentView() { if (string.IsNullOrEmpty(this.ViewId)) throw new InvalidOperationException("Can not close current view. No view ID has been associated with this message service"); if (_closeCurrentViewRequested == false) { ConsoleMessageQueueFacade.Enqueue(new CloseViewMessageQueueItem { ViewId = this.ViewId }, this.ConsoleId); } _closeCurrentViewRequested = true; } public void RefreshTreeSection(EntityToken entityToken) { if (entityToken == null) throw new ArgumentNullException("entityToken"); if (GlobalSettingsFacade.BroadcastConsoleElementChanges) { ConsoleMessageQueueFacade.Enqueue(new RefreshTreeMessageQueueItem { EntityToken = entityToken }, null); } else { ConsoleMessageQueueFacade.Enqueue(new RefreshTreeMessageQueueItem { EntityToken = entityToken }, this.ConsoleId); } } public void ShowLogEntry(Type sender, Exception exception) { StringBuilder messageBuilder = new StringBuilder(); Exception logException = exception; string indention = ""; while (logException != null) { messageBuilder.AppendLine(String.Format("{0}{1} threw an exception of type {2}", indention, logException.Source, logException.GetType())); messageBuilder.AppendLine(indention + logException.Message); if (logException.StackTrace != null) { messageBuilder.AppendLine(indention + logException.StackTrace.Replace("\n", "\n" + indention)); } indention += " "; logException = logException.InnerException; if (logException != null) messageBuilder.AppendLine(); } ShowLogEntry(sender, LogLevel.Fatal, messageBuilder.ToString()); } public void ShowLogEntry(Type sender, LogLevel logLevel, string message) { ConsoleMessageQueueFacade.Enqueue(new LogEntryMessageQueueItem { Sender = sender, Level = logLevel, Message = message }, this.ConsoleId); } public void ShowMessage(DialogType dialogType, string title, string message) { ConsoleMessageQueueFacade.Enqueue(new MessageBoxMessageQueueItem { DialogType = dialogType, Title = title, Message = message }, this.ConsoleId); } public void ShowGlobalMessage(DialogType dialogType, string title, string message) { ConsoleMessageQueueFacade.Enqueue(new MessageBoxMessageQueueItem { DialogType = dialogType, Title = title, Message = message }, null); } public bool CloseCurrentViewRequested { get { return _closeCurrentViewRequested; } } public string CurrentConsoleId { get { return this.ConsoleId; } } public void RebootConsole() { ConsoleMessageQueueFacade.Enqueue(new RebootConsoleMessageQueueItem(), this.ConsoleId); } public void CollapseAndRefresh() { ConsoleMessageQueueFacade.Enqueue(new CollapseAndRefreshConsoleMessageQueueItem(), this.ConsoleId); } public void LockSystem() { ConsoleMessageQueueFacade.Enqueue(new LockSystemConsoleMessageQueueItem(), this.ConsoleId); } public void BroadcastMessage(string name, string value) { ConsoleMessageQueueFacade.Enqueue(new BroadcastMessageQueueItem { Name = name, Value = value }, this.ConsoleId); } public void SaveStatus(bool succeeded) { ConsoleMessageQueueFacade.Enqueue(new SaveStatusConsoleMessageQueueItem { ViewId = ViewId, Succeeded = succeeded }, this.ConsoleId); } public void BindEntityTokenToView(string entityToken) { ConsoleMessageQueueFacade.Enqueue(new BindEntityTokenToViewQueueItem { ViewId = ViewId, EntityToken = entityToken }, this.ConsoleId); } public void SelectElement(string entityToken) { ConsoleMessageQueueFacade.Enqueue(new SelectElementQueueItem { EntityToken = entityToken }, this.ConsoleId); } } } ================================================ FILE: Composite/C1Console/Events/MessageBoxMessageQueueItem.cs ================================================ using System; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class MessageBoxMessageQueueItem : IConsoleMessageQueueItem { /// public string Title { get; set; } /// public string Message { get; set; } /// public DialogType DialogType { get; set; } } } ================================================ FILE: Composite/C1Console/Events/OpenExternalViewQueueItem.cs ================================================ using System; using System.Collections.Generic; using Composite.Core.ResourceSystem; using Composite.C1Console.Security; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class OpenExternalViewQueueItem : IConsoleMessageQueueItem { /// public OpenExternalViewQueueItem(EntityToken entityToken) { this.EntityToken = EntityTokenSerializer.Serialize(entityToken); } /// public string ViewId { get; set; } /// public string EntityToken { get; set; } /// public string Label { get; set; } /// public string ToolTip { get; set; } /// public ResourceHandle IconResourceHandle { get; set; } /// public string Url { get; set; } /// public string ViewType { get; set; } /// public Dictionary UrlPostArguments { get; set; } } } ================================================ FILE: Composite/C1Console/Events/OpenGenericViewQueueItem.cs ================================================ using System; using System.Collections.Generic; using Composite.Core.ResourceSystem; using Composite.C1Console.Security; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class OpenGenericViewQueueItem : IConsoleMessageQueueItem { /// public OpenGenericViewQueueItem(EntityToken entityToken) : this(entityToken, Guid.NewGuid().ToString()) { } /// public OpenGenericViewQueueItem(EntityToken entityToken, string viewId) { this.EntityToken = EntityTokenSerializer.Serialize(entityToken); this.ViewId = viewId; } /// public string ViewId { get; set; } /// public string EntityToken { get; set; } /// public string Label { get; set; } /// public string ToolTip { get; set; } /// public ResourceHandle IconResourceHandle { get; set; } /// public string Url { get; set; } /// public Dictionary UrlPostArguments { get; set; } } } ================================================ FILE: Composite/C1Console/Events/OpenHandledViewMessageQueueItem.cs ================================================ using Composite.Core.ResourceSystem; using System.Collections.Generic; using System; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class OpenHandledViewMessageQueueItem : IConsoleMessageQueueItem { /// public OpenHandledViewMessageQueueItem(string entityToken, string handle) { this.EntityToken = entityToken; this.Handle = handle; this.Arguments = new Dictionary(); } /// public OpenHandledViewMessageQueueItem(string entityToken, string handle, Dictionary arguments) { this.EntityToken = entityToken; this.Handle = handle; this.Arguments = arguments; } /// public string EntityToken { get; set; } /// public string Handle { get; set; } /// public Dictionary Arguments { get; set; } } } ================================================ FILE: Composite/C1Console/Events/OpenSlideViewQueueItem.cs ================================================ using System; using System.Collections.Generic; using Composite.Core.ResourceSystem; using Composite.C1Console.Security; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class OpenSlideViewQueueItem : IConsoleMessageQueueItem { /// public string ViewId { get; set; } /// public string EntityToken { get; set; } /// public string Url { get; set; } } } ================================================ FILE: Composite/C1Console/Events/OpenViewMessageQueueItem.cs ================================================ using Composite.Core.ResourceSystem; using System; using System.Collections.Generic; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class OpenViewMessageQueueItem : IConsoleMessageQueueItem { /// public OpenViewMessageQueueItem() { this.FlowHandle = ""; } /// public string ViewId { get; set; } /// public string EntityToken { get; set; } /// public string FlowHandle { get; set; } /// public string Url { get; set; } /// public Dictionary UrlPostArguments { get; set; } /// public ViewType ViewType { get; set; } /// public string Label { get; set; } /// public string ToolTip { get; set; } /// public ResourceHandle IconResourceHandle { get; set; } } } ================================================ FILE: Composite/C1Console/Events/RebootConsoleMessageQueueItem.cs ================================================ using System; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class RebootConsoleMessageQueueItem : IConsoleMessageQueueItem { } } ================================================ FILE: Composite/C1Console/Events/RefreshTreeMessageQueueItem.cs ================================================ using Composite.C1Console.Security; using Composite.Core.Serialization; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class RefreshTreeMessageQueueItemSerializerHandler : ISerializerHandler { /// public string Serialize(object objectToSerialize) { return EntityTokenSerializer.Serialize(((RefreshTreeMessageQueueItem)objectToSerialize).EntityToken); } /// public object Deserialize(string serializedObject) { RefreshTreeMessageQueueItem result = new RefreshTreeMessageQueueItem(); result.EntityToken = EntityTokenSerializer.Deserialize(serializedObject); return result; } } /// /// Refreshed children of the elements with the specified entity token /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SerializerHandler(typeof(RefreshTreeMessageQueueItemSerializerHandler))] public sealed class RefreshTreeMessageQueueItem : IConsoleMessageQueueItem { /// public EntityToken EntityToken { get; set; } /// public override string ToString() { return this.EntityToken.ToString(); } } } ================================================ FILE: Composite/C1Console/Events/SaveStatusConsoleMessageQueueItem.cs ================================================ using System; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class SaveStatusConsoleMessageQueueItem : IConsoleMessageQueueItem { /// public string ViewId { get; set; } /// public bool Succeeded { get; set; } } } ================================================ FILE: Composite/C1Console/Events/SelectElementQueueItem.cs ================================================ using System; namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class SelectElementQueueItem : IConsoleMessageQueueItem { /// public string EntityToken { get; set; } /// public string PerspectiveElementKey { get; set; } } } ================================================ FILE: Composite/C1Console/Events/ViewType.cs ================================================ namespace Composite.C1Console.Events { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum ViewType { /// Main = 0, /// ModalDialog = 1, /// RightTop = 2, /// RightBottom = 3, /// BottomLeft = 4, /// BottomRight = 5, /// External = 6 } } ================================================ FILE: Composite/C1Console/Forms/BindablePropertyAttribute.cs ================================================ using System; namespace Composite.C1Console.Forms { /// /// Defines that a property supports data binding. This attribute should only be assigned to updateable fields. /// /// [AttributeUsage(AttributeTargets.Property,AllowMultiple=false,Inherited=true)] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class BindablePropertyAttribute : Attribute { } } ================================================ FILE: Composite/C1Console/Forms/ControlValuePropertyAttribute.cs ================================================ using System; namespace Composite.C1Console.Forms { /// /// Defines the default property of a UiControl that "inner values" will be assigned to. /// [AttributeUsage(AttributeTargets.Class,AllowMultiple=false,Inherited=true)] internal sealed class ControlValuePropertyAttribute : Attribute { public ControlValuePropertyAttribute(string propertyName) { _propertyName = propertyName; } private readonly string _propertyName; public string PropertyName { get { return _propertyName; } } } } ================================================ FILE: Composite/C1Console/Forms/CoreFunctions/BooleanCheckFunctionFactory.cs ================================================ using Composite.C1Console.Forms.Plugins.FunctionFactory; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.CoreFunctions { internal sealed class BooleanCheckFunction : IFormFunction { public BooleanCheckFunction() { } [FormsProperty()] public object WhenTrue { get; set; } [FormsProperty()] public object WhenFalse { get; set; } [RequiredValue()] [FormsProperty()] public bool CheckValue { get; set; } public object Execute() { if (this.CheckValue) { return this.WhenTrue; } else { return this.WhenFalse; } } } [ConfigurationElementType(typeof(BooleanCheckFunctionFactoryData))] internal sealed class BooleanCheckFunctionFactory : IFormFunctionFactory { public IFormFunction CreateFunction() { return new BooleanCheckFunction(); } } [Assembler(typeof(NonConfigurableFunctionFactoryAssembler))] internal sealed class BooleanCheckFunctionFactoryData : FunctionFactoryData { } } ================================================ FILE: Composite/C1Console/Forms/CoreFunctions/CompositeFunctionCall.cs ================================================ using Composite.C1Console.Forms.Plugins.FunctionFactory; using Composite.Functions; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.CoreFunctions { [ControlValueProperty("Parameters")] internal sealed class CompositeFunctionCall : IFormFunction { public CompositeFunctionCall() { } [FormsProperty()] [RequiredValue()] public string Name { get; set; } public object Execute() { return FunctionFacade.Execute(FunctionFacade.GetFunction(this.Name)); } } [ConfigurationElementType(typeof(CompositeFunctionCallFunctionFactoryData))] internal sealed class CompositeFunctionCallFunctionFactory : IFormFunctionFactory { public IFormFunction CreateFunction() { return new CompositeFunctionCall(); } } [Assembler(typeof(NonConfigurableFunctionFactoryAssembler))] internal sealed class CompositeFunctionCallFunctionFactoryData : FunctionFactoryData { } } ================================================ FILE: Composite/C1Console/Forms/CoreFunctions/NamedValueFunctionFactory.cs ================================================ using System.Collections; using Composite.C1Console.Forms.Plugins.FunctionFactory; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.CoreFunctions { [ControlValueProperty("Value")] internal sealed class NamedValue : IFormFunction { [BindableProperty()] [FormsProperty()] public object Value { get; set; } [RequiredValue()] [FormsProperty()] public string Name { get; set; } public object Execute() { return new DictionaryEntry(this.Name, this.Value); } } [ConfigurationElementType(typeof(NamedValueFunctionFactoryData))] internal sealed class NamedValueFunctionFactory : IFormFunctionFactory { public IFormFunction CreateFunction() { return new NamedValue(); } } [Assembler(typeof(NonConfigurableFunctionFactoryAssembler))] internal sealed class NamedValueFunctionFactoryData : FunctionFactoryData { } } ================================================ FILE: Composite/C1Console/Forms/CoreFunctions/NullCheckFunctionFactory.cs ================================================ using Composite.C1Console.Forms.Plugins.FunctionFactory; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.CoreFunctions { internal sealed class NullCheck : IFormFunction { public NullCheck() { } [FormsProperty()] public object WhenNull { get; set; } [FormsProperty()] public object WhenNotNull { get; set; } [RequiredValue()] [FormsProperty()] public object CheckValue { get; set; } public object Execute() { if (this.CheckValue == null) { return this.WhenNull; } else { return this.WhenNotNull; } } } [ConfigurationElementType(typeof(NullCheckFunctionFactoryData))] internal sealed class NullCheckFunctionFactory : IFormFunctionFactory { public IFormFunction CreateFunction() { return new NullCheck(); } } [Assembler(typeof(NonConfigurableFunctionFactoryAssembler))] internal sealed class NullCheckFunctionFactoryData : FunctionFactoryData { } } ================================================ FILE: Composite/C1Console/Forms/CoreFunctions/ReplicatorFunctionFactory.cs ================================================ using Composite.C1Console.Forms.Plugins.FunctionFactory; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.CoreFunctions { [ControlValueProperty("Value")] internal sealed class Replicator : IFormFunction { [BindableProperty()] [FormsProperty()] public object Value { get; set; } public object Execute() { return this.Value; } } [ConfigurationElementType(typeof(ReplicatorFunctionFactoryData))] internal sealed class ReplicatorFunctionFactory : IFormFunctionFactory { public IFormFunction CreateFunction() { return new Replicator(); } } [Assembler(typeof(NonConfigurableFunctionFactoryAssembler))] internal sealed class ReplicatorFunctionFactoryData : FunctionFactoryData { } } ================================================ FILE: Composite/C1Console/Forms/CoreFunctions/StaticMethodCallFunctionFactory.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.C1Console.Forms.Plugins.FunctionFactory; using Composite.Core.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.CoreFunctions { [ControlValueProperty("Parameters")] internal sealed class StaticMethodCall : IFormFunction { public StaticMethodCall() { this.Parameters = null; } [FormsProperty()] public Type Type { get; set; } [FormsProperty()] public string Method { get; set; } [FormsProperty()] public Object Parameters { get; set; } public object Execute() { MethodInfo methodToCall; List preparedParameters = new List(); object result; try { methodToCall = this.Type.GetMethod(this.Method, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); if (methodToCall == null) throw new InvalidOperationException("No such method found"); } catch (Exception ex) { throw new InvalidOperationException(string.Format("Failed to locate a static method named '{0}' on the type '{1}'", this.Method, this.Type.FullName), ex); } ParameterInfo[] parameterInfos = methodToCall.GetParameters(); if (parameterInfos != null && parameterInfos.Length > 0) { if (this.Parameters == null) { throw new InvalidOperationException(string.Format("Missing parameters for static method named '{0}' on the type '{1}'.", this.Method, this.Type.FullName)); } if (parameterInfos.Length > 1) { throw new InvalidOperationException(string.Format("Static method named '{0}' on the type '{1}' take more than one parameter which is not supported.", this.Method, this.Type.FullName)); } var parameterInfo = parameterInfos.First(); object currentSuppliedParameter = this.Parameters; if (currentSuppliedParameter == null) { preparedParameters.Add(null); } else { if (currentSuppliedParameter.GetType() == parameterInfo.ParameterType) { preparedParameters.Add(currentSuppliedParameter); } else { var converted = ValueTypeConverter.Convert(currentSuppliedParameter, parameterInfo.ParameterType); preparedParameters.Add(converted); } } } else { if (this.Parameters != null) { throw new InvalidOperationException(string.Format("Parameters were supplied for static method named '{0}' on the type '{1}'. This method takes no parameters", this.Method, this.Type.FullName)); } } try { result = methodToCall.Invoke(null, preparedParameters.ToArray()); } catch (Exception ex) { throw new InvalidOperationException(string.Format("Failed while executing static method '{0}' on the type '{1}'.", this.Method, this.Type.FullName), ex); } return result; } } [ConfigurationElementType(typeof(StaticMethodCallFunctionFactoryData))] internal sealed class StaticMethodCallFunctionFactory : IFormFunctionFactory { public IFormFunction CreateFunction() { return new StaticMethodCall(); } } [Assembler(typeof(NonConfigurableFunctionFactoryAssembler))] internal sealed class StaticMethodCallFunctionFactoryData : FunctionFactoryData { } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/BaseSelectorUiControl.cs ================================================ using System; using System.Collections; using System.ComponentModel; using System.Globalization; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { internal abstract class BaseSelectorUiControl : UiControl { protected BaseSelectorUiControl() { this.OptionsKeyField = "."; this.OptionsLabelField = "."; this.Required = true; } [RequiredValue] [FormsProperty] public IEnumerable Options { get; set; } [FormsProperty] public string OptionsKeyField { get; set; } [FormsProperty] public string OptionsLabelField { get; set; } [FormsProperty] public SelectorBindingType BindingType { get; set; } [FormsProperty] public bool Required { get; set; } [FormsProperty] public bool ReadOnly { get; set; } [BindableProperty] [FormsProperty] public EventHandler SelectedIndexChangedEventHandler { get; set; } } [TypeConverter(typeof(SelectorBindingTypeConverter))] internal enum SelectorBindingType { BindToObject, BindToKeyFieldValue } internal class SelectorBindingTypeConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string val = value as string; switch (val.ToLowerInvariant()) { case "bindtoobject": return SelectorBindingType.BindToObject; case "bindtokeyfieldvalue": return SelectorBindingType.BindToKeyFieldValue; default: throw new FormatException($"{value} is not a valid Selector BindingType value - use {nameof(SelectorBindingType.BindToObject)} or {nameof(SelectorBindingType.BindToKeyFieldValue)}"); } } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/BoolSelectorUiControl.cs ================================================ using System; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { [ControlValueProperty("IsTrue")] internal abstract class BoolSelectorUiControl : UiControl { [BindableProperty] [FormsProperty] public bool IsTrue { get; set; } [FormsProperty] public string TrueLabel { get; set; } [FormsProperty] public string FalseLabel { get; set; } [BindableProperty] [FormsProperty] public EventHandler SelectionChangedEventHandler { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/ButtonUiControl.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Forms.Foundation; using System; namespace Composite.C1Console.Forms.CoreUiControls { [ControlValueProperty("Label")] internal abstract class ButtonUiControl : UiControl { private EventHandler _eventHandler; [FormsProperty()] public EventHandler ClickEventHandler { get { return _eventHandler; } set { _eventHandler = value; } } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/ButtonUiControlFactoryData.cs ================================================ using System.Configuration; using Composite.C1Console.Forms.Plugins.UiControlFactory; namespace Composite.C1Console.Forms.CoreUiControls { internal class ButtonUiControlFactoryData : UiControlFactoryData { } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/CheckBoxUiControl.cs ================================================ using System; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { [ControlValueProperty(nameof(Checked))] internal abstract class CheckBoxUiControl : UiControl { [BindableProperty] [FormsProperty] public bool Checked { get; set; } [FormsProperty] public string ItemLabel { get; set; } [BindableProperty] [FormsProperty] public EventHandler CheckedChangedEventHandler { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/CheckBoxUiControlFactoryData.cs ================================================ using System; using System.Configuration; using Composite.C1Console.Forms.Plugins.UiControlFactory; namespace Composite.C1Console.Forms.CoreUiControls { internal class CheckBoxUiControlFactoryData : UiControlFactoryData { } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/ContainerUiControl.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { /// /// Base class for UiControl containers. /// [ControlValueProperty("UiControls")] internal abstract class ContainerUiControlBase : UiControl, IContainerUiControl { public ContainerUiControlBase() { this.UiControls = new List(); } /// /// The list of contained UiControls. /// [FormsProperty()] public List UiControls { get; private set; } public abstract void InitializeLazyBindedControls(); } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/ContainerUiControlFactoryData.cs ================================================ using System.Configuration; using Composite.C1Console.Forms.Plugins.UiControlFactory; namespace Composite.C1Console.Forms.CoreUiControls { internal class ContainerUiControlFactoryData: UiControlFactoryData { } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/DataReferenceSelectorUiControl.cs ================================================ using System.ComponentModel; using Composite.Data; using Composite.C1Console.Forms.Foundation; using System; namespace Composite.C1Console.Forms.CoreUiControls { [DefaultBindingProperty("Selected")] internal class DataReferenceSelectorUiControl : UiControl { private object _selected = null; [BindableProperty()] [FormsProperty()] public object Selected { get { if (_selected == null) return null; if (_selected is IDataReference) return _selected; if (this.DataType==null) throw new InvalidOperationException("'DataType' property have on been initialized. Unable to convert to IDataReference"); return DataReferenceFacade.BuildDataReference(this.DataType, _selected); } set { _selected = value; } } [RequiredValue()] [FormsProperty()] public Type DataType { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/DataReferenceTreeSelectorUiControl.cs ================================================ using System; using System.ComponentModel; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { [DefaultBindingProperty("Selected")] internal class DataReferenceTreeSelectorUiControl : UiControl { public DataReferenceTreeSelectorUiControl() { Selected = null; } [BindableProperty(), FormsProperty()] public string Selected { get; set; } [FormsProperty()] public string Handle { get; set; } [FormsProperty()] public string RootEntityToken { get; set; } [FormsProperty()] public string SearchToken { get; set; } [FormsProperty()] public Type DataType { get; set; } [FormsProperty()] public bool NullValueAllowed { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/DateSelectorUiControl.cs ================================================ using System; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { [ControlValueProperty("Date")] internal abstract class DateTimeSelectorUiControl : UiControl { [BindableProperty] [FormsProperty] public DateTime? Date { get; set; } [FormsProperty] public bool ReadOnly { get; set; } [FormsProperty] public bool Required { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/DebugUiControl.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { [ControlValueProperty("UiControl")] internal abstract class DebugUiControl : UiControl { private IUiControl _uiControl; private string _tagName; private List _bindings = new List(); private string _sourceElementXPath; public IUiControl UiControl { get { return _uiControl; } set { _uiControl = value; } } public string TagName { get { return _tagName; } set { _tagName = value; } } [FormsProperty()] public override string Label { get { return _uiControl.Label; } set { throw new InvalidOperationException( "Debug.Label may not be assigned" ); } } public List Bindings { get { return _bindings; } } public string SourceElementXPath { get { return _sourceElementXPath; } set { _sourceElementXPath = value; } } internal class BindingInformation { private string _bindingObjectName; private Type _bindingObjectType; private string _bindingPropertyName; public BindingInformation(string bindingObjectName, Type bindingObjectType, string bindingPropertyName) { _bindingObjectName = bindingObjectName; _bindingObjectType = bindingObjectType; _bindingPropertyName = bindingPropertyName; } public string BindingObjectName { get { return _bindingObjectName; } } public Type BindingObjectType { get { return _bindingObjectType; } } public string BindingPropertyName { get { return _bindingPropertyName; } } } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/DebugUiControlFactoryData.cs ================================================ using Composite.C1Console.Forms.Plugins.UiControlFactory; namespace Composite.C1Console.Forms.CoreUiControls { internal class DebugUiControlFactoryData : UiControlFactoryData { } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/DoubleSelectorUiControl.cs ================================================ using System; namespace Composite.C1Console.Forms.CoreUiControls { internal class SelectorUiControl : BaseSelectorUiControl { [BindableProperty()] [FormsProperty()] public object Selected { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/EnumSelectorUiControl.cs ================================================ using System; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { [ControlValueProperty("Selected")] internal abstract class EnumSelectorUiControl : UiControl { private string _selected; [BindableProperty()] [FormsProperty()] public string Selected { get { return _selected; } set { _selected = Enum.Parse(EnumType, value).ToString(); } } [RequiredValue()] [FormsProperty()] public Type EnumType { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/FileUploadUiControl.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Text; using Composite.C1Console.Forms.Foundation; using Composite.Core.Serialization; namespace Composite.C1Console.Forms.CoreUiControls { /// /// [ControlValueProperty("UploadedFile")] internal abstract class FileUploadUiControl : UiControl { /// /// [RequiredValue()] [BindableProperty] [FormsProperty()] public UploadedFile UploadedFile { get; set; } } internal sealed class UploadedFileSerializerHandler : ISerializerHandler { public string Serialize(object objectToSerialize) { if (objectToSerialize == null) throw new ArgumentNullException("objectToSerialize"); StringBuilder sb = new StringBuilder(); UploadedFile uploadedFile = (UploadedFile)objectToSerialize; StringConversionServices.SerializeKeyValuePair(sb, "HasFile", uploadedFile.HasFile); if (uploadedFile.FileName != null) { StringConversionServices.SerializeKeyValuePair(sb, "FileName", uploadedFile.FileName); } if (uploadedFile.ContentType != null) { StringConversionServices.SerializeKeyValuePair(sb, "ContentType", uploadedFile.ContentType); } StringConversionServices.SerializeKeyValuePair(sb, "ContentLength", uploadedFile.ContentLength); if (uploadedFile.FileStream != null) { long position = uploadedFile.FileStream.Position; uploadedFile.FileStream.Seek(0, SeekOrigin.Begin); byte[] buffer = new byte[uploadedFile.FileStream.Length]; uploadedFile.FileStream.Read(buffer, 0, (int)uploadedFile.FileStream.Length); StringConversionServices.SerializeKeyValueArrayPair(sb, "FileStream", buffer); uploadedFile.FileStream.Seek(position, SeekOrigin.Begin); } return sb.ToString(); } public object Deserialize(string serializedObject) { if (serializedObject == null) throw new ArgumentNullException("serializedObject"); Dictionary dic = StringConversionServices.ParseKeyValueCollection(serializedObject); UploadedFile uploadedFile = new UploadedFile(); if (dic.ContainsKey("HasFile") == false) throw new InvalidOperationException("Not correct serialized format"); uploadedFile.HasFile = StringConversionServices.DeserializeValueBool(dic["HasFile"]); if (dic.ContainsKey("FileName")) { uploadedFile.FileName = StringConversionServices.DeserializeValueString(dic["FileName"]); } if (dic.ContainsKey("ContentType")) { uploadedFile.ContentType = StringConversionServices.DeserializeValueString(dic["ContentType"]); } if (dic.ContainsKey("ContentLength") == false) throw new InvalidOperationException("Not correct serialized format"); uploadedFile.ContentLength = StringConversionServices.DeserializeValueInt(dic["ContentLength"]); if (dic.ContainsKey("FileStream")) { byte[] bytes = StringConversionServices.DeserializeValueArray(dic["FileStream"]); uploadedFile.FileStream = new MemoryStream(bytes); } return uploadedFile; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SerializerHandler(typeof(UploadedFileSerializerHandler))] public sealed class UploadedFile { /// public UploadedFile() { this.HasFile = false; } /// public bool HasFile { get; set; } /// public string FileName { get; set; } /// public string ContentType { get; set; } /// public int ContentLength { get; set; } /// public Stream FileStream { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/FontIconSelectorUiControl.cs ================================================ using System; using System.Globalization; using System.ComponentModel; using Composite.C1Console.Forms.Foundation; using System.Collections.Generic; namespace Composite.C1Console.Forms.CoreUiControls { [ControlValueProperty("Text")] internal abstract class FontIconSelectorUiControl : UiControl { public FontIconSelectorUiControl() { this.SelectedClassName = ""; this.Required = false; } [BindableProperty] [FormsProperty] public string SelectedClassName { get; set; } [FormsProperty] [RequiredValue] public object ClassNameOptions { get; set; } [FormsProperty] [RequiredValue] public string StylesheetPath { get; set; } [FormsProperty] public string ClassNamePrefix { get; set; } [FormsProperty] public bool Required { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/FunctionCallDesignerUiControl.cs ================================================ using System; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { internal abstract class FunctionCallsDesignerUiControl : UiControl { /// /// [RequiredValue] [FormsProperty] public abstract string SessionStateProvider { get; set; } /// /// [RequiredValue] [FormsProperty] public abstract Guid SessionStateId { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/FunctionParameterDesignerUiControl.cs ================================================ using System; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { internal abstract class FunctionParameterDesignerUiControl : UiControl { /// /// [RequiredValue] [FormsProperty] public abstract string SessionStateProvider { get; set; } /// /// [RequiredValue] [FormsProperty] public abstract Guid SessionStateId { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/HeadingUiControl.cs ================================================ using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { [ControlValueProperty("Title")] internal abstract class HeadingUiControl : UiControl { [FormsProperty()] public string Title { get; set; } [FormsProperty()] public string Description { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/HierarchicalSelectorUiControl.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { [ControlValueProperty("SelectedKeys")] internal abstract class HierarchicalSelectorUiControl : UiControl { internal HierarchicalSelectorUiControl() { this.AutoSelectParents = true; } [BindableProperty] [FormsProperty] public IEnumerable SelectedKeys { get; set; } [FormsProperty] public IEnumerable TreeNodes { get; set; } [FormsProperty] public bool AutoSelectChildren { get; set; } [FormsProperty] public bool AutoSelectParents { get; set; } [FormsProperty] public bool Required { get; set; } } /// [Serializable] public sealed class SelectionTreeNode { /// public object Key { get; set; } /// public string Label { get; set; } /// /// Determines whether a tree element should feature a checkbox. /// public bool Selectable { get; set; } /// /// Determines whether the tree element's checkbox is readonly. /// public bool Readonly { get; set; } /// public string Icon { get; set; } /// public IEnumerable Children { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/HierarchicalSelectorUiControlFactoryData.cs ================================================ using Composite.C1Console.Forms.Plugins.UiControlFactory; namespace Composite.C1Console.Forms.CoreUiControls { internal class HierarchicalSelectorUiControlFactoryData : UiControlFactoryData { } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/HtmlBlobUiControl.cs ================================================ using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { [ControlValueProperty("Html")] internal abstract class HtmlBlobUiControl : UiControl { private string _html = ""; [FormsProperty()] public string Html { get { return _html; } set { _html = value; } } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/IContainerUiControl.cs ================================================ using System; using System.Collections.Generic; namespace Composite.C1Console.Forms.CoreUiControls { internal interface IContainerUiControl : IUiControl { [FormsProperty()] List UiControls { get; } void InitializeLazyBindedControls(); } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/ITabbedContainerUiControl.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { /// /// Base class for UiControl tabbed containers. /// internal interface ITabbedContainerUiControl : IContainerUiControl { /// /// Zero-based index of pre selected tab. /// [FormsProperty()] int PreSelectedIndex { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/InfoTableUiControl.cs ================================================ using System; using System.Globalization; using System.ComponentModel; using Composite.C1Console.Forms.Foundation; using System.Collections.Generic; namespace Composite.C1Console.Forms.CoreUiControls { [ControlValueProperty("Rows")] internal abstract class InfoTableUiControl : UiControl { [FormsProperty()] public List Headers { get; set; } [FormsProperty()] public List> Rows { get; set; } [FormsProperty()] public string Caption { get; set; } [FormsProperty()] public bool Border { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/MultiContentXhtmlEditorUiControl.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { internal abstract class MultiContentXhtmlEditorUiControl : UiControl { [FormsProperty()] public Dictionary PlaceholderDefinitions { get; set; } [FormsProperty()] public Dictionary PlaceholderContainerClasses { get; set; } [FormsProperty()] public string DefaultPlaceholderId { get; set; } [FormsProperty()] [BindableProperty()] public Dictionary NamedXhtmlFragments { get; set; } [FormsProperty()] public string ClassConfigurationName { get; set; } [FormsProperty()] public IEnumerable EmbedableFieldsTypes { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/MultiSelectorUiControl.cs ================================================ using System.Collections; namespace Composite.C1Console.Forms.CoreUiControls { internal class MultiSelectorUiControl : BaseSelectorUiControl { public MultiSelectorUiControl() : base() { this.Required = false; } [BindableProperty()] [FormsProperty()] public IEnumerable Selected { get; set; } [BindableProperty()] [FormsProperty()] public string SelectedAsString { get; set; } [FormsProperty()] public bool CompactMode { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/PageReferenceSelectorUiControl.cs ================================================ using System.ComponentModel; using Composite.Data; using Composite.C1Console.Forms.Foundation; using System; using Composite.Data.Types; namespace Composite.C1Console.Forms.CoreUiControls { [DefaultBindingProperty("Selected")] internal class PageReferenceSelectorUiControl : UiControl { private DataReference _selected = null; [BindableProperty()] [FormsProperty()] public DataReference Selected { get { return _selected; } set { _selected = value; } } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/QueryCallDefinitionsEditorUiControl.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { internal class QueryCallDefinitionsEditorUiControl : UiControl { /// /// List of "Local name" and "Query Id" elements /// [BindableProperty()] [FormsProperty()] public IEnumerable> Queries { get; set; } /// /// Lookup where "Local name" is key and value is a key value pair /// [BindableProperty()] [FormsProperty()] public ILookup> Parameters { get; set; } [BindableProperty()] [FormsProperty()] public string UserProvidedPreviewXml { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/SaveButtonUiControl.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Forms.Foundation; using System; namespace Composite.C1Console.Forms.CoreUiControls { [ControlValueProperty("Label")] internal abstract class SaveButtonUiControl : UiControl { private EventHandler _saveEventHandler; private EventHandler _saveAndPublishEventHandler; [FormsProperty()] public EventHandler SaveEventHandler { get { return _saveEventHandler; } set { _saveEventHandler = value; } } [FormsProperty()] public EventHandler SaveAndPublishEventHandler { get { return _saveAndPublishEventHandler; } set { _saveAndPublishEventHandler = value; } } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/SelectorUiControl.cs ================================================ using System; namespace Composite.C1Console.Forms.CoreUiControls { internal class DoubleSelectorUiControl : BaseSelectorUiControl { [BindableProperty()] [FormsProperty()] public object FirstKey { get; set; } [BindableProperty()] [FormsProperty()] public object SecondKey { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/SelectorUiControlFactoryData.cs ================================================ using System; using System.Configuration; using Composite.C1Console.Forms.Plugins.UiControlFactory; namespace Composite.C1Console.Forms.CoreUiControls { internal class SelectorUiControlFactoryData : UiControlFactoryData { private const string _bindingTypePropertyName = "BindingType"; [ConfigurationProperty(_bindingTypePropertyName, DefaultValue=SelectorBindingType.BindToObject, IsRequired=true)] [FormsProperty()] public SelectorBindingType BindingType { get { return (SelectorBindingType)base[_bindingTypePropertyName]; } set { base[_bindingTypePropertyName] = value; } } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/SvgIconSelectorUiControl.cs ================================================ using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { [ControlValueProperty("Text")] internal abstract class SvgIconSelectorUiControl : UiControl { public SvgIconSelectorUiControl() { this.Selected = ""; this.Required = false; } [BindableProperty] [FormsProperty] public string Selected { get; set; } [FormsProperty] public string SvgSpritePath { get; set; } [FormsProperty] public bool Required { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/TextEditorUiControl.cs ================================================ using System; using System.Globalization; using System.ComponentModel; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { [ControlValueProperty("Text")] internal abstract class TextEditorUiControl : UiControl { public TextEditorUiControl() { this.Text = ""; this.MimeType = "text/plain"; } [BindableProperty()] [FormsProperty()] public string Text { get; set; } [FormsProperty()] public string MimeType { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/TextInputUiControl.cs ================================================ using System; using System.Globalization; using System.ComponentModel; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum TextBoxType { /// String = 0, /// Integer = 1, /// Decimal = 2, /// Password = 3, /// ProgrammingIdentifier = 4, /// ProgrammingNamespace = 5, /// ReadOnly = 6, /// Guid = 7 } [ControlValueProperty("Text")] internal abstract class TextInputUiControl : UiControl { public TextInputUiControl() { this.Text = ""; this.Type = TextBoxType.String; this.Required = false; this.SpellCheck = true; } [BindableProperty] [FormsProperty] public string Text { get; set; } [FormsProperty] public TextBoxType Type { get; set; } [FormsProperty] public bool Required { get; set; } [FormsProperty] public bool SpellCheck { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/TextUiControl.cs ================================================ using System; using System.Globalization; using System.ComponentModel; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { [ControlValueProperty("Text")] internal abstract class TextUiControl : UiControl { private string _text = ""; [FormsProperty()] public string Text { get { return _text; } set { _text = value; } } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/ToolbarButtonUiControl.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Composite.C1Console.Forms.CoreUiControls { internal abstract class ToolbarButtonUiControl : ButtonUiControl { public ToolbarButtonUiControl() { this.IsDisabled = false; this.SaveBehaviour = false; } [FormsProperty()] public string IconHandle { get; set; } [FormsProperty()] public string DisabledIconHandle { get; set; } [FormsProperty()] public bool IsDisabled { get; set; } [FormsProperty()] public string LaunchUrl { get; set; } [FormsProperty()] public bool SaveBehaviour { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/ToolbarButtonUiControlFactoryData.cs ================================================ using Composite.C1Console.Forms.Plugins.UiControlFactory; namespace Composite.C1Console.Forms.CoreUiControls { internal class ToolbarButtonUiControlFactoryData : UiControlFactoryData { } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/TreeSelectorUiControl.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { [ControlValueProperty("SelectedKeys")] internal abstract class TreeSelectorUiControl : UiControl { [BindableProperty] [FormsProperty] public string SelectedKey { get; set; } [FormsProperty] public string ElementProvider { get; set; } [FormsProperty] public string SelectableElementPropertyName { get; set; } [FormsProperty] public string SelectableElementPropertyValue { get; set; } [FormsProperty] public string SelectableElementReturnValue { get; set; } [FormsProperty] public string SerializedSearchToken { get; set; } [FormsProperty] public bool Required { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/TypeFieldDesignerUiControl.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Forms.Foundation; using Composite.Data.DynamicTypes; namespace Composite.C1Console.Forms.CoreUiControls { /// /// Provides editing functionality for DataFieldDescriptor elements /// internal abstract class TypeFieldDesignerUiControl : UiControl { /// /// [RequiredValue] [BindableProperty] [FormsProperty] public IEnumerable Fields { get; set; } /// /// [RequiredValue] [BindableProperty] [FormsProperty] public string LabelFieldName { get; set; } /// /// When true, the type selector for a key field will be disabled. /// [BindableProperty] [FormsProperty] public bool KeyFieldReadOnly { get; set; } [BindableProperty] [FormsProperty] public string KeyFieldName { get; set; } [FormsProperty] public bool IsSearchable { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/TypeSelectorUiControl.cs ================================================ using Composite.C1Console.Forms.Foundation; using System; using System.Collections.Generic; using Composite.Core.Types; using System.ComponentModel; using System.Globalization; namespace Composite.C1Console.Forms.CoreUiControls { [Flags] [TypeConverter(typeof(UiControlTypeSelectorModeConverter))] internal enum UiControlTypeSelectorMode { // Composite selector types /// /// Include interfaces in the result. /// InterfaceTypes = 0x01, /// /// Include concrete types in the result. /// ConcreteTypes = 0x02, /// /// Include primitives in the result. /// PrimitiveTypes = 0x04, } internal class UiControlTypeSelectorModeConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string val = value as string; val = val.ToLowerInvariant(); string[] options = val.Split('|'); UiControlTypeSelectorMode mode = new UiControlTypeSelectorMode(); foreach (string opt in options) { string option = opt.Trim(); if (option == TypeIncludes.ConcreteTypes.ToString().ToLowerInvariant()) { mode = mode | UiControlTypeSelectorMode.ConcreteTypes; } else if (option == TypeIncludes.InterfaceTypes.ToString().ToLowerInvariant()) { mode = mode | UiControlTypeSelectorMode.InterfaceTypes; } else if (option == TypeIncludes.PrimitiveTypes.ToString().ToLowerInvariant()) { mode = mode | UiControlTypeSelectorMode.PrimitiveTypes; } else { throw new FormatException(String.Format("{0} is not a valid TextSelector Mode value - use ConcreteTypes, InterfaceTypes, PrimitiveTypes", value)); } } return mode; } } [ControlValueProperty("SelectedType")] internal abstract class TypeSelectorUiControl : UiControl { [BindableProperty()] [FormsProperty()] public Type SelectedType { get; set; } [FormsProperty()] public IEnumerable TypeOptions { get; set; } [FormsProperty()] public Type AssignableTo { get; set; } [FormsProperty()] public UiControlTypeSelectorMode Mode { get; set; } private static bool IsSet(UiControlTypeSelectorMode flags, UiControlTypeSelectorMode compareFlag) { return ((flags & compareFlag) == compareFlag); } private IEnumerable EnumerateWithCompositeSelector() { TypeIncludes includes = new TypeIncludes(); if (IsSet(Mode, UiControlTypeSelectorMode.ConcreteTypes)) { includes = TypeIncludes.ConcreteTypes; } if (IsSet(Mode, UiControlTypeSelectorMode.InterfaceTypes)) { includes = includes | TypeIncludes.InterfaceTypes; } if (IsSet(Mode, UiControlTypeSelectorMode.PrimitiveTypes)) { includes = includes | TypeIncludes.PrimitiveTypes; } return TypeLocator.FindTypes(includes, this.AssignableTo); } protected IEnumerable GetTypeOptions() { if (this.AssignableTo != null && this.TypeOptions != null) throw new InvalidOperationException("Both TypeOptions and AssignableTo has been set. Only one may be set."); if (this.TypeOptions != null) return this.TypeOptions; if (this.AssignableTo == null) { throw new ArgumentNullException("AssignableTo"); } return EnumerateWithCompositeSelector(); } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/TypeSelectorUiControlFactoryData.cs ================================================ using System; using System.Configuration; using Composite.C1Console.Forms.Plugins.UiControlFactory; namespace Composite.C1Console.Forms.CoreUiControls { internal class TypeSelectorUiControlFactoryData : UiControlFactoryData { } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/XhtmlEditorUiControl.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { [ControlValueProperty("Xhtml")] internal abstract class XhtmlEditorUiControl : UiControl { private string _xhtml = ""; [BindableProperty] [FormsProperty] public string Xhtml { get { return _xhtml; } set { _xhtml = value; } } [FormsProperty] public string ClassConfigurationName { get; set; } [FormsProperty] public string ContainerClasses { get; set; } [FormsProperty] public IEnumerable EmbedableFieldsTypes { get; set; } [FormsProperty] public Guid PreviewPageId { get; set; } [FormsProperty] public Guid PreviewTemplateId { get; set; } [FormsProperty] public string PreviewPlaceholder { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/XhtmlEditorUiControlFactoryData.cs ================================================ using System.Configuration; using Composite.C1Console.Forms.Plugins.UiControlFactory; namespace Composite.C1Console.Forms.CoreUiControls { internal class XhtmlEditorUiControlFactoryData : UiControlFactoryData { private const string _classConfigurationNamePropertyName = "ClassConfigurationName"; private const string _containerClassesPropertyName = "ContainerClasses"; [ConfigurationProperty(_classConfigurationNamePropertyName,IsRequired=false,DefaultValue="common")] public string ClassConfigurationName { get { return (string)base[_classConfigurationNamePropertyName]; } set { base[_classConfigurationNamePropertyName] = value; } } [ConfigurationProperty(_containerClassesPropertyName, IsRequired = false, DefaultValue = "")] public string ContainerClasses { get { return (string)base[_containerClassesPropertyName]; } set { base[_containerClassesPropertyName] = value; } } } } ================================================ FILE: Composite/C1Console/Forms/CoreUiControls/XmlFunctionsDefinitionsEditorUiControl.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.CoreUiControls { internal class XmlFunctionsDefinitionsEditorUiControl : UiControl { /// /// List of "CompositeFuntionName" and "Result Name" pairs /// [RequiredValue()] [BindableProperty()] [FormsProperty()] public IEnumerable> XmlFunctions { get; set; } /// /// Lookup where "Local name" is key and value is a key value pair /// [RequiredValue()] [BindableProperty()] [FormsProperty()] public ILookup> Parameters { get; set; } [BindableProperty()] [FormsProperty()] public string UserProvidedPreviewXml { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/DataServices/FormDefinitionFileMarkupProvider.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using Composite.C1Console.Forms.Flows; using Composite.Data; using Composite.Data.Types; namespace Composite.C1Console.Forms.DataServices { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class FormDefinitionFileMarkupProvider : IFormMarkupProvider, ITestAutomationLocatorInformation { private readonly string _formPath; /// public FormDefinitionFileMarkupProvider(string formPath) { Verify.ArgumentNotNullOrEmpty(formPath, "formPath"); _formPath = formPath; } /// public string TestAutomationLocator { get { return Path.GetFileNameWithoutExtension(_formPath); } } /// public XmlReader GetReader() { string folderPath = Path.GetDirectoryName(_formPath).ToLowerInvariant(); string fileName = Path.GetFileName(_formPath).ToLowerInvariant(); List formFiles = (from file in DataFacade.GetData() where file.FolderPath.ToLowerInvariant() == folderPath && file.FileName.ToLowerInvariant() == fileName select file).ToList(); if (formFiles.Count == 0) throw new InvalidOperationException(string.Format("No form definition with path '{0}' was found. Please use a virtual Form Path", _formPath)); if (formFiles.Count > 1) throw new InvalidOperationException(string.Format("Multiple form definitions with path '{0}' was found", _formPath)); return new XmlTextReader(formFiles[0].GetReadStream()); } } } ================================================ FILE: Composite/C1Console/Forms/DataServices/Foundation/FormBuilder.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using Composite.Data; using Composite.Data.Types; namespace Composite.C1Console.Forms.DataServices.Foundation { internal static class FormBuilder { internal static FormTreeCompiler Build(string formPath, IFormChannelIdentifier channel, Dictionary bindings, bool debugMode) { string folderPath = Path.GetDirectoryName(formPath).ToLowerInvariant(); string fileName = Path.GetFileName(formPath).ToLowerInvariant(); List formFiles = (from file in DataFacade.GetData() where file.FolderPath.ToLowerInvariant() == folderPath && file.FileName.ToLowerInvariant() == fileName select file).ToList(); if (formFiles.Count == 0) throw new ArgumentException(string.Format("No form definition with path '{0}' was found. Please use a virtual Form Path", formPath), "formPath"); if (formFiles.Count > 1) throw new ArgumentException(string.Format("Multiple form definitions with path '{0}' was found", formPath), "formPath"); FormTreeCompiler compiler = new FormTreeCompiler(); using (XmlTextReader formMarkupReader = new XmlTextReader(formFiles[0].GetReadStream())) { compiler.Compile(formMarkupReader, channel, bindings, debugMode); return compiler; } } } } ================================================ FILE: Composite/C1Console/Forms/DataServices/Functions/GetDataFunctionFactory.cs ================================================ using System; using Composite.Data; using Composite.C1Console.Forms.Plugins.FunctionFactory; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.DataServices.Functions { internal sealed class GetData : IFormFunction { private Type _type; [FormsProperty()] public string TypeName { get { return _type.FullName; } set { _type = Composite.Core.Types.TypeManager.GetType( value ); } } public object Execute() { return DataFacade.GetData(_type); } } [ConfigurationElementType(typeof(GetDataFunctionFactoryData))] internal sealed class GetDataFunctionFactory : IFormFunctionFactory { public IFormFunction CreateFunction() { return new GetData(); } } [Assembler(typeof(NonConfigurableFunctionFactoryAssembler))] internal sealed class GetDataFunctionFactoryData : FunctionFactoryData { } } ================================================ FILE: Composite/C1Console/Forms/DataServices/Functions/ListDataInterfacesFunctionFactory.cs ================================================ using Composite.Data; using Composite.C1Console.Forms.Plugins.FunctionFactory; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.DataServices.Functions { internal sealed class ListDataInterfacesFunction : IFormFunction { public object Execute() { return DataFacade.GetAllInterfaces(); } } [ConfigurationElementType(typeof(ListDataInterfacesFunctionFactoryData))] internal sealed class ListDataInterfacesFunctionFactory : IFormFunctionFactory { public IFormFunction CreateFunction() { return new ListDataInterfacesFunction(); } } [Assembler(typeof(NonConfigurableFunctionFactoryAssembler))] internal sealed class ListDataInterfacesFunctionFactoryData : FunctionFactoryData { } } ================================================ FILE: Composite/C1Console/Forms/DataServices/IFormDefinitionFile.cs ================================================ using Composite.Data.Types; using Composite.Data; namespace Composite.C1Console.Forms.DataServices { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DataScope(DataScopeIdentifier.PublicName)] public interface IFormDefinitionFile : IFile { } } ================================================ FILE: Composite/C1Console/Forms/DataServices/UiControls/EmbeddedForm.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Text; using Composite.C1Console.Forms.Foundation; namespace Composite.C1Console.Forms.DataServices.UiControls { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ControlValueProperty("Bindings")] public class EmbeddedFormUiControl : UiControl { private FormTreeCompiler _compiler; /// [RequiredValue()] public string FormPath { get; set; } /// public bool Debug { get; set; } /// public Dictionary Bindings { get; set; } /// public override string Label { get { if (base.Label != null) { return base.Label; } return this.CompiledUiControl.Label; } set { base.Label = value; } } /// public EmbeddedFormUiControl() { base.Label = null; this.Bindings = new Dictionary(); } /// public override void BindStateToControlProperties() { _compiler.SaveAndValidateControlProperties(); } /// protected internal IUiControl CompiledUiControl { get { if (_compiler == null) { _compiler = Foundation.FormBuilder.Build(this.FormPath, this.UiControlChannel, this.Bindings, this.Debug); } return _compiler.UiControl; } } } } ================================================ FILE: Composite/C1Console/Forms/Flows/BindingValidationService.cs ================================================ using System; using System.Collections.Generic; namespace Composite.C1Console.Forms.Flows { internal class BindingValidationService: IBindingValidationService { public BindingValidationService(Dictionary validationErrors) { BindingErrors = validationErrors; } public Dictionary BindingErrors { get; private set; } } } ================================================ FILE: Composite/C1Console/Forms/Flows/FormFlowEventHandlerDelegate.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Actions; namespace Composite.C1Console.Forms.Flows { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public delegate void FormFlowEventHandler(FlowToken flowToken, Dictionary bindings, FlowControllerServicesContainer serviceContainer); } ================================================ FILE: Composite/C1Console/Forms/Flows/FormFlowRenderingService.cs ================================================ using System; using System.Web; using System.Collections.Generic; using Composite.Core.WebClient; namespace Composite.C1Console.Forms.Flows { internal class FormFlowRenderingService : IFormFlowRenderingService { private Dictionary _bindingPathedMessages; public void RerenderView() { this.RerenderViewRequested = true; } public bool RerenderViewRequested { get; private set; } public bool HasFieldMessages { get { return _bindingPathedMessages != null && _bindingPathedMessages.Count > 0; } } public void ShowFieldMessages(Dictionary bindingPathedMessages) { if (_bindingPathedMessages == null) { _bindingPathedMessages = new Dictionary(); } foreach (var msgElement in bindingPathedMessages) { _bindingPathedMessages.Add(msgElement.Key, msgElement.Value); } } public Dictionary BindingPathedMessages => _bindingPathedMessages; public void ShowFieldMessage(string fieldBindingPath, string message) { Verify.ArgumentNotNullOrEmpty(fieldBindingPath, "fieldBindingPath"); Verify.ArgumentNotNullOrEmpty(message, "message"); if (_bindingPathedMessages == null) { _bindingPathedMessages = new Dictionary(); } if (_bindingPathedMessages.ContainsKey(fieldBindingPath)) { _bindingPathedMessages[fieldBindingPath] += "\n" + message; } else { _bindingPathedMessages.Add(fieldBindingPath, message); } } public void SetSaveStatus(bool succeeded) { var httpContext = HttpContext.Current; (httpContext.Handler as FlowPage).SaveStepSucceeded = succeeded; } } } ================================================ FILE: Composite/C1Console/Forms/Flows/FormFlowUiDefinition.cs ================================================ using System.Collections.Generic; using System.Xml; using Composite.C1Console.Actions; using Composite.Data.Validation.ClientValidationRules; namespace Composite.C1Console.Forms.Flows { internal delegate Dictionary DelegatedBindingsProvider(); internal delegate XmlReader DelegatedMarkupProvider(); internal class FormFlowUiDefinition : VisualFlowUiDefinitionBase { private Dictionary _eventHandlers = new Dictionary(); public FormFlowUiDefinition(IFormMarkupProvider markupProvider, IFlowUiContainerType containerType, string containerLabel, IBindingsProvider bindingsProvider, Dictionary> bindingsValidationRules) { this.MarkupProvider = markupProvider; this.UiContainerType = containerType; this.ContainerLabel = containerLabel; this.BindingsProvider = bindingsProvider; this.BindingsValidationRules = bindingsValidationRules; } public FormFlowUiDefinition(IFormMarkupProvider markupProvider, IFlowUiContainerType containerType, string containerLabel, Dictionary bindings) : this(markupProvider, containerType, containerLabel, new PreLoadedBindingsProvider(bindings), null) { } public FormFlowUiDefinition(IFormMarkupProvider markupProvider, IFlowUiContainerType containerType, string containerLabel, Dictionary bindings, Dictionary> bindingsValidationRules) : this(markupProvider, containerType, containerLabel, new PreLoadedBindingsProvider(bindings), bindingsValidationRules) { } public FormFlowUiDefinition(XmlReader markupReader, IFlowUiContainerType containerType, string containerLabel, Dictionary bindings) : this(new PreLoadedMarkupProvider(markupReader), containerType, containerLabel, new PreLoadedBindingsProvider(bindings), null) { } public FormFlowUiDefinition(XmlReader markupReader, IFlowUiContainerType containerType, string containerLabel, Dictionary bindings, Dictionary> bindingsValidationRules) : this(new PreLoadedMarkupProvider(markupReader), containerType, containerLabel, new PreLoadedBindingsProvider(bindings), bindingsValidationRules) { } public FormFlowUiDefinition(IFormMarkupProvider markupProvider, IFlowUiContainerType containerType, string containerLabel, DelegatedBindingsProvider delegatedBindingsProvider) : this(markupProvider, containerType, containerLabel, new DelegateBasedBindingsProvider(delegatedBindingsProvider), null) { } public FormFlowUiDefinition(DelegatedMarkupProvider delegatedMarkupProvider, IFlowUiContainerType containerType, string containerLabel, DelegatedBindingsProvider delegatedBindingsProvider) : this(new DelegateBasedMarkupProvider(delegatedMarkupProvider), containerType, containerLabel, new DelegateBasedBindingsProvider(delegatedBindingsProvider), null) { } public IFormMarkupProvider MarkupProvider { get; private set; } public IFormMarkupProvider CustomToolbarItemsMarkupProvider { get; private set; } public void SetCustomToolbarMarkupProvider(XmlReader markupReader) { this.CustomToolbarItemsMarkupProvider = new PreLoadedMarkupProvider(markupReader); } public void SetCustomToolbarMarkupProvider(IFormMarkupProvider markupProvider) { this.CustomToolbarItemsMarkupProvider = markupProvider; } public override IFlowUiContainerType UiContainerType { get; protected set; } public IBindingsProvider BindingsProvider { get; private set; } public Dictionary EventHandlers { get { return _eventHandlers; } } public Dictionary> BindingsValidationRules { get; private set; } private class PreLoadedMarkupProvider : IFormMarkupProvider { private XmlReader _xmlReader; public PreLoadedMarkupProvider(XmlReader xmlReader) { _xmlReader = xmlReader; } public XmlReader GetReader() { return _xmlReader; } } private class PreLoadedBindingsProvider : IBindingsProvider { private Dictionary _bindings; public PreLoadedBindingsProvider(Dictionary bindings) { _bindings = bindings; } public Dictionary GetBindings() { return _bindings; } } private class DelegateBasedBindingsProvider : IBindingsProvider { private DelegatedBindingsProvider _delegatedBindingsProvider; internal DelegateBasedBindingsProvider(DelegatedBindingsProvider delegatedBindingsProvider) { _delegatedBindingsProvider = delegatedBindingsProvider; } public Dictionary GetBindings() { return _delegatedBindingsProvider.Invoke(); } } private class DelegateBasedMarkupProvider : IFormMarkupProvider { private DelegatedMarkupProvider _delegatedMarkupProvider; internal DelegateBasedMarkupProvider(DelegatedMarkupProvider delegatedMarkupProvider) { _delegatedMarkupProvider = delegatedMarkupProvider; } public XmlReader GetReader() { return _delegatedMarkupProvider.Invoke(); } } } } ================================================ FILE: Composite/C1Console/Forms/Flows/Foundation/PluginFacades/UiContainerFactoryFactoryPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using Composite.C1Console.Actions; using Composite.Core.Collections.Generic; using Composite.C1Console.Events; using Composite.C1Console.Forms.Flows.Plugins.UiContainerFactory; using Composite.C1Console.Forms.Flows.Plugins.UiContainerFactory.Runtime; namespace Composite.C1Console.Forms.Flows.Foundation.PluginFacades { internal static class UiContainerFactoryFactoryPluginFacade { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); static UiContainerFactoryFactoryPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static IUiContainer CreateContainer(IFormChannelIdentifier channel, IFlowUiContainerType flowUiContainerType) { string compositeName = string.Format("{0}->{1}", channel.ChannelName, flowUiContainerType.ContainerName); IUiContainerFactory containerFactory; if (_resourceLocker.Resources.ContainerfactoryCache.TryGetValue(compositeName, out containerFactory) == false) { try { containerFactory = _resourceLocker.Resources.Factory.Create(compositeName); using (_resourceLocker.Locker) { if (_resourceLocker.Resources.ContainerfactoryCache.ContainsKey(compositeName) == false) _resourceLocker.Resources.ContainerfactoryCache.Add(compositeName, containerFactory); } } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } return containerFactory.CreateContainer(); } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", UiContainerFactorySettings.SectionName), ex); } private sealed class Resources { public UiContainerFactoryFactory Factory { get; set; } public Dictionary ContainerfactoryCache { get; set; } public static void Initialize(Resources resources) { try { resources.Factory = new UiContainerFactoryFactory(); } catch (NullReferenceException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } resources.ContainerfactoryCache = new Dictionary(); } } } } ================================================ FILE: Composite/C1Console/Forms/Flows/IBindingValidationService.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Actions; namespace Composite.C1Console.Forms.Flows { internal interface IBindingValidationService : IFlowControllerService { Dictionary BindingErrors { get; } } } ================================================ FILE: Composite/C1Console/Forms/Flows/IBindingsProvider.cs ================================================ using System.Collections.Generic; namespace Composite.C1Console.Forms.Flows { internal interface IBindingsProvider { Dictionary GetBindings(); } } ================================================ FILE: Composite/C1Console/Forms/Flows/IFormEventIdentifier.cs ================================================  namespace Composite.C1Console.Forms.Flows { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IFormEventIdentifier { /// string BindingName { get; } } } ================================================ FILE: Composite/C1Console/Forms/Flows/IFormFlowRenderingService.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Actions; namespace Composite.C1Console.Forms.Flows { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IFormFlowRenderingService : IFlowControllerService { /// void RerenderView(); /// bool RerenderViewRequested { get; } /// bool HasFieldMessages { get; } /// void ShowFieldMessage(string fieldBindingPath, string message); /// void SetSaveStatus(bool succeeded); /// Dictionary BindingPathedMessages { get; } } } ================================================ FILE: Composite/C1Console/Forms/Flows/IFormMarkupProvider.cs ================================================ using System.Xml; namespace Composite.C1Console.Forms.Flows { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IFormMarkupProvider { /// XmlReader GetReader(); } } ================================================ FILE: Composite/C1Console/Forms/Flows/IUiContainer.cs ================================================ using System.Collections.Generic; using Composite.Core.ResourceSystem; namespace Composite.C1Console.Forms.Flows { internal interface IUiContainer { IUiControl Render( IUiControl innerForm, IUiControl customToolbarItems, IFormChannelIdentifier channel, IDictionary eventHandlerBindings, string containerLabel, string containerLabelField, string containerTooltip, ResourceHandle containerIcon); } } ================================================ FILE: Composite/C1Console/Forms/Flows/Plugins/UiContainerFactory/IUiContainerFactory.cs ================================================ using Composite.C1Console.Forms.Flows.Plugins.UiContainerFactory.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.Flows.Plugins.UiContainerFactory { [CustomFactory(typeof(UiContainerFactoryCustomFactory))] [ConfigurationNameMapper(typeof(UiContainerFactoryDefaultNameRetriever))] internal interface IUiContainerFactory { IUiContainer CreateContainer(); } } ================================================ FILE: Composite/C1Console/Forms/Flows/Plugins/UiContainerFactory/NonConfigurableUiContainerFactory.cs ================================================ using System; using Microsoft.Practices.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.Flows.Plugins.UiContainerFactory { [Assembler(typeof(NonConfigurableUiContainerFactoryAssembler))] internal sealed class NonConfigurableUiContainerFactory : UiContainerFactoryData { } internal sealed class NonConfigurableUiContainerFactoryAssembler : IAssembler { public IUiContainerFactory Assemble(IBuilderContext context, UiContainerFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IUiContainerFactory)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/C1Console/Forms/Flows/Plugins/UiContainerFactory/Runtime/UiContainerFactoryCustomFactory.cs ================================================ using System; using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.Flows.Plugins.UiContainerFactory.Runtime { internal sealed class UiContainerFactoryCustomFactory : AssemblerBasedCustomFactory { protected override UiContainerFactoryData GetConfiguration(string name, IConfigurationSource configurationSource) { UiContainerFactorySettings settings = configurationSource.GetSection(UiContainerFactorySettings.SectionName) as UiContainerFactorySettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", UiContainerFactorySettings.SectionName)); } int index1 = name.IndexOf("->"); string channelName = name.Substring(0, index1); string containerName = name.Substring(index1 + 2); ChannelConfigurationElement channelElement = settings.Channels[channelName]; if (null == channelElement) throw new ConfigurationErrorsException(string.Format("The channel {0} is missing from the configuration", channelName)); return channelElement.Factories.Get(containerName); } } } ================================================ FILE: Composite/C1Console/Forms/Flows/Plugins/UiContainerFactory/Runtime/UiContainerFactoryDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.Flows.Plugins.UiContainerFactory.Runtime { internal sealed class UiContainerFactoryDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/C1Console/Forms/Flows/Plugins/UiContainerFactory/Runtime/UiContainerFactoryFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.Flows.Plugins.UiContainerFactory.Runtime { internal sealed class UiContainerFactoryFactory : NameTypeFactoryBase { public UiContainerFactoryFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/C1Console/Forms/Flows/Plugins/UiContainerFactory/Runtime/UiContainerFactorySettings.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Composite.Core.Configuration; namespace Composite.C1Console.Forms.Flows.Plugins.UiContainerFactory.Runtime { internal sealed class UiContainerFactorySettings : SerializableConfigurationSection { public const string SectionName = "Composite.C1Console.Forms.Flows.Plugins.UiContainerFactoryConfiguration"; private const string _channelsProperty = "Channels"; [ConfigurationProperty(_channelsProperty, IsRequired = true)] public ChannelConfigurationElementCollection Channels { get { return (ChannelConfigurationElementCollection)base[_channelsProperty]; } } } internal sealed class ChannelConfigurationElement : NamedConfigurationElement { private const string _factoriesPropertyName = "Factories"; [ConfigurationProperty(_factoriesPropertyName, IsRequired = true)] public NameTypeManagerTypeConfigurationElementCollection Factories { get { return (NameTypeManagerTypeConfigurationElementCollection)base[_factoriesPropertyName]; } } } internal sealed class ChannelConfigurationElementCollection : ConfigurationElementCollection { public ChannelConfigurationElementCollection() : base() { AddElementName = "Channel"; } public void Add(ChannelConfigurationElement channelConfigurationElement) { BaseAdd(channelConfigurationElement); } new public ChannelConfigurationElement this[string Name] { get { return (ChannelConfigurationElement)BaseGet(Name); } } protected override ConfigurationElement CreateNewElement() { return new ChannelConfigurationElement(); } protected override object GetElementKey(ConfigurationElement element) { return (element as ChannelConfigurationElement).Name; } } } ================================================ FILE: Composite/C1Console/Forms/Flows/Plugins/UiContainerFactory/UiContainerFactoryData.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Forms.Flows.Plugins.UiContainerFactory { [ConfigurationElementType(typeof(NonConfigurableUiContainerFactory))] internal class UiContainerFactoryData : NameTypeManagerTypeConfigurationElement { private const string _templateFormVirtualPathPropertyName = "templateFormVirtualPath"; [ConfigurationProperty(_templateFormVirtualPathPropertyName, IsRequired = true)] public string TemplateFormVirtualPath { get { return (string)base[_templateFormVirtualPathPropertyName]; } set { base[_templateFormVirtualPathPropertyName] = value; } } private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } } } ================================================ FILE: Composite/C1Console/Forms/Flows/StandardEventIdentifiers.cs ================================================ using System; namespace Composite.C1Console.Forms.Flows { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class StandardEventIdentifiers { /// public static IFormEventIdentifier Save { get { return new SaveEvent(); } } /// public static IFormEventIdentifier SaveAndPublish { get { return new SaveAndPublishEvent(); } } /// public static IFormEventIdentifier SaveAs { get { return new SaveAsEvent(); } } /// public static IFormEventIdentifier Next { get { return new NextEvent(); } } /// public static IFormEventIdentifier Previous { get { return new PreviousEvent(); } } /// public static IFormEventIdentifier Finish { get { return new FinishEvent(); } } /// public static IFormEventIdentifier Cancel { get { return new CancelEvent(); } } /// public static IFormEventIdentifier Preview { get { return new PreviewEvent(); } } /// public static IFormEventIdentifier CustomEvent01 { get { return new CustomEvent(1); } } /// public static IFormEventIdentifier CustomEvent02 { get { return new CustomEvent(2); } } /// public static IFormEventIdentifier CustomEvent03 { get { return new CustomEvent(3); } } /// public static IFormEventIdentifier CustomEvent04 { get { return new CustomEvent(4); } } /// public static IFormEventIdentifier CustomEvent05 { get { return new CustomEvent(5); } } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class SaveEvent : IFormEventIdentifier { /// public SaveEvent() { } /// public string BindingName { get { return "SaveEventHandler"; } } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class SaveAndPublishEvent : IFormEventIdentifier { /// public SaveAndPublishEvent() { } /// public string BindingName { get { return "SaveAndPublishEventHandler"; } } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class SaveAsEvent : IFormEventIdentifier { /// public SaveAsEvent() { } /// public string BindingName { get { return "SaveAsEventHandler"; } } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class PreviewEvent : IFormEventIdentifier { /// public PreviewEvent() { } /// public string BindingName { get { return "PreviewEventHandler"; } } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class NextEvent : IFormEventIdentifier { /// public NextEvent() { } /// public string BindingName { get { return "NextEventHandler"; } } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class PreviousEvent : IFormEventIdentifier { /// public PreviousEvent() { } /// public string BindingName { get { return "PreviousEventHandler"; } } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class FinishEvent : IFormEventIdentifier { /// public FinishEvent() { } /// public string BindingName { get { return "FinishEventHandler"; } } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class CancelEvent : IFormEventIdentifier { /// public CancelEvent() { } /// public string BindingName { get { return "CancelEventHandler"; } } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class CustomEvent : IFormEventIdentifier { /// public CustomEvent(int eventNumber) { if (eventNumber < 1 || eventNumber > 5) throw new ArgumentException("Value must be between 1 and 5", "eventNumber"); this.BindingName = string.Format("CustomEvent0{0}Handler", eventNumber); } /// public string BindingName { get; private set; } } } ================================================ FILE: Composite/C1Console/Forms/Flows/StringBasedFormMarkupProvider.cs ================================================ using System; using System.IO; using System.Xml; namespace Composite.C1Console.Forms.Flows { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class StringBasedFormMarkupProvider : IFormMarkupProvider { private string Document { get; set; } /// public StringBasedFormMarkupProvider(string document) { if (document == null) throw new ArgumentNullException("document"); this.Document = document; } /// public XmlReader GetReader() { return new XmlTextReader(new StringReader(this.Document)); } } } ================================================ FILE: Composite/C1Console/Forms/FormCompileException.cs ================================================ using System; using Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompileTreeNodes; namespace Composite.C1Console.Forms { internal class FormCompileException : ApplicationException { private readonly XmlSourceNodeInformation _xmlInformation; private readonly XmlSourceNodeInformation _propertyXmlInformation; private readonly XmlSourceNodeInformation _extraPropertyXmlInformation; public FormCompileException(string message, XmlSourceNodeInformation xmlInformation) : base(message) { _xmlInformation = xmlInformation; } public FormCompileException(string message, XmlSourceNodeInformation xmlInformation, XmlSourceNodeInformation propertyXmlInformation) : base(message) { _xmlInformation = xmlInformation; _propertyXmlInformation = propertyXmlInformation; } public FormCompileException(string message, CompileTreeNode treeNode, CompileTreeNode propertyTreeNode) : this(message, treeNode.XmlSourceNodeInformation, propertyTreeNode.XmlSourceNodeInformation) { } public FormCompileException(string message, XmlSourceNodeInformation xmlInformation, XmlSourceNodeInformation propertyXmlInformation, XmlSourceNodeInformation extraPropertyXmlInformation) : base(message) { _xmlInformation = xmlInformation; _propertyXmlInformation = propertyXmlInformation; _extraPropertyXmlInformation = extraPropertyXmlInformation; } public FormCompileException(string message, XmlSourceNodeInformation xmlInformation, Exception inner) : base(message, inner) { _xmlInformation = xmlInformation; } public string TagName { get { return _xmlInformation.TagName; } } public string XPath { get { return _xmlInformation.XPath; } } public override string ToString() { string result = Message; if (null != _xmlInformation) { result = string.Format("{0}\n\nTag = {1}\nXPath = {2}", result, _xmlInformation.TagName, _xmlInformation.XPath); } if (null != _propertyXmlInformation) { result = string.Format("{0}\n\nProperty:\nTag = {1}\nXPath = {2}", result, _propertyXmlInformation.TagName, _propertyXmlInformation.XPath); } if (null != _extraPropertyXmlInformation) { result = string.Format("{0}\n\nProperty:\nTag = {1}\nXPath = {2}", result, _extraPropertyXmlInformation.TagName, _extraPropertyXmlInformation.XPath); } return result; } } } ================================================ FILE: Composite/C1Console/Forms/FormDefinition.cs ================================================ using System.Collections.Generic; using System.Xml; namespace Composite.C1Console.Forms { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class FormDefinition { /// public FormDefinition(XmlReader formMarkup, Dictionary bindings) { this.FormMarkup = formMarkup; this.Bindings = bindings; } /// public XmlReader FormMarkup { get; private set; } /// public Dictionary Bindings { get; private set; } } } ================================================ FILE: Composite/C1Console/Forms/FormFactoryService.cs ================================================ using Composite.C1Console.Forms.Foundation.PluginFacades; using Composite.C1Console.Forms.Plugins.FunctionFactory; namespace Composite.C1Console.Forms { internal static class FormFactoryService { public static IFormFunction GetFunction(string namespaceName, string name) { return FunctionFactoryPluginFacade.GetFunction(namespaceName, name); } public static IUiControl CreateControl(string channelName, string namespaceName, string name) { return UiControlFactoryPluginFacade.CreateControl(new ChannelIdentifier(channelName), namespaceName, name); } public static IUiControl CreateControl(IFormChannelIdentifier channel, string namespaceName, string name) { return UiControlFactoryPluginFacade.CreateControl(channel, namespaceName, name); } private class ChannelIdentifier : IFormChannelIdentifier { public ChannelIdentifier( string name ) { this.ChannelName = name; } public string ChannelName { get; private set; } } } } ================================================ FILE: Composite/C1Console/Forms/FormKeyTagNames.cs ================================================ using Composite.C1Console.Forms.Foundation.FormTreeCompiler; namespace Composite.C1Console.Forms { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class FormKeyTagNames { /// public static readonly string DefaultPropertyName = CompilerGlobals.DefaultPropertyName; /// public static readonly string FormDefinition = CompilerGlobals.FormDefinition_TagName; /// public static readonly string Layout = CompilerGlobals.Layout_TagName; /// public static readonly string Bindings = CompilerGlobals.Bindings_TagName; /// public static readonly string Binding = CompilerGlobals.Binding_TagName; /// public static readonly string Bind = CompilerGlobals.Bind_TagName; /// public static readonly string Read = CompilerGlobals.Read_TagName; /// public static readonly string IfCondition = CompilerGlobals.IfCondition_TagName; /// public static readonly string IfWhenTrue = CompilerGlobals.IfWhenTrue_TagName; /// public static readonly string IfWhenFalse = CompilerGlobals.IfWhenFalse_TagName; } } ================================================ FILE: Composite/C1Console/Forms/FormTreeCompiler.cs ================================================ using System; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; using Composite.C1Console.Forms.Foundation.FormTreeCompiler; using Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompilePhases; using Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompileTreeNodes; using Composite.C1Console.Forms.WebChannel; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.Core.WebClient.FlowMediators.FormFlowRendering; using Composite.Data.Validation.ClientValidationRules; namespace Composite.C1Console.Forms { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class FormTreeCompiler { private CompileContext _context; private Dictionary _bindingObjects; private IUiControl _uiControl; private CompileTreeNode _rootCompilerNode; private string _label; private string _tooltip; private string _iconHandle; /// public void Compile(XmlReader reader, IFormChannelIdentifier channel, Dictionary bindingObjects) { Compile(reader, channel, bindingObjects, false, "", null); } /// public void Compile(XmlReader reader, IFormChannelIdentifier channel, Dictionary bindingObjects, Dictionary> bindingsValidationRules) { Compile(reader, channel, bindingObjects, false, "", bindingsValidationRules); } /// public void Compile(XmlReader reader, IFormChannelIdentifier channel, Dictionary bindingObjects, bool withDebug) { Compile(reader, channel, bindingObjects, withDebug, "", null); } /// public void Compile(XmlReader reader, IFormChannelIdentifier channel, Dictionary bindingObjects, bool withDebug, Dictionary> bindingsValidationRules) { Compile(reader, channel, bindingObjects, withDebug, "", bindingsValidationRules); } /// public void Compile(XmlReader reader, IFormChannelIdentifier channel, Dictionary bindingObjects, bool withDebug, string customControlIdPrefix) { Compile(reader, channel, bindingObjects, withDebug, customControlIdPrefix, null); } /// public void Compile(XmlReader reader, IFormChannelIdentifier channel, Dictionary bindingObjects, bool withDebug, string customControlIdPrefix, Dictionary> bindingsValidationRules) { XDocument doc = XDocument.Load(reader); reader.Close(); Compile(doc, channel, bindingObjects, withDebug, customControlIdPrefix, bindingsValidationRules); } /// public void Compile(XDocument doc, IFormChannelIdentifier channel, Dictionary bindingObjects, bool withDebug, string customControlIdPrefix, Dictionary> bindingsValidationRules) { _bindingObjects = bindingObjects; _context = new CompileContext { BindingObjects = bindingObjects, BindingsValidationRules = bindingsValidationRules, CurrentChannel = channel, CustomControlIdPrefix = customControlIdPrefix }; _rootCompilerNode = BuildFromXmlPhase.BuildTree(doc); UpdateXmlInformationPhase updateInfo = new UpdateXmlInformationPhase(); updateInfo.UpdateInformation(_rootCompilerNode); CreateProducersPhase createProducers = new CreateProducersPhase(_context); createProducers.CreateProducers(_rootCompilerNode); EvaluatePropertiesPhase evaluateProperties = new EvaluatePropertiesPhase(_context, withDebug); evaluateProperties.Evaluate(_rootCompilerNode); ExtractUiArtifactsPhase extractUiArtifacts = new ExtractUiArtifactsPhase(); extractUiArtifacts.ExtractUiArtifacts(_rootCompilerNode, out _uiControl, out _label, out _tooltip, out _iconHandle); } /// /// Saves control properties into bindings. /// /// public void SaveControlProperties() { SaveAndValidateControlProperties(); } /// /// Saves control properties into bindings and returns validation errors. /// /// public Dictionary SaveAndValidateControlProperties() { _uiControl.BindStateToControlProperties(); var bindingErrors = new Dictionary(); foreach (CompileContext.IRebinding rd in _context.Rebindings) { rd.Rebind(_bindingObjects, bindingErrors); } return bindingErrors; } /// public Dictionary GetBindingToClientIDMapping() { var result = new Dictionary(); FormFlowUiDefinitionRenderer.ResolveBindingPathToClientIDMappings(_uiControl as IWebUiControl, result); return result; } /// public IUiControl UiControl => _uiControl; /// public string Label { get { return !string.IsNullOrEmpty(_label) ? _label : _uiControl.Label; } } /// public string Tooltip => _tooltip; /// public ResourceHandle Icon { get { if (string.IsNullOrEmpty(_iconHandle)) { return null; } if (_iconHandle.IndexOf(',') == -1) { return new ResourceHandle(BuildInIconProviderName.ProviderName, _iconHandle.Trim()); } string[] resourceParts = _iconHandle.Split(','); if (resourceParts.Length != 2) throw new InvalidOperationException( $"Invalid icon resource name '{_iconHandle}'. Only one comma expected."); return new ResourceHandle(resourceParts[0].Trim(), resourceParts[1].Trim()); } } /// public Dictionary BindingObjects => _bindingObjects; /// public CompileTreeNode RootCompileTreeNode => _rootCompilerNode; } } ================================================ FILE: Composite/C1Console/Forms/FormsPropertyAttribute.cs ================================================ using System; namespace Composite.C1Console.Forms { /// /// Defines that a property should be visuble / accessible in the forms environment. /// /// [AttributeUsage(AttributeTargets.Property,AllowMultiple=false,Inherited=true)] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class FormsPropertyAttribute : Attribute { } } ================================================ FILE: Composite/C1Console/Forms/Foundation/FormTreeCompiler/CompileContext.cs ================================================ using System; using System.Reflection; using System.Collections.Generic; using Composite.Core.Types; using Composite.Data.Validation.ClientValidationRules; namespace Composite.C1Console.Forms.Foundation.FormTreeCompiler { internal sealed class CompileContext { private IFormChannelIdentifier _currentChannel; private object _bindingsProducer = null; private Dictionary _bindingObjects = new Dictionary(); private Dictionary _bindingObjectsInformations = new Dictionary(); private Dictionary> _bindingsValidationRules = new Dictionary>(); private List _registeredBindingNames = new List(); private List _registeredSourceObjectBindings = new List(); private Dictionary> _registeredSourcePropertyBindings = new Dictionary>(); private List _rebindings = new List(); private int _controlIdCounter = 0; private int _debugControlIdCounter = 0; internal bool RegistarBindingName(string bindingName) { if (_registeredBindingNames.Contains(bindingName)) return false; _registeredBindingNames.Add(bindingName); return true; } internal bool RegisterUniqueSourceObjectBinding(string bindSourceName) { if (_registeredSourceObjectBindings.Contains(bindSourceName) == false) { _registeredSourceObjectBindings.Add(bindSourceName); return true; } return false; } internal bool IsUniqueSourceObjectBinding(string bindSourceName) { return _registeredSourceObjectBindings.Contains(bindSourceName); } internal bool RegisterUniqueSourcePropertyBinding(string bindSounceName, string bindPropertyName) { List boundProperties; if (_registeredSourcePropertyBindings.ContainsKey(bindSounceName)) { boundProperties = _registeredSourcePropertyBindings[bindSounceName]; if (boundProperties.Contains(bindPropertyName)) return false; } else { boundProperties = new List(); _registeredSourcePropertyBindings.Add(bindSounceName, boundProperties); } boundProperties.Add(bindPropertyName); return true; } internal bool IsUniqueSourcePropertyBinding(string bindSounceName) { return _registeredSourcePropertyBindings.ContainsKey(bindSounceName); } internal IFormChannelIdentifier CurrentChannel { get { return _currentChannel; } set { _currentChannel = value; } } internal object BindingsProducer { get { return _bindingsProducer; } set { _bindingsProducer = value; } } internal object GetBindingObject(string name) { if (_bindingObjects == null || !_bindingObjects.ContainsKey(name)) return null; return _bindingObjects[name]; } internal bool BindingObjectExists(string name) { return _bindingObjects != null && _bindingObjects.ContainsKey(name); } internal void SetBindingType(string name, Type type) { BindingInformation bindingInformation; if (!_bindingObjectsInformations.TryGetValue(name, out bindingInformation)) { bindingInformation = new BindingInformation(); _bindingObjectsInformations.Add(name, bindingInformation); } bindingInformation.BindingType = type; } internal List GetBindingsValidationRules(string bindingName) { if (_bindingsValidationRules == null) return null; List rules; _bindingsValidationRules.TryGetValue(bindingName, out rules); return rules; } public Dictionary BindingObjects { set { _bindingObjects = value; } } public Dictionary> BindingsValidationRules { set { _bindingsValidationRules = value; } } internal List Rebindings { get { return _rebindings; } } internal string GetNextControlId( string prefix ) { return string.Format("{0}{1}{2}", this.CustomControlIdPrefix, prefix, _controlIdCounter++); } internal string GetNextDebugControlId { get { return string.Format("UiDebugControl{0}", _debugControlIdCounter++); } } internal string CustomControlIdPrefix { get; set; } internal interface IRebinding { void Rebind(Dictionary bindingObjects, Dictionary conversionErrors); string BindingObjectName { get; } string PropertyName { get; } Type DestinationObjectType { get; } object SourceProducer { get; } } internal class ObjectRebinding : IRebinding { private object _sourceProducer; private MethodInfo _sourceProducerGetProperty; private string _bindSourceName; private Type _destinationObjectType; internal ObjectRebinding(object sourceProducer, MethodInfo sourceProducerGetProperty, string bindSourceName, Type destinationObjectType) { _sourceProducer = sourceProducer; _sourceProducerGetProperty = sourceProducerGetProperty; _bindSourceName = bindSourceName; _destinationObjectType = destinationObjectType; } public void Rebind(Dictionary bindingObjects, Dictionary conversionErrors) { IValidatingUiControl validating = _sourceProducer as IValidatingUiControl; if (validating != null && validating.IsValid == false) { conversionErrors.Add(_bindSourceName, new InvalidOperationException(validating.ValidationError)); } else { object value = _sourceProducerGetProperty.Invoke(_sourceProducer, null); Exception conversionError; bindingObjects[_bindSourceName] = ValueTypeConverter.TryConvert(value, _destinationObjectType, out conversionError); if (conversionError != null) { conversionErrors.Add(_bindSourceName, conversionError); } } } public string BindingObjectName { get { return _bindSourceName; } } public string PropertyName { get { return null; } } public Type DestinationObjectType { get { return _destinationObjectType; } } public object SourceProducer { get { return _sourceProducer; } } } internal class PropertyRebinding : IRebinding { private object _sourceProducer; private MethodInfo _sourceProducerGetProperty; private object _destinationObject; private MethodInfo _destinationSetProperty; private Type _destinationSetPropertyType; private string _bindingObjectName; private string _propertyName; internal PropertyRebinding(object sourceProducer, MethodInfo sourceProducerGetProperty, object destinationObject, MethodInfo destinationSetProperty, Type destinationSetPropertyType, string bindingObjectName, string propertyName) { _sourceProducer = sourceProducer; _sourceProducerGetProperty = sourceProducerGetProperty; _destinationObject = destinationObject; _destinationSetProperty = destinationSetProperty; _destinationSetPropertyType = destinationSetPropertyType; _bindingObjectName = bindingObjectName; _propertyName = propertyName; } public void Rebind(Dictionary bindingObjects, Dictionary conversionErrors) { object value = _sourceProducerGetProperty.Invoke(_sourceProducer, null); object parm = ValueTypeConverter.Convert(value, _destinationSetPropertyType); object[] parms = { parm }; try { _destinationSetProperty.Invoke(_destinationObject, parms); } catch(TargetInvocationException e) { throw e.InnerException; } } public string BindingObjectName { get { return _bindingObjectName; } } public string PropertyName { get { return _propertyName; } } public Type DestinationObjectType { get { return _destinationObject.GetType(); } } public object SourceProducer { get { return _sourceProducer; } } } internal class BindingInformation { private Type _bindingType; public Type BindingType { get { return _bindingType; } set { _bindingType = value; } } } } } ================================================ FILE: Composite/C1Console/Forms/Foundation/FormTreeCompiler/CompilePhases/BuildFromXmlPhase.cs ================================================ using System.Linq; using System.Xml.Linq; using Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompileTreeNodes; using Composite.Core.ResourceSystem; namespace Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompilePhases { /// /// Converts form markup xml into tree of . Translates properties /// internal static class BuildFromXmlPhase { public static CompileTreeNode BuildTree(XDocument document) { return BuildRec(document.Root); } public static ElementCompileTreeNode BuildRec(XElement element) { int depth = element.Ancestors().Count(); var debugInfo = new XmlSourceNodeInformation(depth, element.Name.LocalName, element.Name.LocalName, element.Name.NamespaceName); var result = new ElementCompileTreeNode(debugInfo); foreach (var attribute in element.Attributes()) { if (attribute.Name.LocalName == "xmlns") continue; bool isNamespaceDeclaration = attribute.Name.Namespace == "http://www.w3.org/2000/xmlns/"; var property = new PropertyCompileTreeNode(attribute.Name.LocalName, debugInfo, isNamespaceDeclaration); property.Value = StringResourceSystemFacade.ParseString(attribute.Value); result.AddNamedProperty(property); } foreach (var node in element.Nodes()) { if (node is XElement) { result.Children.Add(BuildRec(node as XElement)); continue; } if (node is XText) { string text = (node as XText).Value; if (string.IsNullOrWhiteSpace(text)) { continue; } var textProperty = new PropertyCompileTreeNode(CompilerGlobals.DefaultPropertyName, debugInfo); textProperty.Value = StringResourceSystemFacade.ParseString(text); result.DefaultProperties.Add(textProperty); continue; } } return result; } } } ================================================ FILE: Composite/C1Console/Forms/Foundation/FormTreeCompiler/CompilePhases/CreateProducersPhase.cs ================================================ using Composite.C1Console.Forms.Foundation.PluginFacades; using Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompileTreeNodes; namespace Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompilePhases { internal sealed class CreateProducersPhase { private CompileContext _compileContext; public CreateProducersPhase(CompileContext compileContext) { _compileContext = compileContext; } public void CreateProducers(CompileTreeNode node) { if (node is ElementCompileTreeNode) { ElementCompileTreeNode element = node as ElementCompileTreeNode; if ((CompilerGlobals.IsProducerTag(element)) || (CompilerGlobals.IsReadTag(element)) || (CompilerGlobals.IsBindTag(element)) || (CompilerGlobals.IsBindingTag(element)) || (CompilerGlobals.IsLayoutTag(element))) { element.Producer = ProducerMediatorPluginFacade.CreateProducer(_compileContext.CurrentChannel, element.XmlSourceNodeInformation.NamespaceURI, element.XmlSourceNodeInformation.Name); if (element.Producer is IUiControl) { (element.Producer as IUiControl).UiControlID = _compileContext.GetNextControlId(element.XmlSourceNodeInformation.Name); } } else if (CompilerGlobals.IsBindingsTag(element)) { if (null == _compileContext.BindingsProducer) { _compileContext.BindingsProducer = ProducerMediatorPluginFacade.CreateProducer(_compileContext.CurrentChannel, element.XmlSourceNodeInformation.NamespaceURI, element.XmlSourceNodeInformation.Name); } element.Producer = _compileContext.BindingsProducer; } } foreach (CompileTreeNode subNode in node.AllSubNodes) CreateProducers(subNode); } } } ================================================ FILE: Composite/C1Console/Forms/Foundation/FormTreeCompiler/CompilePhases/EvaluatePropertiesPhase.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompileTreeNodes; using Composite.C1Console.Forms.Foundation.PluginFacades; using Composite.C1Console.Forms.StandardProducerMediators.BuildinProducers; using Composite.Core.Types; namespace Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompilePhases { internal sealed class EvaluatePropertiesPhase { private readonly CompileContext _compileContext; private readonly bool _withDebug = false; public EvaluatePropertiesPhase(CompileContext compileContext) { _compileContext = compileContext; } public EvaluatePropertiesPhase(CompileContext compileContext, bool withDebug) : this(compileContext) { _withDebug = withDebug; } public CompileTreeNode Evaluate(CompileTreeNode node) { return Evaluate(node as ElementCompileTreeNode, null); } public ElementCompileTreeNode Evaluate(ElementCompileTreeNode node, List newProperties, string defaultOverloadPropertyName = null) { var replacedNodes = new Dictionary>(); bool isIfProducer = node.Producer is IfProducer; if (!isIfProducer) { foreach (ElementCompileTreeNode child in node.Children) { var newProps = new List(); string childDefaultOverloadPropertyName = null; if (node.Producer != null) { ReadBindingControlValueOverload attribute = node.Producer.GetType().GetCustomAttributesRecursively().SingleOrDefault(); if (attribute != null) { childDefaultOverloadPropertyName = attribute.PropertyName; } } ElementCompileTreeNode resultNode = Evaluate(child, newProps, childDefaultOverloadPropertyName); if ((null == resultNode) || (false == child.Equals(resultNode))) { replacedNodes.Add(child, newProps); foreach (PropertyCompileTreeNode newProperty in newProps) { if (newProperty.Name == CompilerGlobals.DefaultPropertyName) { node.DefaultProperties.Add(newProperty); } else { node.AddNamedProperty(newProperty); } } } } } if (!isIfProducer) { foreach (ElementCompileTreeNode nodeToRemove in replacedNodes.Keys) { node.Children.Remove(nodeToRemove); } } return EvaluateElementCompileTreeNode(node, newProperties, defaultOverloadPropertyName); } public ElementCompileTreeNode EvaluateElementCompileTreeNode(ElementCompileTreeNode element, List newProperties, string defaultOverloadPropertyName) { if (CompilerGlobals.IsElementEmbeddedProperty(element)) { return HandleEmbeddedProperty(element, newProperties); } if (element.Producer == null) return element; if (element.Producer is IfProducer) { return HandleIfProducerElement(element, newProperties); } return HandleProducerElement(element, newProperties, defaultOverloadPropertyName); } private ElementCompileTreeNode HandleEmbeddedProperty(ElementCompileTreeNode element, List newProperties) { if (element.NamedProperties.Count > 0) throw new FormCompileException("Attrbute not allow on embedded properties", element.XmlSourceNodeInformation); string producerName; string propertyName; CompilerGlobals.GetSplittedPropertyNameFromCompositeName(element, out producerName, out propertyName); foreach (PropertyCompileTreeNode property in element.DefaultProperties) { var replacingProperty = new PropertyCompileTreeNode(propertyName, element.XmlSourceNodeInformation) { Value = property.Value, InclosingProducerName = producerName }; newProperties.Add(replacingProperty); } return null; } private ElementCompileTreeNode HandleIfProducerElement(ElementCompileTreeNode element, List newProperties) { ElementCompileTreeNode conditionElement = null; ElementCompileTreeNode whenTrueElement = null; ElementCompileTreeNode whenFalseElement = null; foreach (ElementCompileTreeNode child in element.Children) { if (CompilerGlobals.IsElementIfConditionTag(child)) conditionElement = child; if (CompilerGlobals.IsElementIfWhenTrueTag(child)) whenTrueElement = child; if (CompilerGlobals.IsElementIfWhenFalseTag(child)) whenFalseElement = child; } if (conditionElement == null) throw new FormCompileException(string.Format("Missing condition tag ({0})", CompilerGlobals.IfCondition_TagName), element.XmlSourceNodeInformation); if (whenTrueElement == null) throw new FormCompileException(string.Format("Missing when true tag ({0})", CompilerGlobals.IfWhenTrue_TagName), element.XmlSourceNodeInformation); var newConditionProperties = new List(); Evaluate(conditionElement, newConditionProperties); var conditionProducer = (IfConditionProducer)newConditionProperties[0].Value; object value; if (conditionProducer.Condition) { var newWhenTrueProperties = new List(); Evaluate(whenTrueElement, newWhenTrueProperties); var whenTrueProducer = (IfWhenTrueProducer)newWhenTrueProperties[0].Value; if (whenTrueProducer.Result.Count == 1) { value = whenTrueProducer.Result[0]; } else { value = whenTrueProducer.Result; } } else if (whenFalseElement != null) { var newWhenFalseProperties = new List(); Evaluate(whenFalseElement, newWhenFalseProperties); var whenFalseProducer = (IfWhenFalseProducer)newWhenFalseProperties[0].Value; if (whenFalseProducer.Result.Count == 1) { value = whenFalseProducer.Result[0]; } else { value = whenFalseProducer.Result; } } else { return null; } var replacingProperty = new PropertyCompileTreeNode(CompilerGlobals.DefaultPropertyName, element.XmlSourceNodeInformation); replacingProperty.Value = value; newProperties.Add(replacingProperty); return null; } private ElementCompileTreeNode HandleProducerElement(ElementCompileTreeNode element, List newProperties, string defaultOverloadPropertyName) { PropertyAssigner.AssignPropertiesToProducer(element, _compileContext); string replacingPropertyName = CompilerGlobals.DefaultPropertyName; if (defaultOverloadPropertyName != null) { replacingPropertyName = defaultOverloadPropertyName; } var replacingProperty = new PropertyCompileTreeNode(replacingPropertyName, element.XmlSourceNodeInformation); object result = ProducerMediatorPluginFacade.EvaluateProducer(element.XmlSourceNodeInformation.NamespaceURI, element.Producer); if (result is BindingProducer) { var bindingProducer = (BindingProducer)result; if (string.IsNullOrEmpty(bindingProducer.name)) throw new FormCompileException("A binding declaraions is missing its name attribute", element.XmlSourceNodeInformation); if (!_compileContext.RegistarBindingName(bindingProducer.name)) throw new FormCompileException(string.Format("Name binding name {0} is used twice which is not allowed", bindingProducer.name), element.XmlSourceNodeInformation); //if (_compileContext.GetBindingObject(bindingProducer.name) == null && !bindingProducer.optional) //{ // throw new FormCompileException(string.Format("The non optional binding {0} is missing its binding value", bindingProducer.name), element.XmlSourceNodeInformation); //} Type type = TypeManager.GetType(bindingProducer.type); _compileContext.SetBindingType(bindingProducer.name, type); } else if (_withDebug && result is IUiControl) { IUiControl uiControl = result as IUiControl; string debugControlNamespace; string debugControlName; UiControlFactoryPluginFacade.GetDebugControlName(_compileContext.CurrentChannel, out debugControlNamespace, out debugControlName); DebugUiControl debug = ProducerMediatorPluginFacade.CreateProducer(_compileContext.CurrentChannel, debugControlNamespace, debugControlName) as DebugUiControl; debug.UiControlID = _compileContext.GetNextDebugControlId; debug.UiControl = uiControl; result = debug; debug.UiControlID = uiControl.UiControlID; debug.TagName = element.XmlSourceNodeInformation.TagName; debug.SourceElementXPath = element.XmlSourceNodeInformation.XPath; foreach (CompileContext.IRebinding rd in _compileContext.Rebindings) { if (ReferenceEquals(uiControl, rd.SourceProducer)) { debug.Bindings.Add(new DebugUiControl.BindingInformation( rd.BindingObjectName, rd.DestinationObjectType, rd.PropertyName)); } } } replacingProperty.Value = result; newProperties.Add(replacingProperty); return null; } } } ================================================ FILE: Composite/C1Console/Forms/Foundation/FormTreeCompiler/CompilePhases/ExtractUiArtifactsPhase.cs ================================================ using Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompileTreeNodes; using Composite.C1Console.Forms.StandardProducerMediators.BuildinProducers; namespace Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompilePhases { internal sealed class ExtractUiArtifactsPhase { public void ExtractUiArtifacts(CompileTreeNode node, out IUiControl uiControl, out string label, out string tooltip, out string iconhandle ) { foreach (PropertyCompileTreeNode n in node.DefaultProperties) { if (n.Value is LayoutProducer) { var lp = (LayoutProducer) n.Value; uiControl = lp.UiControl; label = lp.label; iconhandle = lp.iconhandle; tooltip = lp.tooltip; return; } } throw new FormCompileException("No layout defined in the source file", node.XmlSourceNodeInformation); } } } ================================================ FILE: Composite/C1Console/Forms/Foundation/FormTreeCompiler/CompilePhases/UpdateXmlInformationPhase.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompileTreeNodes; namespace Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompilePhases { internal sealed class UpdateXmlInformationPhase { public void UpdateInformation(CompileTreeNode startNode) { UpdateInformation(startNode, "", null); } private void UpdateInformation(CompileTreeNode node, string currentXPath, int? childNumber) { if (childNumber.HasValue) { currentXPath = string.Format("{0}/{1}[{2}]", currentXPath, node.XmlSourceNodeInformation.TagName, childNumber.Value); } else { currentXPath = string.Format("{0}/{1}", currentXPath, node.XmlSourceNodeInformation.TagName); } node.XmlSourceNodeInformation.XPath = currentXPath; Dictionary tagOccursCount = new Dictionary(); Dictionary xPathCounter = new Dictionary(); foreach (CompileTreeNode child in node.Children) { if (false == tagOccursCount.ContainsKey(child.XmlSourceNodeInformation.Name)) tagOccursCount.Add(child.XmlSourceNodeInformation.Name, 0); tagOccursCount[child.XmlSourceNodeInformation.Name]++; } foreach (CompileTreeNode child in node.Children) { if (tagOccursCount[child.XmlSourceNodeInformation.Name] > 1) { if (false == xPathCounter.ContainsKey(child.XmlSourceNodeInformation.Name)) xPathCounter.Add(child.XmlSourceNodeInformation.Name, 1); UpdateInformation(child, currentXPath, xPathCounter[child.XmlSourceNodeInformation.Name]++); } else { UpdateInformation(child, currentXPath, null); } } foreach (PropertyCompileTreeNode nameProperty in node.AllNamedProperties) { nameProperty.XmlSourceNodeInformation.NamespaceURI = node.XmlSourceNodeInformation.NamespaceURI; UpdateInformation(nameProperty, currentXPath, null); } if (node.DefaultProperties.Count == 1) { node.DefaultProperties[0].XmlSourceNodeInformation.NamespaceURI = node.XmlSourceNodeInformation.NamespaceURI; UpdateInformation(node.DefaultProperties[0], currentXPath, null); } else if (node.DefaultProperties.Count > 1) { int counter = 1; foreach (CompileTreeNode defaultProperty in node.DefaultProperties) { defaultProperty.XmlSourceNodeInformation.NamespaceURI = node.XmlSourceNodeInformation.NamespaceURI; UpdateInformation(defaultProperty, currentXPath, counter++); } } } } } ================================================ FILE: Composite/C1Console/Forms/Foundation/FormTreeCompiler/CompileTreeNodes/CompileTreeNode.cs ================================================ using System.Collections.Generic; using System.Diagnostics; namespace Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompileTreeNodes { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DebuggerDisplay("Name {_xmlSourceNodeInformation.Name}")] public class CompileTreeNode { private static int _compilerIdCounter = 0; private int _compilerId; private XmlSourceNodeInformation _xmlSourceNodeInformation; private List _childNodes = new List(); private List _defaultProperties = new List(); private Dictionary> _namedProperties = new Dictionary>(); /// public CompileTreeNode(XmlSourceNodeInformation xmlSourceNodeInformation) { _compilerId = _compilerIdCounter++; _xmlSourceNodeInformation = xmlSourceNodeInformation; } /// public XmlSourceNodeInformation XmlSourceNodeInformation { get { return _xmlSourceNodeInformation; } } /// public List Children { get { return _childNodes; } } /// public List DefaultProperties { get { return _defaultProperties; } } /// public Dictionary> NamedProperties { get { return _namedProperties; } } /// public void AddNamedProperty(PropertyCompileTreeNode property) { AddNamedProperty(property.Name, property); } /// public void AddNamedProperty(string name, PropertyCompileTreeNode property) { if (false == _namedProperties.ContainsKey(name)) { _namedProperties.Add(name, new List()); } _namedProperties[name].Add(property); } /// public IEnumerable AllNamedProperties { get { foreach (List namedProperties in NamedProperties.Values) { foreach (PropertyCompileTreeNode namedProperty in namedProperties) yield return namedProperty; } } } /// public IEnumerable AllSubNodes { get { foreach (CompileTreeNode child in Children) yield return child; foreach (List namedProperties in NamedProperties.Values) { foreach (CompileTreeNode namedProperty in namedProperties) yield return namedProperty; } foreach (CompileTreeNode defaultProperty in DefaultProperties) yield return defaultProperty; } } /// public int CompilerId { get { return _compilerId; } } /// public override int GetHashCode() { return _compilerId; } /// public override bool Equals(object obj) { if (null == obj) return false; CompileTreeNode node = obj as CompileTreeNode; if (null == node) return false; return node._compilerId == _compilerId; } /// public bool Equals(CompileTreeNode node) { if (null == node) return false; return node._compilerId == _compilerId; } } } ================================================ FILE: Composite/C1Console/Forms/Foundation/FormTreeCompiler/CompileTreeNodes/ElementCompileTreeNode.cs ================================================ using System.Collections.Generic; namespace Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompileTreeNodes { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ElementCompileTreeNode : CompileTreeNode { private object _producer = null; private Dictionary> _addedProperties = new Dictionary>(); /// public ElementCompileTreeNode(XmlSourceNodeInformation sourceInformation) : base(sourceInformation) { } /// public object Producer { get { return _producer; } set { _producer = value; } } /// public Dictionary> AddedProperties { get { return _addedProperties; } } } } ================================================ FILE: Composite/C1Console/Forms/Foundation/FormTreeCompiler/CompileTreeNodes/PropertyCompileTreeNode.cs ================================================ using System.Diagnostics; using Composite.Data.Validation.ClientValidationRules; using System.Collections.Generic; namespace Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompileTreeNodes { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DebuggerDisplay("PropertyCompileTreeNode: {Name} = {Value}")] public sealed class PropertyCompileTreeNode : CompileTreeNode { private string _name = ""; private object _value = null; private string _inclosingProducerName = ""; /// public PropertyCompileTreeNode(string name, XmlSourceNodeInformation sourceInformation, bool isNamespaceDeclaration = false) : base(sourceInformation) { _name = name; IsNamespaceDeclaration = isNamespaceDeclaration; } /// public string Name { get { return _name; } } /// public bool IsNamespaceDeclaration { get; private set; } /// public object Value { get { return _value; } set { _value = value; } } /// public string InclosingProducerName { get { return _inclosingProducerName; } set { _inclosingProducerName = value; } } /// public List ClientValidationRules { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/Foundation/FormTreeCompiler/CompileTreeNodes/XmlSourceNodeInformation.cs ================================================ namespace Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompileTreeNodes { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class XmlSourceNodeInformation { private int _depth; private string _name; private string _tagName; private string _namespaceURI; private string _xPath; /// public XmlSourceNodeInformation(int depth, string name, string tagName, string namespaceURI) { _depth = depth; _name = name; _tagName = tagName; _namespaceURI = namespaceURI; _xPath = ""; } /// public int Depth { get { return _depth; } } /// public string Name { get { return _name; } } /// public string TagName { get { return _tagName; } } /// public string NamespaceURI { get { return _namespaceURI; } set { _namespaceURI = value; } } /// public string XPath { get { return _xPath; } set { _xPath = value; } } } } ================================================ FILE: Composite/C1Console/Forms/Foundation/FormTreeCompiler/CompilerGlobals.cs ================================================ using Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompileTreeNodes; namespace Composite.C1Console.Forms.Foundation.FormTreeCompiler { internal sealed class CompilerGlobals { public static readonly string DefaultPropertyName = ":default:"; public static readonly string FormDefinition_TagName = "formdefinition"; public static readonly string Layout_TagName = "layout"; public static readonly string Bindings_TagName = "bindings"; public static readonly string Binding_TagName = "binding"; public static readonly string Bind_TagName = "bind"; public static readonly string Read_TagName = "read"; public static readonly string IfCondition_TagName = "ifCondition"; public static readonly string IfWhenTrue_TagName = "ifWhenTrue"; public static readonly string IfWhenFalse_TagName = "ifWhenFalse"; public static readonly string RootNamespaceURI = "http://www.composite.net/ns/management/bindingforms/1.0"; public static bool IsProducerTag(CompileTreeNode node) { ElementCompileTreeNode element = node as ElementCompileTreeNode; if (null == element) return false; if (IsElementEmbeddedProperty(element)) return false; if (IsReadTag(element)) return false; if (IsBindTag(element)) return false; if (IsBindingTag(element)) return false; if (IsBindingsTag(element)) return false; if (IsLayoutTag(element)) return false; if (IsFormDefinitionTag(element)) return false; return true; } public static bool IsElementEmbeddedProperty(ElementCompileTreeNode element) { return element.XmlSourceNodeInformation.Name.Contains("."); } public static bool IsReadTag(ElementCompileTreeNode element) { return (element.XmlSourceNodeInformation.Name == Read_TagName) && (element.XmlSourceNodeInformation.NamespaceURI == RootNamespaceURI); } public static bool IsBindTag(ElementCompileTreeNode element) { return (element.XmlSourceNodeInformation.Name == Bind_TagName) && (element.XmlSourceNodeInformation.NamespaceURI == RootNamespaceURI); } public static bool IsBindingTag(ElementCompileTreeNode element) { return (element.XmlSourceNodeInformation.Name == Binding_TagName) && (element.XmlSourceNodeInformation.NamespaceURI == RootNamespaceURI); } public static bool IsBindingsTag(ElementCompileTreeNode element) { return (element.XmlSourceNodeInformation.Name == Bindings_TagName) && (element.XmlSourceNodeInformation.NamespaceURI == RootNamespaceURI); } public static bool IsLayoutTag(ElementCompileTreeNode element) { return (element.XmlSourceNodeInformation.Name == Layout_TagName) && (element.XmlSourceNodeInformation.NamespaceURI == RootNamespaceURI); } public static bool IsFormDefinitionTag(ElementCompileTreeNode element) { return (element.XmlSourceNodeInformation.Name == FormDefinition_TagName) && (element.XmlSourceNodeInformation.NamespaceURI == RootNamespaceURI); } public static bool IsElementIfConditionTag(ElementCompileTreeNode element) { return (element.XmlSourceNodeInformation.Name == IfCondition_TagName) && (element.XmlSourceNodeInformation.NamespaceURI == RootNamespaceURI); } public static bool IsElementIfWhenTrueTag(ElementCompileTreeNode element) { return (element.XmlSourceNodeInformation.Name == IfWhenTrue_TagName) && (element.XmlSourceNodeInformation.NamespaceURI == RootNamespaceURI); } public static bool IsElementIfWhenFalseTag(ElementCompileTreeNode element) { return (element.XmlSourceNodeInformation.Name == IfWhenFalse_TagName) && (element.XmlSourceNodeInformation.NamespaceURI == RootNamespaceURI); } public static void GetSplittedPropertyNameFromCompositeName(CompileTreeNode node, out string producerName, out string propertyName) { string[] split = node.XmlSourceNodeInformation.Name.Split('.'); if (2 != split.Length) throw new FormCompileException("Wrong tag format", node.XmlSourceNodeInformation); producerName = split[0]; propertyName = split[1]; } } } ================================================ FILE: Composite/C1Console/Forms/Foundation/FormTreeCompiler/PropertyAssigner.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompileTreeNodes; using Composite.C1Console.Forms.StandardProducerMediators.BuildinProducers; using Composite.Core.Types; using Composite.Data.Validation; using Composite.Functions; using Composite.Functions.Forms; namespace Composite.C1Console.Forms.Foundation.FormTreeCompiler { internal sealed class PropertyAssigner { public static void AssignPropertiesToProducer(ElementCompileTreeNode element, CompileContext compileContext) { List requiredPropertyNames; if (element.Producer != null) { Type producerType = element.Producer.GetType(); requiredPropertyNames = (from prop in producerType.GetProperties() where prop.GetCustomAttributes(typeof(RequiredValueAttribute), true).Length > 0 select prop.Name).ToList(); } else { requiredPropertyNames = new List(); } foreach (PropertyCompileTreeNode namedProperty in element.AllNamedProperties) { SetPropertyOnProducer(element, namedProperty.Name, namedProperty, compileContext); requiredPropertyNames.Remove(namedProperty.Name); } foreach (PropertyCompileTreeNode property in element.DefaultProperties) { string propertyName = GetDefaultPropertyNameOnProducer(element); SetPropertyOnProducer(element, propertyName, property, compileContext); requiredPropertyNames.Remove(propertyName); } if (requiredPropertyNames.Count > 0) { throw new FormCompileException(string.Format("The property named {0} on tag {1} requires a value but have not been assigned a value", requiredPropertyNames[0], element.XmlSourceNodeInformation.TagName), element.XmlSourceNodeInformation); } } private static void SetPropertyOnProducer(ElementCompileTreeNode element, string propertyName, PropertyCompileTreeNode property, CompileContext compileContext) { SetPropertyOnProducer2(element, propertyName, property, compileContext); IUiControl uiControl = element.Producer as IUiControl; if (uiControl != null && property.ClientValidationRules != null) { if (uiControl.ClientValidationRules != null && uiControl.ClientValidationRules.Count > 0) { uiControl.ClientValidationRules.AddRange(property.ClientValidationRules); } else { uiControl.ClientValidationRules = property.ClientValidationRules; } } } private static void SetPropertyOnProducer2(ElementCompileTreeNode element, string propertyName, PropertyCompileTreeNode property, CompileContext compileContext) { if (property.Value is BaseFunctionRuntimeTreeNode && !(element.Producer is FunctionParameterProducer)) { property.Value = ((BaseFunctionRuntimeTreeNode)property.Value).GetValue(); } if (property.InclosingProducerName != "" && element.XmlSourceNodeInformation.Name != property.InclosingProducerName) { throw new FormCompileException(string.Format("The inclosing tag does not match the embedded property tag name {0}", propertyName), element, property); } Type producerType = element.Producer.GetType(); PropertyInfo propertyInfo = producerType.GetProperty(propertyName); if (propertyInfo == null) { if (property.IsNamespaceDeclaration) return; // Ignore it throw new FormCompileException(string.Format("The producer {0} does not have property named {1}", producerType, propertyName), element, property); } MethodInfo getMethodInfo = propertyInfo.GetGetMethod(); if (null == getMethodInfo) throw new FormCompileException(string.Format("The producer {0} does not have a public get for the property named {1}", producerType, propertyName), element, property); bool isReadOrBindProduced = property.Value is BindProducer || property.Value is ReadProducer; if (!isReadOrBindProduced && typeof(IDictionary).IsAssignableFrom(getMethodInfo.ReturnType)) { if (property.Value == null) throw new FormCompileException(string.Format("Can not assign null to {0} dictionary", propertyName), element, property); IDictionary dictionary = getMethodInfo.Invoke(element.Producer, null) as IDictionary; if (dictionary == null) throw new InvalidOperationException(string.Format("Property '{0}' on '{1}' has not been initialized.", propertyName, producerType)); MethodInfo dictionaryAddMethodInfo = dictionary.GetType().GetMethod("Add"); ParameterInfo[] dictionaryAddParmInfo = dictionaryAddMethodInfo.GetParameters(); Type valueType = property.Value.GetType(); if (property.Value is IDictionary) { IDictionary values = (IDictionary)property.Value; IDictionaryEnumerator dictionaryEnumerator = values.GetEnumerator(); while (dictionaryEnumerator.MoveNext()) { dictionary.Add(dictionaryEnumerator.Key, dictionaryEnumerator.Value); } } else { if (property.Value is DictionaryEntry) { var dictionaryEntry = (DictionaryEntry)property.Value; dictionary.Add(dictionaryEntry.Key, dictionaryEntry.Value); } else { PropertyInfo valueKeyProperty = valueType.GetProperty("Key"); PropertyInfo valueValueProperty = valueType.GetProperty("Value"); if (valueKeyProperty == null || valueValueProperty == null) throw new FormCompileException(string.Format("The type {0} can not be assigned to the The parameter type {0} for the method 'Add' on the return type of the property {1} does not match the value type {2}", dictionaryAddParmInfo[0].ParameterType.ToString(), propertyName, property.Value.GetType()), element, property); object dictionaryEntryKey = valueKeyProperty.GetGetMethod().Invoke(property.Value, null); object dictionaryEntryValue = valueValueProperty.GetGetMethod().Invoke(property.Value, null); dictionary.Add(dictionaryEntryKey, dictionaryEntryValue); } } return; } if (!isReadOrBindProduced && typeof(IList).IsAssignableFrom(getMethodInfo.ReturnType)) { IList list = getMethodInfo.Invoke(element.Producer, null) as IList; if (list == null) throw new InvalidOperationException(string.Format("Property '{0}' (an IList) on '{1}' has not been initialized.", propertyName, producerType)); MethodInfo listAddMethodInfo = list.GetType().GetMethod("Add"); ParameterInfo[] listAddParmInfo = listAddMethodInfo.GetParameters(); if (property.Value is IList) { IList values = (IList)property.Value; foreach (object value in values) { if (!listAddParmInfo[0].ParameterType.IsInstanceOfType(value)) { throw new FormCompileException(string.Format( "The parameter type {0} for the method 'Add' on the return type of the property {1} does not match the value type {2}", listAddParmInfo[0].ParameterType, propertyName, property.Value.GetType()), element, property); } list.Add(value); } return; } if (property.Value != null) { if (!listAddParmInfo[0].ParameterType.IsInstanceOfType(property.Value)) { throw new FormCompileException(string.Format( "The parameter type {0} for the method 'Add' on the return type of the property {1} does not match the value type {2}", listAddParmInfo[0].ParameterType, propertyName, property.Value.GetType()), element, property); } list.Add(property.Value); } return; } // Binding values for function parameters if (property.Value is ReadProducer && typeof(IList).IsAssignableFrom(getMethodInfo.ReturnType)) { IList list = getMethodInfo.Invoke(element.Producer, null) as IList; object bindingObject; string source = (property.Value as ReadProducer).source; if (source.Contains(".")) { string[] parts = source.Split('.'); ResolvePropertyBinding(element, property, compileContext, parts[0], parts.Skip(1).ToArray(), out bindingObject); } else { Type bindingType; ResolveBindingObject(element, property, compileContext, source, out bindingObject, out bindingType); } list.Add(new ConstantObjectParameterRuntimeTreeNode("BindedValue", bindingObject)); return; } CheckForMultiblePropertyAdds(element, propertyName, property); MethodInfo setMethodInfo = propertyInfo.GetSetMethod(); if (null == setMethodInfo) throw new FormCompileException(string.Format("The producer {0} does not have a public set for the property named {1}", producerType, propertyName), element, property); object parm; if (null != property.Value) { if (property.Value is BindProducer) { object[] attributes = propertyInfo.GetCustomAttributes(typeof(BindablePropertyAttribute), true); if (attributes.Length == 0) throw new FormCompileException(string.Format("The property {0} on the producer {1}, does not have a bind attribute specified", propertyName, producerType), element, property); BindProducer bind = (BindProducer)property.Value; string source = bind.source; EvaluteBinding(element, source, property, compileContext, getMethodInfo, true); } else if (property.Value is ReadProducer) { ReadProducer bind = (ReadProducer)property.Value; string source = bind.source; EvaluteBinding(element, source, property, compileContext, getMethodInfo, false); } } if (property.Value != null && getMethodInfo.ReturnType.IsInstanceOfType(property.Value)) { if (typeof(IEnumerable).IsAssignableFrom(getMethodInfo.ReturnType) && getMethodInfo.ReturnType != typeof(string) && property.Value is string && ((string)property.Value).Length > 0) { // common err in form: specify a string, where a binding was expected. Problem with IEnumerable: string is converted to char array - hardly the expected result // this is not a critical, but helpful, check throw new InvalidOperationException(string.Format("Unable to cast {0} value '{1}' to type '{2}'", property.Value.GetType().FullName, property.Value, getMethodInfo.ReturnType.FullName)); } parm = property.Value; } else if (property.Value is BaseRuntimeTreeNode) { if (!(element.Producer is IFunctionProducer)) { // Handles C1 function in forms markup BaseRuntimeTreeNode baseRuntimeTreeNode = property.Value as BaseRuntimeTreeNode; object value = baseRuntimeTreeNode.GetValue(); parm = value; } else { parm = property.Value; } } else { parm = ValueTypeConverter.Convert(property.Value, getMethodInfo.ReturnType); } if (element.Producer is LayoutProducer && propertyName == "UiControl") { LayoutProducer layoutProducer = (LayoutProducer)element.Producer; if (layoutProducer.UiControl != null) throw new FormCompileException(string.Format("Only one ui control is allow at the top level of the layout."), element, property); } object[] parms = { parm }; setMethodInfo.Invoke(element.Producer, parms); } private static void CheckForMultiblePropertyAdds(ElementCompileTreeNode element, string propertyName, PropertyCompileTreeNode property) { if (element.AddedProperties.ContainsKey(element.CompilerId)) { XmlSourceNodeInformation foundNode = null; PropertyCompileTreeNode node = element.AddedProperties[element.CompilerId].Find(delegate(PropertyCompileTreeNode pctn) { if (pctn.Name == propertyName) { foundNode = pctn.XmlSourceNodeInformation; return true; } return false; }); if (null != node) throw new FormCompileException(string.Format("Duplicate '{0}' attributes is not allowed", propertyName), element.XmlSourceNodeInformation, property.XmlSourceNodeInformation, foundNode); } else { element.AddedProperties.Add(element.CompilerId, new List()); } element.AddedProperties[element.CompilerId].Add(property); } private static void EvaluteBinding(ElementCompileTreeNode element, string source, PropertyCompileTreeNode property, CompileContext compileContext, MethodInfo sourceGetMethodInfo, bool makeBinding) { if (source.Contains(".")) { string[] parts = source.Split('.'); EvalutePropertyBinding(element, property, compileContext, sourceGetMethodInfo, parts[0], parts.Skip(1).ToArray(), makeBinding); } else { EvaluteObjectBinding(element, property, compileContext, sourceGetMethodInfo, source, makeBinding); } IUiControl uiControl; if (makeBinding && (uiControl = element.Producer as IUiControl) != null) { if (uiControl.SourceBindingPaths == null) { uiControl.SourceBindingPaths = new List(); } uiControl.SourceBindingPaths.Add(source); } } private static void EvaluteObjectBinding(ElementCompileTreeNode element, PropertyCompileTreeNode property, CompileContext compileContext, MethodInfo sourceGetMethodInfo, string bindSourceName, bool makeBinding) { if (makeBinding) { if (compileContext.IsUniqueSourcePropertyBinding(bindSourceName)) throw new FormCompileException(string.Format("{0} binds to {1} which is already property bound. Object bindings to a source object which is property bound is not allowed.", element.XmlSourceNodeInformation.XPath, bindSourceName), element, property); if (!compileContext.RegisterUniqueSourceObjectBinding(bindSourceName)) throw new FormCompileException(string.Format("{0} binds to {1} which is already bound. Multiple bindings to the same source object.", element.XmlSourceNodeInformation.XPath, bindSourceName), element, property); } object bindingObject; Type bindType; ResolveBindingObject(element, property, compileContext, bindSourceName, out bindingObject, out bindType); if (makeBinding) { compileContext.Rebindings.Add(new CompileContext.ObjectRebinding( element.Producer, sourceGetMethodInfo, bindSourceName, bindType) ); } property.Value = bindingObject; property.ClientValidationRules = compileContext.GetBindingsValidationRules(bindSourceName); } private static void ResolveBindingObject(ElementCompileTreeNode element, PropertyCompileTreeNode property, CompileContext compileContext, string bindSourceName, out object bindingObject, out Type bindType) { var bindingProducer = (BindingsProducer) compileContext.BindingsProducer; if (bindingProducer == null) { throw new FormCompileException($"Failed to resolve binding object {bindSourceName} - the binding producer is null", element, property); } string typeName = bindingProducer.GetTypeNameByName(bindSourceName); if (typeName == null) { throw new FormCompileException($"{element.XmlSourceNodeInformation.XPath} binds to an undeclared binding name '{bindSourceName}'. All binding names must be declared in /cms:formdefinition/cms:bindings", element, property); } bindType = TypeManager.TryGetType(typeName); if (bindType == null) { throw new FormCompileException($"The form binding '{bindSourceName}' is declared as an unknown type '{typeName}'", element, property); } bool? optional = bindingProducer.GetOptionalValueByName(bindSourceName); bindingObject = compileContext.GetBindingObject(bindSourceName); if (!optional.Value && !compileContext.BindingObjectExists(bindSourceName)) { throw new FormCompileException($"The binding object named '{bindSourceName}' not found in the input dictionary", element, property); } if (bindingObject != null) { Type bindingObjectType = bindingObject.GetType(); if (!bindType.IsAssignableOrLazyFrom(bindingObjectType)) { throw new FormCompileException($"The binding object named '{bindSourceName}' from the input dictionary is not of expected type '{bindType.FullName}', but '{bindingObjectType.FullName}'", element, property); } } } private static void ResolvePropertyBinding( ElementCompileTreeNode element, PropertyCompileTreeNode property, CompileContext compileContext, string bindSourceName, string[] propertyPath, out object value ) { Type type; object propertyOwner; string propertyName; MethodInfo getMethodInfo, setMethodInfo; ResolvePropertyBinding(element, property, compileContext, bindSourceName, propertyPath, out value, out type, out propertyOwner, out propertyName, out getMethodInfo, out setMethodInfo); } private static void ResolvePropertyBinding( ElementCompileTreeNode element, PropertyCompileTreeNode property, CompileContext compileContext, string bindSourceName, string[] propertyPath, out object value, out Type type, out object propertyOwner, out string propertyName, out MethodInfo getMethodInfo, out MethodInfo setMethodInfo ) { string typeName = ((BindingsProducer)compileContext.BindingsProducer).GetTypeNameByName(bindSourceName); if (typeName == null) { throw new FormCompileException(string.Format("{1} binds to an undeclared binding name '{0}'. All binding names must be declared in /cms:formdefinition/cms:bindings", bindSourceName, element.XmlSourceNodeInformation.XPath), element, property); } Type bindType = TypeManager.TryGetType(typeName); if (bindType == null) { throw new FormCompileException(string.Format("The form binding '{0}' is declared as an unknown type '{1}'", bindSourceName, typeName), element, property); } object bindingObject = compileContext.GetBindingObject(bindSourceName); if (bindingObject == null) { throw new FormCompileException(string.Format("The binding object named '{0}' not found in the input dictionary", bindSourceName), element, property); } Type bindingObjectType = bindingObject.GetType(); if (!bindType.IsAssignableFrom(bindingObjectType)) throw new FormCompileException(string.Format("The binding object named '{0}' from the input dictionary is not of expected type '{1}', but '{2}'", bindSourceName, bindType.FullName, bindingObjectType.FullName), element, property); propertyName = null; getMethodInfo = setMethodInfo = null; type = bindType; propertyOwner = value = bindingObject; for (int i = 0; i < propertyPath.Length; ++i) { string name = propertyName = propertyPath[i]; PropertyInfo propertyInfo = type.GetPropertiesRecursively(x => x.Name == name).FirstOrDefault(); if (propertyInfo == null) { throw new FormCompileException(string.Format("The type {0} does not have a property named {1}", type, propertyName), element, property); } getMethodInfo = propertyInfo.GetGetMethod(); if (getMethodInfo == null) { throw new FormCompileException(string.Format("The type {0} does not have a get property named {1}", type, propertyName), element, property); } setMethodInfo = propertyInfo.GetSetMethod(); propertyOwner = value; type = getMethodInfo.ReturnType; value = getMethodInfo.Invoke(propertyOwner, null); } } private static void EvalutePropertyBinding(ElementCompileTreeNode element, PropertyCompileTreeNode property, CompileContext compileContext, MethodInfo sourceGetMethodInfo, string bindSourceName, string[] propertyPath, bool makeBinding) { if (makeBinding) { bool? optional = ((BindingsProducer)compileContext.BindingsProducer).GetOptionalValueByName(bindSourceName); if (!optional.HasValue) throw new FormCompileException(string.Format("{1} binds to an undeclared binding name '{0}'. All binding names must be declared in /cms:formdefinition/cms:bindings", bindSourceName, element.XmlSourceNodeInformation.XPath), element, property); if (optional.Value) throw new FormCompileException(string.Format("Property binding to the optional object named '{0}' is not allowed", bindSourceName), element, property); if (compileContext.IsUniqueSourceObjectBinding(bindSourceName)) throw new FormCompileException(string.Format("{0} binds to {1} which is already object bound. Property bindings to a source object which is object bound is not allowed.", element.XmlSourceNodeInformation.XPath, bindSourceName), element, property); var uniquePropertyName = new StringBuilder(); for (int i = 0; i < propertyPath.Length; ++i) { uniquePropertyName.Append(propertyPath[i]); } if (!compileContext.RegisterUniqueSourcePropertyBinding(bindSourceName, uniquePropertyName.ToString())) throw new FormCompileException(string.Format("{0} binds to {1} which is already bound. Multiple bindings to the same source object property is not allowed.", element.XmlSourceNodeInformation.XPath, uniquePropertyName), element, property); } object value, propertyOwner; MethodInfo getMethodInfo, setMethodInfo; string propertyName; Type type; ResolvePropertyBinding(element, property, compileContext, bindSourceName, propertyPath, out value, out type, out propertyOwner, out propertyName, out getMethodInfo, out setMethodInfo); if (makeBinding) { if (setMethodInfo == null) throw new FormCompileException(string.Format("The type {0} does not have a set property named {1}", type, propertyName), element, property); compileContext.Rebindings.Add(new CompileContext.PropertyRebinding( element.Producer, sourceGetMethodInfo, propertyOwner, setMethodInfo, getMethodInfo.ReturnType, bindSourceName, propertyName)); } property.Value = value; IUiControl uiControl = element.Producer as IUiControl; if (uiControl != null) { uiControl.ClientValidationRules = ClientValidationRuleFacade.GetClientValidationRules(propertyOwner, propertyName); } } //private static void SetDefaultPropertyOnProducer(ElementCompileTreeNode element, PropertyCompileTreeNode property, CompileContext compileContext) //{ // string propertyName = GetDefaultPropertyNameOnProducer(element); // SetPropertyOnProducer(element, propertyName, property, compileContext); //} private static string GetDefaultPropertyNameOnProducer(ElementCompileTreeNode element) { Type producerType = element.Producer.GetType(); ControlValuePropertyAttribute cvpa = Attribute.GetCustomAttribute(producerType, typeof(ControlValuePropertyAttribute)) as ControlValuePropertyAttribute; if (null == cvpa) throw new FormCompileException(string.Format("The producer {0} does not have a default property specified", producerType.ToString()), element.XmlSourceNodeInformation); return cvpa.PropertyName; } } } ================================================ FILE: Composite/C1Console/Forms/Foundation/PluginFacades/FunctionFactoryPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.C1Console.Events; using Composite.C1Console.Forms.Plugins.FunctionFactory; using Composite.C1Console.Forms.Plugins.FunctionFactory.Runtime; namespace Composite.C1Console.Forms.Foundation.PluginFacades { internal static class FunctionFactoryPluginFacade { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); static FunctionFactoryPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static IFormFunction GetFunction(string namespaceName, string name) { string compositeName = string.Format("{0}->{1}", namespaceName, name); if (false == _resourceLocker.Resources.FactoryCache.ContainsKey(compositeName)) { try { IFormFunctionFactory formFunctionFactory = _resourceLocker.Resources.Factory.Create(compositeName); using (_resourceLocker.Locker) { if (_resourceLocker.Resources.FactoryCache.ContainsKey(compositeName) == false) { _resourceLocker.Resources.FactoryCache.Add(compositeName, formFunctionFactory); } } } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } return _resourceLocker.Resources.FactoryCache[compositeName].CreateFunction(); } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", FunctionFactorySettings.SectionName), ex); } private sealed class Resources { public FunctionFactoryFactory Factory { get; set; } public Dictionary FactoryCache { get; set; } public static void Initialize(Resources resources) { try { resources.Factory = new FunctionFactoryFactory(); } catch (NullReferenceException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } resources.FactoryCache = new Dictionary(); } } } } ================================================ FILE: Composite/C1Console/Forms/Foundation/PluginFacades/ProducerMediatorPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.C1Console.Events; using Composite.C1Console.Forms.Plugins.ProducerMediator; using Composite.C1Console.Forms.Plugins.ProducerMediator.Runtime; namespace Composite.C1Console.Forms.Foundation.PluginFacades { internal static class ProducerMediatorPluginFacade { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); static ProducerMediatorPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static object CreateProducer(IFormChannelIdentifier channel, string namespaceName, string name) { return GetProducerMediator(namespaceName).CreateProducer(channel, namespaceName, name); } public static object EvaluateProducer(string namespaceName, object producer) { return GetProducerMediator(namespaceName).EvaluateProducer(producer); } private static IProducerMediator GetProducerMediator(string namespaceName) { if (false == _resourceLocker.Resources.ProducerMediators.ContainsKey(namespaceName)) { try { IProducerMediator producerMediator = _resourceLocker.Resources.Factory.Create(namespaceName); using (_resourceLocker.Locker) { if (_resourceLocker.Resources.ProducerMediators.ContainsKey(namespaceName) == false) _resourceLocker.Resources.ProducerMediators.Add(namespaceName, producerMediator); } } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } return _resourceLocker.Resources.ProducerMediators[namespaceName]; } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", ProducerMediatorSettings.SectionName), ex); } private sealed class Resources { public ProducerMediatorFactory Factory { get; set; } public Dictionary ProducerMediators { get; set; } public static void Initialize(Resources resources) { try { resources.Factory = new ProducerMediatorFactory(); } catch (NullReferenceException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } resources.ProducerMediators = new Dictionary(); } } } } ================================================ FILE: Composite/C1Console/Forms/Foundation/PluginFacades/UiControlFactoryPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.C1Console.Events; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.Plugins.UiControlFactory.Runtime; namespace Composite.C1Console.Forms.Foundation.PluginFacades { internal static class UiControlFactoryPluginFacade { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); static UiControlFactoryPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static IUiControl CreateControl(IFormChannelIdentifier channel, string namespaceName, string name) { string compositeName = string.Format("{0}->{1}->{2}", channel.ChannelName, namespaceName, name); if (false == _resourceLocker.Resources.FactoryCache.ContainsKey(compositeName)) { try { IUiControlFactory uiControlFactory = _resourceLocker.Resources.Factory.Create(compositeName); using (_resourceLocker.Locker) { if (_resourceLocker.Resources.FactoryCache.ContainsKey(compositeName) == false) { _resourceLocker.Resources.FactoryCache.Add(compositeName, uiControlFactory); } } } catch (ArgumentException ex) { HandleControlConfigurationError(ex, compositeName); } catch (ConfigurationErrorsException ex) { HandleControlConfigurationError(ex, compositeName); } } IUiControlFactory factory = _resourceLocker.Resources.FactoryCache[compositeName]; IUiControl control = factory.CreateControl(); control.UiControlChannel = channel; return control; } public static void GetDebugControlName(IFormChannelIdentifier channel, out string debugControlNamespace, out string debugControlName) { if (null == ConfigurationServices.ConfigurationSource) { throw new ConfigurationErrorsException("Missing configuration"); } UiControlFactorySettings settings = ConfigurationServices.ConfigurationSource.GetSection(UiControlFactorySettings.SectionName) as UiControlFactorySettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", UiControlFactorySettings.SectionName)); } try { debugControlNamespace = settings.Channels[channel.ChannelName].DebugControlNamespace; debugControlName = settings.Channels[channel.ChannelName].DebugControlName; } catch (Exception e) { throw new ConfigurationErrorsException(string.Format("The channel {0} is missing from the configuration", channel.ChannelName), e); } } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", UiControlFactorySettings.SectionName), ex); } private static void HandleControlConfigurationError(Exception ex, string controlCompositeName) { Flush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration for IUiControlFactory '{0}'.", controlCompositeName), ex); } private sealed class Resources { public UiControlFactoryFactory Factory { get; set; } public Dictionary FactoryCache { get; set; } public static void Initialize(Resources resources) { try { resources.Factory = new UiControlFactoryFactory(); } catch (NullReferenceException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } resources.FactoryCache = new Dictionary(); } } } } ================================================ FILE: Composite/C1Console/Forms/Foundation/UiControl.cs ================================================ using System.Collections.Generic; using Composite.Data.Validation.ClientValidationRules; namespace Composite.C1Console.Forms.Foundation { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class UiControl : IUiControl { private string _label = ""; private string _help = ""; /// public UiControl() { this.SourceBindingPaths = new List(); } /// /// The unique and permanent ID of the UiControl instance. /// public string UiControlID { get; set; } /// /// The channel name of the UiControl instance. /// public IFormChannelIdentifier UiControlChannel { get; set; } /// /// The label of the UiControl. Containers may use this value when applying layout to a list of UiControls. /// [FormsProperty()] public virtual string Label { get { return _label; } set { _label = value; } } /// /// Short context sensitive help relevant to the control. /// [FormsProperty()] public virtual string Help { get { return _help; } set { _help = value; } } /// public List ClientValidationRules { get; set; } /// /// When invoked, UiControl Properies that expose bindable data must be updated to reflect user induced state. /// I.e. the Text property of a TextBox UiControl should be assigned the Text property of it's inner control, so /// the Composite.C1Console.Forms Manager can access the users input. /// public virtual void BindStateToControlProperties() { } /// /// A (short) message to the user relating to this control, typically information about missing or /// bad input. /// public List SourceBindingPaths { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/IFormChannelIdentifier.cs ================================================  namespace Composite.C1Console.Forms { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IFormChannelIdentifier { /// string ChannelName { get; } } } ================================================ FILE: Composite/C1Console/Forms/ITestAutomationLocatorInformation.cs ================================================ namespace Composite.C1Console.Forms { /// public interface ITestAutomationLocatorInformation { /// string TestAutomationLocator { get; } } } ================================================ FILE: Composite/C1Console/Forms/IUiControl.cs ================================================ using Composite.Data.Validation.ClientValidationRules; using System.Collections.Generic; namespace Composite.C1Console.Forms { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IUiControl { /// /// UiControls are automatically assigned a unique and permanent UiControlID by the Composite.C1Console.Forms Manager. /// Use the UiControlID to uniquely identify a UiControl instance between build ups. /// string UiControlID { get; set; } /// /// UiControls are automatically assigned the name of the channel they are executed within. /// You can use the channel name when compiling embedded forms. /// IFormChannelIdentifier UiControlChannel { get; set; } /// /// UiControl labels are used by most containers to label the control. /// string Label { get; set; } /// /// UiControl help strings are used by most containers to add context sensitive help to the control. /// string Help { get; set; } /// /// UiControls can use these validation rules to perform client side validaion /// List ClientValidationRules { get; set; } /// /// When invoked, UiControl Properies that expose bindable data must be updated to reflect user induced state. /// I.e. the Text property of a TextBox UiControl should be assigned the Text property of it's inner control, so /// the Composite.C1Console.Forms Manager can access the users input. /// void BindStateToControlProperties(); /// /// The "path to the source" that is bound to this control - i.e. the value written in the "source" property in the form markup. /// List SourceBindingPaths { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/IValidatingUiControl.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Composite.C1Console.Forms { /// /// UiControls can be in a situation where user input can not be converted to the type the control is binding to. /// Rather than throwing an exception, the control can declare that is is in an invalid state and give a message. /// This allow the core to abort saving etc. /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IValidatingUiControl : IUiControl { /// /// This field declare is your control is in a valid state. /// If this returns true, actions like Save and Preview will be canceled. /// bool IsValid { get; } /// /// When in an invalid state this field is expected to describe the reason for this invalid state. The text is intended /// for the end-user and should explain what they did wrong, like "Date format is invalid, use 'yyyy-mm-dd'". /// string ValidationError { get; } } } ================================================ FILE: Composite/C1Console/Forms/Plugins/FunctionFactory/FunctionFactoryData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Forms.Plugins.FunctionFactory { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ConfigurationElementType(typeof(NonConfigurableFunctionFactory))] public class FunctionFactoryData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/C1Console/Forms/Plugins/FunctionFactory/IFormFunction.cs ================================================ namespace Composite.C1Console.Forms.Plugins.FunctionFactory { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IFormFunction { /// object Execute(); } } ================================================ FILE: Composite/C1Console/Forms/Plugins/FunctionFactory/IFunctionFactory.cs ================================================ using Composite.C1Console.Forms.Plugins.FunctionFactory.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.Plugins.FunctionFactory { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [CustomFactory(typeof(FunctionFactoryCustomFactory))] [ConfigurationNameMapper(typeof(FunctionFactoryDefaultNameRetriever))] public interface IFormFunctionFactory { /// IFormFunction CreateFunction(); } } ================================================ FILE: Composite/C1Console/Forms/Plugins/FunctionFactory/NonConfigurableFunctionFactory.cs ================================================ using Microsoft.Practices.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using System; namespace Composite.C1Console.Forms.Plugins.FunctionFactory { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Assembler(typeof(NonConfigurableFunctionFactoryAssembler))] public sealed class NonConfigurableFunctionFactory : FunctionFactoryData { } internal sealed class NonConfigurableFunctionFactoryAssembler : IAssembler { public IFormFunctionFactory Assemble(IBuilderContext context, FunctionFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IFormFunctionFactory)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/C1Console/Forms/Plugins/FunctionFactory/Runtime/FunctionFactoryCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using System; namespace Composite.C1Console.Forms.Plugins.FunctionFactory.Runtime { internal sealed class FunctionFactoryCustomFactory : AssemblerBasedCustomFactory { protected override FunctionFactoryData GetConfiguration(string name, IConfigurationSource configurationSource) { FunctionFactorySettings settings = configurationSource.GetSection(FunctionFactorySettings.SectionName) as FunctionFactorySettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", FunctionFactorySettings.SectionName)); } int index = name.IndexOf("->"); string namespaceName = name.Substring(0, index); string tag = name.Substring(index + 2); NamespaceConfigurationElement namespaceElement = settings.Namespaces[namespaceName]; if (null == namespaceElement) throw new ConfigurationErrorsException(string.Format("The namespace {0} is missing from the configuration", namespaceName)); return namespaceElement.Factories.Get(tag); } } } ================================================ FILE: Composite/C1Console/Forms/Plugins/FunctionFactory/Runtime/FunctionFactoryDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.Plugins.FunctionFactory.Runtime { internal sealed class FunctionFactoryDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/C1Console/Forms/Plugins/FunctionFactory/Runtime/FunctionFactoryFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.Plugins.FunctionFactory.Runtime { internal sealed class FunctionFactoryFactory : NameTypeFactoryBase { public FunctionFactoryFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/C1Console/Forms/Plugins/FunctionFactory/Runtime/FunctionFactorySettings.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Composite.Core.Configuration; namespace Composite.C1Console.Forms.Plugins.FunctionFactory.Runtime { internal sealed class FunctionFactorySettings : SerializableConfigurationSection { public const string SectionName = "Composite.C1Console.Forms.Plugins.FunctionFactoryConfiguration"; private const string _namespacesProperty = "Namespaces"; [ConfigurationProperty(_namespacesProperty, IsRequired = true)] public NamespaceConfigurationElementCollection Namespaces { get { return (NamespaceConfigurationElementCollection)base[_namespacesProperty]; } } } internal sealed class NamespaceConfigurationElement : NamedConfigurationElement { private const string _factoriesPropertyName = "Factories"; [ConfigurationProperty(_factoriesPropertyName, IsRequired=true)] public NameTypeManagerTypeConfigurationElementCollection Factories { get { return (NameTypeManagerTypeConfigurationElementCollection)base[_factoriesPropertyName]; } } } internal sealed class NamespaceConfigurationElementCollection : ConfigurationElementCollection { public NamespaceConfigurationElementCollection() { AddElementName = "Namespace"; } public void Add(NamespaceConfigurationElement element) { BaseAdd(element); } new public NamespaceConfigurationElement this[string Name] { get { return (NamespaceConfigurationElement)BaseGet(Name); } } protected override ConfigurationElement CreateNewElement() { return new NamespaceConfigurationElement(); } protected override object GetElementKey(ConfigurationElement element) { return (element as NamespaceConfigurationElement).Name; } } } ================================================ FILE: Composite/C1Console/Forms/Plugins/ProducerMediator/IProducerMediator.cs ================================================ using Composite.C1Console.Forms.Plugins.ProducerMediator.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.Plugins.ProducerMediator { [CustomFactory(typeof(ProducerMediatorCustomFactory))] [ConfigurationNameMapper(typeof(ProducerMediatorDefaultNameRetriever))] internal interface IProducerMediator { object CreateProducer(IFormChannelIdentifier channel, string namespaceName, string name); object EvaluateProducer(object producer); } } ================================================ FILE: Composite/C1Console/Forms/Plugins/ProducerMediator/NonConfigurableProducerMediator.cs ================================================ using System; using Microsoft.Practices.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.Plugins.ProducerMediator { [Assembler(typeof(NonConfigurableProducerMediatorAssembler))] internal sealed class NonConfigurableProducerMediator : ProducerMediatorData { } internal sealed class NonConfigurableProducerMediatorAssembler : IAssembler { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IProducerMediator Assemble(IBuilderContext context, ProducerMediatorData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IProducerMediator)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/C1Console/Forms/Plugins/ProducerMediator/ProducerMediatorData.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Forms.Plugins.ProducerMediator { internal class ProducerMediatorData : NameTypeConfigurationElement { } } ================================================ FILE: Composite/C1Console/Forms/Plugins/ProducerMediator/Runtime/ProducerMediatorCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.Plugins.ProducerMediator.Runtime { internal sealed class ProducerMediatorCustomFactory : AssemblerBasedCustomFactory { protected override ProducerMediatorData GetConfiguration(string name, IConfigurationSource configurationSource) { ProducerMediatorSettings settings = configurationSource.GetSection(ProducerMediatorSettings.SectionName) as ProducerMediatorSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", ProducerMediatorSettings.SectionName)); } return settings.Mediators.Get(name); } } } ================================================ FILE: Composite/C1Console/Forms/Plugins/ProducerMediator/Runtime/ProducerMediatorDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.Plugins.ProducerMediator.Runtime { internal sealed class ProducerMediatorDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/C1Console/Forms/Plugins/ProducerMediator/Runtime/ProducerMediatorFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.Plugins.ProducerMediator.Runtime { internal sealed class ProducerMediatorFactory : NameTypeFactoryBase { public ProducerMediatorFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/C1Console/Forms/Plugins/ProducerMediator/Runtime/ProducerMediatorSettings.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Forms.Plugins.ProducerMediator.Runtime { internal sealed class ProducerMediatorSettings : SerializableConfigurationSection { public const string SectionName = "Composite.C1Console.Forms.Plugins.ProducerMediatorConfiguration"; private const string _mediatorsPropertyName = "Mediators"; [ConfigurationProperty(_mediatorsPropertyName)] public NameTypeConfigurationElementCollection Mediators { get { return (NameTypeConfigurationElementCollection)base[_mediatorsPropertyName]; } } } } ================================================ FILE: Composite/C1Console/Forms/Plugins/UiControlFactory/IUiControlFactory.cs ================================================ using Composite.C1Console.Forms.Plugins.UiControlFactory.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.Plugins.UiControlFactory { [CustomFactory(typeof(UiControlFactoryCustomFactory))] [ConfigurationNameMapper(typeof(UiControlFactoryDefaultNameRetriever))] internal interface IUiControlFactory { IUiControl CreateControl(); } } ================================================ FILE: Composite/C1Console/Forms/Plugins/UiControlFactory/NonConfigurableUiControlFactoryAssembler.cs ================================================ using System; using Microsoft.Practices.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.Plugins.UiControlFactory { internal sealed class NonConfigurableUiControlFactoryAssembler : IAssembler { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IUiControlFactory)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/C1Console/Forms/Plugins/UiControlFactory/Runtime/UiControlFactoryCustomFactory.cs ================================================ using System; using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.Plugins.UiControlFactory.Runtime { internal sealed class UiControlFactoryCustomFactory : AssemblerBasedCustomFactory { protected override UiControlFactoryData GetConfiguration(string name, IConfigurationSource configurationSource) { UiControlFactorySettings settings = configurationSource.GetSection(UiControlFactorySettings.SectionName) as UiControlFactorySettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", UiControlFactorySettings.SectionName)); } int index1 = name.IndexOf("->"); int index2 = name.IndexOf("->", index1 + 1); string channelName = name.Substring(0, index1); string namespaceName = name.Substring(index1 + 2, index2 - index1 - 2); string tag = name.Substring(index2 + 2); ChannelConfigurationElement channelElement = settings.Channels[channelName]; if (null == channelElement) throw new ConfigurationErrorsException(string.Format("The channel {0} is missing from the configuration", channelName)); NamespaceConfigurationElement namespaceElement = channelElement.Namespaces[namespaceName]; if (null == namespaceElement) throw new ConfigurationErrorsException(string.Format("The namespace {0} is missing from the configuration of channel {1}", namespaceName, channelName)); return namespaceElement.Factories.Get(tag); } } } ================================================ FILE: Composite/C1Console/Forms/Plugins/UiControlFactory/Runtime/UiControlFactoryDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.Plugins.UiControlFactory.Runtime { internal sealed class UiControlFactoryDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/C1Console/Forms/Plugins/UiControlFactory/Runtime/UiControlFactoryFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.Plugins.UiControlFactory.Runtime { internal sealed class UiControlFactoryFactory : NameTypeFactoryBase { public UiControlFactoryFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/C1Console/Forms/Plugins/UiControlFactory/Runtime/UiControlFactorySettings.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Composite.Core.Configuration; namespace Composite.C1Console.Forms.Plugins.UiControlFactory.Runtime { internal sealed class UiControlFactorySettings : SerializableConfigurationSection { public const string SectionName = "Composite.C1Console.Forms.Plugins.UiControlFactoryConfiguration"; private const string _channelsProperty = "Channels"; [ConfigurationProperty(_channelsProperty, IsRequired = true)] public ChannelConfigurationElementCollection Channels { get { return (ChannelConfigurationElementCollection)base[_channelsProperty]; } } } internal sealed class NamespaceConfigurationElement : NamedConfigurationElement { private const string _factoriesPropertyName = "Factories"; [ConfigurationProperty(_factoriesPropertyName, IsRequired = true)] public NameTypeManagerTypeConfigurationElementCollection Factories { get { return (NameTypeManagerTypeConfigurationElementCollection)base[_factoriesPropertyName]; } } } internal sealed class NamespaceConfigurationElementCollection : ConfigurationElementCollection { public NamespaceConfigurationElementCollection() : base() { AddElementName = "Namespace"; } public void Add(NamedConfigurationElement element) { BaseAdd(element); } new public NamespaceConfigurationElement this[string Name] { get { return (NamespaceConfigurationElement)BaseGet(Name); } } protected override ConfigurationElement CreateNewElement() { return new NamespaceConfigurationElement(); } protected override object GetElementKey(ConfigurationElement element) { return (element as NamespaceConfigurationElement).Name; } } internal sealed class ChannelConfigurationElement : NamedConfigurationElement { private const string _debugControlNamespacePropertyName = "debugControlNamespace"; [ConfigurationProperty(_debugControlNamespacePropertyName, IsRequired = true)] public string DebugControlNamespace { get { return (string)base[_debugControlNamespacePropertyName]; } set { base[_debugControlNamespacePropertyName] = value; } } private const string _debugControlNamePropertyName = "debugControlName"; [ConfigurationProperty(_debugControlNamePropertyName, IsRequired = true)] public string DebugControlName { get { return (string)base[_debugControlNamePropertyName]; } set { base[_debugControlNamePropertyName] = value; } } private const string _namespacesProperty = "Namespaces"; [ConfigurationProperty(_namespacesProperty, IsRequired = true)] public NamespaceConfigurationElementCollection Namespaces { get { return (NamespaceConfigurationElementCollection)base[_namespacesProperty]; } } } internal sealed class ChannelConfigurationElementCollection : ConfigurationElementCollection { public ChannelConfigurationElementCollection() : base() { AddElementName = "Channel"; } public void Add(ChannelConfigurationElement channelConfigurationElement) { BaseAdd(channelConfigurationElement); } new public ChannelConfigurationElement this[string Name] { get { return (ChannelConfigurationElement)BaseGet(Name); } } protected override ConfigurationElement CreateNewElement() { return new ChannelConfigurationElement(); } protected override object GetElementKey(ConfigurationElement element) { return (element as ChannelConfigurationElement).Name; } } } ================================================ FILE: Composite/C1Console/Forms/Plugins/UiControlFactory/UiControlFactoryData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Forms.Plugins.UiControlFactory { [ConfigurationElementType(typeof(NonConfigurableUiControlFactoryAssembler))] internal class UiControlFactoryData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/C1Console/Forms/ReadBindingControlValueOverload.cs ================================================ using System; namespace Composite.C1Console.Forms { /// /// If the "inner value" is a bindings read, then this defines an property that will be assigned to. /// This is an overload/special case handling of /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] internal sealed class ReadBindingControlValueOverload : Attribute { public ReadBindingControlValueOverload(string propertyName) { this.PropertyName = propertyName; } public string PropertyName { get; private set; } } } ================================================ FILE: Composite/C1Console/Forms/RequiredValueAttribute.cs ================================================ using System; namespace Composite.C1Console.Forms { /// [AttributeUsage(AttributeTargets.Property, AllowMultiple=false, Inherited=true)] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class RequiredValueAttribute : Attribute { } } ================================================ FILE: Composite/C1Console/Forms/SchemaBuilder.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Xml.Linq; using Composite.Core.Configuration; using Composite.Core.Xml; namespace Composite.C1Console.Forms { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class SchemaInfo { /// public enum FormSchemaType { /// Uicontrols = 0, /// Functions = 1 } internal SchemaInfo(IFormChannelIdentifier channelIdentifier, XNamespace namespaceObj, XDocument schema) { this.ChannelIdentifier = channelIdentifier; this.Namespace = namespaceObj; this.Schema = schema; this.SchemaType = FormSchemaType.Uicontrols; } internal SchemaInfo(XNamespace namespaceObj, XDocument schema) { this.Namespace = namespaceObj; this.Schema = schema; this.SchemaType = FormSchemaType.Functions; } /// public IFormChannelIdentifier ChannelIdentifier { get; private set; } /// public XNamespace Namespace { get; private set; } /// public XDocument Schema { get; private set; } /// public FormSchemaType SchemaType { get; private set; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class SchemaBuilder { /// public static IEnumerable GenerateAllDynamicSchemas() { List generatedSchemas = new List(); ElementInformationExtractor worker = new ElementInformationExtractor(ConfigurationServices.FileConfigurationSourcePath); var channels = from c in worker.GetUiControlDescriptors() group c by c.ChannelName into g select g; foreach (var channel in channels) { var xmlnss = from c in channel group c by c.NamespaceName into g select g; foreach (var xmlns in xmlnss) { XDocument schema = worker.GetXsd( xmlns, xmlns.Key); generatedSchemas.Add(new SchemaInfo(new ChannelIdentifier(channel.Key), xmlns.Key, schema)); } } var namespaceBasedFunctionLookup = from c in worker.GetFunctionDescriptors() group c by c.NamespaceName into g select g; foreach (var xmlns in namespaceBasedFunctionLookup) { XDocument schema = worker.GetXsd(xmlns, xmlns.Key); generatedSchemas.Add(new SchemaInfo(xmlns.Key, schema)); } return generatedSchemas; } /// public static XDocument GenerateUiControlSchema(IFormChannelIdentifier channelIdentifier, XNamespace controlNamespace) { Dictionary schemas = new Dictionary(); ElementInformationExtractor worker = new ElementInformationExtractor(ConfigurationServices.FileConfigurationSourcePath); var elementDescriptors = from descriptor in worker.GetUiControlDescriptors() where descriptor.ChannelName == channelIdentifier.ChannelName && descriptor.NamespaceName == controlNamespace select descriptor; return worker.GetXsd(elementDescriptors, controlNamespace); } private class ChannelIdentifier : IFormChannelIdentifier { public ChannelIdentifier(string name) { this.ChannelName = name; } public string ChannelName { get; private set; } } private class ElementInformationExtractor { private string configurationFilePath; private List UiContolNs; private List FunctionNs; private XDocument configDoc; public string OutputDir { get; set; } internal IEnumerable GetUiControlDescriptors() { var uiControlConfigRoot = configDoc.Descendants("Composite.C1Console.Forms.Plugins.UiControlFactoryConfiguration").Single(); var controlInfos = from controlElement in uiControlConfigRoot.Descendants("add") select new { Name = controlElement.Attribute("name").Value, NamespaceName = controlElement.Parent.Parent.Attribute("name").Value, ChannelName = controlElement.Parent.Parent.Parent.Parent.Attribute("name").Value }; return from controlInfo in controlInfos select new ElementDescriptor { ChannelName = controlInfo.ChannelName, NamespaceName = controlInfo.NamespaceName, Name = controlInfo.Name, ElementType = Composite.C1Console.Forms.FormFactoryService.CreateControl(controlInfo.ChannelName, controlInfo.NamespaceName, controlInfo.Name).GetType() }; } public ElementInformationExtractor(string configurationFilePath) { this.configurationFilePath = configurationFilePath; configDoc = XDocumentUtils.Load(configurationFilePath); //Quick code for nameSpaces UiContolNs = (from c in GetUiControlDescriptors() group c by c.NamespaceName into g select g.Key).ToList(); FunctionNs = (from c in GetFunctionDescriptors() group c by c.NamespaceName into g select g.Key).ToList(); } private XElement GetXsdSequence(PropertyInfo property, XNamespace xsd, XNamespace targetNamespace) { var isContainer = typeof(List) == property.PropertyType || typeof(System.Object) == property.PropertyType; return new XElement(xsd + "sequence", (property.PropertyType.GetInterface("IList") != null) ? new XAttribute("maxOccurs", "unbounded") : new XAttribute("maxOccurs", "1"), new XAttribute("minOccurs", "0"), new XElement(xsd + "choice", // if Element is bindable ((property.GetCustomAttributes(typeof(Composite.C1Console.Forms.BindablePropertyAttribute), true)).Count() > 0) ? new XElement(xsd + "element", new XAttribute("ref", "cms:bind") ) : null, new XElement(xsd + "element", new XAttribute("ref", "cms:read") ), //UiControls isContainer ? new XElement(xsd + "group", new XAttribute("ref", "ElementList") ) : null, //Other UiControls isContainer ? from ns in UiContolNs where ns != targetNamespace.NamespaceName select new XElement(xsd + "any", new XAttribute("namespace", ns) ) : null, //Functions from ns in FunctionNs where ns != targetNamespace.NamespaceName select new XElement(xsd + "any", new XAttribute("namespace", ns) ) ) ); } private XElement GetXsdContolValue(ElementDescriptor element, XNamespace xsd, XNamespace targetNamespace) { try { ControlValuePropertyAttribute controlValue = (ControlValuePropertyAttribute)(element.ElementType.GetCustomAttributes(typeof(ControlValuePropertyAttribute), true).First()); return GetXsdSequence(element.ElementType.GetProperty(controlValue.PropertyName), xsd, targetNamespace); } catch (Exception) { } return null; } private XAttribute GetXsdAttributeType(PropertyInfo property) { if (property.PropertyType == typeof(int)) { return new XAttribute("type", "xsd:int"); } if (property.PropertyType == typeof(Boolean)) { return new XAttribute("type", "xsd:boolean"); } return new XAttribute("type", "xsd:string"); } /// /// Generate XSD file by List of ElementDescriptor /// /// List of ElementDescriptor /// Namespace /// XSD File public XDocument GetXsd(IEnumerable xmlns, XNamespace targetNamespace/*, List functionNss*/) { XNamespace xsd = "http://www.w3.org/2001/XMLSchema"; var controlsList = from element in xmlns select new XElement(xsd + "element", new XAttribute("name", element.Name), new XAttribute("type", element.Name) ); XDocument doc = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XElement(xsd + "schema", new XAttribute(XNamespace.Xmlns + "xsd", xsd.NamespaceName), new XAttribute(XNamespace.Xmlns + "cms", "http://www.composite.net/ns/management/bindingforms/1.0"), new XAttribute("targetNamespace", targetNamespace.NamespaceName), new XAttribute("xmlns", targetNamespace.NamespaceName), new XAttribute("elementFormDefault", "qualified"), new XElement(xsd + "import", new XAttribute("namespace", "http://www.w3.org/XML/1998/namespace")//, //new XAttribute("schemaLocation", "xml.xsd") ), new XElement(xsd + "import", new XAttribute("namespace", "http://www.composite.net/ns/management/bindingforms/1.0"), new XAttribute("schemaLocation", "bindingforms10.xsd") ), controlsList, new XElement(xsd + "group", new XAttribute("name", "ElementList"), new XElement(xsd + "sequence", new XElement(xsd + "choice", new XAttribute("minOccurs", "0"), controlsList ) ) ), from element in xmlns select new XElement( xsd + "complexType", new XAttribute("name", element.Name), new XAttribute("mixed", "true"), new XElement(xsd + "sequence", new XAttribute("maxOccurs", "unbounded"), new XAttribute("minOccurs", "0"), (element.ElementType.GetProperties().Where( f=> f.GetCustomAttributes(typeof(FormsPropertyAttribute), true).Any()).Any()) ? new XElement(xsd + "choice", from property in element.ElementType.GetProperties() where property.CanWrite && property.GetCustomAttributes(typeof(FormsPropertyAttribute), true).Any() select new XElement(xsd + "element", new XAttribute("name", element.Name + "." + property.Name), new XElement(xsd + "complexType", new XAttribute("mixed", "true"), GetXsdSequence(property, xsd, targetNamespace) ) ), GetXsdContolValue(element, xsd, targetNamespace) ) : null ), from property in element.ElementType.GetProperties() where property.CanWrite && property.GetCustomAttributes(typeof(FormsPropertyAttribute), true).Any() && property.PropertyType.GetInterface("IList") == null select new XElement(xsd + "attribute", new XAttribute("name", property.Name), GetXsdAttributeType(property), new XAttribute("use", "optional") ) ) ) ); return doc; } /// /// For all channels and namespaces of elements generate XSD file /// /// public void GenerateUiControls() { var channels = from c in GetUiControlDescriptors() group c by c.ChannelName into g select g; foreach (var channel in channels) { int countChannels = 0; var xmlnss = from c in channel group c by c.NamespaceName into g select g; foreach (var xmlns in xmlnss) { XDocument uicontrols = GetXsd( xmlns, xmlns.Key ); uicontrols.SaveToFile(OutputDir + channel.Key + ((countChannels++ > 0) ? "." + countChannels : "") + ".xsd"); } } } /// /// For all namespaces of functions generate XSD file /// /// public void GenerateFunctions() { var xmlnss = from c in GetFunctionDescriptors().ToList() group c by c.NamespaceName into g select g; int countChannels = 0; foreach (var xmlns in xmlnss) { XDocument uicontrols = GetXsd( xmlns, xmlns.Key ); uicontrols.SaveToFile(OutputDir + "Plugins.Function" + ((countChannels++ > 0) ? "." + countChannels : "") + ".xsd"); } } internal IEnumerable GetFunctionDescriptors() { var uiControlConfigRoot = configDoc.Descendants("Composite.C1Console.Forms.Plugins.FunctionFactoryConfiguration").Single(); var functionInfos = from functionlElement in uiControlConfigRoot.Descendants("add") select new { Name = functionlElement.Attribute("name").Value, NamespaceName = functionlElement.Parent.Parent.Attribute("name").Value, }; return from functionInfo in functionInfos select new ElementDescriptor { NamespaceName = functionInfo.NamespaceName, Name = functionInfo.Name, ElementType = Composite.C1Console.Forms.FormFactoryService.GetFunction(functionInfo.NamespaceName, functionInfo.Name).GetType() }; } } internal class ElementDescriptor { public string ChannelName { get; set; } public string NamespaceName { get; set; } public string Name { get; set; } public Type ElementType { get; set; } } } } ================================================ FILE: Composite/C1Console/Forms/StandardProducerMediators/BuildinProducerMediator.cs ================================================ using System; using Composite.C1Console.Forms.Plugins.ProducerMediator; using Composite.C1Console.Forms.StandardProducerMediators.BuildinProducers; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.StandardProducerMediators { [ConfigurationElementType(typeof(BuildinProducerMediatorData))] internal sealed class BuildinProducerMediator : IProducerMediator { public object CreateProducer(IFormChannelIdentifier channel, string namespaceName, string name) { switch (name) { case "if": return new IfProducer(); case "ifCondition": return new IfConditionProducer(); case "ifWhenTrue": return new IfWhenTrueProducer(); case "ifWhenFalse": return new IfWhenFalseProducer(); case "read": return new ReadProducer(); case "bind": return new BindProducer(); case "binding": return new BindingProducer(); case "bindings": return new BindingsProducer(); case "layout": return new LayoutProducer(); case "evalfunc": return new EvalFuncProducer(); } throw new NotImplementedException(string.Format("Unknown buildin producer type {0}", name)); } public object EvaluateProducer(object producer) { if ( false == (producer is IBuildinProducer)) { throw new ArgumentException(string.Format("The parameter type {0} did not match the expected type {1}", producer.GetType().ToString(), typeof(IBuildinProducer).ToString()), "producer"); } return producer; } } [Assembler(typeof(NonConfigurableProducerMediatorAssembler))] internal sealed class BuildinProducerMediatorData : ProducerMediatorData { } } ================================================ FILE: Composite/C1Console/Forms/StandardProducerMediators/BuildinProducers/BindProducer.cs ================================================ namespace Composite.C1Console.Forms.StandardProducerMediators.BuildinProducers { internal sealed class BindProducer : IBuildinProducer { private string _source; internal BindProducer() { } public string source { get { return _source; } set { _source = value; } } } } ================================================ FILE: Composite/C1Console/Forms/StandardProducerMediators/BuildinProducers/BindingProducer.cs ================================================ namespace Composite.C1Console.Forms.StandardProducerMediators.BuildinProducers { internal sealed class BindingProducer : IBuildinProducer { private string _type; private string _name; private bool _optional = false; internal BindingProducer() { } public string type { get { return _type; } set { _type = value; } } public string name { get { return _name; } set { _name = value; } } public bool optional { get { return _optional; } set { _optional = value; } } } } ================================================ FILE: Composite/C1Console/Forms/StandardProducerMediators/BuildinProducers/BindingsProducer.cs ================================================ using System; using System.Collections.Generic; using System.Linq; namespace Composite.C1Console.Forms.StandardProducerMediators.BuildinProducers { [ControlValueProperty("bindings")] internal sealed class BindingsProducer : IBuildinProducer { private List _bindings = new List(); internal BindingsProducer() { } public List bindings { get { return _bindings; } set { _bindings = value; } } public string GetTypeNameByName(string name) { return _bindings.FirstOrDefault(bp => bp.name == name)?.type; } public bool? GetOptionalValueByName(string name) { return _bindings.FirstOrDefault(bp => bp.name == name)?.optional; } } } ================================================ FILE: Composite/C1Console/Forms/StandardProducerMediators/BuildinProducers/EvalFuncProducer.cs ================================================ using System.Xml.Linq; using Composite.Functions; using Composite.Core.Xml; using System.Text; namespace Composite.C1Console.Forms.StandardProducerMediators.BuildinProducers { [ControlValueProperty("Markup")] internal sealed class EvalFuncProducer : IBuildinProducer { public XElement Markup { get; set; } public override string ToString() { BaseRuntimeTreeNode baseRuntimeTreeNode = FunctionTreeBuilder.Build(this.Markup); XDocument result = (XDocument)baseRuntimeTreeNode.GetValue(); XhtmlDocument xhtmlDocument = result as XhtmlDocument; if (xhtmlDocument != null) { StringBuilder sb = new StringBuilder(); foreach (XElement element in xhtmlDocument.Body.Elements()) { sb.AppendLine(element.ToString()); } return sb.ToString(); } return result.ToString(); } } } ================================================ FILE: Composite/C1Console/Forms/StandardProducerMediators/BuildinProducers/IBuildinProducer.cs ================================================ namespace Composite.C1Console.Forms.StandardProducerMediators.BuildinProducers { internal interface IBuildinProducer { } } ================================================ FILE: Composite/C1Console/Forms/StandardProducerMediators/BuildinProducers/IfConditionProducer.cs ================================================ namespace Composite.C1Console.Forms.StandardProducerMediators.BuildinProducers { [ControlValueProperty("Condition")] internal sealed class IfConditionProducer : IBuildinProducer { private bool _condition; internal IfConditionProducer() { } public bool Condition { get { return _condition; } set { _condition = value; } } } } ================================================ FILE: Composite/C1Console/Forms/StandardProducerMediators/BuildinProducers/IfProducer.cs ================================================ namespace Composite.C1Console.Forms.StandardProducerMediators.BuildinProducers { internal sealed class IfProducer : IBuildinProducer { internal IfProducer() { } } } ================================================ FILE: Composite/C1Console/Forms/StandardProducerMediators/BuildinProducers/IfWhenFalseProducer.cs ================================================ using System.Collections.Generic; namespace Composite.C1Console.Forms.StandardProducerMediators.BuildinProducers { [ControlValueProperty("Result")] internal sealed class IfWhenFalseProducer : IBuildinProducer { private List _result = new List(); internal IfWhenFalseProducer() { } public List Result { get { return _result; } set { _result = value; } } } } ================================================ FILE: Composite/C1Console/Forms/StandardProducerMediators/BuildinProducers/IfWhenTrueProducer.cs ================================================ using System.Collections.Generic; namespace Composite.C1Console.Forms.StandardProducerMediators.BuildinProducers { [ControlValueProperty("Result")] internal sealed class IfWhenTrueProducer : IBuildinProducer { private List _result = new List(); internal IfWhenTrueProducer() { } public List Result { get { return _result; } set { _result = value; } } } } ================================================ FILE: Composite/C1Console/Forms/StandardProducerMediators/BuildinProducers/LayoutProducer.cs ================================================ namespace Composite.C1Console.Forms.StandardProducerMediators.BuildinProducers { [ControlValueProperty(nameof(UiControl))] internal sealed class LayoutProducer : IBuildinProducer { public IUiControl UiControl { get; set; } public string label { get; set; } public string tooltip { get; set; } public string iconhandle { get; set; } } } ================================================ FILE: Composite/C1Console/Forms/StandardProducerMediators/BuildinProducers/ReadProducer.cs ================================================ namespace Composite.C1Console.Forms.StandardProducerMediators.BuildinProducers { internal sealed class ReadProducer : IBuildinProducer { private string _source; internal ReadProducer() { } public string source { get { return _source; } set { _source = value; } } } } ================================================ FILE: Composite/C1Console/Forms/StandardProducerMediators/FunctionProducerMediator.cs ================================================ using System; using Composite.C1Console.Forms.Foundation.PluginFacades; using Composite.C1Console.Forms.Plugins.FunctionFactory; using Composite.C1Console.Forms.Plugins.ProducerMediator; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.StandardProducerMediators { [ConfigurationElementType(typeof(FunctionProducerMediatorData))] internal sealed class FunctionProducerMediator : IProducerMediator { public object CreateProducer(IFormChannelIdentifier channel, string namespaceName, string name) { return FunctionFactoryPluginFacade.GetFunction(namespaceName, name); } public object EvaluateProducer(object producer) { if (false == (producer is IFormFunction)) { throw new ArgumentException(string.Format("The parameter type {0} did not match the expected type {1}", producer.GetType().ToString(), typeof(IFormFunction).ToString()), "producer"); } return (producer as IFormFunction).Execute(); } } [Assembler(typeof(NonConfigurableProducerMediatorAssembler))] internal sealed class FunctionProducerMediatorData : ProducerMediatorData { } } ================================================ FILE: Composite/C1Console/Forms/StandardProducerMediators/UiControlProducerMediator.cs ================================================ using System; using Composite.C1Console.Forms.Foundation.PluginFacades; using Composite.C1Console.Forms.Plugins.ProducerMediator; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Forms.StandardProducerMediators { [ConfigurationElementType(typeof(UiControlProducerMediatorData))] internal sealed class UiControlProducerMediator : IProducerMediator { public object CreateProducer(IFormChannelIdentifier channel, string namespaceName, string name) { return UiControlFactoryPluginFacade.CreateControl(channel, namespaceName, name); } public object EvaluateProducer(object producer) { if (false == (producer is IUiControl)) { throw new ArgumentException(string.Format("The parameter type {0} did not match the expected type {1}", producer.GetType().ToString(), typeof(IUiControl).ToString()), "producer"); } return producer; } } [Assembler(typeof(NonConfigurableProducerMediatorAssembler))] internal sealed class UiControlProducerMediatorData : ProducerMediatorData { } } ================================================ FILE: Composite/C1Console/Forms/WebChannel/IClickableTabPanelControl.cs ================================================ using System.Web.UI; namespace Composite.C1Console.Forms.WebChannel { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IClickableTabPanelControl { /// string CustomTabId { get; } /// Control EventControl { get; } } } ================================================ FILE: Composite/C1Console/Forms/WebChannel/IWebUiContainer.cs ================================================ using Composite.C1Console.Forms.Flows; using System.Collections.Generic; namespace Composite.C1Console.Forms.WebChannel { internal interface IWebUiContainer : IUiContainer { void ShowFieldMessages(Dictionary clientIDPathedMessages); } } ================================================ FILE: Composite/C1Console/Forms/WebChannel/IWebUiControl.cs ================================================ using System.Web.UI; namespace Composite.C1Console.Forms.WebChannel { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IWebUiControl : IUiControl { /// Control BuildWebControl(); /// void InitializeViewState(); /// string ClientName { get; } /// bool IsFullWidthControl { get; } } } ================================================ FILE: Composite/C1Console/Forms/WebChannel/WebManagementChannel.cs ================================================  namespace Composite.C1Console.Forms.WebChannel { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class WebManagementChannel : IFormChannelIdentifier { private static IFormChannelIdentifier _instance = new WebManagementChannel(); /// public static IFormChannelIdentifier Identifier { get { return _instance; } } private WebManagementChannel() { } /// public string ChannelName { get { return "AspNet.Management"; } } /// public override string ToString() { throw new System.Exception("Treated as string here!"); } } } ================================================ FILE: Composite/C1Console/Forms/WebChannel/WebStandardsChannel.cs ================================================  namespace Composite.C1Console.Forms.WebChannel { internal class WebStandardsChannel : IFormChannelIdentifier { private static IFormChannelIdentifier _instance = new WebStandardsChannel(); public static IFormChannelIdentifier Identifier { get { return _instance; } } private WebStandardsChannel() { } public string ChannelName { get { return "AspNet.WebStandards"; } } public override string ToString() { throw new System.Exception("Treated as string here!"); } } } ================================================ FILE: Composite/C1Console/Forms/WebChannel/WebUiHelpers.cs ================================================ //using System.Web.UI; //using System.Web.UI.WebControls; //using Composite.Core.WebClient.UiControlLib; //namespace Composite.C1Console.Forms.WebChannel //{ // internal sealed class WebUiHelpers // { // public static Control WrapInUpdatePanel( Control content, bool childrenAsUpdateTriggers ) // { // BindingUpdatePanel updatePanel = new BindingUpdatePanel(); // updatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional; // updatePanel.ChildrenAsTriggers = childrenAsUpdateTriggers; // updatePanel.ID = content.ID + "UpdatePanel"; // updatePanel.ContentTemplateContainer.Controls.Add( content ); // return updatePanel; // } // } //} ================================================ FILE: Composite/C1Console/RichContent/Components/Component.cs ================================================ using System; using System.Collections.Generic; using System.Xml.Linq; namespace Composite.C1Console.RichContent.Components { /// /// Describes component structure /// public class Component { /// /// Component's unique id /// public virtual Guid Id { get; set; } /// /// Component's Title /// public virtual string Title { get; set; } /// /// Component's Description /// public virtual string Description { get; set; } /// /// Component's Tags which would be categorized with /// public virtual IEnumerable GroupingTags { get; set; } /// /// Container classes in which this component can appear /// public virtual IEnumerable ContainerClasses { get; set; } /// /// Container classes in which this component should not appear /// public virtual IEnumerable AntiTags { get; set; } /// /// Image or Icon that should be used for component /// public virtual ComponentImage ComponentImage { get; set; } /// /// Component's definition /// public virtual string ComponentDefinition { get; set; } } /// /// Image or Icon that should be used for component /// public class ComponentImage { /// /// Icon name /// public string IconName; /// /// Image uri /// public string CustomImageUri; } } ================================================ FILE: Composite/C1Console/RichContent/Components/ComponentChangeNotifier.cs ================================================ using Composite.Core.Application; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; namespace Composite.C1Console.RichContent.Components { [ApplicationStartup()] internal class ComponentChangeNotifierRegistrator { public void ConfigureServices(IServiceCollection serviceCollection) { serviceCollection.AddSingleton(typeof(ComponentChangeNotifier)); } } /// /// Component change structure /// public class ComponentChange { /// /// Provider's Id, e.g. provider's class name /// public string ProviderId { get; set; } } /// /// This class manages change notifiers subscribed in component providers /// public class ComponentChangeNotifier : IObservable { /// public ComponentChangeNotifier() { _observers = new List>(); } private readonly List> _observers; /// /// Use this method to subscribe an observer /// /// public IDisposable Subscribe(IObserver observer) { if (!_observers.Contains(observer)) _observers.Add(observer); return new Unsubscriber(_observers, observer); } private class Unsubscriber : IDisposable { private readonly List> _observers; private readonly IObserver _observer; public Unsubscriber(List> observers, IObserver observer) { this._observers = observers; this._observer = observer; } public void Dispose() { if (_observer != null && _observers.Contains(_observer)) _observers.Remove(_observer); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~Unsubscriber() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } /// /// Notify a change in the provider /// /// public void ProviderChange(string providerId) { var change = new ComponentChange { ProviderId = providerId }; foreach (var observer in _observers) { observer.OnNext(change); } } } } ================================================ FILE: Composite/C1Console/RichContent/Components/ComponentManager.cs ================================================ using Composite.Core; using Composite.Core.Application; using Composite.Core.Logging; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; namespace Composite.C1Console.RichContent.Components { [ApplicationStartup()] internal class ComponentManagerRegistrator { public void ConfigureServices(IServiceCollection serviceCollection) { serviceCollection.AddSingleton(typeof(ComponentManager)); } } /// /// Get this class through the . Describes components registered. /// public class ComponentManager : IObserver { /// /// Instanciates a new instance of the ComponentManager. This class aggregate Components delivered from providers /// implementing and registered with . /// Get this class from . /// /// Providers the ComponentManager should read from. /// Service to signal changes in providers /// Service to write to log public ComponentManager(IEnumerable providers, ComponentChangeNotifier changeNotifier, ILog log) { _log = log; _providers = providers.ToList(); _notifierUnsubscriber = changeNotifier.Subscribe(this); _log.LogVerbose(nameof(ComponentManager), "Registering {0} IComponentProvider instances: {1}", _providers.Count, string.Join(",", _providers.Select(f => f.ProviderId))); } private readonly ILog _log; private readonly List _providers; private IDisposable _notifierUnsubscriber; private List _componentCache; /// /// Returns all known Components /// /// Components public IEnumerable GetComponents() { var components = _componentCache; if (components == null) { components = _providers.SelectMany(p => p.GetComponents()).ToList(); _componentCache = components; } return components; } #region Change notifications void IObserver.OnCompleted() { _log.LogWarning(nameof(ComponentManager), "Unexpected ComponentChange OnCompleted called"); } void IObserver.OnError(Exception error) { _log.LogError(nameof(ComponentManager), error); } void IObserver.OnNext(ComponentChange value) { _componentCache = null; } #endregion } } ================================================ FILE: Composite/C1Console/RichContent/Components/IComponentProvider.cs ================================================ using System.Collections.Generic; namespace Composite.C1Console.RichContent.Components { /// /// Component provider interface /// public interface IComponentProvider { /// /// Unique id for this provider. Use this id to signal Component changes via . /// string ProviderId { get; } /// /// Return Component items known by the implemented provider. /// The ComponentManager will only call this once and then cache components for the duration of the process lifetime. /// If your list of components change, use the service and signal changes /// via . /// /// One or more Component insances IEnumerable GetComponents(); } } ================================================ FILE: Composite/C1Console/RichContent/ContainerClasses/AntonymContainerClassManager.cs ================================================ using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq; using Composite.Core; using Composite.Core.IO; using Composite.Core.Xml; namespace Composite.C1Console.RichContent.ContainerClasses { internal static class AntonymContainerClassManager { private static readonly Dictionary AntonymDictionaryFromConfig = AntonymContainerClassLoader(); private const string AntonymClassConfigurationsRelativePath = "~/App_Data/Composite/Configuration/AntonymClassDefinitions.xml"; private static Dictionary AntonymContainerClassLoader() { XDocument document = null; try { document = XDocumentUtils.Load(PathUtil.Resolve(AntonymClassConfigurationsRelativePath)); } catch (XmlException exception) { Log.LogWarning(nameof(AntonymContainerClassManager),$"error in parsing config file: {exception}"); return new Dictionary(); } return (from element in document.Root?.Elements() select new { Name = element.GetAttributeValue("name"), Value = element.GetAttributeValue("antonym") }) .ToDictionary(o => o.Name, o => o.Value); } public static string GetAntonym(string str) { return AntonymDictionaryFromConfig.ContainsKey(str) ? AntonymDictionaryFromConfig[str] : ""; } } } ================================================ FILE: Composite/C1Console/RichContent/ContainerClasses/ContainerClassManager.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Data; using Composite.Data.Types; namespace Composite.C1Console.RichContent.ContainerClasses { /// /// Services for working with Container Classes - a concept that allow you to attach styling to visual editors and filter Components /// public static class ContainerClassManager { /// /// Returns Container Classes defined for a Page Type Placeholder. /// /// Page Type to query /// Placeholder to query /// List of container class names public static IEnumerable GetPageTypeContainerClasses(Guid pageTypeId, string placeholderId) { using (DataConnection connection = new DataConnection()) { var containerClasses = connection.Get().Where(f => f.PageTypeId == pageTypeId && f.PlaceHolderId == placeholderId).Select(f => f.ContainerClasses).FirstOrDefault(); return ParseToList(containerClasses); } } /// /// Given a string containing zero or more class names seperated by space/and or commas, this function returned a list of trimmed class names. /// /// String with one or more class names /// strings, one for each class public static IEnumerable ParseToList(string containerClasses) { if (!string.IsNullOrEmpty(containerClasses)) { var classList = containerClasses.Replace(" ", ",").Split(',').Where(s => !string.IsNullOrWhiteSpace(s)); foreach (string containerClass in classList) { yield return containerClass; } } yield break; } /// /// Ensure that a user provided string with 0 or more container class names is on the format "class1,class2,class3" /// /// User provided string /// Structurally dependant string - each class seperated with a comma public static string NormalizeClassNamesString(string containerClasses) { return string.Join(",", ParseToList(containerClasses)); } /// /// Merge two IList based class lists into one. /// /// Original list of classes. Some classes may be dropped from this list, if updated list has anantonyms /// Extra classes to add. These classes will have precedence. /// public static IList MergeContainerClasses(IEnumerable originalClassList, IEnumerable updatedClassList) { return updatedClassList.Union(originalClassList ?? Enumerable.Empty(), new EqualOrAntonymComparer()).ToList(); } /// /// Merge two IList based class lists into one. /// /// Original list of classes. Some classes may be dropped from this list, if updated list has anantonyms /// Extra classes to add. These classes will have precedence. /// public static string MergeContainerClasses(string originalClassList, string updatedClassList) { return string.Join(",", MergeContainerClasses(ParseToList(originalClassList),ParseToList(updatedClassList))); } } } ================================================ FILE: Composite/C1Console/RichContent/ContainerClasses/EqualOrAntonymComparer.cs ================================================ using System.Collections.Generic; namespace Composite.C1Console.RichContent.ContainerClasses { internal class EqualOrAntonymComparer : IEqualityComparer { public bool Equals(string x, string y) { return x.Equals(AntonymContainerClassManager.GetAntonym(y)) || x.Equals(y); } public int GetHashCode(string obj) { return obj.GetHashCode() ^ AntonymContainerClassManager.GetAntonym(obj).GetHashCode(); } } } ================================================ FILE: Composite/C1Console/Security/ActionToken.cs ================================================ using System.Collections.Generic; using System; using Composite.Core.Types; using System.Linq; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class ActionToken { /// public abstract IEnumerable PermissionTypes { get; } /// public virtual string Serialize() { return ""; } /// public virtual bool IgnoreEntityTokenLocking { get { return false; } } } internal static class ActionTokenExtensionMethods { public static bool IsIgnoreEntityTokenLocking(this ActionToken actionToken) { if (actionToken == null) throw new ArgumentNullException(nameof(actionToken)); return actionToken.IgnoreEntityTokenLocking; } } } ================================================ FILE: Composite/C1Console/Security/ActionTokenSerializer.cs ================================================ using System; using System.Collections.Generic; using System.Reflection; using System.Security; using System.Text; using Composite.Core.Serialization; using Composite.Core.Types; using Composite.Core; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ActionTokenSerializer { /// public static string Serialize(ActionToken actionToken) { return Serialize(actionToken, false); } /// public static string Serialize(ActionToken actionToken, bool includeHashValue) { StringBuilder sb = new StringBuilder(); StringConversionServices.SerializeKeyValuePair(sb, "actionTokenType", TypeManager.SerializeType(actionToken.GetType())); string serializedActionToken = actionToken.Serialize(); StringConversionServices.SerializeKeyValuePair(sb, "actionToken", serializedActionToken); if (includeHashValue) { StringConversionServices.SerializeKeyValuePair(sb, "actionTokenHash", HashSigner.GetSignedHash(serializedActionToken).Serialize()); } return sb.ToString(); } /// public static ActionToken Deserialize(string serialziedActionToken) { return Deserialize(serialziedActionToken, false); } /// public static ActionToken Deserialize(string serialziedActionToken, bool includeHashValue) { if (string.IsNullOrEmpty(serialziedActionToken)) throw new ArgumentNullException("serialziedActionToken"); Dictionary dic = StringConversionServices.ParseKeyValueCollection(serialziedActionToken); if ((dic.ContainsKey("actionTokenType") == false) || (dic.ContainsKey("actionToken") == false) || ((includeHashValue) && (dic.ContainsKey("actionTokenHash") == false))) { throw new ArgumentException("Failed to deserialize the value. It has to be serialized with ActionTokenSerializer class.", "serialziedActionToken"); } string actionTokenTypeString = StringConversionServices.DeserializeValueString(dic["actionTokenType"]); string actionTokenString = StringConversionServices.DeserializeValueString(dic["actionToken"]); if (includeHashValue) { string actionTokenHash = StringConversionServices.DeserializeValueString(dic["actionTokenHash"]); HashValue hashValue = HashValue.Deserialize(actionTokenHash); if (HashSigner.ValidateSignedHash(actionTokenString, hashValue) == false) { throw new SecurityException("Serialized action token is tampered"); } } Type actionType = TypeManager.GetType(actionTokenTypeString); MethodInfo methodInfo = actionType.GetMethod("Deserialize", BindingFlags.Public | BindingFlags.Static); if (methodInfo == null || !(typeof(ActionToken).IsAssignableFrom(methodInfo.ReturnType))) { Log.LogWarning("ActionTokenSerializer", string.Format("The action token {0} is missing a public static Deserialize method taking a string as parameter and returning an {1}", actionType, typeof(ActionToken))); throw new InvalidOperationException(string.Format("The action token {0} is missing a public static Deserialize method taking a string as parameter and returning an {1}", actionType, typeof(ActionToken))); } ActionToken actionToken; try { actionToken = (ActionToken)methodInfo.Invoke(null, new object[] { actionTokenString }); } catch (Exception ex) { Log.LogWarning("ActionTokenSerializer", string.Format("The action token {0} is missing a public static Deserialize method taking a string as parameter and returning an {1}", actionType, typeof(ActionToken))); Log.LogWarning("ActionTokenSerializer", ex); throw new InvalidOperationException(string.Format("The action token {0} is missing a public static Deserialize method taking a string as parameter and returning an {1}", actionType, typeof(ActionToken)), ex); } if (actionToken == null) { Log.LogWarning("ActionTokenSerializer", string.Format("public static Deserialize method taking a string as parameter and returning an {1} on the action token {0} did not return an object", actionType, typeof(ActionToken))); throw new InvalidOperationException(string.Format("public static Deserialize method taking a string as parameter and returning an {1} on the action token {0} did not return an object", actionType, typeof(ActionToken))); } return actionToken; } /// public static T Deserialize(string serialziedActionToken) where T : ActionToken { return (T)Deserialize(serialziedActionToken); } } } ================================================ FILE: Composite/C1Console/Security/AdministratorAutoCreator.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Composite.C1Console.Elements; using Composite.C1Console.Security.Foundation.PluginFacades; using Composite.C1Console.Users; using Composite.Core; using Composite.Core.Configuration; using Composite.Core.Logging; using Composite.Core.ResourceSystem; using Composite.Data; using Composite.Data.Types; namespace Composite.C1Console.Security { /// /// Can create "the first user" on a newly installed system. This class only works if /// - no other users has been created before /// - the global configuration contains a "auto create administrator" user name /// - the provided user name matches the user name from the global configuration /// - the provided password validates as a non-weak password /// - the used login provider supports adding users /// - the used permission provider supports adding permission types /// internal static class AdministratorAutoCreator { public static bool CanBeAutoCreated(string userName) { string defaultAdminUserName = GlobalSettingsFacade.AutoCreatedAdministratorUserName; return !string.IsNullOrEmpty(defaultAdminUserName) && userName == defaultAdminUserName && !LoginProviderPluginFacade.UsersExists; } /// /// Used for "first time" login on systems configured for this. A way to create the first user. This only works on systems /// with no users and with a valid "auto create admin username" specified by the global settings. /// /// The user name - must match GlobalSettingsProvider.AutoCreatedAdministratorUserName /// A password that meets a minimum requirement. /// THe users email. /// When true only the username specified in Composite.config as auto createable (usually 'admin') is allowed. Set to false to use a different user name. /// true if the user was auto created. Otherwise false. public static void AutoCreateAdministrator(string userName, string password, string email, bool validateAutoCreateUserName = true) { if (validateAutoCreateUserName && !CanBeAutoCreated(userName)) { throw new InvalidOperationException("Unable to auto create account. Either the user name is not eligble for auto creation or other users exists in the system. This feature only works for a specific user name and when no users exists."); } if (!LoginProviderPluginFacade.CanAddNewUser) { throw new InvalidOperationException("Unable to auto create account. The current login provider does not support adding users"); } if (!PermissionTypeFacade.CanAlterDefinitions) { throw new InvalidOperationException("Unable to auto create account. The current permission defintion provider does not support changes"); } //PasswordValidator validator = new PasswordValidator(); //ValidationResults validationResults = validator.Validate(password); //if (validationResults.IsValid == false) //{ // throw new InvalidOperationException("Unable to auto create account. The specified password is not strong enough."); //} // All seems bo be ok green light go for auto creating the user. string group = StringResourceSystemFacade.GetString("Composite.C1Console.Users", "AdministratorAutoCreator.DefaultGroupName"); LoginProviderPluginFacade.FormAddNewUser(userName, password, group, email); Log.LogVerbose("AdministratorAutoCreator", String.Format("Auto Created Administrator with user name '{0}'.", userName), LoggingService.Category.Audit); IUser user = DataFacade.GetData().Where(f => f.Username == userName).SingleOrDefault(); IUserGroup userGroup = DataFacade.GetData().Where(f => f.Name == "Administrator").SingleOrDefault(); if (user != null && userGroup != null) { IUserUserGroupRelation userUserGroupRelation = DataFacade.BuildNew(); userUserGroupRelation.UserId = user.Id; userUserGroupRelation.UserGroupId = userGroup.Id; DataFacade.AddNew(userUserGroupRelation); } else { foreach (Element appRootElement in ElementFacade.GetRootsWithNoSecurity()) { string serializedEntityToken = EntityTokenSerializer.Serialize(appRootElement.ElementHandle.EntityToken); LoggingService.LogVerbose("AdministratorAutoCreator", String.Format("Adding '{0}' on element '{1}' ('{2}').", userName, appRootElement.VisualData.Label ?? "(no label)", serializedEntityToken), LoggingService.Category.Audit); UserPermissionDefinition userPermissionDefinition = new ConstructorBasedUserPermissionDefinition(userName, PermissionTypeFacade.GrantingPermissionTypes, serializedEntityToken); PermissionTypeFacade.SetUserPermissionDefinition(userPermissionDefinition); } Log.LogVerbose("AdministratorAutoCreator", string.Format("Activating all known perspectives for user '{0}'", userName)); IEnumerable perspectiveEntityTokens = ElementFacade.GetPerspectiveElementsWithNoSecurity().Select(f => f.ElementHandle.EntityToken); UserPerspectiveFacade.SetEntityTokens(userName, perspectiveEntityTokens); } foreach (CultureInfo cultureInfo in DataLocalizationFacade.ActiveLocalizationCultures) { UserSettings.AddActiveLocaleCultureInfo(userName, cultureInfo); if (Core.Localization.LocalizationFacade.IsDefaultLocale(cultureInfo)) { UserSettings.SetCurrentActiveLocaleCultureInfo(userName, cultureInfo); UserSettings.SetForeignLocaleCultureInfo(userName, cultureInfo); } } } } } ================================================ FILE: Composite/C1Console/Security/AuxiliarySecurityAncestorFacade.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Events; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class AuxiliarySecurityAncestorFacade { private static IAuxiliarySecurityAncestorFacade _implementation = new AuxiliarySecurityAncestorFacadeImpl(); static AuxiliarySecurityAncestorFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => _implementation.Flush()); } internal static IAuxiliarySecurityAncestorFacade Implementation { get { return _implementation; } set { _implementation = value; } } /// public static IEnumerable GetParents(EntityToken entityToken) { return _implementation.GetParents(entityToken); } // Overload /// /// Providers will get flushed on flushes /// /// /// public static void AddAuxiliaryAncestorProvider(IAuxiliarySecurityAncestorProvider auxiliarySecurityAncestorProvider) where T : EntityToken { AddAuxiliaryAncestorProvider(typeof(T), auxiliarySecurityAncestorProvider); } // Overload /// /// /// /// /// public static void AddAuxiliaryAncestorProvider(IAuxiliarySecurityAncestorProvider auxiliarySecurityAncestorProvider, bool flushPersistent) where T : EntityToken { AddAuxiliaryAncestorProvider(typeof(T), auxiliarySecurityAncestorProvider, flushPersistent); } /// /// Providers will get flushed on flushes /// /// /// public static void AddAuxiliaryAncestorProvider(Type entityTokenType, IAuxiliarySecurityAncestorProvider auxiliarySecurityAncestorProvider) { _implementation.AddAuxiliaryAncestorProvider(entityTokenType, auxiliarySecurityAncestorProvider, false); } /// /// Providers will get flushed on flushes /// /// /// /// public static void AddAuxiliaryAncestorProvider(Type entityTokenType, IAuxiliarySecurityAncestorProvider auxiliarySecurityAncestorProvider, bool flushPersistent) { _implementation.AddAuxiliaryAncestorProvider(entityTokenType, auxiliarySecurityAncestorProvider, flushPersistent); } /// public static IEnumerable GetAuxiliaryAncestorProviders(Type entityTokenType) { return _implementation.GetAuxiliaryAncestorProviders(entityTokenType); } } } ================================================ FILE: Composite/C1Console/Security/AuxiliarySecurityAncestorFacadeImpl.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Core.Extensions; namespace Composite.C1Console.Security { internal sealed class AuxiliarySecurityAncestorFacadeImpl : IAuxiliarySecurityAncestorFacade { private Dictionary> _auxiliarySecurityAncestorProviders = new Dictionary>(); private Dictionary> _flushPersistentAuxiliarySecurityAncestorProviders = new Dictionary>(); public IEnumerable GetParents(EntityToken entityToken) { Verify.ArgumentNotNull(entityToken, nameof(entityToken)); List auxiliarySecurityAncestorProviders; List flushPersistentAuxiliarySecurityAncestorProviders; _auxiliarySecurityAncestorProviders.TryGetValue(entityToken.GetType(), out auxiliarySecurityAncestorProviders); _flushPersistentAuxiliarySecurityAncestorProviders.TryGetValue(entityToken.GetType(), out flushPersistentAuxiliarySecurityAncestorProviders); IEnumerable resultSecurityAncestorProviders = auxiliarySecurityAncestorProviders.ConcatOrDefault(flushPersistentAuxiliarySecurityAncestorProviders); if (resultSecurityAncestorProviders == null) return null; IEnumerable totalResult = null; foreach (IAuxiliarySecurityAncestorProvider auxiliarySecurityAncestorProvider in resultSecurityAncestorProviders) { var result = auxiliarySecurityAncestorProvider.GetParents(new [] { entityToken }); if (result.Count > 0) { totalResult = totalResult.ConcatOrDefault(result.Values.First()); } } return totalResult; } public void AddAuxiliaryAncestorProvider(Type entityTokenType, IAuxiliarySecurityAncestorProvider auxiliarySecurityAncestorProvider, bool flushPersistent) { var providers = !flushPersistent ? _auxiliarySecurityAncestorProviders : _flushPersistentAuxiliarySecurityAncestorProviders; List auxiliarySecurityAncestorProviders; if (!providers.TryGetValue(entityTokenType, out auxiliarySecurityAncestorProviders)) { auxiliarySecurityAncestorProviders = new List(); providers.Add(entityTokenType, auxiliarySecurityAncestorProviders); } if (auxiliarySecurityAncestorProviders.Contains(auxiliarySecurityAncestorProvider)) { throw new ArgumentException("The given provider has already been added with the given entity token", nameof(auxiliarySecurityAncestorProvider)); } auxiliarySecurityAncestorProviders.Add(auxiliarySecurityAncestorProvider); } public void RemoveAuxiliaryAncestorProvider(Type entityTokenType, IAuxiliarySecurityAncestorProvider auxiliarySecurityAncestorProvider) { List auxiliarySecurityAncestorProviders; if (_auxiliarySecurityAncestorProviders.TryGetValue(entityTokenType, out auxiliarySecurityAncestorProviders)) { auxiliarySecurityAncestorProviders.Remove(auxiliarySecurityAncestorProvider); } if (_flushPersistentAuxiliarySecurityAncestorProviders.TryGetValue(entityTokenType, out auxiliarySecurityAncestorProviders)) { auxiliarySecurityAncestorProviders.Remove(auxiliarySecurityAncestorProvider); } } public IEnumerable GetAuxiliaryAncestorProviders(Type entityTokenType) { List auxiliarySecurityAncestorProviders; if (_auxiliarySecurityAncestorProviders.TryGetValue(entityTokenType, out auxiliarySecurityAncestorProviders)) { foreach (IAuxiliarySecurityAncestorProvider auxiliarySecurityAncestorProvider in auxiliarySecurityAncestorProviders) { yield return auxiliarySecurityAncestorProvider; } } if (_flushPersistentAuxiliarySecurityAncestorProviders.TryGetValue(entityTokenType, out auxiliarySecurityAncestorProviders)) { foreach (IAuxiliarySecurityAncestorProvider auxiliarySecurityAncestorProvider in auxiliarySecurityAncestorProviders) { yield return auxiliarySecurityAncestorProvider; } } } public void Flush() { _auxiliarySecurityAncestorProviders = new Dictionary>(); } } } ================================================ FILE: Composite/C1Console/Security/AuxiliarySecurityAncestorProviderAttribute.cs ================================================ using System; namespace Composite.C1Console.Security { [AttributeUsageAttribute(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] internal sealed class AuxiliarySecurityAncestorProviderAttribute : Attribute { private Type _auxiliarySecurityAncestorProviderType; public AuxiliarySecurityAncestorProviderAttribute(Type auxiliarySecurityAncestorProviderType) { _auxiliarySecurityAncestorProviderType = auxiliarySecurityAncestorProviderType; } public Type AuxiliarySecurityAncestorProviderType { get { return _auxiliarySecurityAncestorProviderType; } } } } ================================================ FILE: Composite/C1Console/Security/BuildinPlugins/BuildinLoginSessionStore/BuildinLoginSessionStore.cs ================================================ using System.Net; using Composite.C1Console.Security.Plugins.LoginSessionStore; namespace Composite.C1Console.Security.BuildinPlugins.BuildinLoginSessionStore { internal class BuildinLoginSessionStore : ILoginSessionStore { public static string Username { get { return "testUser"; } } string _username = Username; public bool CanPersistAcrossSessions { get { return true; } } public void StoreUsername(string username, bool persistAcrossSessions) { _username = username; } public void FlushUsername() { _username = Username; } public string StoredUsername { get { return _username; } } public IPAddress UserIpAddress { get { return IPAddress.Loopback; } } } } ================================================ FILE: Composite/C1Console/Security/BuildinPlugins/BuildinUserPermissionDefinitionProvider/BuildinUserRoleDefinitionProvider.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.C1Console.Security.Plugins.UserPermissionDefinitionProvider; namespace Composite.C1Console.Security.BuildinPlugins.BuildinUserPermissionDefinitionProvider { internal sealed class BuildinUserPermissionDefinitionProvider : IUserPermissionDefinitionProvider { private List _userPermissionDefinitions = new List(); public IEnumerable AllUserPermissionDefinitions { get { return _userPermissionDefinitions; } } public bool CanAlterDefinitions { get { return true; } } public void SetUserPermissionDefinition(UserPermissionDefinition userPermissionDefinition) { _userPermissionDefinitions.Add(userPermissionDefinition); } public void RemoveUserPermissionDefinition(UserToken userToken, string serializedEntityToken) { _userPermissionDefinitions = new List(); } #region IUserPermissionDefinitionProvider Members public IEnumerable GetPermissionsByUser(string userName) { return from urd in AllUserPermissionDefinitions where urd.Username == userName select urd; } #endregion } } ================================================ FILE: Composite/C1Console/Security/Compatibility/LegacySerializedEntityTokenUpgrader.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Xml.Linq; using Composite.Core.Application; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.Logging; using Composite.Data; using Composite.Data.DynamicTypes; namespace Composite.C1Console.Security.Compatibility { /// /// Will auto upgrade serialized entity tokens and data ids, stored in c1 data. Needed because serialization has changed. /// [ApplicationStartup(AbortStartupOnException = false)] public static class LegacySerializedEntityTokenUpgrader { const string LogTitle = nameof(LegacySerializedEntityTokenUpgrader); const string _configFilename = "LegacySerializedEntityTokenUpgrader.config"; static readonly XName _docRoot = "UpgradeSettings"; private static ILog _log; private const int MaxErrorMessagesPerType = 1000; /// /// See class description - this allow us to run on startup /// /// public static void OnInitialized(ILog log) { if (ShouldRun) { _log = log; try { Run(); } catch (Exception ex) { _log.LogError(LogTitle, ex); throw; } } } private static void Run() { UpgradeStoredData(); var config = GetConfigElement(); config.SetAttributeValue("last-run", DateTime.Now); config.SetAttributeValue("completed", true); config.Save(ConfigFilePath); } private static bool ShouldRun { get { var _xConfig = GetConfigElement(); return true == (bool)_xConfig.Attribute("enabled") && (false == (bool)_xConfig.Attribute("completed") || true == (bool)_xConfig.Attribute("force") || (DateTime)_xConfig.Attribute("last-run") - (DateTime)_xConfig.Attribute("inception") < TimeSpan.FromMinutes(5)); } } private static string ConfigFilePath { get { var configDir = PathUtil.Resolve(GlobalSettingsFacade.ConfigurationDirectory); var configFilePath = Path.Combine(configDir, _configFilename); return configFilePath; } } private static XElement GetConfigElement() { XDocument config = null; if (File.Exists(ConfigFilePath)) { config = XDocument.Load(ConfigFilePath); } else { config = new XDocument( new XElement(_docRoot, new XAttribute("inception", DateTime.Now), new XAttribute("force", false), new XAttribute("completed", false), new XAttribute("enabled", true))); } return config.Root; } private static void UpgradeStoredData() { const string _ET = "EntityToken"; const string _DSI = "DataSourceId"; List magicPropertyNames = new List { _ET, _DSI }; Func isSerializedFieldFunc = g => magicPropertyNames.Any(s => g.Name.Contains(s)); var descriptors = DataMetaDataFacade.AllDataTypeDescriptors.Where(f => f.Fields.Any(isSerializedFieldFunc)); foreach (var descriptor in descriptors) { Type dataType = descriptor.GetInterfaceType(); if (dataType == null) { continue; } var propertiesToUpdate = new List(); foreach (var tokenField in descriptor.Fields.Where(isSerializedFieldFunc)) { var tokenProperty = dataType.GetProperty(tokenField.Name); propertiesToUpdate.Add(tokenProperty); } using (new DataConnection(PublicationScope.Unpublished)) { var allRows = DataFacade.GetData(dataType).ToDataList(); var toUpdate = new List(); int errors = 0, updated = 0; foreach (var rowItem in allRows) { bool rowChange = false; foreach (var tokenProperty in propertiesToUpdate) { string token = tokenProperty.GetValue(rowItem) as string; try { string tokenReserialized; if (tokenProperty.Name.Contains(_ET)) { var entityToken = EntityTokenSerializer.Deserialize(token); tokenReserialized = EntityTokenSerializer.Serialize(entityToken); } else if (tokenProperty.Name.Contains(_DSI)) { token = EnsureValidDataSourceId(token); var dataSourceId = DataSourceId.Deserialize(token); tokenReserialized = dataSourceId.Serialize(); } else { throw new InvalidOperationException("This line should not be reachable"); } if (tokenReserialized != token) { tokenProperty.SetValue(rowItem, tokenReserialized); rowChange = true; } } catch (Exception ex) { errors++; if (errors <= MaxErrorMessagesPerType) { _log.LogError(LogTitle, $"Failed to upgrade old token '{token}' from data type '{dataType.FullName}' as EntityToken.\n{ex}"); } } } if (rowChange) { updated++; toUpdate.Add(rowItem); if (toUpdate.Count >= 1000) { DataFacade.Update(toUpdate, true, false, false); toUpdate.Clear(); } } } if (toUpdate.Count > 0) { DataFacade.Update(toUpdate, true, false, false); toUpdate.Clear(); } _log.LogInformation(LogTitle, $"Finished updating serialized tokens for data type '{dataType.FullName}'. Rows: {allRows.Count}, Updated: {updated}, Errors: {errors}"); } } } private static string EnsureValidDataSourceId(string token) { try { // fixing specific data inconsistency, where old serialized data id's for versioned data do not reflect versionid property added in a later version if (token.Contains("Composite_Data_Types_IPagePlaceholderContentDataId") && !token.Contains("VersionId")) { var pageId = Guid.Parse(token.Substring(19, 36)); token = token.Replace("'_dataIdType_", String.Format(",\\ VersionId=\\'{0}\\''_dataIdType_", pageId)); } } catch (Exception) { // if we have an issue, caller will act } return token; } } } ================================================ FILE: Composite/C1Console/Security/ConstructorBasedUserGroupPermissionDefinition.cs ================================================ using System; using System.Collections.Generic; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ConstructorBasedUserGroupPermissionDefinition : UserGroupPermissionDefinition { private Guid _userGroupId; private IEnumerable _permissionTypes; private string _serializedEntityToken; /// public ConstructorBasedUserGroupPermissionDefinition(Guid userGroupId, IEnumerable permissionTypes, string serializedEntityToken) { _userGroupId = userGroupId; _permissionTypes = permissionTypes; _serializedEntityToken = serializedEntityToken; } /// public override Guid UserGroupId { get { return _userGroupId; } } /// public override IEnumerable PermissionTypes { get { return _permissionTypes; } } /// public override string SerializedEntityToken { get { return _serializedEntityToken; } } } } ================================================ FILE: Composite/C1Console/Security/ConstructorBasedUserPermissionDefinition.cs ================================================ using System.Collections.Generic; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ConstructorBasedUserPermissionDefinition : UserPermissionDefinition { private string _username; private IEnumerable _permissionTypes; private string _serializedEntityToken; /// public ConstructorBasedUserPermissionDefinition(string username, IEnumerable permissionTypes, string serializedEntityToken) { _username = username; _permissionTypes = permissionTypes; _serializedEntityToken = serializedEntityToken; } /// public override string Username { get { return _username; } } /// public override IEnumerable PermissionTypes { get { return _permissionTypes; } } /// public override string SerializedEntityToken { get { return _serializedEntityToken; } } } } ================================================ FILE: Composite/C1Console/Security/Cryptography/Cryptographer.cs ================================================ using System; using System.IO; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; namespace Composite.C1Console.Security.Cryptography { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Cryptographer { private static string _secretKey; private static Encoding _encoding = Encoding.Unicode; static Cryptographer() { _secretKey = "u?Ccr?"; GCHandle gch = GCHandle.Alloc(_secretKey, GCHandleType.Pinned); //ZeroMemory(gch.AddrOfPinnedObject(), _secretKey.Length * 2); //gch.Free(); } /// public static string Encrypt(this string data) { byte[] byteData = _encoding.GetBytes(data); byte[] encrypted = Cryptographer.EncryptBytes(byteData); return Convert.ToBase64String(encrypted); } /// public static string Decrypt(this string data) { byte[] byteData = _encoding.GetBytes(data); byte[] decrypted = Cryptographer.DecryptBytes(Convert.FromBase64String(data)); return _encoding.GetString(decrypted); } /// public static byte[] EncryptBytes(byte[] toEncrypt) { DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); DES.Key = ASCIIEncoding.ASCII.GetBytes(_secretKey); DES.IV = ASCIIEncoding.ASCII.GetBytes(_secretKey); ICryptoTransform desencrypt = DES.CreateEncryptor(); byte[] result; using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cryptostream = new CryptoStream(ms, desencrypt, CryptoStreamMode.Write)) { cryptostream.Write(toEncrypt, 0, toEncrypt.Length); cryptostream.Close(); } result = ms.ToArray(); } return result; } /// public static byte[] DecryptBytes(byte[] toDecrypt) { DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); DES.Key = ASCIIEncoding.ASCII.GetBytes(_secretKey); DES.IV = ASCIIEncoding.ASCII.GetBytes(_secretKey); ICryptoTransform desdecrypt = DES.CreateDecryptor(); byte[] result; using (MemoryStream memoryWriteStream = new MemoryStream()) { memoryWriteStream.Write(toDecrypt, 0, toDecrypt.Length); memoryWriteStream.Position = 0; using (CryptoStream cryptostreamDecr = new CryptoStream(memoryWriteStream, desdecrypt, CryptoStreamMode.Read)) { using (Stream memoryReadStream = new MemoryStream()) { int size = 2048; byte[] data = new byte[2048]; while (true) { size = cryptostreamDecr.Read(data, 0, data.Length); if (size > 0) { memoryReadStream.Write(data, 0, size); } else { break; } } result = new byte[memoryReadStream.Length]; memoryReadStream.Position = 0; memoryReadStream.Read(result, 0, (int)memoryReadStream.Length); } } } return result; } } } ================================================ FILE: Composite/C1Console/Security/DataHookMapper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Data; namespace Composite.C1Console.Security { internal sealed class DataHookMapper where T : class, IData { private EntityTokenHook _currentEntityTokenHook; private EntityToken ParentEntityToken { get; set; } public DataHookMapper(EntityToken parentEntityToken) { if (parentEntityToken == null) throw new ArgumentNullException("parentEntityToken"); DataEventSystemFacade.SubscribeToDataAfterAdd(OnDataAddedOrDeleted, false); DataEventSystemFacade.SubscribeToDataDeleted(OnDataAddedOrDeleted, false); DataEventSystemFacade.SubscribeToStoreChanged(OnStoreChanged, false); this.ParentEntityToken = parentEntityToken; } public EntityTokenHook CurrentEntityTokenHook { get { if (_currentEntityTokenHook == null) { UpdateCurrentEntityTokenHook(); } return _currentEntityTokenHook; } } private void UpdateCurrentEntityTokenHook() { EntityTokenHook entityTokenHook = new EntityTokenHook(this.ParentEntityToken); List datas = DataFacade.GetData().ToList(); foreach (T data in datas) { entityTokenHook.AddHookie(data.GetDataEntityToken()); } _currentEntityTokenHook = entityTokenHook; } private void OnStoreChanged(object sender, StoreEventArgs dataEventArgs) { if (!dataEventArgs.DataEventsFired) { HookingFacade.RemoveHook(this.CurrentEntityTokenHook); UpdateCurrentEntityTokenHook(); HookingFacade.AddHook(this.CurrentEntityTokenHook); } } private void OnDataAddedOrDeleted(object sender, DataEventArgs dataEventArgs) { HookingFacade.RemoveHook(this.CurrentEntityTokenHook); UpdateCurrentEntityTokenHook(); HookingFacade.AddHook(this.CurrentEntityTokenHook); } } } ================================================ FILE: Composite/C1Console/Security/DataSecurityAncestorProvider.cs ================================================ using System; using System.Collections.Generic; using Composite.Data.Hierarchy; using Composite.Data; namespace Composite.C1Console.Security { internal sealed class DataSecurityAncestorProvider : ISecurityAncestorProvider { public IEnumerable GetParents(EntityToken entityToken) { if (entityToken == null) throw new ArgumentNullException("entityToken"); DataEntityToken dataEntityToken = entityToken as DataEntityToken; if (dataEntityToken == null) throw new ArgumentException(string.Format("The type of the entityToken should be of type {0}", typeof(DataEntityToken)), "entityToken"); IData data = dataEntityToken.Data; if(data == null) return null; // A piece of data may be deleted to this point using (new DataScope(data.DataSourceId.DataScopeIdentifier, data.DataSourceId.LocaleScope)) { IData parent = DataAncestorFacade.GetParent(dataEntityToken.Data); if (parent == null) { return null; } return new List { parent.GetDataEntityToken() }; } } } } ================================================ FILE: Composite/C1Console/Security/EntityToken.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using Composite.Core.Serialization; using Newtonsoft.Json; namespace Composite.C1Console.Security { internal class EntityTokenSerializerHandler : ISerializerHandler { public string Serialize(object objectToSerialize) { return EntityTokenSerializer.Serialize((EntityToken)objectToSerialize); } public object Deserialize(string serializedObject) { return EntityTokenSerializer.Deserialize(serializedObject); } } /// /// EntityToken is used through out C1 CMS to describe artifacts that can have security settings. Also see . /// /// /// When subclassing this class and adding properties that have an impact when identity (equality) /// of the subclass, remember to overload Equal and GetHashCode! /// [DebuggerDisplay("Type = {Type}, Source = {Source}, Id = {Id}")] [SerializerHandler(typeof(EntityTokenSerializerHandler))] public abstract class EntityToken { private bool _entityTokenUniquenessValidated; /// /// A string that forms one third of the unique key for the entity being represented. Being the 'type' part of the globally unique key 'type/source/id', /// this value should be unique for your code and not clash with 'type' strings used in other code modules. /// public abstract string Type { get; } /// /// A string that forms one third of the unique key for the entity being represented. Being the 'source' part of the globally unique key 'type/source/id', /// this value should be unique the source (like a file name or sql connection) when whence the entity come. This field is only important if enteties of /// this type can come from different sources. /// public abstract string Source { get; } /// /// A string that forms one third of the unique key for the entity being represented. Being the 'id' part of the globally unique key 'type/source/id', /// this value should identify a specific entity of the given 'type' from the given 'source'. /// public abstract string Id { get; } /// /// The state of the EntityToken. Invalid entity tokens will be automatically removed from the system. /// /// The state of the EntityToken. public virtual bool IsValid() => true; /// /// Serialize the EntityToken /// /// a string representation of the entity token public abstract string Serialize(); /// protected void DoSerialize(StringBuilder stringBuilder) { StringConversionServices.SerializeKeyValuePair(stringBuilder, "_EntityToken_Type_", Type); StringConversionServices.SerializeKeyValuePair(stringBuilder, "_EntityToken_Source_", Source); StringConversionServices.SerializeKeyValuePair(stringBuilder, "_EntityToken_Id_", Id); } /// protected string DoSerialize() { return CompositeJsonSerializer.Serialize( new Dictionary() {{nameof(Type), Type}, { nameof(Source), Source}, {nameof(Id), Id}}); } /// protected static void DoDeserialize(string serializedEntityToken, out string type, out string source, out string id) { DoDeserialize(serializedEntityToken, out type, out source, out id, out Dictionary _); } /// protected static void DoDeserialize(string serializedEntityToken, out string type, out string source, out string id, out Dictionary dictionary) { if (!CompositeJsonSerializer.IsJsonSerialized(serializedEntityToken)) { DoDeserializeLegacy(serializedEntityToken, out type, out source, out id, out dictionary); return; } var properties = CompositeJsonSerializer.Deserialize>(serializedEntityToken); if (!properties.TryGetValue(nameof(Type), out type) || !properties.TryGetValue(nameof(Source), out source) || !properties.TryGetValue(nameof(Id), out id)) { throw new ArgumentException("Is not a serialized entity token", nameof(serializedEntityToken)); } properties.Remove(nameof(Type)); properties.Remove(nameof(Source)); properties.Remove(nameof(Id)); dictionary = properties; } /// private static void DoDeserializeLegacy(string serializedEntityToken, out string type, out string source, out string id, out Dictionary dic) { dic = StringConversionServices.ParseKeyValueCollection(serializedEntityToken); if (!dic.TryGetValue("_EntityToken_Type_", out string serializedType) || !dic.TryGetValue("_EntityToken_Source_", out string serializedSource) || !dic.TryGetValue("_EntityToken_Id_", out string serializedId)) { throw new ArgumentException("Is not a serialized entity token", nameof(serializedEntityToken)); } type = StringConversionServices.DeserializeValueString(serializedType); source = StringConversionServices.DeserializeValueString(serializedSource); id = StringConversionServices.DeserializeValueString(serializedId); } /// protected int HashCode { get; set; } /// public virtual string GetPrettyHtml(Dictionary piggybag) { var entityTokenHtmlPrettyfier = new EntityTokenHtmlPrettyfier(this, piggybag); OnGetPrettyHtml(entityTokenHtmlPrettyfier); return entityTokenHtmlPrettyfier.GetResult(); } /// public virtual string OnGetTypePrettyHtml() => this.Type; /// public virtual string OnGetSourcePrettyHtml() => this.Source; /// public virtual string OnGetIdPrettyHtml() => this.Id; /// public virtual string OnGetExtraPrettyHtml() => null; /// public virtual void OnGetPrettyHtml(EntityTokenHtmlPrettyfier entityTokenHtmlPrettyfier) { } /// public override bool Equals(object obj) { return obj is EntityToken entityToken && entityToken.GetVersionHashCode() == GetVersionHashCode() && entityToken.VersionId == this.VersionId && EqualsWithVersionIgnore(entityToken); } /// public bool EqualsWithVersionIgnore(object obj) { var entityToken = obj as EntityToken; if (entityToken == null) return false; ValidateEntityToken(); return entityToken.GetHashCode() == GetHashCode() && entityToken.Id == this.Id && entityToken.Type == this.Type && entityToken.Source == this.Source && entityToken.GetType() == this.GetType(); } /// [JsonIgnore] public virtual string VersionId { get; } = ""; /// public bool Equals(EntityToken entityToken) { return Equals(entityToken as object); } /// public override int GetHashCode() { if (this.HashCode == 0) { ValidateEntityToken(); this.HashCode = this.Type.GetHashCode() ^ this.Source.GetHashCode() ^ this.Id.GetHashCode(); } return this.HashCode; } /// public int GetVersionHashCode() { if (this.VersionHashCode == 0) { this.VersionHashCode = this.VersionId.GetHashCode(); } return this.VersionHashCode; } /// protected int VersionHashCode { get; set; } /// public override string ToString() { return $"Source = {this.Source}, Type = {this.Type}, Id = {this.Id}"; } private void ValidateEntityToken() { if (_entityTokenUniquenessValidated) return; _entityTokenUniquenessValidated = true; if (string.IsNullOrEmpty(this.Type) && string.IsNullOrEmpty(this.Source) && string.IsNullOrEmpty(this.Id)) { ThrowNotUniqueException(); } } private void ThrowNotUniqueException() { throw new InvalidOperationException($"EntityTokens should be unique for the given element. The properties Type, Source and Id may not all be empty string. This is not the case for this type {GetType()}"); } } } ================================================ FILE: Composite/C1Console/Security/EntityTokenCacheFacade.cs ================================================ //#define DISABLE_ENTITYTOKEN_CACHE using System; using System.Collections.Generic; using System.Collections.Concurrent; using Composite.Core.Linq; using Composite.Core.Instrumentation; using Composite.Core.Configuration; using Composite.C1Console.Users; using System.Globalization; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class EntityTokenCacheFacade { private sealed class CacheKey { public string Username { get; set; } public EntityToken EntityToken { get; set; } public CultureInfo Locale { get; set; } public override bool Equals(object obj) { return Equals(obj as CacheKey); } public bool Equals(CacheKey cacheKey) { if (cacheKey == null) return false; return cacheKey.Username.Equals(this.Username) && cacheKey.EntityToken.Equals(this.EntityToken) && cacheKey.Locale.Equals(this.Locale); } public override int GetHashCode() { return this.Username.GetHashCode() ^ this.EntityToken.GetHashCode() ^ this.Locale.GetHashCode(); } } private static ConcurrentDictionary _nativeCache = new ConcurrentDictionary(); private static ConcurrentDictionary _hookingCache = new ConcurrentDictionary(); private static bool Enabled { get; set; } private static int MaxSize { get; set; } private const int DefaultSize = 50000; static EntityTokenCacheFacade() { CachingSettings cachingSettings = GlobalSettingsFacade.GetNamedCaching("Entity token parents"); Enabled = cachingSettings.Enabled; MaxSize = cachingSettings.GetSize(DefaultSize); #if DISABLE_ENTITYTOKEN_CACHE Enabled = false; #endif } /// public static void AddNativeCache(EntityToken entityToken, IEnumerable parentEntityTokens) { if (!Enabled || !UserValidationFacade.IsLoggedIn()) return; CacheEntry cacheEntry = new CacheEntry(entityToken) { ParentEntityTokens = parentEntityTokens.EvaluateOrNull(), Timestamp = DateTime.Now }; CacheKey cacheKey = new CacheKey { Username = ResolveUsername(), EntityToken = entityToken, Locale = Data.LocalizationScopeManager.CurrentLocalizationScope }; _nativeCache.TryAdd(cacheKey, cacheEntry); if (_nativeCache.Count > MaxSize) { _nativeCache = new ConcurrentDictionary(); } } /// public static void AddHookingCache(EntityToken entityToken, IEnumerable parentEntityTokens) { if (!Enabled || !UserValidationFacade.IsLoggedIn()) return; CacheEntry cacheEntry = new CacheEntry(entityToken) { ParentEntityTokens = parentEntityTokens.EvaluateOrNull(), Timestamp = DateTime.Now }; CacheKey cacheKey = new CacheKey { Username = ResolveUsername(), EntityToken = entityToken, Locale = Data.LocalizationScopeManager.CurrentLocalizationScope }; _hookingCache.TryAdd(cacheKey, cacheEntry); if (_hookingCache.Count > MaxSize) { _hookingCache = new ConcurrentDictionary(); } } /// public static bool GetCachedNativeParents(EntityToken entityToken, out IEnumerable parentEntityTokens) { if (!Enabled) { parentEntityTokens = null; return false; } string userName = UserValidationFacade.IsLoggedIn() ? ResolveUsername() : null; return GetCachedNativeParents(entityToken, out parentEntityTokens, userName); } internal static bool GetCachedNativeParents(EntityToken entityToken, out IEnumerable parentEntityTokens, string userName) { if (!Enabled || userName == null) { parentEntityTokens = null; return false; } CacheKey cacheKey = new CacheKey { Username = userName, EntityToken = entityToken, Locale = Data.LocalizationScopeManager.CurrentLocalizationScope }; CacheEntry cacheEntry; if (_nativeCache.TryGetValue(cacheKey, out cacheEntry)) { PerformanceCounterFacade.EntityTokenParentCacheHitIncrement(); parentEntityTokens = cacheEntry.ParentEntityTokens; return true; } PerformanceCounterFacade.EntityTokenParentCacheMissIncrement(); parentEntityTokens = null; return false; } /// public static bool GetCachedHookingParents(EntityToken entityToken, out IEnumerable parentEntityTokens) { if (!Enabled) { parentEntityTokens = null; return false; } string userName = UserValidationFacade.IsLoggedIn() ? ResolveUsername() : null; return GetCachedHookingParents(entityToken, out parentEntityTokens, userName); } internal static bool GetCachedHookingParents(EntityToken entityToken, out IEnumerable parentEntityTokens, string userName) { if (!Enabled || userName == null) { parentEntityTokens = null; return false; } CacheKey cacheKey = new CacheKey { Username = userName, EntityToken = entityToken, Locale = Data.LocalizationScopeManager.CurrentLocalizationScope }; CacheEntry cacheEntry; if (_hookingCache.TryGetValue(cacheKey, out cacheEntry)) { PerformanceCounterFacade.EntityTokenParentCacheHitIncrement(); parentEntityTokens = cacheEntry.ParentEntityTokens; return true; } PerformanceCounterFacade.EntityTokenParentCacheMissIncrement(); parentEntityTokens = null; return false; } /// public static void ClearCache(EntityToken entityToken) { if (!Enabled) { return; } string userName = UserValidationFacade.IsLoggedIn() ? ResolveUsername() : null; ClearCache(entityToken, userName); } /// public static void ClearCache(EntityToken entityToken, string userName) { if (!Enabled || userName == null) { return; } var cacheKey = new CacheKey { Username = userName, EntityToken = entityToken, Locale = Data.LocalizationScopeManager.CurrentLocalizationScope }; CacheEntry nativeCacheEntry; _nativeCache.TryRemove(cacheKey, out nativeCacheEntry); CacheEntry hookingCacheEntry; _hookingCache.TryRemove(cacheKey, out hookingCacheEntry); } /// public static void ClearCache() { _nativeCache = new ConcurrentDictionary(); _hookingCache = new ConcurrentDictionary(); } private static string ResolveUsername() { return UserSettings.Username; } private sealed class CacheEntry { public CacheEntry(EntityToken entityToken) { this.EntityToken = entityToken; } public EntityToken EntityToken { get; private set; } public DateTime Timestamp { get; set; } public IEnumerable ParentEntityTokens { get; set; } public override int GetHashCode() { return this.EntityToken.GetHashCode(); } public override bool Equals(object obj) { bool result = Equals(obj as CacheEntry); return result; } public bool Equals(CacheEntry obj) { if (obj == null) return false; bool result = this.EntityToken.Equals(obj.EntityToken); return result; } public override string ToString() { return this.EntityToken.ToString(); } } } } ================================================ FILE: Composite/C1Console/Security/EntityTokenHook.cs ================================================ using System.Linq; using System.Collections.Generic; using System.Diagnostics; using Composite.Core.Linq; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DebuggerDisplay("Hooker = {Hooker}")] public sealed class EntityTokenHook { private List _hooks = new List(); /// public EntityTokenHook(EntityToken hooker) { Verify.ArgumentNotNull(hooker, "hooker"); this.Hooker = hooker; } /// public EntityToken Hooker { get; private set; } /// public IEnumerable Hookies { get { return _hooks; } } /// public void AddHookie(EntityToken hook) { Verify.ArgumentNotNull(hook, "hook"); _hooks.Add(hook); } /// public void AddHookies(IEnumerable hooks) { Verify.ArgumentNotNull(hooks, "hooks"); IEnumerable resolvedHooks = hooks.Evaluate(); Verify.ArgumentCondition(!resolvedHooks.Contains(null), "hooks", "The collection contains one or more null values"); _hooks.AddRange(resolvedHooks); } } } ================================================ FILE: Composite/C1Console/Security/EntityTokenHtmlPrettyfier.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using Composite.Core.Extensions; using Composite.Core.Types; using System.Reflection; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class EntityTokenHtmlPrettyfier { private Dictionary> _customProperties = new Dictionary>(); /// public EntityToken EntityToken { get; set; } /// public Dictionary PiggyBag { get; set; } /// public EntityTokenHtmlPrettyfier(EntityToken entityToken, Dictionary piggybag) { this.EntityToken = entityToken; this.PiggyBag = piggybag; } private static string Strong(string text) { return "" + HttpUtility.HtmlEncode(text) + ""; } internal static string GetTypeHtml(Type type) { return GetTypeHtml(type.FullName); } internal static string GetTypeHtml(string fullTypeName) { int dotIndex = fullTypeName.LastIndexOf(".", StringComparison.Ordinal); if (dotIndex <= 0) { return fullTypeName; } return "" + fullTypeName.Substring(0, dotIndex + 1) + "" + fullTypeName.Substring(dotIndex + 1); } /// public static Action DefaultOnWriteEntityTokenType = (token, helper) => helper.AddFullRow(new [] { Strong("EntityToken"), GetTypeHtml( token.GetType() ) }); /// public static Action DefaultOnWriteType = (token, helper) => helper.AddFullRow(new [] { Strong("Type"), GetTypeHtml( token.Type )}); /// public static Action DefaultOnWriteSource = (token, helper) => helper.AddFullRow(new [] { Strong("Source"), token.Source }); /// public static Action DefaultOnWriteId = (token, helper) => helper.AddFullRow(new [] { Strong("Id"), token.Id }); /// public static Action DefaultOnWriteCustomProperty = (name, value, helper) => helper.AddFullRow(new [] { Strong(name), value.ToString() }); /// public static Action DefaultOnPiggyBagEntry = (key, value, helper) => { string valueStr = value; if (key.StartsWith("ParentEntityToken")) { EntityToken et = EntityTokenSerializer.Deserialize(value); valueStr = string.Format("Type = {0}", GetTypeHtml( et.GetType() )); } helper.AddFullRow(new[] { "" + key + "", valueStr }); }; /// public static Action DefaultOnWriteSecurityAncestorProvider = (attribute, helper) => helper.AddFullRow(new[] { "Type", GetTypeHtml(attribute.GetType()) }); /// public static Action DefaultOnWriteAuxiliarySecurityAncestorProvider = (provider, helper) => helper.AddFullRow(new[] { "Type", GetTypeHtml(provider.GetType()) }); /// public Action OnWriteEntityTokenType = DefaultOnWriteEntityTokenType; /// public Action OnWriteType = DefaultOnWriteType; /// public Action OnWriteSource = DefaultOnWriteSource; /// public Action OnWriteId = DefaultOnWriteId; /// public static Action OnWriteCustomProperty = DefaultOnWriteCustomProperty; /// public Action OnPiggyBagEntry = DefaultOnPiggyBagEntry; /// public Action OnWriteSecurityAncestorProvider = DefaultOnWriteSecurityAncestorProvider; /// public Action OnWriteAuxiliarySecurityAncestorProvider = DefaultOnWriteAuxiliarySecurityAncestorProvider; /// public void AddCustomSimpleProperty(string propertyName) { _customProperties.Add(propertyName, DefaultOnWriteCustomProperty); } /// public void AddCustomProperty(string propertyName, Action onWriteAction) { _customProperties.Add(propertyName, onWriteAction); } /// public string GetResult() { EntityTokenHtmlPrettyfierHelper helper = new EntityTokenHtmlPrettyfierHelper(); helper.StartTable(); helper.AddHeading("Basic Information"); OnWriteEntityTokenType(this.EntityToken, helper); OnWriteType(this.EntityToken, helper); OnWriteSource(this.EntityToken, helper); OnWriteId(this.EntityToken, helper); var extraInfo = EntityToken.OnGetExtraPrettyHtml(); if (!extraInfo.IsNullOrEmpty()) { helper.AddFullRow(new[] { "Extra", extraInfo }); } helper.AddHeading("Custom Properties"); foreach (var kvp in _customProperties) { PropertyInfo propertyInfo = this.EntityToken.GetType().GetPropertiesRecursively().Single(f => f.Name == kvp.Key); kvp.Value(kvp.Key, propertyInfo.GetValue(this.EntityToken, null), helper); } helper.AddHeading("Piggybag"); foreach (var kvp in this.PiggyBag) { OnPiggyBagEntry(kvp.Key, kvp.Value, helper); } helper.AddHeading("SecurityAncestorProvider"); SecurityAncestorProviderAttribute attribute = this.EntityToken.GetType().GetCustomAttributesRecursively().SingleOrDefault(); OnWriteSecurityAncestorProvider(attribute, helper); helper.AddHeading("AuxiliarySecurityAncestorProviders"); foreach (IAuxiliarySecurityAncestorProvider auxiliarySecurityAncestorProvider in AuxiliarySecurityAncestorFacade.GetAuxiliaryAncestorProviders(this.EntityToken.GetType())) { OnWriteAuxiliarySecurityAncestorProvider(auxiliarySecurityAncestorProvider, helper); } helper.EndTable(); return helper.GetResult(); } } } ================================================ FILE: Composite/C1Console/Security/EntityTokenHtmlPrettyfierHelper.cs ================================================ using System.Collections.Generic; using System.Text; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class EntityTokenHtmlPrettyfierHelper { private StringBuilder _stringBuilder = new StringBuilder(); /// public void StartTable() { _stringBuilder.AppendLine(@""); } /// public void EndTable() { _stringBuilder.AppendLine(@"
"); } /// public void StartRow() { _stringBuilder.AppendLine(@""); } /// public void EndRow() { _stringBuilder.AppendLine(@""); } /// public void AddCell(string value) { AddCell(value, 1); } /// public void AddCell(string value, int colspan, string backgroundColor = "#ffffff") { _stringBuilder.AppendLine(string.Format(@"{2}", colspan, backgroundColor, value)); } /// public void AddFullRow(IEnumerable values) { StartRow(); foreach (string value in values) { AddCell(value); } EndRow(); } /// public void AddHeading(string value) { StartRow(); _stringBuilder.AppendLine(string.Format(@"{0}", value)); EndRow(); } /// public string GetResult() { return _stringBuilder.ToString(); } } } ================================================ FILE: Composite/C1Console/Security/EntityTokenSerializer.cs ================================================ using System; using System.Reflection; using System.Security; using Composite.Core.Serialization; using Composite.Core.Types; using Composite.Core; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class EntityTokenSerializer { /// public static string Serialize(EntityToken entityToken) { return Serialize(entityToken, false); } /// public static string Serialize(EntityToken entityToken, bool includeHashValue) { Verify.ArgumentNotNull(entityToken, "entityToken"); return CompositeJsonSerializer.Serialize(entityToken, includeHashValue); } /// public static EntityToken Deserialize(string serializedEntityToken) { return Deserialize(serializedEntityToken, false); } /// public static EntityToken Deserialize(string serializedEntityToken, bool includeHashValue) { if (string.IsNullOrEmpty(serializedEntityToken)) throw new ArgumentNullException(nameof(serializedEntityToken)); EntityToken entityToken; if (CompositeJsonSerializer.IsJsonSerialized(serializedEntityToken)) { entityToken = CompositeJsonSerializer .Deserialize(serializedEntityToken, includeHashValue); } else { entityToken = DeserializeLegacy(serializedEntityToken, includeHashValue); Log.LogVerbose(nameof(EntityTokenSerializer), entityToken.GetType().FullName); } if (entityToken == null) { throw new EntityTokenSerializerException($"Deserialization function returned null value. EntityToken: '{serializedEntityToken}'"); } return entityToken; } private static EntityToken DeserializeLegacy(string serializedEntityToken, bool includeHashValue) { var dic = StringConversionServices.ParseKeyValueCollection(serializedEntityToken); if (!dic.ContainsKey("entityTokenType") || !dic.ContainsKey("entityToken") || (includeHashValue && !dic.ContainsKey("entityTokenHash"))) { throw new ArgumentException("Failed to deserialize the value. Is has to be serialized with EntityTokenSerializer.", nameof(serializedEntityToken)); } string entityTokenTypeString = StringConversionServices.DeserializeValueString(dic["entityTokenType"]); string entityTokenString = StringConversionServices.DeserializeValueString(dic["entityToken"]); if (includeHashValue) { string entityTokenHash = StringConversionServices.DeserializeValueString(dic["entityTokenHash"]); HashValue hashValue = HashValue.Deserialize(entityTokenHash); if (!HashSigner.ValidateSignedHash(entityTokenString, hashValue)) { throw new SecurityException("Serialized entity token is tampered"); } } Type entityType = TypeManager.GetType(entityTokenTypeString); MethodInfo methodInfo = entityType.GetMethod("Deserialize", BindingFlags.Public | BindingFlags.Static); if (methodInfo == null || !(typeof(EntityToken).IsAssignableFrom(methodInfo.ReturnType))) { throw new InvalidOperationException($"The entity token {entityType} is missing a public static Deserialize method taking a string as parameter and returning an {typeof(EntityToken)}"); } EntityToken entityToken; try { entityToken = (EntityToken)methodInfo.Invoke(null, new object[] { entityTokenString }); } catch (Exception ex) { throw new EntityTokenSerializerException($"Failed to deserialize entity token '{serializedEntityToken}'", ex); } if (entityToken == null) { throw new EntityTokenSerializerException($"Deserialization function returned null value. EntityToken: '{serializedEntityToken}'"); } return entityToken; } /// public static T Deserialize(string serializedEntityToken) where T : EntityToken { return (T)Deserialize(serializedEntityToken); } } } ================================================ FILE: Composite/C1Console/Security/EntityTokenSerializerException.cs ================================================ using System; namespace Composite.C1Console.Security { internal class EntityTokenSerializerException : Exception { public EntityTokenSerializerException(string message) : base(message) { } public EntityTokenSerializerException(string message, Exception innerException) : base( message, innerException) { } } } ================================================ FILE: Composite/C1Console/Security/Foundation/HookRegistratorRegistry.cs ================================================ using System.Collections.Generic; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.C1Console.Events; using Composite.C1Console.Security.Plugins.HookRegistrator; using Composite.C1Console.Security.Plugins.HookRegistrator.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Security.Foundation { internal static class HookRegistratorRegistry { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.DoInitializeResources); static HookRegistratorRegistry() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } public static IEnumerable HookRegistratorPluginNames { get { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.HookRegistratorPluginNames; } } } private static bool HasConfiguration() { var configSource = ConfigurationServices.ConfigurationSource; return configSource != null && configSource.GetSection(HookRegistratorSettings.SectionName) != null; } private static IConfigurationSource GetConfiguration() { IConfigurationSource source = ConfigurationServices.ConfigurationSource; if (null == source) { throw new ConfigurationErrorsException(string.Format("No configuration source specified")); } return source; } private static void Flush() { _resourceLocker.ResetInitialization(); } private sealed class Resources { public List HookRegistratorPluginNames { get; set; } public static void DoInitializeResources(Resources resources) { if (HasConfiguration()) { resources.HookRegistratorPluginNames = new List(); IConfigurationSource configurationSource = GetConfiguration(); var settings = configurationSource.GetSection(HookRegistratorSettings.SectionName) as HookRegistratorSettings; if (settings == null) { throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration", HookRegistratorSettings.SectionName)); } foreach (HookRegistratorData data in settings.HookRegistratorPlugins) { resources.HookRegistratorPluginNames.Add(data.Name); } } else { resources.HookRegistratorPluginNames = new List(); } } } } } ================================================ FILE: Composite/C1Console/Security/Foundation/PermissionTypeFacadeCaching.cs ================================================ using System.Collections.Generic; using System.Linq; using Composite.Core.Caching; namespace Composite.C1Console.Security.Foundation { internal static class PermissionTypeFacadeCaching { private static readonly string CurrentPermissionTypeCachingKey = "PermissionTypeFacadeCaching_CurrentPermissionTypeCachingKey"; private static readonly string InheritedPermissionsTypeCachingKey = "PermissionTypeFacadeCaching_InheritedPermissionsTypeCachingKey"; private static readonly string UserPermissionTypeCachingKey = "PermissionTypeFacadeCaching_UserPermissionTypeCachingKey"; private static readonly string UserGroupPermissionTypeCachingKey = "UserGroupPermissionTypeCachingKey_UserPermissionTypeCachingKey"; public static IReadOnlyCollection GetCurrentPermissionTypes(UserToken userToken, EntityToken entityToken) { return GetFromCache(userToken, entityToken, CurrentPermissionTypeCachingKey); } public static void SetCurrentPermissionTypes(UserToken userToken, EntityToken entityToken, IReadOnlyCollection permissionTypes) { SetToCache(userToken, entityToken, permissionTypes, CurrentPermissionTypeCachingKey); } public static IReadOnlyCollection GetInheritedPermissionsTypes(UserToken userToken, EntityToken entityToken) { return GetFromCache(userToken, entityToken, InheritedPermissionsTypeCachingKey); } public static void SetInheritedPermissionsTypes(UserToken userToken, EntityToken entityToken, IReadOnlyCollection permissionTypes) { SetToCache(userToken, entityToken, permissionTypes, InheritedPermissionsTypeCachingKey); } public static IReadOnlyCollection GetUserPermissionTypes(UserToken userToken, EntityToken entityToken) { return GetFromCache(userToken, entityToken, UserPermissionTypeCachingKey); } public static void SetUserPermissionTypes(UserToken userToken, EntityToken entityToken, IReadOnlyCollection permissionTypes) { SetToCache(userToken, entityToken, permissionTypes, UserPermissionTypeCachingKey); } public static IReadOnlyCollection GetUserGroupPermissionTypes(UserToken userToken, EntityToken entityToken) { return GetFromCache(userToken, entityToken, UserGroupPermissionTypeCachingKey); } public static void SetUserGroupPermissionTypes(UserToken userToken, EntityToken entityToken, IReadOnlyCollection permissionTypes) { SetToCache(userToken, entityToken, permissionTypes, UserGroupPermissionTypeCachingKey); } public static bool CachingWorking { get { return RequestLifetimeCache.HasKey(UserPermissionTypeCachingKey) && RequestLifetimeCache.HasKey(UserGroupPermissionTypeCachingKey); } } private static void SetToCache(UserToken userToken, EntityToken entityToken, IReadOnlyCollection permissionTypes, object cachingKey) { // Using RequestLifetimeCache and there for no thread locking /MRJ Dictionary>> permissionTypeCache; if (RequestLifetimeCache.HasKey(cachingKey)) { permissionTypeCache = RequestLifetimeCache.TryGet>>>(cachingKey); } else { permissionTypeCache = new Dictionary>>(); RequestLifetimeCache.Add(cachingKey, permissionTypeCache); } Dictionary> entityTokenPermissionTypes; if (!permissionTypeCache.TryGetValue(userToken, out entityTokenPermissionTypes)) { entityTokenPermissionTypes = new Dictionary>(); permissionTypeCache.Add(userToken, entityTokenPermissionTypes); } if (!entityTokenPermissionTypes.ContainsKey(entityToken)) { entityTokenPermissionTypes.Add(entityToken, permissionTypes); } else { entityTokenPermissionTypes[entityToken] = entityTokenPermissionTypes[entityToken].Concat(permissionTypes).Distinct().ToList(); } } private static IReadOnlyCollection GetFromCache(UserToken userToken, EntityToken entityToken, object cachingKey) { var permissionTypeCache = RequestLifetimeCache.TryGet>>>(cachingKey); if (permissionTypeCache == null || !permissionTypeCache.TryGetValue(userToken, out var entityTokenPermissionTypes)) { return null; } entityTokenPermissionTypes.TryGetValue(entityToken, out var permissionTypes); return permissionTypes; } } } ================================================ FILE: Composite/C1Console/Security/Foundation/PluginFacades/HookRegistratorPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.C1Console.Events; using Composite.C1Console.Security.Plugins.HookRegistrator; using Composite.C1Console.Security.Plugins.HookRegistrator.Runtime; namespace Composite.C1Console.Security.Foundation.PluginFacades { internal static class HookRegistratorPluginFacade { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); private static object _lock = new object(); static HookRegistratorPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static IEnumerable GetHooks(string pluginName) { using (_resourceLocker.Locker) { return GetHookRegistratorProvider(pluginName).GetHooks(); } } private static IHookRegistrator GetHookRegistratorProvider(string pluginName) { using (_resourceLocker.Locker) { IHookRegistrator hookRegistrator; if (_resourceLocker.Resources.HookRegistratorCache.TryGetValue(pluginName, out hookRegistrator) == false) { try { hookRegistrator = _resourceLocker.Resources.Factory.Create(pluginName); _resourceLocker.Resources.HookRegistratorCache.Add(pluginName, hookRegistrator); } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } return hookRegistrator; } } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw ex; /* ConfigurationErrorsException newEx = new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", LoginProviderSettings.SectionName), ex); if (ExceptionService.HandleException(newEx, Policy.Plugin) == HandleResult.Rethrow) { throw newEx; }*/ } private sealed class Resources { public HookRegistratorFactory Factory { get; set; } public Dictionary HookRegistratorCache { get; set; } public static void Initialize(Resources resources) { try { resources.Factory = new HookRegistratorFactory(); resources.HookRegistratorCache = new Dictionary(); } catch (NullReferenceException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } } } } ================================================ FILE: Composite/C1Console/Security/Foundation/PluginFacades/LoginProviderPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.C1Console.Events; using Composite.C1Console.Security.Plugins.LoginProvider; using Composite.C1Console.Security.Plugins.LoginProvider.Runtime; namespace Composite.C1Console.Security.Foundation.PluginFacades { internal class LoginProviderPluginFacade { private static readonly ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.DoInitializeResources); static LoginProviderPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } public static IEnumerable AllUsernames { get { return _resourceLocker.Resources.Plugin.AllUsernames; } } public static bool CanSetUserPassword { get { return _resourceLocker.Resources.Plugin.CanSetUserPassword; } } public static bool CanAddNewUser { get { return _resourceLocker.Resources.Plugin.CanAddNewUser; } } public static bool UsersExists { get { return _resourceLocker.Resources.Plugin.UsersExists; } } public static LoginResult FormValidateUser(string userName, string password) { var validator = _resourceLocker.Resources.Plugin as IFormLoginProvider; return validator.Validate(userName, password); } public static void FormSetUserPassword(string userName, string password) { var validator = _resourceLocker.Resources.Plugin as IFormLoginProvider; validator.SetUserPassword(userName, password); } public static void FormAddNewUser(string userName, string password, string group, string email) { var validator = _resourceLocker.Resources.Plugin as IFormLoginProvider; Verify.That(validator.CanAddNewUser, "Login provider does not support adding users"); validator.AddNewUser(userName, password, group, email); } public static bool WindowsValidateUser(string userName, string domainName) { var validator = _resourceLocker.Resources.Plugin as IWindowsLoginProvider; return validator.Validate(userName, domainName); } /// /// Returns a Type object containing the type of the current plugin /// /// public static bool CheckType() { return _resourceLocker.Resources.Plugin is T; } public static Type GetValidationPluginType() { return _resourceLocker.Resources.Plugin.GetType(); } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", LoginProviderSettings.SectionName), ex); } private sealed class Resources { public LoginProviderFactory Factory { get; set; } public ILoginProvider Plugin { get; set; } public static void DoInitializeResources(Resources resources) { try { resources.Factory = new LoginProviderFactory(); resources.Plugin = resources.Factory.CreateDefault(); } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } } } } ================================================ FILE: Composite/C1Console/Security/Foundation/PluginFacades/LoginSessionStorePluginFacade.cs ================================================ using System; using System.Configuration; using System.Net; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.C1Console.Events; using Composite.C1Console.Security.BuildinPlugins.BuildinLoginSessionStore; using Composite.C1Console.Security.Plugins.LoginSessionStore; using Composite.C1Console.Security.Plugins.LoginSessionStore.Runtime; namespace Composite.C1Console.Security.Foundation.PluginFacades { internal class LoginSessionStorePluginFacade { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.DoInitializeResources); static LoginSessionStorePluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } public static bool HasConfiguration() { return ConfigurationServices.ConfigurationSource?.GetSection(LoginSessionStoreSettings.SectionName) != null; } public static bool CanPersistAcrossSessions { get { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.Provider.CanPersistAcrossSessions; } } } public static void StoreUsername(string userName, bool persistAcrossSessions) { using (_resourceLocker.ReadLocker) { _resourceLocker.Resources.Provider.StoreUsername(userName, persistAcrossSessions); } } public static string Logout() { using (_resourceLocker.ReadLocker) { var provider = _resourceLocker.Resources.Provider; provider.FlushUsername(); return (provider as ILoginSessionStoreRedirectedLogout)?.LogoutUrl; } } public static string StoredUsername => _resourceLocker.Resources.Provider.StoredUsername; public static IPAddress UserIpAddress { get { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.Provider.UserIpAddress; } } } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException($"Failed to load the configuration section '{LoginSessionStoreSettings.SectionName}' from the configuration.", ex); } private sealed class Resources { private LoginSessionStoreFactory Factory { get; set; } public ILoginSessionStore Provider { get; private set; } public static void DoInitializeResources(Resources resources) { if (LoginSessionStorePluginFacade.HasConfiguration()) { try { resources.Factory = new LoginSessionStoreFactory(); resources.Provider = resources.Factory.CreateDefault(); } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } else if (RuntimeInformation.IsUnittest) { // This is a fallback for unittests resources.Provider = new BuildinLoginSessionStore(); } } } } } ================================================ FILE: Composite/C1Console/Security/Foundation/PluginFacades/PasswordRulePluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using Composite.C1Console.Security.Plugins.PasswordPolicy; using Composite.C1Console.Security.Plugins.PasswordPolicy.Runtime; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.C1Console.Events; using Composite.Core; using Composite.Data.Types; namespace Composite.C1Console.Security.Foundation.PluginFacades { internal static class PasswordRulePluginFacade { private static readonly ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.DoInitializeResources); static PasswordRulePluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } /// /// Validates the password against the rules defined in the configuration. /// /// /// /// /// public static bool ValidatePassword(IUser user, string password, out IList validationMessages) { bool isValid = true; validationMessages = new List(); foreach (var rule in _resourceLocker.Resources.PasswordRules) { if (!rule.ValidatePassword(user, password)) { isValid = false; validationMessages.Add(rule.GetRuleDescription()); } } return isValid; } public static int PasswordExpirationTimeInDays { get { var settings = GetSettings(); return settings?.PasswordExpirationTimeInDays ?? 0; } } public static int PasswordHistoryLength { get { var settings = GetSettings(); return settings?.PasswordHistoryLength ?? 0; } } private static PasswordPolicySettings GetSettings() { var configuration = ConfigurationServices.ConfigurationSource; return configuration?.GetSection(PasswordPolicySettings.SectionName) as PasswordPolicySettings; } public static bool HasConfiguration() { return GetSettings() != null; } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException($"Failed to load the configuration section '{PasswordPolicySettings.SectionName}' from the configuration.", ex); } private sealed class Resources { PasswordRuleFactory Factory { get; set; } public IReadOnlyCollection PasswordRules { get; private set; } public static void DoInitializeResources(Resources resources) { var settings = GetSettings(); if (settings == null) { Log.LogWarning(nameof(PasswordRulePluginFacade), $"Composite.config is missing '{PasswordPolicySettings.SectionName}' section"); resources.PasswordRules = new IPasswordRule[0]; return; } try { var factory = resources.Factory = new PasswordRuleFactory(); var rules = settings.PasswordRules.Select(passwordRuleData => factory.Create(passwordRuleData.Name)).ToList(); resources.PasswordRules = rules; } catch (Exception ex) { if (!(ex is ArgumentException) && !(ex is ConfigurationErrorsException)) throw; HandleConfigurationError(ex); } } } } } ================================================ FILE: Composite/C1Console/Security/Foundation/PluginFacades/UserGroupDefinitionProviderPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.C1Console.Events; using Composite.C1Console.Security.Plugins.UserGroupPermissionDefinitionProvider; using Composite.C1Console.Security.Plugins.UserGroupPermissionDefinitionProvider.Runtime; using Composite.Core.Extensions; namespace Composite.C1Console.Security.Foundation.PluginFacades { internal static class UserGroupPermissionDefinitionProviderPluginFacade { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.DoInitializeResources); static UserGroupPermissionDefinitionProviderPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static IEnumerable AllUserGroupPermissionDefinitions { get { return _resourceLocker.Resources.Plugin.AllUserGroupPermissionDefinitions; } } public static bool CanAlterDefinitions { get { return _resourceLocker.Resources.Plugin.CanAlterDefinitions; } } public static IEnumerable GetPermissionsByUserGroup(Guid userGroupId) { return _resourceLocker.Resources.Plugin.GetPermissionsByUserGroup(userGroupId); } public static void SetUserGroupPermissionDefinition(UserGroupPermissionDefinition userGroupPermissionDefinition) { Verify.ArgumentNotNull(userGroupPermissionDefinition, "userGroupPermissionDefinition"); Verify.ArgumentCondition(!userGroupPermissionDefinition.SerializedEntityToken.IsNullOrEmpty(), "userGroupPermissionDefinition", "SerializedEntityToken is empty"); Verify.ArgumentCondition(userGroupPermissionDefinition.UserGroupId != Guid.Empty, "userGroupPermissionDefinition", "Is Guid.Empty"); _resourceLocker.Resources.Plugin.SetUserGroupPermissionDefinition(userGroupPermissionDefinition); } public static void RemoveUserGroupPermissionDefinition(Guid userGroupID, string serializedEntityToken) { if (userGroupID == Guid.Empty) throw new ArgumentNullException("userGroupID"); if (string.IsNullOrEmpty(serializedEntityToken)) throw new ArgumentNullException("serializedEntityToken"); _resourceLocker.Resources.Plugin.RemoveUserGroupPermissionDefinition(userGroupID, serializedEntityToken); } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", UserGroupPermissionDefinitionProviderSettings.SectionName), ex); } private sealed class Resources { public UserGroupPermissionDefinitionProviderFactory Factory { get; set; } public IUserGroupPermissionDefinitionProvider Plugin { get; set; } public static void DoInitializeResources(Resources resources) { try { resources.Factory = new UserGroupPermissionDefinitionProviderFactory(); resources.Plugin = resources.Factory.CreateDefault(); } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } } } } ================================================ FILE: Composite/C1Console/Security/Foundation/PluginFacades/UserRoleDefinitionProviderPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.C1Console.Events; using Composite.C1Console.Security.BuildinPlugins.BuildinUserPermissionDefinitionProvider; using Composite.C1Console.Security.Plugins.UserPermissionDefinitionProvider; using Composite.C1Console.Security.Plugins.UserPermissionDefinitionProvider.Runtime; namespace Composite.C1Console.Security.Foundation.PluginFacades { internal static class UserPermissionDefinitionProviderPluginFacade { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.DoInitializeResources); static UserPermissionDefinitionProviderPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static bool HasConfiguration() { return (ConfigurationServices.ConfigurationSource != null) && (ConfigurationServices.ConfigurationSource.GetSection(UserPermissionDefinitionProviderSettings.SectionName) != null); } public static IEnumerable AllUserPermissionDefinitions { get { return _resourceLocker.Resources.Plugin.AllUserPermissionDefinitions; } } public static bool CanAlterDefinitions { get { return _resourceLocker.Resources.Plugin.CanAlterDefinitions; } } public static void SetUserPermissionDefinition(UserPermissionDefinition userPermissionDefinition) { if (userPermissionDefinition == null) throw new ArgumentNullException("userPermissionDefinition"); if (string.IsNullOrEmpty(userPermissionDefinition.SerializedEntityToken)) throw new ArgumentNullException("userPermissionDefinition"); if (string.IsNullOrEmpty(userPermissionDefinition.Username)) throw new ArgumentNullException("userPermissionDefinition"); _resourceLocker.Resources.Plugin.SetUserPermissionDefinition(userPermissionDefinition); } public static void RemoveUserPermissionDefinition(UserToken userToken, string serializedEntityToken) { if (userToken == null) throw new ArgumentNullException("userToken"); if (string.IsNullOrEmpty(serializedEntityToken)) throw new ArgumentNullException("serializedEntityToken"); _resourceLocker.Resources.Plugin.RemoveUserPermissionDefinition(userToken, serializedEntityToken); } public static IEnumerable GetPermissionsByUser(string userName) { return _resourceLocker.Resources.Plugin.GetPermissionsByUser(userName); } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", UserPermissionDefinitionProviderSettings.SectionName), ex); } private sealed class Resources { public UserPermissionDefinitionProviderFactory Factory { get; set; } public IUserPermissionDefinitionProvider Plugin { get; set; } public static void DoInitializeResources(Resources resources) { if (HasConfiguration()) { try { resources.Factory = new UserPermissionDefinitionProviderFactory(); resources.Plugin = resources.Factory.CreateDefault(); } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } else { resources.Plugin = new BuildinUserPermissionDefinitionProvider(); } } } } } ================================================ FILE: Composite/C1Console/Security/Foundation/RelationshipGraphLevelEnumerable.cs ================================================ using System.Collections; using System.Collections.Generic; namespace Composite.C1Console.Security.Foundation { internal sealed class RelationshipGraphLevelEnumerable : IEnumerable { private RelationshipGraph _relationshipGraph; internal RelationshipGraphLevelEnumerable(RelationshipGraph relationshipGraph) { _relationshipGraph = relationshipGraph; } public IEnumerator GetEnumerator() { return new RelationshipGraphLevelEnumerator(_relationshipGraph); } IEnumerator IEnumerable.GetEnumerator() { return new RelationshipGraphLevelEnumerator(_relationshipGraph); } } } ================================================ FILE: Composite/C1Console/Security/Foundation/RelationshipGraphLevelEnumerator.cs ================================================ using System.Collections; using System.Collections.Generic; namespace Composite.C1Console.Security.Foundation { internal sealed class RelationshipGraphLevelEnumerator : IEnumerator { private RelationshipGraph _relationshipGraph; private RelationshipGraphLevel _currentLevel = null; internal RelationshipGraphLevelEnumerator(RelationshipGraph relationshipGraph) { _relationshipGraph = relationshipGraph; } public RelationshipGraphLevel Current { get { return _currentLevel; } } public void Dispose() { #if LeakCheck System.GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = System.Environment.StackTrace; /// ~RelationshipGraphLevelEnumerator() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif object IEnumerator.Current { get { return _currentLevel; } } public bool MoveNext() { int levelNumber; if (_currentLevel == null) { levelNumber = 0; } else { levelNumber = _currentLevel.Level + 1; } RelationshipGraphLevel newLevel = _relationshipGraph.GetLevel(levelNumber); if (newLevel == null) return false; _currentLevel = newLevel; return true; } public void Reset() { _currentLevel = null; } } } ================================================ FILE: Composite/C1Console/Security/Foundation/SecurityAncestorFacade.cs ================================================ using System; using System.Collections.Generic; namespace Composite.C1Console.Security.Foundation { internal static class SecurityAncestorFacade { public static IEnumerable GetParents(EntityToken entityToken) { if (entityToken == null) throw new ArgumentNullException("entityToken"); ISecurityAncestorProvider provider = SecurityAncestorProviderCache.GetSecurityAncestorProvider(entityToken); IEnumerable result = provider.GetParents(entityToken); return result; } } } ================================================ FILE: Composite/C1Console/Security/Foundation/SecurityAncestorProviderCache.cs ================================================ using System; using Composite.C1Console.Events; using Composite.Core.Collections.Generic; namespace Composite.C1Console.Security.Foundation { internal static class SecurityAncestorProviderCache { private static Hashtable _securityAncestorProviderCache = new Hashtable(); private static object _lock = new object(); static SecurityAncestorProviderCache() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlush); } public static ISecurityAncestorProvider GetSecurityAncestorProvider(EntityToken entityToken) { Verify.ArgumentNotNull(entityToken, "entityToken"); ISecurityAncestorProvider securityAncestorProvider; Type entityTokenType = entityToken.GetType(); if (_securityAncestorProviderCache.TryGetValue(entityTokenType, out securityAncestorProvider) == false) { lock (_lock) { if (_securityAncestorProviderCache.TryGetValue(entityTokenType, out securityAncestorProvider) == false) { object[] attributes = entityTokenType.GetCustomAttributes(typeof(SecurityAncestorProviderAttribute), true); Verify.That(attributes.Length > 0, "Missing {0} attribute on the entity token {1}", typeof(SecurityAncestorProviderAttribute), entityTokenType); var attribute = (SecurityAncestorProviderAttribute)attributes[0]; Verify.IsNotNull(attribute.SecurityAncestorProviderType, "Security ancestor provider type can not be null on the entity token {0}", entityTokenType); Verify.That(typeof(ISecurityAncestorProvider).IsAssignableFrom(attribute.SecurityAncestorProviderType), "Security ancestor provider '{0}' should implement the interface '{1}'", attribute.SecurityAncestorProviderType, typeof(ISecurityAncestorProvider)); securityAncestorProvider = (ISecurityAncestorProvider)Activator.CreateInstance(attribute.SecurityAncestorProviderType); _securityAncestorProviderCache.Add(entityTokenType, securityAncestorProvider); } } } return securityAncestorProvider; } private static void Flush() { lock (_lock) { _securityAncestorProviderCache = new Hashtable(); } } private static void OnFlush(FlushEventArgs args) { Flush(); } } } ================================================ FILE: Composite/C1Console/Security/HashSigner.cs ================================================ namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class HashSigner { private const int _privateKey = 180226750; /// public static HashValue GetSignedHash(string content) { int hashCode = content.GetHashCode(); return new HashValue(hashCode ^ _privateKey); } /// public static bool ValidateSignedHash(string content, HashValue hashValue) { HashValue newHashValue = GetSignedHash(content); return newHashValue.Equals(hashValue); } } } ================================================ FILE: Composite/C1Console/Security/HashValue.cs ================================================ using System; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class HashValue { private int _value; /// public HashValue(int value) { _value = value; } /// public string Serialize() { return _value.ToString(); } /// public static HashValue Deserialize(string serializedHashValue) { int value; if (int.TryParse(serializedHashValue, out value) == false) { throw new ArgumentException("The string is not a valid serialized hash value"); } return new HashValue(value); } /// public override bool Equals(object obj) { return Equals(obj as HashValue); } /// public bool Equals(HashValue hashValue) { if (hashValue == null) return false; return _value == hashValue._value; } /// public override string ToString() { return _value.ToString(); } /// public override int GetHashCode() { return _value.GetHashCode(); } } } ================================================ FILE: Composite/C1Console/Security/HookingFacade.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using Composite.C1Console.Events; using Composite.Core; namespace Composite.C1Console.Security { /// /// /// [EditorBrowsable(EditorBrowsableState.Never)] public delegate void DirtyHooksCallbackDelegate(); /// /// /// [EditorBrowsable(EditorBrowsableState.Never)] public static class HookingFacade { /// public delegate void NewElementProviderRootEntitiesDelegate(HookingFacadeEventArgs hookingFacadeEventArgs); private static IHookingFacade _hookingFacade = new HookingFacadeImpl(); static HookingFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } /// public static void EnsureInitialization() { _hookingFacade.EnsureInitialization(); } /// public static IEnumerable GetHookies(EntityToken hooker) { try { using (GlobalInitializerFacade.CoreIsInitializedScope) { return _hookingFacade.GetHookies(hooker); } } catch (Exception ex) { Log.LogCritical("HookingFacade", ex); GlobalInitializerFacade.FatalResetTheSystem(); throw; } } /// public static IEnumerable GetParentHookers() { try { using (GlobalInitializerFacade.CoreIsInitializedScope) { return _hookingFacade.GetParentHookers(); } } catch (Exception ex) { Log.LogCritical("HookingFacade", ex); GlobalInitializerFacade.FatalResetTheSystem(); throw; } } /// public static IEnumerable GetParentToChildHooks(EntityToken parentEntityToken) { try { using (GlobalInitializerFacade.CoreIsInitializedScope) { return _hookingFacade.GetParentToChildHooks(parentEntityToken); } } catch (Exception ex) { Log.LogCritical("HookingFacade", ex); GlobalInitializerFacade.FatalResetTheSystem(); throw; } } /// public static void RemoveHook(EntityTokenHook entityTokenHook) { RemoveHooks(new [] { entityTokenHook}); } /// public static void RemoveHooks(IEnumerable entityTokenHooks) { try { using (GlobalInitializerFacade.CoreIsInitializedScope) { _hookingFacade.RemoveHooks(entityTokenHooks); } } catch (Exception ex) { Log.LogCritical("HookingFacade", ex); GlobalInitializerFacade.FatalResetTheSystem(); throw; } } /// public static void AddHook(EntityTokenHook entityTokenHook) { AddHooks(new[] {entityTokenHook}); } /// public static void AddHooks(IEnumerable entityTokenHooks) { try { using (GlobalInitializerFacade.CoreIsInitializedScope) { _hookingFacade.AddHooks(entityTokenHooks); } } catch (Exception ex) { Log.LogCritical("HookingFacade", ex); GlobalInitializerFacade.FatalResetTheSystem(); throw; } } /// /// Use this method to register a callback method that will be called when fully updated hooks are needed. /// /// /// The id of the callback method. This ensures that only one callback is registered /// for each id. /// /// /// public static void RegisterDirtyCallback(string id, DirtyHooksCallbackDelegate dirtyHooksCallbackDelegate) { using (GlobalInitializerFacade.CoreIsInitializedScope) { _hookingFacade.RegisterDirtyCallback(id, dirtyHooksCallbackDelegate); } } /// public static void SubscribeToNewElementProviderRootEntitiesEvent(NewElementProviderRootEntitiesDelegate newElementProviderRootEntitiesDelegate) { using (GlobalInitializerFacade.CoreIsInitializedScope) { _hookingFacade.SubscribeToNewElementProviderRootEntitiesEvent(newElementProviderRootEntitiesDelegate); } } /// public static void UnsubscribeFromNewElementProviderRootEntitiesEvent(NewElementProviderRootEntitiesDelegate newElementProviderRootEntitiesDelegate) { using (GlobalInitializerFacade.CoreIsInitializedScope) { _hookingFacade.UnsubscribeFromNewElementProviderRootEntitiesEvent(newElementProviderRootEntitiesDelegate); } } /// public static void FireNewElementProviderRootEntitiesEvent(string providerName) { using (GlobalInitializerFacade.CoreIsInitializedScope) { _hookingFacade.FireNewElementProviderRootEntitiesEvent(providerName); } } private static void OnFlushEvent(FlushEventArgs args) { _hookingFacade.Flush(); } } } ================================================ FILE: Composite/C1Console/Security/HookingFacadeEventArgs.cs ================================================ using System; using System.ComponentModel; namespace Composite.C1Console.Security { /// /// /// [EditorBrowsable(EditorBrowsableState.Never)] public sealed class HookingFacadeEventArgs : EventArgs { /// public HookingFacadeEventArgs(string providerName) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); this.ProviderName = providerName; } /// public string ProviderName { get; private set; } } } ================================================ FILE: Composite/C1Console/Security/HookingFacadeImpl.cs ================================================ using System.Collections.Generic; using System; using System.Linq; using System.Web.Hosting; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.Instrumentation; using Composite.C1Console.Security.Foundation; using Composite.C1Console.Security.Foundation.PluginFacades; using Composite.Data; using Composite.Core.Types; namespace Composite.C1Console.Security { internal sealed class HookingFacadeImpl : IHookingFacade { private event HookingFacade.NewElementProviderRootEntitiesDelegate _newElementProviderRootEntitiesEvent; private EvaluatedHooks _evaluatedHooks; private DateTime _lastFlushDateTime = DateTime.MinValue; private bool _isInitializing; private Dictionary _dirtyHooksCallbackDelegates = new Dictionary(); private readonly object _lock = new object(); private readonly object _changesQueueSyncRoot = new object(); private readonly List> _changesQueue = new List>(); private class EvaluatedHooks { public Dictionary> ParentToChild = new Dictionary>(); public Dictionary> ChildToParent = new Dictionary>(); } public void EnsureInitialization() { GetEvaluatedHooks(); } private EvaluatedHooks GetEvaluatedHooks() { var evaluatedHooks = _evaluatedHooks; if (evaluatedHooks != null) return evaluatedHooks; lock (_lock) { evaluatedHooks = _evaluatedHooks; if (evaluatedHooks != null) return evaluatedHooks; Verify.IsFalse(_isInitializing, "Calling to HookingFacade while it's initializing is not allowed"); _isInitializing = true; DateTime calculationTime = DateTime.Now; try { ClearChangesQueue(); evaluatedHooks = DoInitializeFromRegistrator(); var dirtyHooksCallbackDelegates = _dirtyHooksCallbackDelegates; if (dirtyHooksCallbackDelegates.Count > 0) { var delegates = new Dictionary(dirtyHooksCallbackDelegates); _dirtyHooksCallbackDelegates = new Dictionary(); foreach (DirtyHooksCallbackDelegate dirtyHooksCallbackDelegate in delegates.Values) { try { dirtyHooksCallbackDelegate(); } catch (Exception ex) { Log.LogError("HookingFacade", ex); } } } ApplyQueuedChanges(evaluatedHooks); if (calculationTime > _lastFlushDateTime) { _evaluatedHooks = evaluatedHooks; } return evaluatedHooks; } finally { _isInitializing = false; } } } public IEnumerable GetHookies(EntityToken hook) { Verify.ArgumentNotNull(hook, "hook"); var evaluatedHooks = GetEvaluatedHooks(); List hooks; return evaluatedHooks.ChildToParent.TryGetValue(hook, out hooks) ? hooks : null; } public IEnumerable GetParentHookers() { var evaluatedHooks = GetEvaluatedHooks(); return evaluatedHooks.ParentToChild.Keys; } public IEnumerable GetParentToChildHooks(EntityToken parentEntityToken) { Verify.ArgumentNotNull(parentEntityToken, "parentEntityToken"); var evaluatedHooks = GetEvaluatedHooks(); List hooks; return evaluatedHooks.ParentToChild.TryGetValue(parentEntityToken, out hooks) ? hooks : null; } private void RemoveHookInternal(EvaluatedHooks hooks, EntityTokenHook entityTokenHook) { Verify.ArgumentNotNull(entityTokenHook, "entityTokenHook"); if (hooks.ParentToChild.ContainsKey(entityTokenHook.Hooker)) { List hookies = hooks.ParentToChild[entityTokenHook.Hooker]; foreach (EntityToken hookie in hookies) { hooks.ChildToParent[hookie].Remove(entityTokenHook.Hooker); if (hooks.ChildToParent[hookie].Count == 0) { hooks.ChildToParent.Remove(hookie); } } hooks.ParentToChild.Remove(entityTokenHook.Hooker); } } public void RemoveHooks(IEnumerable entityTokenHooks) { Verify.ArgumentNotNull(entityTokenHooks, "entityTokenHooks"); lock (_changesQueueSyncRoot) { _changesQueue.AddRange(entityTokenHooks.Select(hook => new Pair(false, hook))); } } private void AddHookInternal(EvaluatedHooks hooks, EntityTokenHook entityTokenHook) { Verify.ArgumentNotNull(entityTokenHook, "entityTokenHook"); List hookies; if (!hooks.ParentToChild.TryGetValue(entityTokenHook.Hooker, out hookies)) { hooks.ParentToChild.Add(entityTokenHook.Hooker, entityTokenHook.Hookies.ToList()); } else { foreach (var entityToken in entityTokenHook.Hookies) { if (!hookies.Contains(entityToken)) { hookies.Add(entityToken); } } } foreach (EntityToken hookie in entityTokenHook.Hookies) { List hookers; if (!hooks.ChildToParent.TryGetValue(hookie, out hookers)) { hookers = new List(); hooks.ChildToParent.Add(hookie, hookers); } else if (hookers.Contains(entityTokenHook.Hooker)) { continue; } hookers.Add(entityTokenHook.Hooker); } } public void AddHooks(IEnumerable entityTokenHooks) { Verify.ArgumentNotNull(entityTokenHooks, "entityTokenHooks"); lock (_changesQueueSyncRoot) { _changesQueue.AddRange(entityTokenHooks.Select(hook => new Pair(true, hook))); } } public void RegisterDirtyCallback(string id, DirtyHooksCallbackDelegate dirtyHooksCallbackDelegate) { Verify.ArgumentNotNull(dirtyHooksCallbackDelegate, "dirtyHooksCallbackDelegate"); lock (_lock) { if (!_dirtyHooksCallbackDelegates.ContainsKey(id)) { _dirtyHooksCallbackDelegates.Add(id, dirtyHooksCallbackDelegate); } } } public void SubscribeToNewElementProviderRootEntitiesEvent(HookingFacade.NewElementProviderRootEntitiesDelegate newElementProviderRootEntitiesDelegate) { lock (_lock) { _newElementProviderRootEntitiesEvent += newElementProviderRootEntitiesDelegate; } } public void UnsubscribeFromNewElementProviderRootEntitiesEvent(HookingFacade.NewElementProviderRootEntitiesDelegate newElementProviderRootEntitiesDelegate) { lock (_lock) { _newElementProviderRootEntitiesEvent -= newElementProviderRootEntitiesDelegate; } } public void FireNewElementProviderRootEntitiesEvent(string providerName) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); lock (_lock) { EnsureInitialization(); HookingFacade.NewElementProviderRootEntitiesDelegate del = _newElementProviderRootEntitiesEvent; if (del != null) { del(new HookingFacadeEventArgs(providerName)); } } } public void Flush() { _lastFlushDateTime = DateTime.Now; _evaluatedHooks = null; _dirtyHooksCallbackDelegates = new Dictionary(); } private EvaluatedHooks DoInitializeFromRegistrator() { var result = new EvaluatedHooks(); using (GlobalInitializerFacade.CoreIsInitializedScope) { if (HostingEnvironment.ApplicationHost.ShutdownInitiated()) { return result; } using(new LogExecutionTime("RGB(194, 252, 131)HookingFacade", "Initializing Entity Hooks")) using (new DataScope(DataScopeIdentifier.Administrated)) { Verify.That(GlobalInitializerFacade.SystemCoreInitialized, "Expected system core to be initialized"); foreach (string name in HookRegistratorRegistry.HookRegistratorPluginNames) { var entityTokenHooks = HookRegistratorPluginFacade.GetHooks(name); foreach (EntityTokenHook entityTokenHook in entityTokenHooks) { List hookies = result.ParentToChild.GetOrAdd(entityTokenHook.Hooker, () => new List()); hookies.AddRange(entityTokenHook.Hookies); } } foreach (KeyValuePair> kvp in result.ParentToChild) { foreach (EntityToken hookie in kvp.Value) { List hookers = result.ChildToParent.GetOrAdd(hookie, () => new List()); hookers.Add(kvp.Key); } } } } return result; } private void ClearChangesQueue() { lock (_changesQueueSyncRoot) { _changesQueue.Clear(); } } private void ApplyQueuedChanges(EvaluatedHooks evaluatedHooks) { lock (_changesQueueSyncRoot) { foreach (Pair change in _changesQueue) { if (change.First) { AddHookInternal(evaluatedHooks, change.Second); } else { RemoveHookInternal(evaluatedHooks, change.Second); } } _changesQueue.Clear(); } } } } ================================================ FILE: Composite/C1Console/Security/IAuxiliarySecurityAncestorFacade.cs ================================================ using System; using System.Collections.Generic; namespace Composite.C1Console.Security { internal interface IAuxiliarySecurityAncestorFacade { IEnumerable GetParents(EntityToken entityToken); void AddAuxiliaryAncestorProvider(Type entityTokenType, IAuxiliarySecurityAncestorProvider auxiliarySecurityAncestorProvider, bool flushPersistent); void RemoveAuxiliaryAncestorProvider(Type entityTokenType, IAuxiliarySecurityAncestorProvider auxiliarySecurityAncestorProvider); IEnumerable GetAuxiliaryAncestorProviders(Type entityTokenType); void Flush(); } } ================================================ FILE: Composite/C1Console/Security/IAuxiliarySecurityAncestorProvider.cs ================================================ using System.Collections.Generic; namespace Composite.C1Console.Security { /// /// To add a see . /// Typically added from a element provider /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IAuxiliarySecurityAncestorProvider { /// /// If the entityToken do not have any parents, this method should return an entry in the dictionary with a IEnumerable /// with zero elements. /// /// /// /// A dictionary with where child entity token is key and the value of this key /// is enumerable of the parent entity tokens - possibly empty Dictionary> GetParents(IEnumerable entityTokens); } } ================================================ FILE: Composite/C1Console/Security/IHookingFacade.cs ================================================ using System.Collections.Generic; namespace Composite.C1Console.Security { internal interface IHookingFacade { void EnsureInitialization(); IEnumerable GetHookies(EntityToken hooker); IEnumerable GetParentHookers(); IEnumerable GetParentToChildHooks(EntityToken parentEntityToken); void RemoveHooks(IEnumerable entityTokenHooks); void AddHooks(IEnumerable entityTokenHooks); void RegisterDirtyCallback(string id, DirtyHooksCallbackDelegate dirtyHooksCallbackDelegate); void SubscribeToNewElementProviderRootEntitiesEvent(HookingFacade.NewElementProviderRootEntitiesDelegate newElementProviderRootEntitiesDelegate); void UnsubscribeFromNewElementProviderRootEntitiesEvent(HookingFacade.NewElementProviderRootEntitiesDelegate newElementProviderRootEntitiesDelegate); void FireNewElementProviderRootEntitiesEvent(string providerName); void Flush(); } } ================================================ FILE: Composite/C1Console/Security/ISecurityAncestorProvider.cs ================================================ using System.Collections.Generic; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface ISecurityAncestorProvider { /// /// If the entityToken does not exists, this method should return null. /// If the entityToken do not have any parents, this method should return an IEnumerable /// with zero elements. /// /// /// IEnumerable GetParents(EntityToken entityToken); } } ================================================ FILE: Composite/C1Console/Security/LoginResult.cs ================================================ namespace Composite.C1Console.Security { /// /// Describing the result of a login validation /// public enum LoginResult { /// /// Success /// Success = 0, /// /// Incorrect password /// IncorrectPassword = 1, /// /// User does not exist /// UserDoesNotExist = 2, /// /// Login policy violated /// PolicyViolated = 3, /// /// User is locked after maximum login attempts /// UserLockedAfterMaxLoginAttempts = 4, /// /// User is locked by administrator /// UserLockedByAdministrator = 5, /// /// User's password has to be updated. /// PasswordUpdateRequired = 6 } } ================================================ FILE: Composite/C1Console/Security/NoSecurityEntityToken.cs ================================================ using Composite.C1Console.Security.SecurityAncestorProviders; namespace Composite.C1Console.Security { /// /// This will alway be shown and allow all actions on it. /// It is not possible for the user to set any permissions on it. /// Use with care!! /// [SecurityAncestorProvider(typeof(NoAncestorSecurityAncestorProvider))] internal sealed class NoSecurityEntityToken : EntityToken { public override string Type { get { return ""; } } public override string Source { get { return ""; } } public override string Id { get { return "NoSecurityEntityToken"; } } public override string Serialize() { return DoSerialize(); } public static EntityToken Deserialize(string serializeedEntityToken) { return new NoSecurityEntityToken(); } } } ================================================ FILE: Composite/C1Console/Security/ParentsFacade.cs ================================================ using System.Collections.Generic; namespace Composite.C1Console.Security { internal static class ParentsFacade { public static List GetAllParents(EntityToken entityToken) { return GetAllParents(entityToken, 1); } public static List GetAllParents(EntityToken entityToken, int levelCount) { RelationshipGraph graph = new RelationshipGraph(entityToken, RelationshipGraphSearchOption.Both, true); List tokens = new List(); int currentLevel = 0; foreach (RelationshipGraphLevel level in graph.Levels) { if (currentLevel > levelCount) { break; } else if ((currentLevel > 0) && (currentLevel <= levelCount)) { tokens.AddRange(level.AllEntities); } currentLevel++; } return tokens; } } } ================================================ FILE: Composite/C1Console/Security/PasswordPolicyFacade.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Security.Foundation.PluginFacades; using Composite.Data.Types; namespace Composite.C1Console.Security { /// /// Facade for calling password rule plugings. /// public static class PasswordPolicyFacade { /// /// Returns password expiration time in days. 0 will be returned if no expiration set. /// public static int PasswordExpirationTimeInDays { get { return PasswordRulePluginFacade.PasswordExpirationTimeInDays; } } /// /// /// public static int PasswordHistoryLength { get { return PasswordRulePluginFacade.PasswordHistoryLength; } } /// /// Validates the password against the rules defined in the configuration. /// /// The user information. /// The new password that has to be validated. /// The list of password rules that password did not satisfy. /// public static bool ValidatePassword(IUser user, string password, out IList validationMessages) { return PasswordRulePluginFacade.ValidatePassword(user, password, out validationMessages); } } } ================================================ FILE: Composite/C1Console/Security/PermissionDescriptor.cs ================================================ using System.Diagnostics; using Composite.Core.ResourceSystem; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DebuggerDisplay("PermissionType = {PermissionType}")] public sealed class PermissionDescriptor { /// public PermissionDescriptor(PermissionType permissionType) { this.PermissionType = permissionType; } /// public PermissionType PermissionType { get; private set; } /// public string Label { get { return StringResourceSystemFacade.GetString("Composite.Permissions", string.Format("{0}Label", this.PermissionType)); } } } } ================================================ FILE: Composite/C1Console/Security/PermissionType.cs ================================================ using System; using System.Collections.Generic; using System.Text; namespace Composite.C1Console.Security { /// /// Permission types that can be attached to actions in the C1 Console /// public enum PermissionType { /// /// User may read/view the element /// Read = 0, /// /// User may edit the element /// Edit = 1, /// /// User may add items below this element /// Add = 2, /// /// User may delete the element /// Delete = 3, /// /// User may approve the element as part of a workflow /// Approve = 4, /// /// User may publish the element as part of a workflow /// Publish = 5, /// /// User may do administrative tasks on the element /// Administrate = 6, /// ClearPermissions = 7, /// /// User may do configuration tasks on the element - super user actions. /// Configure = 8 } internal static class PermissionTypePredefined { public static readonly IEnumerable Add = new PermissionType[] { PermissionType.Add }; public static readonly IEnumerable Delete = new PermissionType[] { PermissionType.Delete }; public static readonly IEnumerable Edit = new PermissionType[] { PermissionType.Edit }; } internal static class PermissionTypeExtensionMethods { public static IEnumerable FromListOfStrings(this IEnumerable permissionTypeNames) { if (permissionTypeNames == null) throw new ArgumentNullException("permissionTypeNames"); foreach (string permissionTypeName in permissionTypeNames) { PermissionType permissionType = (PermissionType)Enum.Parse(typeof(PermissionType), permissionTypeName); yield return permissionType; } } public static string SerializePermissionTypes(this IEnumerable permissionTypes) { if (permissionTypes == null) throw new ArgumentNullException("permissionType"); StringBuilder sb = new StringBuilder(); bool first = true; foreach (PermissionType permissionType in permissionTypes) { if (first == false) sb.Append(""); else first = false; sb.Append(permissionType.ToString()); } return sb.ToString(); } public static IEnumerable DesrializePermissionTypes(this string serializedPermissionTypes) { if (serializedPermissionTypes == null) throw new ArgumentNullException("serializedPermissionTypes"); string[] split = serializedPermissionTypes.Split(new[] { '' }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in split) { yield return (PermissionType)Enum.Parse(typeof(PermissionType), s); } } } } ================================================ FILE: Composite/C1Console/Security/PermissionTypeFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Elements; using Composite.C1Console.Security.Foundation.PluginFacades; using Composite.C1Console.Security.Foundation; using Composite.Core; using Composite.Core.Configuration; using Composite.Core.Linq; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PermissionTypeFacade { private static readonly IReadOnlyCollection EmptyPermissionTypeCollection = new PermissionType[0]; /// public static IEnumerable GetLocallyDefinedUserPermissionTypes(UserToken userToken, EntityToken entityToken) { Verify.ArgumentNotNull(userToken, "userToken"); Verify.ArgumentNotNull(entityToken, "entityToken"); IEnumerable userPermissionDefinitions = GetUserPermissionDefinitions(userToken.Username); var result = new List(); foreach (UserPermissionDefinition userPermissionDefinition in userPermissionDefinitions) { if (userPermissionDefinition.EntityToken.EqualsWithVersionIgnore(entityToken)) { result.AddRange(userPermissionDefinition.PermissionTypes); } } return result.Distinct(); } /// public static IEnumerable GetLocallyDefinedUserGroupPermissionTypes(Guid userGroupId, EntityToken entityToken) { Verify.ArgumentNotNull(userGroupId, "userGroupId"); Verify.ArgumentNotNull(entityToken, "entityToken"); IEnumerable userGroupPermissionDefinitions = GetUserGroupPermissionDefinitions(userGroupId); var result = new List(); foreach (UserGroupPermissionDefinition userGroupPermissionDefinition in userGroupPermissionDefinitions) { if (userGroupPermissionDefinition.EntityToken.EqualsWithVersionIgnore(entityToken)) { result.AddRange(userGroupPermissionDefinition.PermissionTypes); } } return result.Distinct(); } /// public static IEnumerable GetLocallyDefinedUserGroupPermissionTypes(string username, EntityToken entityToken) { var userGroupIds = UserGroupFacade.GetUserGroupIds(username); IEnumerable permissionTypes = new List(); foreach (Guid userGroupId in userGroupIds) { IEnumerable localPermissionTypes = GetLocallyDefinedUserGroupPermissionTypes(userGroupId, entityToken); permissionTypes = permissionTypes.Concat(localPermissionTypes); } return permissionTypes.Distinct(); } /// /// This returns a merged result of user permissions and user group permissions /// /// /// /// /// /// public static IEnumerable GetCurrentPermissionTypes(UserToken userToken, EntityToken entityToken, IEnumerable userPermissionDefinitions, IEnumerable userGroupPermissionDefinitions) { Verify.ArgumentNotNull(userToken, "userToken"); Verify.ArgumentNotNull(entityToken, "entityToken"); IReadOnlyCollection resultPermissionTypes = PermissionTypeFacadeCaching.GetCurrentPermissionTypes(userToken, entityToken); if (resultPermissionTypes != null) { return resultPermissionTypes; } IReadOnlyCollection userPermissionTypes = PermissionTypeFacadeCaching.GetUserPermissionTypes(userToken, entityToken); if (userPermissionTypes == null) { userPermissionTypes = RecursiveUpdateCurrentUserPermissionTypes(userToken, entityToken, userPermissionDefinitions, new HashSet()); PermissionTypeFacadeCaching.SetUserPermissionTypes(userToken, entityToken, userPermissionTypes); } IReadOnlyCollection userGroupPermissionTypes = PermissionTypeFacadeCaching.GetUserGroupPermissionTypes(userToken, entityToken); if (userGroupPermissionTypes == null) { userGroupPermissionTypes = RecursiveUpdateCurrentUserGroupPermissionTypes(userToken, entityToken, userGroupPermissionDefinitions, new HashSet()); PermissionTypeFacadeCaching.SetUserGroupPermissionTypes(userToken, entityToken, userGroupPermissionTypes); } resultPermissionTypes = new List(userPermissionTypes.Concat(userGroupPermissionTypes).Distinct()); if (resultPermissionTypes.Contains(PermissionType.ClearPermissions)) { resultPermissionTypes = EmptyPermissionTypeCollection; } PermissionTypeFacadeCaching.SetCurrentPermissionTypes(userToken, entityToken, resultPermissionTypes); return resultPermissionTypes; } /// /// This returns a merged result of user permissions and user group permissions /// /// /// /// public static IEnumerable GetInheritedPermissionsTypes(UserToken userToken, EntityToken entityToken) { return GetInheritedPermissionsTypes(userToken, entityToken, null); } /// /// This returns a merged result of user permissions and user group permissions /// /// /// /// /// This is used for simulating that local defined user group permissions has been set /// /// public static IEnumerable GetInheritedPermissionsTypes(UserToken userToken, EntityToken entityToken, Dictionary> presetUserGroupPermissions) { if (userToken == null) throw new ArgumentNullException("userToken"); if (entityToken == null) throw new ArgumentNullException("entityToken"); var cachedValue = PermissionTypeFacadeCaching.GetInheritedPermissionsTypes(userToken, entityToken); if (cachedValue != null) { return cachedValue; } if (presetUserGroupPermissions == null || presetUserGroupPermissions.Count == 0) { ICollection localDefinedUserGroupPermissionTypes = GetLocallyDefinedUserGroupPermissionTypes(userToken.Username, entityToken).Evaluate(); if (localDefinedUserGroupPermissionTypes.Count > 0) { PermissionTypeFacadeCaching.SetInheritedPermissionsTypes(userToken, entityToken, localDefinedUserGroupPermissionTypes.ToList()); return localDefinedUserGroupPermissionTypes; } } else { var userGroupIds = UserGroupFacade.GetUserGroupIds(userToken.Username); var localDefinedUserGroupPermissionTypes = new List(); foreach (Guid userGroupId in userGroupIds) { IEnumerable groupPermissionTypes; if (presetUserGroupPermissions.TryGetValue(userGroupId, out groupPermissionTypes)) { localDefinedUserGroupPermissionTypes.AddRange(groupPermissionTypes); } } if (localDefinedUserGroupPermissionTypes.Contains(PermissionType.ClearPermissions)) { return new PermissionType[0]; } return localDefinedUserGroupPermissionTypes.Distinct(); } ICollection userPermissionDefinitions = GetUserPermissionDefinitions(userToken.Username).Evaluate(); ICollection userGroupPermissionDefinitions = GetUserGroupPermissionDefinitions(userToken.Username).Evaluate(); List parentEntityTokens = ParentsFacade.GetAllParents(entityToken); foreach (EntityToken parentEntityToken in parentEntityTokens) { RecursiveUpdateCurrentUserPermissionTypes(userToken, parentEntityToken, userPermissionDefinitions, new HashSet()); RecursiveUpdateCurrentUserGroupPermissionTypes(userToken, parentEntityToken, userGroupPermissionDefinitions, new HashSet()); } if (!PermissionTypeFacadeCaching.CachingWorking) { throw new InvalidOperationException("RequestLifetimeCache is not operational"); } var permissionTypes = Enumerable.Empty(); foreach (EntityToken parentEntityToken in parentEntityTokens) { IEnumerable parentUserPermissionTypes = PermissionTypeFacadeCaching.GetUserPermissionTypes(userToken, parentEntityToken); if (parentUserPermissionTypes != null) { permissionTypes = permissionTypes.Concat(parentUserPermissionTypes); } IEnumerable parentUserGroupPermissionTypes = PermissionTypeFacadeCaching.GetUserGroupPermissionTypes(userToken, parentEntityToken); if (parentUserGroupPermissionTypes != null) { permissionTypes = permissionTypes.Concat(parentUserGroupPermissionTypes); } } var distinctPermissionTypes = permissionTypes.Distinct().ToList(); PermissionTypeFacadeCaching.SetInheritedPermissionsTypes(userToken, entityToken, distinctPermissionTypes); return distinctPermissionTypes; } /// /// This uses a merged result of user permissions and user group permissions /// /// /// /// /// /// public static bool IsSubBrachContainingPermissionTypes(UserToken userToken, EntityToken entityToken, IEnumerable userPermissionDefinitions, IEnumerable userGroupPermissionDefinitions) { Verify.ArgumentNotNull(userToken, "userToken"); Verify.ArgumentNotNull(entityToken, "entityToken"); IEnumerable permissionTypes = GetCurrentPermissionTypes(userToken, entityToken, userPermissionDefinitions, userGroupPermissionDefinitions); if (permissionTypes.Any()) { return true; } // User permissions foreach (UserPermissionDefinition userPermissionDefinition in userPermissionDefinitions) { if (!userPermissionDefinition.PermissionTypes.Contains(PermissionType.ClearPermissions)) { var graph = new RelationshipGraph(userPermissionDefinition.EntityToken, RelationshipGraphSearchOption.Both, true); if (graph.Levels.Any(level => level.AllEntities.Contains(entityToken))) { return true; } } } // User group permissions foreach (UserGroupPermissionDefinition userGroupPermissionDefinition in userGroupPermissionDefinitions) { if (!userGroupPermissionDefinition.PermissionTypes.Contains(PermissionType.ClearPermissions)) { var graph = new RelationshipGraph(userGroupPermissionDefinition.EntityToken, RelationshipGraphSearchOption.Both, true); if (graph.Levels.Any(level => level.AllEntities.Contains(entityToken))) { return true; } } } return false; } /// public static IEnumerable GetInheritedGroupPermissionsTypes(Guid userGroupId, EntityToken entityToken) { var userGroupPermissionDefinitions = GetUserGroupPermissionDefinitions(userGroupId); List parentEntityTokens = ParentsFacade.GetAllParents(entityToken); var permissionTypes = new List(); foreach (EntityToken parentEntityToken in parentEntityTokens) { permissionTypes.AddRange(GetInheritedGroupPermissionsTypesRecursivly(parentEntityToken, userGroupPermissionDefinitions)); } return permissionTypes.Distinct(); } /// public static IEnumerable GetUserPermissionDefinitions(string username) { Verify.ArgumentNotNullOrEmpty(username, "username"); IEnumerable userPermissionDefinitions = UserPermissionDefinitionProviderPluginFacade.GetPermissionsByUser(username); var result = new List(); foreach (UserPermissionDefinition userPermissionDefinition in userPermissionDefinitions) { EntityToken entityToken = userPermissionDefinition.EntityToken; if (entityToken == null) { continue; } if (!entityToken.IsValid()) { if (UserPermissionDefinitionProviderPluginFacade.CanAlterDefinitions) { Log.LogWarning("PermissionTypeFacade", "System removing invalid permission setting for user '{0}' because the data entity token could not be validated. Token was '{1}'.", username, userPermissionDefinition.SerializedEntityToken); UserPermissionDefinitionProviderPluginFacade.RemoveUserPermissionDefinition(new UserToken(username), userPermissionDefinition.SerializedEntityToken); } continue; } result.Add(userPermissionDefinition); } return result; } /// public static IEnumerable GetUserGroupPermissionDefinitions(string username) { var userGroupIds = UserGroupFacade.GetUserGroupIds(username); foreach (Guid userGroupId in userGroupIds) { foreach (UserGroupPermissionDefinition userGroupPermissionDefinition in GetUserGroupPermissionDefinitions(userGroupId)) { yield return userGroupPermissionDefinition; } } } /// public static IEnumerable GetUserGroupPermissionDefinitions(Guid userGroupId) { if (userGroupId == Guid.Empty) throw new ArgumentException("Guid value is empty", "userGroupId"); IEnumerable userPermissionDefinitions = UserGroupPermissionDefinitionProviderPluginFacade.GetPermissionsByUserGroup(userGroupId); var result = new List(); foreach (UserGroupPermissionDefinition userPermissionDefinition in userPermissionDefinitions) { var entityToken = userPermissionDefinition.EntityToken; if (entityToken == null) { continue; } if (!entityToken.IsValid()) { if (UserPermissionDefinitionProviderPluginFacade.CanAlterDefinitions) { Log.LogWarning("PermissionTypeFacade", "System removing invalid permission setting for user group '{0}' because the data entity token could not be validated. Token was '{1}'.", userGroupId, userPermissionDefinition.SerializedEntityToken); UserGroupPermissionDefinitionProviderPluginFacade.RemoveUserGroupPermissionDefinition(userGroupId, userPermissionDefinition.SerializedEntityToken); } continue; } result.Add(userPermissionDefinition); } return result; } /// public static bool CanAlterDefinitions { get { return UserPermissionDefinitionProviderPluginFacade.CanAlterDefinitions; } } /// public static void SetUserPermissionDefinition(UserPermissionDefinition userPermissionDefinition) { if (userPermissionDefinition == null) throw new ArgumentNullException("userPermissionDefinition"); if (userPermissionDefinition.EntityToken is NoSecurityEntityToken) return; if (userPermissionDefinition.PermissionTypes.Contains(PermissionType.ClearPermissions) && userPermissionDefinition.PermissionTypes.Count() > 1) { throw new ArgumentException(string.Format("The permission type '{0}' may not be used with other permission types", PermissionType.ClearPermissions)); } if (!UserPermissionDefinitionProviderPluginFacade.CanAlterDefinitions) throw new InvalidOperationException("The user permission definition provider does not support altering user permission defintions"); EntityTokenCacheFacade.ClearCache(); UserPermissionDefinitionProviderPluginFacade.SetUserPermissionDefinition(userPermissionDefinition); } /// public static void RemoveUserPermissionDefinition(UserToken userToken, EntityToken entityToken) { if (userToken == null) throw new ArgumentNullException("userToken"); if (entityToken == null) throw new ArgumentNullException("entityToken"); if (entityToken is NoSecurityEntityToken) return; if (!UserPermissionDefinitionProviderPluginFacade.CanAlterDefinitions) throw new InvalidOperationException("The user permission definition provider does not support altering user permission defintions"); string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken); EntityTokenCacheFacade.ClearCache(); UserPermissionDefinitionProviderPluginFacade.RemoveUserPermissionDefinition(userToken, serializedEntityToken); } /// public static void SetUserGroupPermissionDefinition(UserGroupPermissionDefinition userGroupPermissionDefinition) { Verify.ArgumentNotNull(userGroupPermissionDefinition, "userGroupPermissionDefinition"); if (userGroupPermissionDefinition.EntityToken is NoSecurityEntityToken) return; if (userGroupPermissionDefinition.PermissionTypes.Contains(PermissionType.ClearPermissions) && (userGroupPermissionDefinition.PermissionTypes.Count() > 1)) { throw new ArgumentException(string.Format("The permission type '{0}' may not be used with other permission types", PermissionType.ClearPermissions)); } Verify.That(UserPermissionDefinitionProviderPluginFacade.CanAlterDefinitions, "The user permission definition provider does not support altering user permission defintions"); EntityTokenCacheFacade.ClearCache(); UserGroupPermissionDefinitionProviderPluginFacade.SetUserGroupPermissionDefinition(userGroupPermissionDefinition); } /// public static void RemoveUserPermissionDefinition(Guid userGroupId, EntityToken entityToken) { if (entityToken == null) throw new ArgumentNullException("entityToken"); if (entityToken is NoSecurityEntityToken) return; if (!UserPermissionDefinitionProviderPluginFacade.CanAlterDefinitions) throw new InvalidOperationException("The user permission definition provider does not support altering user permission defintions"); string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken); EntityTokenCacheFacade.ClearCache(); UserGroupPermissionDefinitionProviderPluginFacade.RemoveUserGroupPermissionDefinition(userGroupId, serializedEntityToken); } /// public static IEnumerable AllPermissionTypes { get { foreach (PermissionType permissionType in GrantingPermissionTypes) { yield return permissionType; } yield return PermissionType.ClearPermissions; } } /// public static IEnumerable GrantingPermissionTypes { get { yield return PermissionType.Read; yield return PermissionType.Add; yield return PermissionType.Edit; yield return PermissionType.Delete; yield return PermissionType.Approve; yield return PermissionType.Publish; yield return PermissionType.Configure; yield return PermissionType.Administrate; } } /// public static IEnumerable AllPermissionDescriptors => AllPermissionTypes.Select(p => new PermissionDescriptor(p)); /// public static IEnumerable GrantingPermissionDescriptors => GrantingPermissionTypes.Select(pt => new PermissionDescriptor(pt)); private static IReadOnlyCollection RecursiveUpdateCurrentUserPermissionTypes(UserToken userToken, EntityToken entityToken, IEnumerable userPermissionDefinitions, HashSet alreadyProcessedTokens) { var cached = PermissionTypeFacadeCaching.GetUserPermissionTypes(userToken, entityToken); if (cached != null) { return cached; } UserPermissionDefinition userPermissionDefinition = userPermissionDefinitions .Where(f => entityToken.EqualsWithVersionIgnore(f.EntityToken)).SingleOrDefaultOrException("More then one UserPermissionDefinition for the same entity token"); var thisPermissionTypes = new List(); if (userPermissionDefinition != null) { thisPermissionTypes.AddRange(userPermissionDefinition.PermissionTypes); } if (thisPermissionTypes.Count > 0) { thisPermissionTypes = thisPermissionTypes.Distinct().ToList(); if (thisPermissionTypes.Contains(PermissionType.ClearPermissions)) { thisPermissionTypes = new List(); } PermissionTypeFacadeCaching.SetUserPermissionTypes(userToken, entityToken, thisPermissionTypes); // Local defined permission overrules all other permissions return thisPermissionTypes; } // Call resursively on all parents var parentEntityTokens = ParentsFacade.GetAllParents(entityToken); var parentsPermissionTypes = Enumerable.Empty(); foreach (var parentEntityToken in parentEntityTokens) { var pair = new EntityTokenPair(entityToken, parentEntityToken); if (alreadyProcessedTokens.Contains(pair)) continue; alreadyProcessedTokens.Add(pair); var thisParentPermissionTypes = RecursiveUpdateCurrentUserPermissionTypes(userToken, parentEntityToken, userPermissionDefinitions, alreadyProcessedTokens); var filteredPermissions = FilterParentPermissions(userToken, parentEntityToken, thisParentPermissionTypes); parentsPermissionTypes = parentsPermissionTypes.Concat(filteredPermissions); } List permissionTypes = parentsPermissionTypes.Distinct().ToList(); PermissionTypeFacadeCaching.SetUserPermissionTypes(userToken, entityToken, permissionTypes); return permissionTypes; } private static IReadOnlyCollection RecursiveUpdateCurrentUserGroupPermissionTypes(UserToken userToken, EntityToken entityToken, IEnumerable userGroupPermissionDefinitions, HashSet alreadyProcessedTokens) { var cached = PermissionTypeFacadeCaching.GetUserGroupPermissionTypes(userToken, entityToken); if (cached != null) { return cached; } var selectedUserGroupPermissionDefinitions = userGroupPermissionDefinitions.Where(f => entityToken.EqualsWithVersionIgnore(f.EntityToken)); var thisPermissionTypes = new List(); foreach (var userGroupPermissionDefinition in selectedUserGroupPermissionDefinitions) { List groupPermissionTypes = userGroupPermissionDefinition.PermissionTypes.ToList(); thisPermissionTypes.AddRange(groupPermissionTypes); } if (thisPermissionTypes.Count > 0) { thisPermissionTypes = thisPermissionTypes.Distinct().ToList(); if (thisPermissionTypes.Contains(PermissionType.ClearPermissions)) { thisPermissionTypes = new List(); } PermissionTypeFacadeCaching.SetUserGroupPermissionTypes(userToken, entityToken, thisPermissionTypes); // Local defined permission overrules all other permissions return thisPermissionTypes; } // Call resursively on all parents List parentEntityTokens = ParentsFacade.GetAllParents(entityToken); var parentsPermissionTypes = Enumerable.Empty(); foreach (EntityToken parentEntityToken in parentEntityTokens) { var pair = new EntityTokenPair(entityToken, parentEntityToken); if (alreadyProcessedTokens.Contains(pair)) continue; alreadyProcessedTokens.Add(pair); var thisParentPermissionTypes = RecursiveUpdateCurrentUserGroupPermissionTypes(userToken, parentEntityToken, userGroupPermissionDefinitions, alreadyProcessedTokens); var filteredPermissionTypes = FilterParentPermissions(userToken, entityToken, thisParentPermissionTypes); parentsPermissionTypes = parentsPermissionTypes.Concat(filteredPermissionTypes); } List permissionTypes = parentsPermissionTypes.Distinct().ToList(); PermissionTypeFacadeCaching.SetUserGroupPermissionTypes(userToken, entityToken, permissionTypes); return permissionTypes; } private static IEnumerable FilterParentPermissions( UserToken userToken, EntityToken entityToken, IReadOnlyCollection permissions) { if (!permissions.Any() || !ElementFacade.IsPerspectiveEntityToken(entityToken)) { return permissions; } bool perspectiveVisible = UserPerspectiveFacade.PerspectiveVisible(userToken.Username, entityToken); if (perspectiveVisible) return permissions; return GlobalSettingsFacade.InheritGlobalReadPermissionOnHiddenPerspectives ? permissions.Where(p => p == PermissionType.Read) : Enumerable.Empty(); } private static IEnumerable GetInheritedGroupPermissionsTypesRecursivly(EntityToken entityToken, IEnumerable userGroupPermissionDefinitions, List visitedParents = null) { var selectedUserGroupPermissionDefinition = userGroupPermissionDefinitions.SingleOrDefault(f => entityToken.EqualsWithVersionIgnore(f.EntityToken)); if (selectedUserGroupPermissionDefinition != null) { if (selectedUserGroupPermissionDefinition.PermissionTypes.Contains(PermissionType.ClearPermissions) == false) { foreach (PermissionType permissionType in selectedUserGroupPermissionDefinition.PermissionTypes) { yield return permissionType; } } yield break; } List parentEntityTokens = ParentsFacade.GetAllParents(entityToken); if (visitedParents == null) { visitedParents = new List(); } var parentsPermissionTypes = Enumerable.Empty(); foreach (EntityToken parentEntityToken in parentEntityTokens) { if (visitedParents.Contains(parentEntityToken)) continue; visitedParents.Add(parentEntityToken); IEnumerable result = GetInheritedGroupPermissionsTypesRecursivly(parentEntityToken, userGroupPermissionDefinitions, visitedParents).ToList(); parentsPermissionTypes = parentsPermissionTypes.Concat(result); } foreach (PermissionType permissionType in parentsPermissionTypes.Distinct()) { yield return permissionType; } } private sealed class EntityTokenPair { public EntityTokenPair(EntityToken firstEntityToken, EntityToken secondEntityToken) { this.FirstEntityToken = firstEntityToken; this.SecondEntityToken = secondEntityToken; } public EntityToken FirstEntityToken { get; } public EntityToken SecondEntityToken { get; } public override int GetHashCode() { return this.FirstEntityToken.GetHashCode() ^ this.SecondEntityToken.GetHashCode(); } public bool Equals(EntityTokenPair entityTokenPair) { if (entityTokenPair == null) return false; return this.FirstEntityToken.EqualsWithVersionIgnore(entityTokenPair.FirstEntityToken) && this.SecondEntityToken.EqualsWithVersionIgnore(entityTokenPair.SecondEntityToken); } public override bool Equals(object obj) { return Equals(obj as EntityTokenPair); } } } } ================================================ FILE: Composite/C1Console/Security/PermissionsFacade.cs ================================================ using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Composite.C1Console.Elements; using Composite.Core.Linq; namespace Composite.C1Console.Security { /// /// This class can be use to get allowed permissions for current user or given UserToken and an EntityToken. /// [EditorBrowsable(EditorBrowsableState.Never)] public static class PermissionsFacade { /// /// This method will return all allowed permission for the current logged in user given the . /// /// EntityToken to get permissions for. /// Allowed permission types public static IEnumerable GetPermissionsForCurrentUser(EntityToken entityToken) { UserToken userToken = UserValidationFacade.GetUserToken(); return GetPermissions(userToken, entityToken); } /// /// This method will return all allowed permission for the given and given the . /// /// UserToken to get permissions for. /// EntityToken to get permissions for. /// Allowed permission types public static IEnumerable GetPermissions(UserToken userToken, EntityToken entityToken) { IEnumerable userPermissionDefinitions = PermissionTypeFacade.GetUserPermissionDefinitions(userToken.Username); IEnumerable userGroupPermissionDefinitions = PermissionTypeFacade.GetUserGroupPermissionDefinitions(userToken.Username); IEnumerable permissions = PermissionTypeFacade.GetCurrentPermissionTypes(userToken, entityToken, userPermissionDefinitions, userGroupPermissionDefinitions).Evaluate(); return permissions; } /// /// This method returns true if the given username has admin rights on the root element. /// This is normal way of creating a administrator in C1. /// /// Username to test /// True if the given username has admin rights on the root element. public static bool IsAdministrator(string username) { UserToken userToken = new UserToken(username); EntityToken rootEntityToken = ElementFacade.GetRootsWithNoSecurity().First().ElementHandle.EntityToken; IEnumerable permissions = GetPermissions(userToken, rootEntityToken); return permissions.Contains(PermissionType.Administrate); } } } ================================================ FILE: Composite/C1Console/Security/Plugins/HookRegistrator/HookRegistratorData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Security.Plugins.HookRegistrator { [ConfigurationElementType(typeof(NonConfigurableHookRegistrator))] internal class HookRegistratorData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/C1Console/Security/Plugins/HookRegistrator/IHookRegistrator.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Security.Plugins.HookRegistrator.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.HookRegistrator { [CustomFactory(typeof(HookRegistratorCustomFactory))] [ConfigurationNameMapper(typeof(HookRegistratorDefaultNameRetriever))] internal interface IHookRegistrator { IEnumerable GetHooks(); } } ================================================ FILE: Composite/C1Console/Security/Plugins/HookRegistrator/NonConfigurableHookRegistrator.cs ================================================ using System; using Microsoft.Practices.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.HookRegistrator { [Assembler(typeof(NonConfigurableHookRegistratorAssembler))] internal sealed class NonConfigurableHookRegistrator : HookRegistratorData { } internal sealed class NonConfigurableHookRegistratorAssembler : IAssembler { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IHookRegistrator Assemble(IBuilderContext context, HookRegistratorData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IHookRegistrator)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/C1Console/Security/Plugins/HookRegistrator/Runtime/HookRegistratorCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.HookRegistrator.Runtime { internal sealed class HookRegistratorCustomFactory : AssemblerBasedCustomFactory { protected override HookRegistratorData GetConfiguration(string name, IConfigurationSource configurationSource) { HookRegistratorSettings settings = configurationSource.GetSection(HookRegistratorSettings.SectionName) as HookRegistratorSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", HookRegistratorSettings.SectionName)); } return settings.HookRegistratorPlugins.Get(name); } } } ================================================ FILE: Composite/C1Console/Security/Plugins/HookRegistrator/Runtime/HookRegistratorDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.HookRegistrator.Runtime { internal sealed class HookRegistratorDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/C1Console/Security/Plugins/HookRegistrator/Runtime/HookRegistratorFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.HookRegistrator.Runtime { internal sealed class HookRegistratorFactory : NameTypeFactoryBase { public HookRegistratorFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/C1Console/Security/Plugins/HookRegistrator/Runtime/HookRegistratorSettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Security.Plugins.HookRegistrator.Runtime { internal sealed class HookRegistratorSettings : SerializableConfigurationSection { public const string SectionName = "Composite.C1Console.Security.Plugins.HookRegistratorConfiguration"; private const string _hookRegistratorPluginsProperty = "HookRegistratorPlugins"; [ConfigurationProperty(_hookRegistratorPluginsProperty)] public NameTypeManagerTypeConfigurationElementCollection HookRegistratorPlugins { get { return (NameTypeManagerTypeConfigurationElementCollection)base[_hookRegistratorPluginsProperty]; } } } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginProvider/IFormLoginProvider.cs ================================================ namespace Composite.C1Console.Security.Plugins.LoginProvider { /// /// Interface for form login providers - providers able to validate logins (username/password) and manage basic login information. /// The provider is as a minimum expected to provide Validate( username, password ), UsersExists { get; } and AllUsernames { get; }. /// If the provider support adding new users and changing a users password, this is declared via CanAddNewUser and CanSetUserPassword. /// public interface IFormLoginProvider : ILoginProvider { /// /// Validate a login (username and password combination) /// /// User name to validate /// Password to validate /// Emun describing the result of the validation LoginResult Validate(string username, string password); /// /// Updates a user password /// /// Name of user to update password for /// Desired password void SetUserPassword(string username, string password); /// /// Create a new login /// /// Name of user to update password for /// Desired password /// Name of group (simple container) for user /// User email address void AddNewUser(string username, string password, string group, string email); } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginProvider/ILoginProvider.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Security.Plugins.LoginProvider.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.LoginProvider { /// /// Base interface for login providers. /// [CustomFactory(typeof(LoginProviderCustomFactory))] [ConfigurationNameMapper(typeof(LoginProviderDefaultNameRetriever))] public interface ILoginProvider { /// /// Enumerates all known user names /// IEnumerable AllUsernames { get; } /// /// When true the provider is capable of changing a users password /// bool CanSetUserPassword { get; } /// /// When true the provider is capable of creating new users /// bool CanAddNewUser { get; } /// /// When true users exists in the system, i.e. AllUsernames.Any() /// bool UsersExists { get; } } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginProvider/IWindowsLoginProvider.cs ================================================ namespace Composite.C1Console.Security.Plugins.LoginProvider { internal interface IWindowsLoginProvider : ILoginProvider { bool Validate(string username, string domainName); } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginProvider/LoginProviderData.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Security.Plugins.LoginProvider { /// /// Base class for login provider configuration. Inherit from this class to declare the configuration a custom provider. /// public class LoginProviderData : NameTypeConfigurationElement { /// public LoginProviderData() : base("Unnamed", typeof(ILoginProvider)) { } /// public LoginProviderData(string name, Type type) : base(name, type) { } } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginProvider/NonConfigurableLoginProvider.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.LoginProvider { /// /// Default login provider configuration, you can use this if you require no custom configuration fields. /// [Assembler(typeof(NonConfigurableLoginProviderAssembler))] public class NonConfigurableLoginProvider : LoginProviderData { } /// /// Assembles login providers based on type only, i.e. without anhy custom configuration. /// If your provider require custom configuration you should also make your own assembler and configuration classes. /// public sealed class NonConfigurableLoginProviderAssembler : IAssembler { /// public ILoginProvider Assemble(Microsoft.Practices.ObjectBuilder.IBuilderContext context, LoginProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { if (null == objectConfiguration) throw new ArgumentNullException("objectConfiguration"); return (ILoginProvider)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginProvider/Runtime/LoginProviderCustomFactory.cs ================================================ using System.Configuration; using Composite.C1Console.Security.Plugins.LoginProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.LoginProvider.Runtime { internal class LoginProviderCustomFactory : AssemblerBasedCustomFactory { protected override LoginProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { LoginProviderSettings settings = (LoginProviderSettings)configurationSource.GetSection(LoginProviderSettings.SectionName); if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", LoginProviderSettings.SectionName)); } return settings.LoginProviderPlugins.Get(name); } } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginProvider/Runtime/LoginProviderDefaultNameRetriever.cs ================================================ using System; using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.LoginProvider.Runtime { internal class LoginProviderDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { if (null == configSource) throw new ArgumentNullException("configSource"); if (null != name) { return name; } var settings = configSource.GetSection(LoginProviderSettings.SectionName) as LoginProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("Could not load configuration section {0}", LoginProviderSettings.SectionName)); } return settings.DefaultLoginProviderPlugin; } } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginProvider/Runtime/LoginProviderFactory.cs ================================================ using Composite.Core.Configuration; using Composite.C1Console.Security.Plugins.LoginProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.LoginProvider.Runtime { internal class LoginProviderFactory : NameTypeFactoryBase { public LoginProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginProvider/Runtime/LoginProviderSettings.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Security.Plugins.LoginProvider.Runtime { internal class LoginProviderSettings : SerializableConfigurationSection { public const string SectionName = "Composite.C1Console.Security.Plugins.LoginProviderConfiguration"; private const string _loginProvidersProperty = "LoginProviderPlugins"; [ConfigurationProperty(_loginProvidersProperty, IsRequired = true)] public NameTypeConfigurationElementCollection LoginProviderPlugins { get { return (NameTypeConfigurationElementCollection)base[_loginProvidersProperty]; } } private const string _defaultLoginProviderPluginProperty = "defaultLoginProviderPlugin"; [ConfigurationProperty(_defaultLoginProviderPluginProperty, IsRequired = true)] public string DefaultLoginProviderPlugin { get { return (string)base[_defaultLoginProviderPluginProperty]; } set { base[_defaultLoginProviderPluginProperty] = value; } } private const string _maxLoginAttempts = "maxLoginAttempts"; [ConfigurationProperty(_maxLoginAttempts, IsRequired = false, DefaultValue = int.MaxValue)] public int MaxLoginAttempts { get { return (int)base[_maxLoginAttempts]; } set { base[_maxLoginAttempts] = value; } } } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginSessionStore/ILoginSessionStore.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Composite.C1Console.Security.Plugins.LoginSessionStore.Runtime; using System.Net; namespace Composite.C1Console.Security.Plugins.LoginSessionStore { /// [CustomFactory(typeof(LoginSessionStoreCustomFactory))] [ConfigurationNameMapper(typeof(LoginSessionStoreDefaultNameRetriever))] public interface ILoginSessionStore { /// bool CanPersistAcrossSessions { get; } /// void StoreUsername(string username, bool persistAcrossSessions); /// string StoredUsername { get; } /// void FlushUsername(); /// IPAddress UserIpAddress { get; } } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginSessionStore/ILoginSessionStoreRedirectedLogout.cs ================================================ namespace Composite.C1Console.Security.Plugins.LoginSessionStore { /// /// Allows specifying a logout URL. /// public interface ILoginSessionStoreRedirectedLogout { /// string LogoutUrl { get; } } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginSessionStore/INoneConfigurationBasedLoginSessionStore.cs ================================================ namespace Composite.C1Console.Security.Plugins.LoginSessionStore { internal interface INoneConfigurationBasedLoginSessionStore : ILoginSessionStore { } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginSessionStore/LoginSessionStoreData.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Security.Plugins.LoginSessionStore { /// public class LoginSessionStoreData : NameTypeConfigurationElement { /// public LoginSessionStoreData() : base("Unnamed", typeof(ILoginSessionStore)) { } /// public LoginSessionStoreData(string name, Type type) : base(name, type) { } } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginSessionStore/NonConfigurableLoginSessionStore.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.LoginSessionStore { /// [Assembler(typeof(NonConfigurableSessionDataProviderAssembler))] public sealed class NonConfigurableLoginSessionStore : LoginSessionStoreData { } /// public sealed class NonConfigurableSessionDataProviderAssembler : IAssembler { /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public ILoginSessionStore Assemble(Microsoft.Practices.ObjectBuilder.IBuilderContext context, LoginSessionStoreData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (ILoginSessionStore)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginSessionStore/Runtime/LoginSessionStoreCustomFactory.cs ================================================ using System.Configuration; using Composite.C1Console.Security.Plugins.LoginSessionStore; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.LoginSessionStore.Runtime { internal class LoginSessionStoreCustomFactory : AssemblerBasedCustomFactory { protected override LoginSessionStoreData GetConfiguration(string name, IConfigurationSource configurationSource) { LoginSessionStoreSettings settings = (LoginSessionStoreSettings)configurationSource.GetSection(LoginSessionStoreSettings.SectionName); if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", LoginSessionStoreSettings.SectionName)); } return settings.LoginSessionStores.Get(name); } } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginSessionStore/Runtime/LoginSessionStoreDefaultNameRetriever.cs ================================================ using System; using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.LoginSessionStore.Runtime { internal class LoginSessionStoreDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { if (null == configSource) throw new ArgumentNullException("configSource"); if (null != name) { return name; } else { LoginSessionStoreSettings settings = configSource.GetSection(LoginSessionStoreSettings.SectionName) as LoginSessionStoreSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("Could not load configuration section {0}", LoginSessionStoreSettings.SectionName)); } return settings.DefaultLoginSessionStore; } } } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginSessionStore/Runtime/LoginSessionStoreFactory.cs ================================================ using System.Linq; using Composite.Core; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.LoginSessionStore.Runtime { internal class LoginSessionStoreFactory : NameTypeFactoryBase { public LoginSessionStoreFactory() : base(ConfigurationServices.ConfigurationSource) { } public new ILoginSessionStore CreateDefault() { if (ServiceLocator.HasService(typeof(INoneConfigurationBasedLoginSessionStore))) { var loginSessionstores = ServiceLocator.GetServices().Union(new[] { base.CreateDefault() }); return new LoginSessionStoreResolver(loginSessionstores); } return new LoginSessionStoreResolver(new[] { base.CreateDefault() }); } } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginSessionStore/Runtime/LoginSessionStoreResolver.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Net; using Composite.Core.Extensions; namespace Composite.C1Console.Security.Plugins.LoginSessionStore.Runtime { internal class LoginSessionStoreResolver : ILoginSessionStore, ILoginSessionStoreRedirectedLogout { private readonly IEnumerable _loginSessionStores; public LoginSessionStoreResolver(IEnumerable loginSessionStores) { _loginSessionStores = loginSessionStores; } private ILoginSessionStore PreferredLoginSessionStore() { return _loginSessionStores.FirstOrDefault(f => f.StoredUsername != null); } public bool CanPersistAcrossSessions => Convert.ToBoolean( PreferredLoginSessionStore()?.CanPersistAcrossSessions); public void StoreUsername(string username, bool persistAcrossSessions) { _loginSessionStores.ForEach(f => f.StoreUsername(username, persistAcrossSessions)); } public string StoredUsername => PreferredLoginSessionStore()?.StoredUsername; public void FlushUsername() { _loginSessionStores.ForEach(f => f.FlushUsername()); } public IPAddress UserIpAddress => PreferredLoginSessionStore()?.UserIpAddress; public string LogoutUrl => _loginSessionStores .OfType() .Select(_ => _.LogoutUrl) .FirstOrDefault(url => !string.IsNullOrEmpty(url)); } } ================================================ FILE: Composite/C1Console/Security/Plugins/LoginSessionStore/Runtime/LoginSessionStoreSettings.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Composite.C1Console.Security.Plugins.LoginSessionStore; namespace Composite.C1Console.Security.Plugins.LoginSessionStore.Runtime { internal class LoginSessionStoreSettings : SerializableConfigurationSection { public const string SectionName = "Composite.C1Console.Security.Plugins.LoginSessionStoreConfiguration"; private const string _sessionDataProvidersProperty = "LoginSessionStore"; [ConfigurationProperty(_sessionDataProvidersProperty, IsRequired = true)] public NameTypeConfigurationElementCollection LoginSessionStores { get { return (NameTypeConfigurationElementCollection)base[_sessionDataProvidersProperty]; } } private const string _defaultProviderProperty = "defaultProvider"; [ConfigurationProperty(_defaultProviderProperty, IsRequired = true)] public string DefaultLoginSessionStore { get{ return (string)base[_defaultProviderProperty];} set { base[_defaultProviderProperty] = value; } } } } ================================================ FILE: Composite/C1Console/Security/Plugins/PasswordPolicy/IPasswordRule.cs ================================================ using Composite.C1Console.Security.Plugins.PasswordPolicy.Runtime; using Composite.Data.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.PasswordPolicy { /// /// Represents a password validaiton rule. /// [CustomFactory(typeof(PasswordRuleCustomFactory))] public interface IPasswordRule { /// /// Checks if the password satisfies the rule. /// /// The user. /// A password string. /// true is password matches the rule, otherwise - false bool ValidatePassword(IUser user, string password); /// /// Returns rule description to be shown in UI if password didn't pass the validation. /// /// string GetRuleDescription(); } } ================================================ FILE: Composite/C1Console/Security/Plugins/PasswordPolicy/NonConfigurablePasswordRule.cs ================================================ using System; using Microsoft.Practices.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.PasswordPolicy { /// [Assembler(typeof(NonConfigurablePasswordRuleAssembler))] public sealed class NonConfigurablePasswordRule : PasswordRuleData { } internal sealed class NonConfigurablePasswordRuleAssembler : IAssembler { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IPasswordRule Assemble(IBuilderContext context, PasswordRuleData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IPasswordRule)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/C1Console/Security/Plugins/PasswordPolicy/PasswordRuleData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Security.Plugins.PasswordPolicy { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ConfigurationElementType(typeof(NonConfigurablePasswordRule))] public class PasswordRuleData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/C1Console/Security/Plugins/PasswordPolicy/Runtime/PasswordPolicySettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Security.Plugins.PasswordPolicy.Runtime { internal class PasswordPolicySettings : SerializableConfigurationSection { public const string SectionName = "Composite.C1Console.Security.Plugins.PasswordPolicy"; /// /// Password expiraton time in days. After password expires, the user will be asked to /// private const string _attr_passwordExpirationTimeInDays = "passwordExpirationTimeInDays"; [ConfigurationProperty(_attr_passwordExpirationTimeInDays, IsRequired = false, DefaultValue = 0)] public int PasswordExpirationTimeInDays { get { return (int)base[_attr_passwordExpirationTimeInDays]; } set { base[_attr_passwordExpirationTimeInDays] = value; } } /// /// Number of old passwords to be preserved for every user. /// private const string _attr_passwordHistoryLength = "passwordHistoryLength"; [ConfigurationProperty(_attr_passwordHistoryLength, IsRequired = false, DefaultValue = 0)] public int PasswordHistoryLength { get { return (int)base[_attr_passwordHistoryLength]; } set { base[_attr_passwordHistoryLength] = value; } } private const string _elem_PasswordRules = "PasswordRules"; [ConfigurationProperty(_elem_PasswordRules)] public NameTypeManagerTypeConfigurationElementCollection PasswordRules { get { return (NameTypeManagerTypeConfigurationElementCollection) base[_elem_PasswordRules]; } } } } ================================================ FILE: Composite/C1Console/Security/Plugins/PasswordPolicy/Runtime/PasswordRuleCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.PasswordPolicy.Runtime { internal class PasswordRuleCustomFactory : AssemblerBasedCustomFactory { protected override PasswordRuleData GetConfiguration(string name, IConfigurationSource configurationSource) { const string sectionName = PasswordPolicySettings.SectionName; var settings = (PasswordPolicySettings)configurationSource.GetSection(sectionName); if (settings == null) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", sectionName)); } return settings.PasswordRules.Get(name); } } } ================================================ FILE: Composite/C1Console/Security/Plugins/PasswordPolicy/Runtime/PasswordRuleFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.PasswordPolicy.Runtime { internal sealed class PasswordRuleFactory : NameTypeFactoryBase { public PasswordRuleFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/C1Console/Security/Plugins/UserGroupPermissionDefinitionProvider/IUserGroupPermissionDefinitionProvider.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Composite.C1Console.Security.Plugins.UserGroupPermissionDefinitionProvider.Runtime; namespace Composite.C1Console.Security.Plugins.UserGroupPermissionDefinitionProvider { [CustomFactory(typeof(UserGroupPermissionDefinitionProviderCustomFactory))] [ConfigurationNameMapper(typeof(UserGroupPermissionDefinitionProviderDefaultNameRetriever))] internal interface IUserGroupPermissionDefinitionProvider { IEnumerable AllUserGroupPermissionDefinitions { get; } bool CanAlterDefinitions { get; } IEnumerable GetPermissionsByUserGroup(Guid userGroupId); void SetUserGroupPermissionDefinition(UserGroupPermissionDefinition userGroupPermissionDefinition); void RemoveUserGroupPermissionDefinition(Guid userGroupId, string serializedEntityToken); } } ================================================ FILE: Composite/C1Console/Security/Plugins/UserGroupPermissionDefinitionProvider/NonConfigurableUserGroupPermissionDefinitionProvider.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.UserGroupPermissionDefinitionProvider { [Assembler(typeof(NonConfigurableUserGroupPermissionDefinitionProviderAssembler))] internal sealed class NonConfigurableUserGroupPermissionDefinitionProvider : UserGroupPermissionDefinitionProviderData { } internal sealed class NonConfigurableUserGroupPermissionDefinitionProviderAssembler : IAssembler { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IUserGroupPermissionDefinitionProvider Assemble(Microsoft.Practices.ObjectBuilder.IBuilderContext context, UserGroupPermissionDefinitionProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IUserGroupPermissionDefinitionProvider)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/C1Console/Security/Plugins/UserGroupPermissionDefinitionProvider/Runtime/UserGroupPermissionDefinitionProviderCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.UserGroupPermissionDefinitionProvider.Runtime { internal class UserGroupPermissionDefinitionProviderCustomFactory : AssemblerBasedCustomFactory { protected override UserGroupPermissionDefinitionProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { UserGroupPermissionDefinitionProviderSettings settings = (UserGroupPermissionDefinitionProviderSettings)configurationSource.GetSection(UserGroupPermissionDefinitionProviderSettings.SectionName); if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", UserGroupPermissionDefinitionProviderSettings.SectionName)); } return settings.UserGroupPermissionDefinitionProvidersPlugins.Get(name); } } } ================================================ FILE: Composite/C1Console/Security/Plugins/UserGroupPermissionDefinitionProvider/Runtime/UserGroupPermissionDefinitionProviderDefaultNameRetriever.cs ================================================ using System; using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.UserGroupPermissionDefinitionProvider.Runtime { internal class UserGroupPermissionDefinitionProviderDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { if (null == configSource) throw new ArgumentNullException("configSource"); if (null != name) { return name; } else { UserGroupPermissionDefinitionProviderSettings settings = configSource.GetSection(UserGroupPermissionDefinitionProviderSettings.SectionName) as UserGroupPermissionDefinitionProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("Could not load configuration section {0}", UserGroupPermissionDefinitionProviderSettings.SectionName)); } return settings.DefaultUserGroupPermissionDefinitionProvider; } } } } ================================================ FILE: Composite/C1Console/Security/Plugins/UserGroupPermissionDefinitionProvider/Runtime/UserGroupPermissionDefinitionProviderFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.UserGroupPermissionDefinitionProvider.Runtime { internal class UserGroupPermissionDefinitionProviderFactory : NameTypeFactoryBase { public UserGroupPermissionDefinitionProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/C1Console/Security/Plugins/UserGroupPermissionDefinitionProvider/Runtime/UserGroupPermissionDefinitionProviderSettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Security.Plugins.UserGroupPermissionDefinitionProvider.Runtime { internal class UserGroupPermissionDefinitionProviderSettings : SerializableConfigurationSection { public const string SectionName = "Composite.C1Console.Security.Plugins.UserGroupPermissionDefinitionProviderConfiguration"; private const string _userGroupPermissionDefinitionProviderPluginsPropertyName = "UserGroupPermissionDefinitionProviderPlugins"; [ConfigurationProperty(_userGroupPermissionDefinitionProviderPluginsPropertyName, IsRequired = true)] public NameTypeManagerTypeConfigurationElementCollection UserGroupPermissionDefinitionProvidersPlugins { get { return (NameTypeManagerTypeConfigurationElementCollection)base[_userGroupPermissionDefinitionProviderPluginsPropertyName]; } } private const string _defaultProviderProperty = "defaultProvider"; [ConfigurationProperty(_defaultProviderProperty, IsRequired = true)] public string DefaultUserGroupPermissionDefinitionProvider { get { return (string)base[_defaultProviderProperty]; } set { base[_defaultProviderProperty] = value; } } } } ================================================ FILE: Composite/C1Console/Security/Plugins/UserGroupPermissionDefinitionProvider/UserGroupPermissionDefinitionProviderData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Security.Plugins.UserGroupPermissionDefinitionProvider { [ConfigurationElementType(typeof(NonConfigurableUserGroupPermissionDefinitionProvider))] internal class UserGroupPermissionDefinitionProviderData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/C1Console/Security/Plugins/UserPermissionDefinitionProvider/IUserPermissionDefinitionProvider.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Security.Plugins.UserPermissionDefinitionProvider.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.UserPermissionDefinitionProvider { [CustomFactory(typeof(UserPermissionDefinitionProviderCustomFactory))] [ConfigurationNameMapper(typeof(UserPermissionDefinitionProviderDefaultNameRetriever))] internal interface IUserPermissionDefinitionProvider { IEnumerable AllUserPermissionDefinitions { get; } bool CanAlterDefinitions { get; } IEnumerable GetPermissionsByUser(string userName); void SetUserPermissionDefinition(UserPermissionDefinition userPermissionDefinition); void RemoveUserPermissionDefinition(UserToken userToken, string serializedEntityToken); } } ================================================ FILE: Composite/C1Console/Security/Plugins/UserPermissionDefinitionProvider/NonConfigurableUserPermissionDefinitionProvider.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.UserPermissionDefinitionProvider { [Assembler(typeof(NonConfigurableUserPermissionDefinitionProviderAssembler))] internal sealed class NonConfigurableUserPermissionDefinitionProvider : UserPermissionDefinitionProviderData { } internal sealed class NonConfigurableUserPermissionDefinitionProviderAssembler : IAssembler { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IUserPermissionDefinitionProvider Assemble(Microsoft.Practices.ObjectBuilder.IBuilderContext context, UserPermissionDefinitionProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IUserPermissionDefinitionProvider)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/C1Console/Security/Plugins/UserPermissionDefinitionProvider/Runtime/UserPermissionDefinitionProviderCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.UserPermissionDefinitionProvider.Runtime { internal class UserPermissionDefinitionProviderCustomFactory : AssemblerBasedCustomFactory { protected override UserPermissionDefinitionProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { UserPermissionDefinitionProviderSettings settings = (UserPermissionDefinitionProviderSettings)configurationSource.GetSection(UserPermissionDefinitionProviderSettings.SectionName); if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", UserPermissionDefinitionProviderSettings.SectionName)); } return settings.UserPermissionDefinitionProvidersPlugins.Get(name); } } } ================================================ FILE: Composite/C1Console/Security/Plugins/UserPermissionDefinitionProvider/Runtime/UserPermissionDefinitionProviderDefaultNameRetriever.cs ================================================ using System; using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.UserPermissionDefinitionProvider.Runtime { internal class UserPermissionDefinitionProviderDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { if (null == configSource) throw new ArgumentNullException("configSource"); if (null != name) { return name; } else { UserPermissionDefinitionProviderSettings settings = configSource.GetSection(UserPermissionDefinitionProviderSettings.SectionName) as UserPermissionDefinitionProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("Could not load configuration section {0}", UserPermissionDefinitionProviderSettings.SectionName)); } return settings.DefaultUserPermissionDefinitionProvider; } } } } ================================================ FILE: Composite/C1Console/Security/Plugins/UserPermissionDefinitionProvider/Runtime/UserPermissionDefinitionProviderFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Security.Plugins.UserPermissionDefinitionProvider.Runtime { internal class UserPermissionDefinitionProviderFactory : NameTypeFactoryBase { public UserPermissionDefinitionProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/C1Console/Security/Plugins/UserPermissionDefinitionProvider/Runtime/UserPermissionDefinitionProviderSettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Security.Plugins.UserPermissionDefinitionProvider.Runtime { internal class UserPermissionDefinitionProviderSettings : SerializableConfigurationSection { public const string SectionName = "Composite.C1Console.Security.Plugins.UserPermissionDefinitionProviderConfiguration"; private const string _userPermissionDefinitionProviderPluginsPropertyName = "UserPermissionDefinitionProviderPlugins"; [ConfigurationProperty(_userPermissionDefinitionProviderPluginsPropertyName, IsRequired = true)] public NameTypeManagerTypeConfigurationElementCollection UserPermissionDefinitionProvidersPlugins { get { return (NameTypeManagerTypeConfigurationElementCollection)base[_userPermissionDefinitionProviderPluginsPropertyName]; } } private const string _defaultProviderProperty = "defaultProvider"; [ConfigurationProperty(_defaultProviderProperty, IsRequired = true)] public string DefaultUserPermissionDefinitionProvider { get { return (string)base[_defaultProviderProperty]; } set { base[_defaultProviderProperty] = value; } } } } ================================================ FILE: Composite/C1Console/Security/Plugins/UserPermissionDefinitionProvider/UserPermissionDefinitionProviderData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Security.Plugins.UserPermissionDefinitionProvider { [ConfigurationElementType(typeof(NonConfigurableUserPermissionDefinitionProvider))] internal class UserPermissionDefinitionProviderData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/C1Console/Security/RefreshBeforeAfterEntityTokenFinder.cs ================================================ using System.Collections.Generic; using System.Linq; namespace Composite.C1Console.Security { internal static class RefreshBeforeAfterEntityTokenFinder { public static IEnumerable FindEntityTokens(RelationshipGraph beforeGraph, RelationshipGraph afterGraph) { Verify.ArgumentNotNull(beforeGraph, "beforeGraph"); Verify.ArgumentNotNull(afterGraph, "afterGraph"); var nodes = new List(); FindNodes(beforeGraph, afterGraph, nodes); FindNodes(afterGraph, beforeGraph, nodes); if (nodes.Count > 1) { nodes = nodes.Where(n => n.ParentNodes.Any()).ToList(); // Ignoring root node nodes = FilterNodes(nodes); } foreach (RelationshipGraphNode node in nodes) { foreach (RelationshipGraphNode parentNode in node.ParentNodes) { yield return parentNode.EntityToken; } } } private static void FindNodes(RelationshipGraph leftGraph, RelationshipGraph rightGraph, List foundNodes) { foreach (RelationshipGraphNode leftNode in leftGraph.TopNodes) { RelationshipGraphNode currentNode = null; foreach (RelationshipGraphNode rightNode in rightGraph.TopNodes) { RelationshipGraphNode foundNode = FindNode(leftNode, rightNode, null); if (foundNode != null) { if (currentNode == null || currentNode.Level > foundNode.Level) { currentNode = foundNode; } } } if (currentNode != null) { if (foundNodes.Find(node => node.EntityToken.Equals(currentNode.EntityToken)) == null) { foundNodes.Add(currentNode); } } } } private static RelationshipGraphNode FindNode(RelationshipGraphNode leftNode, RelationshipGraphNode rightNode, RelationshipGraphNode lastLeftNode) { // Searched for the first node in "leftNode" chain which isn't present in "rightNode" chain // leftNode -> A -> B -> C -> D -> .... // rightNode -> A -> B -> C -> E -> .... // Result: D; // leftNode -> A -> B -> C -> D // rightNode -> A -> B -> C -> D -> .... // Result: D; // leftNode -> A -> B -> C -> D -> .... // rightNode -> A -> B -> C -> D // Result: D; // leftNode -> A -> B -> C -> D // rightNode -> A -> B -> C -> D // Result: D; if (!leftNode.EntityToken.Equals(rightNode.EntityToken)) { return lastLeftNode; } if (leftNode.ChildNode != null && rightNode.ChildNode != null) { return FindNode(leftNode.ChildNode, rightNode.ChildNode, leftNode); } return leftNode; } private static List FilterNodes(ICollection nodesToFilter) { var resultNodes = new List(); foreach (RelationshipGraphNode nodeToFilter in nodesToFilter) { bool anyParentsInTheList = nodesToFilter.Any(node => !node.EntityToken.Equals(nodeToFilter.EntityToken) && IsParent(nodeToFilter, node)); if (!anyParentsInTheList) { resultNodes.Add(nodeToFilter); } } return resultNodes; } private static bool IsParent(RelationshipGraphNode possibleChildNode, RelationshipGraphNode possibleParentNode) { foreach (RelationshipGraphNode parentNode in possibleChildNode.ParentNodes) { if (parentNode.EntityToken.Equals(possibleParentNode.EntityToken) || IsParent(parentNode, possibleParentNode)) { return true; } } return false; } } } ================================================ FILE: Composite/C1Console/Security/RefreshDeleteEntityTokenFinder.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security.Foundation; namespace Composite.C1Console.Security { internal static class RefreshDeleteEntityTokenFinder { public static IEnumerable FindEntityTokens(RelationshipGraph beforeGraph) { return FindEntityTokens(beforeGraph, false); } public static IEnumerable FindEntityTokens(RelationshipGraph beforeGraph, bool skipBottemNodes) { if (beforeGraph == null) throw new ArgumentNullException("beforeGraph"); List foundEntityTokens = new List(); foreach (RelationshipGraphNode node in beforeGraph.BottomNodes) { if (skipBottemNodes) { foreach (RelationshipGraphNode parentNode in node.ParentNodes) { FindExistingParents(parentNode, foundEntityTokens); } } else { FindExistingParents(node, foundEntityTokens); } } return foundEntityTokens; } private static void FindExistingParents(RelationshipGraphNode node, List foundEntityTokens) { if ((SecurityAncestorFacade.GetParents(node.EntityToken) != null) || (HookingFacade.GetHookies(node.EntityToken) != null)) { if (foundEntityTokens.Find(et => et.GetHashCode() == node.EntityToken.GetHashCode()) == null) { foundEntityTokens.Add(node.EntityToken); } } else { foreach (RelationshipGraphNode parentNode in node.ParentNodes) { FindExistingParents(parentNode, foundEntityTokens); } } } } } ================================================ FILE: Composite/C1Console/Security/RelationshipGraph.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using Composite.Core.Extensions; using Composite.C1Console.Security.Foundation; using Composite.C1Console.Users; using Composite.Core.Linq; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class RelationshipOrientedGraphNodeExtensions { /// public static IEnumerable> GetAllPaths(this RelationshipOrientedGraphNode node) { List> allPaths = new List>(); List path = new List { node.EntityToken }; allPaths.Add(path); GetAllPathsImpl(node, path, allPaths, new List()); return allPaths; } private static void GetAllPathsImpl(RelationshipOrientedGraphNode node, List currentPath, List> allPaths, List processedNodes) { processedNodes.Add(node); int count = node.Parents.Count(); if (count == 0) { return; } if (count == 1) { RelationshipOrientedGraphNode parentNode = node.Parents.Single(); if (!processedNodes.Contains(parentNode)) { currentPath.Add(parentNode.EntityToken); GetAllPathsImpl(parentNode, currentPath, allPaths, processedNodes); } return; } allPaths.Remove(currentPath); foreach (RelationshipOrientedGraphNode parentNode in node.Parents) { if (!processedNodes.Contains(parentNode)) { var newCurrentPath = new List(currentPath); allPaths.Add(newCurrentPath); newCurrentPath.Add(parentNode.EntityToken); GetAllPathsImpl(parentNode, newCurrentPath, allPaths, new List(processedNodes)); } } } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DebuggerDisplay("EntityToken = {EntityToken}")] public sealed class RelationshipOrientedGraphNode { private List _parentNodes; private Action _expandAction; /// public RelationshipOrientedGraphNode(EntityToken entityToken, Action expandAction) { this.EntityToken = entityToken; _expandAction = expandAction; } /// public EntityToken EntityToken { get; private set; } /// public IEnumerable Parents { get { Expand(); foreach (RelationshipOrientedGraphNode parentNode in _parentNodes) { yield return parentNode; } } } internal void Expand() { if (_parentNodes != null) return; _parentNodes = new List(); _expandAction(this); } internal void AddParant(RelationshipOrientedGraphNode parentNode) { if (_parentNodes.Contains(parentNode) == false) { _parentNodes.Add(parentNode); } } /// public override int GetHashCode() { return this.EntityToken.GetHashCode(); } /// public override bool Equals(object obj) { return Equals(obj as RelationshipOrientedGraphNode); } /// public bool Equals(RelationshipOrientedGraphNode node) { if (node == null) return false; return node.EntityToken.Equals(this.EntityToken); } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class RelationshipOrientedGraph { private List _nodes = new List(); /// public RelationshipOrientedGraph(EntityToken sourceEntityToken) { RelationshipOrientedGraphNode node = CreateNewNode(sourceEntityToken); _nodes.Add(node); } /// public RelationshipOrientedGraphNode Root { get { return _nodes[0]; } } private void Expand(RelationshipOrientedGraphNode node) { IEnumerable nativeParentEntityTokens = SecurityAncestorFacade.GetParents(node.EntityToken); if (nativeParentEntityTokens != null) { nativeParentEntityTokens.ForEach(f => AddEntityToken(node, f)); } IEnumerable auxiliaryParentEntityTokens = AuxiliarySecurityAncestorFacade.GetParents(node.EntityToken); if (auxiliaryParentEntityTokens != null) { auxiliaryParentEntityTokens.ForEach(f => AddEntityToken(node, f)); } IEnumerable hookingParentEntityTokens = HookingFacade.GetHookies(node.EntityToken); if (hookingParentEntityTokens != null) { hookingParentEntityTokens.ForEach(f => AddEntityToken(node, f)); } } private void AddEntityToken(RelationshipOrientedGraphNode node, EntityToken parentEntityToken) { RelationshipOrientedGraphNode existingParentNode = (from n in _nodes where n.EntityToken.Equals(parentEntityToken) select n).SingleOrDefault(); if (existingParentNode != null) { node.AddParant(existingParentNode); } else { RelationshipOrientedGraphNode parentNode = CreateNewNode(parentEntityToken); _nodes.Add(parentNode); node.AddParant(parentNode); } } private RelationshipOrientedGraphNode CreateNewNode(EntityToken entityToken) { return new RelationshipOrientedGraphNode(entityToken, Expand); } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum RelationshipGraphSearchOption { /// /// Parent items get from /// Native = 0, /// /// Parent items get from and /// Hooked = 1, /// Both = 2 } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class RelationshipGraph { private readonly RelationshipGraphSearchOption _searchOption; private readonly Dictionary> _levels = new Dictionary>(); private readonly HashSet _visitedEntityTokens = new HashSet(); private readonly bool _excludeReoccuringNodes; private bool _moreLevelsToExpend; /// public RelationshipGraph(EntityToken sourceEntityToken, RelationshipGraphSearchOption searchOption) : this(sourceEntityToken, searchOption, false, true) { } /// public RelationshipGraph(EntityToken sourceEntityToken, RelationshipGraphSearchOption searchOption, bool lazyEvaluation) : this(sourceEntityToken, searchOption, lazyEvaluation, true) { } /// public RelationshipGraph(EntityToken sourceEntityToken, RelationshipGraphSearchOption searchOption, bool lazyEvaluation, bool excludeReoccuringNodes) { _excludeReoccuringNodes = excludeReoccuringNodes; Verify.ArgumentNotNull(sourceEntityToken, "sourceEntityToken"); _searchOption = searchOption; RelationshipGraphNode node = new RelationshipGraphNode(sourceEntityToken, 0, RelationshipGraphNodeType.Entity); _levels.Add(0, new List { node }); string userName = UserValidationFacade.IsLoggedIn() ? UserSettings.Username : null; ExpandNextLevel(userName); if (lazyEvaluation == false) { while (_moreLevelsToExpend) { ExpandNextLevel(userName); } } } /// public IEnumerable Levels { get { return new RelationshipGraphLevelEnumerable(this); } } /// public IEnumerable TopNodes { get { Verify.That(!_excludeReoccuringNodes, "It is necessary to set 'excludeReoccuringNodes' to 'false' to enable TopNodes calculation."); foreach (List nodes in _levels.Values) { foreach (RelationshipGraphNode node in nodes) { if (node.ParentNodes.Count == 0) { yield return node; } } } } } /// public IEnumerable BottomNodes { get { foreach (List nodes in _levels.Values) { foreach (RelationshipGraphNode node in nodes) { if (node.ChildNode == null) { yield return node; } } } } } /// public override string ToString() { var sb = new StringBuilder(); foreach (RelationshipGraphLevel level in this.Levels) { sb.AppendLine("Level: " + level.Level); foreach (EntityToken entityToken in level.Entities) { sb.AppendLine($"Native: Type = {entityToken.Type} Source = {entityToken.Source} Id = {entityToken.Id}"); } foreach (EntityToken entityToken in level.HookedEntities) { sb.AppendLine($"Hooked: Type = {entityToken.Type} Source = {entityToken.Source} Id = {entityToken.Id}"); } sb.AppendLine("---------"); } return sb.ToString(); } internal int LevelCount => _levels.Count; internal RelationshipGraphLevel GetLevel(int level) { string userName = UserValidationFacade.IsLoggedIn() ? UserSettings.Username : null; while (_levels.Count - 1 < level && _moreLevelsToExpend) { ExpandNextLevel(userName); } if (_levels.Count - 1 < level) { return null; } return new RelationshipGraphLevel(level, _levels[level]); } private void ExpandNextLevel(string userName) { int levelNumber = _levels.Count - 1; if (levelNumber > 1000) { throw new InvalidOperationException( $"The entity token '{_levels[0][0].EntityToken}' has more than 1000 levels of parents, this might be an infinite loop"); } _moreLevelsToExpend = false; List nodes = _levels[levelNumber]; if (nodes.Count > 1000) { throw new InvalidOperationException($"The entity token '{_levels[0][0].EntityToken}' has more than 1000 nodes at the level {levelNumber}, this might be an infinite loop"); } foreach (RelationshipGraphNode node in nodes) { if (_searchOption == RelationshipGraphSearchOption.Native || _searchOption == RelationshipGraphSearchOption.Both) { IEnumerable parentEntityTokens; if (!EntityTokenCacheFacade.GetCachedNativeParents(node.EntityToken, out parentEntityTokens, userName)) { parentEntityTokens = SecurityAncestorFacade.GetParents(node.EntityToken)?.Evaluate(); EntityTokenCacheFacade.AddNativeCache(node.EntityToken, parentEntityTokens); } if (parentEntityTokens != null) { AddNewParentEntityTokens(node, parentEntityTokens, RelationshipGraphNodeType.Entity, levelNumber); } } if (_searchOption == RelationshipGraphSearchOption.Hooked || _searchOption == RelationshipGraphSearchOption.Both) { IEnumerable parentEntityTokens; if (!EntityTokenCacheFacade.GetCachedHookingParents(node.EntityToken, out parentEntityTokens, userName)) { IEnumerable auxiliaryParentEntityTokens = AuxiliarySecurityAncestorFacade.GetParents(node.EntityToken); IEnumerable hookingParentEntityTokens = HookingFacade.GetHookies(node.EntityToken); parentEntityTokens = auxiliaryParentEntityTokens.ConcatOrDefault(hookingParentEntityTokens)?.Evaluate(); EntityTokenCacheFacade.AddHookingCache(node.EntityToken, parentEntityTokens); } if (parentEntityTokens != null) { AddNewParentEntityTokens(node, parentEntityTokens, RelationshipGraphNodeType.Hooking, levelNumber); } } } } private void AddNewParentEntityTokens(RelationshipGraphNode childNode, IEnumerable parents, RelationshipGraphNodeType nodeType, int levelNumber) { int newLevelNumber = levelNumber + 1; List levelNodes; if (!_levels.TryGetValue(newLevelNumber, out levelNodes)) { levelNodes = new List(); _levels.Add(newLevelNumber, levelNodes); } foreach (EntityToken parent in parents) { if(parent == null) { continue; } if (_visitedEntityTokens.Contains(parent)) { if (_excludeReoccuringNodes) { continue; // We have already visited this entity token, no new information here } } else { _visitedEntityTokens.Add(parent); } var parentNode = new RelationshipGraphNode(parent, newLevelNumber, nodeType); levelNodes.Add(parentNode); childNode.ParentNodes.Add(parentNode); parentNode.ChildNode = childNode; _moreLevelsToExpend = true; } } } } ================================================ FILE: Composite/C1Console/Security/RelationshipGraphLevel.cs ================================================ using System.Linq; using System.Collections.Generic; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class RelationshipGraphLevel { private List _relationshipGraphNodes; internal RelationshipGraphLevel(int level, List relationshipGraphNodes) { this.Level = level; this._relationshipGraphNodes = relationshipGraphNodes; } /// public int Level { get; private set; } /// public IEnumerable Entities { get { return from node in _relationshipGraphNodes where node.NodeType == RelationshipGraphNodeType.Entity select node.EntityToken; } } /// public IEnumerable HookedEntities { get { return from node in _relationshipGraphNodes where node.NodeType == RelationshipGraphNodeType.Hooking select node.EntityToken; } } /// public IEnumerable AllEntities { get { return from node in _relationshipGraphNodes select node.EntityToken; } } } } ================================================ FILE: Composite/C1Console/Security/RelationshipGraphNode.cs ================================================ using System.Diagnostics; using System.Collections.Generic; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum RelationshipGraphNodeType { /// Entity = 0, /// Hooking = 1 } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DebuggerDisplay("Level = {Level}, Type = {NodeType}, EntityToken = {EntityToken}")] public sealed class RelationshipGraphNode { internal RelationshipGraphNode(EntityToken entityToken, int level, RelationshipGraphNodeType relationshipGraphNodeType) { this.EntityToken = entityToken; this.Level = level; this.NodeType = relationshipGraphNodeType; this.ChildNode = null; this.ParentNodes = new List(); } /// public EntityToken EntityToken { get; private set; } /// public int Level { get; private set; } /// public RelationshipGraphNodeType NodeType { get; private set; } /// public List ParentNodes { get; set; } /// public RelationshipGraphNode ChildNode { get; set; } } } ================================================ FILE: Composite/C1Console/Security/SecurityAncestorProviderAttribute.cs ================================================ using System; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AttributeUsageAttribute(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public sealed class SecurityAncestorProviderAttribute : Attribute { private readonly Type _securityAncestorProviderType; /// public SecurityAncestorProviderAttribute(Type securityAncestorProviderType) { _securityAncestorProviderType = securityAncestorProviderType; } /// public Type SecurityAncestorProviderType { get { return _securityAncestorProviderType; } } } } ================================================ FILE: Composite/C1Console/Security/SecurityAncestorProviders/NoAncestorSecurityAncestorProvider.cs ================================================ using System; using System.Collections.Generic; namespace Composite.C1Console.Security.SecurityAncestorProviders { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class NoAncestorSecurityAncestorProvider : ISecurityAncestorProvider { /// public IEnumerable GetParents(EntityToken entityToken) { if (entityToken == null) throw new ArgumentNullException("entityToken"); return new EntityToken[] { }; } } } ================================================ FILE: Composite/C1Console/Security/SecurityResolver.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using Composite.Core.Linq; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class SecurityResolver { /// public static SecurityResult Resolve(UserToken userToken, ActionToken actionToken, EntityToken entityToken, IEnumerable userPermissionDefinitions, IEnumerable userGroupPermissionDefinition) { if (userToken == null) throw new ArgumentNullException("userToken"); if (actionToken == null) throw new ArgumentNullException("actionToken"); return Resolve(userToken, actionToken.PermissionTypes, entityToken, userPermissionDefinitions, userGroupPermissionDefinition); } /// public static SecurityResult Resolve(UserToken userToken, IEnumerable requiredPermissions, EntityToken entityToken, IEnumerable userPermissionDefinitions, IEnumerable userGroupPermissionDefinition) { if (userToken == null) throw new ArgumentNullException("userToken"); if (requiredPermissions == null) throw new ArgumentNullException("requiredPermissions"); if ((entityToken is NoSecurityEntityToken)) return SecurityResult.Allowed; requiredPermissions = requiredPermissions.Evaluate(); if (!requiredPermissions.Any()) { return SecurityResult.Allowed; } IEnumerable currentPermissionTypes = PermissionTypeFacade.GetCurrentPermissionTypes(userToken, entityToken, userPermissionDefinitions, userGroupPermissionDefinition); if (!currentPermissionTypes.Any()) { return SecurityResult.Disallowed; } // At least one of the permissions should be allowed foreach (PermissionType permissionType in currentPermissionTypes) { if (requiredPermissions.Contains(permissionType)) { return SecurityResult.Allowed; } } return SecurityResult.Disallowed; } /// public static SecurityResult Resolve(SecurityToken securityToken) { if (securityToken == null) throw new ArgumentNullException("securityToken"); IEnumerable userPermissionDefinitions = PermissionTypeFacade.GetUserPermissionDefinitions(securityToken.UserToken.Username); IEnumerable userGroupPermissionDefinition = PermissionTypeFacade.GetUserGroupPermissionDefinitions(securityToken.UserToken.Username); return Resolve(securityToken.UserToken, securityToken.ActionToken, securityToken.EntityToken, userPermissionDefinitions, userGroupPermissionDefinition); } } } ================================================ FILE: Composite/C1Console/Security/SecurityResult.cs ================================================ namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum SecurityResult { /// Disallowed, /// Allowed, /// Unspecified } } ================================================ FILE: Composite/C1Console/Security/SecurityToken.cs ================================================ namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class SecurityToken { private EntityToken _entityToken; private ActionToken _actionToken; private UserToken _userToken; /// public SecurityToken(EntityToken entityToken, ActionToken actionToken, UserToken userToken) { _entityToken = entityToken; _actionToken = actionToken; _userToken = userToken; } /// public EntityToken EntityToken { get { return _entityToken; } } /// public ActionToken ActionToken { get { return _actionToken; } } /// public UserToken UserToken { get { return _userToken; } } } } ================================================ FILE: Composite/C1Console/Security/UserGroupFacade.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; using Composite.Core.Linq; using Composite.Data; using Composite.Data.Types; namespace Composite.C1Console.Security { /// /// Provides a cached lookup to user group ids related to a user /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class UserGroupFacade { private static readonly ConcurrentDictionary> _cache = new ConcurrentDictionary>(); static UserGroupFacade() { DataEventSystemFacade.SubscribeToStoreChanged(OnDataChanged, true); DataEventSystemFacade.SubscribeToStoreChanged(OnDataChanged, true); DataEventSystemFacade.SubscribeToStoreChanged(OnDataChanged, true); } /// public static IReadOnlyCollection GetUserGroupIds(string username) { Verify.ArgumentNotNullOrEmpty(username, nameof(username)); return _cache.GetOrAdd(username, name => { IUser user = DataFacade.GetData() .Where(f => string.Compare(f.Username, name, StringComparison.InvariantCultureIgnoreCase) == 0) .SingleOrDefaultOrException("Multiple data records for the same user name '{0}'", name); Verify.IsNotNull(user, "Failed to find user by name '{0}'", name); return (from ur in DataFacade.GetData() where ur.UserId == user.Id select ur.UserGroupId).ToList(); }); } /// public static IEnumerable GetUserGroupActiveCultures(string username) { Verify.ArgumentNotNullOrEmpty(username, nameof(username)); return from ugal in DataFacade.GetData() join uugr in DataFacade.GetData() on ugal.UserGroupId equals uugr.UserGroupId join user in DataFacade.GetData() on uugr.UserId equals user.Id where user.Username == username select CultureInfo.CreateSpecificCulture(ugal.CultureName); } private static void OnDataChanged(object sender, StoreEventArgs storeEventArgs) { _cache.Clear(); } } } ================================================ FILE: Composite/C1Console/Security/UserGroupPermissionDefinition.cs ================================================ using System.Collections.Generic; using System; using Composite.Core; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class UserGroupPermissionDefinition { private EntityToken _entityToken; private bool _entityTokenInitialized; /// public abstract Guid UserGroupId { get; } /// public abstract IEnumerable PermissionTypes { get; } /// public abstract string SerializedEntityToken { get; } /// public EntityToken EntityToken { get { if (!_entityTokenInitialized) { try { _entityToken = EntityTokenSerializer.Deserialize(this.SerializedEntityToken, false); } catch (Exception ex) { Log.LogWarning("UserPermissionDefinition", "Failed to deserialize an entity token: '{0}'", SerializedEntityToken); Log.LogWarning("UserPermissionDefinition", ex); } finally { _entityTokenInitialized = true; } } return _entityToken; } } } } ================================================ FILE: Composite/C1Console/Security/UserGroupPerspectiveFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Data; using Composite.Data.Types; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class UserGroupPerspectiveFacade { /// public static IEnumerable GetSerializedEntityTokens(string username) { foreach (Guid userGroupId in UserGroupFacade.GetUserGroupIds(username)) { foreach (string serializedEntityToken in GetSerializedEntityTokens(userGroupId)) { yield return serializedEntityToken; } } } /// public static IEnumerable GetSerializedEntityTokens(Guid userGroupId) { return (from activePerspective in DataFacade.GetData() where activePerspective.UserGroupId == userGroupId select activePerspective.SerializedEntityToken).ToList(); } /// public static IEnumerable GetEntityTokens(Guid userGroupId) { return GetSerializedEntityTokens(userGroupId).Select(EntityTokenSerializer.Deserialize); } /// public static IEnumerable GetEntityTokens(string username) { return GetSerializedEntityTokens(username).Select(EntityTokenSerializer.Deserialize); } /// public static void SetEntityTokens(Guid userGroupId, IEnumerable entityTokens) { SetSerializedEntityTokens(userGroupId, entityTokens.Select(EntityTokenSerializer.Serialize)); } /// public static void SetSerializedEntityTokens(Guid userGroupId, IEnumerable serializedEntityTokens) { DataFacade.Delete(f => f.UserGroupId == userGroupId); foreach (string serializedEntityToken in serializedEntityTokens) { var activePerspective = DataFacade.BuildNew(); activePerspective.Id = Guid.NewGuid(); activePerspective.UserGroupId = userGroupId; activePerspective.SerializedEntityToken = serializedEntityToken; DataFacade.AddNew(activePerspective); } } /// public static void DeleteAll(Guid userGroupId) { DataFacade.Delete(f => f.UserGroupId == userGroupId); } } } ================================================ FILE: Composite/C1Console/Security/UserLockoutReason.cs ================================================ namespace Composite.C1Console.Security { /// /// Describing the user lockout reason /// internal enum UserLockoutReason { /// /// Undefined /// Undefined = 0, /// /// User has been locked by administrator /// LockedByAdministrator = 1, /// /// There were too many login attempts /// TooManyFailedLoginAttempts = 2, } } ================================================ FILE: Composite/C1Console/Security/UserPermissionDefinition.cs ================================================ using System.Collections.Generic; using System; using Composite.Core; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class UserPermissionDefinition { private EntityToken _entityToken; private bool _entityTokenInitialized; /// public abstract string Username { get; } /// public abstract IEnumerable PermissionTypes { get; } /// public abstract string SerializedEntityToken { get; } /// public EntityToken EntityToken { get { if (!_entityTokenInitialized) { try { _entityToken = EntityTokenSerializer.Deserialize(this.SerializedEntityToken, false); } catch (Exception ex) { Log.LogWarning("UserPermissionDefinition", "Failed to deserialize an entity token: '{0}'", SerializedEntityToken); Log.LogWarning("UserPermissionDefinition", ex); } finally { _entityTokenInitialized = true; } } return _entityToken; } } } } ================================================ FILE: Composite/C1Console/Security/UserPerspectiveFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Data; using Composite.Data.Types; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class UserPerspectiveFacade { /// public static IEnumerable GetSerializedEntityTokens(string username) { return from activePerspective in DataFacade.GetData() where activePerspective.Username == username select activePerspective.SerializedEntityToken; } /// public static IEnumerable GetEntityTokens(string username ) { return GetSerializedEntityTokens(username).Select(EntityTokenSerializer.Deserialize); } /// public static void SetEntityTokens(string username, IEnumerable entityTokens) { SetSerializedEntityTokens(username, entityTokens.Select(EntityTokenSerializer.Serialize)); } /// public static void SetSerializedEntityTokens(string username, IEnumerable serializedEntityTokens) { DataFacade.Delete(f => f.Username == username); foreach (string serializedEntityToken in serializedEntityTokens) { var activePerspective = DataFacade.BuildNew(); activePerspective.Username = username; activePerspective.SerializedEntityToken = serializedEntityToken; activePerspective.Id = Guid.NewGuid(); DataFacade.AddNew(activePerspective); } } /// public static void DeleteAll(string username) { DataFacade.Delete(f => f.Username == username); } internal static bool PerspectiveVisible(string username, EntityToken perspectiveEntityToken) { Verify.ArgumentNotNull(username, nameof(username)); Verify.ArgumentNotNull(perspectiveEntityToken, nameof(perspectiveEntityToken)); return GetEntityTokens(username).Contains(perspectiveEntityToken) || UserGroupPerspectiveFacade.GetEntityTokens(username).Contains(perspectiveEntityToken); } } } ================================================ FILE: Composite/C1Console/Security/UserToken.cs ================================================ namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class UserToken { /// public UserToken(string username) { this.Username = username; } /// public string Username { get; private set; } /// public override bool Equals(object obj) { return obj != null && obj is UserToken && (obj as UserToken).Username == Username; } /// public override int GetHashCode() { return Username.GetHashCode(); } } } ================================================ FILE: Composite/C1Console/Security/UserValidationFacade.cs ================================================ using System; using System.Web; using Composite.Core.Logging; using Composite.C1Console.Security.Foundation.PluginFacades; using Composite.C1Console.Security.Plugins.LoginProvider; using System.Collections.Generic; namespace Composite.C1Console.Security { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class UserValidationFacade { private static readonly object _lock = new object(); /// public enum ValidationType { /// None = 0, /// Form = 1, /// Windows = 2 }; private static readonly Dictionary LoginResultDescriptions = new Dictionary { {LoginResult.IncorrectPassword, "Incorrect password."}, {LoginResult.UserDoesNotExist, "User does not exist."}, {LoginResult.PolicyViolated, "Login policy violated."}, {LoginResult.UserLockedByAdministrator, "User is locked by an administrator."}, {LoginResult.UserLockedAfterMaxLoginAttempts, "User locked after reaching maximum login attempts."} }; /// public static ValidationType GetValidationType() { if (LoginProviderPluginFacade.CheckType()) { return ValidationType.Form; } if (LoginProviderPluginFacade.CheckType()) { return ValidationType.Windows; } throw new InvalidOperationException($"Validation plugin '{LoginProviderPluginFacade.GetValidationPluginType()}' does not implement a known validation interface"); } /// public static IEnumerable AllUsernames => LoginProviderPluginFacade.AllUsernames; /// public static bool CanSetUserPassword => LoginProviderPluginFacade.CanSetUserPassword; /// /// Validates and persists a form based login. If no users exist and the user name matches the default administrator user, that user will be created. /// /// /// /// True if the user was validated public static LoginResult FormValidateUser(string userName, string password) { LoginResult loginResult = LoginProviderPluginFacade.FormValidateUser(userName, password); if (loginResult == LoginResult.UserDoesNotExist && AdministratorAutoCreator.CanBeAutoCreated(userName)) { lock (_lock) { loginResult = LoginProviderPluginFacade.FormValidateUser(userName, password); if (loginResult == LoginResult.UserDoesNotExist && AdministratorAutoCreator.CanBeAutoCreated(userName)) { AdministratorAutoCreator.AutoCreateAdministrator(userName, password, ""); loginResult = LoginProviderPluginFacade.FormValidateUser(userName, password); } } } if (loginResult == LoginResult.Success) { LoggingService.LogVerbose("UserValidation", $"The user: [{userName}], has been validated and accepted. {GetIpInformation()}", LoggingService.Category.Audit); PersistUsernameInSessionDataProvider(userName); } else if (LoginResultDescriptions.ContainsKey(loginResult)) { LogLoginFailed(userName, LoginResultDescriptions[loginResult]); } return loginResult; } private static void LogLoginFailed(string userName, string message) { LoggingService.LogWarning("UserValidation", $"Login as [{userName}] failed. {message} {GetIpInformation()}", LoggingService.Category.Audit); } private static string GetIpInformation() { var httpContext = HttpContext.Current; if(httpContext == null) { return string.Empty; } string ipaddress = httpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (String.IsNullOrWhiteSpace(ipaddress)) { ipaddress = httpContext.Request.ServerVariables["REMOTE_ADDR"]; } if (String.IsNullOrWhiteSpace(ipaddress)) { return string.Empty; } return "IP address: " + ipaddress; } /// public static bool FormValidateUserWithoutLogin(string userName, string password) { return LoginProviderPluginFacade.FormValidateUser(userName, password) == LoginResult.Success; } /// public static void FormSetUserPassword(string userName, string password) { LoginProviderPluginFacade.FormSetUserPassword(userName, password); } /// /// Validates and persists a windows based login. Actual Windows username / password validation should precede this call. /// /// /// /// True if the user was validated public static bool WindowsValidateUser(string userName, string domainName) { bool userIsValidated = LoginProviderPluginFacade.WindowsValidateUser(userName, domainName); if (userIsValidated) { PersistUsernameInSessionDataProvider(userName); } return userIsValidated; } /// /// Flushes the username from the login session. /// [Obsolete("Use Logout() instead.")] public static void FlushUsername() => Logout(); /// /// Flushes the username from the login session (if applicable) and returns a logout URL. /// public static string Logout() => LoginSessionStorePluginFacade.Logout(); /// public static bool IsLoggedIn() => !string.IsNullOrEmpty(LoginSessionStorePluginFacade.StoredUsername); /// public static UserToken GetUserToken() { var userName = LoginSessionStorePluginFacade.StoredUsername; Verify.That(!string.IsNullOrEmpty(userName), "No user has been logged in"); return new UserToken(userName); } /// public static string GetUsername() { var userName = LoginSessionStorePluginFacade.StoredUsername; Verify.That(!string.IsNullOrEmpty(userName), "No user has been logged in"); return userName; } private static void PersistUsernameInSessionDataProvider(string userName) { LoginSessionStorePluginFacade.StoreUsername(userName, false); } } } ================================================ FILE: Composite/C1Console/Security/Utilities.cs ================================================ using System; namespace Composite.C1Console.Security { internal static class Utilities { public static void ParseUserLoginString(string windowsAuthenticatedFullName, out string userName, out string domainName) { ParseUserLoginString(windowsAuthenticatedFullName, out userName, out domainName, true); } public static bool TryParseUserLoginString(string windowsAuthenticatedFullName, out string userName, out string domainName) { return ParseUserLoginString(windowsAuthenticatedFullName, out userName, out domainName, false); } private static bool ParseUserLoginString(string windowsAuthenticatedFullName, out string userName, out string domainName, bool throwException) { // Format: [domain]\[username] or [username] if (string.IsNullOrEmpty(windowsAuthenticatedFullName)) { userName = null; domainName = null; return HandleError("Authenticated user name can not be null or empty", "windowsAuthenticatedFullName", throwException); } if (windowsAuthenticatedFullName.IndexOf(@"\") == -1) { domainName = ""; userName = windowsAuthenticatedFullName; } else { char[] userLoginSeparator = { '\\' }; string[] userLoginParts = windowsAuthenticatedFullName.Split(userLoginSeparator); if (2 == userLoginParts.Length && string.IsNullOrEmpty(userLoginParts[0]) == false && string.IsNullOrEmpty(userLoginParts[1]) == false) { domainName = userLoginParts[0]; userName = userLoginParts[1]; } else { userName = null; domainName = null; return HandleError("Unexpected user login format", "windowsAuthenticatedFullName", throwException); } } return true; } private static bool HandleError(string message, string paramName, bool throwException) { if (throwException) { throw new ArgumentException(message, paramName); } return false; } } } ================================================ FILE: Composite/C1Console/Tasks/BaseTaskManager.cs ================================================ using System; namespace Composite.C1Console.Tasks { internal class BaseTaskManager : ITaskManager { public virtual bool OnCreated(string taskId, TaskManagerEvent taskManagerEvent) { return true; } public virtual void OnCompleted(string taskId, TaskManagerEvent taskManagerEvent) { } public virtual void OnRun(string taskId, TaskManagerEvent taskManagerEvent) { } public virtual void OnStatus(string taskId, TaskManagerEvent taskManagerEvent) { } public virtual void OnIdle(string taskId, TaskManagerEvent taskManagerEvent) { } } } ================================================ FILE: Composite/C1Console/Tasks/ITaskManager.cs ================================================ using System; using Composite.C1Console.Actions; namespace Composite.C1Console.Tasks { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class TaskManagerEvent { } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class FlowTaskManagerEvent : TaskManagerEvent { /// public FlowTaskManagerEvent(FlowToken flowToken) { this.FlowToken = flowToken; } /// public FlowToken FlowToken { get; private set; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface ITaskManager { /// /// This is called when the tast is created for the first time. /// If this method returns false, the task will not get started and /// no more events on the task mananger will get called. /// /// /// /// bool OnCreated(string taskId, TaskManagerEvent taskManagerEvent); /// /// This is called just before an action/flow is started /// /// /// void OnRun(string taskId, TaskManagerEvent taskManagerEvent); /// /// This this will always be called after OnRun and before OnIdle. /// It may not be called, and it might also be called more than once. /// Check the for more information on the call /// /// /// void OnStatus(string taskId, TaskManagerEvent taskManagerEvent); /// /// This is called after an action/flow has gone idle /// /// /// void OnIdle(string taskId, TaskManagerEvent taskManagerEvent); /// /// This is called when the task is compleated. /// void OnCompleted(string taskId, TaskManagerEvent taskManagerEvent); } } ================================================ FILE: Composite/C1Console/Tasks/ITaskManagerFacade.cs ================================================ using System; using Composite.C1Console.Actions; using Composite.C1Console.Security; namespace Composite.C1Console.Tasks { internal interface ITaskManagerFacade { void AttachTaskCreator(Func taskCreator); TaskContainer CreateNewTasks(EntityToken entityToken, ActionToken actionToken, TaskManagerEvent taskManagerEvent); TaskContainer RuntTasks(FlowToken flowToken, TaskManagerEvent taskManagerEvent); void CompleteTasks(FlowToken flowToken); } } ================================================ FILE: Composite/C1Console/Tasks/ITaskManagerFlowControllerService.cs ================================================ using Composite.C1Console.Actions; namespace Composite.C1Console.Tasks { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface ITaskManagerFlowControllerService : IFlowControllerService { /// void OnStatus(TaskManagerEvent taskManagerEvent); } } ================================================ FILE: Composite/C1Console/Tasks/Task.cs ================================================ using System; using Composite.C1Console.Actions; namespace Composite.C1Console.Tasks { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class Task { /// public Task(string id, Type taskManagerType) { VerifyTaskManagerType(taskManagerType); this.Id = id; this.TaskManagerType = taskManagerType; this.StartTime = DateTime.Now; this.TaskManager = (ITaskManager)Activator.CreateInstance(taskManagerType); } /// public string Id { get; private set; } /// public Type TaskManagerType { get; private set; } /// public DateTime StartTime { get; internal set; } internal ITaskManager TaskManager { get; set; } internal string FlowToken { get; set; } private static void VerifyTaskManagerType(Type taskManagerType) { if (taskManagerType == null) throw new ArgumentNullException("taskManagerType"); if (typeof(ITaskManager).IsAssignableFrom(taskManagerType) == false) throw new ArgumentException("The type taskManagerType is not assigneble from the type: " + typeof(ITaskManager).FullName); } } } ================================================ FILE: Composite/C1Console/Tasks/TaskContainer.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Actions; using Composite.Core; using Composite.Core.Types; using Composite.Data; using Composite.Data.Types; namespace Composite.C1Console.Tasks { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class TaskContainer : IDisposable { private static readonly string LogTitle = typeof (TaskContainer).Name; private readonly List _tasks; private bool _disposed; internal TaskContainer(List tasks, TaskManagerEvent taskManagerEvent) { _tasks = tasks; foreach (Task task in _tasks) { task.TaskManager.OnRun(task.Id, taskManagerEvent); } } /// public void UpdateTasksWithFlowToken(FlowToken flowToken) { foreach (Task task in _tasks) { task.FlowToken = flowToken.Serialize(); } } /// public void OnStatus(TaskManagerEvent taskManagerEvent) { foreach (Task task in _tasks) { task.TaskManager.OnStatus(task.Id, taskManagerEvent); } } /// public void SetOnIdleTaskManagerEvent(TaskManagerEvent taskManagerEvent) { _onIdleTaskManagerEvent = taskManagerEvent; } private TaskManagerEvent _onIdleTaskManagerEvent; /// /// Saves tasks to database /// public void SaveTasks() { foreach (Task task in _tasks) { try { ITaskItem taskItem = DataFacade.BuildNew(); taskItem.Id = Guid.NewGuid(); taskItem.TaskId = task.Id; taskItem.TaskManagerType = TypeManager.SerializeType(task.TaskManagerType); taskItem.SerializedFlowToken = task.FlowToken; taskItem.StartTime = task.StartTime; DataFacade.AddNew(taskItem); } catch (Exception ex) { Log.LogError(LogTitle, "Error while attempt to persist a task"); Log.LogError(LogTitle, ex); } } } #if LeakCheck private string stack = Environment.StackTrace; /// ~TaskContainer() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); Dispose(false); } #endif /// public void Dispose() { Dispose(true); #if LeakCheck GC.SuppressFinalize(this); #endif } /// public void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; foreach (Task task in _tasks) { task.TaskManager.OnIdle(task.Id, _onIdleTaskManagerEvent); } } } } } ================================================ FILE: Composite/C1Console/Tasks/TaskManagerFacade.cs ================================================ using System; using Composite.C1Console.Actions; using Composite.C1Console.Security; namespace Composite.C1Console.Tasks { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class TaskManagerFacade { private static ITaskManagerFacade _implementation; private static readonly object _syncRoot = new object(); internal static ITaskManagerFacade Implementation { get { // Avoiding initialization in a static constructor so sql timeouts won't cause the type initialization exception var implementation = _implementation; if(implementation == null) { lock(_syncRoot) { implementation = _implementation; if(implementation == null) { _implementation = implementation = new TaskManagerFacadeImpl(); } } } return implementation; } set { _implementation = value; } } /// public static void AttachTaskCreator(Func taskCreator) { Implementation.AttachTaskCreator(taskCreator); } internal static TaskContainer CreateNewTasks(EntityToken entityToken, ActionToken actionToken, TaskManagerEvent taskManagerEvent) { return Implementation.CreateNewTasks(entityToken, actionToken, taskManagerEvent); } /// public static TaskContainer RuntTasks(FlowToken flowToken, TaskManagerEvent taskManagerEvent) { return Implementation.RuntTasks(flowToken, taskManagerEvent); } internal static void CompleteTasks(FlowToken flowToken) { Implementation.CompleteTasks(flowToken); } } } ================================================ FILE: Composite/C1Console/Tasks/TaskManagerFacadeImpl.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Security; using Composite.Core; using Composite.Data; using Composite.Core.Linq; using Composite.Data.Types; using Composite.Core.Threading; using Composite.Core.Types; namespace Composite.C1Console.Tasks { internal class TaskManagerFacadeImpl : ITaskManagerFacade { private readonly List> _taskCreators = new List>(); private readonly List _tasks = new List(); private readonly object _lock = new object(); public TaskManagerFacadeImpl() { LoadTasks(); } public void AttachTaskCreator(Func taskCreator) { _taskCreators.Add(taskCreator); } public TaskContainer CreateNewTasks(EntityToken entityToken, ActionToken actionToken, TaskManagerEvent taskManagerEvent) { List newTasks = new List(); lock (_lock) { foreach (Func taskCreator in _taskCreators) { try { Task task = taskCreator(entityToken, actionToken); if (task == null) continue; bool result = task.TaskManager.OnCreated(task.Id, taskManagerEvent); if (result == false) continue; _tasks.Add(task); newTasks.Add(task); } catch (Exception ex) { Log.LogError("TaskManagerFacade", "Starting new task failed with following exception"); Log.LogError("TaskManagerFacade", ex); } } } return new TaskContainer(newTasks, null); } public TaskContainer RuntTasks(FlowToken flowToken, TaskManagerEvent taskManagerEvent) { string serializedFlowToken = flowToken.Serialize(); List tasks; lock (_lock) { tasks = _tasks.Where(f => f.FlowToken == serializedFlowToken).ToList(); } return new TaskContainer(tasks, taskManagerEvent); } public void CompleteTasks(FlowToken flowToken) { string serializedFlowToken = flowToken.Serialize(); lock (_lock) { List tasks = _tasks.Where(f => f.FlowToken == serializedFlowToken).ToList(); foreach (Task task in tasks) { task.TaskManager.OnCompleted(task.Id, null); _tasks.Remove(task); DataFacade.Delete(f => f.TaskId == task.Id); } } } /// /// Loads task persisted in database /// private void LoadTasks() { using (ThreadDataManager.EnsureInitialize()) { IEnumerable taskItems = DataFacade.GetData().Evaluate(); var toDelete = new List(); foreach (ITaskItem taskItem in taskItems) { Type type = TypeManager.TryGetType(taskItem.TaskManagerType); if (type == null) { Log.LogWarning(nameof(TaskManagerFacade), $"Removing task item with id '{taskItem.TaskId}'. The Task Manager Type '{taskItem.TaskManagerType}' can not be found."); toDelete.Add(taskItem); if (toDelete.Count >= 100) { DataFacade.Delete(toDelete); toDelete.Clear(); } continue; } Task task = new Task(taskItem.TaskId, type) { StartTime = taskItem.StartTime, FlowToken = taskItem.SerializedFlowToken }; _tasks.Add(task); } if (toDelete.Count > 0) { DataFacade.Delete(toDelete); } } } } } ================================================ FILE: Composite/C1Console/Tasks/TaskManagerFlowControllerService.cs ================================================ namespace Composite.C1Console.Tasks { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class TaskManagerFlowControllerService : ITaskManagerFlowControllerService { private TaskContainer TaskContainer { get; set; } /// public TaskManagerFlowControllerService(TaskContainer taskContainer) { Verify.IsNotNull(taskContainer, "taskContainer"); this.TaskContainer = taskContainer; } /// public void OnStatus(TaskManagerEvent taskManagerEvent) { this.TaskContainer.OnStatus(taskManagerEvent); } } } ================================================ FILE: Composite/C1Console/Trees/ActionNode.cs ================================================ using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.Linq; using Composite.C1Console.Elements; using Composite.Core.ResourceSystem; using Composite.C1Console.Security; using Composite.Core; using Composite.Core.IO; using Composite.Core.Serialization; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class ActionNode { private static string TreeIdSerializedKeyName = "_TreeId_"; private static string ActionNodeIdSerializedKeyName = "_ActionNodeId_"; /// public string XPath { get; internal set; } /// public int Id { get; internal set; } /// public string Label { get; set; } // Requried /// public string ToolTip { get; set; } // Defaults to Label /// public ResourceHandle Icon { get; internal set; } // Requried /// public ActionLocation Location { get; internal set; } // Optional /// public List PermissionTypes { get; internal set; } // Optional /// public TreeNode OwnerNode { get; internal set; } // Cached values private DynamicValuesHelper LabelDynamicValuesHelper { get; set; } private DynamicValuesHelper ToolTipDynamicValuesHelper { get; set; } /// protected abstract void OnAddAction(Action actionAdder, EntityToken parentEntityToken, TreeNodeDynamicContext dynamicContext, DynamicValuesHelperReplaceContext dynamicValuesHelperReplaceContext); /// protected virtual void OnInitialize() { } /// protected ActionVisualizedData CreateActionVisualizedData(DynamicValuesHelperReplaceContext dynamicValuesHelperReplaceContext) { return new ActionVisualizedData { Label = this.LabelDynamicValuesHelper.ReplaceValues(dynamicValuesHelperReplaceContext), ToolTip = this.ToolTipDynamicValuesHelper.ReplaceValues(dynamicValuesHelperReplaceContext), Icon = this.Icon, Disabled = false, ActionLocation = this.Location }; } /// /// Use this method to do initializing and validation /// internal void Initialize() { this.LabelDynamicValuesHelper = new DynamicValuesHelper(this.Label); this.LabelDynamicValuesHelper.Initialize(this); this.ToolTipDynamicValuesHelper = new DynamicValuesHelper(this.ToolTip); this.ToolTipDynamicValuesHelper.Initialize(this); OnInitialize(); } /// public void AddAction(Action actionAdder, EntityToken entityToken, TreeNodeDynamicContext dynamicContext) { var piggybag = dynamicContext.Piggybag; if (!entityToken.Equals(dynamicContext.CurrentEntityToken)) { piggybag = piggybag.PreparePiggybag(dynamicContext.CurrentTreeNode, dynamicContext.CurrentEntityToken); } var replaceContext = new DynamicValuesHelperReplaceContext(entityToken, piggybag); OnAddAction(actionAdder, entityToken, dynamicContext, replaceContext); } /// public string Serialize() { var sb = new StringBuilder(); Serialize(sb); return sb.ToString(); } /// public void Serialize(StringBuilder sb) { StringConversionServices.SerializeKeyValuePair(sb, TreeIdSerializedKeyName, this.OwnerNode.Tree.TreeId); StringConversionServices.SerializeKeyValuePair(sb, ActionNodeIdSerializedKeyName, this.Id); } /// public static ActionNode Deserialize(string serializedString) { Dictionary serializedValueCollection = StringConversionServices.ParseKeyValueCollection(serializedString); return Deserialize(serializedValueCollection); } /// public static ActionNode Deserialize(Dictionary serializedValueCollection, bool removeEntiresFromCollection = false) { string treeId = StringConversionServices.DeserializeValueString(serializedValueCollection[TreeIdSerializedKeyName]); int actionNodeId = StringConversionServices.DeserializeValueInt(serializedValueCollection[ActionNodeIdSerializedKeyName]); if (removeEntiresFromCollection) { serializedValueCollection.Remove(TreeIdSerializedKeyName); serializedValueCollection.Remove(ActionNodeIdSerializedKeyName); } Tree tree = TreeFacade.GetTree(treeId); return tree?.GetActionNode(actionNodeId); } /// protected void AddValidationError(ValidationError validationError) { this.OwnerNode.Tree.BuildResult.AddValidationError(validationError); } /// protected void AddValidationError(string stringName, params object[] args) { this.OwnerNode.Tree.BuildResult.AddValidationError(ValidationError.Create(this.XPath, stringName, args)); } internal string LoadAndValidateCustomFormMarkupPath(string customFormMarkupPath) { string path; try { path = PathUtil.Resolve(customFormMarkupPath); if (!C1File.Exists(path)) { AddValidationError("TreeValidationError.CustomFormMarkup.MissingFile", path); return customFormMarkupPath; } } catch { AddValidationError("TreeValidationError.CustomFormMarkup.BadMarkupPath", customFormMarkupPath); return customFormMarkupPath; } try { XDocument.Load(path); } catch(Exception ex) { Log.LogError(nameof(ActionNode), $"Failed to load xml file '{path}'"); Log.LogError(nameof(ActionNode), ex); AddValidationError("TreeValidationError.CustomFormMarkup.InvalidXml", customFormMarkupPath); } return path; } } } ================================================ FILE: Composite/C1Console/Trees/AttributeDynamicValuesHelper.cs ================================================ using System.Collections.Generic; using System.Xml.Linq; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class AttributeDynamicValuesHelper { private readonly Dictionary _dynamicValuesHelpers = new Dictionary(); /// public XElement Element { get; private set; } /// public AttributeDynamicValuesHelper(XElement element) { this.Element = element; } /// public XElement ReplaceValues(DynamicValuesHelperReplaceContext context) { XElement result = new XElement(this.Element); foreach (XAttribute attribute in GetAttributes(result)) { DynamicValuesHelper dynamicValuesHelper = _dynamicValuesHelpers[GetKeyValue(attribute)]; string newValue = dynamicValuesHelper.ReplaceValues(context); attribute.SetValue(newValue); } return result; } /// public void Initialize(TreeNode ownerTreeNode) { foreach (XAttribute attribute in GetAttributes(this.Element)) { string key = GetKeyValue(attribute); if (_dynamicValuesHelpers.ContainsKey(key)) continue; DynamicValuesHelper dynamicValuesHelper = new DynamicValuesHelper(attribute.Value); dynamicValuesHelper.Initialize(ownerTreeNode); _dynamicValuesHelpers.Add(key, dynamicValuesHelper); } } private static IEnumerable GetAttributes(XElement element) { return element.DescendantsAndSelf().Attributes(); } private static string GetKeyValue(XAttribute attribute) { return attribute.Name + "·" + attribute.Value; } } } ================================================ FILE: Composite/C1Console/Trees/BuildResult.cs ================================================ using System.Collections.Generic; namespace Composite.C1Console.Trees { /// /// Contains information about tree validation errors /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class BuildResult { private readonly List _validationErrors = new List(); /// public void AddValidationError(ValidationError validationError) { Verify.IsNotNull(validationError, "validationError"); _validationErrors.Add(validationError); } /// public IEnumerable ValidationErrors { get { return _validationErrors; } } } } ================================================ FILE: Composite/C1Console/Trees/ConfirmActionNode.cs ================================================ using System; using System.Xml.Linq; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Functions; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ConfirmActionNode : ActionNode { /// public string ConfirmTitle { get; internal set; } // Requried /// public string ConfirmMessage { get; internal set; } // Requried /// public XElement FunctionMarkup { get; internal set; } // Requried /// public bool RefreshTree { get; internal set; } // Optional // Cached values /// public DynamicValuesHelper ConfirmTitleDynamicValuesHelper { get; set; } /// public DynamicValuesHelper ConfirmMessageDynamicValuesHelper { get; set; } /// public AttributeDynamicValuesHelper FunctionMarkupDynamicValuesHelper { get; private set; } /// protected override void OnAddAction(Action actionAdder, EntityToken entityToken, TreeNodeDynamicContext dynamicContext, DynamicValuesHelperReplaceContext dynamicValuesHelperReplaceContext) { WorkflowActionToken actionToken = new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.C1Console.Trees.Workflows.ConfirmActionWorkflow"), this.PermissionTypes) { Payload = this.Serialize(), ExtraPayload = PiggybagSerializer.Serialize(dynamicContext.Piggybag.PreparePiggybag(this.OwnerNode, dynamicContext.CurrentEntityToken)), DoIgnoreEntityTokenLocking = true }; actionAdder(new ElementAction(new ActionHandle(actionToken)) { VisualData = CreateActionVisualizedData(dynamicValuesHelperReplaceContext) }); } /// protected override void OnInitialize() { try { FunctionTreeBuilder.Build(this.FunctionMarkup); } catch { AddValidationError("TreeValidationError.Common.WrongFunctionMarkup"); return; } this.FunctionMarkupDynamicValuesHelper = new AttributeDynamicValuesHelper(this.FunctionMarkup); this.FunctionMarkupDynamicValuesHelper.Initialize(this.OwnerNode); this.ConfirmTitleDynamicValuesHelper = new DynamicValuesHelper(this.ConfirmTitle); this.ConfirmTitleDynamicValuesHelper.Initialize(this.OwnerNode); this.ConfirmMessageDynamicValuesHelper = new DynamicValuesHelper(this.ConfirmMessage); this.ConfirmMessageDynamicValuesHelper.Initialize(this.OwnerNode); } } } ================================================ FILE: Composite/C1Console/Trees/CustomUrlActionNode.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Elements; using Composite.Core.ResourceSystem; using Composite.C1Console.Security; using Composite.Core.Serialization; using Composite.Core.WebClient; namespace Composite.C1Console.Trees { internal enum CustomUrlActionNodeViewType { GenericView = 0, PageBrowser = 1, FileDownload = 2, DocumentView = 3, ExternalView = 4 } internal sealed class CustomUrlActionNode : ActionNode { public string Url { get; internal set; } // Requried public CustomUrlActionNodeViewType ViewType { get; internal set; } // Optional public string ViewLabel { get; internal set; } // Optional public string ViewToolTip { get; internal set; } // Optional public ResourceHandle ViewIcon { get; internal set; } // Optional public bool External { get; internal set; } // Optional public Dictionary PostParameters { get; internal set; } // Optional // Cached values private DynamicValuesHelper UrlDynamicValuesHelper { get; set; } private DynamicValuesHelper ViewLabelDynamicValuesHelper { get; set; } private DynamicValuesHelper ViewToolTipDynamicValuesHelper { get; set; } protected override void OnAddAction(Action actionAdder, EntityToken entityToken, TreeNodeDynamicContext dynamicContext, DynamicValuesHelperReplaceContext dynamicValuesHelperReplaceContext) { string url = this.UrlDynamicValuesHelper.ReplaceValues(dynamicValuesHelperReplaceContext); this.External = url.Contains("//"); if(!External) { url = UrlUtils.ResolvePublicUrl(url); } CustomUrlActionNodeActionToken actionToken = new CustomUrlActionNodeActionToken( url, this.External, (this.External ? "externalview" : "documentview"), this.ViewLabelDynamicValuesHelper.ReplaceValues(dynamicValuesHelperReplaceContext), this.ViewToolTipDynamicValuesHelper.ReplaceValues(dynamicValuesHelperReplaceContext), this.Serialize(), this.PermissionTypes); ElementAction elementAction = new ElementAction(new ActionHandle(actionToken)) { VisualData = CreateActionVisualizedData(dynamicValuesHelperReplaceContext) }; actionAdder(elementAction); } protected override void OnInitialize() { this.UrlDynamicValuesHelper = new DynamicValuesHelper(this.Url); this.UrlDynamicValuesHelper.Initialize(this.OwnerNode); this.UrlDynamicValuesHelper.UseUrlEncode = true; this.ViewLabelDynamicValuesHelper = new DynamicValuesHelper(this.ViewLabel); this.ViewLabelDynamicValuesHelper.Initialize(this.OwnerNode); this.ViewToolTipDynamicValuesHelper = new DynamicValuesHelper(this.ViewToolTip); this.ViewToolTipDynamicValuesHelper.Initialize(this.OwnerNode); } } internal sealed class CustomUrlActionNodeActionExecutor : IActionExecutor { public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { CustomUrlActionNodeActionToken customUrlActionNodeActionToken = (CustomUrlActionNodeActionToken)actionToken; CustomUrlActionNode customUrlActionNode = (CustomUrlActionNode)ActionNode.Deserialize(customUrlActionNodeActionToken.SerializedActionNode); string currentConsoleId = flowControllerServicesContainer.GetService().CurrentConsoleId; switch (customUrlActionNode.ViewType) { case CustomUrlActionNodeViewType.DocumentView: { string viewId = Guid.NewGuid().ToString(); string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken, true); OpenViewMessageQueueItem openViewMessageQueueItem = new OpenViewMessageQueueItem() { ViewId = viewId, EntityToken = serializedEntityToken, Label = customUrlActionNodeActionToken.ViewLabel, ToolTip = customUrlActionNodeActionToken.ViewToolTip, IconResourceHandle = customUrlActionNode.ViewIcon, Url = customUrlActionNodeActionToken.Url, UrlPostArguments = customUrlActionNode.PostParameters }; ConsoleMessageQueueFacade.Enqueue(openViewMessageQueueItem, currentConsoleId); BindEntityTokenToViewQueueItem bindEntityTokenToViewQueueItem = new BindEntityTokenToViewQueueItem() { ViewId = viewId, EntityToken = serializedEntityToken }; ConsoleMessageQueueFacade.Enqueue(bindEntityTokenToViewQueueItem, currentConsoleId); } break; case CustomUrlActionNodeViewType.ExternalView: { string viewId = Guid.NewGuid().ToString(); string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken, true); OpenExternalViewQueueItem openExternalViewQueueItem = new OpenExternalViewQueueItem(entityToken) { ViewId = viewId, EntityToken = serializedEntityToken, Label = customUrlActionNodeActionToken.ViewLabel, ToolTip = customUrlActionNodeActionToken.ViewToolTip, IconResourceHandle = customUrlActionNode.ViewIcon, Url = customUrlActionNodeActionToken.Url, ViewType = customUrlActionNodeActionToken.ViewType, UrlPostArguments = customUrlActionNode.PostParameters }; ConsoleMessageQueueFacade.Enqueue(openExternalViewQueueItem, currentConsoleId); BindEntityTokenToViewQueueItem bindEntityTokenToViewQueueItem = new BindEntityTokenToViewQueueItem() { ViewId = viewId, EntityToken = serializedEntityToken }; ConsoleMessageQueueFacade.Enqueue(bindEntityTokenToViewQueueItem, currentConsoleId); } break; case CustomUrlActionNodeViewType.GenericView: { string viewId = Guid.NewGuid().ToString(); string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken, true); OpenGenericViewQueueItem openGenericViewQueueItem = new OpenGenericViewQueueItem(entityToken) { ViewId = viewId, EntityToken = serializedEntityToken, Label = customUrlActionNodeActionToken.ViewLabel, ToolTip = customUrlActionNodeActionToken.ViewToolTip, IconResourceHandle = customUrlActionNode.ViewIcon, Url = customUrlActionNodeActionToken.Url, UrlPostArguments = customUrlActionNode.PostParameters }; ConsoleMessageQueueFacade.Enqueue(openGenericViewQueueItem, currentConsoleId); BindEntityTokenToViewQueueItem bindEntityTokenToViewQueueItem = new BindEntityTokenToViewQueueItem() { ViewId = viewId, EntityToken = serializedEntityToken }; ConsoleMessageQueueFacade.Enqueue(bindEntityTokenToViewQueueItem, currentConsoleId); } break; case CustomUrlActionNodeViewType.PageBrowser: Dictionary arguments = new Dictionary(); arguments.Add("URL", customUrlActionNodeActionToken.Url); OpenHandledViewMessageQueueItem openHandledViewMessageQueueItem = new OpenHandledViewMessageQueueItem( EntityTokenSerializer.Serialize(entityToken, true), "Composite.Management.Browser", arguments ); ConsoleMessageQueueFacade.Enqueue(openHandledViewMessageQueueItem, currentConsoleId); break; case CustomUrlActionNodeViewType.FileDownload: DownloadFileMessageQueueItem downloadFileMessageQueueItem = new DownloadFileMessageQueueItem(customUrlActionNodeActionToken.Url); ConsoleMessageQueueFacade.Enqueue(downloadFileMessageQueueItem, currentConsoleId); break; } return null; } } [ActionExecutor(typeof(CustomUrlActionNodeActionExecutor))] internal sealed class CustomUrlActionNodeActionToken : ActionToken { private List _permissionTypes; public CustomUrlActionNodeActionToken(string url, bool external, string viewtype, string viewLabel, string viewToolTip, string serializedActionNode, List permissionTypes) { this.Url = url; this.Extenal = external; this.ViewType = viewtype; this.ViewLabel = viewLabel; this.ViewToolTip = viewToolTip; _permissionTypes = permissionTypes; this.SerializedActionNode = serializedActionNode; } public string Url { get; private set; } public bool Extenal { get; private set; } public string ViewLabel { get; private set; } public string ViewToolTip { get; private set; } public string ViewType { get; private set; } public string SerializedActionNode { get; private set; } public override IEnumerable PermissionTypes { get { return _permissionTypes; } } public override string Serialize() { StringBuilder sb = new StringBuilder(); StringConversionServices.SerializeKeyValuePair(sb, "Url", this.Url); StringConversionServices.SerializeKeyValuePair(sb, "External", this.Extenal.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()); StringConversionServices.SerializeKeyValuePair(sb, "ViewType", this.ViewType); StringConversionServices.SerializeKeyValuePair(sb, "ViewLabel", this.ViewLabel); StringConversionServices.SerializeKeyValuePair(sb, "ViewToolTip", this.ViewToolTip); StringConversionServices.SerializeKeyValuePair(sb, "SerializedActionNode", this.SerializedActionNode); StringConversionServices.SerializeKeyValuePair(sb, "PermissionTypes", _permissionTypes.SerializePermissionTypes()); return sb.ToString(); } public static ActionToken Deserialize(string serializedData) { Dictionary dic = StringConversionServices.ParseKeyValueCollection(serializedData); return new CustomUrlActionNodeActionToken ( StringConversionServices.DeserializeValueString(dic["Url"]), StringConversionServices.DeserializeValueBool(dic["External"]), StringConversionServices.DeserializeValueString(dic["ViewType"]), StringConversionServices.DeserializeValueString(dic["ViewLabel"]), StringConversionServices.DeserializeValueString(dic["ViewToolTip"]), StringConversionServices.DeserializeValueString(dic["SerializedActionNode"]), StringConversionServices.DeserializeValueString(dic["PermissionTypes"]).DesrializePermissionTypes().ToList() ); } } } ================================================ FILE: Composite/C1Console/Trees/DataElementsTreeNode.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.C1Console.Trees.Foundation; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.ResourceSystem; using Composite.Core.Routing; using Composite.Core.Types; using Composite.Data; using Composite.Data.ProcessControlled; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class DataElementsTreeNode : DataFilteringTreeNode { /// public Type InterfaceType { get; internal set; } // Requried /// public string Label { get; internal set; } // Optional /// public string ToolTip { get; internal set; } // Optional /// public ResourceHandle Icon { get; internal set; } // Defaults to C1 standard data icons /// public ResourceHandle OpenedIcon { get; internal set; } // Defaults to C1 standard data icons or Icon if it is setted /// public LeafDisplayMode Display { get; internal set; } // Optional /// public bool ShowForeignItems { get; internal set; } // Optional /// public string BrowserUrl { get; internal set; } // Optional /// public string BrowserImage { get; internal set; } // Optional // Cached values private Dictionary ParentFilteringHelpers { get; set; } // Cached values private PropertyInfo KeyPropertyInfo { get; set; } // Cached values private ParentIdFilterNode JoinParentIdFilterNode { get; set; } private DataElementsTreeNode JoinDataElementsTreeNode { get; set; } private PropertyInfo JoinInnerKeyReferencePropertyInfo { get; set; } private DynamicValuesHelper LabelDynamicValuesHelper { get; set; } private DynamicValuesHelper ToolTipDynamicValuesHelper { get; set; } private DynamicValuesHelper BrowserUrlDynamicValuesHelper { get; set; } private DynamicValuesHelper BrowserImageDynamicValuesHelper { get; set; } private static readonly ResourceHandle LocalizeDataTypeIcon = ResourceHandle.BuildIconFromDefaultProvider("tree-localize-data"); private static readonly PermissionType[] LocalizeDataPermissionTypes = new PermissionType[] { PermissionType.Add }; /// public override IEnumerable GetEntityTokens(EntityToken childEntityToken, TreeNodeDynamicContext dynamicContext) { IEnumerable dataset = GetDataset(dynamicContext, false).DataItems; return dataset.Select(f => (EntityToken)f.GetDataEntityToken()).Evaluate(); } /// public override AncestorResult GetParentEntityToken(EntityToken ownEntityToken, Type parentInterfaceOfInterest, TreeNodeDynamicContext dynamicContext) { if (this.ParentFilteringHelpers == null) { throw new InvalidOperationException(string.Format("Failed to find parent, are you missing a parent filter for the type '{0}'", this.InterfaceType)); } ParentFilterHelper helper; if (this.ParentFilteringHelpers.TryGetValue(parentInterfaceOfInterest, out helper) == false) { // We cant find the interface of interest directly, so we will give 'some' parent entity token // by using 'one' of our own parent id filters helper = this.ParentFilteringHelpers.First().Value; } DataEntityToken dataEntityToken = (DataEntityToken)ownEntityToken; IData data = dataEntityToken.Data; Verify.ArgumentCondition(data != null, "ownEntityToken", "Failed to get data"); object parentFieldValue = helper.ParentReferencedPropertyInfo.GetValue(data, null); ParameterExpression parameterExpression = Expression.Parameter(helper.ParentIdFilterNode.ParentFilterType, "data"); Expression expression = Expression.Equal( ExpressionHelper.CreatePropertyExpression(helper.ParentRefereePropertyName, parameterExpression), Expression.Constant(parentFieldValue, helper.ParentReferencedPropertyInfo.PropertyType) ); Expression whereExpression = ExpressionHelper.CreateWhereExpression( DataFacade.GetData(helper.ParentIdFilterNode.ParentFilterType).Expression, parameterExpression, expression ); IData parentDataItem = ExpressionHelper.GetCastedObjects(helper.ParentIdFilterNode.ParentFilterType, whereExpression) .FirstOrDefault(); Verify.IsNotNull(parentDataItem, "Failed to get parent data item. Check if there's a broken parent reference."); DataEntityToken parentEntityToken = parentDataItem.GetDataEntityToken(); TreeNode parentTreeNode = this.ParentNode; var dataElementsTreeNode = parentTreeNode as DataElementsTreeNode; while (dataElementsTreeNode == null || dataElementsTreeNode.InterfaceType != parentEntityToken.InterfaceType) { parentTreeNode = parentTreeNode.ParentNode; } return new AncestorResult(parentTreeNode, parentEntityToken); } /// protected override IEnumerable OnGetElements(EntityToken parentEntityToken, TreeNodeDynamicContext dynamicContext) { bool localizationEnabled = this.ShowForeignItems && !UserSettings.ActiveLocaleCultureInfo.Equals(UserSettings.ForeignLocaleCultureInfo); NodeDataSet dataset = GetDataset(dynamicContext); var itemKeys = new List(); IEnumerable dataItems; IEnumerable keysJoinedByParentFilters = dataset.JoinedKeys; if (localizationEnabled && UserSettings.ForeignLocaleCultureInfo != null) { NodeDataSet foreignDataset; using (new DataScope(UserSettings.ForeignLocaleCultureInfo)) { foreignDataset = GetDataset(dynamicContext); } ParameterExpression parameterExpression = Expression.Parameter(this.InterfaceType, "data"); IEnumerable combinedData = dataset.DataItems.Concat(foreignDataset.DataItems).ToCastedDataEnumerable(this.InterfaceType); Expression orderByExpression = this.CreateOrderByExpression(combinedData.AsQueryable().Expression, parameterExpression); dataItems = combinedData.AsQueryable().Provider.CreateQuery(orderByExpression); foreach (IData data in dataset.DataItems) { Verify.IsNotNull(data, "Fetching data for data interface '{0}' with expression '{1}' yielded an null element".FormatWith(this.InterfaceType, orderByExpression)); object keyValue = this.KeyPropertyInfo.GetValue(data, null); itemKeys.Add(keyValue); } keysJoinedByParentFilters = keysJoinedByParentFilters.ConcatOrDefault(foreignDataset.JoinedKeys); } else { dataItems = dataset.DataItems; itemKeys = new List(); } var replaceContext = new DynamicValuesHelperReplaceContext(parentEntityToken, dynamicContext.Piggybag); var elements = new List(); foreach (IData data in dataItems) { Verify.IsNotNull(data, "Fetching data for data interface '{0}' yielded an null element".FormatWith(this.InterfaceType)); var element = BuildElement(data, replaceContext, dynamicContext, localizationEnabled, itemKeys, ref keysJoinedByParentFilters, parentEntityToken); if(element == null) continue; elements.Add(element); } if (!this.OrderByNodes.Any()) { return elements.OrderBy(f => f.VisualData.Label); } return elements; } private Element BuildElement(IData data, DynamicValuesHelperReplaceContext replaceContext, TreeNodeDynamicContext dynamicContext, bool localizationEnabled, List itemKeys, ref IEnumerable keysJoinedByParentFilters, EntityToken parentEntityToken ) { replaceContext.CurrentDataItem = data; object keyValue = this.KeyPropertyInfo.GetValue(data, null); bool itemLocalizationEnabledAndForeign = localizationEnabled && !data.DataSourceId.LocaleScope.Equals(UserSettings.ActiveLocaleCultureInfo); if (itemLocalizationEnabledAndForeign && itemKeys.Contains(keyValue)) return null; var currentEntityToken = data.GetDataEntityToken(); var element = new Element(new ElementHandle ( dynamicContext.ElementProviderName, currentEntityToken, dynamicContext.Piggybag.PreparePiggybag(this.ParentNode, parentEntityToken) )); if (parentEntityToken is TreePerspectiveEntityToken) { element.ElementHandle.Piggyback[StringConstants.PiggybagTreeId] = Tree.TreeId; } bool hasChildren; bool isDisabled = false; ResourceHandle icon, openedIcon; if (itemLocalizationEnabledAndForeign) { hasChildren = false; isDisabled = !data.IsTranslatable(); if (this.Icon != null) { icon = this.Icon; openedIcon = this.OpenedIcon; } else { icon = data.GetForeignIcon(); openedIcon = icon; } } else { if (this.Display != LeafDisplayMode.Auto) { hasChildren = ChildNodes.Any(); } else { hasChildren = ChildNodes.OfType().Any(); if (!hasChildren) { if (keysJoinedByParentFilters != null) { keysJoinedByParentFilters = keysJoinedByParentFilters.Evaluate(); hasChildren = keysJoinedByParentFilters.Contains(keyValue); } } // Checking children filtered by FunctionFilters if (!hasChildren) { foreach (var childNode in this.ChildNodes.OfType() .Where(n => n.FilterNodes.OfType().Any())) { var newDynamicContext = new TreeNodeDynamicContext(TreeNodeDynamicContextDirection.Down) { ElementProviderName = dynamicContext.ElementProviderName, Piggybag = dynamicContext.Piggybag.PreparePiggybag(this.ParentNode, parentEntityToken), CurrentEntityToken = currentEntityToken }; if (childNode.GetDataset(newDynamicContext, false).DataItems.Any()) { hasChildren = true; break; } } } } if (this.Icon != null) { icon = this.Icon; openedIcon = this.OpenedIcon; } else { openedIcon = icon = data.GetIcon(); } } string label = this.Label.IsNullOrEmpty() ? data.GetLabel() : this.LabelDynamicValuesHelper.ReplaceValues(replaceContext); string toolTip = this.ToolTip.IsNullOrEmpty() ? label : this.ToolTipDynamicValuesHelper.ReplaceValues(replaceContext); if (itemLocalizationEnabledAndForeign) { label = string.Format("{0} ({1})", label, DataLocalizationFacade.GetCultureTitle(UserSettings.ForeignLocaleCultureInfo)); if (!data.IsTranslatable()) { toolTip = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "LocalizeDataWorkflow.DisabledData"); } else { toolTip = string.Format("{0} ({1})", toolTip, DataLocalizationFacade.GetCultureTitle(UserSettings.ForeignLocaleCultureInfo)); } } element.VisualData = new ElementVisualizedData { Label = label, ToolTip = toolTip, HasChildren = hasChildren, Icon = icon, OpenedIcon = openedIcon, IsDisabled = isDisabled }; if (InternalUrls.DataTypeSupported(data.DataSourceId.InterfaceType)) { var dataReference = data.ToDataReference(); if (DataUrls.CanBuildUrlForData(dataReference)) { string internalUrl = InternalUrls.TryBuildInternalUrl(dataReference); if (internalUrl != null) { element.PropertyBag.Add("Uri", internalUrl); } } } if (this.BrowserUrl != null) { var url = this.BrowserUrlDynamicValuesHelper.ReplaceValues(replaceContext); if (!url.Contains("//")) { url = Core.WebClient.UrlUtils.ResolvePublicUrl(url); } element.PropertyBag.Add("BrowserUrl", url); element.PropertyBag.Add("BrowserToolingOn", "false"); } if (this.BrowserImage != null) { var url = this.BrowserImageDynamicValuesHelper.ReplaceValues(replaceContext); if (!url.Contains("//")) { url = Core.WebClient.UrlUtils.ResolvePublicUrl(url); } element.PropertyBag.Add("ListViewImage", url); if (this.BrowserUrl == null) { element.PropertyBag.Add("DetailViewImage", url); } } if (itemLocalizationEnabledAndForeign) { var actionToken = new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.C1Console.Trees.Workflows.LocalizeDataWorkflow"), LocalizeDataPermissionTypes); element.AddAction(new ElementAction(new ActionHandle(actionToken)) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "LocalizeDataWorkflow.LocalizeDataLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "LocalizeDataWorkflow.LocalizeDataToolTip"), Icon = LocalizeDataTypeIcon, Disabled = false, ActionLocation = ActionLocation.OtherPrimaryActionLocation } }); } return element; } /// protected override void OnInitialize() { if (!typeof(IData).IsAssignableFrom(this.InterfaceType)) { AddValidationError("TreeValidationError.Common.NotImplementingIData", this.InterfaceType, typeof(IData)); return; } IEnumerable siblingInterfaceTypes = this.ParentNode.ChildNodes.Where(f => f.GetType() == typeof(DataElementsTreeNode)).Select(f => ((DataElementsTreeNode)f).InterfaceType).ToList(); if (siblingInterfaceTypes.Count() != siblingInterfaceTypes.Distinct().Count()) { AddValidationError("TreeValidationError.DataElementsTreeNode.SameInterfaceUsedTwice", this.InterfaceType); return; } this.KeyPropertyInfo = this.CurrentDataInterfaceType.GetKeyProperties()[0]; foreach (ParentIdFilterNode parentIdFilterNode in this.FilterNodes.OfType()) { if (this.ParentFilteringHelpers == null) this.ParentFilteringHelpers = new Dictionary(); if (this.ParentFilteringHelpers.ContainsKey(parentIdFilterNode.ParentFilterType)) { AddValidationError("TreeValidationError.DataElementsTreeNode.SameParentFilterInterfaceUsedTwice", parentIdFilterNode.ParentFilterType); return; } var helper = new ParentFilterHelper { ParentIdFilterNode = parentIdFilterNode, ParentReferencedPropertyInfo = this.InterfaceType.GetPropertiesRecursively().Single(f => f.Name == parentIdFilterNode.ReferenceFieldName), ParentRefereePropertyName = parentIdFilterNode.ParentFilterType.GetKeyProperties()[0].Name }; this.ParentFilteringHelpers.Add(parentIdFilterNode.ParentFilterType, helper); } this.JoinParentIdFilterNode = null; this.JoinDataElementsTreeNode = null; foreach (TreeNode descendantTreeNode in this.DescendantsBreadthFirst()) { var dataElementTreeNode = descendantTreeNode as DataElementsTreeNode; if (dataElementTreeNode == null) continue; ParentIdFilterNode parentIdFilterNode = dataElementTreeNode.FilterNodes.OfType() .FirstOrDefault(f => f.ParentFilterType == this.InterfaceType); if (parentIdFilterNode != null) { if (this.JoinParentIdFilterNode == null) { this.JoinParentIdFilterNode = parentIdFilterNode; this.JoinDataElementsTreeNode = dataElementTreeNode; this.JoinInnerKeyReferencePropertyInfo = this.JoinDataElementsTreeNode.CurrentDataInterfaceType.GetAllProperties().Single(f => f.Name == this.JoinParentIdFilterNode.ReferenceFieldName); } else if (this.Display != LeafDisplayMode.Lazy) { AddValidationError("TreeValidationError.DataElementsTreeNode.MoreThanOnParentFilterIsPointingToMe", this.InterfaceType); return; } } } if (this.Label != null) { this.LabelDynamicValuesHelper = new DynamicValuesHelper(this.Label); this.LabelDynamicValuesHelper.Initialize(this); } if (this.ToolTip != null) { this.ToolTipDynamicValuesHelper = new DynamicValuesHelper(this.ToolTip); this.ToolTipDynamicValuesHelper.Initialize(this); } if (!typeof(ILocalizedControlled).IsAssignableFrom(this.InterfaceType)) { this.ShowForeignItems = false; } if (this.BrowserUrl != null) { this.BrowserUrlDynamicValuesHelper = new DynamicValuesHelper(this.BrowserUrl); this.BrowserUrlDynamicValuesHelper.Initialize(this); } if (this.BrowserImage != null) { this.BrowserImageDynamicValuesHelper = new DynamicValuesHelper(this.BrowserImage); this.BrowserImageDynamicValuesHelper.Initialize(this); } } internal override Type CurrentDataInterfaceType { get { return this.InterfaceType; } } /// /// Data related to a tree node /// private class NodeDataSet { public IEnumerable DataItems; public IEnumerable JoinedKeys; } private NodeDataSet GetDataset(TreeNodeDynamicContext dynamicContext, bool returnJoinedTableKeys = true) { List innerKeys = null; Expression expression; if (this.Display == LeafDisplayMode.Compact && this.JoinDataElementsTreeNode != null) { expression = CreateJoinExpression(dynamicContext); } else if (this.Display == LeafDisplayMode.Auto && this.JoinDataElementsTreeNode != null) { expression = CreateSimpleExpression(dynamicContext); if (returnJoinedTableKeys) { //MRJ: Multiple Parent Filter: Not a real problem here as we just make a request for every filter Expression innerExpression = CreateInnerExpression(dynamicContext, this.JoinParentIdFilterNode, this.JoinDataElementsTreeNode, false); if (dynamicContext.Direction == TreeNodeDynamicContextDirection.Down) { innerExpression.DebugLogExpression("DataElementTreeNode", label: "Parent ids with children expression:"); } innerKeys = DataFacade.GetData(this.JoinDataElementsTreeNode.CurrentDataInterfaceType).Provider .CreateQuery(innerExpression) .ToEnumerableOfObjects() .ToList(); } } else { expression = CreateSimpleExpression(dynamicContext); } if (dynamicContext.Direction == TreeNodeDynamicContextDirection.Down) expression.DebugLogExpression("DataElementTreeNode"); return new NodeDataSet { DataItems = ExpressionHelper.GetCastedObjects(this.InterfaceType, expression), JoinedKeys = innerKeys }; } private Expression CreateSimpleExpression(TreeNodeDynamicContext dynamicContext) { ParameterExpression parameterExpression = Expression.Parameter(this.InterfaceType, "data"); Expression filterExpression = CreateAccumulatedFilterExpression(parameterExpression, this.InterfaceType, dynamicContext); Expression whereExpression = ExpressionHelper.CreateWhereExpression(DataFacade.GetData(this.InterfaceType).Expression, parameterExpression, filterExpression); Expression resultExpression = whereExpression; bool isFirst = true; foreach (OrderByNode orderByNode in this.OrderByNodes) { resultExpression = orderByNode.CreateOrderByExpression(resultExpression, parameterExpression, isFirst); isFirst = false; } return resultExpression; } private Expression CreateJoinExpression(TreeNodeDynamicContext dynamicContext) { //MRJ: Multiple Parent Filter: Here we have to make either multiple calls or create a multiple inner join, kinda hard // Create inner expression tree Expression innerDistinctExpression = CreateInnerExpression(dynamicContext, this.JoinParentIdFilterNode, this.JoinDataElementsTreeNode); // Create outer expression tree ParameterExpression outerParameterExpression = Expression.Parameter(this.InterfaceType, "outerData"); Expression outerFilterExpression = CreateAccumulatedFilterExpression(outerParameterExpression, this.InterfaceType, dynamicContext); Expression outerWhereExpression = ExpressionHelper.CreateWhereExpression(DataFacade.GetData(this.InterfaceType).Expression, outerParameterExpression, outerFilterExpression); Expression outerResultExpression = outerWhereExpression; bool isFirst = true; foreach (OrderByNode orderByNode in this.OrderByNodes) { outerResultExpression = orderByNode.CreateOrderByExpression(outerResultExpression, outerParameterExpression, isFirst); isFirst = false; } // Create join lambda expressions PropertyInfo outerKeyPropertyInfo = this.KeyPropertyInfo; LambdaExpression outerKeySelectorExpression = Expression.Lambda(Expression.Property(outerParameterExpression, outerKeyPropertyInfo), outerParameterExpression); ParameterExpression innerKeySelectorParameterExpression = Expression.Parameter(this.JoinInnerKeyReferencePropertyInfo.PropertyType, "innerKeyParam"); LambdaExpression innerKeySelectorExpression = Expression.Lambda(innerKeySelectorParameterExpression, innerKeySelectorParameterExpression); ParameterExpression parameterExpression1 = Expression.Parameter(this.InterfaceType, "param1"); ParameterExpression parameterExpression2 = Expression.Parameter(outerKeyPropertyInfo.PropertyType, "param2"); LambdaExpression resultSelector = Expression.Lambda(parameterExpression1, parameterExpression1, parameterExpression2); Expression joinExpression = ExpressionHelper.CreateJoinExpression(outerResultExpression, innerDistinctExpression, outerKeySelectorExpression, innerKeySelectorExpression, resultSelector); return joinExpression; } private static Expression CreateInnerExpression(TreeNodeDynamicContext dynamicContext, ParentIdFilterNode parentIdFilterNode, DataElementsTreeNode dataElementsTreeNode, bool includeJoin = true) { Type interfaceType = dataElementsTreeNode.CurrentDataInterfaceType; ParameterExpression parameterExpression = Expression.Parameter(interfaceType, "innerData"); List filtersToSkip = new List() { parentIdFilterNode.Id }; foreach (ParentIdFilterNode childParentIdFilterNode in dataElementsTreeNode.FilterNodes.OfType().Where(f => f.Id != parentIdFilterNode.Id)) { if (childParentIdFilterNode.ParentFilterTypeTreeNode.IsAncestor(parentIdFilterNode.ParentFilterTypeTreeNode)) { filtersToSkip.Add(childParentIdFilterNode.Id); } } Expression filterExpression = dataElementsTreeNode.CreateAccumulatedFilterExpression(parameterExpression, interfaceType, dynamicContext, filtersToSkip); Expression whereExpression = ExpressionHelper.CreateWhereExpression(DataFacade.GetData(interfaceType).Expression, parameterExpression, filterExpression); if ((includeJoin) && (dataElementsTreeNode.JoinDataElementsTreeNode != null)) { //MRJ: Multiple Parent Filter: Recursive call, so we would have to make multiple recursive calls Expression innerInnerExpression = CreateInnerExpression(dynamicContext, dataElementsTreeNode.JoinParentIdFilterNode, dataElementsTreeNode.JoinDataElementsTreeNode); // Create join lambda expressions PropertyInfo outerKeyPropertyInfo = dataElementsTreeNode.KeyPropertyInfo; LambdaExpression outerKeySelectorExpression = Expression.Lambda(Expression.Property(parameterExpression, outerKeyPropertyInfo), parameterExpression); Type innerKeyType = TypeHelpers.FindElementType(innerInnerExpression); ParameterExpression innerKeySelectorParameterExpression = Expression.Parameter(innerKeyType, "innerKeyParam"); LambdaExpression innerKeySelectorExpression = Expression.Lambda(innerKeySelectorParameterExpression, innerKeySelectorParameterExpression); ParameterExpression parameterExpression1 = Expression.Parameter(dataElementsTreeNode.CurrentDataInterfaceType, "param1"); ParameterExpression parameterExpression2 = Expression.Parameter(outerKeyPropertyInfo.PropertyType, "param2"); LambdaExpression resultSelector = Expression.Lambda(parameterExpression1, parameterExpression1, parameterExpression2); Expression joinExpression = ExpressionHelper.CreateJoinExpression( whereExpression, innerInnerExpression, outerKeySelectorExpression, innerKeySelectorExpression, resultSelector); whereExpression = joinExpression; } Expression selectExpression = ExpressionHelper.CreateSelectExpression(whereExpression, ExpressionHelper.CreatePropertyExpression(parentIdFilterNode.ReferenceFieldName, parameterExpression), parameterExpression); Expression distinctExpression = ExpressionHelper.CreateDistinctExpression(selectExpression); return distinctExpression; } private IData GetParentDataItem(Type parentType, EntityToken parentEntityToken, TreeNodeDynamicContext dynamicContext) { if (dynamicContext.CustomData.ContainsKey("ParentData")) { return (IData)dynamicContext.CustomData["ParentData"]; } IData parentDataItem = null; if (parentEntityToken is DataEntityToken) { DataEntityToken dataEntityToken = parentEntityToken as DataEntityToken; Type type = dataEntityToken.InterfaceType; if (type == parentType) { return dataEntityToken.Data; } } if (parentDataItem == null) { foreach (EntityToken entityToken in dynamicContext.Piggybag.GetParentEntityTokens()) { DataEntityToken dataEntityToken = entityToken as DataEntityToken; if (dataEntityToken == null) continue; Type type = dataEntityToken.InterfaceType; if (type != parentType) continue; return dataEntityToken.Data; } } throw new InvalidOperationException(); } /// public override string ToString() { return string.Format("DataElementsTreeNode, Id = {0}, DataType = {1}, Display = {2}, {3}", this.Id, this.InterfaceType, this.Display, this.ParentString()); } private sealed class ParentFilterHelper { public ParentIdFilterNode ParentIdFilterNode { get; set; } public PropertyInfo ParentReferencedPropertyInfo { get; set; } public string ParentRefereePropertyName { get; set; } } } } ================================================ FILE: Composite/C1Console/Trees/DataFieldValueHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Web; using Composite.Data; using Composite.Core.Types; using Composite.C1Console.Trees.Foundation.AttachmentPoints; namespace Composite.C1Console.Trees { internal sealed class DataFieldValueHelper { private const string PreFix = "${C1:Data:"; private static Regex TemplateRegex = new Regex(@"\$\{(?[^\}]+)}", RegexOptions.Compiled); private List _entries = new List(); public string Template { get; private set; } public DataFieldValueHelper(string template) { this.Template = template; } public static bool ContainsDataField(string value) { return value.Contains(PreFix); } public IEnumerable InterfaceTypes { get { return _entries.Select(e => e.InterfaceType);} } public string ReplaceValues(string currentValue, PiggybagDataFinder piggybagDataFinder, IData currentDataItem = null, bool useUrlEncode = false) { string result = currentValue; foreach (DataFieldValueHelperEntry entry in _entries) { IData data = piggybagDataFinder.GetData(entry.InterfaceType, currentDataItem); object value; if (entry.IsReference == false) { value = entry.PropertyInfo.GetValue(data, null); if (value == null) { value = "(NULL)"; } else if (entry.PropertyInfo.PropertyType == typeof(DateTime)) { value = ((DateTime)value).ToString(entry.Format ?? "yyyy MM dd"); } else if (entry.PropertyInfo.PropertyType == typeof(Decimal)) { value = ((Decimal)value).ToString(entry.Format ?? "G"); } else if (entry.PropertyInfo.PropertyType == typeof(int)) { value = ((int)value).ToString(entry.Format ?? "G"); } } else { IData referencedData = data.GetReferenced(entry.PropertyInfo.Name); value = referencedData.GetLabel(); } string stringValue = value.ToString(); if (useUrlEncode) { stringValue = HttpUtility.UrlEncode(stringValue); } result = result.Replace(entry.Match, stringValue); } return result; } /// /// /// /// This is only used to add validation errors public void Initialize(TreeNode ownerTreeNode) { foreach (Match match in TemplateRegex.Matches(this.Template)) { if (match.Value.StartsWith(PreFix) == false) continue; string value = match.Groups["string"].Value; string[] values = value.Split(':'); if (values.Length != 4 && values.Length != 5) { ownerTreeNode.AddValidationError("TreeValidationError.DataFieldValueHelper.WrongFormat", match.Value, string.Format(@"{0}[InterfaceType]:[FieldName]}}", PreFix), string.Format(@"{0}[InterfaceType]:[FieldName]:[Format]}}", PreFix)); return; } string typeName = values[2]; Type interfaceType = TypeManager.TryGetType(typeName); if (interfaceType == null) { ownerTreeNode.AddValidationError("TreeValidationError.Common.UnknownInterfaceType", typeName); return; } if (typeof(IData).IsAssignableFrom(interfaceType) == false) { ownerTreeNode.AddValidationError("TreeValidationError.Common.NotImplementingIData", interfaceType, typeof(IData)); return; } string fieldName = values[3]; PropertyInfo propertyInfo = interfaceType.GetPropertiesRecursively(f => f.Name == fieldName).SingleOrDefault(); if (propertyInfo == null) { ownerTreeNode.AddValidationError("TreeValidationError.Common.MissingProperty", interfaceType, fieldName); return; } bool possibleAttachmentPointsExist = ownerTreeNode.Tree.PossibleAttachmentPoints.OfType().Any(f => f.InterfaceType == interfaceType); bool attachmentPointsExist = ownerTreeNode.Tree.AttachmentPoints.OfType().Any(f => f.InterfaceType == interfaceType); if (!possibleAttachmentPointsExist && !attachmentPointsExist && !ownerTreeNode.SelfAndParentsHasInterface(interfaceType)) { ownerTreeNode.AddValidationError("TreeValidationError.DataFieldValueHelper.InterfaceNotInParentTree", interfaceType); return; } string format = (values.Length == 5 ? values[4] : null); bool isReferencingProperty = DataReferenceFacade.GetForeignKeyProperties(interfaceType).Any(f => f.SourcePropertyInfo.Equals(propertyInfo)); DataFieldValueHelperEntry entry = new DataFieldValueHelperEntry( match.Value, interfaceType, propertyInfo, format, isReferencingProperty ); if (_entries.Contains(entry) == false) { _entries.Add(entry); } } } private sealed class DataFieldValueHelperEntry { public DataFieldValueHelperEntry(string match, Type interfaceType, PropertyInfo propertyInfo, string format, bool isReference) { this.Match = match; this.InterfaceType = interfaceType; this.PropertyInfo = propertyInfo; this.Format = format; this.IsReference = isReference; } public string Match { get; private set; } public Type InterfaceType { get; private set; } public PropertyInfo PropertyInfo { get; private set; } public string Format { get; private set; } public bool IsReference { get; private set; } public override bool Equals(object obj) { return Equals(obj as DataFieldValueHelperEntry); } public bool Equals(DataFieldValueHelperEntry entry) { return entry != null && object.Equals(this.Match, entry.Match); } public override int GetHashCode() { return this.Match.GetHashCode(); } } } } ================================================ FILE: Composite/C1Console/Trees/DataFilteringTreeNode.cs ================================================ using System; using System.Linq; using System.Linq.Expressions; using Composite.Core.Linq; using System.Collections.Generic; namespace Composite.C1Console.Trees { /// /// Tree node that shows filtered data items, or items generated from them (f.e. data grouping elements) /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class DataFilteringTreeNode : TreeNode { internal abstract Type CurrentDataInterfaceType { get; } /// /// Depending on dynamicContext's Direction creates either filter expression for finding child elements or /// a filter expression to find current element based on children elements /// /// The parameter expression. /// The dynamic context. /// The filters to skip. /// internal virtual Expression CreateFilterExpression(ParameterExpression parameterExpression, TreeNodeDynamicContext dynamicContext, IList filtersToSkip = null) { Expression expression = null; var filterNodes = dynamicContext.Direction == TreeNodeDynamicContextDirection.Down ? this.FilterNodes : dynamicContext.CurrentTreeNode.FilterNodes; foreach (FilterNode filterNode in filterNodes) { if (filtersToSkip != null && filtersToSkip.Contains(filterNode.Id)) continue; Expression filterExpression; if (dynamicContext.Direction == TreeNodeDynamicContextDirection.Down) { filterExpression = filterNode.CreateDownwardsFilterExpression(parameterExpression, dynamicContext); } else { filterExpression = filterNode.CreateUpwardsFilterExpression(parameterExpression, dynamicContext); } if (filterExpression == null) continue; expression = expression.NestedAnd(filterExpression); } return expression; } /// /// Creates the accumulated filter expression from current tree definition node, and all the nearest ancestor DataFolderElement-s that /// are related to the same data type. /// /// The parameter expression. /// Type of the affected interface. /// The dynamic context. /// The filters to skip. /// internal Expression CreateAccumulatedFilterExpression(ParameterExpression parameterExpression, Type affectedInterfaceType, TreeNodeDynamicContext dynamicContext, IList filtersToSkip = null) { TreeNode treeNode = this; Expression currentExpression = null; while (treeNode != null) { DataFilteringTreeNode dataFilteringTreeNode = treeNode as DataFilteringTreeNode; if (dataFilteringTreeNode != null && (dataFilteringTreeNode == this || dataFilteringTreeNode is DataFolderElementsTreeNode) && (dataFilteringTreeNode.CurrentDataInterfaceType == affectedInterfaceType)) { Expression filterExpression = dataFilteringTreeNode.CreateFilterExpression(parameterExpression, dynamicContext, filtersToSkip); if (filterExpression != null) { currentExpression = currentExpression.NestedAnd(filterExpression); } } else { break; } treeNode = treeNode.ParentNode; } //currentExpression.DebugLogExpression("DataFileringTreeNode", "Accumulated Filter Expression"); return currentExpression; } /// /// Creates the OrderBy expression. /// /// The source expression. /// The parameter expression. /// /// protected Expression CreateOrderByExpression(Expression sourceExpression, ParameterExpression parameterExpression) { Expression resultExpression = sourceExpression; bool isFirst = true; foreach (OrderByNode orderByNode in this.OrderByNodes) { resultExpression = orderByNode.CreateOrderByExpression(resultExpression, parameterExpression, isFirst); isFirst = false; } return resultExpression; } } } ================================================ FILE: Composite/C1Console/Trees/DataFolderElementsTreeNode.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Core.Extensions; using Composite.Data; using Composite.Data.ProcessControlled; using Composite.C1Console.Elements; using Composite.Core.Linq; using Composite.Core.ResourceSystem; using Composite.C1Console.Security; using Composite.C1Console.Trees.Foundation; using Composite.C1Console.Trees.Foundation.FolderRanges; using Composite.Core.Types; using Composite.C1Console.Users; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class DataFolderElementsTreeNode : DataFilteringTreeNode { private readonly MethodInfo StringStartsWithMethodInfo = typeof(string).GetMethods().First(f => f.Name == nameof(string.StartsWith)); private readonly MethodInfo StringSubstringMethodInfo = typeof(string).GetMethods().Where(f => f.Name == nameof(string.Substring)).Skip(1).First(); private readonly MethodInfo ToUpperCompareMethodInfo = typeof(string).GetMethods().First(f => f.Name == nameof(string.ToUpper)); /// public Type InterfaceType { get; internal set; } // Required /// public ResourceHandle Icon { get; internal set; } // Defaults to 'folder-disabled' /// public string FieldName { get; internal set; } // Required /// public string DateFormat { get; internal set; } // Optional /// public string Range { get; internal set; } // Optional /// public bool FirstLetterOnly { get; internal set; } // Optional /// public SortDirection SortDirection { get; internal set; } // Optional /// public LeafDisplayMode Display { get; internal set; } // Optional /// public bool ShowForeignItems { get; internal set; } // Optional // Cached values private PropertyInfo KeyPropertyInfo { get; set; } private string GroupingValuesFieldName { get; set; } private string SerializedInterfaceType { get; set; } private PropertyInfo PropertyInfo { get; set; } private DateTimeFormater DateTimeFormater { get; set; } private IFolderRanges FolderRanges { get; set; } private List AllGroupingNodes { get; set; } private ConstructorInfo AllGroupingsTupleConstructor { get; set; } private MethodInfo FolderIndexListAddMethodInfo { get; set; } private MethodInfo FolderIndexListClearMethodInfo { get; set; } private object FolderIndexListObject { get; set; } private IQueryable FolderIndexListQueryable { get; set; } /// /// True if parent element is not a /// private bool IsTopFolderParent { get; set; } private DataElementsTreeNode ChildGeneratingDataElementsTreeNode { get; set; } private ParentIdFilterNode ChildGeneratingParentIdFilterNode { get; set; } /// public override IEnumerable GetEntityTokens(EntityToken childEntityToken, TreeNodeDynamicContext dynamicContext) { IEnumerable labels = GetCurrentAndLocalizableObjects(dynamicContext, true); Type childGeneratingDataElementsReferenceType = null; object childGeneratingDataElementsReferenceValue = null; DataEntityToken dataEntityToken = childEntityToken as DataEntityToken; var treeDataFieldGroupingElementEntityToken = childEntityToken as TreeDataFieldGroupingElementEntityToken; if (dataEntityToken != null) { if (this.ChildGeneratingParentIdFilterNode != null) { childGeneratingDataElementsReferenceType = this.ChildGeneratingParentIdFilterNode.ParentFilterType; childGeneratingDataElementsReferenceValue = this.ChildGeneratingParentIdFilterNode.ReferencePropertyInfo.GetValue(dataEntityToken.Data, null); } } else if (treeDataFieldGroupingElementEntityToken != null) { childGeneratingDataElementsReferenceType = treeDataFieldGroupingElementEntityToken.ChildGeneratingDataElementsReferenceType; childGeneratingDataElementsReferenceValue = treeDataFieldGroupingElementEntityToken.ChildGeneratingDataElementsReferenceValue; } foreach (object label in labels) { var tupleIndexer = new TupleIndexer(label); var entityToken = new TreeDataFieldGroupingElementEntityToken(this.Id, this.Tree.TreeId, TypeManager.SerializeType(this.InterfaceType)) { GroupingValues = new Dictionary() }; int index = 1; foreach (DataFolderElementsTreeNode dataFolderElementsTreeNode in this.AllGroupingNodes) { if (dataFolderElementsTreeNode.FolderRanges == null) { object fieldValue = tupleIndexer.GetAtIndex(index++); fieldValue = ConvertFieldValue(dataFolderElementsTreeNode, fieldValue); entityToken.GroupingValues.Add(dataFolderElementsTreeNode.GroupingValuesFieldName, fieldValue); } else { int fieldValue = (int)tupleIndexer.GetAtIndex(index++); entityToken.FolderRangeValues.Add(dataFolderElementsTreeNode.FieldName, fieldValue); } } entityToken.ChildGeneratingDataElementsReferenceType = childGeneratingDataElementsReferenceType; entityToken.ChildGeneratingDataElementsReferenceValue = childGeneratingDataElementsReferenceValue; yield return entityToken; } } internal override Type CurrentDataInterfaceType => this.InterfaceType; /// public override AncestorResult GetParentEntityToken(EntityToken childEntityToken, Type parentInterfaceOfInterest, TreeNodeDynamicContext dynamicContext) { if (this.ParentNode is DataFolderElementsTreeNode) { var childGroupingElementEntityToken = childEntityToken as TreeDataFieldGroupingElementEntityToken; if (childGroupingElementEntityToken != null) { var newGroupingElementEntityToken = new TreeDataFieldGroupingElementEntityToken( this.ParentNode.Id, this.Tree.TreeId, this.SerializedInterfaceType) { GroupingValues = new Dictionary(childGroupingElementEntityToken.GroupingValues), FolderRangeValues = new Dictionary(childGroupingElementEntityToken.FolderRangeValues) }; newGroupingElementEntityToken.GroupingValues.Remove(this.GroupingValuesFieldName); return new AncestorResult(this.ParentNode, newGroupingElementEntityToken); } } throw new NotImplementedException(); } /// protected override IEnumerable OnGetElements(EntityToken parentEntityToken, TreeNodeDynamicContext dynamicContext) { Type referenceType = null; object referenceValue = null; if (this.ChildGeneratingParentIdFilterNode != null) { if (this.IsTopFolderParent) { var dataEntityToken = dynamicContext.Piggybag .GetParentEntityTokens(parentEntityToken) .OfType() .FirstOrDefault(f => f.InterfaceType == ChildGeneratingParentIdFilterNode.ParentFilterType); if (dataEntityToken != null) { var data = dataEntityToken.Data; if (data == null) return Enumerable.Empty(); referenceType = this.ChildGeneratingParentIdFilterNode.KeyPropertyInfo.DeclaringType; referenceValue = this.ChildGeneratingParentIdFilterNode.KeyPropertyInfo.GetValue(data, null); } } else { var treeDataFieldGroupingElementEntityToken = parentEntityToken as TreeDataFieldGroupingElementEntityToken; referenceType = treeDataFieldGroupingElementEntityToken.ChildGeneratingDataElementsReferenceType; referenceValue = treeDataFieldGroupingElementEntityToken.ChildGeneratingDataElementsReferenceValue; } } if (this.FolderRanges != null) { return CreateFolderRangeElements(parentEntityToken, referenceType, referenceValue, dynamicContext); } IEnumerable objects = GetCurrentAndLocalizableObjects(dynamicContext); if (this.FirstLetterOnly) { return CreateFirstLetterOnlyElements(parentEntityToken, referenceType, referenceValue, dynamicContext, objects); } return CreateSimpleElements(parentEntityToken, referenceType, referenceValue, dynamicContext, objects); } private IEnumerable CreateSimpleElements(EntityToken parentEntityToken, Type referenceType, object referenceValue, TreeNodeDynamicContext dynamicContext, IEnumerable objects) { bool shouldBeSortedByLabel; Func labelFunc = GetLabelFunction(out shouldBeSortedByLabel); if (shouldBeSortedByLabel) { objects = objects.Evaluate(); } var objectsAndLabels = objects.Select(o => new { Object = o, Label = labelFunc(o)}); if (shouldBeSortedByLabel) { objectsAndLabels = this.SortDirection == SortDirection.Ascending ? objectsAndLabels.OrderBy(a => a.Label) : objectsAndLabels.OrderByDescending(a => a.Label); } foreach (var pair in objectsAndLabels) { yield return CreateElement( parentEntityToken, referenceType, referenceValue, dynamicContext, pair.Label, f => f.GroupingValues.Add(this.GroupingValuesFieldName, ConvertGroupingValue(pair.Object)) ); } } private object ConvertGroupingValue(object value) { return this.DateTimeFormater.IsDateTimeGroupingValue(value) ? this.DateTimeFormater.Serialize(value) : value; } private Func GetLabelFunction(out bool shouldBeSortedByLabel) { if (this.PropertyInfo.PropertyType == typeof(DateTime)) { shouldBeSortedByLabel = false; return f => this.DateTimeFormater.FormatLabel(f); } var referenceProperties = DataAttributeFacade.GetDataReferenceProperties(PropertyInfo.DeclaringType); var referenceInfo = referenceProperties.FirstOrDefault(p => p.SourcePropertyName == this.PropertyInfo.Name); if (referenceInfo == null) { shouldBeSortedByLabel = false; return f => (f ?? "(NULL)").ToString(); } shouldBeSortedByLabel = true; return key => { if (key == null) return "(NULL)"; IData reference = DataFacade.TryGetDataVersionsByUniqueKey(referenceInfo.TargetType, key).FirstOrDefault(); return reference?.GetLabel() ?? key.ToString(); }; } private IEnumerable CreateFolderRangeElements(EntityToken parentEntityToken, Type referenceType, object referenceValue, TreeNodeDynamicContext dynamicContext) { var indexes = Enumerable.Empty(); if (this.Display != LeafDisplayMode.Lazy) { indexes = GetCurrentAndLocalizableObjects(dynamicContext); } foreach (IFolderRange folderRange in this.FolderRanges.Ranges) { bool contained = indexes.Contains(folderRange.Index); if (this.Display == LeafDisplayMode.Compact && !contained) continue; Element element = CreateElement( parentEntityToken, referenceType, referenceValue, dynamicContext, folderRange.Label, f => { f.FolderRangeValues.Add(this.FieldName, folderRange.Index); } ); if (this.Display == LeafDisplayMode.Auto) { element.VisualData.HasChildren = contained; } yield return element; } } private IEnumerable CreateFirstLetterOnlyElements(EntityToken parentEntityToken, Type referenceType, object referenceValue, TreeNodeDynamicContext dynamicContext, IEnumerable objects) { foreach (string label in objects.OfType()) { yield return CreateElement( parentEntityToken, referenceType, referenceValue, dynamicContext, label, f => f.GroupingValues.Add(this.GroupingValuesFieldName, label) ); } } private Element CreateElement(EntityToken parentEntityToken, Type referenceType, object referenceValue, TreeNodeDynamicContext dynamicContext, string label, Action entityTokenAction) { var entityToken = new TreeDataFieldGroupingElementEntityToken(this.Id.ToString(), this.Tree.TreeId, this.SerializedInterfaceType) { GroupingValues = new Dictionary(dynamicContext.FieldGroupingValues), FolderRangeValues = new Dictionary(dynamicContext.FieldFolderRangeValues), ChildGeneratingDataElementsReferenceType = referenceType, ChildGeneratingDataElementsReferenceValue = referenceValue }; entityTokenAction(entityToken); var element = new Element(new ElementHandle( dynamicContext.ElementProviderName, entityToken, dynamicContext.Piggybag.PreparePiggybag(this.ParentNode, parentEntityToken) )) { VisualData = new ElementVisualizedData { Label = label, ToolTip = label, HasChildren = true, Icon = this.Icon, OpenedIcon = this.Icon } }; element.ElementExternalActionAdding = element.ElementExternalActionAdding.Remove(ElementExternalActionAdding.AllowManageUserPermissions); return element; } private Expression CreateSelectBodyExpression(ParameterExpression parameterExpression, Expression fieldExpression, out List orderByExpressions) { orderByExpressions = null; if (this.FolderRanges != null) { return this.FolderRanges.CreateContainsListSelectBodyExpression(fieldExpression, parameterExpression); } if (this.PropertyInfo.PropertyType == typeof(DateTime)) { var parameters = new List(); if (this.DateTimeFormater.HasYear) parameters.Add(Expression.Property(fieldExpression, DateTimeFormater.DateTime_Year)); if (this.DateTimeFormater.HasMonth) parameters.Add(Expression.Property(fieldExpression, DateTimeFormater.DateTime_Month)); if (this.DateTimeFormater.HasDay) parameters.Add(Expression.Property(fieldExpression, DateTimeFormater.DateTime_Day)); if (this.DateTimeFormater.HasHour) parameters.Add(Expression.Property(fieldExpression, DateTimeFormater.DateTime_Hour)); if (this.DateTimeFormater.HasMinute) parameters.Add(Expression.Property(fieldExpression, DateTimeFormater.DateTime_Minute)); if (this.DateTimeFormater.HasSecond) parameters.Add(Expression.Property(fieldExpression, DateTimeFormater.DateTime_Second)); var members = this.DateTimeFormater.GetTupleMembers(); Expression expression = Expression.New(this.DateTimeFormater.GetTupleConstructor(), parameters, members); if (parameters.Any()) { orderByExpressions = new List(); // Ordering my date parts. Needed for LINQ2SQL to produce a correct query for (int i = 0; i < parameters.Count; i++) { var newParameter = Expression.Parameter(expression.Type); var newTypeProperty = Expression.Property(newParameter, members[i]); var keySelector = Expression.Lambda(newTypeProperty, newParameter); orderByExpressions.Add(keySelector); } } return expression; } if (this.FirstLetterOnly) { Expression expression = Expression.Condition( Expression.And( Expression.NotEqual( fieldExpression, Expression.Constant(null) ), Expression.NotEqual( fieldExpression, Expression.Constant("") ) ), Expression.Call( Expression.Call( fieldExpression, this.StringSubstringMethodInfo, Expression.Constant(0), Expression.Constant(1) ), this.ToUpperCompareMethodInfo ), fieldExpression, typeof(string) ); return expression; } return fieldExpression; } private Expression GetObjectsExpression(TreeNodeDynamicContext dynamicContext, bool includeAllGroupingFields = false) { ParameterExpression parameterExpression = Expression.Parameter(this.InterfaceType, "data"); Expression filterExpression = CreateAccumulatedFilterExpression(parameterExpression, this.InterfaceType, dynamicContext); Expression whereExpression = ExpressionHelper.CreateWhereExpression(DataFacade.GetData(this.InterfaceType).Expression, parameterExpression, filterExpression); Expression fieldExpression = ExpressionHelper.CreatePropertyExpression(this.InterfaceType, this.PropertyInfo.DeclaringType, this.FieldName, parameterExpression); var keySelector = Expression.Lambda(fieldExpression, parameterExpression); Expression orderByExpression = this.SortDirection == SortDirection.Ascending ? ExpressionHelper.CreateOrderByExpression(whereExpression, keySelector) : ExpressionHelper.CreateOrderByDescendingExpression(whereExpression, keySelector); Expression selectBodyExpression; List orderByExpressions = null; if (!includeAllGroupingFields) { selectBodyExpression = CreateSelectBodyExpression(parameterExpression, fieldExpression, out orderByExpressions); } else { List bodyExpressions = new List(); foreach (DataFolderElementsTreeNode dataFolderElementsTreeNode in this.AllGroupingNodes) { List innerOrderByExpressions; Expression groupFieldExpression = ExpressionHelper.CreatePropertyExpression(dataFolderElementsTreeNode.InterfaceType, dataFolderElementsTreeNode.PropertyInfo.DeclaringType, dataFolderElementsTreeNode.FieldName, parameterExpression); Expression bodyExpression = dataFolderElementsTreeNode.CreateSelectBodyExpression(parameterExpression, groupFieldExpression, out innerOrderByExpressions); bodyExpressions.Add(bodyExpression); } selectBodyExpression = Expression.New(this.AllGroupingsTupleConstructor, bodyExpressions); // TODO: proper processing of innerOrderByExpressions } Expression selectExpression = ExpressionHelper.CreateSelectExpression( orderByExpression, selectBodyExpression, parameterExpression); Expression distinctExpression = ExpressionHelper.CreateDistinctExpression(selectExpression); // Sorting after calling "DISTINCT" to fix LINQ2SQL issue. No need to sort while resolving security if (orderByExpressions != null && dynamicContext.Direction == TreeNodeDynamicContextDirection.Down) { distinctExpression = ApplyOrder(distinctExpression, orderByExpressions); } return distinctExpression; } private Expression ApplyOrder(Expression expression, List fieldSelectors) { for (int i = 0; i < fieldSelectors.Count; i++) { if (i == 0) { expression = this.SortDirection == SortDirection.Ascending ? ExpressionHelper.CreateOrderByExpression(expression, fieldSelectors[i]) : ExpressionHelper.CreateOrderByDescendingExpression(expression,fieldSelectors[i]); } else { expression = this.SortDirection == SortDirection.Ascending ? ExpressionHelper.ThenByExpression(expression, fieldSelectors[i]) : ExpressionHelper.ThenByDescendingExpression(expression, fieldSelectors[i]); } } return expression; } private List GetObjects(TreeNodeDynamicContext dynamicContext, bool includeAllGroupingFields = false) { var expression = GetObjectsExpression(dynamicContext, includeAllGroupingFields); return ExpressionHelper.GetCastedObjects(this.InterfaceType, expression); } private IEnumerable GetCurrentAndLocalizableObjects(TreeNodeDynamicContext dynamicContext, bool includeAllGroupingFields = false) { IEnumerable objects = GetObjects(dynamicContext, includeAllGroupingFields); if (!this.LocalizationEnabled) return objects; using (new DataScope(UserSettings.ForeignLocaleCultureInfo)) { var foreignObjects = GetObjects(dynamicContext, includeAllGroupingFields); return objects.Concat(foreignObjects).Distinct(); } } private bool UseChildGeneratingFilterExpression => IsTopFolderParent && Display != LeafDisplayMode.Lazy; internal override Expression CreateFilterExpression(ParameterExpression parameterExpression, TreeNodeDynamicContext dynamicContext, IList filtersToSkip = null) { var dataEntityToken = dynamicContext.CurrentEntityToken as DataEntityToken; var treeSimpleElementEntityToken = dynamicContext.CurrentEntityToken as TreeSimpleElementEntityToken; Expression fieldExpression = ExpressionHelper.CreatePropertyExpression(this.InterfaceType, this.PropertyInfo.DeclaringType, this.FieldName, parameterExpression); object value; Func resultFilterExpressionFactory = () => this.UseChildGeneratingFilterExpression ? this.ChildGeneratingDataElementsTreeNode.CreateFilterExpression(parameterExpression, dynamicContext) : null; if (this.FolderRanges == null) { if (dynamicContext.FieldGroupingValues.ContainsKey(this.GroupingValuesFieldName)) { value = dynamicContext.FieldGroupingValues[this.GroupingValuesFieldName]; } else if (dataEntityToken != null) { if (CreateFilterExpression_GetValueFromDataEntityToken(dataEntityToken, out value) == false) { return resultFilterExpressionFactory(); } } else if (treeSimpleElementEntityToken != null && treeSimpleElementEntityToken.ParentEntityToken is DataEntityToken) { var parentDataEntityToken = treeSimpleElementEntityToken.ParentEntityToken as DataEntityToken; if (CreateFilterExpression_GetValueFromDataEntityToken(parentDataEntityToken, out value) == false) { return resultFilterExpressionFactory(); } } else if (dynamicContext.Direction == TreeNodeDynamicContextDirection.Down) { // We shall not create filter for our self when unfolding return resultFilterExpressionFactory(); } else if (dynamicContext.Direction == TreeNodeDynamicContextDirection.Up) { // At this point we are going upwards, building the filter and one or // more of the parent elements has not been opened, so we are not able to // create a filter. // This will happen if a parent filter is below us return null; } else { // This will only happen if we are searching up and are given another entity token that // TreeDataFieldGroupingElementEntityToken and DataEntityToken or TreeSimpleElementEntityToken throw new NotImplementedException($"Unsupported child entity token type '{dynamicContext.CurrentEntityToken.GetType()}'"); } } else { if (dynamicContext.FieldFolderRangeValues.ContainsKey(this.FieldName)) { value = dynamicContext.FieldFolderRangeValues[this.FieldName]; } else if (dataEntityToken != null) { if (CreateFilterExpression_GetFolderIndexFromDataEntityToken(dataEntityToken, parameterExpression, fieldExpression, out value) == false) { return resultFilterExpressionFactory(); } } else if (treeSimpleElementEntityToken != null && treeSimpleElementEntityToken.ParentEntityToken is DataEntityToken) { DataEntityToken parentDataEntityToken = treeSimpleElementEntityToken.ParentEntityToken as DataEntityToken; if (CreateFilterExpression_GetFolderIndexFromDataEntityToken(parentDataEntityToken, parameterExpression, fieldExpression, out value) == false) { return resultFilterExpressionFactory(); } } else if (dynamicContext.Direction == TreeNodeDynamicContextDirection.Down) { // We shall not create filter for our self when unfolding return resultFilterExpressionFactory(); } else if (dynamicContext.Direction == TreeNodeDynamicContextDirection.Up) { // At this point we are going upwards, building the filter and one or // more of the parent elements has not been opened, so we are not able to // create a filter. // This will happen if a parent filter is below us return null; } else { // This will only happen if we are searching up and are given another entity token that // TreeDataFieldGroupingElementEntityToken and DataEntityToken or TreeSimpleElementEntityToken throw new NotImplementedException($"Unsupported child entity token type '{dynamicContext.CurrentEntityToken.GetType()}'"); } } Expression filterExpression; if (this.FolderRanges != null) { int folderRangeIndex = (int)value; filterExpression = CreateFolderRangeFilterExpression(folderRangeIndex, fieldExpression); } else if (this.FirstLetterOnly) { filterExpression = CreateFirstLetterOnlyFilterExpression(value, fieldExpression); } else { filterExpression = CreateSimpleFilterExpression(value, fieldExpression); } if (dynamicContext.Direction == TreeNodeDynamicContextDirection.Down) { if (this.UseChildGeneratingFilterExpression) { Expression childFilerExpression = this.ChildGeneratingDataElementsTreeNode.CreateFilterExpression(parameterExpression, dynamicContext); filterExpression = filterExpression.NestedAnd(childFilerExpression); } } return filterExpression; } private bool CreateFilterExpression_GetValueFromDataEntityToken(DataEntityToken dataEntityToken, out object value) { if (dataEntityToken.InterfaceType != this.InterfaceType) { // If we don't have the grouping/folderrange value from entity token and don't have the // right data item to get the value, we are not able to create a filter. value = null; return false; } IData data = dataEntityToken.Data; value = this.PropertyInfo.GetValue(data, null); value = ConvertFieldValue(this, value); return true; } private bool CreateFilterExpression_GetFolderIndexFromDataEntityToken(DataEntityToken dataEntityToken, ParameterExpression parameterExpression, Expression fieldExpression, out object value) { if (dataEntityToken.InterfaceType != this.InterfaceType) { // If we don't have the foler range value from entity token and don't have the // right data item to get the value, we are not able to create a filter. value = null; return false; } this.FolderIndexListClearMethodInfo.Invoke(this.FolderIndexListObject, null); this.FolderIndexListAddMethodInfo.Invoke(this.FolderIndexListObject, new object[] { dataEntityToken.Data }); Expression selectBodyExpression = this.FolderRanges.CreateContainsListSelectBodyExpression(fieldExpression, parameterExpression); Expression selectExpression = ExpressionHelper.CreateSelectExpression(this.FolderIndexListQueryable.Expression, selectBodyExpression, parameterExpression); value = this.FolderIndexListQueryable.Provider.CreateQuery(selectExpression).ToEnumerableOfObjects().Single(); return true; } private Expression CreateSimpleFilterExpression(object value, Expression fieldExpression) { Type propertyType = this.PropertyInfo.PropertyType; if (propertyType == typeof (DateTime) || propertyType == typeof (DateTime?)) { return CreateFilterByDateTimeExpression(value, fieldExpression); } if (value != null && !propertyType.IsInstanceOfType(value)) { Exception ex; value = ValueTypeConverter.TryConvert(value, propertyType, out ex); if (ex != null) { throw new InvalidOperationException($"Failed to convent a filtering value to type '{propertyType}'"); } } return Expression.Equal(fieldExpression, Expression.Constant(value, propertyType)); } private Expression CreateFilterByDateTimeExpression(object value, Expression fieldExpression) { DateTime dateTime = DateTimeFormater.Deserialize(value.ToString()); if (this.DateFormat == null) { return Expression.Equal(fieldExpression, Expression.Constant(dateTime)); } Expression currentExpression = null; if (this.DateTimeFormater.HasYear) currentExpression = AddEqualsExpression(fieldExpression, currentExpression, DateTimeFormater.DateTime_Year, dateTime.Year); if (this.DateTimeFormater.HasMonth) currentExpression = AddEqualsExpression(fieldExpression, currentExpression, DateTimeFormater.DateTime_Month, dateTime.Month); if (this.DateTimeFormater.HasDay) currentExpression = AddEqualsExpression(fieldExpression, currentExpression, DateTimeFormater.DateTime_Day, dateTime.Day); if (this.DateTimeFormater.HasHour) currentExpression = AddEqualsExpression(fieldExpression, currentExpression, DateTimeFormater.DateTime_Hour, dateTime.Hour); if (this.DateTimeFormater.HasMinute) currentExpression = AddEqualsExpression(fieldExpression, currentExpression, DateTimeFormater.DateTime_Minute, dateTime.Minute); if (this.DateTimeFormater.HasSecond) currentExpression = AddEqualsExpression(fieldExpression, currentExpression, DateTimeFormater.DateTime_Second, dateTime.Second); return currentExpression; } private Expression CreateFolderRangeFilterExpression(int folderRangeIndex, Expression fieldExpression) { Expression filterExpression = this.FolderRanges.CreateFilterExpression(folderRangeIndex, fieldExpression); return filterExpression; } private Expression CreateFirstLetterOnlyFilterExpression(object value, Expression fieldExpression) { string castedValue = (string)value; if (castedValue == "") { return Expression.Equal(fieldExpression, Expression.Constant("")); } return Expression.Condition( Expression.NotEqual( fieldExpression, Expression.Constant(null) ), Expression.Call( Expression.Call( fieldExpression, this.ToUpperCompareMethodInfo ), this.StringStartsWithMethodInfo, Expression.Constant(castedValue.ToUpperInvariant()) ), Expression.Constant(false) ); } private Expression AddEqualsExpression(Expression fieldExpression, Expression currentExpression, PropertyInfo propertyInfo, int value) { return currentExpression.NestedAnd( Expression.Equal( Expression.Property(fieldExpression, propertyInfo), Expression.Constant(value) ) ); } private static object ConvertFieldValue(DataFolderElementsTreeNode dataFolderElementsTreeNode, object fieldValue) { if (dataFolderElementsTreeNode.FirstLetterOnly) { string stringFieldValue = (string)fieldValue; return stringFieldValue.IsNullOrEmpty() ? "" : stringFieldValue.Substring(0, 1); } if (dataFolderElementsTreeNode.DateFormat != null) { if (fieldValue is DateTime) { return dataFolderElementsTreeNode.DateTimeFormater.SerializeDateTime((DateTime)fieldValue); } dataFolderElementsTreeNode.DateTimeFormater.GetDateTime(fieldValue); return dataFolderElementsTreeNode.DateTimeFormater.Serialize(fieldValue); } return fieldValue; } /// protected override void OnInitialize() { var parentNode = this.ParentNode as DataFolderElementsTreeNode; if (this.InterfaceType == null) { if (parentNode == null) { AddValidationError("TreeValidationError.DataFolderElements.MissingInterfaceType"); return; } this.InterfaceType = parentNode.InterfaceType; } else { if (!typeof(IData).IsAssignableFrom(this.InterfaceType)) { AddValidationError("TreeValidationError.Common.NotImplementingIData", this.InterfaceType, typeof(IData)); return; } if (parentNode != null && parentNode.InterfaceType != this.InterfaceType) { AddValidationError("TreeValidationError.DataFolderElements.WrongInterfaceType", this.InterfaceType, parentNode.InterfaceType); return; } } this.PropertyInfo = this.InterfaceType.GetPropertiesRecursively().SingleOrDefault(f => f.Name == this.FieldName); if (this.PropertyInfo == null) { AddValidationError("TreeValidationError.Common.MissingProperty", this.InterfaceType, this.FieldName); return; } if (this.DateFormat != null && this.PropertyInfo.PropertyType != typeof(DateTime)) { AddValidationError("TreeValidationError.DataFolderElements.DateFormetNotAllowed", this.FieldName, typeof(DateTime), this.PropertyInfo.PropertyType); } if (this.PropertyInfo.PropertyType == typeof(DateTime) && this.DateFormat == null) { AddValidationError("TreeValidationError.DataFolderElements.DateFormetIsMissing", this.FieldName); return; } this.DateTimeFormater = new DateTimeFormater(this.DateFormat); if (!string.IsNullOrEmpty(this.Range) && this.FirstLetterOnly) { AddValidationError("TreeValidationError.DataFolderElements.RangesAndFirstLetterOnlyNotAllowed"); } if (this.FirstLetterOnly && this.PropertyInfo.PropertyType != typeof(string)) { AddValidationError("TreeValidationError.DataFolderElements.WrongFirstLetterOnlyPropertyType", this.FieldName, typeof(string), this.PropertyInfo.PropertyType); } if (!string.IsNullOrEmpty(this.Range)) { this.FolderRanges = FolderRangesCreator.Create(this, this.Range, this.FieldName, this.PropertyInfo.PropertyType); } if (this.ChildNodes.OfType().Any(f => f.InterfaceType != this.InterfaceType)) { AddValidationError("TreeValidationError.DataFolderElements.WrongDateChildInterfaceType", this.InterfaceType); } this.SerializedInterfaceType = TypeManager.SerializeType(this.InterfaceType); this.AllGroupingNodes = new List(); var usedPropertyNames = new List(); var fieldTypes = new List(); DataFolderElementsTreeNode treeNode = this; int dataFolderElementCount = 0; while (treeNode != null) { dataFolderElementCount++; if (treeNode.InterfaceType != this.InterfaceType) { AddValidationError("TreeValidationError.DataFolderElements.InterfaceTypeSwitchNotAllowed", treeNode.InterfaceType, this.InterfaceType); break; } if (treeNode.PropertyInfo.PropertyType != typeof(DateTime)) { if (usedPropertyNames.Contains(treeNode.FieldName)) { AddValidationError("TreeValidationError.DataFolderElements.SameFieldUsedTwice", treeNode.FieldName); break; } usedPropertyNames.Add(treeNode.FieldName); } this.AllGroupingNodes.Add(treeNode); if (treeNode.FolderRanges != null) { fieldTypes.Add(typeof(int)); } else if (treeNode.PropertyInfo.PropertyType == typeof(DateTime)) { fieldTypes.Add(treeNode.DateTimeFormater.GetTupleConstructor().DeclaringType); } else { fieldTypes.Add(treeNode.PropertyInfo.PropertyType); } treeNode = treeNode.ParentNode as DataFolderElementsTreeNode; } Type type = GetTupleType(this.AllGroupingNodes.Count); type = type.MakeGenericType(fieldTypes.ToArray()); this.AllGroupingsTupleConstructor = type.GetConstructors().Single(); Type listType = typeof(List<>).MakeGenericType(this.InterfaceType); this.FolderIndexListAddMethodInfo = listType.GetMethods().Single(f => f.Name == "Add"); this.FolderIndexListClearMethodInfo = listType.GetMethods().Single(f => f.Name == "Clear"); this.FolderIndexListObject = Activator.CreateInstance(listType); this.FolderIndexListQueryable = ((IEnumerable)this.FolderIndexListObject).AsQueryable(); if (this.FieldName == null) { this.GroupingValuesFieldName = this.FieldName; } else { this.GroupingValuesFieldName = $"■{this.FieldName}_{dataFolderElementCount}"; } this.IsTopFolderParent = (this.ParentNode is DataFolderElementsTreeNode) == false; this.ChildGeneratingDataElementsTreeNode = this.DescendantsBreadthFirst().OfType().First(); IEnumerable parentIdFilterNodes = this.ChildGeneratingDataElementsTreeNode.FilterNodes.OfType(); if (parentIdFilterNodes.Count() <= 1) { this.ChildGeneratingParentIdFilterNode = this.ChildGeneratingDataElementsTreeNode.FilterNodes.OfType().SingleOrDefault(); } else { AddValidationError("TreeValidationError.DataFolderElements.TooManyParentIdFilters", treeNode.FieldName); } this.KeyPropertyInfo = this.InterfaceType.GetKeyProperties()[0]; if (!typeof(ILocalizedControlled).IsAssignableFrom(this.InterfaceType)) { this.ShowForeignItems = false; } } private bool LocalizationEnabled => ShowForeignItems && UserValidationFacade.IsLoggedIn() && UserSettings.ForeignLocaleCultureInfo != null && !UserSettings.ActiveLocaleCultureInfo.Equals(UserSettings.ForeignLocaleCultureInfo); private static Type GetTupleType(int filedCount) { switch (filedCount) { case 1: return TupleType1; case 2: return TupleType2; case 3: return TupleType3; case 4: return TupleType4; case 5: return TupleType5; case 6: return TupleType6; default: throw new NotImplementedException(); } } private static readonly Type TupleType1 = typeof(Tuple<>); private static readonly Type TupleType2 = typeof(Tuple<,>); private static readonly Type TupleType3 = typeof(Tuple<,,>); private static readonly Type TupleType4 = typeof(Tuple<,,,>); private static readonly Type TupleType5 = typeof(Tuple<,,,,>); private static readonly Type TupleType6 = typeof(Tuple<,,,,,>); /// public override string ToString() { return $"DataFolderElementsTreeNode, Id = {this.Id}, DataType = {this.InterfaceType}, FieldName = {this.FieldName}, {this.ParentString()}"; } } } ================================================ FILE: Composite/C1Console/Trees/DynamicValuesHelper.cs ================================================ using System.Collections.Generic; using System.Web; using Composite.C1Console.Security; using Composite.Data; using Composite.Core.ResourceSystem; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DynamicValuesHelperReplaceContext { /// /// Initializes a new instance of the class. /// public DynamicValuesHelperReplaceContext() { } /// /// Initializes a new instance of the class. /// public DynamicValuesHelperReplaceContext(EntityToken currentEntityToken, Dictionary piggyback) { piggyback = piggyback ?? new Dictionary(); this.CurrentEntityToken = currentEntityToken; this.PiggybagDataFinder = new PiggybagDataFinder(piggyback, currentEntityToken); if (currentEntityToken is DataEntityToken) { this.CurrentDataItem = (currentEntityToken as DataEntityToken).Data; } } /// /// Gets or sets the piggybag data finder. /// /// /// The piggybag data finder. /// /// public PiggybagDataFinder PiggybagDataFinder { get; set; } /// /// Gets or sets the current data item. /// /// /// The current data item. /// /// public IData CurrentDataItem { get; set; } /// /// Gets or sets the current entity token. /// /// /// The current entity token. /// /// public EntityToken CurrentEntityToken { get; set; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DynamicValuesHelper { const string CurrentEntityTokenMask = "${C1:EntityToken}"; private DataFieldValueHelper DataFieldValueHelper { get; set; } /// public string Template { get; private set; } /// public DynamicValuesHelper(string template) { this.Template = template; this.DataFieldValueHelper = null; } /// public bool UseUrlEncode { get; set; } /// public string ReplaceValues(DynamicValuesHelperReplaceContext context) { string currentValue = this.Template; if (this.DataFieldValueHelper != null) { currentValue = this.DataFieldValueHelper.ReplaceValues(currentValue, context.PiggybagDataFinder, context.CurrentDataItem, this.UseUrlEncode); } if (currentValue.Contains(CurrentEntityTokenMask)) { string serializedEntityToken = context.CurrentEntityToken != null ? EntityTokenSerializer.Serialize(context.CurrentEntityToken) : "(null)"; if (this.UseUrlEncode) { serializedEntityToken = HttpUtility.UrlEncode(serializedEntityToken); } currentValue = currentValue.Replace(CurrentEntityTokenMask, serializedEntityToken); } return StringResourceSystemFacade.ParseString(currentValue); } /// /// /// /// This is only used to add validation errors public void Initialize(TreeNode ownerTreeNode) { Initialize_DataFieldValueHelper(ownerTreeNode); } /// public void Initialize(ActionNode ownerActionNode) { Initialize(ownerActionNode.OwnerNode); } /// /// /// /// This is only used to add validation errors private void Initialize_DataFieldValueHelper(TreeNode ownerTreeNode) { if (DataFieldValueHelper.ContainsDataField(this.Template) == false) return; this.DataFieldValueHelper = new DataFieldValueHelper(this.Template); this.DataFieldValueHelper.Initialize(ownerTreeNode); } } } ================================================ FILE: Composite/C1Console/Trees/FieldFilterNode.cs ================================================ using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Core.Linq; using Composite.Core.Types; namespace Composite.C1Console.Trees { internal enum FieldFilterNodeOperator { Equal = 0, Inequal = 1, Lesser = 2, Greater = 3, LesserEqual = 4, GreaterEqual = 5 } internal class FieldFilterNode : FilterNode { private PropertyInfo PropertyInfo { get; set; } private object ConvertedValue { get; set ;} public string FieldName { get; internal set; } // Required public string FieldValue { get; internal set; } // Required public FieldFilterNodeOperator Operator { get; internal set; } // Optional public override Expression CreateDownwardsFilterExpression(ParameterExpression parameterExpression, TreeNodeDynamicContext dynamicContext) { return CreateFilterExpression(parameterExpression, dynamicContext); } public override Expression CreateUpwardsFilterExpression(ParameterExpression parameterExpression, TreeNodeDynamicContext dynamicContext) { return CreateFilterExpression(parameterExpression, dynamicContext); } internal override void Initialize() { this.PropertyInfo = this.OwnerNode.InterfaceType.GetPropertiesRecursively().Where(f => f.Name == this.FieldName).SingleOrDefault(); if (this.PropertyInfo == null) { AddValidationError("TreeValidationError.Common.MissingProperty", this.OwnerNode.InterfaceType, this.FieldName); return; } try { this.ConvertedValue = ValueTypeConverter.Convert(this.FieldValue, this.PropertyInfo.PropertyType); } catch { AddValidationError("TreeValidationError.FieldFilter.ValueCouldNotBeConverted", this.FieldValue, this.PropertyInfo.PropertyType); } if ((this.PropertyInfo.PropertyType == typeof(string)) || (this.PropertyInfo.PropertyType == typeof(Guid))) { if ((this.Operator != FieldFilterNodeOperator.Equal) && (this.Operator != FieldFilterNodeOperator.Inequal)) { AddValidationError("TreeValidationError.FieldFilter.OperatorNotSupportedForType", this.Operator, this.PropertyInfo.PropertyType); } } } private Expression CreateFilterExpression(ParameterExpression parameterExpression, TreeNodeDynamicContext dynamicContext) { object value = ValueTypeConverter.Convert(this.FieldValue, this.PropertyInfo.PropertyType); Expression valueExpression = Expression.Constant(value, this.PropertyInfo.PropertyType); Expression expression; switch (this.Operator) { case FieldFilterNodeOperator.Equal: expression = Expression.Equal(ExpressionHelper.CreatePropertyExpression(this.FieldName, parameterExpression), valueExpression); break; case FieldFilterNodeOperator.Inequal: expression = Expression.NotEqual(ExpressionHelper.CreatePropertyExpression(this.FieldName, parameterExpression), valueExpression); break; case FieldFilterNodeOperator.Greater: expression = Expression.GreaterThan(ExpressionHelper.CreatePropertyExpression(this.FieldName, parameterExpression), valueExpression); break; case FieldFilterNodeOperator.GreaterEqual: expression = Expression.GreaterThanOrEqual(ExpressionHelper.CreatePropertyExpression(this.FieldName, parameterExpression), valueExpression); break; case FieldFilterNodeOperator.Lesser: expression = Expression.LessThan(ExpressionHelper.CreatePropertyExpression(this.FieldName, parameterExpression), valueExpression); break; case FieldFilterNodeOperator.LesserEqual: expression = Expression.LessThanOrEqual(ExpressionHelper.CreatePropertyExpression(this.FieldName, parameterExpression), valueExpression); break; default: throw new NotImplementedException(); } return expression; } public override string ToString() { return string.Format("FieldFilterNode, FieldName = {0}, FieldValue = {1}", this.FieldName, this.FieldValue); } } } ================================================ FILE: Composite/C1Console/Trees/FieldOrderByNode.cs ================================================ using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Core.Linq; using Composite.Core.Types; namespace Composite.C1Console.Trees { internal sealed class FieldOrderByNode : OrderByNode { private PropertyInfo PropertyInfo { get; set; } public string FieldName { get; internal set; } // Required public string Direction { get; internal set; } // Optional public override Expression CreateOrderByExpression(Expression sourceExpression, ParameterExpression parameterExpression, bool first) { Expression fieldExpression = ExpressionHelper.CreatePropertyExpression(this.OwnerNode.InterfaceType, this.PropertyInfo.DeclaringType, this.FieldName, parameterExpression); LambdaExpression lambdaExpression = Expression.Lambda(fieldExpression, parameterExpression); if (first) { return this.Direction == "ascending" ? ExpressionCreator.OrderBy(sourceExpression, lambdaExpression) : ExpressionCreator.OrderByDescending(sourceExpression, lambdaExpression); } return this.Direction == "ascending" ? ExpressionCreator.ThenBy(sourceExpression, lambdaExpression) : ExpressionCreator.ThenByDescending(sourceExpression, lambdaExpression); } internal override void Initialize() { if ((this.Direction != "ascending") && (this.Direction != "descending")) { AddValidationError("TreeValidationError.FieldOrderBy.UnknownDirection", this.Direction); } this.PropertyInfo = this.OwnerNode.InterfaceType.GetPropertiesRecursively().SingleOrDefault(f => f.Name == this.FieldName); if (this.PropertyInfo == null) { AddValidationError("TreeValidationError.FieldOrderBy.UnknownField", this.OwnerNode.InterfaceType, this.FieldName); } } public override string ToString() { return string.Format("OrderByNode, FieldName = {0}, Direction = {1}", this.FieldName, this.Direction); } } } ================================================ FILE: Composite/C1Console/Trees/FilterNode.cs ================================================ using System.Linq.Expressions; using System.Collections.Generic; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class FilterNode { /// public string XPath { get; internal set; } /// public int Id { get; internal set; } /// public DataElementsTreeNode OwnerNode { get; internal set; } /// /// This is used when finding data to create elements from (elements going down) /// /// /// /// public virtual Expression CreateDownwardsFilterExpression(ParameterExpression parameterExpression, TreeNodeDynamicContext dynamicContext) { return null; } /// /// This is used when finding data to create entity tokens (security going up) /// /// /// /// public virtual Expression CreateUpwardsFilterExpression(ParameterExpression parameterExpression, TreeNodeDynamicContext dynamicContext) { return null; } /// /// Use this method to do initializing and validation /// internal virtual void Initialize() { } /// public void SetOwnerNode(TreeNode treeNode) { this.OwnerNode = (DataElementsTreeNode)treeNode; } /// protected void AddValidationError(ValidationError validationError) { this.OwnerNode.Tree.BuildResult.AddValidationError(validationError); } /// protected void AddValidationError(string stringName, params object[] args) { this.OwnerNode.Tree.BuildResult.AddValidationError(ValidationError.Create(this.XPath, stringName, args)); } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/ActionNodeCreatorFactory.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.C1Console.Events; using Composite.C1Console.Elements; using Composite.Functions.Foundation; using Composite.Core.ResourceSystem; using Composite.C1Console.Security; using Composite.Core.Types; using Composite.Core.Xml; namespace Composite.C1Console.Trees.Foundation { internal static class ActionNodeCreatorFactory { private static readonly string DefaultAddDataResourceName = "generated-type-data-add"; private static readonly string DefaultEditDataResourceName = "generated-type-data-edit"; private static readonly string DefaultDeleteDataResourceName = "generated-type-data-delete"; private static readonly string DefaultDuplicateDataResourceName = "generated-type-data-duplicate"; private static readonly string DefaultReportFunctionResourceName = "reportfunctionaction-defaulticon"; private static readonly string DefaultMessageBoxResourceName = "messageboxaction-defaulticon"; private static readonly string DefaultCustomUrlResourceName = "customurlaction-defaulticon"; private static readonly string DefaultConfirmResourceName = "confirmaction-defaulticon"; private static readonly string DefaultWorkflowResourceName = "workflowaction-defaulticon"; private static readonly List DefaultAddPermissionTypes = new List { PermissionType.Add }; private static readonly List DefaultEditPermissionTypes = new List { PermissionType.Edit }; private static readonly List DefaultDeletePermissionTypes = new List { PermissionType.Delete }; private static readonly List DefaultDuplicatePermissionTypes = new List { PermissionType.Add }; public static ActionNode CreateActionNode(XElement element, Tree tree) { if (element.Name == TreeMarkupConstants.Namespace + "AddDataAction") { GenericAddDataActionNode actionNode = new GenericAddDataActionNode(); InitializeWithCommonValue(element, tree, actionNode, DefaultAddDataResourceName, StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "GenericAddDataAction.DefaultLabel"), ActionLocation.AddPrimaryActionLocation, DefaultAddPermissionTypes); XAttribute typeAttribute = element.Attribute("Type"); XAttribute customFormMarkupAttribute = element.Attribute("CustomFormMarkupPath"); if (typeAttribute == null) { tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.MissingAttribute", "Type"); } else { actionNode.InterfaceType = TypeManager.TryGetType(typeAttribute.Value); if (actionNode.InterfaceType == null) tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.UnknownInterfaceType", typeAttribute.Value); } actionNode.CustomFormMarkupPath = customFormMarkupAttribute.GetValueOrDefault(null); return actionNode; } else if (element.Name == TreeMarkupConstants.Namespace + "EditDataAction") { GenericEditDataActionNode actionNode = new GenericEditDataActionNode(); InitializeWithCommonValue(element, tree, actionNode, DefaultEditDataResourceName, StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "GenericEditDataAction.DefaultLabel"), ActionLocation.EditPrimaryActionLocation, DefaultEditPermissionTypes); XAttribute customFormMarkupAttribute = element.Attribute("CustomFormMarkupPath"); actionNode.CustomFormMarkupPath = customFormMarkupAttribute.GetValueOrDefault(null); return actionNode; } else if (element.Name == TreeMarkupConstants.Namespace + "DeleteDataAction") { GenericDeleteDataActionNode actionNode = new GenericDeleteDataActionNode(); InitializeWithCommonValue(element, tree, actionNode, DefaultDeleteDataResourceName, StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "GenericDeleteDataAction.DefaultLabel"), ActionLocation.DeletePrimaryActionLocation, DefaultDeletePermissionTypes); return actionNode; } else if (element.Name == TreeMarkupConstants.Namespace + "DuplicateDataAction") { GenericDuplicateDataActionNode actionNode = new GenericDuplicateDataActionNode(); InitializeWithCommonValue(element, tree, actionNode, DefaultDuplicateDataResourceName, StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "GenericDuplicateDataAction.DefaultLabel"), ActionLocation.OtherPrimaryActionLocation, DefaultDuplicatePermissionTypes); return actionNode; } else if (element.Name == TreeMarkupConstants.Namespace + "ReportFunctionAction") { ReportFunctionActionNode actionNode = new ReportFunctionActionNode(); InitializeWithCommonValue(element, tree, actionNode, DefaultReportFunctionResourceName); XAttribute documentLabelAttribute = element.Attribute("DocumentLabel"); XAttribute documentIconAttribute = element.Attribute("DocumentIcon"); XElement functionMarkupElement = element.Element((XNamespace)FunctionTreeConfigurationNames.NamespaceName + FunctionTreeConfigurationNames.FunctionTagName); if (functionMarkupElement == null) tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.MissingFunctionMarkup"); actionNode.FunctionMarkup = functionMarkupElement; actionNode.DocumentLabel = documentLabelAttribute.GetValueOrDefault(actionNode.Label); if (documentIconAttribute != null) { actionNode.DocumentIcon = FactoryHelper.GetIcon(documentIconAttribute.Value); } else { actionNode.DocumentIcon = actionNode.Icon; } return actionNode; } else if (element.Name == TreeMarkupConstants.Namespace + "MessageBoxAction") { MessageBoxActionNode actionNode = new MessageBoxActionNode(); InitializeWithCommonValue(element, tree, actionNode, DefaultMessageBoxResourceName); XAttribute messageBoxTitleAttribute = element.Attribute("MessageBoxTitle"); XAttribute messageBoxMessageAttribute = element.Attribute("MessageBoxMessage"); if (messageBoxTitleAttribute == null) { tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.MissingAttribute", "MessageBoxTitle"); } else { actionNode.Title = messageBoxTitleAttribute.Value; } if (messageBoxMessageAttribute == null) { tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.MissingAttribute", "MessageBoxMessage"); } else { actionNode.Message = messageBoxMessageAttribute.Value; } XAttribute dialogTypeAttribute = element.Attribute("MessageDialogType"); string dialogTypeValue = dialogTypeAttribute.GetValueOrDefault("message"); switch (dialogTypeValue) { case "message": actionNode.DialogType = DialogType.Message; break; case "question": actionNode.DialogType = DialogType.Question; break; case "warning": actionNode.DialogType = DialogType.Warning; break; case "error": actionNode.DialogType = DialogType.Error; break; default: tree.AddValidationError(element.GetXPath(), "TreeValidationError.MessageBoxAction.UnknownDialogType", dialogTypeValue); break; } return actionNode; } else if (element.Name == TreeMarkupConstants.Namespace + "CustomUrlAction") { CustomUrlActionNode actionNode = new CustomUrlActionNode(); InitializeWithCommonValue(element, tree, actionNode, DefaultCustomUrlResourceName); XAttribute urlAttribute = element.Attribute("Url"); XAttribute viewLabelAttribute = element.Attribute("ViewLabel"); XAttribute viewToolTipAttribute = element.Attribute("ViewToolTip"); XAttribute viewIconAttribute = element.Attribute("ViewIcon"); IEnumerable postParameterElements = element.Elements(TreeMarkupConstants.Namespace + "PostParameters"); XElement postParametersElement = null; if (postParameterElements.Count() == 1) { postParametersElement = element.Element(TreeMarkupConstants.Namespace + "PostParameters"); } else if (postParameterElements.Count() > 1) { tree.AddValidationError(element.GetXPath(), "TreeValidationError.CustomUrlAction.TooManyPostParameterElements", "PostParameters"); } if (urlAttribute == null) { tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.MissingAttribute", "Url"); } else { actionNode.Url = urlAttribute.Value; } actionNode.ViewLabel = viewLabelAttribute.GetValueOrDefault(actionNode.Label); actionNode.ViewToolTip = viewToolTipAttribute.GetValueOrDefault(actionNode.ToolTip); actionNode.ViewIcon = FactoryHelper.GetIcon(viewIconAttribute.GetValueOrDefault(DefaultCustomUrlResourceName)); bool urlIsAbsolute = actionNode.Url != null && actionNode.Url.Contains("://"); XAttribute viewTypeAttribute = element.Attribute("ViewType"); string viewTypeValue = viewTypeAttribute.GetValueOrDefault(urlIsAbsolute ? "externalview" : "documentview"); switch (viewTypeValue) { case "externalview": actionNode.ViewType = CustomUrlActionNodeViewType.ExternalView; break; case "genericview": actionNode.ViewType = CustomUrlActionNodeViewType.GenericView; break; case "pagebrowser": actionNode.ViewType = CustomUrlActionNodeViewType.PageBrowser; break; case "filedownload": actionNode.ViewType = CustomUrlActionNodeViewType.FileDownload; break; case "documentview": actionNode.ViewType = CustomUrlActionNodeViewType.DocumentView; break; default: tree.AddValidationError(element.GetXPath(), "TreeValidationError.CustomUrlAction.UnknownViewType", viewTypeValue); break; } actionNode.PostParameters = new Dictionary(); if (postParametersElement != null) { foreach (XElement parameterElement in postParametersElement.Elements(TreeMarkupConstants.Namespace + "Parameter")) { XAttribute keyAttribute = parameterElement.Attribute("Key"); XAttribute valueAttribute = parameterElement.Attribute("Value"); if (keyAttribute == null) { tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.MissingAttribute", "Key"); continue; } else if (string.IsNullOrWhiteSpace(keyAttribute.Value)) { tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.WrongAttributeValue", "Key"); continue; } if (valueAttribute == null) { tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.MissingAttribute", "Value"); continue; } actionNode.PostParameters.Add(keyAttribute.Value, valueAttribute.Value); } } return actionNode; } else if (element.Name == TreeMarkupConstants.Namespace + "ConfirmAction") { ConfirmActionNode actionNode = new ConfirmActionNode(); InitializeWithCommonValue(element, tree, actionNode, DefaultConfirmResourceName); XAttribute confirmTitleAttribute = element.Attribute("ConfirmTitle"); XAttribute confirmMessageAttribute = element.Attribute("ConfirmMessage"); if (confirmTitleAttribute == null) { tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.MissingAttribute", "ConfirmTitle"); } else { actionNode.ConfirmTitle = confirmTitleAttribute.Value; } if (confirmMessageAttribute == null) { tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.MissingAttribute", "ConfirmMessage"); } else { actionNode.ConfirmMessage = confirmMessageAttribute.Value; } XElement functionMarkupElement = element.Element((XNamespace)FunctionTreeConfigurationNames.NamespaceName + FunctionTreeConfigurationNames.FunctionTagName); if (functionMarkupElement == null) tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.MissingFunctionMarkup"); actionNode.FunctionMarkup = functionMarkupElement; XAttribute refreshTreeAttribute = element.Attribute("RefreshTree"); string refreshTreeAttributeValue = refreshTreeAttribute.GetValueOrDefault("false").ToLowerInvariant(); if (refreshTreeAttributeValue == "true") { actionNode.RefreshTree = true; } else { actionNode.RefreshTree = false; } return actionNode; } else if (element.Name == TreeMarkupConstants.Namespace + "WorkflowAction") { WorkflowActionNode actionNode = new WorkflowActionNode(); InitializeWithCommonValue(element, tree, actionNode, DefaultWorkflowResourceName); XAttribute workflowTypeAttribute = element.Attribute("WorkflowType"); if (workflowTypeAttribute == null) { tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.MissingAttribute", "ConfirmTitle"); } else { actionNode.WorkflowType = TypeManager.TryGetType(workflowTypeAttribute.Value); if (actionNode.WorkflowType == null) tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.UnknownInterfaceType", workflowTypeAttribute.Value); } return actionNode; } else { tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.UnknownElement", element.Name); return null; } } private static void InitializeWithCommonValue(XElement element, Tree tree, ActionNode actionNode, string defaultIconName, string defaultLabelName = null, ActionLocation defaultActionLocation = null, List defaultPermissionTypes = null) { XAttribute labelAttribute = element.Attribute("Label"); XAttribute toolTipAttribute = element.Attribute("ToolTip"); XAttribute iconAttribute = element.Attribute("Icon"); if ((defaultLabelName == null) && (labelAttribute == null)) tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.MissingAttribute", "Label"); actionNode.XPath = element.GetXPath(); actionNode.Id = tree.BuildProcessContext.ActionIdCounter++; actionNode.Label = labelAttribute.GetValueOrDefault(defaultLabelName); actionNode.ToolTip = toolTipAttribute.GetValueOrDefault(actionNode.Label); actionNode.Icon = FactoryHelper.GetIcon(iconAttribute.GetValueOrDefault(defaultIconName)); actionNode.Location = GetActionLocation(element, tree, defaultActionLocation); if (defaultPermissionTypes != null) { actionNode.PermissionTypes = defaultPermissionTypes; } else { actionNode.PermissionTypes = GetPermissionTypes(element, tree); } } public static List GetPermissionTypes(XElement element, Tree tree, List defaultPermissionTypes = null) { XAttribute permissionTypesAttribute = element.Attribute("PermissionTypes"); if ((permissionTypesAttribute == null) && (defaultPermissionTypes != null)) return defaultPermissionTypes; string permissionTypesString = permissionTypesAttribute.GetValueOrDefault("read"); string[] permissionTypesStrings = permissionTypesString.Split(','); var permissionTypes = new List(); foreach (string permission in permissionTypesStrings) { PermissionType permissionType; if (Enum.TryParse(permission.Trim(), true, out permissionType) == false) { tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.WrongPermissionValue", permission.Trim()); continue; } permissionTypes.Add(permissionType); } return permissionTypes; } public static ActionLocation GetActionLocation(XElement element, Tree tree, ActionLocation defaultActionLocation = null) { XAttribute locationAttribute = element.Attribute("Location"); if (locationAttribute == null) return ActionLocation.OtherPrimaryActionLocation; switch (locationAttribute.Value) { case "Add": return ActionLocation.AddPrimaryActionLocation; case "Edit": return ActionLocation.EditPrimaryActionLocation; case "Delete": return ActionLocation.DeletePrimaryActionLocation; case "Other": return ActionLocation.OtherPrimaryActionLocation; default: if (defaultActionLocation != null) return defaultActionLocation; tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.WrongLocationValue", locationAttribute.Value); return ActionLocation.OtherPrimaryActionLocation; } } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/AttachmentPoints/BaseAttachmentPoint.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Elements.Plugins.ElementAttachingProvider; using Composite.C1Console.Security; namespace Composite.C1Console.Trees.Foundation.AttachmentPoints { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class BaseAttachmentPoint : IAttachmentPoint { /// public abstract bool IsAttachmentPoint(EntityToken parentEntityToken); /// public ElementAttachingProviderPosition Position { get; set; } /// public abstract IEnumerable GetEntityTokens(EntityToken childEntityToken, TreeNodeDynamicContext dynamicContext); /// public abstract void Log(string title, string indention = ""); } } ================================================ FILE: Composite/C1Console/Trees/Foundation/AttachmentPoints/BasePossibleAttachmentPoint.cs ================================================ using Composite.C1Console.Elements.Plugins.ElementAttachingProvider; using Composite.C1Console.Security; namespace Composite.C1Console.Trees.Foundation.AttachmentPoints { internal abstract class BasePossibleAttachmentPoint : IPossibleAttachmentPoint { public abstract bool IsPossibleAttachmentPoint(EntityToken parentEntityToken); public ElementAttachingProviderPosition Position { get; set; } public abstract void Log(string title, string indention = ""); } } ================================================ FILE: Composite/C1Console/Trees/Foundation/AttachmentPoints/CustomAttachmentPoint.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Elements.Plugins.ElementAttachingProvider; using Composite.C1Console.Security; namespace Composite.C1Console.Trees.Foundation.AttachmentPoints { internal sealed class CustomAttachmentPoint : BaseAttachmentPoint { private readonly EntityToken _parentEntityToken; public CustomAttachmentPoint(EntityToken parentEntityToken) { _parentEntityToken = parentEntityToken; this.Position = ElementAttachingProviderPosition.Top; } public CustomAttachmentPoint(EntityToken parentEntityToken, ElementAttachingProviderPosition position) :this(parentEntityToken) { this.Position = position; } public override bool IsAttachmentPoint(EntityToken parentEntityToken) { return parentEntityToken.Equals(_parentEntityToken); } public override IEnumerable GetEntityTokens(EntityToken childEntityToken, TreeNodeDynamicContext dynamicContext) { yield return _parentEntityToken; } public override void Log(string title, string indention = "") { Composite.Core.Log.LogVerbose(title, "{0}Custom: Position = {1}, EntityTokenType = {2}, EntityToken = {3}", indention, this.Position, _parentEntityToken.GetType(), _parentEntityToken); } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/AttachmentPoints/DataItemAttachmentPoint.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Composite.Data; using Composite.Data.ProcessControlled; using Composite.Core.Logging; using Composite.C1Console.Security; namespace Composite.C1Console.Trees.Foundation.AttachmentPoints { internal class DataItemAttachmentPoint : BaseAttachmentPoint, IDataItemAttachmentPoint { public Type InterfaceType { get; set; } public override bool IsAttachmentPoint(EntityToken parentEntityToken) { DataEntityToken dataEntityToken = parentEntityToken as DataEntityToken; if (dataEntityToken == null) return false; if (dataEntityToken.InterfaceType != this.InterfaceType) return false; return true; } public override IEnumerable GetEntityTokens(EntityToken childEntityToken, TreeNodeDynamicContext dynamicContext) { throw new NotImplementedException("This is prevented by validation"); //if (typeof(ILocalizedControlled).IsAssignableFrom(this.InterfaceType)) //{ // foreach (CultureInfo cultureInfo in DataLocalizationFacade.ActiveLocalizationCultures) // { // using (new DataScope(cultureInfo)) // { // EntityToken entityToken = GetEntityTokensImpl(); // if (entityToken != null) // { // yield return entityToken; // } // } // } //} //else //{ // yield return GetEntityTokensImpl(); //} } private EntityToken GetEntityTokensImpl() { // Any data item will work, but if security is set on the first item, it will rule them alll......is this good? // This is no problem for Simple elements, but huge problem for data elements and data folder elements. // Should this be disallowed??? IData data = DataFacade.GetData(this.InterfaceType).ToDataEnumerable().FirstOrDefault(); if (data == null) return null; return data.GetDataEntityToken(); } public override void Log(string title, string indention) { LoggingService.LogVerbose(title, string.Format("{0}DataType: Position = {1}, Type = {2}", indention, this.Position, this.InterfaceType)); } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/AttachmentPoints/DataItemPossibleAttachmentPoint.cs ================================================ using System; using Composite.Data; using Composite.Core.Logging; using Composite.C1Console.Security; namespace Composite.C1Console.Trees.Foundation.AttachmentPoints { internal sealed class DataItemPossibleAttachmentPoint : BasePossibleAttachmentPoint, IDataItemAttachmentPoint { public Type InterfaceType { get; set; } public override bool IsPossibleAttachmentPoint(EntityToken parentEntityToken) { DataEntityToken dataEntityToken = parentEntityToken as DataEntityToken; if (dataEntityToken == null) return false; if (dataEntityToken.InterfaceType != this.InterfaceType) return false; return true; } public override void Log(string title, string indention = "") { LoggingService.LogVerbose(title, string.Format("{0}DataType: Position = {1}, InterfaceType = {2}", indention, this.Position, this.InterfaceType)); } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/AttachmentPoints/DynamicDataItemAttachmentPoint.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using Composite.Data; using Composite.C1Console.Security; using Composite.Data.ProcessControlled; namespace Composite.C1Console.Trees.Foundation.AttachmentPoints { /// /// This class is used when the user adds trees dynamicly /// Used as a dual with Composite.Data.Types.IDataItemTreeAttachmentPoint /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DebuggerDisplay("DynamicDataItemAttachmentPoint. Type = '{InterfaceType}', Key = '{KeyValue}'")] public sealed class DynamicDataItemAttachmentPoint : BaseAttachmentPoint, IDataItemAttachmentPoint { /// public Type InterfaceType { get; set; } /// public object KeyValue { get; set; } /// public override bool IsAttachmentPoint(EntityToken parentEntityToken) { DataEntityToken dataEntityToken = parentEntityToken as DataEntityToken; if (dataEntityToken == null) return false; if (dataEntityToken.InterfaceType != this.InterfaceType) return false; // The data item has not been localized, so down attach the tree. if (dataEntityToken.DataSourceId.LocaleScope.Equals(LocalizationScopeManager.CurrentLocalizationScope) == false) return false; object keyValue = dataEntityToken.DataSourceId.GetKeyValue(); return object.Equals(keyValue, this.KeyValue); } /// public override IEnumerable GetEntityTokens(EntityToken childEntityToken, TreeNodeDynamicContext dynamicContext) { if (typeof(ILocalizedControlled).IsAssignableFrom(this.InterfaceType)) { foreach (CultureInfo cultureInfo in DataLocalizationFacade.ActiveLocalizationCultures) { using (new DataScope(cultureInfo)) { EntityToken entityToken = GetEntityTokensImpl(); if (entityToken != null) { yield return entityToken; } } } } else { yield return GetEntityTokensImpl(); } } private EntityToken GetEntityTokensImpl() { IData data = DataFacade.TryGetDataVersionsByUniqueKey(this.InterfaceType, KeyValue).FirstOrDefault(); return data == null ? null : data.GetDataEntityToken(); } /// public override void Log(string title, string indention = "") { Core.Log.LogVerbose(title, string.Format("{0}DynamicDataType: Position = {1}, Type = {2}, KeyValue = {3}", indention, this.Position, this.InterfaceType, this.KeyValue)); } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/AttachmentPoints/IAttachmentPoint.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Elements.Plugins.ElementAttachingProvider; using Composite.C1Console.Security; namespace Composite.C1Console.Trees.Foundation.AttachmentPoints { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IBaseAttachmentPoint { /// ElementAttachingProviderPosition Position { get; set; } /// void Log(string title, string indention = ""); } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IAttachmentPoint : IBaseAttachmentPoint { /// bool IsAttachmentPoint(EntityToken parentEntityToken); /// IEnumerable GetEntityTokens(EntityToken childEntityToken, TreeNodeDynamicContext dynamicContext); } } ================================================ FILE: Composite/C1Console/Trees/Foundation/AttachmentPoints/IDataItemAttachmentPoint.cs ================================================ using System; namespace Composite.C1Console.Trees.Foundation.AttachmentPoints { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IDataItemAttachmentPoint : IBaseAttachmentPoint { /// Type InterfaceType { get; set; } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/AttachmentPoints/INamedAttachmentPoint.cs ================================================ using Composite.C1Console.Elements; namespace Composite.C1Console.Trees.Foundation.AttachmentPoints { internal interface INamedAttachmentPoint : IBaseAttachmentPoint { AttachingPoint AttachingPoint { get; set; } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/AttachmentPoints/IPossibleAttachmentPoint.cs ================================================ using Composite.C1Console.Security; using Composite.C1Console.Elements.Plugins.ElementAttachingProvider; namespace Composite.C1Console.Trees.Foundation.AttachmentPoints { internal interface IPossibleAttachmentPoint : IBaseAttachmentPoint { bool IsPossibleAttachmentPoint(EntityToken parentEntityToken); } } ================================================ FILE: Composite/C1Console/Trees/Foundation/AttachmentPoints/NamedAttachmentPoint.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Elements; using Composite.Core.Logging; using Composite.C1Console.Security; namespace Composite.C1Console.Trees.Foundation.AttachmentPoints { internal sealed class NamedAttachmentPoint : BaseAttachmentPoint, INamedAttachmentPoint { public AttachingPoint AttachingPoint { get; set; } public override IEnumerable GetEntityTokens(EntityToken childEntityToken, TreeNodeDynamicContext dynamicContext) { yield return this.AttachingPoint.EntityToken; } public override bool IsAttachmentPoint(EntityToken parentEntityToken) { return ElementAttachingPointFacade.IsAttachingPoint(parentEntityToken, this.AttachingPoint); } public override void Log(string title, string indention = "") { LoggingService.LogVerbose(title, string.Format("{0}Named: Position = {1}, Id = {2}, EntityTokenType = {3}, EntityToken = {4}", indention, this.Position, this.AttachingPoint.Id, this.AttachingPoint.EntityTokenType, this.AttachingPoint.EntityToken)); } } internal sealed class EntityTokenAttachmentPoint : BaseAttachmentPoint { public EntityToken EntityToken { get; set; } public override IEnumerable GetEntityTokens(EntityToken childEntityToken, TreeNodeDynamicContext dynamicContext) { yield return this.EntityToken; } public override bool IsAttachmentPoint(EntityToken parentEntityToken) { return ElementAttachingPointFacade.IsAttachingPoint(parentEntityToken, this.EntityToken); } public override void Log(string title, string indention = "") { LoggingService.LogVerbose(title, string.Format("{0}EntityToken: Position = {1}, EntityToken = {2}", indention, this.Position, this.EntityToken)); } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/BuildProcessContext.cs ================================================ using System; using System.Collections.Generic; namespace Composite.C1Console.Trees.Foundation { internal sealed class BuildProcessContext { private int _nodeIdCounter; private List _usedIds = new List(); public BuildProcessContext() { _nodeIdCounter = 0; this.ActionIdCounter = 0; this.FilterIdCounter = 0; } public int ActionIdCounter; public int FilterIdCounter; public string CreateNewNodeId() { return string.Format("NodeAutoId_{0}", _nodeIdCounter++); } public bool AlreadyUsed(string id) { return _usedIds.Contains(id); } public void AddUsedId(string id) { _usedIds.Add(id); } public Dictionary> DataInteraceToTreeNodes = new Dictionary>(); } } ================================================ FILE: Composite/C1Console/Trees/Foundation/DateTimeFormater.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; namespace Composite.C1Console.Trees.Foundation { internal sealed class DateTimeFormater { private readonly string _format; private int _fieldCount; private readonly string _yearFormat; private readonly string _monthFormat; private readonly string _dayFormat; private readonly string _hourFormat; private readonly string _minuteFormat; private readonly string _secondFormat; private static readonly IList Tuples_Constructors; private static readonly IList Tuples_Members; static DateTimeFormater() { var tupleTypes = new[] { typeof (Tuple), typeof (Tuple), typeof (Tuple), typeof (Tuple), typeof (Tuple), typeof (Tuple) }; Tuples_Constructors = new List(); Tuples_Members = new List(); for (int i = 0; i < tupleTypes.Length; i++) { var type = tupleTypes[i]; Tuples_Constructors.Add(type.GetConstructors().Single()); Tuples_Members.Add(type.GetProperties().Select(p => p.GetGetMethod()).ToArray()); } } public bool IsDateTimeGroupingValue(object value) { if (value == null) { return false; } var type = value.GetType(); return type.FullName.StartsWith(typeof(Tuple).FullName) && type.IsGenericType && type.GetGenericArguments().All(a => a == typeof(int)); } public DateTimeFormater(string format) { _format = format; if (_format != null) { // The ordering yyyy, yyy, yy, y is important here. So for the others. SetFormat("yyyy", ref _yearFormat); SetFormat("yyy", ref _yearFormat); SetFormat("yy", ref _yearFormat); SetFormat("y", ref _yearFormat); SetFormat("MMMM", ref _monthFormat); SetFormat("MMM", ref _monthFormat); SetFormat("MM", ref _monthFormat); SetFormat("M", ref _monthFormat); SetFormat("dddd", ref _dayFormat); SetFormat("ddd", ref _dayFormat); SetFormat("dd", ref _dayFormat); SetFormat("d", ref _dayFormat); SetFormat("hh", ref _hourFormat); SetFormat("h", ref _hourFormat); SetFormat("HH", ref _hourFormat); SetFormat("H", ref _hourFormat); SetFormat("mm", ref _minuteFormat); SetFormat("m", ref _minuteFormat); SetFormat("ss", ref _secondFormat); SetFormat("s", ref _secondFormat); } } public string FormatLabel(object dateTimeValue) { DateTime dateTime = GetDateTime(dateTimeValue); return dateTime.ToString(_format); } public string Serialize(object value) { if (!this.IsFormated) { TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(DateTime)); return typeConverter.ConvertToString(value); } string serializedValue = "·"; TupleIndexer tupleIndexer = new TupleIndexer(value); int counter = 1; if (this.HasYear) { serializedValue += tupleIndexer[counter++]; } serializedValue += ","; if (this.HasMonth) { serializedValue += tupleIndexer[counter++]; } serializedValue += ","; if (this.HasDay) { serializedValue += tupleIndexer[counter++]; } serializedValue += ","; if (this.HasHour) { serializedValue += tupleIndexer[counter++]; } serializedValue += ","; if (this.HasMinute) { serializedValue += tupleIndexer[counter++]; } serializedValue += ","; if (this.HasSecond) { serializedValue += tupleIndexer[counter++]; } return serializedValue; } public string SerializeDateTime(DateTime value) { string serializedValue = "·"; if (this.HasYear) serializedValue += value.Year.ToString(); serializedValue += ","; if (this.HasMonth) serializedValue += value.Month.ToString(); serializedValue += ","; if (this.HasDay) serializedValue += value.Day.ToString(); serializedValue += ","; if (this.HasHour) serializedValue += value.Hour.ToString(); serializedValue += ","; if (this.HasMinute) serializedValue += value.Millisecond.ToString(); serializedValue += ","; if (this.HasSecond) serializedValue += value.Second.ToString(); return serializedValue; } public static DateTime Deserialize(string serializedValue, DateTime? currentTime = null) { if (serializedValue.StartsWith("·")) { serializedValue = serializedValue.Remove(1, 0); } else { TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(DateTime)); return (DateTime)typeConverter.ConvertFromString(serializedValue); } string[] values = serializedValue.Remove(0, 1).Split(','); if (values.Length != 6) throw new InvalidOperationException("DateTimeFormat is of wrong format"); int year = 2000, month = 1, day = 1, hour = 0, minute = 0, second = 0; if (currentTime.HasValue) { year = currentTime.Value.Year; month = currentTime.Value.Month; day = currentTime.Value.Day; hour = currentTime.Value.Hour; minute = currentTime.Value.Minute; second = currentTime.Value.Second; } if (values[0] != "") year = int.Parse(values[0]); if (values[1] != "") month = int.Parse(values[1]); if (values[2] != "") day = int.Parse(values[2]); if (values[3] != "") hour = int.Parse(values[3]); if (values[4] != "") minute = int.Parse(values[4]); if (values[5] != "") second = int.Parse(values[5]); return new DateTime(year, month, day, hour, minute, second); } public DateTime GetDateTime(object value) { if (this.IsFormated == false) { return (DateTime)value; } int year = 2000, month = 1, day = 1, hour = 0, minute = 0, second = 0; TupleIndexer tupleIndexer = new TupleIndexer(value); int counter = 1; if (this.HasYear) year = tupleIndexer[counter++]; if (this.HasMonth) month = tupleIndexer[counter++]; if (this.HasDay) day = tupleIndexer[counter++]; if (this.HasHour) hour = tupleIndexer[counter++]; if (this.HasMinute) minute = tupleIndexer[counter++]; if (this.HasSecond) second = tupleIndexer[counter++]; return new DateTime(year, month, day, hour, minute, second); } public ConstructorInfo GetTupleConstructor() { ValidateFieldsCount(); return Tuples_Constructors[_fieldCount - 1]; } public MethodInfo[] GetTupleMembers() { ValidateFieldsCount(); return Tuples_Members[_fieldCount - 1]; } //public ConstructorInfo GetAnonymousTypeConstructor() //{ // ValidateFieldsCount(); // return AnonymousTypes_Constructors[_fieldCount - 1]; //} //public MethodInfo[] GetAnonymousTypeMembers() //{ // ValidateFieldsCount(); // return AnonymousTypes_Members[_fieldCount - 1]; //} private void ValidateFieldsCount() { Verify.That(_fieldCount > 0, "Amount of fields should be positive"); Verify.That(_fieldCount < Tuples_Constructors.Count, "To many fields specified: {0}", _fieldCount); } public bool IsFormated => _format != null; public bool HasYear => _yearFormat != null; public bool HasMonth => _monthFormat != null; public bool HasDay => _dayFormat != null; public bool HasHour => _hourFormat != null; public bool HasMinute => _minuteFormat != null; public bool HasSecond => _secondFormat != null; private void SetFormat(string pattern, ref string format) { if (_format.Contains(pattern) && format == null) { format = pattern; _fieldCount++; } } public static PropertyInfo DateTime_Year = typeof(DateTime).GetProperty(nameof(DateTime.Year)); public static PropertyInfo DateTime_Month = typeof(DateTime).GetProperty(nameof(DateTime.Month)); public static PropertyInfo DateTime_Day = typeof(DateTime).GetProperty(nameof(DateTime.Day)); public static PropertyInfo DateTime_Hour = typeof(DateTime).GetProperty(nameof(DateTime.Hour)); public static PropertyInfo DateTime_Minute = typeof(DateTime).GetProperty(nameof(DateTime.Minute)); public static PropertyInfo DateTime_Second = typeof(DateTime).GetProperty(nameof(DateTime.Second)); } } ================================================ FILE: Composite/C1Console/Trees/Foundation/FactoryHelper.cs ================================================ using System; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; namespace Composite.C1Console.Trees.Foundation { internal static class FactoryHelper { internal static ResourceHandle GetIcon(string name) { if (name.Contains(",") == false) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } throw new NotImplementedException(); } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/FilterNodeCreatorFactory.cs ================================================ using System; using System.Xml.Linq; using Composite.Functions.Foundation; using Composite.Core.Types; using Composite.Core.Xml; namespace Composite.C1Console.Trees.Foundation { internal static class FilterNodeCreatorFactory { public static FilterNode CreateFilterNode(XElement filterElement, Tree tree) { if (filterElement.Name == TreeMarkupConstants.Namespace + "ParentIdFilter") { XAttribute parentTypeAttribute = filterElement.Attribute("ParentType"); XAttribute referenceFieldNameAttribute = filterElement.Attribute("ReferenceFieldName"); if (parentTypeAttribute == null) { tree.AddValidationError(filterElement.GetXPath(), "TreeValidationError.Common.MissingAttribute", "ParentType"); return null; } if (referenceFieldNameAttribute == null) { tree.AddValidationError(filterElement.GetXPath(), "TreeValidationError.Common.MissingAttribute", "ReferenceFieldName"); return null; } Type parentInterfaceType = TypeManager.TryGetType(parentTypeAttribute.Value); if (parentInterfaceType == null) { tree.AddValidationError(filterElement.GetXPath(), "TreeValidationError.Common.UnknownInterfaceType", parentTypeAttribute.Value); return null; } return new ParentIdFilterNode { XPath = filterElement.GetXPath(), Id = tree.BuildProcessContext.FilterIdCounter++, ParentFilterType = parentInterfaceType, ReferenceFieldName = referenceFieldNameAttribute.Value }; } if (filterElement.Name == TreeMarkupConstants.Namespace + "FieldFilter") { XAttribute fieldNameAttribute = filterElement.Attribute("FieldName"); XAttribute fieldValueAttribute = filterElement.Attribute("FieldValue"); XAttribute operatorValueAttribute = filterElement.Attribute("Operator"); if (fieldNameAttribute == null) { tree.AddValidationError(filterElement.GetXPath(), "TreeValidationError.Common.MissingAttribute", "FieldName"); return null; } if (fieldValueAttribute == null) { tree.AddValidationError(filterElement.GetXPath(), "TreeValidationError.Common.MissingAttribute", "FieldValue"); return null; } FieldFilterNodeOperator filterOperator; string operatorValue = operatorValueAttribute.GetValueOrDefault("equal"); switch (operatorValue) { case "equal": filterOperator = FieldFilterNodeOperator.Equal; break; case "inequal": filterOperator = FieldFilterNodeOperator.Inequal; break; case "lesser": filterOperator = FieldFilterNodeOperator.Lesser; break; case "greater": filterOperator = FieldFilterNodeOperator.Greater; break; case "lesserequal": filterOperator = FieldFilterNodeOperator.LesserEqual; break; case "greaterequal": filterOperator = FieldFilterNodeOperator.GreaterEqual; break; default: tree.AddValidationError(filterElement.GetXPath(), "TreeValidationError.FieldFilter.UnknownOperatorName", operatorValue); return null; } return new FieldFilterNode { XPath = filterElement.GetXPath(), Id = tree.BuildProcessContext.FilterIdCounter++, FieldName = fieldNameAttribute.Value, FieldValue = fieldValueAttribute.Value, Operator = filterOperator }; } if (filterElement.Name == TreeMarkupConstants.Namespace + "FunctionFilter") { XElement functionMarkupElement = filterElement.Element((XNamespace)FunctionTreeConfigurationNames.NamespaceName + FunctionTreeConfigurationNames.FunctionTagName); if (functionMarkupElement == null) { tree.AddValidationError(filterElement.GetXPath(), "TreeValidationError.FunctionFilter.MissingFunctionMarkup"); return null; } return new FunctionFilterNode() { XPath = filterElement.GetXPath(), Id = tree.BuildProcessContext.FilterIdCounter++, FunctionMarkup = functionMarkupElement }; } throw new NotImplementedException("ValidationError"); } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/FolderRanges/BaseFolderRanges.cs ================================================ using System.Linq; using System.Collections.Generic; using System.Linq.Expressions; namespace Composite.C1Console.Trees.Foundation.FolderRanges { internal abstract class BaseFolderRanges : IFolderRanges { private List _folderRanges = new List(); public void AddFolderRange(IFolderRange folderRange) { _folderRanges.Add(folderRange); } public abstract Expression CreateContainsListSelectBodyExpression(Expression fieldExpression, ParameterExpression parameterExpression); public abstract Expression CreateFilterExpression(int folderRangeIndex, Expression fieldExpression); public IEnumerable Ranges { get { foreach (IFolderRange folderRange in _folderRanges) { yield return folderRange; } } } protected IFolderRange GetFolderRange(int index) { return _folderRanges.Where(f => f.Index == index).Single(); } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/FolderRanges/FolderRangesCreator.cs ================================================ using System; using System.Collections.Generic; namespace Composite.C1Console.Trees.Foundation.FolderRanges { internal static class FolderRangesCreator { public static IFolderRanges Create(TreeNode ownerTreeNode, string rangeString, string fieldName, Type propertyType) { string[] rangesSplit = rangeString.Split(','); bool includeWildCard = false; List rangeStrings = new List(); foreach (string rangeSplit in rangesSplit) { string range = rangeSplit.Trim(); if (range != "*") { rangeStrings.Add(range); } else { includeWildCard = true; } } if (rangeStrings.Count == 0) { ownerTreeNode.AddValidationError("TreeValidationError.Range.WrongFormat"); return null; } List> ranges = new List>(); if (rangeStrings.Count == 1) { Tuple range = ValidateRange(rangeStrings[0], allowMinOpenEnded: true, allowMaxOpenEnded: true); if (range == null) { ownerTreeNode.AddValidationError("TreeValidationError.Range.WrongFormat"); return null; } ranges.Add(range); } else if (rangeStrings.Count > 1) { string firstString = rangeStrings[0]; string lastString = rangeStrings[rangeStrings.Count - 1]; Tuple firstRange = ValidateRange(firstString, allowMinOpenEnded: true); Tuple lastRange = ValidateRange(lastString, allowMaxOpenEnded: true); if ((firstRange == null) || (lastRange == null)) { ownerTreeNode.AddValidationError("TreeValidationError.Range.WrongFormat"); return null; } ranges.Add(firstRange); for (int i = 1; i <= rangeStrings.Count - 2; i++) { Tuple range = ValidateRange(rangeStrings[i]); if (range == null) { ownerTreeNode.AddValidationError("TreeValidationError.Range.WrongFormat"); return null; } ranges.Add(range); } ranges.Add(lastRange); } if (propertyType == typeof(int)) { return FolderRangesFactory.CreateIntFolderRangeIterator(ownerTreeNode, ranges, includeWildCard); } else if (propertyType == typeof(string)) { return FolderRangesFactory.CreateStringFolderRanges(ownerTreeNode, ranges, includeWildCard); } else { ownerTreeNode.AddValidationError("TreeValidationError.Range.UnsupportedType", fieldName, propertyType); return null; } } private static Tuple ValidateRange(string range, bool allowMinOpenEnded = false, bool allowMaxOpenEnded = false) { string[] str = range.Split('>'); if (str.Length != 2) return null; if ((str[0] == "") && (str[1] == "")) return null; if ((str[0] == "") && (allowMinOpenEnded == false)) return null; if ((str[1] == "") && (allowMaxOpenEnded == false)) return null; return new Tuple(str[0], str[1]); } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/FolderRanges/FolderRangesFactory.cs ================================================ using System; using System.Linq; using System.Collections.Generic; namespace Composite.C1Console.Trees.Foundation.FolderRanges { internal static class FolderRangesFactory { public static IFolderRanges CreateIntFolderRangeIterator(TreeNode ownerTreeNode, List> ranges, bool includeWildCard) { IntFolderRanges folderRanges = new IntFolderRanges(); int counter = 0; int? lastMaxValue = null; foreach (Tuple range in ranges) { int minValue = 0; int maxValue = 0; bool isMinOpenEnded = range.Item1 == ""; bool isMaxOpenEnded = range.Item2 == ""; if ((range.Item1 != "") && (int.TryParse(range.Item1, out minValue) == false)) { ownerTreeNode.AddValidationError("TreeValidationError.Range.WrongFormat"); return null; } if ((range.Item2 != "") && (int.TryParse(range.Item2, out maxValue) == false)) { ownerTreeNode.AddValidationError("TreeValidationError.Range.WrongFormat"); return null; } if ((isMinOpenEnded == false) && (isMaxOpenEnded == false) && (minValue >= maxValue)) { ownerTreeNode.AddValidationError("TreeValidationError.Range.MinMaxError", minValue, maxValue); return null; } if (lastMaxValue.HasValue == false) { lastMaxValue = maxValue; } else if (lastMaxValue.Value >= minValue) { ownerTreeNode.AddValidationError("TreeValidationError.Range.NextRangeError"); } IntFolderRange folderRange = new IntFolderRange( counter++, minValue, maxValue, isMinOpenEnded, isMaxOpenEnded ); folderRanges.AddFolderRange(folderRange); } if (includeWildCard) { IntFolderRange folderRange = new IntFolderRange( -1, 0, 0, false, false ); folderRanges.AddFolderRange(folderRange); } return folderRanges; } public static IFolderRanges CreateStringFolderRanges(TreeNode ownerTreeNode, List> ranges, bool includeWildCard) { StringFolderRanges folderRanges = new StringFolderRanges(); int counter = 0; string lastMaxValue = null; foreach (Tuple range in ranges) { string minValue = ""; string maxValue = ""; bool isMinOpenEnded = range.Item1 == ""; bool isMaxOpenEnded = range.Item2 == ""; if (range.Item1 != "") { if (range.Item1.Length != 1) { ownerTreeNode.AddValidationError("TreeValidationError.Range.WrongFormat"); return null; } else { minValue = range.Item1; } } if (range.Item2 != "") { if (range.Item2.Length != 1) { ownerTreeNode.AddValidationError("TreeValidationError.Range.WrongFormat"); return null; } else { maxValue = range.Item2; } } if ((isMinOpenEnded == false) && (isMaxOpenEnded == false) && (string.Compare(minValue, maxValue) >= 0)) { ownerTreeNode.AddValidationError("TreeValidationError.Range.MinMaxError", minValue, maxValue); return null; } if (lastMaxValue == null) { lastMaxValue = maxValue; } else if (string.Compare(lastMaxValue, minValue) >= 0) { ownerTreeNode.AddValidationError("TreeValidationError.Range.NextRangeError"); } StringFolderRange folderRange = new StringFolderRange( counter++, minValue, maxValue, isMinOpenEnded, isMaxOpenEnded ); folderRanges.AddFolderRange(folderRange); } if (includeWildCard) { StringFolderRange folderRange = new StringFolderRange( -1, "", "", false, false ); folderRanges.AddFolderRange(folderRange); } return folderRanges; } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/FolderRanges/IFolderRange.cs ================================================ using System.Linq.Expressions; namespace Composite.C1Console.Trees.Foundation.FolderRanges { internal interface IFolderRange { /// /// Indexed from 0 and up, -1 is wildcard/other /// int Index { get; } object MinValue { get; } object MaxValue { get; } bool IsMinOpenEnded { get; } bool IsMaxOpenEnded { get; } string Label { get; } object DefaultValue { get; } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/FolderRanges/IFolderRanges.cs ================================================ using System.Collections.Generic; using System.Linq.Expressions; namespace Composite.C1Console.Trees.Foundation.FolderRanges { internal interface IFolderRanges { /// /// This is called by DataFolderElementsTreeNode when finding folders /// /// /// /// /// This should return an expression that gives a list of bools foreach folder range /// whether folder range is containing data or not. /// Expression CreateContainsListSelectBodyExpression(Expression fieldExpression, ParameterExpression parameterExpression); /// /// This is called by DataFolderElementsTreeNode when finding children to a folder element /// /// /// This should return an expression that filters so that only children of the given folder /// element is return. /// Expression CreateFilterExpression(int folderRangeIndex, Expression fieldExpression); IEnumerable Ranges { get; } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/FolderRanges/IntFolderRange.cs ================================================ using System.Diagnostics; using Composite.Core.ResourceSystem; namespace Composite.C1Console.Trees.Foundation.FolderRanges { [DebuggerDisplay("{Index} : ({MinValue}-{MaxValue}) : {Label}")] internal sealed class IntFolderRange : IFolderRange { private int _index; private int _minValue; private int _maxValue; private bool _isMinOpenEnded; private bool _isMaxOpenEnded; public IntFolderRange(int index, int minValue, int maxValue, bool isMinOpenEnded, bool isMaxOpenEnded) { _index = index; _minValue = minValue; _maxValue = maxValue; _isMinOpenEnded = isMinOpenEnded; _isMaxOpenEnded = isMaxOpenEnded; } public int Index { get { return _index; } } public object MinValue { get { return _minValue; } } public object MaxValue { get { return _maxValue; } } public bool IsMinOpenEnded { get { return _isMinOpenEnded; } } public bool IsMaxOpenEnded { get { return _isMaxOpenEnded; } } public string Label { get { if (this.Index == -1) { return StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeRanges.IntRange.Other"); } else if (this.IsMinOpenEnded) { return string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeRanges.IntRange.MinOpenEnded"), this.MaxValue); } else if (this.IsMaxOpenEnded) { return string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeRanges.IntRange.MaxOpenEnded"), this.MinValue); } else { return string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeRanges.IntRange.Closed"), this.MinValue, this.MaxValue); } } } public object DefaultValue { get { return 0; } } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/FolderRanges/IntFolderRanges.cs ================================================ using System.Linq; using System.Linq.Expressions; using Composite.Core.Linq; namespace Composite.C1Console.Trees.Foundation.FolderRanges { internal sealed class IntFolderRanges : BaseFolderRanges { public override Expression CreateContainsListSelectBodyExpression(Expression fieldExpression, ParameterExpression parameterExpression) { Expression currentExpression = null; foreach (IFolderRange folderRange in this.Ranges) { int minValue = (int)folderRange.MinValue; int maxValue = (int)folderRange.MaxValue; if (currentExpression == null) { currentExpression = Expression.Constant(-1); } Expression minExpression = Expression.GreaterThanOrEqual( fieldExpression, Expression.Constant(minValue) ); Expression maxExpression = Expression.LessThanOrEqual( fieldExpression, Expression.Constant(maxValue) ); if (folderRange.IsMinOpenEnded) { currentExpression = Expression.Condition( maxExpression, Expression.Constant(folderRange.Index), currentExpression ); } else if (folderRange.IsMaxOpenEnded) { currentExpression = Expression.Condition( minExpression, Expression.Constant(folderRange.Index), currentExpression ); } else { currentExpression = Expression.Condition( Expression.AndAlso( minExpression, maxExpression ), Expression.Constant(folderRange.Index), currentExpression ); } } return currentExpression; } public override Expression CreateFilterExpression(int folderRangeIndex, Expression fieldExpression) { if (folderRangeIndex != -1) { IFolderRange folderRange = this.GetFolderRange(folderRangeIndex); int minValue = (int)folderRange.MinValue; int maxValue = (int)folderRange.MaxValue; Expression minExpression = Expression.GreaterThanOrEqual( fieldExpression, Expression.Constant(minValue) ); Expression maxExpression = Expression.LessThanOrEqual( fieldExpression, Expression.Constant(maxValue) ); Expression expression; if (folderRange.IsMinOpenEnded) { expression = maxExpression; } else if (folderRange.IsMaxOpenEnded) { expression = minExpression; } else { expression = Expression.And(minExpression, maxExpression); } return expression; } else { Expression currentExpression = null; foreach (IFolderRange folderRange in this.Ranges.Where(f => f.Index != -1)) { int minValue = (int)folderRange.MinValue; int maxValue = (int)folderRange.MaxValue; Expression minExpression = Expression.GreaterThanOrEqual( fieldExpression, Expression.Constant(minValue) ); Expression maxExpression = Expression.LessThanOrEqual( fieldExpression, Expression.Constant(maxValue) ); if (folderRange.IsMinOpenEnded) { currentExpression = currentExpression.NestedAnd(Expression.Not(maxExpression)); } else if (folderRange.IsMaxOpenEnded) { currentExpression = currentExpression.NestedAnd(Expression.Not(minExpression)); } else { currentExpression = currentExpression.NestedAnd( Expression.Not( Expression.And( minExpression, maxExpression ) ) ); } } return currentExpression; } } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/FolderRanges/StringFolderRange.cs ================================================ using System.Diagnostics; using Composite.Core.ResourceSystem; namespace Composite.C1Console.Trees.Foundation.FolderRanges { [DebuggerDisplay("{Index} : ({MinValue}-{MaxValue}) : {Label}")] internal sealed class StringFolderRange : IFolderRange { private int _index; private string _minValue; private string _maxValue; private bool _isMinOpenEnded; private bool _isMaxOpenEnded; public StringFolderRange(int index, string minValue, string maxValue, bool isMinOpenEnded, bool isMaxOpenEnded) { _index = index; _minValue = minValue; _maxValue = maxValue; _isMinOpenEnded = isMinOpenEnded; _isMaxOpenEnded = isMaxOpenEnded; } public int Index { get { return _index; } } public object MinValue { get { return _minValue; } } public object MaxValue { get { return _maxValue; } } public bool IsMinOpenEnded { get { return _isMinOpenEnded; } } public bool IsMaxOpenEnded { get { return _isMaxOpenEnded; } } public string Label { get { if (this.Index == -1) { return StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeRanges.StringRange.Other"); } else if (this.IsMinOpenEnded) { return string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeRanges.StringRange.MinOpenEnded"), this.MaxValue); } else if (this.IsMaxOpenEnded) { return string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeRanges.StringRange.MaxOpenEnded"), this.MinValue); } else { return string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeRanges.StringRange.Closed"), this.MinValue, this.MaxValue); } } } public object DefaultValue { get { return ""; } } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/FolderRanges/StringFolderRanges.cs ================================================ using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Core.Linq; namespace Composite.C1Console.Trees.Foundation.FolderRanges { internal sealed class StringFolderRanges : BaseFolderRanges { private readonly MethodInfo StringCompare_MethodInfo = typeof(string).GetMethods().First(f => f.Name == "Compare"); private readonly MethodInfo StringToUpper_MethodInfo = typeof(string).GetMethods().First(f => f.Name == "ToUpper"); private readonly MethodInfo StringStartsWith_MethodInfo = typeof(string).GetMethods().First(f => f.Name == "StartsWith"); public override Expression CreateContainsListSelectBodyExpression(Expression fieldExpression, ParameterExpression parameterExpression) { Expression currentExpression = null; foreach (IFolderRange folderRange in this.Ranges) { string minValue = GetMinValue(folderRange); string maxValue = GetMaxValue(folderRange); if (currentExpression == null) { currentExpression = Expression.Constant(-1); } var fieldToUpper = Expression.Call(fieldExpression, this.StringToUpper_MethodInfo); currentExpression = Expression.Condition( Expression.AndAlso( Expression.NotEqual( fieldExpression, Expression.Constant(null, typeof(string)) ), Expression.AndAlso( Expression.GreaterThanOrEqual( Expression.Call( this.StringCompare_MethodInfo, fieldToUpper, Expression.Constant(minValue.ToUpperInvariant()) ), Expression.Constant(0) ), Expression.OrElse( Expression.LessThanOrEqual( Expression.Call( this.StringCompare_MethodInfo, fieldToUpper, Expression.Constant(maxValue.ToUpperInvariant()) ), Expression.Constant(0) ), Expression.Call(fieldToUpper, StringStartsWith_MethodInfo, Expression.Constant(maxValue.ToUpperInvariant())) ) ) ), Expression.Constant(folderRange.Index), currentExpression ); } return currentExpression; } public override Expression CreateFilterExpression(int folderRangeIndex, Expression fieldExpression) { if (folderRangeIndex != -1) { IFolderRange folderRange = this.GetFolderRange(folderRangeIndex); return CreateFolderRangeExpression(folderRange, fieldExpression); } Expression currentExpression = null; foreach (IFolderRange folderRange in this.Ranges.Where(f => f.Index != -1)) { Expression expression = CreateFolderRangeExpression(folderRange, fieldExpression); expression = Expression.Not(expression); currentExpression = currentExpression.NestedAnd(expression); } return currentExpression; } private Expression CreateFolderRangeExpression(IFolderRange folderRange, Expression fieldExpression) { string minValue = GetMinValue(folderRange); string maxValue = GetMaxValue(folderRange); var fieldToUpper = Expression.Call(fieldExpression, this.StringToUpper_MethodInfo); Expression expression = Expression.AndAlso( Expression.NotEqual( fieldExpression, Expression.Constant(null, typeof(string)) ), Expression.AndAlso( Expression.GreaterThanOrEqual( Expression.Call( this.StringCompare_MethodInfo, fieldToUpper, Expression.Constant(minValue.ToUpperInvariant()) ), Expression.Constant(0) ), Expression.OrElse( Expression.LessThanOrEqual( Expression.Call( this.StringCompare_MethodInfo, fieldToUpper, Expression.Constant(maxValue.ToUpperInvariant()) ), Expression.Constant(0) ), Expression.Call(fieldToUpper, StringStartsWith_MethodInfo, Expression.Constant(maxValue.ToUpperInvariant())) ) ) ); return expression; } private static string GetMinValue(IFolderRange folderRange) { if (folderRange.IsMinOpenEnded) { return "" + (char.MinValue + 1) + (char.MinValue + 1) + (char.MinValue + 1); } return (string) folderRange.MinValue; } private static string GetMaxValue(IFolderRange folderRange) { if (folderRange.IsMaxOpenEnded) { return "" + char.MaxValue + char.MaxValue + char.MaxValue; } return (string) folderRange.MaxValue; } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/OrderByNodeCreatorFactory.cs ================================================ using System; using System.Xml.Linq; using Composite.Core.Xml; namespace Composite.C1Console.Trees.Foundation { internal static class OrderByNodeCreatorFactory { public static OrderByNode CreateOrderByNode(XElement element, Tree tree) { if (element.Name == TreeMarkupConstants.Namespace + "Field") { XAttribute nameAttribute = element.Attribute("FieldName"); XAttribute directionAttribute = element.Attribute("Direction"); if (nameAttribute == null) { tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.MissingAttribute", "FieldName"); return null; } return new FieldOrderByNode { XPath = element.GetXPath(), FieldName = nameAttribute.Value, Direction = directionAttribute.GetValueOrDefault("ascending") }; } else { throw new InvalidOperationException(string.Format("OrderBy node {0} not supported", element.Name)); } } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/StringConstants.cs ================================================  namespace Composite.C1Console.Trees.Foundation { internal static class StringConstants { public const string RootNodeId = "RootTreeNode"; public const string PiggybagTreeId = "TreeId"; public const string PiggybagSharedTreeId = "SharedTreeId_"; } } ================================================ FILE: Composite/C1Console/Trees/Foundation/TreeBuilder.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementAttachingProvider; using Composite.C1Console.Trees.Foundation.AttachmentPoints; using Composite.Core.IO; using Composite.Core.Types; using Composite.Core.Xml; namespace Composite.C1Console.Trees.Foundation { internal static class TreeBuilder { public static Tree BuildTree(string treeId, XDocument document) { Tree tree = new Tree(treeId); tree.BuildProcessContext = new BuildProcessContext(); tree.BuildResult = new BuildResult(); if (ValidateMarkup(tree, document) == false) return tree; try { BuildAutoAttachmentPoints(tree, document); BuildAllowedAttachmentPoints(tree, document); XElement elementRootElement = document.Descendants(TreeMarkupConstants.Namespace + "ElementRoot").Single(); tree.RootTreeNode = BuildInnerTree(elementRootElement, null, tree); if ((tree.AttachmentPoints.OfType().Any()) && (tree.RootTreeNode.ChildNodes.Any())) { // Only simple tree nodes allowed if data item attaching is done tree.AddValidationError("", "TreeValidationError.DataAttachments.NoElementsAllowed"); } if (tree.BuildResult.ValidationErrors.Count() == 0) { tree.RootTreeNode.Initialize(); } } catch (Exception ex) { tree.AddValidationError("", "TreeValidationError.Common.UnknownException", ex.Message); } return tree; } private static bool ValidateMarkup(Tree tree, XDocument document) { try { if (document.Root == null) { tree.AddValidationError("", "TreeValidationError.Markup.NoRootElement"); return false; } bool schemaValidationResult = true; Action onValidationError = (obj, args) => { tree.AddValidationError("", "TreeValidationError.Markup.SchemaError", args.Message, args.Exception.LineNumber, args.Exception.LinePosition); schemaValidationResult = false; }; XDocument schemaDocument = XDocumentUtils.Load(Path.Combine(PathUtil.Resolve("~/Composite/schemas/Trees"), "Tree.xsd")); IEnumerable elements = schemaDocument.Descendants((XNamespace)"http://www.w3.org/2001/XMLSchema" + "import").ToList(); foreach (XElement element in elements) { element.Remove(); } XmlReaderSettings xmlReaderSettings = new XmlReaderSettings(); xmlReaderSettings.ValidationType = ValidationType.Schema; using (XmlReader schemaReader = schemaDocument.CreateReader()) { xmlReaderSettings.Schemas.Add(null, schemaReader); } xmlReaderSettings.Schemas.AddFromPath(null, Path.Combine(PathUtil.Resolve("~/Composite/schemas/Functions"), "Function.xsd")); //xmlReaderSettings.Schemas.AddFromPath(null, Path.Combine(PathUtil.Resolve("~/Composite/schemas/Trees"), "Tree.xsd")); xmlReaderSettings.ValidationEventHandler += new ValidationEventHandler(onValidationError); xmlReaderSettings.ValidationFlags = XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ReportValidationWarnings; XmlReader xmlReader = XmlReader.Create(new StringReader(document.ToString()), xmlReaderSettings); while (xmlReader.Read()) ; if (schemaValidationResult == false) { return false; } } catch (Exception ex) { tree.AddValidationError("", "TreeValidationError.Common.UnknownException", ex.Message); return false; } return true; } private static void BuildAutoAttachmentPoints(Tree tree, XDocument document) { XElement element = document.Root.Elements(TreeMarkupConstants.Namespace + "ElementStructure.AutoAttachments").SingleOrDefault(); if (element == null) return; IEnumerable namedAttachmentPoints = BuildNamedAttachmentPoints(tree, element, () => new NamedAttachmentPoint()); tree.AttachmentPoints.AddRange(namedAttachmentPoints.Cast()); IEnumerable dataItemAttachmentPoint = BuildDataItemPoints(tree, element, () => new DataItemAttachmentPoint()); tree.AttachmentPoints.AddRange(dataItemAttachmentPoint.Cast()); } private static void BuildAllowedAttachmentPoints(Tree tree, XDocument document) { XElement element = document.Root.Elements(TreeMarkupConstants.Namespace + "ElementStructure.AllowedAttachments").SingleOrDefault(); if (element == null) return; XAttribute applicationNameAttribute = element.Attribute("ApplicationName"); if (applicationNameAttribute != null) { tree.AllowedAttachmentApplicationName = applicationNameAttribute.Value; } else { tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.MissingAttribute", "ApplicationName"); return; } //This is just illustrating the generic way of handling these things. Please leave this commet /MRJ //IEnumerable namedAttachmentPoints = BuildNamedAttachmentPoints(tree, element, () => new NamedPossibleAttachmentPoint()); //tree.PossibleAttachmentPoints.AddRange(namedAttachmentPoints.Cast()); IEnumerable namedAttachmentPoints = BuildDataItemPoints(tree, element, () => new DataItemPossibleAttachmentPoint()); tree.PossibleAttachmentPoints.AddRange(namedAttachmentPoints.Cast()); } private static IEnumerable BuildNamedAttachmentPoints(Tree tree, XElement containerElement, Func namedAttachmentPointFactory) { IEnumerable namedElements = containerElement.Elements(TreeMarkupConstants.Namespace + "NamedParent"); foreach (XElement namedElement in namedElements) { XAttribute nameAttribute = namedElement.Attribute("Name"); if (nameAttribute == null) { tree.AddValidationError(namedElement.GetXPath(), "TreeValidationError.Common.MissingAttribute", "Name"); yield break; } AttachingPoint attachingPoint; switch (nameAttribute.Value) { case "PerspectivesRoot": attachingPoint = AttachingPoint.PerspectivesRoot; break; case "Content": attachingPoint = AttachingPoint.ContentPerspective; break; case "Content.WebsiteItems": attachingPoint = AttachingPoint.ContentPerspectiveWebsiteItems; break; case "Data": attachingPoint = AttachingPoint.DataPerspective; break; case "Layout": attachingPoint = AttachingPoint.DesignPerspective; break; case "Media": attachingPoint = AttachingPoint.MediaPerspective; break; case "Function": attachingPoint = AttachingPoint.FunctionPerspective; break; case "System": attachingPoint = AttachingPoint.SystemPerspective; break; case null: case "": tree.AddValidationError(nameAttribute.GetXPath(), "TreeValidationError.AutoAttachments.UnknownAttachmentPoint", nameAttribute.Value); attachingPoint = null; break; default: attachingPoint = AttachingPoint.VirtualElementAttachingPoint(nameAttribute.Value); break; } if (attachingPoint == null) yield break; INamedAttachmentPoint namedAttachmentPoint = namedAttachmentPointFactory(); namedAttachmentPoint.AttachingPoint = attachingPoint; namedAttachmentPoint.Position = GetPosition(tree, namedElement); yield return namedAttachmentPoint; } } private static IEnumerable BuildDataItemPoints(Tree tree, XElement containerElement, Func dataItemAttachmentPointFactory) { IEnumerable dataTypeElements = containerElement.Elements(TreeMarkupConstants.Namespace + "DataType"); foreach (XElement dataTypeElement in dataTypeElements) { XAttribute typeAttribute = dataTypeElement.Attribute("Type"); XAttribute positionAttribute = dataTypeElement.Attribute("Position"); if (typeAttribute == null) { tree.AddValidationError(dataTypeElement.GetXPath(), "TreeValidationError.Common.MissingAttribute", "Type"); continue; } Type interfaceType = TypeManager.TryGetType(typeAttribute.Value); if (interfaceType == null) { tree.AddValidationError(dataTypeElement.GetXPath(), "TreeValidationError.Common.UnknownInterfaceType", typeAttribute.Value); continue; } IDataItemAttachmentPoint dataItemAttachmentPoint = dataItemAttachmentPointFactory(); dataItemAttachmentPoint.InterfaceType = interfaceType; dataItemAttachmentPoint.Position = GetPosition(tree, dataTypeElement); yield return dataItemAttachmentPoint; } } private static ElementAttachingProviderPosition GetPosition(Tree tree, XElement namedElement) { XAttribute positionAttribute = namedElement.Attribute("Position"); string position = positionAttribute.GetValueOrDefault("Top"); switch (position) { case "Top": return ElementAttachingProviderPosition.Top; case "Bottom": return ElementAttachingProviderPosition.Bottom; default: tree.AddValidationError(positionAttribute.GetXPath(), "TreeValidationError.AutoAttachments.UnknownAttachmentPosition", position); return ElementAttachingProviderPosition.Top;; } } private static TreeNode BuildInnerTree(XElement element, TreeNode parentNode, Tree tree) { TreeNode treeNode = TreeNodeCreatorFactory.CreateTreeNode(element, tree); if (treeNode == null) return null; // Actions XElement actionsElement = element.Element(TreeMarkupConstants.Namespace + "Actions"); if (actionsElement != null) { foreach (XElement actionElement in actionsElement.Elements()) { ActionNode actionNode = ActionNodeCreatorFactory.CreateActionNode(actionElement, tree); if (actionNode != null) { treeNode.AddActionNode(actionNode); } } } // OrderBys XElement orderBysElement = element.Element(TreeMarkupConstants.Namespace + "OrderBy"); if (orderBysElement != null) { foreach (XElement orderByElement in orderBysElement.Elements()) { OrderByNode orderByNode = OrderByNodeCreatorFactory.CreateOrderByNode(orderByElement, tree); if (orderByNode != null) { treeNode.AddOrderByNode(orderByNode); } } } // Filters XElement filtersElement = element.Element(TreeMarkupConstants.Namespace + "Filters"); if (filtersElement != null) { foreach (XElement filterElement in filtersElement.Elements()) { FilterNode filterNode = FilterNodeCreatorFactory.CreateFilterNode(filterElement, tree); if (filterNode != null) { treeNode.AddFilterNode(filterNode); } } } if (parentNode != null) { parentNode.AddChildTreeNode(treeNode); } // Children XElement childrenElement = element.Element(TreeMarkupConstants.Namespace + "Children"); if (childrenElement != null) { foreach (XElement childElement in childrenElement.Elements()) { BuildInnerTree(childElement, treeNode, tree); } } treeNode.InitializeActions(); treeNode.InitializeOrderByes(); treeNode.InitializeFilters(); return treeNode; } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/TreeException.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Core.ResourceSystem; namespace Composite.C1Console.Trees.Foundation { internal class TreeException : Exception { public static TreeException CreateException(string stringName, params object[] args) { string resourceString = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", stringName); string message = string.Format(resourceString, args); return new TreeException(message); } public TreeException(string message) : base(message) { } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/TreeNodeCreatorFactory.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Xml.Linq; using Composite.Functions.Foundation; using Composite.Core.ResourceSystem; using Composite.Core.Types; using Composite.Core.Xml; using Composite.C1Console.Trees.Foundation.AttachmentPoints; namespace Composite.C1Console.Trees.Foundation { internal static class TreeNodeCreatorFactory { private static readonly string DefaultFolderResourceName = "folder"; private static readonly string DefaultOpenedFolderResourceName = "folder-open"; private static readonly string DefaultDataGroupingFolderResourceName = "folder"; public static TreeNode CreateTreeNode(XElement element, Tree tree) { if (element.Name == TreeMarkupConstants.Namespace + "ElementRoot") { return BuildRootTreeNode(element, tree); } if (element.Name == TreeMarkupConstants.Namespace + "Element") { return BuildSimpleElementTreeNode(element, tree); } if (element.Name == TreeMarkupConstants.Namespace + "FunctionElementGenerator") { return BuildFunctionElementGeneratorTreeNode(element, tree); } if (element.Name == TreeMarkupConstants.Namespace + "DataElements") { return BuildDataElementsTreeNode(element, tree); } if (element.Name == TreeMarkupConstants.Namespace + "DataFolderElements") { return BuildDataFolderElementsTreeNode(element, tree); } tree.AddValidationError(element, "TreeValidationError.Common.UnknownElement", element.Name); return null; } private static TreeNode BuildDataFolderElementsTreeNode(XElement element, Tree tree) { XAttribute typeAttribute = element.Attribute("Type"); XAttribute fieldGroupingNameAttribute = element.Attribute("FieldGroupingName"); XAttribute dateFormatAttribute = element.Attribute("DateFormat"); XAttribute iconAttribute = element.Attribute("Icon"); XAttribute rangeAttribute = element.Attribute("Range"); XAttribute firstLetterOnlyAttribute = element.Attribute("FirstLetterOnly"); XAttribute showForeignItemsAttribute = element.Attribute("ShowForeignItems"); XAttribute leafDisplayAttribute = element.Attribute("Display"); XAttribute sortDirectionAttribute = element.Attribute("SortDirection"); if (fieldGroupingNameAttribute == null) { tree.AddValidationError(element, "TreeValidationError.Common.MissingAttribute", "FieldGroupingName"); return null; } Type interfaceType = null; if (typeAttribute != null) { interfaceType = TypeManager.TryGetType(typeAttribute.Value); if (interfaceType == null) { tree.AddValidationError(element, "TreeValidationError.Common.UnknownInterfaceType", typeAttribute.Value); return null; } } bool firstLetterOnly = false; if (firstLetterOnlyAttribute != null) { if (!firstLetterOnlyAttribute.TryGetBoolValue(out firstLetterOnly)) { tree.AddValidationError(element, "TreeValidationError.Common.WrongAttributeValue", "FirstLetterOnly"); } } LeafDisplayMode leafDisplay = LeafDisplayModeHelper.ParseDisplayMode(leafDisplayAttribute, tree); SortDirection sortDirection = ParseSortDirection(sortDirectionAttribute, tree); return new DataFolderElementsTreeNode { Tree = tree, Id = tree.BuildProcessContext.CreateNewNodeId(), InterfaceType = interfaceType, Icon = FactoryHelper.GetIcon(iconAttribute.GetValueOrDefault(DefaultDataGroupingFolderResourceName)), FieldName = fieldGroupingNameAttribute.Value, DateFormat = dateFormatAttribute.GetValueOrDefault(null), Range = rangeAttribute.GetValueOrDefault(null), FirstLetterOnly = firstLetterOnly, ShowForeignItems = showForeignItemsAttribute.GetValueOrDefault("true").ToLowerInvariant() == "true", Display = leafDisplay, SortDirection = sortDirection }; } public static SortDirection ParseSortDirection(XAttribute attribute, Tree tree) { if (attribute != null) { SortDirection parsedValue; if (Enum.TryParse(attribute.Value, out parsedValue)) { return parsedValue; } tree.AddValidationError(attribute, "TreeValidationError.Common.WrongAttributeValue", attribute.Value); } return SortDirection.Ascending; } private static TreeNode BuildDataElementsTreeNode(XElement element, Tree tree) { XAttribute typeAttribute = element.Attribute("Type"); XAttribute labelAttribute = element.Attribute("Label"); XAttribute toolTipAttribute = element.Attribute("ToolTip"); XAttribute iconAttribute = element.Attribute("Icon"); XAttribute openedIconAttribute = element.Attribute("OpenedIcon"); XAttribute showForeignItemsAttribute = element.Attribute("ShowForeignItems"); XAttribute leafDisplayAttribute = element.Attribute("Display"); XAttribute browserUrlAttribute = element.Attribute("BrowserUrl"); XAttribute browserImagelAttribute = element.Attribute("BrowserImage"); if (typeAttribute == null) { tree.AddValidationError(element, "TreeValidationError.Common.MissingAttribute", "Type"); return null; } Type interfaceType = TypeManager.TryGetType(typeAttribute.Value); if (interfaceType == null) { tree.AddValidationError(element, "TreeValidationError.Common.UnknownInterfaceType", typeAttribute.Value); return null; } LeafDisplayMode leafDisplay = LeafDisplayModeHelper.ParseDisplayMode(leafDisplayAttribute, tree); ResourceHandle icon = null; if (iconAttribute != null) icon = FactoryHelper.GetIcon(iconAttribute.Value); ResourceHandle openedIcon = null; if (icon != null && openedIconAttribute == null) openedIcon = icon; else if (openedIconAttribute != null) openedIcon = FactoryHelper.GetIcon(openedIconAttribute.Value); var dataElementsTreeNode = new DataElementsTreeNode { Tree = tree, Id = tree.BuildProcessContext.CreateNewNodeId(), InterfaceType = interfaceType, Label = labelAttribute.GetValueOrDefault(null), ToolTip = toolTipAttribute.GetValueOrDefault(null), Icon = icon, OpenedIcon = openedIcon, ShowForeignItems = showForeignItemsAttribute.GetValueOrDefault("true").ToLowerInvariant() == "true", Display = leafDisplay, BrowserUrl = browserUrlAttribute.GetValueOrDefault(null), BrowserImage = browserImagelAttribute.GetValueOrDefault(null), }; List treeNodes; if (tree.BuildProcessContext.DataInteraceToTreeNodes.TryGetValue(interfaceType, out treeNodes) == false) { treeNodes = new List(); tree.BuildProcessContext.DataInteraceToTreeNodes.Add(interfaceType, treeNodes); } treeNodes.Add(dataElementsTreeNode); return dataElementsTreeNode; } private static TreeNode BuildFunctionElementGeneratorTreeNode(XElement element, Tree tree) { XAttribute labelAttribute = element.Attribute("Label"); XAttribute toolTipAttribute = element.Attribute("ToolTip"); XAttribute iconAttribute = element.Attribute("Icon"); XElement functionMarkupContainerElement = element.Element(TreeMarkupConstants.Namespace + "FunctionMarkup"); if (functionMarkupContainerElement == null) { //MRJ: DSLTree: FunctionElementGeneratorTreeNode: Validation error } XElement functionMarkupElement = functionMarkupContainerElement.Element((XNamespace) FunctionTreeConfigurationNames.NamespaceName + FunctionTreeConfigurationNames.FunctionTagName); if (functionMarkupElement == null) { //MRJ: DSLTree: FunctionElementGeneratorTreeNode: Validation error } if (labelAttribute == null) { tree.AddValidationError(element, "TreeValidationError.Common.MissingAttribute", "Label"); return null; } return new FunctionElementGeneratorTreeNode { Tree = tree, Id = tree.BuildProcessContext.CreateNewNodeId(), FunctionMarkup = functionMarkupElement, Label = labelAttribute.Value, ToolTip = toolTipAttribute.GetValueOrDefault(labelAttribute.Value), Icon = FactoryHelper.GetIcon(iconAttribute.GetValueOrDefault(DefaultFolderResourceName)) }; } private static TreeNode BuildSimpleElementTreeNode(XElement element, Tree tree) { XAttribute idAttribute = element.Attribute("Id"); XAttribute labelAttribute = element.Attribute("Label"); XAttribute toolTipAttribute = element.Attribute("ToolTip"); XAttribute iconAttribute = element.Attribute("Icon"); XAttribute openedIconAttribute = element.Attribute("OpenedIcon"); XAttribute browserUrlAttribute = element.Attribute("BrowserUrl"); XAttribute browserImageAttribute = element.Attribute("BrowserImage"); if (idAttribute == null) { tree.AddValidationError(element, "TreeValidationError.Common.MissingAttribute", "Id"); return null; } if (idAttribute.Value == "" || idAttribute.Value == "RootTreeNode" || idAttribute.Value.StartsWith("NodeAutoId_")) { tree.AddValidationError(idAttribute, "TreeValidationError.SimpleElement.WrongIdValue"); } else if (tree.BuildProcessContext.AlreadyUsed(idAttribute.Value)) { tree.AddValidationError(idAttribute, "TreeValidationError.SimpleElement.AlreadyUsedId", idAttribute.Value); } else { tree.BuildProcessContext.AddUsedId(idAttribute.Value); } if (labelAttribute == null) { tree.AddValidationError(element, "TreeValidationError.Common.MissingAttribute", "Label"); return null; } ResourceHandle icon = FactoryHelper.GetIcon(iconAttribute.GetValueOrDefault(DefaultFolderResourceName)); ResourceHandle openedIcon = FactoryHelper.GetIcon(openedIconAttribute.GetValueOrDefault(DefaultOpenedFolderResourceName)); if (iconAttribute != null && openedIconAttribute == null) { openedIcon = icon; } return new SimpleElementTreeNode { Tree = tree, Id = idAttribute.Value, Label = labelAttribute.Value, ToolTip = toolTipAttribute.GetValueOrDefault(labelAttribute.Value), Icon = icon, OpenIcon = openedIcon, BrowserUrl = browserUrlAttribute.GetValueOrDefault(null), BrowserImage = browserImageAttribute.GetValueOrDefault(null) }; } private static TreeNode BuildRootTreeNode(XElement element, Tree tree) { XAttribute shareRootElementByIdAttribute = element.Attribute("ShareRootElementById"); if (shareRootElementByIdAttribute != null) { tree.ShareRootElementById = (bool) shareRootElementByIdAttribute; if (tree.ShareRootElementById) { int count = tree.AttachmentPoints.OfType().Count(); if (count != 1 || tree.AttachmentPoints.Count > count) { tree.AddValidationError(shareRootElementByIdAttribute, "TreeValidationError.ElementRoot.ShareRootElementByIdNotAllowed"); } } } return new RootTreeNode { Tree = tree, Id = tree.BuildProcessContext.CreateNewNodeId() }; } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/TreePerspectiveEntityToken.cs ================================================ using Composite.C1Console.Security; using Composite.Core.Serialization; using Composite.Core; using Newtonsoft.Json; namespace Composite.C1Console.Trees.Foundation { /// [SecurityAncestorProvider(typeof(Composite.C1Console.Security.SecurityAncestorProviders.NoAncestorSecurityAncestorProvider))] public class TreePerspectiveEntityToken : EntityToken { /// [JsonConstructor] public TreePerspectiveEntityToken(string id) { Id = id; } /// public override string Id { get; } /// [JsonIgnore] public override string Type => "C1Trees"; /// [JsonIgnore] public override string Source => "C1Trees"; /// public override string Serialize() => CompositeJsonSerializer.Serialize(this); /// public static EntityToken Deserialize(string serializedEntityToken) { EntityToken entityToken; if (CompositeJsonSerializer.IsJsonSerialized(serializedEntityToken)) { entityToken = CompositeJsonSerializer.Deserialize(serializedEntityToken); } else { entityToken = DeserializeLegacy(serializedEntityToken); Log.LogVerbose(nameof(TreePerspectiveEntityToken), entityToken.GetType().FullName); } return entityToken; } /// public static EntityToken DeserializeLegacy(string serializedEntityToken) { return new TreePerspectiveEntityToken(serializedEntityToken); } } } ================================================ FILE: Composite/C1Console/Trees/Foundation/TupleIndexer.cs ================================================ using System; namespace Composite.C1Console.Trees.Foundation { internal sealed class TupleIndexer { private dynamic _tuple; public TupleIndexer(dynamic tuple) { _tuple = tuple; } public int this[int index] { get { if (index == 1) return (int)_tuple.Item1; else if (index == 2) return (int)_tuple.Item2; else if (index == 3) return (int)_tuple.Item3; else if (index == 4) return (int)_tuple.Item4; else if (index == 5) return (int)_tuple.Item5; else if (index == 6) return (int)_tuple.Item6; else if (index == 7) return (int)_tuple.Item7; else if (index == 8) return (int)_tuple.Item8; else throw new IndexOutOfRangeException(); } } public object GetAtIndex(int index) { if (index == 1) return _tuple.Item1; else if (index == 2) return _tuple.Item2; else if (index == 3) return _tuple.Item3; else if (index == 4) return _tuple.Item4; else if (index == 5) return _tuple.Item5; else if (index == 6) return _tuple.Item6; else if (index == 7) return _tuple.Item7; else if (index == 8) return _tuple.Item8; else throw new IndexOutOfRangeException(); } } } ================================================ FILE: Composite/C1Console/Trees/FunctionElementGeneratorTreeNode.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.C1Console.Security; using Composite.C1Console.Elements; using Composite.Core.ResourceSystem; using System.Xml.Linq; using Composite.Functions; namespace Composite.C1Console.Trees { internal sealed class FunctionElementGeneratorTreeNode : TreeNode { public XElement FunctionMarkup { get; internal set; } // Requried public string Label { get; internal set; } // Requried public string ToolTip { get; internal set; } // Defaults to Label public ResourceHandle Icon { get; internal set; } // Defaults to 'folder' // Cached private BaseRuntimeTreeNode _functionNode; private IEnumerable> GetFunctionResult() { return _functionNode.GetValue>>(); } public override IEnumerable GetEntityTokens(EntityToken childEntityToken, TreeNodeDynamicContext dynamicContext) { IEntityTokenContainingParentEntityToken containingParentEnitytToken = childEntityToken as IEntityTokenContainingParentEntityToken; if (containingParentEnitytToken != null) { childEntityToken = containingParentEnitytToken.GetParentEntityToken(); } foreach (EntityToken entityToken in this.ParentNode.GetEntityTokens(childEntityToken, dynamicContext)) { foreach (var kvp in GetFunctionResult()) { yield return new TreeFunctionElementGeneratorEntityToken(this.Id, this.Tree.TreeId, EntityTokenSerializer.Serialize(entityToken), kvp.Key); } } } public override AncestorResult GetParentEntityToken(EntityToken ownEntityToken, Type parentInterfaceOfInterest, TreeNodeDynamicContext dynamicContext) { return new AncestorResult(this.ParentNode, ((TreeFunctionElementGeneratorEntityToken)ownEntityToken).ParentEntityToken); } protected override IEnumerable OnGetElements(EntityToken parentEntityToken, TreeNodeDynamicContext dynamicContext) { foreach (var kvp in GetFunctionResult()) { Element element = new Element(new ElementHandle( dynamicContext.ElementProviderName, new TreeFunctionElementGeneratorEntityToken(this.Id.ToString(), this.Tree.TreeId, EntityTokenSerializer.Serialize(parentEntityToken), kvp.Key), dynamicContext.Piggybag.PreparePiggybag(this.ParentNode, parentEntityToken) )); element.VisualData = new ElementVisualizedData { Label = kvp.Value, ToolTip = kvp.Value, HasChildren = ChildNodes.Count() > 0, Icon = Core.ResourceSystem.ResourceHandle.BuildIconFromDefaultProvider("folder"), OpenedIcon = Core.ResourceSystem.ResourceHandle.BuildIconFromDefaultProvider("folder") }; yield return element; } } protected override void OnInitialize() { //MRJ: DSLTree: FunctionElementGeneratorTreeNode: More validaion here //MRJ: DSLTree: FunctionElementGeneratorTreeNode: What kind of return type should the function have? _functionNode = FunctionTreeBuilder.Build(this.FunctionMarkup); } public override string ToString() { return string.Format("FunctionElementGeneratorTreeNode, Id = {0}, Label = {1}", this.Id, this.Label); } } } ================================================ FILE: Composite/C1Console/Trees/FunctionFilterNode.cs ================================================ using System; using System.Linq; using System.Linq.Expressions; using System.Xml.Linq; using Composite.Data; using Composite.Functions; using Composite.Core; using Composite.Core.ResourceSystem; namespace Composite.C1Console.Trees { internal sealed class FunctionFilterNode : FilterNode { public XElement FunctionMarkup { get; set; } // Required private AttributeDynamicValuesHelper FunctionMarkupDynamicValuesHelper { get; set; } public override Expression CreateDownwardsFilterExpression(ParameterExpression parameterExpression, TreeNodeDynamicContext dynamicContext) { var replaceContext = new DynamicValuesHelperReplaceContext(dynamicContext.CurrentEntityToken, dynamicContext.Piggybag); XElement markup = this.FunctionMarkupDynamicValuesHelper.ReplaceValues(replaceContext); BaseRuntimeTreeNode baseRuntimeTreeNode = FunctionTreeBuilder.Build(markup); LambdaExpression expression = GetLambdaExpression(baseRuntimeTreeNode); if (expression.Parameters.Count != 1) { throw new InvalidOperationException("Only 1 parameter lamdas supported when calling function: " + markup); } ParameterChangerExpressionVisitor expressionVisitor = new ParameterChangerExpressionVisitor(expression.Parameters.Single(), parameterExpression); Expression resultExpression = expressionVisitor.Visit(expression.Body); return resultExpression; } public override Expression CreateUpwardsFilterExpression(ParameterExpression parameterExpression, TreeNodeDynamicContext dynamicContext) { DataEntityToken currentEntityToken = dynamicContext.CurrentEntityToken as DataEntityToken; IData filteredDataItem = null; Func upwardsFilter = dataItem => { var ancestorEntityToken = dataItem.GetDataEntityToken(); var replaceContext = new DynamicValuesHelperReplaceContext { CurrentDataItem = dataItem, CurrentEntityToken = ancestorEntityToken, PiggybagDataFinder = new PiggybagDataFinder(dynamicContext.Piggybag, ancestorEntityToken) }; XElement markup = this.FunctionMarkupDynamicValuesHelper.ReplaceValues(replaceContext); BaseRuntimeTreeNode baseRuntimeTreeNode = FunctionTreeBuilder.Build(markup); LambdaExpression expression = GetLambdaExpression(baseRuntimeTreeNode); if (expression.Parameters.Count != 1) { throw new InvalidOperationException("Only 1 parameter lamdas supported when calling function: " + markup); } Delegate compiledExpression = expression.Compile(); if (filteredDataItem == null) { filteredDataItem = currentEntityToken.Data; } return (bool)compiledExpression.DynamicInvoke(filteredDataItem); }; return upwardsFilter.Target != null ? Expression.Call(Expression.Constant(upwardsFilter.Target), upwardsFilter.Method, parameterExpression) : Expression.Call(upwardsFilter.Method, parameterExpression); } internal override void Initialize() { try { FunctionTreeBuilder.Build(this.FunctionMarkup); } catch { AddValidationError("TreeValidationError.FunctionFilter.WrongFunctionMarkup"); return; } this.FunctionMarkupDynamicValuesHelper = new AttributeDynamicValuesHelper(this.FunctionMarkup); this.FunctionMarkupDynamicValuesHelper.Initialize(this.OwnerNode); } private LambdaExpression GetLambdaExpression(BaseRuntimeTreeNode baseRuntimeTreeNode) { LambdaExpression expression = (LambdaExpression)baseRuntimeTreeNode.GetValue(); if (expression == null) { string message = string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeValidationError.FunctionFilter.WrongReturnValue"), string.Format("Expression>", this.OwnerNode.InterfaceType)); Log.LogError("TreeFacade", message); Log.LogError("TreeFacade", "In tree " + this.OwnerNode.Tree.TreeId + " in function " + this.XPath); throw new InvalidOperationException(message); } if (expression.ReturnType != typeof(bool)) { string message = string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeValidationError.FunctionFilter.WrongFunctionReturnType"), expression.ReturnType, typeof(bool)); Log.LogError("TreeFacade", message); Log.LogError("TreeFacade", "In tree " + this.OwnerNode.Tree.TreeId + " in function " + this.XPath); throw new InvalidOperationException(message); } if (expression.Parameters.Count() != 1) { string message = string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeValidationError.FunctionFilter.WrongFunctionParameterCount"), expression.Parameters.Count()); Log.LogError("TreeFacade", message); Log.LogError("TreeFacade", "In tree " + this.OwnerNode.Tree.TreeId + " in function " + this.XPath); throw new InvalidOperationException(message); } ParameterExpression parameterExpression = expression.Parameters.Single(); if (this.OwnerNode.InterfaceType.IsAssignableFrom(parameterExpression.Type) == false) { string message = string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeValidationError.FunctionFilter.WrongFunctionParameterType"), parameterExpression.Type, this.OwnerNode.InterfaceType); Log.LogError("TreeFacade", message); Log.LogError("TreeFacade", "In tree " + this.OwnerNode.Tree.TreeId + " in function " + this.XPath); throw new InvalidOperationException(message); } return expression; } private sealed class ParameterChangerExpressionVisitor : ExpressionVisitor { private readonly ParameterExpression _parameterExpressionToChange; private readonly ParameterExpression _newParameterExpression; public ParameterChangerExpressionVisitor(ParameterExpression parameterExpressionToChange, ParameterExpression newParameterExpression) { _parameterExpressionToChange = parameterExpressionToChange; _newParameterExpression = newParameterExpression; } protected override Expression VisitParameter(ParameterExpression node) { if (node == _parameterExpressionToChange) return _newParameterExpression; return node; } } } } ================================================ FILE: Composite/C1Console/Trees/GenericAddDataActionNode.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Core.Linq; using Composite.Core.Serialization; using Composite.Data; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class GenericAddDataActionNode : ActionNode { /// public Type InterfaceType { get; internal set; } // Requried /// public string CustomFormMarkupPath { get; internal set; } // Optional // Cached private List ParentIdEntries { get; set; } /// protected override void OnAddAction(Action actionAdder, EntityToken entityToken, TreeNodeDynamicContext dynamicContext, DynamicValuesHelperReplaceContext dynamicValuesHelperReplaceContext) { var payload = new StringBuilder(); this.Serialize(payload); if (this.ParentIdEntries.Count > 0) { List entityTokens = dynamicContext.Piggybag.GetParentEntityTokens().ToList(); entityTokens.Reverse(); entityTokens.Add(dynamicContext.CurrentEntityToken); entityTokens.Add(entityToken); entityTokens.Reverse(); foreach (ParentIdEntry parentIdEntry in this.ParentIdEntries) { DataEntityToken dataEntityToken = entityTokens.FindDataEntityToken(parentIdEntry.TargetInterface); if (dataEntityToken == null) continue; IData data = dataEntityToken.Data; object keyValue = parentIdEntry.TargetPropertyInfo.GetValue(data, null); StringConversionServices.SerializeKeyValuePair(payload, parentIdEntry.SourcePropertyName, keyValue); } } StringConversionServices.SerializeKeyValuePair(payload, "_InterfaceType_", InterfaceType); StringConversionServices.SerializeKeyValuePair(payload, "_IconResourceName_", Icon.ResourceName); if (!String.IsNullOrEmpty(CustomFormMarkupPath)) { StringConversionServices.SerializeKeyValuePair(payload, "_CustomFormMarkupPath_", CustomFormMarkupPath); } actionAdder(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Trees.Workflows.GenericAddDataWorkflow"), this.PermissionTypes) { Payload = payload.ToString(), DoIgnoreEntityTokenLocking = true, ExtraPayload = PiggybagSerializer.Serialize(dynamicContext.Piggybag.PreparePiggybag(dynamicContext.CurrentTreeNode, dynamicContext.CurrentEntityToken)) })) { VisualData = CreateActionVisualizedData(dynamicValuesHelperReplaceContext) }); } /// protected override void OnInitialize() { if (this.InterfaceType != null && !typeof(IData).IsAssignableFrom(this.InterfaceType)) { AddValidationError("TreeValidationError.Common.NotImplementingIData", this.InterfaceType, typeof(IData)); } this.ParentIdEntries = new List(); IEnumerable treeNodes = this.OwnerNode.Descendants(true).ToList(); foreach (TreeNode treeNode in treeNodes) { DataFilteringTreeNode dataFilteringTreeNode = treeNode as DataFilteringTreeNode; if (dataFilteringTreeNode == null) continue; IEnumerable parentIdFilterNodes = dataFilteringTreeNode.FilterNodes.OfType().Evaluate(); if (!parentIdFilterNodes.Any()) continue; foreach (ParentIdFilterNode parentIdFilterNode in parentIdFilterNodes) { Type interfaceType = parentIdFilterNode.ParentFilterType; IEnumerable foreignPropertyInfos = DataReferenceFacade.GetForeignKeyProperties(this.InterfaceType, interfaceType); foreach (ForeignPropertyInfo foreignPropertyInfo in foreignPropertyInfos) { var parentIdEntry = new ParentIdEntry( interfaceType, foreignPropertyInfo.TargetKeyPropertyInfo, foreignPropertyInfo.SourcePropertyName ); if (!this.ParentIdEntries.Contains(parentIdEntry)) { this.ParentIdEntries.Add(parentIdEntry); } } } } if (!string.IsNullOrEmpty(this.CustomFormMarkupPath)) { this.CustomFormMarkupPath = LoadAndValidateCustomFormMarkupPath(CustomFormMarkupPath); } } /// public override string ToString() { return $"GenericAddDataActionNode, InterfaceType = {this.InterfaceType}, Label = {this.Label}"; } [DebuggerDisplay("{SourcePropertyName} -> {TargetInterface}")] private sealed class ParentIdEntry { public ParentIdEntry(Type targetInterface, PropertyInfo targetPropertyInfo, string sourcePropertyName) { TargetInterface = targetInterface; TargetPropertyInfo = targetPropertyInfo; SourcePropertyName = sourcePropertyName; } public Type TargetInterface { get; } public PropertyInfo TargetPropertyInfo { get; } public string SourcePropertyName { get; } public override bool Equals(object obj) { return Equals(obj as ParentIdEntry); } private bool Equals(ParentIdEntry parentIdEntry) { if (parentIdEntry == null) return false; return parentIdEntry.TargetInterface == this.TargetInterface && parentIdEntry.TargetPropertyInfo == this.TargetPropertyInfo && parentIdEntry.SourcePropertyName == this.SourcePropertyName; } public override int GetHashCode() { return this.TargetInterface.GetHashCode() ^ this.TargetPropertyInfo.GetHashCode() ^ this.SourcePropertyName.GetHashCode(); } } } } ================================================ FILE: Composite/C1Console/Trees/GenericDeleteDataActionNode.cs ================================================ using System; using Composite.C1Console.Actions.Data; using Composite.C1Console.Elements; using Composite.C1Console.Security; namespace Composite.C1Console.Trees { internal sealed class GenericDeleteDataActionNode : ActionNode { protected override void OnAddAction(Action actionAdder, EntityToken entityToken, TreeNodeDynamicContext dynamicContext, DynamicValuesHelperReplaceContext dynamicValuesHelperReplaceContext) { actionAdder(new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.Delete,this.PermissionTypes))) { VisualData = CreateActionVisualizedData(dynamicValuesHelperReplaceContext) }); } protected override void OnInitialize() { if ((this.OwnerNode is DataElementsTreeNode) == false) { AddValidationError("TreeValidationError.GenericDeleteDataAction.OwnerIsNotDataNode"); } } public override string ToString() { return string.Format("GenericDeleteDataActionNode, Label = {0}", this.Label); } } } ================================================ FILE: Composite/C1Console/Trees/GenericDuplicateDataActionNode.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Xml.Linq; using Composite.C1Console.Actions.Data; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.Core.IO; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.Core.Xml; using Composite.Data; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class GenericDuplicateDataActionNode : ActionNode { /// protected override void OnAddAction(Action actionAdder, EntityToken entityToken, TreeNodeDynamicContext dynamicContext, DynamicValuesHelperReplaceContext dynamicValuesHelperReplaceContext) { Icon = new ResourceHandle(BuildInIconProviderName.ProviderName, "copy"); actionAdder(new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.Duplicate,this.PermissionTypes))) { VisualData = CreateActionVisualizedData(dynamicValuesHelperReplaceContext) }); } /// public override string ToString() { return $"GenericDuplicateDataActionNode, Label = {this.Label}"; } } } ================================================ FILE: Composite/C1Console/Trees/GenericEditDataActionNode.cs ================================================ using System; using System.Text; using Composite.C1Console.Actions.Data; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Core.Serialization; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class GenericEditDataActionNode : ActionNode { /// public string CustomFormMarkupPath { get; internal set; } // Optional /// protected override void OnAddAction(Action actionAdder, EntityToken entityToken, TreeNodeDynamicContext dynamicContext, DynamicValuesHelperReplaceContext dynamicValuesHelperReplaceContext) { var payload = new StringBuilder(); this.Serialize(payload); StringConversionServices.SerializeKeyValuePair(payload, "_IconResourceName_", Icon.ResourceName); if (!String.IsNullOrEmpty(CustomFormMarkupPath)) { StringConversionServices.SerializeKeyValuePair(payload, "_CustomFormMarkupPath_", CustomFormMarkupPath); actionAdder(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Trees.Workflows.GenericEditDataWorkflow"), this.PermissionTypes) { Payload = payload.ToString() })) { VisualData = CreateActionVisualizedData(dynamicValuesHelperReplaceContext) }); } else { actionAdder(new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.Edit, this.PermissionTypes))) { VisualData = CreateActionVisualizedData(dynamicValuesHelperReplaceContext) }); } } /// protected override void OnInitialize() { if (!(this.OwnerNode is DataElementsTreeNode)) { AddValidationError("TreeValidationError.GenericEditDataAction.OwnerIsNotDataNode"); } if (!string.IsNullOrEmpty(this.CustomFormMarkupPath)) { this.CustomFormMarkupPath = LoadAndValidateCustomFormMarkupPath(CustomFormMarkupPath); } } /// public override string ToString() { return $"GenericEditDataActionNode, Label = {this.Label}"; } } } ================================================ FILE: Composite/C1Console/Trees/IEntityTokenContainingParentEntityToken.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.C1Console.Security; namespace Composite.C1Console.Trees { internal interface IEntityTokenContainingParentEntityToken { EntityToken GetParentEntityToken(); } } ================================================ FILE: Composite/C1Console/Trees/ITreeFacade.cs ================================================ using System; using System.Collections.Generic; using System.Xml.Linq; using Composite.C1Console.Elements.Plugins.ElementAttachingProvider; using Composite.C1Console.Security; namespace Composite.C1Console.Trees { internal interface ITreeFacade { void Initialize(); Tree GetTree(string treeId); IEnumerable AllTrees { get; } bool HasAttachmentPoints(EntityToken parentEntityToken); bool HasPossibleAttachmentPoints(EntityToken parentEntityToken); IEnumerable GetTreesByEntityToken(EntityToken parentEntityToken); bool AddPersistedAttachmentPoint(string treeId, Type interfaceType, object keyValue, ElementAttachingProviderPosition position = ElementAttachingProviderPosition.Top); bool RemovePersistedAttachmentPoint(string treeId, Type interfaceType, object keyValue); bool AddCustomAttachmentPoint(string treeId, EntityToken entityToken, ElementAttachingProviderPosition position = ElementAttachingProviderPosition.Top); Tree LoadTreeFromDom(string treeId, XDocument document); void OnFlush(); } } ================================================ FILE: Composite/C1Console/Trees/LeafDisplayMode.cs ================================================ using System; using System.Xml.Linq; using Composite.Core.Xml; namespace Composite.C1Console.Trees { /// /// Defines the way an element is shown depending on presense of the child elements /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum LeafDisplayMode { /// /// Only shows the elements that has child elements; hides all the elements without child elements. /// Compact = 0, /// /// Element is always shown, as well as the the "+" sign even when element doesn't have any child items. Default value, has the best performance /// Lazy = 1, /// /// Element is always shown, the "+" sign is shown only if there're child elements. /// Auto = 2 } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class LeafDisplayModeHelper { /// public static LeafDisplayMode ParseDisplayMode(XAttribute attribute, Tree tree) { if (attribute != null) { LeafDisplayMode parsedValue; if (Enum.TryParse(attribute.Value, out parsedValue)) { return parsedValue; } tree.AddValidationError(attribute.GetXPath(), "TreeValidationError.Common.WrongAttributeValue", attribute.Value); } return LeafDisplayMode.Lazy; } } } ================================================ FILE: Composite/C1Console/Trees/MessageBoxActionNode.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.Core.Serialization; namespace Composite.C1Console.Trees { internal class MessageBoxActionNode : ActionNode { public string Title { get; set; } // Required public string Message { get; set; } // Required public DialogType DialogType { get; set; } // Optional // Cached values private DynamicValuesHelper TitleDynamicValuesHelper { get; set; } private DynamicValuesHelper MessageDynamicValuesHelper { get; set; } protected override void OnAddAction(Action actionAdder, EntityToken entityToken, TreeNodeDynamicContext dynamicContext, DynamicValuesHelperReplaceContext dynamicValuesHelperReplaceContext) { ActionToken actionToken = new MessageBoxActionNodeActionToken( this.TitleDynamicValuesHelper.ReplaceValues(dynamicValuesHelperReplaceContext), this.MessageDynamicValuesHelper.ReplaceValues(dynamicValuesHelperReplaceContext), this.Serialize(), this.PermissionTypes ); ElementAction elementAction = new ElementAction(new ActionHandle(actionToken)) { VisualData = this.CreateActionVisualizedData(dynamicValuesHelperReplaceContext) }; elementAction.VisualData.ActionLocation = this.Location; actionAdder(elementAction); } protected override void OnInitialize() { this.TitleDynamicValuesHelper = new DynamicValuesHelper(this.Title); this.TitleDynamicValuesHelper.Initialize(this.OwnerNode); this.MessageDynamicValuesHelper = new DynamicValuesHelper(this.Message); this.MessageDynamicValuesHelper.Initialize(this.OwnerNode); } } internal sealed class MessageBoxActionNodeActionExecutor : IActionExecutor { public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { MessageBoxActionNodeActionToken messageBoxActionNodeActionToken = (MessageBoxActionNodeActionToken)actionToken; MessageBoxActionNode messageBoxActionNode = (MessageBoxActionNode)ActionNode.Deserialize(messageBoxActionNodeActionToken.SerializedActionNode); IManagementConsoleMessageService managementConsoleMessageService = flowControllerServicesContainer.GetService(); managementConsoleMessageService.ShowMessage( messageBoxActionNode.DialogType, messageBoxActionNodeActionToken.Title, messageBoxActionNodeActionToken.Message); return null; } } [ActionExecutor(typeof(MessageBoxActionNodeActionExecutor))] internal sealed class MessageBoxActionNodeActionToken : ActionToken { private List _permissionTypes; public MessageBoxActionNodeActionToken(string title, string message, string serializedActionNode, List permissionTypes) { this.Title = title; this.Message = message; _permissionTypes = permissionTypes; this.SerializedActionNode = serializedActionNode; } public string Title { get; private set; } public string Message { get; private set; } public string SerializedActionNode { get; private set; } public override IEnumerable PermissionTypes { get { return _permissionTypes; } } public override string Serialize() { StringBuilder sb = new StringBuilder(); StringConversionServices.SerializeKeyValuePair(sb, "Title", this.Title); StringConversionServices.SerializeKeyValuePair(sb, "Message", this.Message); StringConversionServices.SerializeKeyValuePair(sb, "SerializedActionNode", this.SerializedActionNode); StringConversionServices.SerializeKeyValuePair(sb, "PermissionTypes", _permissionTypes.SerializePermissionTypes()); return sb.ToString(); } public static ActionToken Deserialize(string serializedData) { Dictionary dic = StringConversionServices.ParseKeyValueCollection(serializedData); return new MessageBoxActionNodeActionToken ( StringConversionServices.DeserializeValueString(dic["Title"]), StringConversionServices.DeserializeValueString(dic["Message"]), StringConversionServices.DeserializeValueString(dic["SerializedActionNode"]), StringConversionServices.DeserializeValueString(dic["PermissionTypes"]).DesrializePermissionTypes().ToList() ); } } } ================================================ FILE: Composite/C1Console/Trees/OrderByNode.cs ================================================ using System.Linq.Expressions; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class OrderByNode { /// public string XPath { get; internal set; } /// public DataElementsTreeNode OwnerNode { get; internal set; } /// /// Creates OrderBy expression. /// /// The source expression. /// The parameter expression. /// Implementations of this class should use this parameter to distinguish between OrderBy and ThenBy /// public abstract Expression CreateOrderByExpression(Expression sourceExpression, ParameterExpression parameterExpression, bool first); /// /// Use this method to do initializing and validation /// internal virtual void Initialize() { } /// public void SetOwnerNode(TreeNode treeNode) { this.OwnerNode = (DataElementsTreeNode)treeNode; } /// protected void AddValidationError(string stringName, params object[] args) { this.OwnerNode.Tree.BuildResult.AddValidationError(ValidationError.Create(this.XPath, stringName, args)); } } } ================================================ FILE: Composite/C1Console/Trees/ParentIdFilterNode.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Data; using Composite.Core.Linq; using Composite.C1Console.Security; using Composite.C1Console.Trees.Foundation.AttachmentPoints; using Composite.Core.Types; namespace Composite.C1Console.Trees { internal class ParentIdFilterNode : FilterNode { public Type ParentFilterType { get; internal set; } // Required public string ReferenceFieldName { get; internal set; } // Required public DataElementsTreeNode ParentFilterTypeTreeNode { get; internal set; } internal PropertyInfo KeyPropertyInfo { get; set; } internal PropertyInfo ReferencePropertyInfo { get; set; } public override Expression CreateDownwardsFilterExpression(ParameterExpression parameterExpression, TreeNodeDynamicContext dynamicContext) { IData parentDataItem = GetParentDataItem(this.ParentFilterType, dynamicContext.CurrentEntityToken, dynamicContext); if (parentDataItem == null) return null; object parentFieldValue = this.KeyPropertyInfo.GetValue(parentDataItem, null); Expression expression = Expression.Equal(ExpressionHelper.CreatePropertyExpression(this.ReferenceFieldName, parameterExpression), Expression.Constant(parentFieldValue, this.ReferencePropertyInfo.PropertyType)); if (ReferencePropertyInfo.PropertyType.IsGenericType && ReferencePropertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { PropertyInfo propertyInfo = ReferencePropertyInfo.PropertyType.GetProperty("HasValue"); Expression hasValueExpression = Expression.Property(Expression.Property(parameterExpression, this.ReferenceFieldName), propertyInfo); expression = Expression.AndAlso(hasValueExpression, expression); } return expression; } private bool IsInParentTree(TreeNode treeNode) { TreeNode searchTreeNode = treeNode.ParentNode; while (searchTreeNode != null) { var node = searchTreeNode as DataElementsTreeNode; if (node != null) { if (node.InterfaceType == this.OwnerNode.InterfaceType) { // Found in parent tree. return true; } searchTreeNode = searchTreeNode.ParentNode; } else { searchTreeNode = searchTreeNode.ParentNode; } } return false; } /// /// This method finds the callers tree node own entity token by searching up/down using filters. /// In some cases this can be expensive. /// /// /// /// /// private EntityToken FindOwnEntityToken(TreeNode treeNode, EntityToken entityToken, TreeNodeDynamicContext dynamicContext) { DataElementsTreeNode dataElementsTreeNode = treeNode as DataElementsTreeNode; if (dataElementsTreeNode != null) { if (dataElementsTreeNode.InterfaceType == this.OwnerNode.InterfaceType) // We found it :) { return entityToken; } } TreeDataFieldGroupingElementEntityToken dataFieldGroupingElementEntityToken = entityToken as TreeDataFieldGroupingElementEntityToken; if (dataFieldGroupingElementEntityToken != null) // Search 'downwards' { ParameterExpression parameterExpression = Expression.Parameter(this.OwnerNode.InterfaceType, "data"); DataKeyPropertyCollection dataKeyPropertyCollection = new DataKeyPropertyCollection(); dataKeyPropertyCollection.AddKeyProperty("Id", dataFieldGroupingElementEntityToken.ChildGeneratingDataElementsReferenceValue); Type dataType = dataFieldGroupingElementEntityToken.ChildGeneratingDataElementsReferenceType; IData parentData = DataFacade.GetDataByUniqueKey(dataType, dataKeyPropertyCollection); TreeNodeDynamicContext dummyContext = new TreeNodeDynamicContext(TreeNodeDynamicContextDirection.Down); dummyContext.CustomData.Add("ParentData", parentData); IData resultData; if (this.OwnerNode.InterfaceType == TypeManager.GetType(dataFieldGroupingElementEntityToken.Type)) { Expression filterExpression = this.CreateDownwardsFilterExpression(parameterExpression, dummyContext); Expression whereExpression = ExpressionHelper.CreateWhereExpression(DataFacade.GetData(this.OwnerNode.InterfaceType).Expression, parameterExpression, filterExpression); resultData = (IData)DataFacade.GetData(this.OwnerNode.InterfaceType).Provider.CreateQuery(whereExpression).ToEnumerableOfObjects().First(); } else { resultData = parentData; } return resultData.GetDataEntityToken(); } AncestorResult ancestorResult = treeNode.GetParentEntityToken(entityToken, this.ParentFilterType, dynamicContext); if ((this.OwnerNode.Id == ancestorResult.TreeNode.Id) || (this.OwnerNode.IsDescendant(ancestorResult.TreeNode))) // Search upwards { return FindOwnEntityToken(ancestorResult.TreeNode, ancestorResult.EntityToken, dynamicContext); } // Search 'downwards' by using the parent datas key value to get DataElementsTreeNode parentDataElementsTreeNode = (DataElementsTreeNode)ancestorResult.TreeNode; if (this.ParentFilterType == parentDataElementsTreeNode.InterfaceType) { DataEntityToken dataEntityToken = (DataEntityToken)ancestorResult.EntityToken; ParameterExpression parameterExpression = Expression.Parameter(this.OwnerNode.InterfaceType, "data"); TreeNodeDynamicContext dummyContext = new TreeNodeDynamicContext(TreeNodeDynamicContextDirection.Down); dummyContext.CustomData.Add("ParentData", dataEntityToken.Data); Expression filterExpression = this.CreateDownwardsFilterExpression(parameterExpression, dummyContext); Expression whereExpression = ExpressionHelper.CreateWhereExpression(DataFacade.GetData(this.OwnerNode.InterfaceType).Expression, parameterExpression, filterExpression); IData resultData = (IData)DataFacade.GetData(this.OwnerNode.InterfaceType).Provider.CreateQuery(whereExpression).ToEnumerableOfObjects().First(); return resultData.GetDataEntityToken(); } throw new InvalidOperationException("Missing parent id filtering or try to simplify the parent id filterings (Unable to find own entity token)"); } internal object FindParentKeyValue(TreeNodeDynamicContext dynamicContext) { if ((dynamicContext.CurrentEntityToken is DataEntityToken)) { DataEntityToken currentDataEntityToken = dynamicContext.CurrentEntityToken as DataEntityToken; if (currentDataEntityToken.InterfaceType == this.ParentFilterType) { return this.KeyPropertyInfo.GetValue(currentDataEntityToken.Data, null); } } EntityToken ownFilterEntityToken = FindOwnEntityToken(dynamicContext.CurrentTreeNode, dynamicContext.CurrentEntityToken, dynamicContext); DataEntityToken dataEntityToken = (DataEntityToken)ownFilterEntityToken; IData data = dataEntityToken.Data; object parentFieldValue = this.ReferencePropertyInfo.GetValue(data, null); return parentFieldValue; } public override Expression CreateUpwardsFilterExpression(ParameterExpression parameterExpression, TreeNodeDynamicContext dynamicContext) { // To create a upwards filter, we need the parent key value to filter on our own reference value (by constant) // To do this we need the parent entity token or our own entity token object parentFieldValue = FindParentKeyValue(dynamicContext); var constantType = this.ReferencePropertyInfo.PropertyType; if (constantType.IsGenericType && constantType.GetGenericTypeDefinition() == typeof (Nullable<>)) { constantType = constantType.GetGenericArguments()[0]; } return Expression.Equal(ExpressionHelper.CreatePropertyExpression(this.KeyPropertyInfo.Name, parameterExpression), Expression.Constant(parentFieldValue, constantType)); } internal override void Initialize() { foreach (TreeNode treeNode in this.OwnerNode.Ancestors(true)) { DataElementsTreeNode dataElementsTreeNode = treeNode as DataElementsTreeNode; if (dataElementsTreeNode != null && dataElementsTreeNode.InterfaceType == this.ParentFilterType) { this.ParentFilterTypeTreeNode = dataElementsTreeNode; break; } } bool dataItemAttachmentPointExists = this.OwnerNode.Tree.AttachmentPoints.OfType().Any(f => f.InterfaceType == this.ParentFilterType) || this.OwnerNode.Tree.PossibleAttachmentPoints.OfType().Any(f => f.InterfaceType == this.ParentFilterType); if (this.ParentFilterTypeTreeNode != null || dataItemAttachmentPointExists) { this.KeyPropertyInfo = this.ParentFilterType.GetKeyProperties()[0]; } if (this.KeyPropertyInfo == null) { AddValidationError("TreeValidationError.ParentIdFilterNode.TypeIsNotInParentTree", this.ParentFilterType); } this.ReferencePropertyInfo = this.OwnerNode.InterfaceType.GetPropertiesRecursively().SingleOrDefault(f => f.Name == this.ReferenceFieldName); if (this.ReferencePropertyInfo == null) { AddValidationError("TreeValidationError.Common.MissingProperty", this.OwnerNode.InterfaceType, this.ReferenceFieldName); } } public override string ToString() { if (this.ParentFilterTypeTreeNode != null) { return string.Format("ParentIdFilterNode, ParentFilterType = {0}, ReferenceFieldName = {1}, ParentFilterTreeNodeId = {2}", this.ParentFilterType, this.ReferenceFieldName, this.ParentFilterTypeTreeNode.Id); } return string.Format("ParentIdFilterNode, ParentFilterType = {0}, ReferenceFieldName = {1}", this.ParentFilterType, this.ReferenceFieldName); } private object Find(TreeNode currentTreeNode, EntityToken currentEntityToken) { if (this.OwnerNode.IsAncestor(currentTreeNode)) // Is parent { return currentTreeNode; } if (this.OwnerNode.Id != currentTreeNode.Id) // Is child { IEnumerable parentIdFilterNodes = currentTreeNode.FilterNodes.OfType(); foreach (ParentIdFilterNode parentIdFilterNode in parentIdFilterNodes) { Find(parentIdFilterNode.ParentFilterTypeTreeNode, null); } } foreach (TreeNode childTreeNode in this.OwnerNode.ChildNodes) { object res = Find(childTreeNode, null); if (res != null) { return res; } } return null; } private IData GetParentDataItem(Type parentType, EntityToken parentEntityToken, TreeNodeDynamicContext dynamicContext) { if (dynamicContext.CustomData.ContainsKey("ParentData")) { return (IData)dynamicContext.CustomData["ParentData"]; } IData parentDataItem = null; if (parentEntityToken is DataEntityToken) { DataEntityToken dataEntityToken = parentEntityToken as DataEntityToken; Type type = dataEntityToken.InterfaceType; if (type == parentType) { return dataEntityToken.Data; } } if (parentDataItem == null) { foreach (EntityToken entityToken in dynamicContext.Piggybag.GetParentEntityTokens()) { DataEntityToken dataEntityToken = entityToken as DataEntityToken; if (dataEntityToken == null) continue; Type type = dataEntityToken.InterfaceType; if (type != parentType) continue; return dataEntityToken.Data; } } return null; } } } ================================================ FILE: Composite/C1Console/Trees/PiggybagDataFinder.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.C1Console.Security; using Composite.Data; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class PiggybagDataFinder { private List _parentEntityTokens; private readonly Dictionary _piggybag; private readonly EntityToken _currentEntityToken; /// public PiggybagDataFinder(Dictionary piggybag, EntityToken currentEntityToken) { _piggybag = piggybag; _currentEntityToken = currentEntityToken; } /// public Dictionary Piggybag { get { return _piggybag; } } /// public IData GetData(Type interfaceType, IData currentData = null) { if ((currentData != null) && (currentData.DataSourceId.InterfaceType == interfaceType)) return currentData; DataEntityToken dataEntityToken = GetDataEntityToken(interfaceType); return dataEntityToken.Data; } /// public IData TryGetData(Type interfaceType, IData currentData = null) { if ((currentData != null) && (currentData.DataSourceId.InterfaceType == interfaceType)) return currentData; DataEntityToken dataEntityToken = TryGetDataEntityToken(interfaceType); if (dataEntityToken == null) return null; return dataEntityToken.Data; } private DataEntityToken GetDataEntityToken(Type interfaceType) { DataEntityToken dataEntityToken = TryGetDataEntityToken(interfaceType); if ((dataEntityToken == null) || (dataEntityToken.InterfaceType != interfaceType)) throw new InvalidOperationException("Could not find data entity token that match the given interface type"); return dataEntityToken; } private DataEntityToken TryGetDataEntityToken(Type interfaceType) { DataEntityToken dataEntityToken = _currentEntityToken as DataEntityToken; if ((dataEntityToken == null) || (dataEntityToken.InterfaceType != interfaceType)) { dataEntityToken = this.ParentEntityTokens.FindDataEntityToken(interfaceType); } return dataEntityToken; } private IEnumerable ParentEntityTokens { get { if (_parentEntityTokens == null) { _parentEntityTokens = _piggybag.GetParentEntityTokens().ToList(); } return _parentEntityTokens; } } } } ================================================ FILE: Composite/C1Console/Trees/PiggybagExtensionMethods.cs ================================================ using System; using System.Collections.Generic; using Composite.Data; using Composite.C1Console.Security; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PiggybagExtensionMethods { private const string ParentEntityTokenPiggybagString = "ParentEntityToken"; private const string ParentNodeIdPiggybagString = "ParentId"; /// public static string GetParentIdFromPiggybag(this Dictionary piggybag) { return GetParentIdFromPiggybag(piggybag, 1); } /// public static string GetParentIdFromPiggybag(this Dictionary piggybag, int generation) { return piggybag[string.Format("{0}{1}", ParentNodeIdPiggybagString, generation)]; } /// public static Dictionary PreparePiggybag(this Dictionary piggybag, TreeNode parentNode, EntityToken parentEntityToken) { var newPiggybag = new Dictionary(); foreach (KeyValuePair kvp in piggybag) { if (kvp.Key.StartsWith(ParentEntityTokenPiggybagString)) { int generation = int.Parse(kvp.Key.Substring(ParentEntityTokenPiggybagString.Length)); generation += 1; newPiggybag.Add(string.Format("{0}{1}", ParentEntityTokenPiggybagString, generation), kvp.Value); } else if (kvp.Key.StartsWith(ParentNodeIdPiggybagString)) { int generation = int.Parse(kvp.Key.Substring(ParentNodeIdPiggybagString.Length)); generation += 1; newPiggybag.Add(string.Format("{0}{1}", ParentNodeIdPiggybagString, generation), kvp.Value); } else { newPiggybag.Add(kvp.Key, kvp.Value); } } newPiggybag.Add(string.Format("{0}1", ParentEntityTokenPiggybagString), EntityTokenSerializer.Serialize(parentEntityToken)); newPiggybag.Add(string.Format("{0}1", ParentNodeIdPiggybagString), parentNode.Id.ToString()); return newPiggybag; } /// public static bool TryGetPiggybaggedEntityToken(this Dictionary piggybag, out EntityToken entityToken) { return TryGetPiggybaggedEntityToken(piggybag, 1, out entityToken); } /// public static bool TryGetPiggybaggedEntityToken(this Dictionary piggybag, int generation, out EntityToken entityToken) { string key = $"{ParentEntityTokenPiggybagString}{generation}"; string serializedEntityToken; if (!piggybag.TryGetValue(key, out serializedEntityToken)) { entityToken = null; return false; } entityToken = EntityTokenSerializer.Deserialize(serializedEntityToken); return true; } /// public static IEnumerable GetParentEntityTokens(this Dictionary piggybag, EntityToken entityTokenToInclude = null) { if (entityTokenToInclude != null) { yield return entityTokenToInclude; } int generation = 1; string serializedEntityToken; while (piggybag.TryGetValue($"{ParentEntityTokenPiggybagString}{generation}", out serializedEntityToken)) { yield return EntityTokenSerializer.Deserialize(serializedEntityToken); generation++; } } /// public static DataEntityToken FindDataEntityToken(this IEnumerable entityTokens, Type interfaceType) { foreach (EntityToken entityToken in entityTokens) { DataEntityToken dataEntityToken = entityToken as DataEntityToken; if (dataEntityToken == null) continue; if (dataEntityToken.InterfaceType == interfaceType) { return dataEntityToken; } } return null; } } } ================================================ FILE: Composite/C1Console/Trees/ReportFunctionActionNode.cs ================================================ using System; using System.Collections.Generic; using System.Text; using System.Xml.Linq; using Composite.C1Console.Elements; using Composite.Functions; using Composite.Core.ResourceSystem; using Composite.C1Console.Security; using Composite.Core.Serialization; using Composite.C1Console.Workflow; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ReportFunctionActionNode : ActionNode { /// public XElement FunctionMarkup { get; set; } // Required /// public string DocumentLabel { get; set; } // Optional, defaults to Label /// public ResourceHandle DocumentIcon { get; set; } // Optional, defaults to Icon /// public AttributeDynamicValuesHelper FunctionMarkupDynamicValuesHelper { get; private set; } /// public DynamicValuesHelper DocumentLabelDynamicValueHelper { get; private set; } /// protected override void OnAddAction(Action actionAdder, EntityToken entityToken, TreeNodeDynamicContext dynamicContext, DynamicValuesHelperReplaceContext dynamicValuesHelperReplaceContext) { StringBuilder payload = new StringBuilder(); StringConversionServices.SerializeKeyValuePair(payload, "TreeId", this.OwnerNode.Tree.TreeId); StringConversionServices.SerializeKeyValuePair(payload, "ActionId", this.Id); WorkflowActionToken actionToken = new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.C1Console.Trees.Workflows.ReportFunctionActionWorkflow"), this.PermissionTypes) { Payload = this.Serialize(), ExtraPayload = PiggybagSerializer.Serialize(dynamicContext.Piggybag.PreparePiggybag(dynamicContext.CurrentTreeNode, dynamicContext.CurrentEntityToken)), DoIgnoreEntityTokenLocking = true }; actionAdder(new ElementAction(new ActionHandle(actionToken)) { VisualData = CreateActionVisualizedData(dynamicValuesHelperReplaceContext) }); } /// protected override void OnInitialize() { try { FunctionTreeBuilder.Build(this.FunctionMarkup); } catch { AddValidationError("TreeValidationError.Common.WrongFunctionMarkup"); return; } this.FunctionMarkupDynamicValuesHelper = new AttributeDynamicValuesHelper(this.FunctionMarkup); this.FunctionMarkupDynamicValuesHelper.Initialize(this.OwnerNode); this.DocumentLabelDynamicValueHelper = new DynamicValuesHelper(this.DocumentLabel); this.DocumentLabelDynamicValueHelper.Initialize(this.OwnerNode); } /// public override string ToString() { return string.Format("ReportFunctionActionNode, Label = {0}", this.Label); } } } ================================================ FILE: Composite/C1Console/Trees/RootTreeNode.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.C1Console.Trees.Foundation; using Composite.C1Console.Trees.Foundation.AttachmentPoints; namespace Composite.C1Console.Trees { /// /// This node is a virtual node represending the element that the tree is attached under. /// internal class RootTreeNode : TreeNode { public RootTreeNode() { this.Id = StringConstants.RootNodeId; } private class AncestorMatch { public Type InterfaceType; public object KeyValue; } public override IEnumerable GetEntityTokens(EntityToken childEntityToken, TreeNodeDynamicContext dynamicContext) { TreeSimpleElementEntityToken treeSimpleElementEntityToken = childEntityToken as TreeSimpleElementEntityToken; if (treeSimpleElementEntityToken != null) { yield return treeSimpleElementEntityToken.ParentEntityToken; } else { AncestorMatch ancestorFromFilter = GetAncestorFromParentFilter(dynamicContext); foreach (IAttachmentPoint attachmentPoint in this.Tree.AttachmentPoints) { if(attachmentPoint is DynamicDataItemAttachmentPoint && ancestorFromFilter != null) { var dynamicAttachmentPoint = attachmentPoint as DynamicDataItemAttachmentPoint; if (ancestorFromFilter.InterfaceType == dynamicAttachmentPoint.InterfaceType) { if (dynamicAttachmentPoint.KeyValue.Equals(ancestorFromFilter.KeyValue)) { foreach (var e in dynamicAttachmentPoint.GetEntityTokens(null, null)) { yield return e; } } continue; } } foreach (EntityToken entityToken in attachmentPoint.GetEntityTokens(childEntityToken, dynamicContext)) { yield return entityToken; } } } } private AncestorMatch GetAncestorFromParentFilter(TreeNodeDynamicContext dynamicContext) { var treeNode = dynamicContext.CurrentTreeNode; if (treeNode is DataElementsTreeNode) { var parentIdFilter = treeNode.FilterNodes.OfType().FirstOrDefault(); if (parentIdFilter == null) return null; Type ancestorType = parentIdFilter.ParentFilterType; object key = parentIdFilter.FindParentKeyValue(dynamicContext); return key == null ? null : new AncestorMatch { InterfaceType = ancestorType, KeyValue = key}; } if (treeNode is DataFolderElementsTreeNode && dynamicContext.CurrentEntityToken is TreeDataFieldGroupingElementEntityToken groupEntityToken && groupEntityToken.ChildGeneratingDataElementsReferenceValue != null) { return new AncestorMatch { InterfaceType = groupEntityToken.ChildGeneratingDataElementsReferenceType, KeyValue = groupEntityToken.ChildGeneratingDataElementsReferenceValue }; } return null; } public override AncestorResult GetParentEntityToken(EntityToken childEntityToken, Type parentInterfaceOfInterest, TreeNodeDynamicContext dynamicContext) { throw new NotImplementedException("Should never get called"); } protected override IEnumerable OnGetElements(EntityToken parentEntityToken, TreeNodeDynamicContext dynamicContext) { foreach (TreeNode childTreeNode in this.ChildNodes) { foreach (Element element in childTreeNode.GetElements(parentEntityToken, dynamicContext)) { element.ElementHandle.Piggyback[StringConstants.PiggybagTreeId] = this.Tree.TreeId; yield return element; } } } public override string ToString() { return "RootTreeNode, Id = " + this.Id; } } } ================================================ FILE: Composite/C1Console/Trees/SimpleElementTreeNode.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.C1Console.Trees.Foundation; using Composite.Core.ResourceSystem; namespace Composite.C1Console.Trees { internal class SimpleElementTreeNode : TreeNode { public string Label { get; internal set; } // Requried public string ToolTip { get; internal set; } // Defaults to Label public ResourceHandle Icon { get; internal set; } // Defaults to 'folder' public ResourceHandle OpenIcon { get; internal set; } // Defaults to 'open-folder' or if Icon is set, then, Icon public string BrowserUrl { get; internal set; } // Defaults to no URL, what will be shows in console browser on focus public string BrowserImage { get; internal set; } // Defaults to no (image) URL, what will be shows in console browser on focus / lists // Cached values internal DynamicValuesHelper LabelDynamicValuesHelper { get; set; } internal DynamicValuesHelper ToolTipDynamicValuesHelper { get; set; } public override IEnumerable GetEntityTokens(EntityToken childEntityToken, TreeNodeDynamicContext dynamicContext) { var possibleCurrentEntityToken = childEntityToken is TreeSimpleElementEntityToken seEntityToken ? seEntityToken.ParentEntityToken : childEntityToken; foreach (EntityToken entityToken in this.ParentNode.GetEntityTokens(possibleCurrentEntityToken, dynamicContext)) { yield return new TreeSimpleElementEntityToken(this.Id, this.Tree.TreeId, EntityTokenSerializer.Serialize(entityToken)); } } internal override IEnumerable FilterParentGeneretedEntityTokens(EntityToken selfEntityToken, IEnumerable parentGeneretedEntityTokens, TreeNodeDynamicContext dynamicContext) { // Check below ensures that the parent EntityToken actually present in a tree and not been filtered out var treeSimpleElementEntityToken = (TreeSimpleElementEntityToken) selfEntityToken; var parentEntityToken = treeSimpleElementEntityToken.ParentEntityToken; foreach (EntityToken entityToken in parentGeneretedEntityTokens) { if (parentEntityToken.Equals(entityToken)) { return new[] { parentEntityToken }; } var castedEntityToken = entityToken as TreeSimpleElementEntityToken; if (castedEntityToken != null && parentEntityToken.Equals(castedEntityToken.ParentEntityToken)) { return new [] { parentEntityToken }; } } return Array.Empty(); } public override AncestorResult GetParentEntityToken(EntityToken ownEntityToken, Type parentInterfaceOfInterest, TreeNodeDynamicContext dynamicContext) { return new AncestorResult(this.ParentNode, ((TreeSimpleElementEntityToken)ownEntityToken).ParentEntityToken); } protected override IEnumerable OnGetElements(EntityToken parentEntityToken, TreeNodeDynamicContext dynamicContext) { var entityToken = new TreeSimpleElementEntityToken( this.Id, this.Tree.TreeId, EntityTokenSerializer.Serialize(parentEntityToken)); var element = new Element(new ElementHandle( dynamicContext.ElementProviderName, entityToken, dynamicContext.Piggybag.PreparePiggybag(this.ParentNode, parentEntityToken) )); if (this.BrowserUrl != null) { var url = this.BrowserUrl; if (!url.Contains("//")) { url = Core.WebClient.UrlUtils.ResolvePublicUrl(url); } element.PropertyBag.Add("BrowserUrl", url); element.PropertyBag.Add("BrowserToolingOn", "false"); } if (this.BrowserImage != null) { var url = this.BrowserImage; if (!url.Contains("//")) { url = Core.WebClient.UrlUtils.ResolvePublicUrl(url); } element.PropertyBag.Add("ListViewImage", url); if (this.BrowserUrl == null) { element.PropertyBag.Add("DetailViewImage", url); } } if (parentEntityToken is TreePerspectiveEntityToken) { element.ElementHandle.Piggyback[StringConstants.PiggybagTreeId] = Tree.TreeId; } var replaceContext = new DynamicValuesHelperReplaceContext(parentEntityToken, dynamicContext.Piggybag); element.VisualData = new ElementVisualizedData { Label = this.LabelDynamicValuesHelper.ReplaceValues(replaceContext), ToolTip = this.ToolTipDynamicValuesHelper.ReplaceValues(replaceContext), HasChildren = ChildNodes.Any(), Icon = this.Icon, OpenedIcon = this.OpenIcon }; yield return element; } protected override void OnInitialize() { this.LabelDynamicValuesHelper = new DynamicValuesHelper(this.Label); this.LabelDynamicValuesHelper.Initialize(this); this.ToolTipDynamicValuesHelper = new DynamicValuesHelper(this.ToolTip); this.ToolTipDynamicValuesHelper.Initialize(this); } public override string ToString() => $"SimpleElementTreeNode, Id = {Id}, Label = {Label}"; } } ================================================ FILE: Composite/C1Console/Trees/SortDirection.cs ================================================ namespace Composite.C1Console.Trees { /// /// Specifies how to sort tree elements /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum SortDirection { /// /// Sort from smallest to largest. For example, A to Z. /// Ascending = 0, /// /// Sort from largest to smallest. For example, Z to A. /// Descending = 1 } } ================================================ FILE: Composite/C1Console/Trees/Tree.cs ================================================ using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Xml.Linq; using Composite.C1Console.Security; using Composite.C1Console.Trees.Foundation; using Composite.C1Console.Trees.Foundation.AttachmentPoints; using Composite.Core; using Composite.Core.Xml; namespace Composite.C1Console.Trees { /// /// Result of parsing tree definition xml file /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DebuggerDisplay("{TreeId}")] public sealed class Tree { private static readonly string LogTitle = "TreeFacade"; /// public string TreeId { get; private set; } /// public string AllowedAttachmentApplicationName { get; internal set; } /// public TreeNode RootTreeNode { get; internal set; } internal BuildProcessContext BuildProcessContext { get; set; } /// /// Gets or sets information about validation erros. /// /// /// The build result. /// /// public BuildResult BuildResult { get; set; } // These are used to attach this tree at current/existing places internal List AttachmentPoints { get; private set; } // These are used to determin if a tree CAN be attached to a given place internal List PossibleAttachmentPoints { get; private set; } internal bool ShareRootElementById { get; set; } /// public Tree(string treeId) { this.TreeId = treeId; this.AttachmentPoints = new List(); this.PossibleAttachmentPoints = new List(); } /// public TreeNode GetTreeNode(string id) { return FindTreeNode(id, this.RootTreeNode); } /// public ActionNode GetActionNode(int id) { return FindActionNode(id, this.RootTreeNode); } /// public bool HasAttachmentPoints(EntityToken parentEntityToken) { return this.AttachmentPoints.Any(f => f.IsAttachmentPoint(parentEntityToken)); } /// public bool HasPossibleAttachmentPoints(EntityToken parentEntityToken) { return this.PossibleAttachmentPoints.Any(f => f.IsPossibleAttachmentPoint(parentEntityToken)); } /// public IEnumerable GetAttachmentPoints(EntityToken parentEntityToken) { return this.AttachmentPoints.Where(f => f.IsAttachmentPoint(parentEntityToken)); } internal void ClearAttachmentPoints() where T : IAttachmentPoint { this.AttachmentPoints = this.AttachmentPoints.Where(f => f.GetType() != typeof(T)).ToList(); } internal void AddValidationError(XObject @object, string stringName, params object[] args) { AddValidationError(@object.GetXPath(), stringName, args); } internal void AddValidationError(string xPath, string stringName, params object[] args) { this.BuildResult.AddValidationError(ValidationError.Create(xPath, stringName, args)); } private TreeNode FindTreeNode(string id, TreeNode treeNode) { if (treeNode.Id == id) return treeNode; foreach (TreeNode childTreeNode in treeNode.ChildNodes) { TreeNode resultTreeNode = FindTreeNode(id, childTreeNode); if (resultTreeNode != null) { return resultTreeNode; } } return null; } private ActionNode FindActionNode(int id, TreeNode treeNode) { ActionNode actionNode = treeNode.ActionNodes.SingleOrDefault(f => f.Id == id); if (actionNode != null) return actionNode; foreach (TreeNode childTreeNode in treeNode.ChildNodes) { ActionNode resultActionNode = FindActionNode(id, childTreeNode); if (resultActionNode != null) { return resultActionNode; } } return null; } /// public void LogTree() { Log.LogVerbose(LogTitle, string.Format("{0} - Tree informations:", this.TreeId)); Log.LogVerbose(LogTitle, "Attachment points:"); AttachmentPoints.ForEach(a => a.Log(LogTitle, indention: " ")); Log.LogVerbose(LogTitle, "Possible attachment points:"); PossibleAttachmentPoints.ForEach(a => a.Log(LogTitle, indention: " ")); Log.LogVerbose(LogTitle, "Tree nodes:"); this.RootTreeNode.LogTree(1); } } } ================================================ FILE: Composite/C1Console/Trees/TreeAuxiliaryAncestorProvider.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Security; using Composite.C1Console.Trees.Foundation; using Composite.Core; using Composite.Core.Extensions; using Composite.Data; namespace Composite.C1Console.Trees { internal sealed class TreeAuxiliaryAncestorProvider : IAuxiliarySecurityAncestorProvider { public Dictionary> GetParents(IEnumerable entityTokens) { var result = new Dictionary>(); foreach (EntityToken entityToken in entityTokens) { var dynamicContext = new TreeNodeDynamicContext(TreeNodeDynamicContextDirection.Up) { CurrentEntityToken = entityToken }; if (entityToken is TreeSimpleElementEntityToken || entityToken is TreeFunctionElementGeneratorEntityToken) { var parentEntityTokenSource = entityToken as IEntityTokenContainingParentEntityToken; try { result.Add(entityToken, new[] { parentEntityTokenSource.GetParentEntityToken() }); } catch (Exception ex) { string treeId; if (entityToken is TreeSimpleElementEntityToken simpleElementEntityToken) { treeId = simpleElementEntityToken.TreeNodeId; } else if (entityToken is TreeFunctionElementGeneratorEntityToken functionGenEntityToken) { treeId = functionGenEntityToken.TreeNodeId; } else { throw new InvalidOperationException("This code should not be reachable."); } Log.LogError("TreeFacade", $"The tree '{treeId}' failed to return parent entity tokens and are ignored"); Log.LogError("TreeFacade", ex); } } else if (entityToken is TreeDataFieldGroupingElementEntityToken dataFieldGroupingEntityToken) { string treeId = entityToken.Source; try { Tree tree = TreeFacade.GetTree(treeId); string treeNodeId = dataFieldGroupingEntityToken.TreeNodeId; TreeNode treeNode = tree.GetTreeNode(treeNodeId); dynamicContext.FieldGroupingValues = dataFieldGroupingEntityToken.GroupingValues; dynamicContext.FieldFolderRangeValues = dataFieldGroupingEntityToken.FolderRangeValues; dynamicContext.CurrentTreeNode = treeNode; result.Add(entityToken, treeNode.ParentNode.GetEntityTokens(entityToken, dynamicContext)); } catch (Exception ex) { Log.LogError("TreeFacade", $"The tree '{treeId}' failed to return parent entity tokens and are ignored"); Log.LogError("TreeFacade", ex); } } else if (entityToken is DataEntityToken dataEntityToken) { Type interfaceType = dataEntityToken.InterfaceType; foreach (Tree tree in TreeFacade.AllTrees) { List treeNodes; if (!tree.BuildProcessContext.DataInteraceToTreeNodes.TryGetValue(interfaceType, out treeNodes)) continue; IEnumerable concatList = null; foreach (TreeNode treeNode in treeNodes) { try { dynamicContext.CurrentTreeNode = treeNode; concatList = concatList.ConcatOrDefault(treeNode.ParentNode.GetEntityTokens(entityToken, dynamicContext)); } catch (Exception ex) { Log.LogError("TreeFacade", $"The tree '{treeNode.Tree.TreeId}' failed to return parent entity tokens and are ignored"); Log.LogError("TreeFacade", ex); } } if (concatList != null) { // Filtering the current element to avoid loops while resolving security concatList = concatList.Where(e => !entityToken.Equals(e)); IEnumerable existingList; if (result.TryGetValue(entityToken, out existingList)) { result[entityToken] = existingList.Concat(concatList); } else { result.Add(entityToken, concatList); } } } } else if (entityToken is TreePerspectiveEntityToken) { result.Add(entityToken, new[] { TreeSharedRootsFacade.SharedRootFolders[entityToken.Id].AttachmentPoint.AttachingPoint.EntityToken }); } } return result; } } } ================================================ FILE: Composite/C1Console/Trees/TreeDataFieldGroupingElementEntityToken.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Composite.C1Console.Security; using Composite.C1Console.Security.SecurityAncestorProviders; using Composite.Core.Extensions; using Composite.Core.Serialization; using Composite.Core.Types; using Composite.C1Console.Trees.Foundation; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(NoAncestorSecurityAncestorProvider))] public sealed class TreeDataFieldGroupingElementEntityToken : EntityToken { private const string _magicNullValue = "·NULL·"; private string _treeNodeId; private string _treeId; private string _type; private Dictionary _groupingValues = null; private Dictionary _folderRangeValues = null; private Dictionary _deserializeDictionary; // Used for lazy deserializing grouping values private int _hashCode = 0; /// public TreeDataFieldGroupingElementEntityToken(string treeNodeId, string treeId, string dataType) { _treeNodeId = treeNodeId; _treeId = treeId; _type = dataType; _deserializeDictionary = new Dictionary(); } /// public TreeDataFieldGroupingElementEntityToken(string treeNodeId, string treeId, string dataType, Dictionary deserializeDictionary) : this(treeNodeId, treeId, dataType) { _deserializeDictionary = deserializeDictionary; } /// /// Contains the interface type (serialized) /// public override string Type { get { return _type; } } /// /// Contains the Id of the tree /// public override string Source { get { return _treeId; } } /// /// Contains the Id of the owner tree node /// public override string Id { get { return _treeNodeId; } } /// public string TreeNodeId { get { return this.Id; } } /// public Dictionary GroupingValues { get { if (_groupingValues == null) { _groupingValues = new Dictionary(); Type dataType = TypeManager.GetType(this.Type); List propertyInfos = dataType.GetPropertiesRecursively(); foreach (var kvp in _deserializeDictionary) { string propertyName = kvp.Key; if (propertyName.StartsWith("■")) { propertyName = propertyName.Substring(1).Substring(0, propertyName.IndexOf("_", System.StringComparison.Ordinal) - 1); } PropertyInfo propertyInfo = propertyInfos.SingleOrDefault(f => f.Name == propertyName); if (propertyInfo == null) continue; object value = null; if (kvp.Value != _magicNullValue) { if (propertyInfo.PropertyType == typeof(DateTime)) { value = StringConversionServices.DeserializeValue(kvp.Value, typeof(string)); } else { value = StringConversionServices.DeserializeValue(kvp.Value, propertyInfo.PropertyType); } } _groupingValues.Add(kvp.Key, value); } } return _groupingValues; } set { _groupingValues = value; } } /// public Dictionary DeserializedGroupingValues { get { Dictionary result = new Dictionary(); Type dataType = TypeManager.GetType(this.Type); List propertyInfos = dataType.GetPropertiesRecursively(); foreach (var kvp in this.GroupingValues) { string propertyName = kvp.Key; if (propertyName.StartsWith("■")) { propertyName = propertyName.Substring(1).Substring(0, propertyName.IndexOf("_", System.StringComparison.Ordinal) - 1); } object value = kvp.Value; PropertyInfo propertyInfo = propertyInfos.SingleOrDefault(f => f.Name == propertyName); if (propertyInfo.PropertyType == typeof(DateTime)) { if (result.ContainsKey(propertyName)) { value = DateTimeFormater.Deserialize((string)value, (DateTime)result[propertyName]); result[propertyName] = value; } else { value = DateTimeFormater.Deserialize((string)value); result.Add(propertyName, value); } } else { result.Add(propertyName, value); } } return result; } } /// public Dictionary FolderRangeValues { get { if (_folderRangeValues == null) { _folderRangeValues = new Dictionary(); foreach (var kvp in _deserializeDictionary) { if (kvp.Key.StartsWith("·") == false) continue; int value = (int)StringConversionServices.DeserializeValue(kvp.Value, typeof(int)); _folderRangeValues.Add(kvp.Key.Substring(1), value); } } return _folderRangeValues; } set { _folderRangeValues = value; } } /// public Type ChildGeneratingDataElementsReferenceType { get; set; } /// public object ChildGeneratingDataElementsReferenceValue { get; set; } /// public override int GetHashCode() { if (_hashCode != 0) { return _hashCode; } int hashCode = base.GetHashCode(); if (this.GroupingValues != null) { foreach (var kvp in this.GroupingValues/*.SortByKeys()*/) { hashCode ^= kvp.Key.GetHashCode(); if (kvp.Value != null) { hashCode ^= kvp.Value.GetHashCode(); } } } if (this.FolderRangeValues != null) { foreach (var kvp in this.FolderRangeValues/*.SortByKeys()*/) { hashCode ^= kvp.Key.GetHashCode(); hashCode ^= kvp.Value.GetHashCode(); } } if (this.ChildGeneratingDataElementsReferenceType != null) { hashCode ^= ChildGeneratingDataElementsReferenceType.GetHashCode(); } if (this.ChildGeneratingDataElementsReferenceValue != null) { hashCode ^= ChildGeneratingDataElementsReferenceValue.GetHashCode(); } return _hashCode = hashCode; } /// public override string Serialize() { StringBuilder sb = new StringBuilder(); DoSerialize(sb); foreach (var kvp in this.GroupingValues.SortByKeys()) { if (kvp.Value != null) { StringConversionServices.SerializeKeyValuePair(sb, kvp.Key, kvp.Value, kvp.Value.GetType()); } else { StringConversionServices.SerializeKeyValuePair(sb, kvp.Key, _magicNullValue, typeof(string)); } } foreach (var kvp in this.FolderRangeValues.SortByKeys()) { StringConversionServices.SerializeKeyValuePair(sb, "·" + kvp.Key, kvp.Value, kvp.Value.GetType()); } if (this.ChildGeneratingDataElementsReferenceType != null) { StringConversionServices.SerializeKeyValuePair(sb, "_ReferenceType_", TypeManager.SerializeType(this.ChildGeneratingDataElementsReferenceType)); } if (this.ChildGeneratingDataElementsReferenceValue != null) { StringConversionServices.SerializeKeyValuePair(sb, "_ReferenceValueType_", this.ChildGeneratingDataElementsReferenceValue.GetType()); StringConversionServices.SerializeKeyValuePair(sb, "_ReferenceValue_", this.ChildGeneratingDataElementsReferenceValue, this.ChildGeneratingDataElementsReferenceValue.GetType()); } return sb.ToString(); } /// public static EntityToken Deserialize(string serializedEntityToken) { string type, source, id; Dictionary dic; DoDeserialize(serializedEntityToken, out type, out source, out id, out dic); TreeDataFieldGroupingElementEntityToken entityToken = new TreeDataFieldGroupingElementEntityToken(id, source, type, dic); if (dic.ContainsKey("_ReferenceType_")) { string typeString = StringConversionServices.DeserializeValueString(dic["_ReferenceType_"]); entityToken.ChildGeneratingDataElementsReferenceType = TypeManager.GetType(typeString); } if (dic.ContainsKey("_ReferenceValueType_")) { Type referenceValueType = StringConversionServices.DeserializeValueType(dic["_ReferenceValueType_"]); entityToken.ChildGeneratingDataElementsReferenceValue = StringConversionServices.DeserializeValue(dic["_ReferenceValue_"], referenceValueType); } return entityToken; } /// public override string OnGetExtraPrettyHtml() { StringBuilder sb = new StringBuilder(); foreach (var kvp in this.GroupingValues.SortByKeys()) { sb.Append("" + kvp.Key + " = " + kvp.Value.ToString() + "
"); } foreach (var kvp in this.FolderRangeValues.SortByKeys()) { sb.Append("" + kvp.Key + " = " + kvp.Value.ToString() + "
"); } if (this.ChildGeneratingDataElementsReferenceValue != null) { sb.Append("" + "ChildGenRef" + " = " + this.ChildGeneratingDataElementsReferenceValue.ToString() + "
"); } else { sb.Append("" + "ChildGenRef" + " = " + "(null)" + "
"); } return sb.ToString(); } /// public override void OnGetPrettyHtml(EntityTokenHtmlPrettyfier prettyfier) { prettyfier.AddCustomProperty("GroupingValues", (name, value, helper) => { Dictionary dic = (Dictionary)value; StringBuilder sb = new StringBuilder(); foreach (var kvp in dic) { sb.Append("" + kvp.Key + ": " + kvp.Value.ToString() + "
"); } helper.AddFullRow(new string[] { "" + name + "", sb.ToString() }); }); prettyfier.AddCustomProperty("FolderRangeValues", (name, value, helper) => { Dictionary dic = (Dictionary)value; StringBuilder sb = new StringBuilder(); foreach (var kvp in dic) { sb.Append("" + kvp.Key + ": " + kvp.Value.ToString() + "
"); } helper.AddFullRow(new [] { "" + name + "", sb.ToString() }); }); prettyfier.AddCustomProperty("ChildGeneratingDataElementsReferenceType", (name, value, helper) => { helper.AddFullRow(new[] { "" + name + "", EntityTokenHtmlPrettyfier.GetTypeHtml((value ?? "(null)").ToString()) }); }); prettyfier.AddCustomProperty("ChildGeneratingDataElementsReferenceValue", (name, value, helper) => { helper.AddFullRow(new [] { "" + name + "", (value ?? "(null)").ToString() }); }); } } } ================================================ FILE: Composite/C1Console/Trees/TreeElementActionProvider.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementActionProvider; using Composite.Core.ResourceSystem; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Trees { [ConfigurationElementType(typeof(NonConfigurableElementActionProvider))] internal sealed class TreeElementActionProvider : IElementActionProvider { private static readonly ResourceHandle AddApplicationIcon = ResourceHandle.BuildIconFromDefaultProvider("tree-add-application"); private static readonly ResourceHandle RemoveApplicationIcon = ResourceHandle.BuildIconFromDefaultProvider("tree-remove-application"); private static readonly ActionGroup ApplicationsActionGroup = new ActionGroup("Applications", ActionGroupPriority.TargetedAppendMedium); private static readonly List AddPermissionTypes = new List { PermissionType.Administrate, PermissionType.Configure }; private static readonly List RemovePermissionTypes = new List { PermissionType.Administrate, PermissionType.Configure }; public IEnumerable GetActions(EntityToken entityToken) { if (TreeFacade.HasPossibleAttachmentPoints(entityToken)) { yield return new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Trees.Workflows.AddApplicationWorkflow"), AddPermissionTypes) { DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "AddApplicationWorkflow.AddApplication.Label"), ToolTip = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "AddApplicationWorkflow.AddApplication.ToolTip"), Icon = AddApplicationIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = false, ActionGroup = ApplicationsActionGroup } } }; yield return new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Trees.Workflows.RemoveApplicationWorkflow"), RemovePermissionTypes) { DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "RemoveApplicationWorkflow.RemoveApplication.Label"), ToolTip = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "RemoveApplicationWorkflow.RemoveApplication.ToolTip"), Icon = RemoveApplicationIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = false, ActionGroup = ApplicationsActionGroup } } }; } List elementActions = new List(); foreach (Tree tree in TreeFacade.GetTreesByEntityToken(entityToken)) { TreeNodeDynamicContext dynamicContext = new TreeNodeDynamicContext(TreeNodeDynamicContextDirection.Down) { CurrentTreeNode = tree.RootTreeNode, CurrentEntityToken = entityToken, Piggybag = new Dictionary() }; foreach (ActionNode actionNode in tree.RootTreeNode.ActionNodes) { actionNode.AddAction(f => elementActions.Add(f), entityToken, dynamicContext); } } foreach (ElementAction elementAction in elementActions) { yield return elementAction; } } } } ================================================ FILE: Composite/C1Console/Trees/TreeElementAttachingProvider.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Core.Extensions; using Composite.Data; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementAttachingProvider; using Composite.Core.Linq; using Composite.Core.Logging; using Composite.Core.ResourceSystem; using Composite.C1Console.Security; using Composite.C1Console.Trees.Foundation; using Composite.C1Console.Trees.Foundation.AttachmentPoints; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Trees { [ConfigurationElementType(typeof(NonConfigurableElementAttachingProvider))] internal class TreeElementAttachingProvider : IMultipleResultElementAttachingProvider { public ElementProviderContext Context { get; set; } public bool HaveCustomChildElements(EntityToken parentEntityToken, Dictionary piggybag) { TreeSharedRootsFacade.Initialize(Context.ProviderName); foreach (Tree tree in TreeFacade.GetTreesByEntityToken(parentEntityToken)) { if (tree.RootTreeNode.ChildNodes.Any()) return true; } return false; } public ElementAttachingProviderResult GetAlternateElementList(EntityToken parentEntityToken, Dictionary piggybag) { throw new NotImplementedException("Will never get called"); } public IEnumerable GetAlternateElementLists(EntityToken parentEntityToken, Dictionary piggybag) { TreeSharedRootsFacade.Initialize(Context.ProviderName); IEnumerable trees = TreeFacade.GetTreesByEntityToken(parentEntityToken); foreach (Tree tree in trees) { foreach (IAttachmentPoint attachmentPoint in tree.GetAttachmentPoints(parentEntityToken)) { TreeNodeDynamicContext dynamicContext = new TreeNodeDynamicContext(TreeNodeDynamicContextDirection.Down) { ElementProviderName = this.Context.ProviderName, Piggybag = piggybag, CurrentEntityToken = parentEntityToken, CurrentTreeNode = tree.RootTreeNode, IsRoot = true }; ElementAttachingProviderResult result = null; try { result = new ElementAttachingProviderResult() { Elements = tree.RootTreeNode.GetElements(parentEntityToken, dynamicContext).Evaluate(), Position = attachmentPoint.Position, PositionPriority = 0 }; } catch (Exception ex) { LoggingService.LogError("TreeFacade", string.Format("Getting elements from the tree '{0}' failed", tree.TreeId)); LoggingService.LogError("TreeFacade", ex); Element errorElement = ShowErrorElementHelper.CreateErrorElement( StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "KeyFacade.ErrorTreeNode.Label"), tree.TreeId, ex.Message); result = new ElementAttachingProviderResult() { Elements = new List() { errorElement }, Position = attachmentPoint.Position, PositionPriority = 0 }; } yield return result; } } foreach (CustomTreePerspectiveInfo info in TreeSharedRootsFacade.SharedRootFolders.Values) { if (info.AttachmentPoint.IsAttachmentPoint(parentEntityToken)) { Element element = new Element(new ElementHandle(info.Element.ElementHandle.ProviderName, info.Element.ElementHandle.EntityToken)) { VisualData = info.Element.VisualData }; int counter = 0; foreach (Tree tree in info.Trees) { string key = StringConstants.PiggybagSharedTreeId + (counter++); element.ElementHandle.Piggyback[key] = tree.TreeId; } ElementAttachingProviderResult result = new ElementAttachingProviderResult { Elements = new [] { info.Element }, Position = info.AttachmentPoint.Position, PositionPriority = 10000 }; yield return result; } } } public IEnumerable GetChildren(EntityToken parentEntityToken, Dictionary piggybag) { TreeSharedRootsFacade.Initialize(Context.ProviderName); List trees; if (parentEntityToken is TreePerspectiveEntityToken) { if (TreeSharedRootsFacade.SharedRootFolders.ContainsKey(parentEntityToken.Id)) trees = TreeSharedRootsFacade.SharedRootFolders[parentEntityToken.Id].Trees; else trees = new List(); } else { if (piggybag.ContainsKey(StringConstants.PiggybagTreeId)) { string treeId = piggybag.Where(f => f.Key == StringConstants.PiggybagTreeId).SingleOrDefault().Value; Tree tree = TreeFacade.GetTree(treeId); if (tree == null) return new Element[] { }; trees = new List { tree }; } else { trees = new List(); int counter = 0; while (true) { string key = StringConstants.PiggybagSharedTreeId + (counter++); if (!piggybag.ContainsKey(key)) break; string treeId = piggybag[key]; Tree tree = TreeFacade.GetTree(treeId); if (tree != null) trees.Add(tree); } } } IEnumerable result = new List(); foreach (Tree tree in trees) { TreeNodeDynamicContext dynamicContext = new TreeNodeDynamicContext(TreeNodeDynamicContextDirection.Down) { ElementProviderName = this.Context.ProviderName, Piggybag = piggybag, CurrentEntityToken = parentEntityToken }; try { if (parentEntityToken is TreePerspectiveEntityToken) { TreeNode treeNode = tree.RootTreeNode; dynamicContext.CurrentTreeNode = treeNode; IEnumerable elements = treeNode.ChildNodes.GetElements(parentEntityToken, dynamicContext); result = result.ConcatOrDefault(elements); } else if (parentEntityToken is TreeSimpleElementEntityToken) { TreeNode treeNode = tree.GetTreeNode(parentEntityToken.Id); if (treeNode == null) throw new InvalidOperationException("Tree is out of sync"); dynamicContext.CurrentTreeNode = treeNode; IEnumerable elements = treeNode.ChildNodes.GetElements(parentEntityToken, dynamicContext); result = result.ConcatOrDefault(elements); } else if (parentEntityToken is TreeFunctionElementGeneratorEntityToken) { TreeNode treeNode = tree.GetTreeNode(parentEntityToken.Id); if (treeNode == null) throw new InvalidOperationException("Tree is out of sync"); dynamicContext.CurrentTreeNode = treeNode; IEnumerable elements = treeNode.ChildNodes.GetElements(parentEntityToken, dynamicContext); result = result.ConcatOrDefault(elements); } else if (parentEntityToken is TreeDataFieldGroupingElementEntityToken) { TreeDataFieldGroupingElementEntityToken castedParentEntityToken = parentEntityToken as TreeDataFieldGroupingElementEntityToken; TreeNode treeNode = tree.GetTreeNode(parentEntityToken.Id); if (treeNode == null) throw new InvalidOperationException("Tree is out of sync"); dynamicContext.CurrentTreeNode = treeNode; dynamicContext.FieldGroupingValues = castedParentEntityToken.GroupingValues; dynamicContext.FieldFolderRangeValues = castedParentEntityToken.FolderRangeValues; IEnumerable elements = treeNode.ChildNodes.GetElements(parentEntityToken, dynamicContext); result = result.ConcatOrDefault(elements); } else if (parentEntityToken is DataEntityToken) { DataEntityToken dataEntityToken = parentEntityToken as DataEntityToken; Type interfaceType = dataEntityToken.InterfaceType; List treeNodes; if (tree.BuildProcessContext.DataInteraceToTreeNodes.TryGetValue(interfaceType, out treeNodes) == false) { throw new InvalidOperationException(); } string parentNodeId = piggybag.GetParentIdFromPiggybag(); TreeNode treeNode = treeNodes.Where(f => f.ParentNode.Id == parentNodeId).SingleOrDefault(); if (treeNode == null) throw new InvalidOperationException("Tree is out of sync"); dynamicContext.CurrentTreeNode = treeNode; IEnumerable elements = treeNode.ChildNodes.GetElements(parentEntityToken, dynamicContext); result = result.ConcatOrDefault(elements); } else { throw new NotImplementedException("Unhandled entityt token type"); } result = result.Evaluate(); } catch (Exception ex) { LoggingService.LogError("TreeFacade", string.Format("Getting elements from the three '{0}' failed", tree.TreeId)); LoggingService.LogError("TreeFacade", ex); Element errorElement = ShowErrorElementHelper.CreateErrorElement( StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "KeyFacade.ErrorTreeNode.Label"), tree.TreeId, ex.Message); return new Element[] { errorElement }; } } return result; } } } ================================================ FILE: Composite/C1Console/Trees/TreeFacade.cs ================================================ using System; using System.Collections.Generic; using System.Xml.Linq; using Composite.C1Console.Elements.Plugins.ElementAttachingProvider; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.Instrumentation; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class TreeFacade { private static readonly string LogTitle = "TreeFacade"; private static readonly ITreeFacade _implementation = new TreeFacadeImpl(); private static readonly object _lock = new object(); private static bool _initialized; static TreeFacade() { GlobalEventSystemFacade.SubscribeToPostFlushEvent(OnPostFlushEvent); } /// private static void EnsureInitialized() { if (_initialized) return; lock (_lock) { if (_initialized) return; using (new LogExecutionTime(LogTitle, "Initializing tree system")) { _implementation.Initialize(); _initialized = true; } } } /// /// Returns a tree given the id of the tree or null if no tree exist with the given id /// /// /// public static Tree GetTree(string treeId) { EnsureInitialized(); return _implementation.GetTree(treeId); } /// public static IEnumerable AllTrees { get { EnsureInitialized(); return _implementation.AllTrees; } } /// public static bool HasAttachmentPoints(EntityToken parentEntityToken) { EnsureInitialized(); return _implementation.HasAttachmentPoints(parentEntityToken); } /// public static bool HasPossibleAttachmentPoints(EntityToken parentEntityToken) { EnsureInitialized(); return _implementation.HasPossibleAttachmentPoints(parentEntityToken); } /// public static IEnumerable GetTreesByEntityToken(EntityToken parentEntityToken) { EnsureInitialized(); return _implementation.GetTreesByEntityToken(parentEntityToken); } /// /// Adds a attachment point that is persisted by the system and is loaded on every restart /// /// /// /// /// /// public static bool AddPersistedAttachmentPoint(string treeId, Type interfaceType, object keyValue, ElementAttachingProviderPosition position = ElementAttachingProviderPosition.Top) { EnsureInitialized(); return _implementation.AddPersistedAttachmentPoint(treeId, interfaceType, keyValue, position); } /// public static bool RemovePersistedAttachmentPoint(string treeId, Type interfaceType, object keyValue) { EnsureInitialized(); return _implementation.RemovePersistedAttachmentPoint(treeId, interfaceType, keyValue); } /// /// This will add a attachment point until the system flushes. /// This can be used by element provider implementors to attach trees to their exising trees. /// /// /// /// public static bool AddCustomAttachmentPoint(string treeId, EntityToken entityToken, ElementAttachingProviderPosition position = ElementAttachingProviderPosition.Top) { EnsureInitialized(); return _implementation.AddCustomAttachmentPoint(treeId, entityToken, position); } /// /// Loads a tree from an /// > /// public static Tree LoadTreeFromDom(string treeId, XDocument document) { EnsureInitialized(); return _implementation.LoadTreeFromDom(treeId, document); } private static void OnPostFlushEvent(PostFlushEventArgs args) { EnsureInitialized(); _implementation.OnFlush(); } } } ================================================ FILE: Composite/C1Console/Trees/TreeFacadeImpl.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Web.Hosting; using System.Xml; using System.Xml.Linq; using System.Xml.Xsl; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementAttachingProvider; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.C1Console.Trees.Foundation; using Composite.C1Console.Trees.Foundation.AttachmentPoints; using Composite.C1Console.Users; using Composite.Core; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Linq; using Composite.Core.ResourceSystem; using Composite.Core.Threading; using Composite.Core.Types; using Composite.Core.Xml; using Composite.Data; using Composite.Data.GeneratedTypes; using Composite.Data.ProcessControlled; using Composite.Data.Transactions; using Composite.Data.Types; using Composite.Plugins.Elements.ElementProviders.DeveloperApplicationProvider; namespace Composite.C1Console.Trees { [FlushAttribute("ReloadAllTrees")] internal sealed class TreeFacadeImpl : ITreeFacade { private static readonly string LogTitle = "TreeFacade"; private const string XslFilename = "Tree.xsl"; private static readonly ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize, false); private static readonly object _reloadAttachmentPointsSyncRoot = new object(); public void Initialize() { using (_resourceLocker.Locker) { var resources = _resourceLocker.Resources; if (!GlobalInitializerFacade.IsReinitializingTheSystem) { DataEvents.OnAfterAdd += OnUpdateTreeAttachmentPoints; DataEvents.OnDeleted += OnUpdateTreeAttachmentPoints; DataEvents.OnStoreChanged += OnTreeAttachmentPointsStoreChange; GeneratedTypesFacade.SubscribeToUpdateTypeEvent(OnDataTypeChanged); var treeAuxiliaryAncestorProvider = new TreeAuxiliaryAncestorProvider(); var entityTokenTypes = new[] { typeof (TreeSimpleElementEntityToken), typeof (TreeFunctionElementGeneratorEntityToken), typeof (TreeDataFieldGroupingElementEntityToken), typeof (DataEntityToken), typeof (TreePerspectiveEntityToken) }; entityTokenTypes.ForEach(type => AuxiliarySecurityAncestorFacade .AddAuxiliaryAncestorProvider(type, treeAuxiliaryAncestorProvider, true)); resources.PersistentAttachmentPoints = new Dictionary>(); LoadAllTrees(); InitializeTreeAttachmentPoints(); TreeSharedRootsFacade.Clear(); var fileWatcher = new C1FileSystemWatcher(TreeDefinitionsFolder, "*.xml"); fileWatcher.Created += OnReloadTrees; fileWatcher.Deleted += OnReloadTrees; fileWatcher.Changed += OnReloadTrees; fileWatcher.Renamed += OnReloadTrees; fileWatcher.EnableRaisingEvents = true; resources.FileSystemWatcher = fileWatcher; resources.RootEntityToken = ElementFacade.GetRootsWithNoSecurity().First().ElementHandle.EntityToken; } } } public Tree GetTree(string treeId) { Tree tree; using (_resourceLocker.ReadLocker) { _resourceLocker.Resources.Trees.TryGetValue(treeId, out tree); } return tree; } public IEnumerable AllTrees { get { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.Trees.Values.Evaluate(); } } } public bool HasAttachmentPoints(EntityToken parentEntityToken) { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.Trees.Any(f => f.Value.HasAttachmentPoints(parentEntityToken)); } } public bool HasPossibleAttachmentPoints(EntityToken parentEntityToken) { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.Trees.Any(f => f.Value.HasPossibleAttachmentPoints(parentEntityToken)); } } public IEnumerable GetTreesByEntityToken(EntityToken parentEntityToken) { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.Trees.Values.Where(tree => tree.HasAttachmentPoints(parentEntityToken)); } } public IEnumerable GetElementsByTreeId(string treeId, EntityToken parentEntityToken, Dictionary piggybag) { Tree tree = GetTree(treeId); if (tree == null) return new Element[] { }; var dynamicContext = new TreeNodeDynamicContext(TreeNodeDynamicContextDirection.Down) { Piggybag = piggybag, CurrentEntityToken = parentEntityToken, CurrentTreeNode = tree.RootTreeNode }; return tree.RootTreeNode.GetElements(parentEntityToken, dynamicContext); } public Tree LoadTreeFromDom(string treeId, XDocument document) { string xslFilename = Path.Combine(TreeDefinitionsFolder, XslFilename); var fileInfo = new C1FileInfo(xslFilename); // The default xslt transformation does no changes and it's xsl file has size of 358 bytes, skipping this file saves up to 0.5 second on site startup if (fileInfo.Exists && fileInfo.Length != 358) { try { var newDocument = new XDocument(); using (XmlWriter xmlWriter = newDocument.CreateWriter()) { var xslTransform = new XslCompiledTransform(); xslTransform.LoadFromPath(xslFilename); xslTransform.Transform(document.CreateReader(), xmlWriter); } document = newDocument; } catch (Exception ex) { Log.LogCritical("TreeFacade", "Failed to apply xslt on the tree {0} with the following exception", treeId); Log.LogCritical("TreeFacade", ex); } } return Load(treeId, document); } public void OnFlush() { using (_resourceLocker.Locker) { _resourceLocker.Resources.PersistentAttachmentPoints = new Dictionary>(); Initialize(); } } private void OnDataTypeChanged(EventArgs eventArgs) { OnReloadTrees(null, null); } private void OnReloadTrees(object sender, FileSystemEventArgs e) { if (HostingEnvironment.ApplicationHost.ShutdownInitiated()) { return; } Thread.CurrentThread.CurrentCulture = UserSettings.CultureInfo; using (GlobalInitializerFacade.CoreIsInitializedScope) using (_resourceLocker.Locker) { TimeSpan timeSpan = DateTime.Now - _resourceLocker.Resources.LastFileChange; if (timeSpan.TotalMilliseconds > 100) { _resourceLocker.Resources.LastFileChange = DateTime.Now; ReloadAllTrees(); } } } private void LoadAllTrees() { using (_resourceLocker.Locker) { _resourceLocker.Resources.Trees = new Dictionary(); Log.LogVerbose(LogTitle, "Loading all tree definitions from {0}", TreeDefinitionsFolder); foreach (string filename in C1Directory.GetFiles(TreeDefinitionsFolder, "*.xml")) { string treeId = Path.GetFileName(filename); try { Log.LogVerbose(LogTitle, "Loading tree from file: " + filename); int t1 = Environment.TickCount; Tree tree = LoadTreeFromFile(treeId); if (tree.BuildResult.ValidationErrors.Any()) { Log.LogError(LogTitle, "Tree {0} was not loaded due to the following validation errors", treeId); foreach (ValidationError validationError in tree.BuildResult.ValidationErrors) { if (string.IsNullOrEmpty(validationError.XPath)) { Log.LogError("TreeFacade", $"{validationError.Message} in {filename}"); } else { Log.LogError("TreeFacade", $"{validationError.Message} at {validationError.XPath} in {filename}"); } } } else { _resourceLocker.Resources.Trees.Add(treeId, tree); } int msElapsed = Environment.TickCount - t1; if (msElapsed > 20) { Log.LogVerbose("TreeFacade", "Time spend on loading the tree: " + msElapsed + "ms, file: " + filename); } } catch (Exception ex) { Log.LogError("TreeFacade: Failed to load the tree " + treeId, ex); //Tree errorTree = CreateErrorTree(treeId, ex.Message); //if (_resourceLocker.Resources.Trees.ContainsKey(errorTree.TreeId) == false) //{ // _resourceLocker.Resources.Trees.Add(errorTree.TreeId, errorTree); //} } } } } private Tree CreateErrorTree(string treeId, string errorMessage) { var tree = new Tree("ERRORTREE:" + treeId) { BuildProcessContext = new BuildProcessContext(), BuildResult = new BuildResult() }; tree.AttachmentPoints.Add( new EntityTokenAttachmentPoint { EntityToken = new DeveloperApplicationProviderEntityToken(DeveloperApplicationProviderEntityToken.TreeDefinitionId, treeId), Position = ElementAttachingProviderPosition.Top } ); tree.RootTreeNode = new RootTreeNode() { Id = "ERRORTREEROOT", Tree = tree }; var simpleElementTreeNode = new SimpleElementTreeNode() { Label = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "KeyFacade.ErrorTreeNode.Label"), Id = "ERROR", ToolTip = errorMessage, Icon = ResourceHandle.BuildIconFromDefaultProvider("close"), Tree = tree }; var messageBoxActionNode = new MessageBoxActionNode { Id = 1, OwnerNode = simpleElementTreeNode, Label = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "KeyFacade.ErrorTreeNode.ShowMessage.Label"), ToolTip = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "KeyFacade.ErrorTreeNode.ShowMessage.ToolTip"), Icon = ResourceHandle.BuildIconFromDefaultProvider("log-showlog"), Title = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "KeyFacade.ErrorTreeNode.ShowMessage.Title"), Message = errorMessage, DialogType = DialogType.Error, PermissionTypes = new List { PermissionType.Administrate } }; simpleElementTreeNode.AddActionNode(messageBoxActionNode); tree.RootTreeNode.AddChildTreeNode(simpleElementTreeNode); return tree; } private Tree LoadTreeFromFile(string treeId) { string filename = Path.Combine(TreeDefinitionsFolder, treeId); for (int i = 0; i < 10; i++) { try { XDocument document = XDocumentUtils.Load(filename); return LoadTreeFromDom(treeId, document); } catch (IOException) { Thread.Sleep(100); } } throw new InvalidOperationException("Could not load tree " + treeId); } private void ReloadAllTrees() { using (ThreadDataManager.EnsureInitialize()) { LoadAllTrees(); InitializeTreeAttachmentPoints(); TreeSharedRootsFacade.Clear(); using (_resourceLocker.ReadLocker) { var refreshTreeMessageQueueItem = new RefreshTreeMessageQueueItem { EntityToken = _resourceLocker.Resources.RootEntityToken }; ConsoleMessageQueueFacade.Enqueue(refreshTreeMessageQueueItem, null); } } } private Tree Load(string treeId, XDocument document) { Tree tree = TreeBuilder.BuildTree(treeId, document); //if (tree.BuildResult.ValidationErrors.Count() == 0) //{ // tree.LogTree(); //} return tree; } private void OnTreeAttachmentPointsStoreChange(object sender, StoreEventArgs storeEventArgs) { if (!storeEventArgs.DataEventsFired) { InitializeTreeAttachmentPoints(); } } private void OnUpdateTreeAttachmentPoints(object sender, DataEventArgs dataEventArgs) { InitializeTreeAttachmentPoints(); } #region Attachment points public bool AddPersistedAttachmentPoint(string treeId, Type interfaceType, object keyValue, ElementAttachingProviderPosition position = ElementAttachingProviderPosition.Top) { var attachmentPoint = DataFacade.BuildNew(); attachmentPoint.Id = Guid.NewGuid(); attachmentPoint.TreeId = treeId; attachmentPoint.Position = position.ToString(); attachmentPoint.InterfaceType = TypeManager.SerializeType(interfaceType); attachmentPoint.KeyValue = ValueTypeConverter.Convert(keyValue); bool added = false; using (var transactionScope = TransactionsFacade.CreateNewScope()) { bool exist = (from d in DataFacade.GetData() where d.InterfaceType == attachmentPoint.InterfaceType && d.KeyValue == attachmentPoint.KeyValue && d.TreeId == treeId select d).Any(); if (!exist) { DataFacade.AddNew(attachmentPoint); added = true; } transactionScope.Complete(); } return added; } public bool RemovePersistedAttachmentPoint(string treeId, Type interfaceType, object keyValue) { string serializedInterfaceType = TypeManager.SerializeType(interfaceType); string serializedKeyValue = ValueTypeConverter.Convert(keyValue); bool removed = false; using (var transactionScope = TransactionsFacade.CreateNewScope()) { IEnumerable dataItemTreeAttachmentPoints = (from d in DataFacade.GetData() where d.InterfaceType == serializedInterfaceType && d.KeyValue == serializedKeyValue && d.TreeId == treeId select d).Evaluate(); if (dataItemTreeAttachmentPoints.Any()) { DataFacade.Delete(dataItemTreeAttachmentPoints); removed = true; } transactionScope.Complete(); } return removed; } /// /// This will add a attachment point until the system flushes. /// This can be used by element provider implementors to attach trees to their existing trees. /// /// /// /// public bool AddCustomAttachmentPoint(string treeId, EntityToken entityToken, ElementAttachingProviderPosition position = ElementAttachingProviderPosition.Top) { Tree tree = GetTree(treeId); if (tree == null) return false; var customAttachmentPoint = new CustomAttachmentPoint(entityToken, position); tree.AttachmentPoints.Add(customAttachmentPoint); List attachmentPoints; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.PersistentAttachmentPoints.TryGetValue(treeId, out attachmentPoints) == false) { attachmentPoints = new List(); _resourceLocker.Resources.PersistentAttachmentPoints.Add(treeId, attachmentPoints); } } attachmentPoints.Add(customAttachmentPoint); return true; } private void ClearAttachmentPoints() where T : IAttachmentPoint { using (_resourceLocker.ReadLocker) { foreach (Tree tree in _resourceLocker.Resources.Trees.Values) { tree.ClearAttachmentPoints(); } } } private void InitializeTreeAttachmentPoints() { lock (_reloadAttachmentPointsSyncRoot) { ClearAttachmentPoints(); IEnumerable attachmentPoints = DataFacade.GetData().Evaluate(); foreach (IDataItemTreeAttachmentPoint attachmentPoint in attachmentPoints) { Tree tree = GetTree(attachmentPoint.TreeId); if (tree == null) { string treePath = Path.Combine(TreeDefinitionsFolder, attachmentPoint.TreeId); if (!C1File.Exists(treePath)) // This ensures that invalid, but existing trees does not remove these attachment points { if (DataFacade.WillDeleteSucceed(attachmentPoint)) { Log.LogWarning("TreeFacade", "A data item attachment points is referring a non existing tree '{0}' and is deleted", attachmentPoint.TreeId); // Preventing events so this method won't call itself recursively DataFacade.Delete(attachmentPoint, true, CascadeDeleteType.Allow); } } continue; } Type interfaceType = TypeManager.GetType(attachmentPoint.InterfaceType); object keyValue = ValueTypeConverter.Convert(attachmentPoint.KeyValue, interfaceType.GetKeyProperties()[0].PropertyType); var position = (ElementAttachingProviderPosition)Enum.Parse(typeof(ElementAttachingProviderPosition), attachmentPoint.Position); var dataItemTreeAttachmentPoint = new DynamicDataItemAttachmentPoint { InterfaceType = interfaceType, KeyValue = keyValue, Position = position }; // Log.LogVerbose("TreeFacade", string.Format("Tree with id '{0}' is dynamically attached to the data type '{1}' with key value of '{2}'", attachmentPoint.TreeId, interfaceType, keyValue)); tree.AttachmentPoints.Add(dataItemTreeAttachmentPoint); DataEventSystemFacade.SubscribeToDataDeleted(interfaceType, OnDataItemDeleted, false); } using (_resourceLocker.ReadLocker) { foreach (var kvp in _resourceLocker.Resources.PersistentAttachmentPoints) { Tree tree = GetTree(kvp.Key); if (tree == null) continue; tree.AttachmentPoints.AddRange(kvp.Value); } } } } private static void OnDataItemDeleted(object sender, DataEventArgs dataEventArgs) { Type interfaceType = dataEventArgs.Data.DataSourceId.InterfaceType; if (typeof(IPublishControlled).IsAssignableFrom(interfaceType) && !dataEventArgs.Data.DataSourceId.DataScopeIdentifier.Equals(DataScopeIdentifier.Administrated)) { return; // Only remove attachment point if its the admin version of a publishable data item that have been delete } if (typeof(ILocalizedControlled).IsAssignableFrom(interfaceType) && DataFacade.ExistsInAnyLocale(interfaceType, dataEventArgs.Data.DataSourceId.LocaleScope)) { return; // Data exists in other locales, so do not remove this attachment point } if (typeof(IVersioned).IsAssignableFrom(interfaceType) && interfaceType.GetKeyProperties().Count == 1) { var key = dataEventArgs.Data.GetUniqueKey(); var versions = DataFacade.TryGetDataVersionsByUniqueKey(interfaceType, key).ToList(); if (versions.Count > 0) { return; // Do not delete the attachment point if the data is versioned // and not all of the versions of the element are deleted. } } PropertyInfo propertyInfo = interfaceType.GetKeyProperties()[0]; string keyValue = ValueTypeConverter.Convert(propertyInfo.GetValue(dataEventArgs.Data, null)); var serializedInterfaceType = TypeManager.SerializeType(interfaceType); var attachmentPoints = DataFacade.GetData() .Where(ap => ap.KeyValue == keyValue && ap.InterfaceType == serializedInterfaceType); DataFacade.Delete(attachmentPoints); } private static string TreeDefinitionsFolder { get { return PathUtil.Resolve(GlobalSettingsFacade.TreeDefinitionsDirectory); } } #endregion private sealed class Resources { public Dictionary Trees { get; set; } public Dictionary> PersistentAttachmentPoints { get; set; } public C1FileSystemWatcher FileSystemWatcher { get; set; } public DateTime LastFileChange { get; set; } public EntityToken RootEntityToken { get; set; } public static void Initialize(Resources resources) { resources.Trees = new Dictionary(); resources.PersistentAttachmentPoints = new Dictionary>(); } } } } ================================================ FILE: Composite/C1Console/Trees/TreeFunctionElementGeneratorEntityToken.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Security; using Composite.C1Console.Security.SecurityAncestorProviders; using Composite.Core; using Composite.Core.Serialization; using Newtonsoft.Json; namespace Composite.C1Console.Trees { [SecurityAncestorProvider(typeof(NoAncestorSecurityAncestorProvider))] internal sealed class TreeFunctionElementGeneratorEntityToken : EntityToken, IEntityTokenContainingParentEntityToken { private EntityToken _parentEntityToken; private readonly string _treeNodeId; private readonly string _treeId; private readonly string _serializedParentEntityToken; public TreeFunctionElementGeneratorEntityToken(string treeNodeId, string treeId, string serializedParentEntityToken, string elementId) { _treeNodeId = treeNodeId; _treeId = treeId; _serializedParentEntityToken = serializedParentEntityToken; this.ElementId = elementId; } [JsonConstructor] private TreeFunctionElementGeneratorEntityToken(string id, string source, EntityToken parentEntityToken, string elementId) { _treeNodeId = id; _treeId = source; _parentEntityToken = parentEntityToken; this.ElementId = elementId; } public override string Type => _serializedParentEntityToken; public override string Source => _treeId; public override string Id => _treeNodeId; public string ElementId { get; set; } public string TreeNodeId => this.Id; [JsonIgnore] public EntityToken ParentEntityToken { get { if (_parentEntityToken == null) { _parentEntityToken = EntityTokenSerializer.Deserialize(this.Type); } return _parentEntityToken; } } public EntityToken GetParentEntityToken() { return this.ParentEntityToken; } public override string Serialize() { return CompositeJsonSerializer.Serialize(this); } public static EntityToken Deserialize(string serializedEntityToken) { EntityToken entityToken; if (CompositeJsonSerializer.IsJsonSerialized(serializedEntityToken)) { entityToken = CompositeJsonSerializer.Deserialize(serializedEntityToken); } else { entityToken = DeserializeLegacy(serializedEntityToken); Log.LogVerbose(nameof(TreeFunctionElementGeneratorEntityToken), entityToken.GetType().FullName); } return entityToken; } public static EntityToken DeserializeLegacy(string serializedEntityToken) { string type, source, id; Dictionary dic; DoDeserialize(serializedEntityToken, out type, out source, out id, out dic); string elementId = StringConversionServices.DeserializeValueString(dic["ElementId"]); return new TreeFunctionElementGeneratorEntityToken(id, source, type, elementId); } public override int GetHashCode() { return base.GetHashCode() ^ this.ElementId.GetHashCode(); } public override bool Equals(object obj) { return base.Equals(obj) && (obj as TreeFunctionElementGeneratorEntityToken).ElementId == this.ElementId; } public override void OnGetPrettyHtml(EntityTokenHtmlPrettyfier prettyfier) { EntityToken parentEntityToken = this.ParentEntityToken; prettyfier.OnWriteType = (token, helper) => helper.AddFullRow(new string[] { "Type", string.Format("ParentEntityToken:
Type: {0}
Source: {1}
Id:{2}
", parentEntityToken.Type, parentEntityToken.Source, parentEntityToken.Id) }); } public override string OnGetTypePrettyHtml() { EntityToken parentEntityToken = this.ParentEntityToken; string type; IEntityTokenContainingParentEntityToken containingParentEnitytToken = parentEntityToken as IEntityTokenContainingParentEntityToken; if (containingParentEnitytToken != null) { type = string.Format(@"
{0}
", parentEntityToken.OnGetTypePrettyHtml()); } else { type = parentEntityToken.Type; } return string.Format("ParentEntityToken:
Type: {0}
Source: {1}
Id:{2}
", type, parentEntityToken.Source, parentEntityToken.Id); } } } ================================================ FILE: Composite/C1Console/Trees/TreeMarkupConstants.cs ================================================ using System.Xml.Linq; namespace Composite.C1Console.Trees { internal static class TreeMarkupConstants { public static string NamespaceString = "http://www.composite.net/ns/management/trees/treemarkup/1.0"; public static XNamespace Namespace = (XNamespace)NamespaceString; } } ================================================ FILE: Composite/C1Console/Trees/TreeNode.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.C1Console.Workflow; namespace Composite.C1Console.Trees { /// /// Information about the ancestor node withing the same tree /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class AncestorResult { /// public AncestorResult(TreeNode treeNode, EntityToken entityToken) { this.TreeNode = treeNode; this.EntityToken = entityToken; } /// public TreeNode TreeNode { get; private set; } /// public EntityToken EntityToken { get; private set; } } /// /// Represents a node in tree definition /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class TreeNode { /// protected List _childNodes = new List(); /// protected List _actionNodes = new List(); /// protected List _orderByNodes = new List(); /// protected List _filterNodes = new List(); /// public string XPath { get; internal set; } /// public string Id { get; internal set; } /// public Tree Tree { get; internal set; } /// public TreeNode ParentNode { get; internal set; } /// public IEnumerable ChildNodes { get { return _childNodes; } } /// public IEnumerable ActionNodes { get { return _actionNodes; } } /// public IEnumerable OrderByNodes { get { return _orderByNodes; } } /// public IEnumerable FilterNodes { get { return _filterNodes; } } /// /// This is call when this nodes entity tokens are needed to climb up the tree. /// If this tree nodes elements dont have any children, then this method will not be called. /// /// The child entity token. /// The dynamic context. /// public abstract IEnumerable GetEntityTokens(EntityToken childEntityToken, TreeNodeDynamicContext dynamicContext); /// /// This is called when a node has genereted its own entity tokens (by a child) and the child /// needs to filter these entity token /// /// The self entity token. /// The parent genereted entity tokens. /// The dynamic context. /// internal virtual IEnumerable FilterParentGeneretedEntityTokens(EntityToken selfEntityToken, IEnumerable parentGeneretedEntityTokens, TreeNodeDynamicContext dynamicContext) { return parentGeneretedEntityTokens; } /// /// This is called to, in the end, find a parent data entity token, so that the data item behind it can be used /// by the start caller (ParentIdFilterNode) to get its own data item for creating an upward filter. /// /// If more than one parent exists, the first one is enough /// /// We are only looking for a data entity token, so 'jumping over' other /// parents is allowed. /// /// /// /// We are searching for a data entity token of interface type state in this parameter /// /// /// public abstract AncestorResult GetParentEntityToken(EntityToken ownEntityToken, Type parentInterfaceOfInterest, TreeNodeDynamicContext dynamicContext); /// /// This is called when this nodes elements are needed to create next sub level of tree elements. /// /// /// /// protected abstract IEnumerable OnGetElements(EntityToken parentEntityToken, TreeNodeDynamicContext dynamicContext); /// public IEnumerable GetElements(EntityToken parentEntityToken, TreeNodeDynamicContext dynamicContext) { IEnumerable elements = OnGetElements(parentEntityToken, dynamicContext); var localizeDataWorkflow = WorkflowFacade.GetWorkflowType("Composite.C1Console.Trees.Workflows.LocalizeDataWorkflow"); foreach (Element element in elements) { bool isForeignLocaleDataItem = element.Actions .Any(x => x.ActionHandle.ActionToken is WorkflowActionToken && ((WorkflowActionToken)x.ActionHandle.ActionToken).WorkflowType == localizeDataWorkflow); if (!isForeignLocaleDataItem) { foreach (ActionNode actionNode in this.ActionNodes) { actionNode.AddAction(element.AddAction, element.ElementHandle.EntityToken, dynamicContext); } } yield return element; } } /// /// This is called after the build of the tree is finished /// /// protected virtual void OnInitialize() { } /// public void Initialize() { this.OnInitialize(); foreach (TreeNode treeNode in this.ChildNodes) { treeNode.Initialize(); } } internal void AddValidationError(string stringName, params object[] args) { this.Tree.AddValidationError(this.XPath, stringName, args); } internal TreeNode AddChildTreeNode(TreeNode treeNode) { treeNode.ParentNode = this; _childNodes.Add(treeNode); return this; } internal void RemoveChildTreeNode(TreeNode treeNode) { _childNodes.Remove(treeNode); } internal void AddActionNode(ActionNode actionNode) { actionNode.OwnerNode = this; _actionNodes.Add(actionNode); } internal void AddOrderByNode(OrderByNode orderByNode) { orderByNode.SetOwnerNode(this); _orderByNodes.Add(orderByNode); } internal void AddFilterNode(FilterNode filterNode) { filterNode.SetOwnerNode(this); _filterNodes.Add(filterNode); } internal bool IsAncestor(TreeNode treeNode) { TreeNode ancestorNode = this.ParentNode; while (ancestorNode != null) { if (ancestorNode.Id == treeNode.Id) return true; ancestorNode = ancestorNode.ParentNode; } return false; } internal bool IsDescendant(TreeNode treeNode) { return this.ChildNodes.Any(childNode => childNode.Id == treeNode.Id || childNode.IsDescendant(treeNode)); } /// protected string ParentString() { return "ParentId = " + ((ParentNode != null) ? ParentNode.Id : "-1"); } } } ================================================ FILE: Composite/C1Console/Trees/TreeNodeDynamicContext.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using Composite.C1Console.Security; using System.Reflection; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum TreeNodeDynamicContextDirection { /// Down, // Creating elements /// Up // Getting ancestor entity tokens } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DebuggerDisplay("TreeNodeDynamicContext. Direction: {Direction}")] public sealed class TreeNodeDynamicContext { private Dictionary _fieldGroupingValues; private Dictionary _fieldFolderRangeValues; /// public TreeNodeDynamicContext(TreeNodeDynamicContextDirection treeNodeDynamicContextDirection) { this.Direction = treeNodeDynamicContextDirection; this.CustomData = new Dictionary(); } /// public string ElementProviderName { get; set; } /// public TreeNodeDynamicContextDirection Direction { get; internal set; } /// public Dictionary FieldGroupingValues { get { if (_fieldGroupingValues == null) { _fieldGroupingValues = new Dictionary(); } return _fieldGroupingValues; } set { _fieldGroupingValues = value; } } /// public Dictionary FieldFolderRangeValues { get { if (_fieldFolderRangeValues == null) { _fieldFolderRangeValues = new Dictionary(); } return _fieldFolderRangeValues; } set { _fieldFolderRangeValues = value; } } /// public Dictionary Piggybag { get; set; } /// public EntityToken CurrentEntityToken { get; set; } /// public TreeNode CurrentTreeNode { get; set; } internal Dictionary CustomData { get; set; } internal bool IsRoot { get; set; } } } ================================================ FILE: Composite/C1Console/Trees/TreeNodeExtensionMethods.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.C1Console.Elements; using Composite.Core.Logging; using Composite.C1Console.Security; namespace Composite.C1Console.Trees { internal static class TreeNodeExtensions { public static IEnumerable OfType(this IEnumerable filterNodes) where T : FilterNode { return filterNodes.Where(f => f.GetType() == typeof(T)).Cast(); } public static IEnumerable GetElements(this IEnumerable treeNodes, EntityToken parentEntityToken, TreeNodeDynamicContext dynamicContext) { IEnumerable elements = null; foreach (TreeNode treeNode in treeNodes) { if (elements == null) { elements = treeNode.GetElements(parentEntityToken, dynamicContext); } else { elements = elements.Concat(treeNode.GetElements(parentEntityToken, dynamicContext)); } } if (elements == null) { elements = new List(); } return elements; } public static bool SelfAndParentsHasInterface(this TreeNode treeNode, Type interfaceType) { DataFilteringTreeNode dataFilteringTreeNode = null; while (treeNode != null) { dataFilteringTreeNode = treeNode as DataFilteringTreeNode; if (dataFilteringTreeNode != null) break; treeNode = treeNode.ParentNode; } if (dataFilteringTreeNode == null) return false; if (dataFilteringTreeNode.CurrentDataInterfaceType == interfaceType) return true; return treeNode.ParentNode.SelfAndParentsHasInterface(interfaceType); } public static IEnumerable AncestorsAndSelf(this TreeNode treeNode) { return Ancestors(treeNode, true); } public static IEnumerable Ancestors(this TreeNode treeNode, bool includeSelf = false) { if (includeSelf) { yield return treeNode; } TreeNode parentTreeNode = treeNode.ParentNode; while (parentTreeNode != null) { yield return parentTreeNode; parentTreeNode = parentTreeNode.ParentNode; } } public static IEnumerable Descendants(this TreeNode treeNode, bool includeSelf = false) { if (includeSelf) yield return treeNode; foreach (TreeNode childTreeNode in treeNode.ChildNodes) { foreach (TreeNode node in childTreeNode.DescendantsImpl()) { yield return node; } } } private static IEnumerable DescendantsImpl(this TreeNode treeNode) { yield return treeNode; foreach (TreeNode childTreeNode in treeNode.ChildNodes) { foreach (TreeNode node in childTreeNode.DescendantsImpl()) { yield return node; } } } public static IEnumerable DescendantsBreadthFirst(this TreeNode treeNode, bool includeSelf = false) { Queue notVisistedTreeNodes = new Queue(); if (includeSelf) { notVisistedTreeNodes.Enqueue(treeNode); } else { foreach (TreeNode childTreeNode in treeNode.ChildNodes) { notVisistedTreeNodes.Enqueue(childTreeNode); } } while (notVisistedTreeNodes.Count > 0) { TreeNode tn = notVisistedTreeNodes.Dequeue(); foreach (TreeNode ctn in tn.ChildNodes) { notVisistedTreeNodes.Enqueue(ctn); } yield return tn; } } public static void LogTree(this TreeNode treeNodes, int level = 0) { LogTree(new TreeNode[] { treeNodes }, level); } public static void LogTree(this IEnumerable treeNodes) { LogTree(treeNodes, 0); } public static void LogTree(this IEnumerable treeNodes, int level) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < level; i++) { sb.Append(" "); } //sb.Append( foreach (TreeNode treeNode in treeNodes) { LoggingService.LogVerbose("TreeFacade", string.Format("{0}{1}", sb, treeNode.ToString())); sb.Append(" "); LogFilter(treeNode.FilterNodes, sb.ToString()); LogOrderBy(treeNode.OrderByNodes, sb.ToString()); LogActions(treeNode.ActionNodes, sb.ToString()); LogTree(treeNode.ChildNodes, level + 1); } } private static void LogFilter(IEnumerable filterNodes, string spacer) { foreach (FilterNode filterNode in filterNodes) { LoggingService.LogVerbose("TreeFacade", string.Format("{0}* {1}", spacer, filterNode.ToString())); } } private static void LogOrderBy(IEnumerable orderByNodes, string spacer) { foreach (OrderByNode orderByNode in orderByNodes) { LoggingService.LogVerbose("TreeFacade", string.Format("{0}¤ {1}", spacer, orderByNode.ToString())); } } private static void LogActions(IEnumerable actionNodes, string spacer) { foreach (ActionNode actionNode in actionNodes) { LoggingService.LogVerbose("TreeFacade", string.Format("{0}# {1}", spacer, actionNode.ToString())); } } internal static void InitializeActions(this TreeNode treeNode) { foreach (ActionNode actionNode in treeNode.ActionNodes) { actionNode.Initialize(); } } internal static void InitializeOrderByes(this TreeNode treeNode) { foreach (OrderByNode orderByNode in treeNode.OrderByNodes) { orderByNode.Initialize(); } } internal static void InitializeFilters(this TreeNode treeNode) { foreach (FilterNode filterNode in treeNode.FilterNodes) { filterNode.Initialize(); } } } } ================================================ FILE: Composite/C1Console/Trees/TreeSharedRootsFacade.cs ================================================ using System.Collections.Generic; using System.Linq; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Foundation; using Composite.C1Console.Elements.Foundation.PluginFacades; using Composite.C1Console.Security; using Composite.C1Console.Trees.Foundation; using Composite.C1Console.Trees.Foundation.AttachmentPoints; namespace Composite.C1Console.Trees { internal class CustomTreePerspectiveInfo { public NamedAttachmentPoint AttachmentPoint { get; set; } public Element Element { get; set; } public List Trees { get; set; } } internal static class TreeSharedRootsFacade { private static volatile IReadOnlyDictionary _sharedRootFolders; private static string _elementAttachingProviderName; private static readonly object _lock = new object(); public static IReadOnlyDictionary SharedRootFolders => GetSharedRootsInt(null); public static void Initialize(string elementAttachingProviderName = null) { GetSharedRootsInt(elementAttachingProviderName); } private static IReadOnlyDictionary GetSharedRootsInt(string elementAttachingProviderName) { var result = _sharedRootFolders; if (result != null) return result; lock (_lock) { result = _sharedRootFolders; if (result != null) return result; if (_elementAttachingProviderName == null) { _elementAttachingProviderName = elementAttachingProviderName ?? GetElementAttachingProviderName(); } result = GetSharedRoots(_elementAttachingProviderName); _sharedRootFolders = result; return result; } } private static string GetElementAttachingProviderName() { foreach (string providerName in ElementAttachingProviderRegistry.ElementAttachingProviderNames) { var provider = ElementAttachingProviderPluginFacade.GetElementAttachingProvider(providerName); if (provider is TreeElementAttachingProvider) { return providerName; } } return null; } public static void Clear() { _sharedRootFolders = null; } private static IReadOnlyDictionary GetSharedRoots(string elementAttachingProviderName) { var sharedRootFolders = new Dictionary(); foreach (var tree in TreeFacade.AllTrees) { if (!tree.ShareRootElementById) continue; IEnumerable namedAttachmentPoints = tree.AttachmentPoints. OfType(); if (namedAttachmentPoints.Count() != 1) continue; if (tree.RootTreeNode.ChildNodes.Count() != 1) continue; SimpleElementTreeNode childTreeNode = tree.RootTreeNode.ChildNodes.Single() as SimpleElementTreeNode; if (childTreeNode == null) continue; NamedAttachmentPoint namedAttachmentPoint = namedAttachmentPoints.Single(); EntityToken perspectiveEntityToken; if (!sharedRootFolders.ContainsKey(childTreeNode.Id)) { perspectiveEntityToken = new TreePerspectiveEntityToken(childTreeNode.Id); var dynamicValuesHelperReplaceContext = new DynamicValuesHelperReplaceContext( namedAttachmentPoint.AttachingPoint.EntityToken, null); // MRJ: Collection actions Element element = new Element(new ElementHandle(elementAttachingProviderName, perspectiveEntityToken)) { VisualData = new ElementVisualizedData { Label = childTreeNode.LabelDynamicValuesHelper.ReplaceValues(dynamicValuesHelperReplaceContext), ToolTip = childTreeNode.ToolTipDynamicValuesHelper.ReplaceValues(dynamicValuesHelperReplaceContext), HasChildren = true, Icon = childTreeNode.Icon, OpenedIcon = childTreeNode.OpenIcon } }; sharedRootFolders.Add(childTreeNode.Id, new CustomTreePerspectiveInfo { AttachmentPoint = new NamedAttachmentPoint { AttachingPoint = new AttachingPoint(namedAttachmentPoint.AttachingPoint), Position = namedAttachmentPoint.Position }, Element = element, Trees = new List { tree } }); } else { perspectiveEntityToken = sharedRootFolders[childTreeNode.Id].Element.ElementHandle.EntityToken; sharedRootFolders[childTreeNode.Id].Trees.Add(tree); } namedAttachmentPoint.AttachingPoint = new AttachingPoint(perspectiveEntityToken); tree.RootTreeNode = childTreeNode; } return sharedRootFolders; } } } ================================================ FILE: Composite/C1Console/Trees/TreeSimpleElementEntityToken.cs ================================================ using System.Diagnostics; using Composite.C1Console.Security; using Composite.C1Console.Security.SecurityAncestorProviders; using Composite.Core.Serialization; using Newtonsoft.Json; using Composite.Core; using Newtonsoft.Json.Linq; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(NoAncestorSecurityAncestorProvider))] [DebuggerDisplay("Id = {Id}, TreeId = {Source}, ParentEntityToken = {Type}")] public sealed class TreeSimpleElementEntityToken : EntityToken, IEntityTokenContainingParentEntityToken { private EntityToken _parentEntityToken; private readonly string _treeNodeId; private readonly string _treeId; private readonly string _serializedParentEntityToken; /// public TreeSimpleElementEntityToken(string treeNodeId, string treeId, string serializedParentEntityToken) { _treeNodeId = treeNodeId; _treeId = treeId; _serializedParentEntityToken = serializedParentEntityToken; } [JsonConstructor] private TreeSimpleElementEntityToken(string treeNodeId, string treeId, JRaw parentEntityToken, string serializedParentEntityToken) { _treeNodeId = treeNodeId; _treeId = treeId; _serializedParentEntityToken = parentEntityToken?.Value.ToString() ?? serializedParentEntityToken; } /// [JsonProperty(PropertyName = "serializedParentEntityToken")] public override string Type => _serializedParentEntityToken; /// public bool ShouldSerializeType() { return !CompositeJsonSerializer.IsJsonSerialized(_serializedParentEntityToken); } [JsonProperty(PropertyName = "parentEntityToken")] private JRaw rawSerializedParentEntityToken => new JRaw(_serializedParentEntityToken); /// public bool ShouldSerializerawSerializedParentEntityToken() { return CompositeJsonSerializer.IsJsonSerialized(_serializedParentEntityToken); } /// [JsonProperty(PropertyName = "treeId")] public override string Source => _treeId; /// [JsonProperty(PropertyName = "treeNodeId")] public override string Id => _treeNodeId; /// [JsonIgnore] public string TreeNodeId => this.Id; /// [JsonIgnore] public string SerializedParentEntityToken => _serializedParentEntityToken; /// [JsonIgnore] public EntityToken ParentEntityToken { get { if (_parentEntityToken == null) { _parentEntityToken = EntityTokenSerializer.Deserialize(_serializedParentEntityToken); } return _parentEntityToken; } } /// public EntityToken GetParentEntityToken() { return this.ParentEntityToken; } /// public override string Serialize() { return CompositeJsonSerializer.Serialize(this); } /// public static EntityToken Deserialize(string serializedEntityToken) { EntityToken entityToken; if (CompositeJsonSerializer.IsJsonSerialized(serializedEntityToken)) { entityToken = CompositeJsonSerializer.Deserialize(serializedEntityToken); } else { entityToken = DeserializeLegacy(serializedEntityToken); Log.LogVerbose(nameof(TreeSimpleElementEntityToken), entityToken.GetType().FullName); } return entityToken; } /// public static EntityToken DeserializeLegacy(string serializedEntityToken) { string type, source, id; DoDeserialize(serializedEntityToken, out type, out source, out id); return new TreeSimpleElementEntityToken(id, source, type); } /// public override void OnGetPrettyHtml(EntityTokenHtmlPrettyfier prettyfier) { EntityToken parentEntityToken = this.ParentEntityToken; prettyfier.OnWriteType = (token, helper) => helper.AddFullRow(new string[] { "Type", string.Format("ParentEntityToken:
Type: {0}
Source: {1}
Id:{2}
", parentEntityToken.Type, parentEntityToken.Source, parentEntityToken.Id) }); } /// public override string OnGetTypePrettyHtml() { EntityToken parentEntityToken = this.ParentEntityToken; string type; if ((parentEntityToken is TreeSimpleElementEntityToken)) { type = string.Format(@"
{0}
", parentEntityToken.OnGetTypePrettyHtml()); } else { type = parentEntityToken.Type; } return string.Format("ParentEntityToken:
Type: {0}
Source: {1}
Id:{2}
", type, parentEntityToken.Source, parentEntityToken.Id); } } } ================================================ FILE: Composite/C1Console/Trees/ValidationError.cs ================================================ using Composite.Core.ResourceSystem; namespace Composite.C1Console.Trees { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ValidationError { /// public static ValidationError Create(string xPath, string stringName, params object[] args) { string resourceString; try { resourceString = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", stringName); } catch { resourceString = string.Format("STRING RESOURCE NAMED '{0}' NOT FOUND", stringName); } return new ValidationError(xPath, string.Format(resourceString, args)); } /// public ValidationError(string xPath, string message) { this.XPath = xPath; this.Message = message; } /// public string XPath { get; set; } /// public string Message { get; set; } } } ================================================ FILE: Composite/C1Console/Trees/WorkflowActionNode.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Elements; using Composite.Core.ResourceSystem; using Composite.C1Console.Security; using Composite.Core.Types; using Composite.C1Console.Workflow; namespace Composite.C1Console.Trees { internal sealed class WorkflowActionNode : ActionNode { public Type WorkflowType { get; internal set; } // Requried protected override void OnAddAction(Action actionAdder, EntityToken entityToken, TreeNodeDynamicContext dynamicContext, DynamicValuesHelperReplaceContext dynamicValuesHelperReplaceContext) { WorkflowActionToken actionToken = new WorkflowActionToken( WorkflowFacade.GetWorkflowType(TypeManager.SerializeType(this.WorkflowType)), this.PermissionTypes) { Payload = this.Serialize(), ExtraPayload = PiggybagSerializer.Serialize(dynamicContext.Piggybag.PreparePiggybag(dynamicContext.CurrentTreeNode, dynamicContext.CurrentEntityToken)), DoIgnoreEntityTokenLocking = true }; actionAdder(new ElementAction(new ActionHandle(actionToken)) { VisualData = CreateActionVisualizedData(dynamicValuesHelperReplaceContext) }); } } } ================================================ FILE: Composite/C1Console/Users/IUserSettingsFacade.cs ================================================ using System.Collections.Generic; using System.Globalization; using System.Net; namespace Composite.C1Console.Users { internal interface IUserSettingsFacade { string Username { get; } CultureInfo CultureInfo { get; set; } CultureInfo C1ConsoleUiLanguage { get; set; } CultureInfo GetUserCultureInfo(string username); void SetUserCultureInfo(string username, CultureInfo cultureInfo); CultureInfo GetUserC1ConsoleUiLanguage(string username); void SetUserC1ConsoleUiLanguage(string username, CultureInfo cultureInfo); CultureInfo GetCurrentActiveLocaleCultureInfo(string username); void SetCurrentActiveLocaleCultureInfo(string username, CultureInfo cultureInfo); void AddActiveLocaleCultureInfo(string username, CultureInfo cultureInfo); void RemoveActiveLocaleCultureInfo(string username, CultureInfo cultureInfo); IEnumerable GetActiveLocaleCultureInfos(string username); CultureInfo GetForeignLocaleCultureInfo(string username); void SetForeignLocaleCultureInfo(string username, CultureInfo cultureInfo); string LastSpecifiedNamespace { get; set;} IPAddress UserIPAddress { get; } } } ================================================ FILE: Composite/C1Console/Users/UserSettings.cs ================================================ using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using Composite.C1Console.Security; using Composite.Core.Caching; using Composite.Data; namespace Composite.C1Console.Users { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class UserSettings { private static IUserSettingsFacade _implementation = new UserSettingsImpl(); internal static IUserSettingsFacade Implementation { get { return _implementation; } set { _implementation = value; } } /// public static string Username { get { return _implementation.Username; } } /// /// A language to which C1 console UI is translated to. /// public static CultureInfo C1ConsoleUiLanguage { get { return _implementation.C1ConsoleUiLanguage; } set { _implementation.C1ConsoleUiLanguage = value; } } /// /// Culture used in console UI for date/number formatting. /// public static CultureInfo CultureInfo { get { return _implementation.CultureInfo; } set { _implementation.CultureInfo = value; } } /// public static CultureInfo GetUserCultureInfo(string username) { return _implementation.GetUserCultureInfo(username); } /// public static CultureInfo GetUserC1ConsoleUiLanguage(string username) { return _implementation.GetUserC1ConsoleUiLanguage(username); } /// public static void SetUserCultureInfo(string username, CultureInfo cultureInfo) { _implementation.SetUserCultureInfo(username, cultureInfo); } /// public static void SetUserC1ConsoleUiLanguage(string username, CultureInfo cultureInfo) { _implementation.SetUserC1ConsoleUiLanguage(username, cultureInfo); } // Overload /// /// This is an overload for GetCurrentActiveLocaleCultureInfo(string username) /// using the current username. /// public static CultureInfo ActiveLocaleCultureInfo { get { return GetCurrentActiveLocaleCultureInfo(UserSettings.Username); } set { SetCurrentActiveLocaleCultureInfo(UserSettings.Username, value); } } /// public static CultureInfo GetCurrentActiveLocaleCultureInfo(string username) { var key = "CurrentActiveCulture" + username; if (RequestLifetimeCache.HasKey(key)) return RequestLifetimeCache.TryGet(key); var cultureInfo = _implementation.GetCurrentActiveLocaleCultureInfo(username); var allowedCultures = GetActiveLocaleCultureInfos(username, true); if( !allowedCultures.Contains(cultureInfo)) cultureInfo = allowedCultures.FirstOrDefault(); if (cultureInfo != null && !RequestLifetimeCache.HasKey(key)) RequestLifetimeCache.Add(key, cultureInfo); return cultureInfo ?? CultureInfo.InvariantCulture; } /// public static void SetCurrentActiveLocaleCultureInfo(string username, CultureInfo cultureInfo) { _implementation.SetCurrentActiveLocaleCultureInfo(username, cultureInfo); } // Overload /// /// This is an overload for GetForeignLocaleCultureInfo(string username) /// using the current username. /// public static CultureInfo ForeignLocaleCultureInfo { get { return GetForeignLocaleCultureInfo(UserSettings.Username); } set { SetForeignLocaleCultureInfo(UserSettings.Username, value); } } /// public static CultureInfo GetForeignLocaleCultureInfo(string username) { return _implementation.GetForeignLocaleCultureInfo(username); } /// public static void SetForeignLocaleCultureInfo(string username, CultureInfo cultureInfo) { _implementation.SetForeignLocaleCultureInfo(username, cultureInfo); } /// public static void AddActiveLocaleCultureInfo(string username, CultureInfo cultureInfo) { _implementation.AddActiveLocaleCultureInfo(username, cultureInfo); } /// public static void RemoveActiveLocaleCultureInfo(string username, CultureInfo cultureInfo) { _implementation.RemoveActiveLocaleCultureInfo(username, cultureInfo); } // Overload /// /// This is an overload for GetActiveLocaleCultureInfos(string username, includeGroupAssignedCultures = true) /// using the current username. /// public static IEnumerable ActiveLocaleCultureInfos { get { return GetActiveLocaleCultureInfos(UserSettings.Username, true); } } /// public static IEnumerable GetActiveLocaleCultureInfos(string username, bool includeGroupAssignedCultures = true) { return includeGroupAssignedCultures ? _implementation.GetActiveLocaleCultureInfos(username).Union(UserGroupFacade.GetUserGroupActiveCultures(username)) : _implementation.GetActiveLocaleCultureInfos(username); } /// public static string LastSpecifiedNamespace { get { return _implementation.LastSpecifiedNamespace; } set { _implementation.LastSpecifiedNamespace = value; } } /// public static IPAddress UserIPAddress { get { return _implementation.UserIPAddress; } } } } ================================================ FILE: Composite/C1Console/Users/UserSettingsImpl.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using Composite.Core.Caching; using Composite.Data; using Composite.Data.Caching; using Composite.Data.Types; using Composite.Core.Configuration; using Composite.C1Console.Security; using Composite.C1Console.Security.Foundation.PluginFacades; namespace Composite.C1Console.Users { internal class UserSettingsImpl : IUserSettingsFacade { private static readonly object _lock = new object(); private static readonly Cache _userSettingsCache = new Cache("User settings", 100); static UserSettingsImpl() { DataEventSystemFacade.SubscribeToDataAfterAdd(OnUserSettingsChanged, true); DataEventSystemFacade.SubscribeToDataAfterUpdate(OnUserSettingsChanged, true); DataEventSystemFacade.SubscribeToDataDeleted(OnUserSettingsChanged, true); DataEventSystemFacade.SubscribeToStoreChanged(OnUserStoreChanged, true); } private static void OnUserStoreChanged(object sender, StoreEventArgs storeEventArgs) { if (!storeEventArgs.DataEventsFired) { lock (_lock) { _userSettingsCache.Clear(); } } } private static void OnUserSettingsChanged(object sender, DataEventArgs dataEventArgs) { IUserSettings settings = dataEventArgs.Data as IUserSettings; if(settings != null) { lock (_lock) { _userSettingsCache.Remove(settings.Username); } } } public string Username { get { return UserValidationFacade.GetUsername(); } } public CultureInfo CultureInfo { get { if (UserProfileDataAvailable) { return CultureInfo.CreateSpecificCulture(GetSettings(UserSettings.Username, true).CultureName); } return GlobalSettingsFacade.DefaultCultureInfo; } set { IUserSettings settings = GetSettings(UserSettings.Username, false); settings.CultureName = value.ToString(); DataFacade.Update(settings); } } public CultureInfo C1ConsoleUiLanguage { get { if (UserProfileDataAvailable) { return CultureInfo.CreateSpecificCulture(GetSettings(UserSettings.Username, true).C1ConsoleUiLanguage); } return GlobalSettingsFacade.DefaultCultureInfo; } set { IUserSettings settings = GetSettings(UserSettings.Username, false); settings.C1ConsoleUiLanguage = value.ToString(); DataFacade.Update(settings); } } public CultureInfo GetUserCultureInfo(string username) { IUserSettings settings = GetSettings(username, true); return CultureInfo.CreateSpecificCulture(settings.CultureName); } public void SetUserCultureInfo(string username, CultureInfo cultureInfo) { IUserSettings settings = GetSettings(username, false); settings.CultureName = cultureInfo.Name; DataFacade.Update(settings); } public CultureInfo GetUserC1ConsoleUiLanguage(string username) { IUserSettings settings = GetSettings(username, true); return CultureInfo.CreateSpecificCulture(settings.C1ConsoleUiLanguage); } public void SetUserC1ConsoleUiLanguage(string username, CultureInfo cultureInfo) { IUserSettings settings = GetSettings(username, false); settings.C1ConsoleUiLanguage = cultureInfo.Name; DataFacade.Update(settings); } public CultureInfo GetCurrentActiveLocaleCultureInfo(string username) { IUserSettings settings = GetSettings(username, true); if (settings.CurrentActiveLocaleCultureName != null) { return CultureInfo.CreateSpecificCulture(settings.CurrentActiveLocaleCultureName); } return DataLocalizationFacade.DefaultLocalizationCulture; } public void SetCurrentActiveLocaleCultureInfo(string username, CultureInfo cultureInfo) { IUserSettings settings = GetSettings(username, false); settings.CurrentActiveLocaleCultureName = cultureInfo.Name; DataFacade.Update(settings); } public CultureInfo GetForeignLocaleCultureInfo(string username) { IUserSettings settings = GetSettings(username, true); if (settings.ForeignLocaleCultureName != null) { return CultureInfo.CreateSpecificCulture(settings.ForeignLocaleCultureName); } return null; } public void SetForeignLocaleCultureInfo(string username, CultureInfo cultureInfo) { IUserSettings settings = GetSettings(username, false); if (cultureInfo != null) { settings.ForeignLocaleCultureName = cultureInfo.Name; } else { settings.ForeignLocaleCultureName = null; } DataFacade.Update(settings); } public void AddActiveLocaleCultureInfo(string username, CultureInfo cultureInfo) { bool exists = (from ual in DataFacade.GetData() where ual.Username == username && ual.CultureName == cultureInfo.Name select ual).Any(); if (exists) return; GetSettings(username, true); // Ensure that we have usersettings var userActiveLocale = DataFacade.BuildNew(); userActiveLocale.Id = Guid.NewGuid(); userActiveLocale.Username = username; userActiveLocale.CultureName = cultureInfo.Name; DataFacade.AddNew(userActiveLocale); } public void RemoveActiveLocaleCultureInfo(string username, CultureInfo cultureInfo) { Guid id = (from ual in DataFacade.GetData() where ual.Username == username && ual.CultureName == cultureInfo.Name select ual.Id).SingleOrDefault(); if (id != Guid.Empty) { IUserSettings userSettings = DataFacade.GetData().SingleOrDefault(f => f.Username == username); if (userSettings != null) { if (userSettings.CurrentActiveLocaleCultureName == cultureInfo.Name) { userSettings.CurrentActiveLocaleCultureName = null; DataFacade.Update(userSettings); } } DataFacade.Delete(f => f.Id == id); } } public IEnumerable GetActiveLocaleCultureInfos(string username) { IEnumerable cultureInfoNames = (from ual in DataFacade.GetData() where ual.Username == username select ual.CultureName); foreach (string cultureInfoName in cultureInfoNames) { yield return CultureInfo.CreateSpecificCulture(cultureInfoName); } } public string LastSpecifiedNamespace { get { return UserProfileDataAvailable ? GetDeveloperSettings().LastSpecifiedNamespace : ""; } set { IUserDeveloperSettings settings = GetDeveloperSettings(); settings.LastSpecifiedNamespace = value; DataFacade.Update(settings); } } public IPAddress UserIPAddress { get { return LoginSessionStorePluginFacade.UserIpAddress; } } private bool UserProfileDataAvailable { get { return GlobalInitializerFacade.SystemCoreInitialized && UserValidationFacade.IsLoggedIn(); } } private IUserSettings GetSettings(string username, bool readonlyUsage) { // "Readonly" values are cached if(readonlyUsage) { IUserSettings cachedValue = _userSettingsCache.Get(username); if (cachedValue != null) { return cachedValue; } } IUserSettings settings; lock (_lock) { settings = DataFacade.GetData(f => f.Username == username, false).FirstOrDefault() ?? CreateUserSettings(username); if(readonlyUsage) { _userSettingsCache.Add(username, settings); } } return settings; } private IUserDeveloperSettings GetDeveloperSettings() { if (RequestLifetimeCache.HasKey(typeof(IUserDeveloperSettings))) { return RequestLifetimeCache.TryGet(typeof(IUserDeveloperSettings)); } IUserDeveloperSettings settings = DataFacade.GetData(f => f.Username == UserSettings.Username).FirstOrDefault(); if (settings == null) { settings = CreateUserDeveloperSettings(); } RequestLifetimeCache.Add(typeof(IUserDeveloperSettings), settings); return settings; } private IUserSettings CreateUserSettings(string username) { var settings = DataFacade.BuildNew(); settings.Username = username; settings.CultureName = GlobalSettingsFacade.DefaultCultureName; settings.C1ConsoleUiLanguage = GlobalSettingsFacade.DefaultCultureName; return DataFacade.AddNew(settings); } private IUserDeveloperSettings CreateUserDeveloperSettings() { var settings = DataFacade.BuildNew(); settings.Username = Username; settings.LastSpecifiedNamespace = ""; return DataFacade.AddNew(settings); } } } ================================================ FILE: Composite/C1Console/Users/UserSettingsMock.cs ================================================ using System; using System.Collections.Generic; using Composite.Core.Configuration; using Composite.C1Console.Security; namespace Composite.C1Console.Users { internal class UserSettingsMock: IUserSettingsFacade { #region IUserSettingsFacade Members public string Username { get { return UserValidationFacade.GetUsername(); } } public System.Globalization.CultureInfo CultureInfo { get { return GlobalSettingsFacade.DefaultCultureInfo; } set { } } public System.Globalization.CultureInfo C1ConsoleUiLanguage { get { return GlobalSettingsFacade.DefaultCultureInfo; } set { } } public System.Globalization.CultureInfo GetUserCultureInfo(string username) { throw new NotImplementedException(); } public void SetUserCultureInfo(string username, System.Globalization.CultureInfo cultureInfo) { throw new NotImplementedException(); } public System.Globalization.CultureInfo GetCurrentActiveLocaleCultureInfo(string username) { throw new NotImplementedException(); } public void SetCurrentActiveLocaleCultureInfo(string username, System.Globalization.CultureInfo cultureInfo) { throw new NotImplementedException(); } public void AddActiveLocaleCultureInfo(string username, System.Globalization.CultureInfo cultureInfo) { throw new NotImplementedException(); } public void RemoveActiveLocaleCultureInfo(string username, System.Globalization.CultureInfo cultureInfo) { throw new NotImplementedException(); } public IEnumerable GetActiveLocaleCultureInfos(string username) { throw new NotImplementedException(); } public System.Globalization.CultureInfo GetForeignLocaleCultureInfo(string username) { throw new NotImplementedException(); } public void SetForeignLocaleCultureInfo(string username, System.Globalization.CultureInfo cultureInfo) { } public string LastSpecifiedNamespace { get { return string.Empty; } set { } } public System.Net.IPAddress UserIPAddress { get { throw new NotImplementedException(); } } #endregion public System.Globalization.CultureInfo GetUserC1ConsoleUiLanguage(string username) { throw new NotImplementedException(); } public void SetUserC1ConsoleUiLanguage(string username, System.Globalization.CultureInfo cultureInfo) { throw new NotImplementedException(); } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/CancelHandleExternalEventActivity.cs ================================================ using System; using System.ComponentModel; using System.Workflow.Activities; using System.Workflow.ComponentModel.Compiler; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DefaultEvent("Invoked")] [ActivityValidator(typeof(HandleExternalEventActivityValidator))] public sealed class CancelHandleExternalEventActivity : HandleExternalEventActivity { /// public CancelHandleExternalEventActivity() : base() { Initialize(); } /// public CancelHandleExternalEventActivity(string name) : base(name) { Initialize(); } /// [Browsable(false)] public override string EventName { get { return base.EventName; } set { base.EventName = value; } } /// [Browsable(false)] public override Type InterfaceType { get { return base.InterfaceType; } set { base.InterfaceType = value; } } private void Initialize() { this.InterfaceType = typeof(IFormsWorkflowEventService); this.EventName = "Cancel"; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/ChildWorkflowDoneHandleExternalEventActivity.cs ================================================ using System; using System.ComponentModel; using System.Workflow.Activities; using System.Workflow.ComponentModel.Compiler; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DefaultEvent("Invoked")] [ActivityValidator(typeof(HandleExternalEventActivityValidator))] public sealed class ChildWorkflowDoneHandleExternalEventActivity : HandleExternalEventActivity { /// public ChildWorkflowDoneHandleExternalEventActivity() : base() { Initialize(); } /// public ChildWorkflowDoneHandleExternalEventActivity(string name) : base(name) { Initialize(); } /// [Browsable(false)] public override string EventName { get { return base.EventName; } set { base.EventName = value; } } /// [Browsable(false)] public override Type InterfaceType { get { return base.InterfaceType; } set { base.InterfaceType = value; } } private void Initialize() { this.InterfaceType = typeof(IFormsWorkflowEventService); this.EventName = "ChildWorkflowDone"; this.Invoked += new EventHandler(OnEventInvoked); } private void OnEventInvoked(object sender, ExternalDataEventArgs e) { FormEventArgs args = (FormEventArgs)e; FormsWorkflow formsWorkflow = this.GetRoot(); formsWorkflow.ChildWorkflowResult = args.WorkflowResult; base.OnInvoked(e); } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/CloseCurrentViewActivity.cs ================================================ using System.Workflow.ComponentModel; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Events; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class CloseCurrentViewActivity : Activity { /// public CloseCurrentViewActivity() { } /// public CloseCurrentViewActivity(string name) : base(name) { } /// protected sealed override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { FormsWorkflow formsWorkflow = this.GetRoot(); FlowControllerServicesContainer container = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); if (container != null) { IManagementConsoleMessageService service = container.GetService(); if (service != null) { service.CloseCurrentView(); } } return ActivityExecutionStatus.Closed; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/ConditionalSetStateActivity.cs ================================================ using System; using System.ComponentModel; using System.Workflow.Activities; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Compiler; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ConditionalSetStateActivity : Activity { /// public static readonly DependencyProperty ConditionProperty = DependencyProperty.Register("Condition", typeof(ActivityCondition), typeof(ConditionalSetStateActivity), new PropertyMetadata(DependencyPropertyOptions.Metadata)); /// public static readonly DependencyProperty TrueTargetStateNameProperty = DependencyProperty.Register("TrueTargetStateName", typeof(string), typeof(ConditionalSetStateActivity), new PropertyMetadata("", DependencyPropertyOptions.Metadata, new Attribute[] { new ValidationOptionAttribute(ValidationOption.Optional) })); /// public static readonly DependencyProperty FalseTargetStateNameProperty = DependencyProperty.Register("FalseTargetStateName", typeof(string), typeof(ConditionalSetStateActivity), new PropertyMetadata("", DependencyPropertyOptions.Metadata, new Attribute[] { new ValidationOptionAttribute(ValidationOption.Optional) })); /// public ConditionalSetStateActivity() { } /// public ConditionalSetStateActivity(string name) : base(name) { } /// protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { StateMachineWorkflowInstance instance = WorkflowFacade.GetStateMachineWorkflowInstance(this.WorkflowInstanceId); bool result = Condition.Evaluate(this, executionContext); SetStateEventArgs args; if (result) { args = new SetStateEventArgs(this.TrueTargetStateName); } else { args = new SetStateEventArgs(this.FalseTargetStateName); } // instance.EnqueueItemOnIdle("SetStateQueue", args, null, null); return ActivityExecutionStatus.Closed; } /// [Browsable(true)] public ActivityCondition Condition { get { return (base.GetValue(ConditionProperty) as ActivityCondition); } set { base.SetValue(ConditionProperty, value); } } /// [DefaultValue((string)null)] public string TrueTargetStateName { get { return (base.GetValue(TrueTargetStateNameProperty) as string); } set { base.SetValue(TrueTargetStateNameProperty, value); } } /// [DefaultValue((string)null)] public string FalseTargetStateName { get { return (base.GetValue(FalseTargetStateNameProperty) as string); } set { base.SetValue(FalseTargetStateNameProperty, value); } } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/ConfirmDialogFormActivity.cs ================================================ using System.Workflow.Activities; using System.Workflow.ComponentModel; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Forms.DataServices; using Composite.C1Console.Forms.Flows; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ConfirmDialogFormActivity : Activity { /// public static readonly DependencyProperty ContainerLabelProperty = DependencyProperty.Register("ContainerLabel", typeof(string), typeof(ConfirmDialogFormActivity)); /// public static readonly DependencyProperty FormDefinitionFileNameProperty = DependencyProperty.Register("FormDefinitionFileName", typeof(string), typeof(ConfirmDialogFormActivity)); /// public ConfirmDialogFormActivity() { } /// public ConfirmDialogFormActivity(string name) : base(name) { } /// public string ContainerLabel { get { return (string)GetValue(ContainerLabelProperty); } set { SetValue(ContainerLabelProperty, value); } } /// public string FormDefinitionFileName { get { return (string)GetValue(FormDefinitionFileNameProperty); } set { SetValue(FormDefinitionFileNameProperty, value); } } /// protected sealed override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { FormsWorkflow formsWorkflow = this.GetRoot(); IFormMarkupProvider markupProvider = new FormDefinitionFileMarkupProvider(this.FormDefinitionFileName); ExternalDataExchangeService externalDataExchangeService = WorkflowFacade.WorkflowRuntime.GetService(); IFormsWorkflowActivityService service = externalDataExchangeService.GetService(typeof(IFormsWorkflowActivityService)) as IFormsWorkflowActivityService; service.DeliverFormData( WorkflowEnvironment.WorkflowInstanceId, this.ContainerLabel, StandardUiContainerTypes.ConfirmDialog, markupProvider, formsWorkflow.Bindings, formsWorkflow.BindingsValidationRules ); return ActivityExecutionStatus.Closed; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/CustomEvent01HandleExternalEventActivity.cs ================================================ using System; using System.ComponentModel; using System.Workflow.Activities; using System.Workflow.ComponentModel.Compiler; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DefaultEvent("Invoked")] [ActivityValidator(typeof(HandleExternalEventActivityValidator))] public sealed class CustomEvent01HandleExternalEventActivity : HandleExternalEventActivity { /// public CustomEvent01HandleExternalEventActivity() : base() { Initialize(); } /// public CustomEvent01HandleExternalEventActivity(string name) : base(name) { Initialize(); } /// [Browsable(false)] public override string EventName { get { return base.EventName; } set { base.EventName = value; } } /// [Browsable(false)] public override Type InterfaceType { get { return base.InterfaceType; } set { base.InterfaceType = value; } } private void Initialize() { this.InterfaceType = typeof(IFormsWorkflowEventService); this.EventName = "CustomEvent01"; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/CustomEvent02HandleExternalEventActivity.cs ================================================ using System; using System.ComponentModel; using System.Workflow.Activities; using System.Workflow.ComponentModel.Compiler; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DefaultEvent("Invoked")] [ActivityValidator(typeof(HandleExternalEventActivityValidator))] public sealed class CustomEvent02HandleExternalEventActivity : HandleExternalEventActivity { /// public CustomEvent02HandleExternalEventActivity() : base() { Initialize(); } /// public CustomEvent02HandleExternalEventActivity(string name) : base(name) { Initialize(); } /// [Browsable(false)] public override string EventName { get { return base.EventName; } set { base.EventName = value; } } /// [Browsable(false)] public override Type InterfaceType { get { return base.InterfaceType; } set { base.InterfaceType = value; } } private void Initialize() { this.InterfaceType = typeof(IFormsWorkflowEventService); this.EventName = "CustomEvent02"; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/CustomEvent03HandleExternalEventActivity.cs ================================================ using System; using System.ComponentModel; using System.Workflow.Activities; using System.Workflow.ComponentModel.Compiler; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DefaultEvent("Invoked")] [ActivityValidator(typeof(HandleExternalEventActivityValidator))] public sealed class CustomEvent03HandleExternalEventActivity : HandleExternalEventActivity { /// public CustomEvent03HandleExternalEventActivity() : base() { Initialize(); } /// public CustomEvent03HandleExternalEventActivity(string name) : base(name) { Initialize(); } /// [Browsable(false)] public override string EventName { get { return base.EventName; } set { base.EventName = value; } } /// [Browsable(false)] public override Type InterfaceType { get { return base.InterfaceType; } set { base.InterfaceType = value; } } private void Initialize() { this.InterfaceType = typeof(IFormsWorkflowEventService); this.EventName = "CustomEvent03"; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/CustomEvent04HandleExternalEventActivity.cs ================================================ using System; using System.ComponentModel; using System.Workflow.Activities; using System.Workflow.ComponentModel.Compiler; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DefaultEvent("Invoked")] [ActivityValidator(typeof(HandleExternalEventActivityValidator))] public sealed class CustomEvent04HandleExternalEventActivity : HandleExternalEventActivity { /// public CustomEvent04HandleExternalEventActivity() : base() { Initialize(); } /// public CustomEvent04HandleExternalEventActivity(string name) : base(name) { Initialize(); } /// [Browsable(false)] public override string EventName { get { return base.EventName; } set { base.EventName = value; } } /// [Browsable(false)] public override Type InterfaceType { get { return base.InterfaceType; } set { base.InterfaceType = value; } } private void Initialize() { this.InterfaceType = typeof(IFormsWorkflowEventService); this.EventName = "CustomEvent04"; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/CustomEvent05HandleExternalEventActivity.cs ================================================ using System; using System.ComponentModel; using System.Workflow.Activities; using System.Workflow.ComponentModel.Compiler; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DefaultEvent("Invoked")] [ActivityValidator(typeof(HandleExternalEventActivityValidator))] public sealed class CustomEvent05HandleExternalEventActivity : HandleExternalEventActivity { /// public CustomEvent05HandleExternalEventActivity() : base() { Initialize(); } /// public CustomEvent05HandleExternalEventActivity(string name) : base(name) { Initialize(); } /// [Browsable(false)] public override string EventName { get { return base.EventName; } set { base.EventName = value; } } /// [Browsable(false)] public override Type InterfaceType { get { return base.InterfaceType; } set { base.InterfaceType = value; } } private void Initialize() { this.InterfaceType = typeof(IFormsWorkflowEventService); this.EventName = "CustomEvent05"; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/DataDialogFormActivity.cs ================================================ using System.Workflow.Activities; using System.Workflow.ComponentModel; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Forms.DataServices; using Composite.C1Console.Forms.Flows; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DataDialogFormActivity : Activity { /// public static readonly DependencyProperty ContainerLabelProperty = DependencyProperty.Register("ContainerLabel", typeof(string), typeof(DataDialogFormActivity)); /// public static readonly DependencyProperty FormDefinitionFileNameProperty = DependencyProperty.Register("FormDefinitionFileName", typeof(string), typeof(DataDialogFormActivity)); /// public DataDialogFormActivity() { } /// public DataDialogFormActivity(string name) : base(name) { } /// public string ContainerLabel { get { return (string)GetValue(ContainerLabelProperty); } set { SetValue(ContainerLabelProperty, value); } } /// public string FormDefinitionFileName { get { return (string)GetValue(FormDefinitionFileNameProperty); } set { SetValue(FormDefinitionFileNameProperty, value); } } /// protected sealed override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { FormsWorkflow formsWorkflow = this.GetRoot(); IFormMarkupProvider markupProvider = new FormDefinitionFileMarkupProvider(this.FormDefinitionFileName); ExternalDataExchangeService externalDataExchangeService = WorkflowFacade.WorkflowRuntime.GetService(); IFormsWorkflowActivityService service = externalDataExchangeService.GetService(typeof(IFormsWorkflowActivityService)) as IFormsWorkflowActivityService; service.DeliverFormData( WorkflowEnvironment.WorkflowInstanceId, this.ContainerLabel, StandardUiContainerTypes.DataDialog, markupProvider, formsWorkflow.Bindings, formsWorkflow.BindingsValidationRules ); return ActivityExecutionStatus.Closed; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/DocumentFormActivity.cs ================================================ using System.Workflow.Activities; using System.Workflow.ComponentModel; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Forms.DataServices; using Composite.C1Console.Forms.Flows; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DocumentFormActivity : Activity { /// public static readonly DependencyProperty ContainerLabelProperty = DependencyProperty.Register("ContainerLabel", typeof(string), typeof(DocumentFormActivity)); /// public static readonly DependencyProperty FormDefinitionFileNameProperty = DependencyProperty.Register("FormDefinitionFileName", typeof(string), typeof(DocumentFormActivity)); /// public static readonly DependencyProperty CustomToolbarDefinitionFileNameProperty = DependencyProperty.Register("CustomToolbarDefinitionFileName", typeof(string), typeof(DocumentFormActivity)); /// public DocumentFormActivity() { } /// public DocumentFormActivity(string name) : base(name) { } /// public string ContainerLabel { get { return (string)GetValue(ContainerLabelProperty); } set { SetValue(ContainerLabelProperty, value); } } /// public string FormDefinitionFileName { get { return (string)GetValue(FormDefinitionFileNameProperty); } set { SetValue(FormDefinitionFileNameProperty, value); } } /// public string CustomToolbarDefinitionFileName { get { return (string)GetValue(CustomToolbarDefinitionFileNameProperty); } set { SetValue(CustomToolbarDefinitionFileNameProperty, value); } } /// protected sealed override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { FormsWorkflow formsWorkflow = this.GetRoot(); IFormMarkupProvider markupProvider = new FormDefinitionFileMarkupProvider(this.FormDefinitionFileName); ExternalDataExchangeService externalDataExchangeService = WorkflowFacade.WorkflowRuntime.GetService(); IFormsWorkflowActivityService service = externalDataExchangeService.GetService(typeof(IFormsWorkflowActivityService)) as IFormsWorkflowActivityService; service.DeliverFormData( WorkflowEnvironment.WorkflowInstanceId, this.ContainerLabel, StandardUiContainerTypes.Document, markupProvider, formsWorkflow.Bindings, formsWorkflow.BindingsValidationRules ); if (string.IsNullOrEmpty(this.CustomToolbarDefinitionFileName) == false) { IFormMarkupProvider customToolbarMarkupProvider = new FormDefinitionFileMarkupProvider(this.CustomToolbarDefinitionFileName); service.DeliverCustomToolbarDefinition(WorkflowEnvironment.WorkflowInstanceId, customToolbarMarkupProvider); } return ActivityExecutionStatus.Closed; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/EmptyDocumentFormActivity.cs ================================================ using System.Workflow.Activities; using System.Workflow.ComponentModel; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Forms.DataServices; using Composite.C1Console.Forms.Flows; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class EmptyDocumentFormActivity : Activity { /// public static readonly DependencyProperty ContainerLabelProperty = DependencyProperty.Register("ContainerLabel", typeof(string), typeof(EmptyDocumentFormActivity)); /// public static readonly DependencyProperty FormDefinitionFileNameProperty = DependencyProperty.Register("FormDefinitionFileName", typeof(string), typeof(EmptyDocumentFormActivity)); /// public EmptyDocumentFormActivity() { } /// public EmptyDocumentFormActivity(string name) : base(name) { } /// public string ContainerLabel { get { return (string)GetValue(ContainerLabelProperty); } set { SetValue(ContainerLabelProperty, value); } } /// public string FormDefinitionFileName { get { return (string)GetValue(FormDefinitionFileNameProperty); } set { SetValue(FormDefinitionFileNameProperty, value); } } /// protected sealed override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { FormsWorkflow formsWorkflow = this.GetRoot(); IFormMarkupProvider markupProvider = new FormDefinitionFileMarkupProvider(this.FormDefinitionFileName); ExternalDataExchangeService externalDataExchangeService = WorkflowFacade.WorkflowRuntime.GetService(); IFormsWorkflowActivityService service = externalDataExchangeService.GetService(typeof(IFormsWorkflowActivityService)) as IFormsWorkflowActivityService; service.DeliverFormData( WorkflowEnvironment.WorkflowInstanceId, this.ContainerLabel, StandardUiContainerTypes.EmptyDocument, markupProvider, formsWorkflow.Bindings, formsWorkflow.BindingsValidationRules ); return ActivityExecutionStatus.Closed; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/ExecuteChildWorkflowActivity.cs ================================================ using System; using System.Workflow.ComponentModel; using System.Workflow.Runtime; using Composite.C1Console.Actions; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ExecuteChildWorkflowActivity : Activity { /// public static readonly DependencyProperty ChildWorkflowTypeProperty = DependencyProperty.Register("ChildWorkflowType", typeof(Type), typeof(ExecuteChildWorkflowActivity)); /// public static readonly DependencyProperty ChildWorkflowPayloadProperty = DependencyProperty.Register("ChildWorkflowPayload", typeof(string), typeof(ExecuteChildWorkflowActivity)); /// public ExecuteChildWorkflowActivity() { } /// public ExecuteChildWorkflowActivity(string name) : base(name) { } /// public Type ChildWorkflowType { get { return (Type)GetValue(ChildWorkflowTypeProperty); } set { SetValue(ChildWorkflowTypeProperty, value); } } /// public string ChildWorkflowPayload { get { return (string)GetValue(ChildWorkflowPayloadProperty); } set { SetValue(ChildWorkflowPayloadProperty, value); } } /// protected sealed override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { FormsWorkflow formsWorkflow = this.GetRoot(); FlowControllerServicesContainer flowControllerServicesContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); IActionExecutionService actionExecutionService = flowControllerServicesContainer.GetService(); WorkflowActionToken workflowActionToken = new WorkflowActionToken(this.ChildWorkflowType) { Payload = this.ChildWorkflowPayload, ParentWorkflowInstanceId = formsWorkflow.InstanceId }; actionExecutionService.Execute(formsWorkflow.EntityToken, workflowActionToken, null); return ActivityExecutionStatus.Closed; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/FinishHandleExternalEventActivity.cs ================================================ using System; using System.ComponentModel; using System.Workflow.Activities; using System.Workflow.ComponentModel.Compiler; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DefaultEvent("Invoked")] [ActivityValidator(typeof(HandleExternalEventActivityValidator))] public sealed class FinishHandleExternalEventActivity : HandleExternalEventActivity { /// public FinishHandleExternalEventActivity() : base() { Initialize(); } /// public FinishHandleExternalEventActivity(string name) : base(name) { Initialize(); } /// [Browsable(false)] public override string EventName { get { return base.EventName; } set { base.EventName = value; } } /// [Browsable(false)] public override Type InterfaceType { get { return base.InterfaceType; } set { base.InterfaceType = value; } } private void Initialize() { this.InterfaceType = typeof(IFormsWorkflowEventService); this.EventName = "Finish"; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/FormsWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Workflow.Activities; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Compiler; using System.Workflow.Runtime; using System.Xml.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Users; using Composite.Core; using Composite.Core.Extensions; using Composite.Data; using Composite.C1Console.Elements; using Composite.C1Console.Forms.Flows; using Composite.Core.Logging; using Composite.Core.ResourceSystem; using Composite.C1Console.Security; using Composite.C1Console.Tasks; using Composite.Data.DynamicTypes; using Composite.Data.Validation; using Composite.Data.Validation.ClientValidationRules; using Composite.C1Console.Workflow.Activities.Foundation; using Composite.C1Console.Trees; using Microsoft.Practices.EnterpriseLibrary.Validation; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ToolboxItem(false)] [ToolboxBitmap(typeof(StateMachineWorkflowActivity), "Resources.StateMachineWorkflowActivity.png")] [ActivityValidator(typeof(StateActivityValidator))] public class FormsWorkflow : StateMachineWorkflowActivity { private string _stringEntityToken; private string _stringActionToken; private Guid _parentWorkflowInstanceId; private string _workflowResult; private string _childWorkflowResult; [NonSerialized] private EntityToken _entityToken; [NonSerialized] private ActionToken _actionToken; [NonSerialized] private WorkflowActionToken _workflowActionToken; [NonSerialized] private Dictionary _bindings = new Dictionary(); private Guid _instanceId; [NonSerialized] private EventHandler _onWorkflowIdledEventHandler; /// public FormsWorkflow() { this.BindingsValidationRules = new Dictionary>(); } /// protected void InitializeExtensions() { CanModifyActivities = true; foreach (var extension in FormsWorkflowExtensions.GetExtensions()) { extension.Initialize(this); } CanModifyActivities = false; } /// protected override void Initialize(IServiceProvider provider) { _onWorkflowIdledEventHandler = OnWorkflowIdled; if (!this.DesignMode) { WorkflowFacade.WorkflowRuntime.WorkflowIdled += _onWorkflowIdledEventHandler; } base.Initialize(provider); if (!BindingExist(EntityTokenKey)) { Bindings.Add(EntityTokenKey, EntityToken); } } internal static readonly string EntityTokenKey = typeof(FormsWorkflow).FullName + ":EntityToken"; /// protected override void Uninitialize(IServiceProvider provider) { if (!this.DesignMode) { WorkflowFacade.WorkflowRuntime.WorkflowIdled -= _onWorkflowIdledEventHandler; } if (this.ParentWorkflowInstanceId != Guid.Empty) { WorkflowFacade.FireChildWorkflowDoneEvent(this.ParentWorkflowInstanceId, this.WorkflowResult); } base.Uninitialize(provider); } /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string SerializedEntityToken { get { return _stringEntityToken; } set { _stringEntityToken = value; } } /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string SerializedActionToken { get { return _stringActionToken; } set { _stringActionToken = value; } } /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Guid ParentWorkflowInstanceId { get { return _parentWorkflowInstanceId; } set { _parentWorkflowInstanceId = value; } } /// /// Use this property to set the result of the workflow /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string WorkflowResult { get { return _workflowResult; } set { _workflowResult = value; } } /// /// This holds the result of a chlid workflow /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string ChildWorkflowResult { get { return _childWorkflowResult; } set { _childWorkflowResult = value; } } /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public EntityToken EntityToken { get { if (_entityToken == null && this.SerializedEntityToken != null) { _entityToken = EntityTokenSerializer.Deserialize(this.SerializedEntityToken); } return _entityToken; } } /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ActionToken ActionToken { get { if (_actionToken == null && this.SerializedActionToken != null) { _actionToken = ActionTokenSerializer.Deserialize(this.SerializedActionToken); } return _actionToken; } } /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Dictionary Bindings { get { if (_bindings == null) { // Workflows with WorkflowPersistingType.Never does not get their bindings persisted. if (!FormsWorkflowBindingCache.Bindings.TryGetValue(_instanceId, out _bindings)) { _bindings = new Dictionary(); } } return _bindings; } set { _bindings = value; FormsWorkflowBindingCache.Bindings[_instanceId] = _bindings; } } internal Dictionary GetBindingErrors() { Guid workflowId = WorkflowEnvironment.WorkflowInstanceId;; FlowControllerServicesContainer container = WorkflowFacade.GetFlowControllerServicesContainer(workflowId); var bindingValidationService = container.GetService(); if (bindingValidationService == null) { return new Dictionary(); } return bindingValidationService.BindingErrors; } /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Dictionary> BindingsValidationRules { get; set; } /// public T GetBinding(string name) { object obj; if (!Bindings.TryGetValue(name, out obj)) { throw new InvalidOperationException($"The binding named '{name}' was not found"); } return (T)obj; } /// public bool TryGetBinding(string name, out T binding) { object obj; if (this.Bindings.TryGetValue(name, out obj)) { binding = (T)obj; return true; } binding = default(T); return false; } /// public void UpdateBinding(string name, object value) { this.Bindings[name] = value; } /// public void UpdateBindings(Dictionary bindings) { foreach (var kvp in bindings) { this.Bindings[kvp.Key] = kvp.Value; } } /// public bool BindingExist(string name) { return this.Bindings.ContainsKey(name); } /// public T GetDataItemFromEntityToken() where T : IData { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; return (T)dataEntityToken.Data; } /// public string Payload { get { if (_workflowActionToken == null) { _workflowActionToken = this.ActionToken as WorkflowActionToken; } return _workflowActionToken?.Payload; } } /// public string ExtraPayload { get { if (_workflowActionToken == null) { _workflowActionToken = this.ActionToken as WorkflowActionToken; } return _workflowActionToken?.ExtraPayload; } } internal Guid InstanceId => _instanceId; private static FlowControllerServicesContainer GetFlowControllerServicesContainer() { return WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); } /// protected void ReportException(Exception ex) { Verify.ArgumentNotNull(ex, nameof(ex)); this.ShowMessage(DialogType.Error, "An unfortunate error occurred", $"Sorry, but an error has occurred, preventing the opperation from completing as expected. The error has been documented in details so a technican may follow up on this issue.\n\nThe error message is: {ex.Message}"); Log.LogCritical(this.GetType().Name, ex); var container = GetFlowControllerServicesContainer(); IManagementConsoleMessageService service = container.GetService(); service.ShowLogEntry(this.GetType(), ex); } /// protected void LogMessage(LogLevel logLevel, string message) { var container = GetFlowControllerServicesContainer(); IManagementConsoleMessageService service = container.GetService(); service.ShowLogEntry(this.GetType(), logLevel, message); switch (logLevel) { case LogLevel.Info: case LogLevel.Debug: case LogLevel.Fine: LoggingService.LogVerbose(this.GetType().Name, message); break; case LogLevel.Warning: LoggingService.LogWarning(this.GetType().Name, message); break; case LogLevel.Error: LoggingService.LogError(this.GetType().Name, message); break; case LogLevel.Fatal: LoggingService.LogCritical(this.GetType().Name, message); break; default: throw new NotImplementedException(); } } /// protected void ShowMessage(DialogType dialogType, string title, string message) { var container = GetFlowControllerServicesContainer(); IManagementConsoleMessageService service = container.GetService(); string localizedTitle = StringResourceSystemFacade.ParseString(title); string localizedMessage = StringResourceSystemFacade.ParseString(message); service.ShowMessage( dialogType, localizedTitle, localizedMessage ); } /// protected void SelectElement(EntityToken entityToken) { var container = GetFlowControllerServicesContainer(); IManagementConsoleMessageService service = container.GetService(); service.SelectElement(EntityTokenSerializer.Serialize(entityToken, true)); } /// protected void RebootConsole() { var container = GetFlowControllerServicesContainer(); IManagementConsoleMessageService service = container.GetService(); service.RebootConsole(); } /// protected void ShowFieldMessage(string fieldBindingPath, string message) { var flowControllerServicesContainer = GetFlowControllerServicesContainer(); var formFlowRenderingService = flowControllerServicesContainer.GetService(); formFlowRenderingService.ShowFieldMessage(fieldBindingPath, StringResourceSystemFacade.ParseString(message)); } /// protected void SetSaveStatus(bool succeeded) { SetSaveStatus(succeeded, (string)null); } /// protected void SetSaveStatus(bool succeeded, IData data) { SetSaveStatus(succeeded, data.GetDataEntityToken()); } /// protected void SetSaveStatus(bool succeeded, EntityToken entityToken) { string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken, true); SetSaveStatus(succeeded, serializedEntityToken); } /// protected void SetSaveStatus(bool succeeded, string serializedEntityToken) { var saveWorklowTaskManagerEvent = new SaveWorklowTaskManagerEvent ( new WorkflowFlowToken(this.InstanceId), this.WorkflowInstanceId, succeeded ); var container = GetFlowControllerServicesContainer(); var service = container.GetService(); service.OnStatus(saveWorklowTaskManagerEvent); var flowRenderingService = container.GetService(); flowRenderingService?.SetSaveStatus(succeeded); var managementConsoleMessageService = container.GetService(); managementConsoleMessageService.SaveStatus(succeeded); // TO BE REMOVED if (serializedEntityToken != null) { managementConsoleMessageService = container.GetService(); managementConsoleMessageService.BindEntityTokenToView(serializedEntityToken); } } /// protected void CloseCurrentView() { var flowControllerServicesContainer = GetFlowControllerServicesContainer(); var managementConsoleMessageService = flowControllerServicesContainer.GetService(); if (!managementConsoleMessageService.CloseCurrentViewRequested) { managementConsoleMessageService.CloseCurrentView(); } } /// protected void LockTheSystem() { var flowControllerServicesContainer = GetFlowControllerServicesContainer(); IManagementConsoleMessageService managementConsoleMessageService = flowControllerServicesContainer.GetService(); managementConsoleMessageService.LockSystem(); } /// public void RerenderView() { var flowControllerServicesContainer = GetFlowControllerServicesContainer(); IFormFlowRenderingService formFlowRenderingService = flowControllerServicesContainer.GetService(); formFlowRenderingService.RerenderView(); } /// protected void CollapseAndRefresh() { var container = GetFlowControllerServicesContainer(); var service = container.GetService(); service.CollapseAndRefresh(); } /// protected string GetCurrentConsoleId() { var flowControllerServicesContainer = GetFlowControllerServicesContainer(); IManagementConsoleMessageService managementConsoleMessageService = flowControllerServicesContainer.GetService(); return managementConsoleMessageService.CurrentConsoleId; } /// protected IEnumerable GetConsoleIdsOpenedByCurrentUser() { return GetConsoleIdsOpenedByUser(UserSettings.Username); } /// protected IEnumerable GetConsoleIdsOpenedByUser(string username) { if (UserSettings.Username == username) { string currentConsoleId = GetCurrentConsoleId(); return ConsoleFacade.GetConsoleIdsByUsername(username).Union(new[] { currentConsoleId }); } else { return ConsoleFacade.GetConsoleIdsByUsername(username); } } /// public void ExecuteAction(EntityToken entityToken, ActionToken actionToken) { var flowControllerServicesContainer = GetFlowControllerServicesContainer(); IActionExecutionService actionExecutionService = flowControllerServicesContainer.GetService(); var taskManagerEvent = new WorkflowCreationTaskManagerEvent(_instanceId); actionExecutionService.Execute(entityToken, actionToken, taskManagerEvent); } /// public void ExecuteWorklow(EntityToken entityToken, Type workflowType) { ExecuteAction(entityToken, new WorkflowActionToken(workflowType)); } /// protected void DeliverFormData(string containerLabel, IFlowUiContainerType containerType, string formDefinition, Dictionary bindings, Dictionary> bindingsValidationRules) { OnDeliverFormData(bindings, bindingsValidationRules); ExternalDataExchangeService externalDataExchangeService = WorkflowFacade.WorkflowRuntime.GetService(); IFormsWorkflowActivityService formsWorkflowActivityService = externalDataExchangeService.GetService(typeof(IFormsWorkflowActivityService)) as IFormsWorkflowActivityService; formsWorkflowActivityService.DeliverFormData(WorkflowEnvironment.WorkflowInstanceId, containerLabel, containerType, formDefinition, bindings, bindingsValidationRules); } /// protected void DeliverFormData(string containerLabel, IFlowUiContainerType containerType, IFormMarkupProvider formMarkupProvider, Dictionary bindings, Dictionary> bindingsValidationRules) { OnDeliverFormData(bindings, bindingsValidationRules); var externalDataExchangeService = WorkflowFacade.WorkflowRuntime.GetService(); var formsWorkflowActivityService = externalDataExchangeService.GetService(typeof(IFormsWorkflowActivityService)) as IFormsWorkflowActivityService; formsWorkflowActivityService.DeliverFormData(WorkflowEnvironment.WorkflowInstanceId, containerLabel, containerType, formMarkupProvider, bindings, bindingsValidationRules); } private void OnDeliverFormData(Dictionary bindings, Dictionary> bindingsValidationRules) { var parameters = new OnDeliverFormDataParameters { Bindings = bindings, BindingsValidationRules = bindingsValidationRules }; foreach (var extension in FormsWorkflowExtensions.GetExtensions()) { extension.OnDeliverFormData(this, parameters); } } /// /// Adds the cms:layout elements Form Definition to the UI toolbar. /// /// String containing a valid Form Definition markup document public void SetCustomToolbarDefinition(string customToolbarDefinition) { SetCustomToolbarDefinition(new StringBasedFormMarkupProvider(customToolbarDefinition)); } /// /// Adds the cms:layout elements Form Definition to the UI toolbar. /// /// Markup provider that can deliver a valid Form Definition markup document protected void SetCustomToolbarDefinition(IFormMarkupProvider customToolbarMarkupProvider) { var externalDataExchangeService = WorkflowFacade.WorkflowRuntime.GetService(); var fwas = externalDataExchangeService.GetService(); fwas.DeliverCustomToolbarDefinition(WorkflowEnvironment.WorkflowInstanceId, customToolbarMarkupProvider); } /// /// Adds a custom toolbar item. /// /// The item id. /// The markup. /// The priority - is used for sorting multiple toolbar items. public void AddCustomToolbarItem(string itemId, XDocument markup, ActionGroupPriority priority) { var externalDataExchangeService = WorkflowFacade.WorkflowRuntime.GetService(); var fwas = externalDataExchangeService.GetService(); Verify.That(WorkflowInstanceId == WorkflowEnvironment.WorkflowInstanceId, "Unexpected workflow id!"); fwas.AddCustomToolbarItem(WorkflowInstanceId, itemId, markup, priority); } /// protected AddNewTreeRefresher CreateAddNewTreeRefresher(EntityToken parentEntityToken) { return new AddNewTreeRefresher(parentEntityToken, WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId)); } /// protected UpdateTreeRefresher CreateUpdateTreeRefresher(EntityToken beforeUpdateEntityToken) { return new UpdateTreeRefresher(beforeUpdateEntityToken, WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId)); } /// protected DeleteTreeRefresher CreateDeleteTreeRefresher(EntityToken beforeDeleteEntityToken) { return new DeleteTreeRefresher(beforeDeleteEntityToken, WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId)); } /// protected ParentTreeRefresher CreateParentTreeRefresher() { return new ParentTreeRefresher(WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId)); } /// protected SpecificTreeRefresher CreateSpecificTreeRefresher() { return new SpecificTreeRefresher(WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId)); } /// protected void RefreshEntityToken(EntityToken entityToken) { SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(entityToken); } /// protected void RefreshCurrentEntityToken() { SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(this.EntityToken); } /// protected void RefreshParentEntityToken() { ParentTreeRefresher parentTreeRefresher = this.CreateParentTreeRefresher(); parentTreeRefresher.PostRefreshMesseges(this.EntityToken); } /// protected void RefreshRootEntityToken() { SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(ElementFacade.GetRootsWithNoSecurity().First().ElementHandle.EntityToken); } /// protected void AcquireLock(EntityToken entityToken) { ActionLockingFacade.AcquireLock(entityToken, this.WorkflowInstanceId); } /// public DynamicValuesHelperReplaceContext CreateDynamicValuesHelperReplaceContext() { return CreateDynamicValuesHelperReplaceContext(this.ExtraPayload); } internal DynamicValuesHelperReplaceContext CreateDynamicValuesHelperReplaceContext(string serializedPiggybag) { Dictionary piggybag = PiggybagSerializer.Deserialize(serializedPiggybag); return CreateDynamicValuesHelperReplaceContext(piggybag); } internal DynamicValuesHelperReplaceContext CreateDynamicValuesHelperReplaceContext(Dictionary piggybag) { return new DynamicValuesHelperReplaceContext(this.EntityToken, piggybag); } /// protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { _instanceId = WorkflowEnvironment.WorkflowInstanceId; ActivityExecutionStatus activityExecutionStatus = base.Execute(executionContext); return activityExecutionStatus; } private void OnWorkflowIdled(object sender, WorkflowEventArgs e) { if (e.WorkflowInstance.InstanceId == _instanceId) { FormsWorkflowBindingCache.Bindings[_instanceId] = this.Bindings; } } /// /// Shows validation messages for fields that weren't binded correctly. /// /// True if all the bindings were processed correctly protected bool ValidateBindings() { Dictionary bindingErrors = GetBindingErrors(); if (bindingErrors.Count == 0) { return true; } foreach (var pair in bindingErrors) { ShowFieldMessage(pair.Key, pair.Value.Message); } return false; } /// /// Binds form values to a data item and sends messages to client to display validation messages. /// /// Form binding helper /// An IData instance /// True, if there were no binding/validation errors protected bool BindAndValidate(DataTypeDescriptorFormsHelper helper, IData data) { Dictionary errorMessages = helper.BindingsToObject(this.Bindings, data); ValidationResults validationResults = ValidationFacade.Validate(data.DataSourceId.InterfaceType, data); bool isValid = true; if (!validationResults.IsValid) { foreach (ValidationResult result in validationResults) { if (!result.Key.IsNullOrEmpty()) { this.ShowFieldMessage(result.Key, result.Message); } else { this.ShowMessage(DialogType.Error, "Validation error", result.Message); } isValid = false; } } // Checking that required strings are not empty var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(data.DataSourceId.InterfaceType); foreach (var fieldName in dataTypeDescriptor.Fields .Where(f => !f.IsNullable && f.InstanceType == typeof (string) && !(f.Inherited && f.Name == "FieldName")) // Skipping validation for inherited IPageMetaData.FieldName .Select(f => f.Name)) { string bindingName = (helper.BindingNamesPrefix ?? "").Replace('.', '_') + fieldName; if(validationResults.Any(r => r.Key == bindingName)) continue; object fieldValue = this.Bindings[bindingName]; if (fieldValue is string && (fieldValue as string) == string.Empty && !helper.BindingIsOptional(bindingName)) { this.ShowFieldMessage(bindingName, LocalizationFiles.Composite_Management.Validation_RequiredField); isValid = false; } } if (errorMessages != null) { isValid = false; foreach (var kvp in errorMessages) { this.ShowFieldMessage(kvp.Key, kvp.Value); } } return isValid; } } internal static class ExternalDataExchangeServiceExtensions { public static T GetService(this ExternalDataExchangeService serviceContainer) where T : class { return serviceContainer.GetService(typeof (T)) as T; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/Foundation/FormsWorkflowBindingCache.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; namespace Composite.C1Console.Workflow.Activities.Foundation { internal static class FormsWorkflowBindingCache { public static ConcurrentDictionary> Bindings = new ConcurrentDictionary>(); } } ================================================ FILE: Composite/C1Console/Workflow/Activities/NextHandleExternalEventActivity.cs ================================================ using System; using System.ComponentModel; using System.Workflow.Activities; using System.Workflow.ComponentModel.Compiler; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DefaultEvent("Invoked")] [ActivityValidator(typeof(HandleExternalEventActivityValidator))] public sealed class NextHandleExternalEventActivity : HandleExternalEventActivity { /// public NextHandleExternalEventActivity() : base() { Initialize(); } /// public NextHandleExternalEventActivity(string name) : base(name) { Initialize(); } /// [Browsable(false)] public override string EventName { get { return base.EventName; } set { base.EventName = value; } } /// [Browsable(false)] public override Type InterfaceType { get { return base.InterfaceType; } set { base.InterfaceType = value; } } private void Initialize() { this.InterfaceType = typeof(IFormsWorkflowEventService); this.EventName = "Next"; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/PreviewHandleExternalEventActivity.cs ================================================ using System; using System.ComponentModel; using System.Workflow.Activities; using System.Workflow.ComponentModel.Compiler; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DefaultEvent("Invoked")] [ActivityValidator(typeof(HandleExternalEventActivityValidator))] public sealed class PreviewHandleExternalEventActivity : HandleExternalEventActivity { /// public PreviewHandleExternalEventActivity() : base() { Initialize(); } /// public PreviewHandleExternalEventActivity(string name) : base(name) { Initialize(); } /// [Browsable(false)] public override string EventName { get { return base.EventName; } set { base.EventName = value; } } /// [Browsable(false)] public override Type InterfaceType { get { return base.InterfaceType; } set { base.InterfaceType = value; } } private void Initialize() { this.InterfaceType = typeof(IFormsWorkflowEventService); this.EventName = "Preview"; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/PreviousHandleExternalEventActivity.cs ================================================ using System; using System.ComponentModel; using System.Workflow.Activities; using System.Workflow.ComponentModel.Compiler; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DefaultEvent("Invoked")] [ActivityValidator(typeof(HandleExternalEventActivityValidator))] public sealed class PreviousHandleExternalEventActivity : HandleExternalEventActivity { /// public PreviousHandleExternalEventActivity() : base() { Initialize(); } /// public PreviousHandleExternalEventActivity(string name) : base(name) { Initialize(); } /// [Browsable(false)] public override string EventName { get { return base.EventName; } set { base.EventName = value; } } /// [Browsable(false)] public override Type InterfaceType { get { return base.InterfaceType; } set { base.InterfaceType = value; } } private void Initialize() { this.InterfaceType = typeof(IFormsWorkflowEventService); this.EventName = "Previous"; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/RerenderViewActivity.cs ================================================ using System.Workflow.ComponentModel; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Forms.Flows; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class RerenderViewActivity : Activity { /// public RerenderViewActivity() { } /// public RerenderViewActivity(string name) : base(name) { } /// protected sealed override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { FlowControllerServicesContainer flowControllerServicesContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); IFormFlowRenderingService formFlowRenderingService = flowControllerServicesContainer.GetService(); formFlowRenderingService.RerenderView(); return ActivityExecutionStatus.Closed; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/SaveAndPublishHandleExternalEventActivity.cs ================================================ using System; using System.ComponentModel; using System.Workflow.Activities; using System.Workflow.ComponentModel.Compiler; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DefaultEvent("Invoked")] [ActivityValidator(typeof(HandleExternalEventActivityValidator))] public sealed class SaveAndPublishHandleExternalEventActivity : HandleExternalEventActivity { /// public SaveAndPublishHandleExternalEventActivity() : base() { Initialize(); } /// public SaveAndPublishHandleExternalEventActivity(string name) : base(name) { Initialize(); } /// [Browsable(false)] public override string EventName { get { return base.EventName; } set { base.EventName = value; } } /// [Browsable(false)] public override Type InterfaceType { get { return base.InterfaceType; } set { base.InterfaceType = value; } } private void Initialize() { this.InterfaceType = typeof(IFormsWorkflowEventService); this.EventName = "SaveAndPublish"; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/SaveHandleExternalEventActivity.cs ================================================ using System; using System.ComponentModel; using System.Workflow.Activities; using System.Workflow.ComponentModel.Compiler; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DefaultEvent("Invoked")] [ActivityValidator(typeof(HandleExternalEventActivityValidator))] public sealed class SaveHandleExternalEventActivity : HandleExternalEventActivity { /// public SaveHandleExternalEventActivity() : base() { Initialize(); } /// public SaveHandleExternalEventActivity(string name) : base(name) { Initialize(); } /// [Browsable(false)] public override string EventName { get { return base.EventName; } set { base.EventName = value; } } /// [Browsable(false)] public override Type InterfaceType { get { return base.InterfaceType; } set { base.InterfaceType = value; } } private void Initialize() { this.InterfaceType = typeof(IFormsWorkflowEventService); this.EventName = "Save"; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/ShowConsoleMessageBoxActivity.cs ================================================ using System.Workflow.ComponentModel; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Core.ResourceSystem; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ShowConsoleMessageBoxActivity : Activity { /// public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(ShowConsoleMessageBoxActivity)); /// public static readonly DependencyProperty MessageProperty = DependencyProperty.Register("Message", typeof(string), typeof(ShowConsoleMessageBoxActivity)); /// public static readonly DependencyProperty DialogTypeProperty = DependencyProperty.Register("DialogType", typeof(DialogType), typeof(ShowConsoleMessageBoxActivity)); /// public ShowConsoleMessageBoxActivity() { } /// public ShowConsoleMessageBoxActivity(string name) : base(name) { } /// public DialogType DialogType { get { return (DialogType)GetValue(DialogTypeProperty); } set { SetValue(DialogTypeProperty, value); } } /// public string Title { get { return (string)GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } /// public string Message { get { return (string)GetValue(MessageProperty); } set { SetValue(MessageProperty, value); } } /// protected sealed override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { FlowControllerServicesContainer container = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); IManagementConsoleMessageService service = container.GetService(); service.ShowMessage(this.DialogType, StringResourceSystemFacade.ParseString(this.Title), StringResourceSystemFacade.ParseString(this.Message)); return ActivityExecutionStatus.Closed; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/ShowFieldMessageActivity.cs ================================================ using System.Workflow.ComponentModel; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Forms.Flows; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ShowFieldMessageActivity : Activity { /// public static readonly DependencyProperty FieldBindingPathProperty = DependencyProperty.Register("FieldBindingPath", typeof(string), typeof(ShowFieldMessageActivity)); /// public static readonly DependencyProperty MessageProperty = DependencyProperty.Register("Message", typeof(string), typeof(ShowFieldMessageActivity)); /// public ShowFieldMessageActivity() { } /// public ShowFieldMessageActivity(string name) : base(name) { } /// public string FieldBindingPath { get { return (string)GetValue(FieldBindingPathProperty); } set { SetValue(FieldBindingPathProperty, value); } } /// public string Message { get { return (string)GetValue(MessageProperty); } set { SetValue(MessageProperty, value); } } /// protected sealed override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { FlowControllerServicesContainer container = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); IFormFlowRenderingService service = container.GetService(); service.ShowFieldMessage( this.FieldBindingPath, this.Message); return ActivityExecutionStatus.Closed; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/WarningDialogFormActivity.cs ================================================ using System.Workflow.Activities; using System.Workflow.ComponentModel; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Forms.DataServices; using Composite.C1Console.Forms.Flows; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class WarningDialogFormActivity : Activity { /// public static readonly DependencyProperty ContainerLabelProperty = DependencyProperty.Register("ContainerLabel", typeof(string), typeof(WarningDialogFormActivity)); /// public static readonly DependencyProperty FormDefinitionFileNameProperty = DependencyProperty.Register("FormDefinitionFileName", typeof(string), typeof(WarningDialogFormActivity)); /// public WarningDialogFormActivity() { } /// public WarningDialogFormActivity(string name) : base(name) { } /// public string ContainerLabel { get { return (string)GetValue(ContainerLabelProperty); } set { SetValue(ContainerLabelProperty, value); } } /// public string FormDefinitionFileName { get { return (string)GetValue(FormDefinitionFileNameProperty); } set { SetValue(FormDefinitionFileNameProperty, value); } } /// protected sealed override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { FormsWorkflow formsWorkflow = this.GetRoot(); IFormMarkupProvider markupProvider = new FormDefinitionFileMarkupProvider(this.FormDefinitionFileName); ExternalDataExchangeService externalDataExchangeService = WorkflowFacade.WorkflowRuntime.GetService(); IFormsWorkflowActivityService service = externalDataExchangeService.GetService(typeof(IFormsWorkflowActivityService)) as IFormsWorkflowActivityService; service.DeliverFormData( WorkflowEnvironment.WorkflowInstanceId, this.ContainerLabel, StandardUiContainerTypes.WarningDialog, markupProvider, formsWorkflow.Bindings, formsWorkflow.BindingsValidationRules ); return ActivityExecutionStatus.Closed; } } } ================================================ FILE: Composite/C1Console/Workflow/Activities/WizardFormActivity.cs ================================================ using System.Workflow.Activities; using System.Workflow.ComponentModel; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Forms.DataServices; using Composite.C1Console.Forms.Flows; namespace Composite.C1Console.Workflow.Activities { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class WizardFormActivity : Activity { /// public static readonly DependencyProperty ContainerLabelProperty = DependencyProperty.Register("ContainerLabel", typeof(string), typeof(WizardFormActivity)); /// public static readonly DependencyProperty FormDefinitionFileNameProperty = DependencyProperty.Register("FormDefinitionFileName", typeof(string), typeof(WizardFormActivity)); /// public WizardFormActivity() { } /// public WizardFormActivity(string name) : base(name) { } /// public string ContainerLabel { get { return (string)GetValue(ContainerLabelProperty); } set { SetValue(ContainerLabelProperty, value); } } /// public string FormDefinitionFileName { get { return (string)GetValue(FormDefinitionFileNameProperty); } set { SetValue(FormDefinitionFileNameProperty, value); } } /// protected sealed override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { FormsWorkflow formsWorkflow = this.GetRoot(); IFormMarkupProvider markupProvider = new FormDefinitionFileMarkupProvider(this.FormDefinitionFileName); ExternalDataExchangeService externalDataExchangeService = WorkflowFacade.WorkflowRuntime.GetService(); IFormsWorkflowActivityService service = externalDataExchangeService.GetService(typeof(IFormsWorkflowActivityService)) as IFormsWorkflowActivityService; service.DeliverFormData( WorkflowEnvironment.WorkflowInstanceId, this.ContainerLabel, StandardUiContainerTypes.Wizard, markupProvider, formsWorkflow.Bindings, formsWorkflow.BindingsValidationRules ); return ActivityExecutionStatus.Closed; } } } ================================================ FILE: Composite/C1Console/Workflow/ActivityExtensionMethods.cs ================================================ using System.Workflow.ComponentModel; namespace Composite.C1Console.Workflow { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ActivityExtensionMethods { /// public static Activity GetRoot(this Activity activity) { if (activity.Parent == null) { return activity; } else { return GetRoot(activity.Parent); } } /// public static T GetRoot(this Activity activity) where T : Activity { return (T)GetRoot(activity); } } } ================================================ FILE: Composite/C1Console/Workflow/AllowPersistingWorkflowAttribute.cs ================================================ using System; namespace Composite.C1Console.Workflow { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum WorkflowPersistingType { /// /// Never persisted /// Never, /// /// Workflow with this type of persistence will be unloaded after entering "Idle" state /// Idle, /// /// Workflow will be unloaded and serialized while shutting down /// Shutdown } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public sealed class AllowPersistingWorkflowAttribute : Attribute { /// public AllowPersistingWorkflowAttribute(WorkflowPersistingType workflowPersistingType) { this.WorkflowPersistingType = workflowPersistingType; } /// public WorkflowPersistingType WorkflowPersistingType { get; private set; } } } ================================================ FILE: Composite/C1Console/Workflow/EntityTokenLockAttribute.cs ================================================ using System; namespace Composite.C1Console.Workflow { /// /// If this attribute is specified on a workflow, then the EntityToken will be locked /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public sealed class EntityTokenLockAttribute : Attribute { /// public EntityTokenLockAttribute() { } } } ================================================ FILE: Composite/C1Console/Workflow/FilePersistenceService.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Serialization; using System.Workflow.Runtime.Hosting; using Composite.Core; using Composite.Core.IO; using Composite.Core.Logging; using Composite.Core.Types; namespace Composite.C1Console.Workflow { internal class FileWorkflowPersistenceService : WorkflowPersistenceService { private static readonly string LogTitle = "Workflow File Persisting Service"; private readonly string _baseDirectory; private Guid[] _abortedWorkflows; private readonly object _syncRoot = new object(); private C1FileSystemWatcher _fileWatcher; private static readonly ConcurrentDictionary _createdWorkflows = new ConcurrentDictionary(); public FileWorkflowPersistenceService(string baseDirectory) { _baseDirectory = baseDirectory; this.PersistAll = false; } public bool PersistAll { get; set; } public IEnumerable GetAbortedWorkflows() { return _abortedWorkflows ?? new Guid[0]; } public IEnumerable GetPersistedWorkflows() { foreach (string filePath in C1Directory.GetFiles(_baseDirectory, "*.bin")) { Guid workflowId; if (TryParseWorkflowId(filePath, out workflowId)) { yield return workflowId; } } } private bool TryParseWorkflowId(string filePath, out Guid workflowId) { string guidString = Path.GetFileNameWithoutExtension(filePath); return Guid.TryParse(guidString ?? "", out workflowId); } public void ListenToDynamicallyAddedWorkflows(Action onWorkflowFileAdded) { Verify.IsNull(_fileWatcher, "The method has already been invoked"); Action handleWorkflowAdded = name => { try { Guid workflowId; if (TryParseWorkflowId(name, out workflowId) && !_createdWorkflows.ContainsKey(workflowId)) { onWorkflowFileAdded(workflowId); } } catch (Exception ex) { Log.LogError(LogTitle, ex); } }; var fileWatcher = new C1FileSystemWatcher(_baseDirectory, "*.bin") { IncludeSubdirectories = false }; fileWatcher.Created += (sender, args) => handleWorkflowAdded(args.Name); fileWatcher.Renamed += (sender, args) => handleWorkflowAdded(args.Name); fileWatcher.EnableRaisingEvents = true; _fileWatcher = fileWatcher; } public bool RemovePersistedWorkflow(Guid instanceId) { string filename = GetFileName(instanceId); if (C1File.Exists(filename)) { try { C1File.Delete(filename); Log.LogVerbose(LogTitle, $"Workflow persisted state deleted. Id = {instanceId}"); } catch { return false; } } byte _; _createdWorkflows.TryRemove(instanceId, out _); return true; } protected override Activity LoadCompletedContextActivity(Guid scopeId, Activity outerActivity) { object obj = DeserializeActivity(outerActivity, scopeId); return (Activity)obj; } protected override Activity LoadWorkflowInstanceState(Guid instanceId) { string filename = GetFileName(instanceId); bool deleteFile = false; if (C1File.Exists(filename)) { try { object obj = DeserializeActivity(null, instanceId); return (Activity)obj; } catch (Exception ex) { LoggingService.LogCritical(LogTitle, ex); deleteFile = true; } } if (deleteFile) { Log.LogWarning(LogTitle, $"Failed to load workflow with id '{filename}'. Deleting file."); C1File.Delete(filename); MarkWorkflowAsAborted(instanceId); } return null; } protected override void SaveCompletedContextActivity(Activity activity) { SaveWorkflowInstanceState(activity); } protected override void SaveWorkflowInstanceState(Activity rootActivity, bool unlock) { SaveWorkflowInstanceState(rootActivity); } protected override bool UnloadOnIdle(Activity activity) { var persistingType = GetPersistingType(activity); if (persistingType == WorkflowPersistingType.Shutdown) { SaveWorkflowInstanceState(activity); } return persistingType == WorkflowPersistingType.Idle; } private void SaveWorkflowInstanceState(Activity activity) { Guid workflowId = (Guid)activity.GetValue(Activity.ActivityContextGuidProperty); SerializeActivity(activity, workflowId); } protected override void UnlockWorkflowInstanceState(Activity rootActivity) { //empty } private bool ActivityIsSerializable(Activity activity) { return PersistAll || GetPersistingType(activity) != WorkflowPersistingType.Never; } private WorkflowPersistingType GetPersistingType(Activity activity) { List attributes = activity.GetType().GetCustomAttributesRecursively().ToList(); if (attributes.Count == 0) return WorkflowPersistingType.Never; return attributes[0].WorkflowPersistingType; } private void SerializeActivity(Activity rootActivity, Guid id) { if (!ActivityIsSerializable(rootActivity)) { Log.LogVerbose(LogTitle, $"The workflow does not support persiting. Id = {id}, Type = {rootActivity.GetType()}"); return; } string filename = GetFileName(id); IFormatter formatter = new BinaryFormatter(); formatter.SurrogateSelector = ActivitySurrogateSelector.Default; _createdWorkflows[id] = 0; using (var stream = new C1FileStream(filename, FileMode.OpenOrCreate)) { try { rootActivity.Save(stream, formatter); stream.Close(); } catch (SerializationException ex) { Log.LogError(LogTitle, ex); } } // Log.LogVerbose(LogTitle, $"Workflow persisted. Id = {id}, Type = {rootActivity.GetType()}"); } private object DeserializeActivity(Activity rootActivity, Guid id) { string filename = GetFileName(id); object result; var formatter = new BinaryFormatter { SurrogateSelector = ActivitySurrogateSelector.Default }; using (var stream = new C1FileStream(filename, FileMode.Open)) { result = Activity.Load(stream, rootActivity, formatter); } // Log.LogVerbose(LogTitle, $"Workflow loaded. Id = {id}, Type = {result.GetType()}"); return result; } private void MarkWorkflowAsAborted(Guid id) { lock (_syncRoot) { _abortedWorkflows = (_abortedWorkflows ?? Array.Empty()) .Concat(new [] {id}).ToArray(); } } private string GetFileName(Guid id) { return Path.Combine(this._baseDirectory, $"{id}.bin"); } } } ================================================ FILE: Composite/C1Console/Workflow/FormsEventArgs.cs ================================================ using System; using System.Workflow.Activities; using System.Collections.Generic; namespace Composite.C1Console.Workflow { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class FormEventArgs : ExternalDataEventArgs { private string _workflowResult; [NonSerialized] private Dictionary _bindings; /// public FormEventArgs(Guid instanceId, string workflowResult) : this(instanceId, workflowResult, null) { } /// public FormEventArgs(Guid instanceId, Dictionary bindings) : this(instanceId, null, bindings) { } /// public FormEventArgs(Guid instanceId, string workflowResult, Dictionary bindings) : base(instanceId) { _workflowResult = workflowResult; _bindings = bindings; } /// public string WorkflowResult { get { return _workflowResult; } set { _workflowResult = value; } } /// public Dictionary Bindings { get { return _bindings; } set { _bindings = value; } } } } ================================================ FILE: Composite/C1Console/Workflow/FormsWorkflowExtensions.cs ================================================ using System.Collections.Generic; namespace Composite.C1Console.Workflow { /// public static class FormsWorkflowExtensions { private static readonly List _extensions = new List(); /// public static void Register(IFormsWorkflowExtension extension) => _extensions.Add(extension); internal static ICollection GetExtensions() => _extensions; } } ================================================ FILE: Composite/C1Console/Workflow/Foundation/FormData.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq; using Composite.C1Console.Actions; using Composite.Data.DynamicTypes; using Composite.C1Console.Forms.Flows; using Composite.Functions; using Composite.Core.Serialization; using Composite.Core.Types; using Composite.Data.Validation.ClientValidationRules; using Composite.Core.Xml; using Composite.Core.Threading; using System.Globalization; using Composite.C1Console.Elements; namespace Composite.C1Console.Workflow.Foundation { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class FormData { /// public string ContainerLabel { get; set; } /// public string FormDefinition { get; set; } /// public List> CustomToolbarItems { get; set; } /// public IFormMarkupProvider FormMarkupProvider { get; set; } /// public Dictionary Bindings { get; set; } /// public Dictionary> BindingsValidationRules { get; set; } /// public IFlowUiContainerType ContainerType { get; set; } /// public Type EventHandleFilterType { get; set; } /// public List ExcludedEvents { get; set; } /// public XElement Serialize() { using (new ThreadCultureScope(CultureInfo.InvariantCulture)) { IXmlSerializer xmlSerializer = new XmlSerializer(new IValueXmlSerializer[] { new SystemPrimitivValueXmlSerializer(), new SystemCollectionValueXmlSerializer(), new SystemTypesValueXmlSerializer(), new CompositeCollectionValueXmlSerializer(), new DataFieldDescriptorValueXmlSerializer(), new DataTypeDescriptorValueXmlSerializer(), new NamedFunctionCallValueXmlSerializer(), new SerializerHandlerValueXmlSerializer(), new SystemSerializableValueXmlSerializer() }); XElement containerLabelElement = new XElement("ContainerLabel"); if (this.ContainerLabel != null) { containerLabelElement.Add(new XAttribute("value", this.ContainerLabel)); } XElement formDefinitionElement = new XElement("FormDefinition"); if (this.FormDefinition != null) { formDefinitionElement.Add(new XAttribute("value", this.FormDefinition)); } else { using (XmlReader xmlReader = this.FormMarkupProvider.GetReader()) { xmlReader.MoveToContent(); XElement element = (XElement)XDocument.ReadFrom(xmlReader); XDocument document = new XDocument(element); string content = document.GetDocumentAsString(); formDefinitionElement.Add(new XAttribute("value", content)); } } XElement customToolBarItems = null; if (CustomToolbarItems != null && CustomToolbarItems.Count > 0) { customToolBarItems = new XElement(nameof(CustomToolbarItems), CustomToolbarItems.Select(tuple => new XElement("item", new XAttribute("id", tuple.Item1.ToString()), new XAttribute("markup", tuple.Item2.ToString()), new XAttribute("priority", (int)tuple.Item3))) .OfType() .ToArray()); } XElement containerTypeElement = xmlSerializer.Serialize(typeof(IFlowUiContainerType), this.ContainerType); Dictionary selectedBindings = (from kvp in this.Bindings where (kvp.Value != null && kvp.Value.GetType() != typeof(System.EventHandler)) || kvp.Value == null select kvp).ToDictionary(f => f.Key, f => f.Value); XElement bindingsElement = xmlSerializer.Serialize(typeof(Dictionary), selectedBindings); XElement bindingsValidationRulesElement = xmlSerializer.Serialize(typeof(Dictionary>), this.BindingsValidationRules); XElement excludedEventsElement = xmlSerializer.Serialize(typeof(List), ExcludedEvents); var formDataElement = new XElement("FormData", containerLabelElement, formDefinitionElement, customToolBarItems, new XElement("ContainerType", containerTypeElement), new XElement("Bindings", bindingsElement), new XElement("BindingsValidationRules", bindingsValidationRulesElement) ); if (excludedEventsElement != null) { formDataElement.Add(new XElement("ExcludedEvents", excludedEventsElement)); } if (this.EventHandleFilterType != null) { formDataElement.Add(new XElement("EventHandleFilterType", new XAttribute("type", TypeManager.SerializeType(this.EventHandleFilterType)))); } return formDataElement; } } /// public static FormData Deserialize(XElement serializedData) { using (new ThreadCultureScope(CultureInfo.InvariantCulture)) { IXmlSerializer xmlSerializer = new XmlSerializer(new IValueXmlSerializer[] { new SystemPrimitivValueXmlSerializer(), new SystemCollectionValueXmlSerializer(), new SystemTypesValueXmlSerializer(), new CompositeCollectionValueXmlSerializer(), new DataFieldDescriptorValueXmlSerializer(), new DataTypeDescriptorValueXmlSerializer(), new NamedFunctionCallValueXmlSerializer(), new SerializerHandlerValueXmlSerializer(), new SystemSerializableValueXmlSerializer()}); FormData formData = new FormData(); XElement containerLabelElement = serializedData.Elements("ContainerLabel").Single(); XAttribute containerLabelValueAttribute = containerLabelElement.Attribute("value"); if (containerLabelValueAttribute != null) { formData.ContainerLabel = containerLabelValueAttribute.Value; } XElement formDefinitionElement = serializedData.Elements("FormDefinition").Single(); XAttribute formDefinitionValueAttribute = formDefinitionElement.Attribute("value"); if (formDefinitionValueAttribute != null) { formData.FormDefinition = formDefinitionValueAttribute.Value; formData.FormMarkupProvider = new StringBasedFormMarkupProvider(formDefinitionValueAttribute.Value); } formData.CustomToolbarItems = new List>(); var customToolbarItemsElement = serializedData.Elements(nameof(CustomToolbarItems)).FirstOrDefault(); if (customToolbarItemsElement != null) { formData.CustomToolbarItems.AddRange( customToolbarItemsElement.Elements().Select(element => new Tuple( (string)element.Attribute("id"), XDocument.Parse((string) element.Attribute("markup")), (ActionGroupPriority) ((int)element.Attribute("priority"))))); } XElement containerTypeElement = serializedData.Elements("ContainerType").Single(); object containerType = xmlSerializer.Deserialize(containerTypeElement.Elements().Single()); formData.ContainerType = (IFlowUiContainerType)containerType; XElement bindingsElement = serializedData.Elements("Bindings").Single(); object bindings = xmlSerializer.Deserialize(bindingsElement.Elements().Single()); formData.Bindings = (Dictionary)bindings; XElement bindingsValidationRulesElement = serializedData.Elements("BindingsValidationRules").Single(); object bindingsValidationRules = xmlSerializer.Deserialize(bindingsValidationRulesElement.Elements().Single()); formData.BindingsValidationRules = (Dictionary>)bindingsValidationRules; XElement eventHandleFilterTypeElement = serializedData.Elements("EventHandleFilterType").SingleOrDefault(); if (eventHandleFilterTypeElement != null) { Type eventHandleFilterType = TypeManager.GetType(eventHandleFilterTypeElement.Attribute("type").Value); formData.EventHandleFilterType = eventHandleFilterType; } XElement excludedEventsElement = serializedData.Elements("ExcludedEvents").SingleOrDefault(); if (excludedEventsElement != null) { object excludedEvents = xmlSerializer.Deserialize(excludedEventsElement.Elements().Single()); formData.ExcludedEvents = (List)excludedEvents; } return formData; } } } } ================================================ FILE: Composite/C1Console/Workflow/Foundation/FormsWorkflowActivityService.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Elements; using Composite.C1Console.Forms.Flows; using Composite.Data.Validation.ClientValidationRules; namespace Composite.C1Console.Workflow.Foundation { internal sealed class FormsWorkflowActivityService : IFormsWorkflowActivityService { public void DeliverFormData(Guid instanceId, string containerLabel, IFlowUiContainerType containerType, string formDefinition, Dictionary bindings) { var formData = GetOrAddFormData(instanceId); formData.ContainerLabel = containerLabel; formData.ContainerType = containerType; formData.FormDefinition = formDefinition; formData.FormMarkupProvider = null; formData.Bindings = bindings; } public void DeliverFormData(Guid instanceId, string containerLabel, IFlowUiContainerType containerType, IFormMarkupProvider formMarkupProvider, Dictionary bindings) { var formData = GetOrAddFormData(instanceId); formData.ContainerLabel = containerLabel; formData.ContainerType = containerType; formData.FormDefinition = null; formData.FormMarkupProvider = formMarkupProvider; formData.Bindings = bindings; } public void DeliverFormData(Guid instanceId, string containerLabel, IFlowUiContainerType containerType, string formDefinition, Dictionary bindings, Dictionary> bindingsValidationRules) { var formData = GetOrAddFormData(instanceId); formData.ContainerLabel = containerLabel; formData.ContainerType = containerType; formData.FormDefinition = formDefinition; formData.FormMarkupProvider = null; formData.Bindings = bindings; formData.BindingsValidationRules = bindingsValidationRules; } public void DeliverFormData(Guid instanceId, string containerLabel, IFlowUiContainerType containerType, IFormMarkupProvider formMarkupProvider, Dictionary bindings, Dictionary> bindingsValidationRules) { var formData = GetOrAddFormData(instanceId); formData.ContainerLabel = containerLabel; formData.ContainerType = containerType; formData.FormDefinition = null; formData.FormMarkupProvider = formMarkupProvider; formData.Bindings = bindings; formData.BindingsValidationRules = bindingsValidationRules; } public void AddCustomToolbarItem(Guid instanceId, string itemId, XDocument markup, ActionGroupPriority priority) { Verify.ArgumentNotNull(itemId, nameof(itemId)); Verify.ArgumentNotNull(markup, nameof(markup)); var formData = GetOrAddFormData(instanceId); if (formData.CustomToolbarItems == null) { formData.CustomToolbarItems = new List>(); } else { var existingItem = formData.CustomToolbarItems.FirstOrDefault(i => i.Item1 == itemId); if (existingItem != null) { formData.CustomToolbarItems.Remove(existingItem); } } formData.CustomToolbarItems.Add(new Tuple( itemId, markup, priority)); } public FlowControllerServicesContainer GetFlowServicesContainer(Guid instanceId) { throw new NotImplementedException(); } public void DeliverCustomToolbarDefinition(Guid instanceId, string customToolbarDefinition) { Verify.ArgumentNotNullOrEmpty(customToolbarDefinition, nameof(customToolbarDefinition)); AddCustomToolbarItem(instanceId, "default", XDocument.Parse(customToolbarDefinition), ActionGroupPriority.TargetedAppendMedium); } public void DeliverCustomToolbarDefinition(Guid instanceId, IFormMarkupProvider customToolbarMarkupProvider) { Verify.ArgumentNotNull(customToolbarMarkupProvider, nameof(customToolbarMarkupProvider)); var doc = XDocument.Load(customToolbarMarkupProvider.GetReader()); AddCustomToolbarItem(instanceId, "default", doc, ActionGroupPriority.TargetedAppendMedium); } private FormData GetOrAddFormData(Guid instanceId) { FormData formData; if (!WorkflowFacade.TryGetFormData(instanceId, out formData)) { formData = new FormData(); WorkflowFacade.AddFormData(instanceId, formData); } return formData; } } } ================================================ FILE: Composite/C1Console/Workflow/Foundation/FormsWorkflowEventService.cs ================================================ using System; namespace Composite.C1Console.Workflow.Foundation { internal sealed class FormsWorkflowEventService : IFormsWorkflowEventService { public event EventHandler Save; public event EventHandler SaveAndPublish; public event EventHandler Next; public event EventHandler Previous; public event EventHandler Finish; public event EventHandler Cancel; public event EventHandler Preview; public event EventHandler CustomEvent01; public event EventHandler CustomEvent02; public event EventHandler CustomEvent03; public event EventHandler CustomEvent04; public event EventHandler CustomEvent05; public event EventHandler ChildWorkflowDone; public void FireSaveEvent(FormEventArgs formEventArgs) { if (Save != null) { EventHandler save = Save; save(null, formEventArgs); } } public void FireSaveAndPublishEvent(FormEventArgs formEventArgs) { if (SaveAndPublish != null) { EventHandler saveAndPublish = SaveAndPublish; saveAndPublish(null, formEventArgs); } } public void FireNextEvent(FormEventArgs formEventArgs) { if (Next != null) { EventHandler next = Next; next(null, formEventArgs); } } public void FirePreviousEvent(FormEventArgs formEventArgs) { if (Previous != null) { EventHandler previous = Previous; previous(null, formEventArgs); } } public void FireFinishEvent(FormEventArgs formEventArgs) { if (Finish != null) { EventHandler finish = Finish; finish(null, formEventArgs); } } public void FireCancelEvent(FormEventArgs formEventArgs) { if (Cancel != null) { EventHandler cancel = Cancel; cancel(null, formEventArgs); } } public void FirePreviewEvent(FormEventArgs formEventArgs) { if (Preview != null) { EventHandler preview = Preview; preview(null, formEventArgs); } } public void FireCustomEvent01(FormEventArgs formEventArgs) { EventHandler customEvent = CustomEvent01; if (customEvent != null) { customEvent(null, formEventArgs); } } public void FireCustomEvent02(FormEventArgs formEventArgs) { EventHandler customEvent = CustomEvent02; if (customEvent != null) { customEvent(null, formEventArgs); } } public void FireCustomEvent03(FormEventArgs formEventArgs) { EventHandler customEvent = CustomEvent03; if (customEvent != null) { customEvent(null, formEventArgs); } } public void FireCustomEvent04(FormEventArgs formEventArgs) { EventHandler customEvent = CustomEvent04; if (customEvent != null) { customEvent(null, formEventArgs); } } public void FireCustomEvent05(FormEventArgs formEventArgs) { EventHandler customEvent = CustomEvent05; if (customEvent != null) { customEvent(null, formEventArgs); } } public void FireChildWorkflowDoneEvent(FormEventArgs formEventArgs) { if (ChildWorkflowDone != null) { EventHandler childWorkflowDone = ChildWorkflowDone; childWorkflowDone(null, formEventArgs); } } } } ================================================ FILE: Composite/C1Console/Workflow/Foundation/IWorkflowRuntimeProviderRegistry.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Composite.C1Console.Workflow.Foundation { internal interface IWorkflowRuntimeProviderRegistry { string DefaultWorkflowRuntimeProviderName { get; } void OnFlush(); } } ================================================ FILE: Composite/C1Console/Workflow/Foundation/PluginFacades/IWorkflowRuntimeProviderPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Workflow.Runtime; namespace Composite.C1Console.Workflow.Foundation.PluginFacades { internal interface IWorkflowRuntimeProviderPluginFacade { bool HasConfiguration { get; } WorkflowRuntime GetWorkflowRuntime(string providerName); void OnFlush(); } } ================================================ FILE: Composite/C1Console/Workflow/Foundation/PluginFacades/WorkflowRuntimeProviderPluginFacade.cs ================================================ using System.Workflow.Runtime; using Composite.C1Console.Events; namespace Composite.C1Console.Workflow.Foundation.PluginFacades { internal static class WorkflowRuntimeProviderPluginFacade { private static IWorkflowRuntimeProviderPluginFacade _implementation = new WorkflowRuntimeProviderPluginFacadeImpl(); internal static IWorkflowRuntimeProviderPluginFacade Implementation { get { return _implementation; } set { _implementation = value; } } static WorkflowRuntimeProviderPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static bool HasConfiguration { get { return _implementation.HasConfiguration; } } public static WorkflowRuntime GetWorkflowRuntime(string providerName) { return _implementation.GetWorkflowRuntime(providerName); } private static void OnFlushEvent(FlushEventArgs args) { _implementation.OnFlush(); } } } ================================================ FILE: Composite/C1Console/Workflow/Foundation/PluginFacades/WorkflowRuntimeProviderPluginFacadeImpl.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Workflow.Runtime; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.C1Console.Workflow.Plugins.WorkflowRuntimeProvider; using Composite.C1Console.Workflow.Plugins.WorkflowRuntimeProvider.Runtime; namespace Composite.C1Console.Workflow.Foundation.PluginFacades { internal class WorkflowRuntimeProviderPluginFacadeImpl : IWorkflowRuntimeProviderPluginFacade { private ResourceLocker _resources; public WorkflowRuntimeProviderPluginFacadeImpl() { _resources = new ResourceLocker(new Resources { Owner = this }, Resources.Initialize); } public bool HasConfiguration { get { return (ConfigurationServices.ConfigurationSource != null) && (ConfigurationServices.ConfigurationSource.GetSection(WorkflowRuntimeProviderSettings.SectionName) != null); } } public WorkflowRuntime GetWorkflowRuntime(string providerName) { if (string.IsNullOrEmpty(providerName)) throw new ArgumentNullException("providerName"); using (_resources.Locker) { WorkflowRuntime workflowRuntime = GetWorkflowRuntimeProvider(providerName).GetWorkflowRuntime(); if (workflowRuntime == null) throw new InvalidOperationException(string.Format("The workflow runtime provider '{0}' returned null", providerName)); return workflowRuntime; } } public void OnFlush() { _resources.ResetInitialization(); } private IWorkflowRuntimeProvider GetWorkflowRuntimeProvider(string providerName) { using (_resources.Locker) { IWorkflowRuntimeProvider provider; if (_resources.Resources.ProviderCache.TryGetValue(providerName, out provider) == false) { try { provider = _resources.Resources.Factory.Create(providerName); _resources.Resources.ProviderCache.Add(providerName, provider); } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } return provider; } } private void HandleConfigurationError(Exception ex) { OnFlush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", WorkflowRuntimeProviderSettings.SectionName), ex); } private sealed class Resources { public WorkflowRuntimeProviderFactory Factory { get; set; } public Dictionary ProviderCache { get; set; } public WorkflowRuntimeProviderPluginFacadeImpl Owner { get; set; } public static void Initialize(Resources resources) { try { resources.Factory = new WorkflowRuntimeProviderFactory(); } catch (NullReferenceException ex) { resources.Owner.HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { resources.Owner.HandleConfigurationError(ex); } resources.ProviderCache = new Dictionary(); } } } } ================================================ FILE: Composite/C1Console/Workflow/Foundation/WorkflowRuntimeProviderRegistry.cs ================================================ using Composite.C1Console.Events; namespace Composite.C1Console.Workflow.Foundation { internal static class WorkflowRuntimeProviderRegistry { private static IWorkflowRuntimeProviderRegistry _implementation = new WorkflowRuntimeProviderRegistryImpl(); internal static IWorkflowRuntimeProviderRegistry Implementation { get { return _implementation; } set { _implementation = value; } } static WorkflowRuntimeProviderRegistry() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static string DefaultWorkflowRuntimeProviderName { get { return _implementation.DefaultWorkflowRuntimeProviderName; } } private static void OnFlushEvent(FlushEventArgs args) { _implementation.OnFlush(); } } } ================================================ FILE: Composite/C1Console/Workflow/Foundation/WorkflowRuntimeProviderRegistryImpl.cs ================================================ using System.Configuration; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.C1Console.Events; using Composite.C1Console.Workflow.Plugins.WorkflowRuntimeProvider.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Composite.Core.Logging; namespace Composite.C1Console.Workflow.Foundation { internal class WorkflowRuntimeProviderRegistryImpl : IWorkflowRuntimeProviderRegistry { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); public string DefaultWorkflowRuntimeProviderName { get { using (_resourceLocker.Locker) { return _resourceLocker.Resources.DefaultWorkflowRuntimeProviderName; } } } public void OnFlush() { _resourceLocker.ResetInitialization(); } private static IConfigurationSource GetConfiguration() { IConfigurationSource source = ConfigurationServices.ConfigurationSource; if (null == source) { throw new ConfigurationErrorsException(string.Format("No configuration source specified")); } return source; } private sealed class Resources { public string DefaultWorkflowRuntimeProviderName { get; set; } public static void Initialize(Resources resources) { IConfigurationSource configurationSource = GetConfiguration(); WorkflowRuntimeProviderSettings settings = configurationSource.GetSection(WorkflowRuntimeProviderSettings.SectionName) as WorkflowRuntimeProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration", WorkflowRuntimeProviderSettings.SectionName)); } resources.DefaultWorkflowRuntimeProviderName = settings.DefaultProviderName; } } } } ================================================ FILE: Composite/C1Console/Workflow/IEventHandleFilter.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Forms.Flows; namespace Composite.C1Console.Workflow { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IEventHandleFilter { /// void Filter(Dictionary eventHandlers); } } ================================================ FILE: Composite/C1Console/Workflow/IFormsWorkflowActivityService.cs ================================================ using System; using System.Workflow.Activities; using System.Collections.Generic; using System.Xml.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Elements; using Composite.C1Console.Forms.Flows; using Composite.Data.Validation.ClientValidationRules; namespace Composite.C1Console.Workflow { [ExternalDataExchange] internal interface IFormsWorkflowActivityService { void DeliverFormData(Guid instanceId, string containerLabel, IFlowUiContainerType containerType, string formMarkup, Dictionary bindings); void DeliverFormData(Guid instanceId, string containerLabel, IFlowUiContainerType containerType, IFormMarkupProvider formMarkupProvider, Dictionary bindings); void DeliverFormData(Guid instanceId, string containerLabel, IFlowUiContainerType containerType, string formMarkup, Dictionary bindings, Dictionary> bindingsValidationRules); void DeliverFormData(Guid instanceId, string containerLabel, IFlowUiContainerType containerType, IFormMarkupProvider formMarkupProvider, Dictionary bindings, Dictionary> bindingsValidationRules); void DeliverCustomToolbarDefinition(Guid instanceId, string customToolbarMarkup); void DeliverCustomToolbarDefinition(Guid instanceId, IFormMarkupProvider customToolbarMarkupProvider); void AddCustomToolbarItem(Guid instanceId, string itemId, XDocument markup, ActionGroupPriority priority); FlowControllerServicesContainer GetFlowServicesContainer(Guid instanceId); } } ================================================ FILE: Composite/C1Console/Workflow/IFormsWorkflowEventService.cs ================================================ using System; using System.Workflow.Activities; namespace Composite.C1Console.Workflow { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ExternalDataExchange()] public interface IFormsWorkflowEventService { /// event EventHandler Save; /// event EventHandler SaveAndPublish; /// event EventHandler Next; /// event EventHandler Previous; /// event EventHandler Finish; /// event EventHandler Cancel; /// event EventHandler Preview; /// event EventHandler CustomEvent01; /// event EventHandler CustomEvent02; /// event EventHandler CustomEvent03; /// event EventHandler CustomEvent04; /// event EventHandler CustomEvent05; /// event EventHandler ChildWorkflowDone; } } ================================================ FILE: Composite/C1Console/Workflow/IFormsWorkflowExtension.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Workflow.Activities; using Composite.Data.Validation.ClientValidationRules; namespace Composite.C1Console.Workflow { /// public class OnDeliverFormDataParameters { /// public Dictionary Bindings { get; set; } /// public Dictionary> BindingsValidationRules { get; set; } } /// /// An interface for forms workflow extensions /// public interface IFormsWorkflowExtension { /// /// In implementation custom workflow activities can be added. /// /// The workflow instance. void Initialize(FormsWorkflow workflow); /// /// Handles form data delivery event /// /// The workflow instance. /// The parameters. void OnDeliverFormData(FormsWorkflow workflow, OnDeliverFormDataParameters parameters); } } ================================================ FILE: Composite/C1Console/Workflow/IWorkflowFacade.cs ================================================ using System; using System.Collections.Generic; using System.Threading; using System.Workflow.Activities; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Security; using Composite.C1Console.Workflow.Foundation; using Composite.C1Console.Events; namespace Composite.C1Console.Workflow { internal interface IWorkflowFacade { void EnsureInitialization(); WorkflowRuntime WorkflowRuntime { get; } void RunWhenInitialized(Action action); #region Workflow methods WorkflowInstance CreateNewWorkflow(Type workflowType); WorkflowInstance CreateNewWorkflow(Type workflowType, Dictionary arguments); WorkflowFlowToken StartNewWorkflow(Type workflowType, FlowControllerServicesContainer flowControllerServicesContainer, EntityToken entityToken, ActionToken actionToken); WorkflowInstance GetWorkflow(Guid instanceId); StateMachineWorkflowInstance GetStateMachineWorkflowInstance(Guid instanceId); void RunWorkflow(Guid instanceId); void RunWorkflow(WorkflowInstance workflowInstance); void AbortWorkflow(Guid instanceId); void AcquireLock(Guid instanceId, EntityToken entityToken); #endregion #region FlowControllerServices methods void SetFlowControllerServicesContainer(Guid instanceId, FlowControllerServicesContainer flowControllerServicesContainer); FlowControllerServicesContainer GetFlowControllerServicesContainer(Guid instanceId); void RemoveFlowControllerServicesContainer(Guid instanceId); #endregion #region Workflow status methods bool WorkflowExists(Guid instanceId); Semaphore WaitForIdleStatus(Guid instanceId); #endregion #region Form workflow methods void SetEventHandlerFilter(Guid instanceId, Type eventHandlerFilterType); IEventHandleFilter GetEventHandleFilter(Guid instanceId); IEnumerable GetCurrentFormEvents(Guid instanceId); IEnumerable GetCurrentFormEvents(WorkflowInstance workflowInstance); void FireSaveEvent(Guid instanceId, Dictionary bindings); void FireSaveAndPublishEvent(Guid instanceId, Dictionary bindings); void FireNextEvent(Guid instanceId, Dictionary bindings); void FirePreviousEvent(Guid instanceId, Dictionary bindings); void FireFinishEvent(Guid instanceId, Dictionary bindings); void FireCancelEvent(Guid instanceId, Dictionary bindings); void FirePreviewEvent(Guid instanceId, Dictionary bindings); void FireCustomEvent(int eventNumber, Guid instanceId, Dictionary bindings); void FireChildWorkflowDoneEvent(Guid parentInstanceId, string workflowResult); #endregion #region FormData methods void AddFormData(Guid instanceId, FormData formData); bool TryGetFormData(Guid instanceId, out FormData formData); FormData GetFormData(Guid instanceId, bool allowCreationIfNotExisting); #endregion void Flush(); void ShutDown(); void ConsoleClosed(ConsoleClosedEventArgs args); } } ================================================ FILE: Composite/C1Console/Workflow/Plugins/WorkflowRuntimeProvider/IWorkflowRuntimeProvider.cs ================================================ using System.Workflow.Runtime; using Composite.C1Console.Workflow.Plugins.WorkflowRuntimeProvider.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Workflow.Plugins.WorkflowRuntimeProvider { [CustomFactory(typeof(WorkflowRuntimeProviderCustomFactory))] [ConfigurationNameMapper(typeof(WorkflowRuntimeProviderDefaultNameRetriever))] internal interface IWorkflowRuntimeProvider { WorkflowRuntime GetWorkflowRuntime(); } } ================================================ FILE: Composite/C1Console/Workflow/Plugins/WorkflowRuntimeProvider/NonConfigurableWorkflowRuntimeProvider.cs ================================================ using System; using Microsoft.Practices.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Workflow.Plugins.WorkflowRuntimeProvider { [Assembler(typeof(NonConfigurableWorkflowRuntimeProviderAssembler))] internal class NonConfigurableWorkflowRuntimeProvider : WorkflowRuntimeProviderData { } internal sealed class NonConfigurableWorkflowRuntimeProviderAssembler : IAssembler { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IWorkflowRuntimeProvider Assemble(IBuilderContext context, WorkflowRuntimeProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IWorkflowRuntimeProvider)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/C1Console/Workflow/Plugins/WorkflowRuntimeProvider/Runtime/WorkflowRuntimeProviderCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Workflow.Plugins.WorkflowRuntimeProvider.Runtime { internal sealed class WorkflowRuntimeProviderCustomFactory : AssemblerBasedCustomFactory { protected override WorkflowRuntimeProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { WorkflowRuntimeProviderSettings settings = configurationSource.GetSection(WorkflowRuntimeProviderSettings.SectionName) as WorkflowRuntimeProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", WorkflowRuntimeProviderSettings.SectionName)); } return settings.WorkflowRuntimeProviderPlugins.Get(name); } } } ================================================ FILE: Composite/C1Console/Workflow/Plugins/WorkflowRuntimeProvider/Runtime/WorkflowRuntimeProviderDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Workflow.Plugins.WorkflowRuntimeProvider.Runtime { internal sealed class WorkflowRuntimeProviderDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/C1Console/Workflow/Plugins/WorkflowRuntimeProvider/Runtime/WorkflowRuntimeProviderFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.C1Console.Workflow.Plugins.WorkflowRuntimeProvider.Runtime { internal sealed class WorkflowRuntimeProviderFactory : NameTypeFactoryBase { public WorkflowRuntimeProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/C1Console/Workflow/Plugins/WorkflowRuntimeProvider/Runtime/WorkflowRuntimeProviderSettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Workflow.Plugins.WorkflowRuntimeProvider.Runtime { internal sealed class WorkflowRuntimeProviderSettings : SerializableConfigurationSection { public const string SectionName = "Composite.C1Console.Workflow.Plugins.WorkflowRuntimeProviderConfiguration"; private const string _defaultProviderNameProperty = "defaultProviderName"; [ConfigurationProperty(_defaultProviderNameProperty, IsRequired = true)] public string DefaultProviderName { get { return (string)base[_defaultProviderNameProperty]; } set { base[_defaultProviderNameProperty] = value; } } private const string _workflowRuntimeProviderPluginsProperty = "WorkflowRuntimeProviderPlugins"; [ConfigurationProperty(_workflowRuntimeProviderPluginsProperty)] public NameTypeManagerTypeConfigurationElementCollection WorkflowRuntimeProviderPlugins { get { return (NameTypeManagerTypeConfigurationElementCollection)base[_workflowRuntimeProviderPluginsProperty]; } } } } ================================================ FILE: Composite/C1Console/Workflow/Plugins/WorkflowRuntimeProvider/WorkflowRuntimeProviderData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.C1Console.Workflow.Plugins.WorkflowRuntimeProvider { [ConfigurationElementType(typeof(NonConfigurableWorkflowRuntimeProvider))] internal class WorkflowRuntimeProviderData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/C1Console/Workflow/StateMachineWorkflowInstanceExtensionMethods.cs ================================================ using System; using System.Collections.Generic; using System.Workflow.Activities; using System.Workflow.ComponentModel; namespace Composite.C1Console.Workflow { internal static class StateMachineWorkflowInstanceExtensionMethods { public static IEnumerable GetCurrentEventNames(this StateMachineWorkflowInstance stateMachineWorkflowInstance, Type eventServiceType) { if (stateMachineWorkflowInstance == null) throw new ArgumentNullException("stateMachineWorkflowInstance"); if (eventServiceType == null) throw new ArgumentNullException("eventServiceType"); Verify.IsNotNull(stateMachineWorkflowInstance.CurrentState, "The workflow has already been canceled."); foreach (Activity currentStateActivity in stateMachineWorkflowInstance.CurrentState.Activities) { if (currentStateActivity.Enabled == false) continue; if ((currentStateActivity is EventDrivenActivity) == false) continue; HandleExternalEventActivity handleExternalEventActivity = ((EventDrivenActivity)currentStateActivity).EventActivity as HandleExternalEventActivity; if (handleExternalEventActivity == null) continue; if (handleExternalEventActivity.Enabled == false) continue; if (handleExternalEventActivity.InterfaceType != eventServiceType) continue; yield return handleExternalEventActivity.EventName; } } } } ================================================ FILE: Composite/C1Console/Workflow/WorkflowActionExecutor.cs ================================================ using System.Collections.Generic; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Security; namespace Composite.C1Console.Workflow { internal sealed class WorkflowActionExecutor : IActionExecutorSerializedParameters { public FlowToken Execute(string serializedEntityToken, string serializedActionToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { WorkflowActionToken workflowActionToken = (WorkflowActionToken)actionToken; WorkflowInstance workflowInstance = WorkflowFacade.CreateNewWorkflow( workflowActionToken.WorkflowType, new Dictionary { { "SerializedEntityToken", serializedEntityToken }, { "SerializedActionToken", serializedActionToken }, { "ParentWorkflowInstanceId", workflowActionToken.ParentWorkflowInstanceId } } ); workflowInstance.Start(); WorkflowFacade.SetFlowControllerServicesContainer(workflowInstance.InstanceId, flowControllerServicesContainer); WorkflowFacade.RunWorkflow(workflowInstance); WorkflowFacade.SetEventHandlerFilter(workflowInstance.InstanceId, workflowActionToken.EventHandleFilterType); return new WorkflowFlowToken(workflowInstance.InstanceId); } public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { return Execute(EntityTokenSerializer.Serialize(entityToken), ActionTokenSerializer.Serialize(actionToken), actionToken, flowControllerServicesContainer); } } } ================================================ FILE: Composite/C1Console/Workflow/WorkflowActionToken.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.C1Console.Actions; using Composite.C1Console.Security; using Composite.Core.Types; using static Composite.Core.Serialization.StringConversionServices; namespace Composite.C1Console.Workflow { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ActionExecutor(typeof(WorkflowActionExecutor))] public class WorkflowActionToken : ActionToken { /// public WorkflowActionToken(Type workflowType) : this(workflowType, null) { } /// public WorkflowActionToken(Type workflowType, IEnumerable permissionType) { Verify.ArgumentNotNull(workflowType, nameof(workflowType)); PermissionTypes = permissionType ?? Enumerable.Empty(); this.WorkflowType = workflowType; this.ParentWorkflowInstanceId = Guid.Empty; this.Payload = ""; this.ExtraPayload = ""; this.EventHandleFilterType = null; } /// public Type WorkflowType { get; } /// public Guid ParentWorkflowInstanceId { get; set; } // User defined data to the workflow /// public string Payload { get; set; } // User defined data to the workflow /// public string ExtraPayload { get; set; } /// public bool DoIgnoreEntityTokenLocking { get; set; } /// public Type EventHandleFilterType { get; set; } /// public override bool IgnoreEntityTokenLocking => this.DoIgnoreEntityTokenLocking; /// public override IEnumerable PermissionTypes { get; } /// public override string Serialize() { var stringBuilder = new StringBuilder(); SerializeKeyValuePair(stringBuilder, "_WorkflowType_", TypeManager.SerializeType(this.WorkflowType)); SerializeKeyValuePair(stringBuilder, "_Payload_", this.Payload); SerializeKeyValuePair(stringBuilder, "_ExtraPayload_", this.ExtraPayload); SerializeKeyValuePair(stringBuilder, "_Ignore_", this.DoIgnoreEntityTokenLocking); SerializeKeyValuePair(stringBuilder, "_PermissionTypes_", this.PermissionTypes.SerializePermissionTypes()); if (this.EventHandleFilterType != null) { string serializedType = TypeManager.SerializeType(this.EventHandleFilterType); SerializeKeyValuePair(stringBuilder, "_EventHandleFilterType_", serializedType); } return stringBuilder.ToString(); } /// public static ActionToken Deserialize(string serializedWorkflowActionToken) { Dictionary dic = ParseKeyValueCollection(serializedWorkflowActionToken); if (!dic.ContainsKey("_WorkflowType_") || !dic.ContainsKey("_Payload_") || !dic.ContainsKey("_ExtraPayload_") || !dic.ContainsKey("_Ignore_") || !dic.ContainsKey("_PermissionTypes_")) { throw new ArgumentException("The serializedWorkflowActionToken is not a serialized WorkflowActionToken", nameof(serializedWorkflowActionToken)); } string serializedType = DeserializeValueString(dic["_WorkflowType_"]); Type type = TypeManager.GetType(serializedType); string permissionTypesString = DeserializeValueString(dic["_PermissionTypes_"]); var workflowActionToken = new WorkflowActionToken(type, permissionTypesString.DesrializePermissionTypes()); string payload = DeserializeValueString(dic["_Payload_"]); workflowActionToken.Payload = payload; string extraPayload = DeserializeValueString(dic["_ExtraPayload_"]); workflowActionToken.ExtraPayload = extraPayload; bool ignoreEntityTokenLocking = DeserializeValueBool(dic["_Ignore_"]); workflowActionToken.DoIgnoreEntityTokenLocking = ignoreEntityTokenLocking; if (dic.ContainsKey("_EventHandleFilterType_")) { string serializedFilterType = DeserializeValueString(dic["_EventHandleFilterType_"]); workflowActionToken.EventHandleFilterType = TypeManager.GetType(serializedFilterType); } return workflowActionToken; } } } ================================================ FILE: Composite/C1Console/Workflow/WorkflowFacade.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Workflow.Activities; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.C1Console.Workflow.Foundation; using Composite.Core.Types; namespace Composite.C1Console.Workflow { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class WorkflowFacade { private static IWorkflowFacade _workflowFacade = new WorkflowFacadeImpl(); private static readonly ConcurrentDictionary _workflowTypeLookupCache = new ConcurrentDictionary(); static WorkflowFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); GlobalEventSystemFacade.SubscribeToShutDownEvent(OnShutDownEvent); ConsoleFacade.SubscribeToConsoleClosedEvent(OnConsoleClosedEvent); } internal static IWorkflowFacade Implementation { get { return _workflowFacade; } set { _workflowFacade = value; } } /// public static void EnsureInitialization() { using (GlobalInitializerFacade.CoreIsInitializedScope) { _workflowFacade.EnsureInitialization(); } } /// public static WorkflowRuntime WorkflowRuntime { get { return _workflowFacade.WorkflowRuntime; } } /// public static Type GetWorkflowType(string typeName) { Type type = _workflowTypeLookupCache.GetOrAdd(typeName, GetWorkflowTypeInternal); Verify.IsNotNull(type, "Could not find the workflow type: {0}", typeName); return type; } private static Type GetWorkflowTypeInternal(string typeName) { Type type = TypeManager.TryGetType(typeName); if (type == null && !typeName.Contains(",")) { string fullname = typeName + ", Composite.Workflows"; type = TypeManager.TryGetType(fullname); } return type; } /// /// Runs the when initialized. /// /// The action. public static void RunWhenInitialized(Action action) { _workflowFacade.RunWhenInitialized(action); } #region Workflow methods /// public static WorkflowInstance CreateNewWorkflow(Type workflowType) { return _workflowFacade.CreateNewWorkflow(workflowType); } /// public static WorkflowInstance CreateNewWorkflow(Type workflowType, Dictionary arguments) { return _workflowFacade.CreateNewWorkflow(workflowType, arguments); } /// public static WorkflowFlowToken StartNewWorkflow(Type workflowType, FlowControllerServicesContainer flowControllerServicesContainer, EntityToken entityToken, ActionToken actionToken) { return _workflowFacade.StartNewWorkflow(workflowType, flowControllerServicesContainer, entityToken, actionToken); } /// public static WorkflowInstance GetWorkflow(Guid instanceId) { return _workflowFacade.GetWorkflow(instanceId); } /// public static StateMachineWorkflowInstance GetStateMachineWorkflowInstance(Guid instanceId) { return _workflowFacade.GetStateMachineWorkflowInstance(instanceId); } /// public static void RunWorkflow(Guid instanceId) { _workflowFacade.RunWorkflow(instanceId); } /// public static void RunWorkflow(WorkflowInstance workflowInstance) { _workflowFacade.RunWorkflow(workflowInstance); } /// public static void AbortWorkflow(Guid instanceId) { _workflowFacade.AbortWorkflow(instanceId); } /// public static void AcquireLock(Guid instanceId, EntityToken entityToken) { _workflowFacade.AcquireLock(instanceId, entityToken); } #endregion #region FlowControllerServices methods /// public static void SetFlowControllerServicesContainer(Guid instanceId, FlowControllerServicesContainer flowControllerServicesContainer) { _workflowFacade.SetFlowControllerServicesContainer(instanceId, flowControllerServicesContainer); } /// public static FlowControllerServicesContainer GetFlowControllerServicesContainer(Guid instanceId) { return _workflowFacade.GetFlowControllerServicesContainer(instanceId); } /// private static void RemoveFlowControllerServicesContainer(Guid instanceId) { _workflowFacade.RemoveFlowControllerServicesContainer(instanceId); } #endregion #region Workflow status methods /// public static bool WorkflowExists(Guid instanceId) { return _workflowFacade.WorkflowExists(instanceId); } /// /// This method returns a semaphore that will be signaled when the workflow instance becomes idle. /// Or null if the workflow instance is idle at the calling moment. /// /// /// public static Semaphore WaitForIdleStatus(Guid instanceId) { return _workflowFacade.WaitForIdleStatus(instanceId); } #endregion #region Form workflow methods /// public static void SetEventHandlerFilter(Guid instanceId, Type eventHandlerFilterType) { _workflowFacade.SetEventHandlerFilter(instanceId, eventHandlerFilterType); } /// public static IEventHandleFilter GetEventHandleFilter(Guid instanceId) { return _workflowFacade.GetEventHandleFilter(instanceId); } /// public static IEnumerable GetCurrentFormEvents(Guid instanceId) { return _workflowFacade.GetCurrentFormEvents(instanceId); } /// public static IEnumerable GetCurrentFormEvents(WorkflowInstance workflowInstance) { return _workflowFacade.GetCurrentFormEvents(workflowInstance); } /// public static void FireSaveEvent(Guid instanceId, Dictionary bindings) { _workflowFacade.FireSaveEvent(instanceId, bindings); } /// public static void FireSaveAndPublishEvent(Guid instanceId, Dictionary bindings) { _workflowFacade.FireSaveAndPublishEvent(instanceId, bindings); } /// public static void FireNextEvent(Guid instanceId, Dictionary bindings) { _workflowFacade.FireNextEvent(instanceId, bindings); } /// public static void FirePreviousEvent(Guid instanceId, Dictionary bindings) { _workflowFacade.FirePreviousEvent(instanceId, bindings); } /// public static void FireFinishEvent(Guid instanceId, Dictionary bindings) { _workflowFacade.FireFinishEvent(instanceId, bindings); } /// public static void FireCancelEvent(Guid instanceId, Dictionary bindings) { _workflowFacade.FireCancelEvent(instanceId, bindings); } /// public static void FirePreviewEvent(Guid instanceId, Dictionary bindings) { _workflowFacade.FirePreviewEvent(instanceId, bindings); } /// public static void FireCustomEvent(int customEventNumber, Guid instanceId, Dictionary bindings) { if (customEventNumber < 1 || customEventNumber > 5) throw new ArgumentException("Number must be between 1 and 5", "customEventNumber"); _workflowFacade.FireCustomEvent(customEventNumber, instanceId, bindings); } /// public static void FireChildWorkflowDoneEvent(Guid parentInstanceId, string workflowResult) { _workflowFacade.FireChildWorkflowDoneEvent(parentInstanceId, workflowResult); } #endregion #region FormData methods internal static void AddFormData(Guid instanceId, FormData formData) { _workflowFacade.AddFormData(instanceId, formData); } /// public static bool TryGetFormData(Guid instanceId, out FormData formData) { return _workflowFacade.TryGetFormData(instanceId, out formData); } /// public static FormData GetFormData(Guid instanceId, bool allowCreationIfNotExisting = false) { return _workflowFacade.GetFormData(instanceId, allowCreationIfNotExisting); } #endregion private static void OnFlushEvent(FlushEventArgs args) { _workflowFacade.Flush(); } private static void OnShutDownEvent(ShutDownEventArgs args) { _workflowFacade.ShutDown(); } private static void OnConsoleClosedEvent(ConsoleClosedEventArgs args) { _workflowFacade.ConsoleClosed(args); } } } ================================================ FILE: Composite/C1Console/Workflow/WorkflowFacadeImpl.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Web.Hosting; using System.Workflow.Activities; using System.Workflow.ComponentModel.Compiler; using System.Workflow.Runtime; using System.Workflow.Runtime.Hosting; using System.Xml.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.C1Console.Tasks; using Composite.C1Console.Workflow.Activities.Foundation; using Composite.C1Console.Workflow.Foundation; using Composite.C1Console.Workflow.Foundation.PluginFacades; using Composite.Core; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Threading; using Composite.Core.Types; using Composite.Core.Xml; using Composite.Data; namespace Composite.C1Console.Workflow { internal sealed class WorkflowFacadeImpl : IWorkflowFacade { private static readonly string LogTitle = "WorkflowFacade"; private static readonly string LogTitleColored = "RGB(194, 252, 131)" + LogTitle; private static readonly TimeSpan OldFileExistenceTimeout = TimeSpan.FromDays(30.0); private Thread _initializeThread; private readonly object _initializeThreadLock = new object(); private bool _isShutDown; private WorkflowRuntime _workflowRuntime; private readonly List _actionToRunWhenInitialized = new List(); private ExternalDataExchangeService _externalDataExchangeService; private FormsWorkflowEventService _formsWorkflowEventService; private ManualWorkflowSchedulerService _manualWorkflowSchedulerService; private FileWorkflowPersistenceService _fileWorkflowPersistenceService; private readonly ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.InitializeResources); private readonly Dictionary _hasEntityTokenLockAttributeCache = new Dictionary(); public WorkflowFacadeImpl() { string serializedWorkflowsDirectory = PathUtil.Resolve(GlobalSettingsFacade.SerializedWorkflowsDirectory); string parentDirectory = Path.GetDirectoryName(serializedWorkflowsDirectory); string lockFileDirectory = Path.Combine(parentDirectory, "LockFiles"); if (!C1Directory.Exists(lockFileDirectory)) C1Directory.CreateDirectory(lockFileDirectory); } public void EnsureInitialization() { if (_initializeThread != null) return; lock (_initializeThreadLock) { if (_initializeThread != null) return; ThreadStart threadStart = () => { using(ThreadDataManager.EnsureInitialize()) { int startTime = Environment.TickCount; while (_workflowRuntime == null && !_isShutDown && startTime + 30000 > Environment.TickCount) { Thread.Sleep(100); } if (_workflowRuntime != null) { Log.LogVerbose(LogTitleColored, "Already initialized, skipping delayed initialization"); return; } if (_isShutDown || HostingEnvironment.ApplicationHost.ShutdownInitiated()) { Log.LogVerbose(LogTitleColored, "System is shutting down, skipping delayed initialization"); return; } int endTime = Environment.TickCount; try { using (_resourceLocker.Locker) { DoInitialize(endTime - startTime); } } catch (Exception ex) { if (_isShutDown || HostingEnvironment.ApplicationHost.ShutdownInitiated()) { Log.LogVerbose(LogTitleColored, "Delayed initialization has failed, but the exception is ignored as the website is shutting down"); return; } Log.LogCritical(LogTitle, ex); } } }; _initializeThread = new Thread(threadStart); _initializeThread.Start(); } } public WorkflowRuntime WorkflowRuntime { get { DoInitialize(0); return _workflowRuntime; } } public void RunWhenInitialized(Action action) { _actionToRunWhenInitialized.Add(action); } #region Workflow methods public WorkflowInstance CreateNewWorkflow(Type workflowType) { GlobalInitializerFacade.EnsureSystemIsInitialized(); DoInitialize(0); try { WorkflowInstance workflowInstance = _workflowRuntime.CreateWorkflow(workflowType); SetWorkflowPersistingType(workflowType, workflowInstance.InstanceId); return workflowInstance; } catch (WorkflowValidationFailedException exp) { StringBuilder errors = new StringBuilder(); foreach (ValidationError error in exp.Errors) { errors.AppendLine(error.ToString()); } Log.LogError(LogTitle, errors.ToString()); throw; } } public WorkflowInstance CreateNewWorkflow(Type workflowType, Dictionary arguments) { GlobalInitializerFacade.EnsureSystemIsInitialized(); DoInitialize(0); try { WorkflowInstance workflowInstance = _workflowRuntime.CreateWorkflow(workflowType, arguments); SetWorkflowPersistingType(workflowType, workflowInstance.InstanceId); if (arguments.TryGetValue("SerializedEntityToken", out var serializedEntityToken) && arguments.TryGetValue("SerializedActionToken", out var serializedActionToken)) { ActionToken actionToken = ActionTokenSerializer.Deserialize((string)serializedActionToken); if (!actionToken.IgnoreEntityTokenLocking) { AcquireLockIfNeeded(workflowType, workflowInstance.InstanceId, (string)serializedEntityToken); } } return workflowInstance; } catch (WorkflowValidationFailedException exp) { var errors = new StringBuilder(); foreach (ValidationError error in exp.Errors) { errors.AppendLine(error.ToString()); } Log.LogError(LogTitle, errors.ToString()); throw; } } public WorkflowFlowToken StartNewWorkflow(Type workflowType, FlowControllerServicesContainer flowControllerServicesContainer, EntityToken entityToken, ActionToken actionToken) { DoInitialize(0); Dictionary arguments = new Dictionary { { "EntityToken", entityToken }, { "ActionToken", actionToken } }; try { WorkflowInstance workflowInstance = _workflowRuntime.CreateWorkflow(workflowType, arguments); SetWorkflowPersistingType(workflowType, workflowInstance.InstanceId); AcquireLockIfNeeded(workflowType, workflowInstance.InstanceId, entityToken); workflowInstance.Start(); SetFlowControllerServicesContainer(workflowInstance.InstanceId, flowControllerServicesContainer); RunWorkflow(workflowInstance); return new WorkflowFlowToken(workflowInstance.InstanceId); } catch (Exception e) { Log.LogCritical(LogTitle, e); throw; } } public WorkflowInstance GetWorkflow(Guid instanceId) { DoInitialize(0); return _workflowRuntime.GetWorkflow(instanceId); } public StateMachineWorkflowInstance GetStateMachineWorkflowInstance(Guid instanceId) { DoInitialize(0); return new StateMachineWorkflowInstance(_workflowRuntime, instanceId); } public void RunWorkflow(Guid instanceId) { DoInitialize(0); SetWorkflowInstanceStatus(instanceId, WorkflowInstanceStatus.Running, false); _manualWorkflowSchedulerService.RunWorkflow(instanceId); if (_resourceLocker.Resources.ExceptionFromWorkflow.TryRemove(Thread.CurrentThread.ManagedThreadId, out var exception)) { throw new InvalidOperationException("Error executing workflow " + instanceId, exception); } } public void RunWorkflow(WorkflowInstance workflowInstance) { RunWorkflow(workflowInstance.InstanceId); } public void AbortWorkflow(Guid instanceId) { DoInitialize(0); using (_resourceLocker.Locker) { if (AbortedWorkflows.Contains(instanceId)) return; AbortedWorkflows.Add(instanceId); if (_resourceLocker.Resources.WorkflowStatusDictionary.ContainsKey(instanceId)) { var workflowInstance = WorkflowRuntime.GetWorkflow(instanceId); workflowInstance.Abort(); if (_resourceLocker.Resources.ExceptionFromWorkflow.TryRemove(Thread.CurrentThread.ManagedThreadId, out var exception)) { throw exception; } } } } private void SetWorkflowPersistingType(Type workflowType, Guid instanceId) { List attributes = workflowType.GetCustomAttributesRecursively().ToList(); Verify.That(attributes.Count <= 1, $"More than one attribute of type '{nameof(AllowPersistingWorkflowAttribute)}' found"); var persistenceType = attributes.Count == 1 ? attributes[0].WorkflowPersistingType : WorkflowPersistingType.Never; using (_resourceLocker.Locker) { _resourceLocker.Resources.WorkflowPersistingTypeDictionary.Add(instanceId, persistenceType); } } private void RemovePersistingType(Guid instanceId) { using (_resourceLocker.Locker) { _resourceLocker.Resources.WorkflowPersistingTypeDictionary.Remove(instanceId); } } private void AcquireLockIfNeeded(Type workflowType, Guid instanceId, string serializedEntityToken) { if (HasEntityTokenLockAttribute(workflowType)) { EntityToken entityToken = EntityTokenSerializer.Deserialize(serializedEntityToken); AcquireLock(instanceId, entityToken); } } private void AcquireLockIfNeeded(Type workflowType, Guid instanceId, EntityToken entityToken) { if (HasEntityTokenLockAttribute(workflowType)) { AcquireLock(instanceId, entityToken); } } public void AcquireLock(Guid instanceId, EntityToken entityToken) { Verify.That(!ActionLockingFacade.IsLocked(entityToken), "The entityToken is already locked"); ActionLockingFacade.AcquireLock(entityToken, instanceId); } private void ReleaseAllLocks(Guid instanceId) { ActionLockingFacade.ReleaseAllLocks(instanceId); } private bool HasEntityTokenLockAttribute(Type workflowType) { return _hasEntityTokenLockAttributeCache.GetOrAdd(workflowType, type => type.GetCustomAttributesRecursively().Any()); } #endregion #region FlowControllerServices methods public void SetFlowControllerServicesContainer(Guid instanceId, FlowControllerServicesContainer flowControllerServicesContainer) { DoInitialize(0); using (_resourceLocker.Locker) { _resourceLocker.Resources.FlowControllerServicesContainers[instanceId] = flowControllerServicesContainer; } } public FlowControllerServicesContainer GetFlowControllerServicesContainer(Guid instanceId) { DoInitialize(0); FlowControllerServicesContainer flowControllerServicesContainer; using (_resourceLocker.Locker) { _resourceLocker.Resources.FlowControllerServicesContainers.TryGetValue(instanceId, out flowControllerServicesContainer); } return flowControllerServicesContainer; } public void RemoveFlowControllerServicesContainer(Guid instanceId) { DoInitialize(0); using (_resourceLocker.Locker) { _resourceLocker.Resources.FlowControllerServicesContainers.Remove(instanceId); } } #endregion #region Workflow status methods public bool WorkflowExists(Guid instanceId) { DoInitialize(0); using (_resourceLocker.Locker) { return _resourceLocker.Resources.WorkflowStatusDictionary.ContainsKey(instanceId); } } public Semaphore WaitForIdleStatus(Guid instanceId) { DoInitialize(0); using (_resourceLocker.Locker) { WorkflowInstanceStatus workflowInstanceStatus; if (!_resourceLocker.Resources.WorkflowStatusDictionary.TryGetValue(instanceId, out workflowInstanceStatus)) { throw new InvalidOperationException($"The workflow with the id '{instanceId}' is unknown"); } if (workflowInstanceStatus == WorkflowInstanceStatus.Idle) { return null; } _resourceLocker.Resources.WorkflowIdleWaitSemaphores.Remove(instanceId); Semaphore semaphore = new Semaphore(0, 1); _resourceLocker.Resources.WorkflowIdleWaitSemaphores.Add(instanceId, semaphore); return semaphore; } } private void SetWorkflowInstanceStatus(Guid instanceId, WorkflowInstanceStatus workflowInstanceStatus, bool newlyCreateOrLoaded) { using (_resourceLocker.Locker) { var resources = _resourceLocker.Resources; Action releaseIdleWaitSemaphore = () => { if (resources.WorkflowIdleWaitSemaphores.TryGetValue(instanceId, out var semaphore)) { semaphore.Release(); resources.WorkflowIdleWaitSemaphores.Remove(instanceId); } }; switch (workflowInstanceStatus) { case WorkflowInstanceStatus.Idle: releaseIdleWaitSemaphore(); resources.WorkflowStatusDictionary[instanceId] = WorkflowInstanceStatus.Idle; PersistFormData(instanceId); break; case WorkflowInstanceStatus.Running: resources.WorkflowStatusDictionary[instanceId] = WorkflowInstanceStatus.Running; break; case WorkflowInstanceStatus.Terminated: releaseIdleWaitSemaphore(); resources.WorkflowStatusDictionary.Remove(instanceId); break; default: throw new InvalidOperationException("This line should not be reachable."); } } string identity = UserValidationFacade.IsLoggedIn() ? UserValidationFacade.GetUsername() : "(system process)"; Log.LogVerbose(LogTitle, $"Workflow instance status changed to {workflowInstanceStatus}. Id = {instanceId}, User = {identity}"); } #endregion #region Form workflow methods public void SetEventHandlerFilter(Guid instanceId, Type eventHandlerFilterType) { DoInitialize(0); if (eventHandlerFilterType != null) { Verify.That(typeof(IEventHandleFilter).IsAssignableFrom(eventHandlerFilterType), "The argument eventHandlerFilterType does dot implement the interface '{0}'", typeof(IEventHandleFilter)); FormData formData = GetFormData(instanceId); if (formData != null) { formData.EventHandleFilterType = eventHandlerFilterType; } } } public IEventHandleFilter GetEventHandleFilter(Guid instanceId) { DoInitialize(0); FormData formData = GetFormData(instanceId); if (formData == null || formData.EventHandleFilterType == null) return null; IEventHandleFilter eventHandleFilter; using (_resourceLocker.Locker) { if (!_resourceLocker.Resources.EventHandleFilters.TryGetValue(formData.EventHandleFilterType, out eventHandleFilter)) { eventHandleFilter = (IEventHandleFilter)Activator.CreateInstance(formData.EventHandleFilterType); _resourceLocker.Resources.EventHandleFilters.Add(formData.EventHandleFilterType, eventHandleFilter); } } return eventHandleFilter; } public IEnumerable GetCurrentFormEvents(Guid instanceId) { DoInitialize(0); IEnumerable eventNames = new StateMachineWorkflowInstance(WorkflowFacade.WorkflowRuntime, instanceId).GetCurrentEventNames(typeof(IFormsWorkflowEventService)); return eventNames; } public IEnumerable GetCurrentFormEvents(WorkflowInstance workflowInstance) { DoInitialize(0); return GetCurrentFormEvents(workflowInstance.InstanceId); } public void FireSaveEvent(Guid instanceId, Dictionary bindings) { DoInitialize(0); using (_resourceLocker.Locker) { if (_resourceLocker.Resources.WorkflowStatusDictionary.ContainsKey(instanceId)) { _formsWorkflowEventService.FireSaveEvent(new FormEventArgs(instanceId, bindings)); } } } public void FireSaveAndPublishEvent(Guid instanceId, Dictionary bindings) { DoInitialize(0); using (_resourceLocker.Locker) { if (_resourceLocker.Resources.WorkflowStatusDictionary.ContainsKey(instanceId)) { _formsWorkflowEventService.FireSaveAndPublishEvent(new FormEventArgs(instanceId, bindings)); } } } public void FireNextEvent(Guid instanceId, Dictionary bindings) { DoInitialize(0); using (_resourceLocker.Locker) { if (_resourceLocker.Resources.WorkflowStatusDictionary.ContainsKey(instanceId)) { _formsWorkflowEventService.FireNextEvent(new FormEventArgs(instanceId, bindings)); } } } public void FirePreviousEvent(Guid instanceId, Dictionary bindings) { DoInitialize(0); using (_resourceLocker.Locker) { if (_resourceLocker.Resources.WorkflowStatusDictionary.ContainsKey(instanceId)) { _formsWorkflowEventService.FirePreviousEvent(new FormEventArgs(instanceId, bindings)); } } } public void FireFinishEvent(Guid instanceId, Dictionary bindings) { DoInitialize(0); using (_resourceLocker.Locker) { if (_resourceLocker.Resources.WorkflowStatusDictionary.ContainsKey(instanceId)) { _formsWorkflowEventService.FireFinishEvent(new FormEventArgs(instanceId, bindings)); } } } public void FireCancelEvent(Guid instanceId, Dictionary bindings) { DoInitialize(0); using (_resourceLocker.Locker) { if (_resourceLocker.Resources.WorkflowStatusDictionary.ContainsKey(instanceId)) { _formsWorkflowEventService.FireCancelEvent(new FormEventArgs(instanceId, bindings)); } } } public void FirePreviewEvent(Guid instanceId, Dictionary bindings) { DoInitialize(0); using (_resourceLocker.Locker) { if (_resourceLocker.Resources.WorkflowStatusDictionary.ContainsKey(instanceId)) { _formsWorkflowEventService.FirePreviewEvent(new FormEventArgs(instanceId, bindings)); } } } public void FireCustomEvent(int customEventNumber, Guid instanceId, Dictionary bindings) { DoInitialize(0); if (customEventNumber < 1 || customEventNumber > 5) throw new ArgumentException("Number must be between 1 and 5", nameof(customEventNumber)); using (_resourceLocker.Locker) { if (_resourceLocker.Resources.WorkflowStatusDictionary.ContainsKey(instanceId)) { switch (customEventNumber) { case 01: _formsWorkflowEventService.FireCustomEvent01(new FormEventArgs(instanceId, bindings)); break; case 02: _formsWorkflowEventService.FireCustomEvent02(new FormEventArgs(instanceId, bindings)); break; case 03: _formsWorkflowEventService.FireCustomEvent03(new FormEventArgs(instanceId, bindings)); break; case 04: _formsWorkflowEventService.FireCustomEvent04(new FormEventArgs(instanceId, bindings)); break; case 05: _formsWorkflowEventService.FireCustomEvent05(new FormEventArgs(instanceId, bindings)); break; } } } } public void FireChildWorkflowDoneEvent(Guid parentInstanceId, string workflowResult) { DoInitialize(0); using (_resourceLocker.Locker) { if (_resourceLocker.Resources.WorkflowStatusDictionary.ContainsKey(parentInstanceId)) { _formsWorkflowEventService.FireChildWorkflowDoneEvent(new FormEventArgs(parentInstanceId, workflowResult)); } } } #endregion #region FormData methods public void AddFormData(Guid instanceId, FormData formData) { if (!_resourceLocker.Resources.FormData.TryAdd(instanceId, formData)) { throw new ArgumentException($"Form data for instance ID '{instanceId}' has already been added"); } } public bool TryGetFormData(Guid instanceId, out FormData formData) { return _resourceLocker.Resources.FormData.TryGetValue(instanceId, out formData); } public FormData GetFormData(Guid instanceId, bool allowCreationIfNotExisting = false) { var allFormData = _resourceLocker.Resources.FormData; if (allowCreationIfNotExisting) { return allFormData.GetOrAdd(instanceId, key => new FormData()); } return allFormData.TryGetValue(instanceId, out var formData) ? formData : null; } private void RemoveIfExistFormData(Guid instanceId) { _resourceLocker.Resources.FormData.TryRemove(instanceId, out _); } #endregion public void Flush() { _workflowRuntime = null; _externalDataExchangeService = null; _manualWorkflowSchedulerService = null; _fileWorkflowPersistenceService = null; _formsWorkflowEventService = null; _resourceLocker.ResetInitialization(); } public void ShutDown() { _isShutDown = true; Log.LogVerbose(LogTitleColored, "----------========== Finalizing Workflows ==========----------"); int startTime = Environment.TickCount; while (_workflowRuntime == null && Environment.TickCount - startTime < 5000) Thread.Sleep(10); if (_workflowRuntime != null) { // system shut down - close all console bound resources using (_resourceLocker.Locker) { using (GlobalInitializerFacade.CoreIsInitializedScope) { PersistFormData(); UnloadWorkflowsSilent(); RemoveNotPersistableWorkflowsState(); } } } _workflowRuntime = null; int endTime = Environment.TickCount; Log.LogVerbose(LogTitleColored, "----------========== Done finalizing Workflows ({0} ms ) ==========----------", endTime - startTime); } public void ConsoleClosed(ConsoleClosedEventArgs args) { DoInitialize(0); using (_resourceLocker.Locker) { List workflowsToCancel = (from kp in _resourceLocker.Resources.FlowControllerServicesContainers where ConsoleIdEquals(kp.Value, args.ConsoleId) select kp.Key).ToList(); foreach (Guid instanceId in workflowsToCancel) { try { AbortWorkflow(instanceId); } catch(Exception ex) { Log.LogError(LogTitle, "Error aborting workflow " + instanceId); Log.LogError(LogTitle, ex); } } } } private void DoInitialize(int delayedTime) { if (_workflowRuntime != null) return; using (GlobalInitializerFacade.CoreNotLockedScope) using (_resourceLocker.Locker) { if (_workflowRuntime != null) return; Log.LogVerbose(LogTitleColored, "----------========== Initializing Workflows (Delayed: {0}) ==========----------", delayedTime); int startTime = Environment.TickCount; _resourceLocker.ResetInitialization(); _workflowRuntime = InitializeWorkflowRuntime(); InitializeFormsWorkflowRuntime(); if (!_workflowRuntime.IsStarted) { _workflowRuntime.StartRuntime(); } DeleteOldWorkflows(); _fileWorkflowPersistenceService.ListenToDynamicallyAddedWorkflows(OnNewWorkflowFileAdded); LoadPersistedWorkflows(); LoadPersistedFormData(); int endTime = Environment.TickCount; Log.LogVerbose(LogTitleColored, "----------========== Done initializing Workflows ({0} ms ) ==========----------", endTime - startTime); foreach (Action action in _actionToRunWhenInitialized) { action(); } } } private WorkflowRuntime InitializeWorkflowRuntime() { WorkflowRuntime workflowRuntime; if (WorkflowRuntimeProviderPluginFacade.HasConfiguration) { string providerName = WorkflowRuntimeProviderRegistry.DefaultWorkflowRuntimeProviderName; workflowRuntime = WorkflowRuntimeProviderPluginFacade.GetWorkflowRuntime(providerName); } else { Log.LogVerbose(LogTitle, "Using default workflow runtime"); workflowRuntime = new WorkflowRuntime(); } _manualWorkflowSchedulerService = new ManualWorkflowSchedulerService(true); workflowRuntime.AddService(_manualWorkflowSchedulerService); _fileWorkflowPersistenceService = new FileWorkflowPersistenceService(SerializedWorkflowsDirectory); workflowRuntime.AddService(_fileWorkflowPersistenceService); _externalDataExchangeService = new ExternalDataExchangeService(); workflowRuntime.AddService(_externalDataExchangeService); AddWorkflowLoggingEvents(workflowRuntime); workflowRuntime.WorkflowCompleted += (sender, args) => { using (ThreadDataManager.EnsureInitialize()) { OnWorkflowInstanceTerminatedCleanup(args.WorkflowInstance.InstanceId); } }; workflowRuntime.WorkflowAborted += (sender, args) => { using (ThreadDataManager.EnsureInitialize()) { OnWorkflowInstanceTerminatedCleanup(args.WorkflowInstance.InstanceId); } }; workflowRuntime.WorkflowTerminated += (sender, args) => { using (ThreadDataManager.EnsureInitialize()) { OnWorkflowInstanceTerminatedCleanup(args.WorkflowInstance.InstanceId); } _resourceLocker.Resources.ExceptionFromWorkflow[Thread.CurrentThread.ManagedThreadId] = args.Exception; }; workflowRuntime.WorkflowCreated += (sender, args) => SetWorkflowInstanceStatus(args.WorkflowInstance.InstanceId, WorkflowInstanceStatus.Idle, true); workflowRuntime.WorkflowIdled += (sender, args) => SetWorkflowInstanceStatus(args.WorkflowInstance.InstanceId, WorkflowInstanceStatus.Idle, false); workflowRuntime.WorkflowLoaded += (sender, args) => SetWorkflowInstanceStatus(args.WorkflowInstance.InstanceId, WorkflowInstanceStatus.Idle, true); return workflowRuntime; } private void OnWorkflowInstanceTerminatedCleanup(Guid instanceId) { AbortedWorkflows.Remove(instanceId); WorkflowFlowToken flowToken = new WorkflowFlowToken(instanceId); TaskManagerFacade.CompleteTasks(flowToken); ReleaseAllLocks(instanceId); SetWorkflowInstanceStatus(instanceId, WorkflowInstanceStatus.Terminated, false); RemoveFlowControllerServicesContainer(instanceId); RemoveIfExistFormData(instanceId); RemovePersistingType(instanceId); DeletePersistedWorkflow(instanceId); DeletePersistedFormData(instanceId); using (ThreadDataManager.EnsureInitialize()) { FlowControllerFacade.FlowComplete(new WorkflowFlowToken(instanceId)); } } private void InitializeFormsWorkflowRuntime() { _formsWorkflowEventService = new FormsWorkflowEventService(); _externalDataExchangeService.AddService(_formsWorkflowEventService); IFormsWorkflowActivityService formsWorkflowActivityService = new FormsWorkflowActivityService(); _externalDataExchangeService.AddService(formsWorkflowActivityService); } [DebuggerHidden] private void LogWorkflowChange(string change, WorkflowEventArgs args, bool logUserName, bool workflowDefinitionAvailable, bool error) { WorkflowInstance instance = null; string activityTypeName = null; try { instance = args.WorkflowInstance; } catch { // Silent } if (workflowDefinitionAvailable && instance != null) { try { activityTypeName = instance.GetWorkflowDefinition().GetType().FullName; } catch { // Silent } } var message = new StringBuilder("Workflow ").Append(change); if (activityTypeName != null) { message.Append(", Activity = " + activityTypeName); } if (instance != null) { message.Append(", Id = " + instance.InstanceId); } if (logUserName) { string identity = UserValidationFacade.IsLoggedIn() ? UserValidationFacade.GetUsername() : "(system process)"; message.Append(", User = " + identity); } if (!error) { Log.LogVerbose(LogTitle, message.ToString()); } else { Log.LogError(LogTitle, message.ToString()); } } private void AddWorkflowLoggingEvents(WorkflowRuntime workflowRuntime) { workflowRuntime.WorkflowCreated += (sender, args) => LogWorkflowChange("created", args, true, true, false); workflowRuntime.WorkflowLoaded += (sender, args) => LogWorkflowChange("loaded", args, true, true, false); workflowRuntime.WorkflowPersisted += (sender, args) => LogWorkflowChange("persisted", args, false, false, false); workflowRuntime.WorkflowAborted += (sender, args) => LogWorkflowChange("aborted", args, false, false, true); workflowRuntime.WorkflowTerminated += (sender, args) => { Log.LogError(LogTitle, "Workflow terminated - Id = {0}, Exception:", args.WorkflowInstance.InstanceId); Log.LogError(LogTitle, args.Exception); }; } private void LoadPersistedWorkflows() { foreach (Guid instanceId in _fileWorkflowPersistenceService.GetPersistedWorkflows()) { LoadPersistedWorkflow(instanceId); } } private void LoadPersistedWorkflow(Guid instanceId) { WorkflowInstanceStatus status; if (!_resourceLocker.Resources.WorkflowStatusDictionary.TryGetValue(instanceId, out status) || status != WorkflowInstanceStatus.Running) { // This will make the runtime load the persisted workflow WorkflowInstance workflowInstance = null; try { workflowInstance = WorkflowRuntime.GetWorkflow(instanceId); } catch (InvalidOperationException) { _fileWorkflowPersistenceService.RemovePersistedWorkflow(instanceId); } if (workflowInstance != null && !_resourceLocker.Resources.WorkflowPersistingTypeDictionary.ContainsKey(instanceId)) { Type workflowType = workflowInstance.GetWorkflowDefinition().GetType(); SetWorkflowPersistingType(workflowType, instanceId); } } } private void LoadPersistedFormData() { using (_resourceLocker.Locker) { foreach (string filename in C1Directory.GetFiles(SerializedWorkflowsDirectory, "*.xml")) { TryLoadPersistedFormData(filename); } } } private void TryLoadPersistedFormData(string filename) { string guidString = Path.GetFileNameWithoutExtension(filename); Guid id; if (!Guid.TryParse(guidString ?? "", out id)) return; try { var doc = XDocumentUtils.Load(filename); var formData = FormData.Deserialize(doc.Root); if (!_resourceLocker.Resources.FormData.ContainsKey(id)) { _resourceLocker.Resources.FormData.TryAdd(id, formData); FormsWorkflowBindingCache.Bindings.TryAdd(id, formData.Bindings); } } catch (DataSerilizationException ex) { Log.LogWarning(LogTitle, $"The workflow {id} contained one or more bindings where data was deleted or data type changed"); Log.LogWarning(LogTitle, ex); //AbortWorkflow(id); } catch (Exception ex) { Log.LogCritical(LogTitle, $"Could not deserialize form data for the workflow {id}"); Log.LogCritical(LogTitle, ex); AbortWorkflow(id); } } private void OnNewWorkflowFileAdded(Guid instanceId) { Thread.Sleep(100); if (HostingEnvironment.ApplicationHost.ShutdownInitiated()) return; Log.LogInformation(LogTitle, "New workflow detected: " + instanceId); using (ThreadDataManager.EnsureInitialize()) { LoadPersistedWorkflow(instanceId); string formDataFilename = GetFormDataFileName(instanceId); if (C1File.Exists(formDataFilename)) { TryLoadPersistedFormData(formDataFilename); } } } private void RemoveNotPersistableWorkflowsState() { using (_resourceLocker.Locker) { IEnumerable instanceIds = from kvp in _resourceLocker.Resources.WorkflowPersistingTypeDictionary where kvp.Value == WorkflowPersistingType.Never select kvp.Key; foreach (Guid instanceId in instanceIds) { _fileWorkflowPersistenceService.RemovePersistedWorkflow(instanceId); } } } private void UnloadWorkflowsSilent() { _fileWorkflowPersistenceService.PersistAll = true; var abortedWorkflows = new HashSet(_fileWorkflowPersistenceService.GetAbortedWorkflows()); foreach (Guid instanceId in _resourceLocker.Resources.WorkflowStatusDictionary.Keys.ToList()) { if (abortedWorkflows.Contains(instanceId)) { continue; } UnloadSilent(instanceId); } _fileWorkflowPersistenceService.PersistAll = false; } [DebuggerHidden] private void UnloadSilent(Guid instanceId) { try { WorkflowInstance workflowInstance = WorkflowRuntime.GetWorkflow(instanceId); workflowInstance.Unload(); } catch (Exception) { // Ignore, the workflow is already dead } } static readonly HashSet AbortedWorkflows = new HashSet(); private void PersistFormData(Guid instanceId) { var resources = _resourceLocker.Resources; bool shouldPersist = resources.WorkflowPersistingTypeDictionary.TryGetValue(instanceId, out var persistanceType) && persistanceType != WorkflowPersistingType.Never; if (!shouldPersist || !resources.FormData.TryGetValue(instanceId, out FormData formData) || formData == null) { return; } PersistFormData(instanceId, formData); } private void PersistFormData() { var resources = _resourceLocker.Resources; List instanceIds = (from kvp in resources.WorkflowPersistingTypeDictionary where kvp.Value != WorkflowPersistingType.Never select kvp.Key).ToList(); // Copying collection since it may be modified why execution of forech-statement var formDataSetToBePersisted = resources.FormData.Where(f => instanceIds.Contains(f.Key)).ToList(); foreach (var kvp in formDataSetToBePersisted) { PersistFormData(kvp.Key, kvp.Value); } } private void PersistFormData(Guid instanceId, FormData formData) { try { XElement element = formData.Serialize(); string filename = GetFormDataFileName(instanceId); XDocument doc = new XDocument(element); doc.SaveToFile(filename); Log.LogVerbose(LogTitle, "FormData persisted for workflow id = " + instanceId); } catch (Exception ex) { // Stop trying serializing this workflow AbortWorkflow(instanceId); Log.LogCritical(LogTitle, ex); } } private void DeletePersistedWorkflow(Guid instanceId) { using (GlobalInitializerFacade.CoreIsInitializedScope) { _fileWorkflowPersistenceService.RemovePersistedWorkflow(instanceId); } } private void DeletePersistedFormData(Guid instanceId) { using (GlobalInitializerFacade.CoreIsInitializedScope) { string filename = GetFormDataFileName(instanceId); if (C1File.Exists(filename)) { C1File.Delete(filename); Log.LogVerbose(LogTitle, $"Persisted FormData deleted for workflow id = {instanceId}"); } } } private string GetFormDataFileName(Guid instanceId) { return Path.Combine(SerializedWorkflowsDirectory, $"{instanceId}.xml"); } private void DeleteOldWorkflows() { using (GlobalInitializerFacade.CoreIsInitializedScope) { foreach (string filename in C1Directory.GetFiles(SerializedWorkflowsDirectory)) { DateTime creationTime = C1File.GetLastWriteTime(filename); if (DateTime.Now.Subtract(creationTime) > OldFileExistenceTimeout) { Guid instanceId = new Guid(Path.GetFileNameWithoutExtension(filename)); if (Path.GetExtension(filename) == "bin") { try { WorkflowRuntime.GetWorkflow(instanceId); AbortWorkflow(instanceId); } catch (Exception) { } } C1File.Delete(filename); Log.LogVerbose(LogTitle, $"Old workflow instance file deleted {filename}"); } } } } private static string SerializedWorkflowsDirectory { get { string directory = PathUtil.Resolve(GlobalSettingsFacade.SerializedWorkflowsDirectory); if (!C1Directory.Exists(directory)) { C1Directory.CreateDirectory(directory); } return directory; } } private static bool ConsoleIdEquals(FlowControllerServicesContainer flowControllerServicesContainer, string consoleId) { var managementConsoleMessageService = flowControllerServicesContainer?.GetService(); if (managementConsoleMessageService == null) return false; return managementConsoleMessageService.CurrentConsoleId == consoleId; } private enum WorkflowInstanceStatus { Idle = 0, Running = 1, Terminated = 2 } private sealed class Resources { public Resources() { this.WorkflowStatusDictionary = new Dictionary(); this.FormData = new ConcurrentDictionary(); this.FlowControllerServicesContainers = new Dictionary(); this.WorkflowPersistingTypeDictionary = new Dictionary(); this.EventHandleFilters = new Dictionary(); } public Dictionary WorkflowStatusDictionary { get; } public ConcurrentDictionary FormData { get; } public Dictionary FlowControllerServicesContainers { get; } public Dictionary WorkflowPersistingTypeDictionary { get; } public Dictionary WorkflowIdleWaitSemaphores { get; private set; } public ConcurrentDictionary ExceptionFromWorkflow { get; private set; } public Dictionary EventHandleFilters { get; } public static void InitializeResources(Resources resources) { IEnumerable instanceIds = (from kvp in resources.WorkflowPersistingTypeDictionary where kvp.Value == WorkflowPersistingType.Never select kvp.Key).ToList(); foreach (Guid instanceId in instanceIds) { resources.WorkflowStatusDictionary.Remove(instanceId); resources.FormData.TryRemove(instanceId, out _); resources.FlowControllerServicesContainers.Remove(instanceId); resources.WorkflowPersistingTypeDictionary.Remove(instanceId); } resources.WorkflowIdleWaitSemaphores = new Dictionary(); resources.ExceptionFromWorkflow = new ConcurrentDictionary(); } } } } ================================================ FILE: Composite/C1Console/Workflow/WorkflowFlowController.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Xml; using System.Xml.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Forms.Flows; using Composite.C1Console.Tasks; using Composite.C1Console.Workflow.Foundation; using Composite.Core; namespace Composite.C1Console.Workflow { internal sealed class WorkflowFlowController : IFlowController { private static readonly string LogTitle = nameof (WorkflowFlowController); public FlowControllerServicesContainer ServicesContainer { set; private get; } public IFlowUiDefinition GetCurrentUiDefinition(FlowToken flowToken) { WorkflowFlowToken workflowFlowToken = (WorkflowFlowToken)flowToken; if (!WorkflowFacade.WorkflowExists(workflowFlowToken.WorkflowInstanceId)) { Log.LogVerbose(LogTitle, "The workflow with Id = {0} does not exists", workflowFlowToken.WorkflowInstanceId); return null; } using (GlobalInitializerFacade.CoreNotLockedScope) { Semaphore semaphore = WorkflowFacade.WaitForIdleStatus(workflowFlowToken.WorkflowInstanceId); if (semaphore != null) { Log.LogVerbose(LogTitle, "The workflow with Id = {0} is running, waiting until its done.", workflowFlowToken.WorkflowInstanceId); semaphore.WaitOne(TimeSpan.FromSeconds(10), true); Log.LogVerbose(LogTitle, "Done waiting on the workflow with Id = {0}.", workflowFlowToken.WorkflowInstanceId); } } FormData formFunction = WorkflowFacade.GetFormData(workflowFlowToken.WorkflowInstanceId); if (formFunction == null) { return null; } FormFlowUiDefinition formFlowUiDefinition; if (formFunction.FormDefinition != null) { formFlowUiDefinition = new FormFlowUiDefinition( ToXmlReader(formFunction.FormDefinition), formFunction.ContainerType, formFunction.ContainerLabel, formFunction.Bindings, formFunction.BindingsValidationRules ); } else if (formFunction.FormMarkupProvider != null) { formFlowUiDefinition = new FormFlowUiDefinition( formFunction.FormMarkupProvider, formFunction.ContainerType, formFunction.ContainerLabel, formFunction.Bindings, formFunction.BindingsValidationRules ); } else { throw new NotImplementedException(); } var markup = GetCustomToolbarMarkup(formFunction); if (markup != null) { formFlowUiDefinition.SetCustomToolbarMarkupProvider(markup); } AddEventHandles(formFlowUiDefinition, workflowFlowToken.WorkflowInstanceId); return formFlowUiDefinition; } private XmlReader GetCustomToolbarMarkup(FormData formData) { if (formData.CustomToolbarItems == null || formData.CustomToolbarItems.Count == 0) { return null; } var parts = formData.CustomToolbarItems .OrderBy(t => t.Item3) .Select(t => t.Item2) .ToList(); if (parts.Count == 1) return ToXmlReader(parts[0]); var templateDocument = XDocument.Parse(@" "); XElement bindings = GetBindingsElement(templateDocument); XElement layout = GetLayoutOrPlaceholderElement(templateDocument); foreach (var part in parts) { bindings.Add(GetBindingsElement(part).Elements()); layout.Add(GetLayoutOrPlaceholderElement(part).Elements()); } return ToXmlReader(templateDocument); } private XElement GetBindingsElement(XDocument templateDocument) { return templateDocument.Descendants().FirstOrDefault(d => d.Name.LocalName == "bindings"); } private XElement GetLayoutOrPlaceholderElement(XDocument doc) { var layoutElement = doc.Descendants().FirstOrDefault(d => d.Name.LocalName == "layout"); Verify.IsNotNull(layoutElement, "Failed to find 'layout' element"); var firstElement = layoutElement.Elements().FirstOrDefault(); if (firstElement != null && firstElement.Name.LocalName == "PlaceHolder") { return firstElement; } return layoutElement; } private XmlReader ToXmlReader(XDocument document) => ToXmlReader(document.ToString()); private XmlReader ToXmlReader(string str) => new XmlTextReader(new StringReader(str)); public void CancelFlow(FlowToken flowToken) { OnCancel(flowToken, null, null); } private static void AddEventHandles(FormFlowUiDefinition formFlowUiDefinition, Guid instanceId) { IEnumerable eventNames = WorkflowFacade.GetCurrentFormEvents(instanceId); FormData formData = WorkflowFacade.GetFormData(instanceId); foreach (string eventName in eventNames) { if (formData?.ExcludedEvents != null && formData.ExcludedEvents.Contains(eventName)) continue; switch (eventName) { case "Save": formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.Save, OnSave); break; case "SaveAndPublish": formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.SaveAndPublish, OnSaveAndPublish); break; case "Next": formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.Next, OnNext); break; case "Previous": formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.Previous, OnPrevious); break; case "Finish": formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.Finish, OnFinish); break; case "Cancel": formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.Cancel, OnCancel); break; case "Preview": formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.Preview, OnPreview); break; case "CustomEvent01": formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.CustomEvent01, OnCustomEvent01); break; case "CustomEvent02": formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.CustomEvent02, OnCustomEvent02); break; case "CustomEvent03": formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.CustomEvent03, OnCustomEvent03); break; case "CustomEvent04": formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.CustomEvent04, OnCustomEvent04); break; case "CustomEvent05": formFlowUiDefinition.EventHandlers.Add(StandardEventIdentifiers.CustomEvent05, OnCustomEvent05); break; } } IEventHandleFilter eventHandlerFilter = WorkflowFacade.GetEventHandleFilter(instanceId); eventHandlerFilter?.Filter(formFlowUiDefinition.EventHandlers); } private static void OnSave(FlowToken flowToken, Dictionary bindings, FlowControllerServicesContainer serviceContainer) { WorkflowFlowToken workflowFlowToken = (WorkflowFlowToken)flowToken; using (TaskContainer taskContainer = TaskManagerFacade.RuntTasks(flowToken, new WorkflowTaskManagerEvent(flowToken, workflowFlowToken.WorkflowInstanceId) { EventName = "Save" })) { TaskManagerFlowControllerService taskManagerFlowControllerService = new TaskManagerFlowControllerService(taskContainer); serviceContainer.AddService(taskManagerFlowControllerService); WorkflowFacade.FireSaveEvent(workflowFlowToken.WorkflowInstanceId, bindings); WorkflowFacade.SetFlowControllerServicesContainer(workflowFlowToken.WorkflowInstanceId, serviceContainer); WorkflowFacade.RunWorkflow(workflowFlowToken.WorkflowInstanceId); taskContainer.SetOnIdleTaskManagerEvent(new WorkflowTaskManagerEvent(flowToken, workflowFlowToken.WorkflowInstanceId)); serviceContainer.RemoveService(taskManagerFlowControllerService); } } private static void OnSaveAndPublish(FlowToken flowToken, Dictionary bindings, FlowControllerServicesContainer serviceContainer) { WorkflowFlowToken workflowFlowToken = (WorkflowFlowToken)flowToken; using (TaskContainer taskContainer = TaskManagerFacade.RuntTasks(flowToken, new WorkflowTaskManagerEvent(flowToken, workflowFlowToken.WorkflowInstanceId) { EventName = "Save" })) { TaskManagerFlowControllerService taskManagerFlowControllerService = new TaskManagerFlowControllerService(taskContainer); serviceContainer.AddService(taskManagerFlowControllerService); WorkflowFacade.FireSaveAndPublishEvent(workflowFlowToken.WorkflowInstanceId, bindings); WorkflowFacade.SetFlowControllerServicesContainer(workflowFlowToken.WorkflowInstanceId, serviceContainer); WorkflowFacade.RunWorkflow(workflowFlowToken.WorkflowInstanceId); taskContainer.SetOnIdleTaskManagerEvent(new WorkflowTaskManagerEvent(flowToken, workflowFlowToken.WorkflowInstanceId)); serviceContainer.RemoveService(taskManagerFlowControllerService); } } private static void OnNext(FlowToken flowToken, Dictionary bindings, FlowControllerServicesContainer serviceContainer) { WorkflowFlowToken workflowFlowToken = (WorkflowFlowToken)flowToken; using (TaskContainer taskContainer = TaskManagerFacade.RuntTasks(flowToken, new WorkflowTaskManagerEvent(flowToken, workflowFlowToken.WorkflowInstanceId) { EventName = "Next" })) { WorkflowFacade.FireNextEvent(workflowFlowToken.WorkflowInstanceId, bindings); WorkflowFacade.SetFlowControllerServicesContainer(workflowFlowToken.WorkflowInstanceId, serviceContainer); WorkflowFacade.RunWorkflow(workflowFlowToken.WorkflowInstanceId); taskContainer.SetOnIdleTaskManagerEvent(new WorkflowTaskManagerEvent(flowToken, workflowFlowToken.WorkflowInstanceId)); } IFormFlowRenderingService formServices = serviceContainer.GetService(); if (!formServices.HasFieldMessages) { serviceContainer.GetService().RerenderView(); } } private static void OnPrevious(FlowToken flowToken, Dictionary bindings, FlowControllerServicesContainer serviceContainer) { WorkflowFlowToken workflowFlowToken = (WorkflowFlowToken)flowToken; using (TaskContainer taskContainer = TaskManagerFacade.RuntTasks(flowToken, new WorkflowTaskManagerEvent(flowToken, workflowFlowToken.WorkflowInstanceId) { EventName = "Previous" })) { WorkflowFacade.FirePreviousEvent(workflowFlowToken.WorkflowInstanceId, bindings); WorkflowFacade.SetFlowControllerServicesContainer(workflowFlowToken.WorkflowInstanceId, serviceContainer); WorkflowFacade.RunWorkflow(workflowFlowToken.WorkflowInstanceId); taskContainer.SetOnIdleTaskManagerEvent(new WorkflowTaskManagerEvent(flowToken, workflowFlowToken.WorkflowInstanceId)); } serviceContainer.GetService().RerenderView(); } private static void OnFinish(FlowToken flowToken, Dictionary bindings, FlowControllerServicesContainer serviceContainer) { WorkflowFlowToken workflowFlowToken = (WorkflowFlowToken)flowToken; using (TaskContainer taskContainer = TaskManagerFacade.RuntTasks(flowToken, new WorkflowTaskManagerEvent(flowToken, workflowFlowToken.WorkflowInstanceId) { EventName = "Finish" })) { TaskManagerFlowControllerService taskManagerFlowControllerService = new TaskManagerFlowControllerService(taskContainer); serviceContainer.AddService(taskManagerFlowControllerService); WorkflowFacade.FireFinishEvent(workflowFlowToken.WorkflowInstanceId, bindings); WorkflowFacade.SetFlowControllerServicesContainer(workflowFlowToken.WorkflowInstanceId, serviceContainer); WorkflowFacade.RunWorkflow(workflowFlowToken.WorkflowInstanceId); taskContainer.SetOnIdleTaskManagerEvent(new WorkflowTaskManagerEvent(flowToken, workflowFlowToken.WorkflowInstanceId)); } IFormFlowRenderingService formServices = serviceContainer.GetService(); if (!formServices.HasFieldMessages) { serviceContainer.GetService().RerenderView(); } } private static void OnCancel(FlowToken flowToken, Dictionary bindings, FlowControllerServicesContainer serviceContainer) { WorkflowFlowToken workflowFlowToken = (WorkflowFlowToken)flowToken; if (WorkflowFacade.WorkflowExists(workflowFlowToken.WorkflowInstanceId)) { using (TaskManagerFacade.RuntTasks(flowToken, new WorkflowTaskManagerEvent(flowToken, workflowFlowToken.WorkflowInstanceId) { EventName = "Cancel" })) { WorkflowFacade.FireCancelEvent(workflowFlowToken.WorkflowInstanceId, bindings); WorkflowFacade.SetFlowControllerServicesContainer(workflowFlowToken.WorkflowInstanceId, serviceContainer); WorkflowFacade.RunWorkflow(workflowFlowToken.WorkflowInstanceId); } } else { Log.LogVerbose(LogTitle, "Cancel event suppressed because the workflow was terminated ({0})", workflowFlowToken.WorkflowInstanceId); } serviceContainer?.GetService().RerenderView(); } private static void OnPreview(FlowToken flowToken, Dictionary bindings, FlowControllerServicesContainer serviceContainer) { WorkflowFlowToken workflowFlowToken = (WorkflowFlowToken)flowToken; using (TaskContainer taskContainer = TaskManagerFacade.RuntTasks(flowToken, new WorkflowTaskManagerEvent(flowToken, workflowFlowToken.WorkflowInstanceId) { EventName = "Preview" })) { WorkflowFacade.FirePreviewEvent(workflowFlowToken.WorkflowInstanceId, bindings); WorkflowFacade.SetFlowControllerServicesContainer(workflowFlowToken.WorkflowInstanceId, serviceContainer); WorkflowFacade.RunWorkflow(workflowFlowToken.WorkflowInstanceId); taskContainer.SetOnIdleTaskManagerEvent(new WorkflowTaskManagerEvent(flowToken, workflowFlowToken.WorkflowInstanceId)); } } private static void OnCustomEvent01(FlowToken flowToken, Dictionary bindings, FlowControllerServicesContainer serviceContainer) { OnCustomEvent(1, flowToken, bindings, serviceContainer); } private static void OnCustomEvent02(FlowToken flowToken, Dictionary bindings, FlowControllerServicesContainer serviceContainer) { OnCustomEvent(2, flowToken, bindings, serviceContainer); } private static void OnCustomEvent03(FlowToken flowToken, Dictionary bindings, FlowControllerServicesContainer serviceContainer) { OnCustomEvent(3, flowToken, bindings, serviceContainer); } private static void OnCustomEvent04(FlowToken flowToken, Dictionary bindings, FlowControllerServicesContainer serviceContainer) { OnCustomEvent(4, flowToken, bindings, serviceContainer); } private static void OnCustomEvent05(FlowToken flowToken, Dictionary bindings, FlowControllerServicesContainer serviceContainer) { OnCustomEvent(5, flowToken, bindings, serviceContainer); } private static void OnCustomEvent(int customEventNumber, FlowToken flowToken, Dictionary bindings, FlowControllerServicesContainer serviceContainer) { if (customEventNumber < 1 || customEventNumber > 5) throw new ArgumentException("Number must be between 1 and 5", nameof(customEventNumber)); WorkflowFlowToken workflowFlowToken = (WorkflowFlowToken)flowToken; using (TaskContainer taskContainer = TaskManagerFacade.RuntTasks(flowToken, new WorkflowTaskManagerEvent(flowToken, workflowFlowToken.WorkflowInstanceId) { EventName = "CustomEvent0" + customEventNumber })) { WorkflowFacade.FireCustomEvent(customEventNumber, workflowFlowToken.WorkflowInstanceId, bindings); WorkflowFacade.SetFlowControllerServicesContainer(workflowFlowToken.WorkflowInstanceId, serviceContainer); WorkflowFacade.RunWorkflow(workflowFlowToken.WorkflowInstanceId); taskContainer.SetOnIdleTaskManagerEvent(new WorkflowTaskManagerEvent(flowToken, workflowFlowToken.WorkflowInstanceId)); } } } } ================================================ FILE: Composite/C1Console/Workflow/WorkflowFlowToken.cs ================================================ using System; using Composite.C1Console.Actions; namespace Composite.C1Console.Workflow { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [FlowController(typeof(WorkflowFlowController))] public sealed class WorkflowFlowToken : FlowToken { private Guid _workflowInstanceId; /// public WorkflowFlowToken(Guid workflowInstanceId) { _workflowInstanceId = workflowInstanceId; } /// public Guid WorkflowInstanceId { get { return _workflowInstanceId; } } /// public override string Serialize() { return _workflowInstanceId.ToString(); } /// public static FlowToken Deserialize(string serializedFlowToken) { return new WorkflowFlowToken(new Guid(serializedFlowToken)); } } } ================================================ FILE: Composite/C1Console/Workflow/WorkflowTaskManagerEvent.cs ================================================ using Composite.C1Console.Tasks; using System; using Composite.C1Console.Actions; namespace Composite.C1Console.Workflow { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class WorkflowTaskManagerEvent : FlowTaskManagerEvent { /// public WorkflowTaskManagerEvent(FlowToken flowToken, Guid workflowInstanceId) : base(flowToken) { this.WorkflowInstanceId = workflowInstanceId; this.EventName = ""; } /// public string EventName { get; set ;} /// public Guid WorkflowInstanceId { get; private set; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class WorkflowCreationTaskManagerEvent : TaskManagerEvent { /// public WorkflowCreationTaskManagerEvent(Guid parentWorkflowInstanceId) { this.ParentWorkflowInstanceId = parentWorkflowInstanceId; } /// public Guid ParentWorkflowInstanceId { get; private set; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class SaveWorklowTaskManagerEvent : WorkflowTaskManagerEvent { /// public SaveWorklowTaskManagerEvent(FlowToken flowToken, Guid workflowInstanceId, bool succeeded) : base(flowToken, workflowInstanceId) { this.Succeeded = succeeded; } /// public bool Succeeded { get; private set; } /// public override string ToString() { return string.Format("WorkflowInstanceId: {0}, SaveStaus: {1}", this.WorkflowInstanceId, this.Succeeded); } } } ================================================ FILE: Composite/Composite.FxCop ================================================  True c:\program files\microsoft fxcop 1.36\Xml\FxCopReport.xsl True True True 10 1 False False 120 False C:/Windows/Microsoft.NET/Framework/v2.0.50727/ ================================================ FILE: Composite/Composite.csproj ================================================  Debug AnyCPU 9.0.30729 2.0 {F8D87A5F-D090-4D24-80C1-DBCD938C6CAB} Library Composite Composite {14822709-B5A1-4724-98CA-57A101D1B079};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 4 v4.8 SAK SAK SAK SAK 3.5 false publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false true true full false bin\Debug\ TRACE;DEBUG prompt false bin\Debug\Composite.xml AllRules.ruleset 618 false 7 pdbonly true bin\Release\ TRACE prompt 4 AllRules.ruleset bin\Release\Composite.XML false ..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll True ..\packages\Microsoft.Extensions.DependencyInjection.1.1.0\lib\netstandard1.1\Microsoft.Extensions.DependencyInjection.dll True ..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.1.1.0\lib\netstandard1.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll True False ..\bin\Microsoft.Practices.EnterpriseLibrary.Common.dll False ..\bin\Microsoft.Practices.EnterpriseLibrary.Logging.dll False ..\bin\Microsoft.Practices.EnterpriseLibrary.Validation.dll False ..\bin\Microsoft.Practices.ObjectBuilder.dll ..\packages\Newtonsoft.Json.6.0.5\lib\net45\Newtonsoft.Json.dll True ..\packages\System.Collections.Immutable.1.3.1\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll True 3.5 ..\packages\System.Diagnostics.DiagnosticSource.4.3.0\lib\net46\System.Diagnostics.DiagnosticSource.dll True ..\packages\System.Reactive.Core.3.0.0\lib\net46\System.Reactive.Core.dll True ..\packages\System.Reactive.Interfaces.3.0.0\lib\net45\System.Reactive.Interfaces.dll True ..\packages\System.Reactive.Linq.3.0.0\lib\net46\System.Reactive.Linq.dll True ..\packages\System.Reactive.PlatformServices.3.0.0\lib\net46\System.Reactive.PlatformServices.dll True ..\packages\System.Reactive.Windows.Threading.3.0.0\lib\net45\System.Reactive.Windows.Threading.dll True 3.0 3.5 ..\packages\System.Threading.Tasks.Dataflow.4.7.0\lib\portable-net45+win8+wpa81\System.Threading.Tasks.Dataflow.dll ..\packages\System.ValueTuple.4.4.0\lib\net47\System.ValueTuple.dll True ..\packages\Microsoft.AspNet.Razor.3.2.3\lib\net45\System.Web.Razor.dll True False ..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.dll True ..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.Razor.dll True 3.5 3.0 False ..\bin\TidyNet.dll ..\packages\WampSharp.18.3.1\lib\net45\WampSharp.dll True ..\packages\WampSharp.AspNet.WebSockets.Server.18.3.1\lib\net45\WampSharp.AspNet.WebSockets.Server.dll True ..\packages\WampSharp.NewtonsoftJson.18.3.1\lib\net45\WampSharp.NewtonsoftJson.dll True ..\packages\WampSharp.WebSockets.18.3.1\lib\net45\WampSharp.WebSockets.dll True ASPXCodeBehind ASPXCodeBehind True True LocalizationFiles.tt Code Code ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind Code Component InstallLocalPackageWorkflow.cs Component InstallRemotePackageWorkflow.cs ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind Component ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind Component Component Component Component Component Component Component Component Component ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind Code ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind ASPXCodeBehind Component Component Component Component Component Component Component Component Component Component Component Component Component Component Component Component Component TextTemplatingFileGenerator LocalizationFiles.cs Designer False .NET Framework 3.5 SP1 Client Profile false False .NET Framework 3.5 SP1 true False Microsoft Visual Basic PowerPacks 10.0 true False Windows Installer 3.1 true $(ProjectDir)git_branch.txt $(ProjectDir)git_commithash.txt $([System.IO.File]::ReadAllText("$(GitBranchFile)").Trim()) $([System.IO.File]::ReadAllText("$(GitCommitHashFile)").Trim()) [assembly: System.Reflection.AssemblyInformationalVersion("$(GitBranch). Commit Hash: $(GitCommitHash)")] copy "$(TargetPath)" "$(ProjectDir)..\bin\" copy "$(TargetPath)" "$(ProjectDir)..\Website\bin\" ================================================ FILE: Composite/Composite.csproj.vspscc ================================================ "" { "FILE_VERSION" = "9237" "ENLISTMENT_CHOICE" = "NEVER" "PROJECT_FILE_RELATIVE_PATH" = "" "NUMBER_OF_EXCLUDED_FILES" = "0" "ORIGINAL_PROJECT_FILE_PATH" = "" "NUMBER_OF_NESTED_PROJECTS" = "0" "SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER" } ================================================ FILE: Composite/Core/Application/AppDomainLocker.cs ================================================ using System; using System.Diagnostics; namespace Composite.Core.Application { /// /// This class provides system wide locking throughout all app domains for the given C1 installation. /// It does lock lock between C1 installations if more than one runs on the same machine. /// internal static class AppDomainLocker { private static readonly SystemGlobalSemaphore _semaphore = new SystemGlobalSemaphore(EventWaitHandleId); private static int _numberOfLocksAcquired; private static readonly object _numberOfLocksAcquiredLock = new object(); private const string _verboseLogEntryTitle = "RGB(205, 92, 92)AppDomainLocker"; private const string _warningLogEntryTitle = "AppDomainLocker"; /// /// Returns an IDisposalbe and requires the lock. Disposing the IDisposable releases the lock. /// /// If this is true, verbose logging is done. Default is false /// /// /// using (AppDomainLocker.NewLock) /// { /// /* This code will only run in one app domain at any time */ /// } /// /// public static IDisposable NewLock(bool verbose = false) { return new DisposableLock(verbose); } /// /// Returns true if the calling app domain has the lock. /// public static bool CurrentAppDomainHasLock => IsCurrentAppDomainLockingAppDomain(); /// /// Acquires a system wide lock accross all app domains for the current C1 installation. /// This call be called multiple times from the same thread. /// To release the lock, call /// /// Acquire lock timeout in milliseconds. /// If this is false, no logging will be done. /// True if the lock was acquired. public static bool AcquireLock(int timeout = 30000, bool verbose = true) { if (RuntimeInformation.AppDomainLockingDisabled) return true; var appDomainId = AppDomain.CurrentDomain.Id; var processId = Process.GetCurrentProcess().Id; lock (_numberOfLocksAcquiredLock) { if (!IsCurrentAppDomainLockingAppDomain()) { if (verbose) Log.LogVerbose(_verboseLogEntryTitle, $"The AppDomain '{appDomainId}', Process '{processId}': Are going to acquire the system wide lock with the key '{_semaphore.Id}'..."); bool entered = _semaphore.Enter(timeout); if (!entered) { string message = $"The AppDomain '{appDomainId}', Process '{processId}': Failed to acquire the system wide lock with the key '{_semaphore.Id}' within the timeout period of {timeout} ms!!!"; Log.LogWarning(_warningLogEntryTitle, message); //throw new WaitHandleCannotBeOpenedException(message); return false; } if (verbose) Log.LogVerbose(_verboseLogEntryTitle, $"The AppDomain '{appDomainId}', Process '{processId}': Acquired the system wide lock with the key '{_semaphore.Id}'!"); } else { if (verbose) Log.LogVerbose(_verboseLogEntryTitle, $"The AppDomain '{appDomainId}', Process '{processId}': Acquiring the lock that it is already holding the system wide lock with the key '{_semaphore.Id}' (Number of inner locks {_numberOfLocksAcquired + 1})"); } _numberOfLocksAcquired++; return true; } } /// /// Releases the acquired system wide lock. /// If the same thread has acquired the lock more than once, only the last call to this method /// from that thread will release the lock. /// /// /// If this is true, the lock will be released regardless if the current app domain has it or not. /// If the lock was released public static bool ReleaseLock(bool verbose = true, bool forceRelease = false) { if (RuntimeInformation.AppDomainLockingDisabled) return true; var appDomainId = AppDomain.CurrentDomain.Id; var processId = Process.GetCurrentProcess().Id; lock (_numberOfLocksAcquiredLock) { if (!forceRelease && IsAllReleased()) { Log.LogWarning(_warningLogEntryTitle, $"The AppDomain '{appDomainId}', Process '{processId}': Is trying to release a system wide lock with the key '{_semaphore.Id}' that it does not hold! Release ignored!"); return true; } if (forceRelease || IsLastReleaseForLockHoldingAppDomain()) { if (verbose) Log.LogVerbose(_verboseLogEntryTitle, $"The AppDomain '{appDomainId}', Process '{processId}': Are going to release the system wide lock with the key '{_semaphore.Id}' (force: {forceRelease})..."); try { _semaphore.Leave(); } catch(Exception) { return false; } if (verbose) Log.LogVerbose(_verboseLogEntryTitle, $"The AppDomain '{appDomainId}', Process '{processId}': Released the system wide lock with the key '{_semaphore.Id}' (force: {forceRelease})..."); } else { if (verbose) Log.LogVerbose(_verboseLogEntryTitle, $"The AppDomain '{appDomainId}', Process '{processId}': Releasing a lock it has aqruired more than once with the key '{_semaphore.Id}'. Lock not released. (Number of inner locks {_numberOfLocksAcquired - 1})"); } if (!forceRelease) _numberOfLocksAcquired--; return true; } } /// /// Used to name the EventWaitHandle, making it a system wide EventWaitHandle /// private static string EventWaitHandleId => RuntimeInformation.UniqueInstanceName; /// /// Returns true if the current thread is the thread holding the lock /// /// private static bool IsCurrentAppDomainLockingAppDomain() => _numberOfLocksAcquired > 0; /// /// Returns true if there will be no more releases for the lock holding thread. /// /// private static bool IsLastReleaseForLockHoldingAppDomain() => _numberOfLocksAcquired == 1; /// /// Returns true if all locks have been released. /// /// private static bool IsAllReleased() => _numberOfLocksAcquired == 0; /// /// Used for implementing the disposable pattern for /// private class DisposableLock : IDisposable { private bool _disposed; private readonly bool _verbose; public DisposableLock(bool verbose = true) { _verbose = verbose; AppDomainLocker.AcquireLock(verbose: _verbose); } public void Dispose() { Dispose(true); #if LeakCheck GC.SuppressFinalize(this); #endif } void Dispose(bool disposing) { if (!disposing || _disposed) return; _disposed = true; AppDomainLocker.ReleaseLock(verbose: _verbose); } #if LeakCheck private string stack = Environment.StackTrace; ~DisposableLock() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); Dispose(false); } #endif } } } ================================================ FILE: Composite/Core/Application/ApplicationOfflineCheckHttpModule.cs ================================================ using System; using System.Web; using Composite.Core.Extensions; using Composite.Core.IO; namespace Composite.Core.Application { internal class ApplicationOfflineCheckHttpModule: IHttpModule { private static bool _isOffline; private static string _responceHtml; public void Init(HttpApplication context) { context.BeginRequest += HttpApplication_BeginRequest; } protected virtual void HttpApplication_BeginRequest(object sender, EventArgs e) { var context = ((HttpApplication)sender).Context; if (!IsOffline || context.Request.FilePath.EndsWith("/Composite/services/LogService/LogService.svc", StringComparison.OrdinalIgnoreCase)) { return; } context.Response.Clear(); context.Response.Write(_responceHtml); context.Response.StatusCode = 480; /* Temporary unavailable*/ context.Response.Flush(); context.ApplicationInstance.CompleteRequest(); } public static bool IsOffline { get { return _isOffline; } set { _isOffline = value; if(!_isOffline) { return; } string filePath = FilePath; Verify.That(!filePath.IsNullOrEmpty(), "Path to 'app_offline.html' has not been set"); try { _responceHtml = C1File.ReadAllText(filePath); } catch(Exception e) { _responceHtml = string.Empty; Core.Logging.LoggingService.LogWarning("Failed to load file '{0}'".FormatWith(filePath), e); } } } public static string FilePath { get; set; } public void Dispose() { } } } ================================================ FILE: Composite/Core/Application/ApplicationOnlineHandlerFacade.cs ================================================ using System; namespace Composite.Core.Application { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ApplicationOnlineHandlerFacade { private static IApplicationOnlineHandlerFacade _applicationOnlineHandlerFacade = new ApplicationOnlineHandlerFacadeImpl(); internal static IApplicationOnlineHandlerFacade Implementation { get { return _applicationOnlineHandlerFacade; } set { _applicationOnlineHandlerFacade = value; } } /// /// Turns application offline /// /// /// Setting softTurnOff to true will only make the application offline to the client, but /// not actually turning off the application. Setting this to false will turn off the /// application. /// public static void TurnApplicationOffline(bool softTurnOff) { _applicationOnlineHandlerFacade.TurnApplicationOffline(softTurnOff, true); } /// public static void TurnApplicationOffline(bool softTurnOff, bool recompileCompositeGenerated) { _applicationOnlineHandlerFacade.TurnApplicationOffline(softTurnOff, recompileCompositeGenerated); } /// public static bool CanPutApplicationOffline(bool softTurnOff, out string errorMessage) { return _applicationOnlineHandlerFacade.CanPutApplicationOffline(softTurnOff, out errorMessage); } /// public static void TurnApplicationOnline() { _applicationOnlineHandlerFacade.TurnApplicationOnline(); } /// public static IDisposable TurnOffScope(bool softTurnOff) { TurnApplicationOffline(softTurnOff); return new TurnOffToken(); } /// public static bool IsApplicationOnline { get { return _applicationOnlineHandlerFacade.IsApplicationOnline; } } private sealed class TurnOffToken : IDisposable { public void Dispose() { ApplicationOnlineHandlerFacade.TurnApplicationOnline(); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~TurnOffToken() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } } ================================================ FILE: Composite/Core/Application/ApplicationOnlineHandlerFacadeImpl.cs ================================================ using System; using System.Threading; using System.Web.Hosting; using Composite.C1Console.Events; using Composite.Core.Application.Foundation.PluginFacades; using Composite.Core.Types; namespace Composite.Core.Application { internal class ApplicationOnlineHandlerFacadeImpl : IApplicationOnlineHandlerFacade { private static readonly string LogTitle = typeof (ApplicationOnlineHandlerFacadeImpl).Name; private bool _isApplicationOnline = true; private bool _wasLastTurnOffSoft = false; private bool _recompileCompositeGenerated; private ShutdownGuard _shutdownGuard; public void TurnApplicationOffline(bool softTurnOff, bool recompileCompositeGenerated) { Verify.IsTrue(this.IsApplicationOnline, "The application is already offline"); Log.LogVerbose("ApplicationOnlineHandlerFacade", string.Format("Turning off the application ({0})", softTurnOff ? "Soft" : "Hard")); _recompileCompositeGenerated = recompileCompositeGenerated; _shutdownGuard = new ShutdownGuard(); try { if (softTurnOff == false) { ApplicationOnlineHandlerPluginFacade.TurnApplicationOffline(); Verify.IsFalse(ApplicationOnlineHandlerPluginFacade.IsApplicationOnline(), "Plugin failed to turn the application offline"); } else { ConsoleMessageQueueFacade.Enqueue(new LockSystemConsoleMessageQueueItem(), ""); } } catch(Exception) { _shutdownGuard.Dispose(); _shutdownGuard = null; throw; } _isApplicationOnline = false; _wasLastTurnOffSoft = softTurnOff; } public void TurnApplicationOnline() { Verify.IsFalse(this.IsApplicationOnline, "The application is already online"); Log.LogVerbose("ApplicationOnlineHandlerFacade", "Turning on the application"); if (_recompileCompositeGenerated) { try { CodeGenerationManager.GenerateCompositeGeneratedAssembly(); } catch (Exception ex) { Log.LogError(LogTitle, "Failed to recompile Composite.Generated.dll"); Log.LogError(LogTitle, ex); } } try { if (_wasLastTurnOffSoft == false) { ApplicationOnlineHandlerPluginFacade.TurnApplicationOnline(); Verify.IsTrue(ApplicationOnlineHandlerPluginFacade.IsApplicationOnline(), "Plugin failed to turn the application online"); } } finally { // Adding a sleep, so delayed notification from FileWatcher will not kill a newly spawned AppDomain Thread.Sleep(250); _shutdownGuard.Dispose(); _shutdownGuard = null; if (HostingEnvironment.IsHosted) { HostingEnvironment.InitiateShutdown(); } } _isApplicationOnline = true; } public bool IsApplicationOnline { get { return _isApplicationOnline; } } public bool CanPutApplicationOffline(bool softTurnOff, out string errorMessage) { if(softTurnOff) { errorMessage = null; return true; } return ApplicationOnlineHandlerPluginFacade.CanPutApplicationOffline(out errorMessage); } } } ================================================ FILE: Composite/Core/Application/ApplicationStartupFacade.cs ================================================ using System; using Composite.Core.Application.Foundation; using Composite.Core.Application.Foundation.PluginFacades; using Microsoft.Extensions.DependencyInjection; namespace Composite.Core.Application { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ApplicationStartupFacade { /// public static void FireConfigureServices(IServiceCollection serviceCollection) { foreach (string hanlderName in ApplicationStartupHandlerRegistry.ApplicationStartupHandlerNames) { ApplicationStartupHandlerPluginFacade.ConfigureServices(hanlderName, serviceCollection); } } /// public static void FireBeforeSystemInitialize(IServiceProvider serviceProvider) { foreach (string hanlderName in ApplicationStartupHandlerRegistry.ApplicationStartupHandlerNames) { ApplicationStartupHandlerPluginFacade.OnBeforeInitialize(hanlderName, serviceProvider); } } /// public static void FireSystemInitialized(IServiceProvider serviceProvider) { foreach (string hanlderName in ApplicationStartupHandlerRegistry.ApplicationStartupHandlerNames) { ApplicationStartupHandlerPluginFacade.OnInitialized(hanlderName, serviceProvider); } } } } ================================================ FILE: Composite/Core/Application/Foundation/ApplicationStartupHandlerRegistry.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.C1Console.Events; namespace Composite.Core.Application.Foundation { internal static class ApplicationStartupHandlerRegistry { private static IApplicationStartupHandlerRegistry _applicationStartupHandlerRegistry = new ApplicationStartupHandlerRegistryImpl(); static ApplicationStartupHandlerRegistry() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } internal static IApplicationStartupHandlerRegistry Implementation { get { return _applicationStartupHandlerRegistry; } set { _applicationStartupHandlerRegistry = value; } } public static IEnumerable ApplicationStartupHandlerNames { get { return _applicationStartupHandlerRegistry.ApplicationStartupHandlerNames; } } private static void Flush() { _applicationStartupHandlerRegistry.Flush(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } } } ================================================ FILE: Composite/Core/Application/Foundation/ApplicationStartupHandlerRegistryImpl.cs ================================================ using System.Collections.Generic; using Composite.Core.Application.Plugins.ApplicationStartupHandler; using Composite.Core.Application.Plugins.ApplicationStartupHandler.Runtime; using Composite.Core.Configuration; namespace Composite.Core.Application.Foundation { internal sealed class ApplicationStartupHandlerRegistryImpl : IApplicationStartupHandlerRegistry { private static List _handlerNames = null; private static object _lock = new object(); public IEnumerable ApplicationStartupHandlerNames { get { Initialize(); foreach (string name in _handlerNames) { yield return name; } } } private void Initialize() { if (_handlerNames == null) { lock (_lock) { if (_handlerNames == null) { _handlerNames = new List(); ApplicationStartupHandlerSettings applicationStartupHandlerSettings = ConfigurationServices.ConfigurationSource.GetSection(ApplicationStartupHandlerSettings.SectionName) as ApplicationStartupHandlerSettings; foreach (ApplicationStartupHandlerData applicationStartupHandlerData in applicationStartupHandlerSettings.ApplicationStartupHandlerPlugins) { _handlerNames.Add(applicationStartupHandlerData.Name); } } } } } public void Flush() { _handlerNames = null; } } } ================================================ FILE: Composite/Core/Application/Foundation/IApplicationStartupHandlerRegistry.cs ================================================ using System.Collections.Generic; namespace Composite.Core.Application.Foundation { internal interface IApplicationStartupHandlerRegistry { IEnumerable ApplicationStartupHandlerNames { get; } void Flush(); } } ================================================ FILE: Composite/Core/Application/Foundation/PluginFacades/ApplicationOnlineHandlerPluginFacade.cs ================================================ using System; using System.Configuration; using Composite.Core.Application.Plugins.ApplicationOnlineHandler; using Composite.Core.Application.Plugins.ApplicationOnlineHandler.Runtime; using Composite.Core.Collections.Generic; using Composite.C1Console.Events; namespace Composite.Core.Application.Foundation.PluginFacades { internal static class ApplicationOnlineHandlerPluginFacade { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); static ApplicationOnlineHandlerPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static void TurnApplicationOffline() { IApplicationOnlineHandler applicationOnlineHandler = GetApplicationOnlineHandler(); applicationOnlineHandler.TurnApplicationOffline(); } public static void TurnApplicationOnline() { IApplicationOnlineHandler applicationOnlineHandler = GetApplicationOnlineHandler(); applicationOnlineHandler.TurnApplicationOnline(); } public static bool IsApplicationOnline() { IApplicationOnlineHandler applicationOnlineHandler = GetApplicationOnlineHandler(); return applicationOnlineHandler.IsApplicationOnline(); } public static bool CanPutApplicationOffline(out string errorMessage) { return GetApplicationOnlineHandler().CanPutApplicationOffline(out errorMessage); } private static IApplicationOnlineHandler GetApplicationOnlineHandler() { IApplicationOnlineHandler handler = null; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.HandlerCache == null) { try { handler = _resourceLocker.Resources.Factory.CreateDefault(); _resourceLocker.Resources.HandlerCache = handler; } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } else { handler = _resourceLocker.Resources.HandlerCache; } } return handler; } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", ApplicationOnlineHandlerSettings.SectionName), ex); } private sealed class Resources { public ApplicationOnlineHandlerFactory Factory { get; set; } public IApplicationOnlineHandler HandlerCache { get; set; } public static void Initialize(Resources resources) { try { resources.Factory = new ApplicationOnlineHandlerFactory(); } catch (NullReferenceException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } resources.HandlerCache = null; } } } } ================================================ FILE: Composite/Core/Application/Foundation/PluginFacades/ApplicationStartupHandlerPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using Composite.Core.Application.Plugins.ApplicationOnlineHandler.Runtime; using Composite.Core.Application.Plugins.ApplicationStartupHandler; using Composite.Core.Application.Plugins.ApplicationStartupHandler.Runtime; using Composite.Core.Collections.Generic; using Microsoft.Extensions.DependencyInjection; namespace Composite.Core.Application.Foundation.PluginFacades { internal static class ApplicationStartupHandlerPluginFacade { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); public static void ConfigureServices(string handlerName, IServiceCollection serviceCollection) { Verify.ArgumentNotNullOrEmpty(handlerName, nameof(handlerName)); Verify.ArgumentNotNull(serviceCollection, nameof(serviceCollection)); using (_resourceLocker.Locker) { IApplicationStartupHandler provider = GetApplicationStartupHandler(handlerName); provider.ConfigureServices(serviceCollection); } } public static void OnBeforeInitialize(string handlerName, IServiceProvider serviceProvider) { Verify.ArgumentNotNullOrEmpty(handlerName, nameof(handlerName)); using (_resourceLocker.Locker) { IApplicationStartupHandler provider = GetApplicationStartupHandler(handlerName); provider.OnBeforeInitialize(serviceProvider); } } public static void OnInitialized(string handlerName, IServiceProvider serviceProvider) { Verify.ArgumentNotNullOrEmpty(handlerName, nameof(handlerName)); using (_resourceLocker.Locker) { IApplicationStartupHandler provider = GetApplicationStartupHandler(handlerName); provider.OnInitialized(serviceProvider); } } private static IApplicationStartupHandler GetApplicationStartupHandler(string handlerName) { IApplicationStartupHandler applicationStartupHandler; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.ProviderCache.TryGetValue(handlerName, out applicationStartupHandler) == false) { try { applicationStartupHandler = _resourceLocker.Resources.Factory.Create(handlerName); _resourceLocker.Resources.ProviderCache.Add(handlerName, applicationStartupHandler); } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } } return applicationStartupHandler; } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", ApplicationOnlineHandlerSettings.SectionName), ex); } private sealed class Resources { public ApplicationStartupHandlerFactory Factory { get; set; } public Dictionary ProviderCache { get; set; } public static void Initialize(Resources resources) { try { resources.Factory = new ApplicationStartupHandlerFactory(); } catch (NullReferenceException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } resources.ProviderCache = new Dictionary(); } } } } ================================================ FILE: Composite/Core/Application/GlobalFileLocker.cs ================================================ using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Threading; using Composite.Core.Configuration; using Composite.Core.IO; namespace Composite.Core.Application { /// /// This class enables cross app domain/process locking using a file. /// [EditorBrowsable(EditorBrowsableState.Never)] internal class GlobalFileLocker { private string Id { get; set; } private string GlobalLockFileName { get; set; } /// /// /// The id is used as part of a filename, so it should only contain file name valid chars. /// Default is temp directory. public GlobalFileLocker(string id, string folderPath = null) { LockTimeOut = 5; if (folderPath == null) { folderPath = PathUtil.Resolve(GlobalSettingsFacade.TempDirectory); } Id = id; GlobalLockFileName = Path.Combine(folderPath, id + ".lock"); } /// /// Time out in seconds. Default is 5 secounds. /// public int LockTimeOut { get; set; } /// /// public IDisposable Lock { get { return new DisposableLock(this); } } /// /// Consider using the for better code safty /// /// /// /// public bool AquireLock(int retryCount = 50, bool thrownOnFail = false) { for (int i = 0; i < retryCount; i++) { bool lockObtained = TryAquireLock(); if (lockObtained) return true; Thread.Sleep(0); // Context switch } string message = string.Format("Failed to obtain global file lock with id '{0}'", Id); Log.LogWarning("GlobalFileLocker", message); if (thrownOnFail) throw new InvalidOperationException(message); return false; } /// /// Consider using the for better code safty /// [SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void ReleaseLock() { if (File.Exists(GlobalLockFileName)) { try { File.Delete(GlobalLockFileName); } catch (Exception ex) { throw new InvalidOperationException("Two or more threads tried to release at the same time. Check AquireLock and ReleaseLock usage.", ex); } } } [SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] private bool TryAquireLock() { double existingLockFileAgeSeconds = File.Exists(GlobalLockFileName) ? (DateTime.Now - File.GetLastWriteTime(GlobalLockFileName)).TotalSeconds : -1; // Does not exist if (existingLockFileAgeSeconds > LockTimeOut) { File.Delete(GlobalLockFileName); } string tmpFileName = GlobalLockFileName + "." + Path.GetRandomFileName(); File.WriteAllText(tmpFileName, "LOCK"); try { // Assumption: This is a system wide atomar action. If one already has the lock, the Move will fail. File.Move(tmpFileName, GlobalLockFileName); return true; } catch (IOException) { File.Delete(tmpFileName); } return false; } /// /// Used for implementing the disposable pattern for /// private class DisposableLock : IDisposable { private bool disposed = false; private GlobalFileLocker _globalFileLocker; public DisposableLock(GlobalFileLocker globalFileLocker) { _globalFileLocker = globalFileLocker; _globalFileLocker.AquireLock(thrownOnFail: true); } public void Dispose() { Dispose(true); #if LeakCheck GC.SuppressFinalize(this); #endif } protected virtual void Dispose(bool disposing) { if (!disposing || disposed) return; disposed = true; _globalFileLocker.ReleaseLock(); } #if LeakCheck private string stack = Environment.StackTrace; ~DisposableLock() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); Dispose(false); } #endif } } } ================================================ FILE: Composite/Core/Application/IApplicationOnlineHandlerFacade.cs ================================================ namespace Composite.Core.Application { internal interface IApplicationOnlineHandlerFacade { /// /// /// /// /// Setting softTurnOff to true will only make the application offline to the client, but /// not actually turning off the application. Setting this to false will turn off the /// application. /// /// /// Settings this to true will result in a recompilation of assemblies at startup /// void TurnApplicationOffline(bool softTurnOff, bool recompileCompositeGenerated); void TurnApplicationOnline(); bool IsApplicationOnline { get; } bool CanPutApplicationOffline(bool softTurnOff, out string errorMessage); } } ================================================ FILE: Composite/Core/Application/Job.cs ================================================ using System; using System.Runtime.InteropServices; namespace Composite.Core.Application { enum JobObjectInfoType { AssociateCompletionPortInformation = 7, BasicLimitInformation = 2, BasicUIRestrictions = 4, EndOfJobTimeInformation = 6, ExtendedLimitInformation = 9, SecurityLimitInformation = 5, GroupInformation = 11 } [StructLayout(LayoutKind.Sequential)] struct SECURITY_ATTRIBUTES { public UInt32 nLength; public IntPtr lpSecurityDescriptor; public Int32 bInheritHandle; } [StructLayout(LayoutKind.Sequential)] struct JOBOBJECT_BASIC_LIMIT_INFORMATION { public Int64 PerProcessUserTimeLimit; public Int64 PerJobUserTimeLimit; public UInt32 LimitFlags; public UIntPtr MinimumWorkingSetSize; public UIntPtr MaximumWorkingSetSize; public UInt32 ActiveProcessLimit; public UIntPtr Affinity; public UInt32 PriorityClass; public UInt32 SchedulingClass; } [StructLayout(LayoutKind.Sequential)] struct IO_COUNTERS { public UInt64 ReadOperationCount; public UInt64 WriteOperationCount; public UInt64 OtherOperationCount; public UInt64 ReadTransferCount; public UInt64 WriteTransferCount; public UInt64 OtherTransferCount; } [StructLayout(LayoutKind.Sequential)] struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION { public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation; public IO_COUNTERS IoInfo; public UIntPtr ProcessMemoryLimit; public UIntPtr JobMemoryLimit; public UIntPtr PeakProcessMemoryUsed; public UIntPtr PeakJobMemoryUsed; } /// /// An utility class for registering child processes that ensures that they will be killed if the current process crashes. /// internal class Job: IDisposable { [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern IntPtr CreateJobObject(IntPtr a, string lpName); [DllImport("kernel32.dll", SetLastError = true)] static extern bool SetInformationJobObject(IntPtr hJob, JobObjectInfoType infoType, IntPtr lpJobObjectInfo, uint cbJobObjectInfoLength); [DllImport("kernel32.dll", SetLastError = true)] static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] static extern bool CloseHandle(IntPtr handle); private IntPtr m_handle; private bool m_disposed = false; public Job() { m_handle = CreateJobObject(IntPtr.Zero, null); var info = new JOBOBJECT_BASIC_LIMIT_INFORMATION { LimitFlags = 0x2000 }; var extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION { BasicLimitInformation = info }; int length = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION)); IntPtr extendedInfoPtr = Marshal.AllocHGlobal(length); Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false); bool success = SetInformationJobObject(m_handle, JobObjectInfoType.ExtendedLimitInformation, extendedInfoPtr, (uint) length); if (!success) { Log.LogError(typeof(Job).FullName, "SetInformationJobObject returned error code " + Marshal.GetLastWin32Error()); } } #region IDisposable Members public void Dispose() { Dispose(true); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~Job() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif #endregion private void Dispose(bool disposing) { if (m_disposed) return; if (disposing) { } Close(); m_disposed = true; } public void Close() { CloseHandle(m_handle); m_handle = IntPtr.Zero; } public bool AddProcess(IntPtr handle) { return AssignProcessToJobObject(m_handle, handle); } } } ================================================ FILE: Composite/Core/Application/Plugins/ApplicationOnlineHandler/ApplicationOnlineHandlerData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Application.Plugins.ApplicationOnlineHandler { [ConfigurationElementType(typeof(NonConfigurableApplicationOnlineHandler))] internal class ApplicationOnlineHandlerData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/Core/Application/Plugins/ApplicationOnlineHandler/IApplicationOnlineHandler.cs ================================================ using Composite.Core.Application.Plugins.ApplicationOnlineHandler.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Application.Plugins.ApplicationOnlineHandler { [CustomFactory(typeof(ApplicationOnlineHandlerCustomFactory))] [ConfigurationNameMapper(typeof(ApplicationOnlineHandlerDefaultNameRetriever))] internal interface IApplicationOnlineHandler { void TurnApplicationOffline(); void TurnApplicationOnline(); bool IsApplicationOnline(); bool CanPutApplicationOffline(out string errorMessage); } } ================================================ FILE: Composite/Core/Application/Plugins/ApplicationOnlineHandler/NonConfigurableApplicationOnlineHandler.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Core.Application.Plugins.ApplicationOnlineHandler { [Assembler(typeof(NonConfigurableApplicationOnlineHandlerAssembler))] internal class NonConfigurableApplicationOnlineHandler : ApplicationOnlineHandlerData { } internal sealed class NonConfigurableApplicationOnlineHandlerAssembler : IAssembler { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IApplicationOnlineHandler Assemble(IBuilderContext context, ApplicationOnlineHandlerData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IApplicationOnlineHandler)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/Core/Application/Plugins/ApplicationOnlineHandler/Runtime/ApplicationOnlineHandlerCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Application.Plugins.ApplicationOnlineHandler.Runtime { internal sealed class ApplicationOnlineHandlerCustomFactory : AssemblerBasedCustomFactory { protected override ApplicationOnlineHandlerData GetConfiguration(string name, IConfigurationSource configurationSource) { ApplicationOnlineHandlerSettings settings = configurationSource.GetSection(ApplicationOnlineHandlerSettings.SectionName) as ApplicationOnlineHandlerSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", ApplicationOnlineHandlerSettings.SectionName)); } return settings.ApplicationOnlineHandlerPlugins.Get(name); } } } ================================================ FILE: Composite/Core/Application/Plugins/ApplicationOnlineHandler/Runtime/ApplicationOnlineHandlerDefaultNameRetriever.cs ================================================ using System; using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Application.Plugins.ApplicationOnlineHandler.Runtime { internal sealed class ApplicationOnlineHandlerDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { if (null == configSource) throw new ArgumentNullException("configSource"); if (null != name) { return name; } else { ApplicationOnlineHandlerSettings settings = configSource.GetSection(ApplicationOnlineHandlerSettings.SectionName) as ApplicationOnlineHandlerSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("Could not load configuration section {0}", ApplicationOnlineHandlerSettings.SectionName)); } return settings.DefaultApplicationOnlineHandler; } } } } ================================================ FILE: Composite/Core/Application/Plugins/ApplicationOnlineHandler/Runtime/ApplicationOnlineHandlerFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Application.Plugins.ApplicationOnlineHandler.Runtime { internal sealed class ApplicationOnlineHandlerFactory : NameTypeFactoryBase { public ApplicationOnlineHandlerFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/Core/Application/Plugins/ApplicationOnlineHandler/Runtime/ApplicationOnlineHandlerSettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Application.Plugins.ApplicationOnlineHandler.Runtime { internal sealed class ApplicationOnlineHandlerSettings : SerializableConfigurationSection { public const string SectionName = "Composite.Core.Application.Plugins.ApplicationOnlineHandlerConfiguration"; private const string _defaultApplicationOnlineHandlerProviderProperty = "defaultApplicationOnlineHandler"; [ConfigurationProperty(_defaultApplicationOnlineHandlerProviderProperty, IsRequired = true)] public string DefaultApplicationOnlineHandler { get { return (string)base[_defaultApplicationOnlineHandlerProviderProperty]; } set { base[_defaultApplicationOnlineHandlerProviderProperty] = value; } } private const string _applicationOnlineHandlerPluginsProperty = "ApplicationOnlineHandlerPlugins"; [ConfigurationProperty(_applicationOnlineHandlerPluginsProperty)] public NameTypeManagerTypeConfigurationElementCollection ApplicationOnlineHandlerPlugins { get { return (NameTypeManagerTypeConfigurationElementCollection)base[_applicationOnlineHandlerPluginsProperty]; } } } } ================================================ FILE: Composite/Core/Application/Plugins/ApplicationStartupHandler/ApplicationStartupHandlerData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Application.Plugins.ApplicationStartupHandler { [ConfigurationElementType(typeof(NonConfigurableApplicationStartupHandler))] internal class ApplicationStartupHandlerData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/Core/Application/Plugins/ApplicationStartupHandler/IApplicationStartupHandler.cs ================================================ using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Composite.Core.Application.Plugins.ApplicationStartupHandler.Runtime; namespace Composite.Core.Application.Plugins.ApplicationStartupHandler { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [CustomFactory(typeof(ApplicationStartupHandlerCustomFactory))] [ConfigurationNameMapper(typeof(ApplicationStartupHandlerDefaultNameRetriever))] public interface IApplicationStartupHandler { /// /// This handler will be called before Composite initialization. The data layer cannot be used here. /// void ConfigureServices(IServiceCollection serviceCollection); /// /// This handler will be called before Composite initialization. The data layer cannot be used here. /// void OnBeforeInitialize(IServiceProvider serviceProvider); /// /// This handler will be called after initialization of Composite core. /// void OnInitialized(IServiceProvider serviceProvider); } } ================================================ FILE: Composite/Core/Application/Plugins/ApplicationStartupHandler/NonConfigurableApplicationStartupHandler.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Core.Application.Plugins.ApplicationStartupHandler { [Assembler(typeof(NonConfigurableApplicationStartupHandlerAssembler))] internal sealed class NonConfigurableApplicationStartupHandler : ApplicationStartupHandlerData { } internal sealed class NonConfigurableApplicationStartupHandlerAssembler : IAssembler { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IApplicationStartupHandler Assemble(IBuilderContext context, ApplicationStartupHandlerData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IApplicationStartupHandler)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/Core/Application/Plugins/ApplicationStartupHandler/Runtime/ApplicationStartupHandlerCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Application.Plugins.ApplicationStartupHandler.Runtime { internal sealed class ApplicationStartupHandlerCustomFactory : AssemblerBasedCustomFactory { protected override ApplicationStartupHandlerData GetConfiguration(string name, IConfigurationSource configurationSource) { ApplicationStartupHandlerSettings settings = configurationSource.GetSection(ApplicationStartupHandlerSettings.SectionName) as ApplicationStartupHandlerSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", ApplicationStartupHandlerSettings.SectionName)); } return settings.ApplicationStartupHandlerPlugins.Get(name); } } } ================================================ FILE: Composite/Core/Application/Plugins/ApplicationStartupHandler/Runtime/ApplicationStartupHandlerDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Application.Plugins.ApplicationStartupHandler.Runtime { internal sealed class ApplicationStartupHandlerDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/Core/Application/Plugins/ApplicationStartupHandler/Runtime/ApplicationStartupHandlerFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Application.Plugins.ApplicationStartupHandler.Runtime { internal sealed class ApplicationStartupHandlerFactory : NameTypeFactoryBase { public ApplicationStartupHandlerFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/Core/Application/Plugins/ApplicationStartupHandler/Runtime/ApplicationStartupHandlerSettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Application.Plugins.ApplicationStartupHandler.Runtime { internal sealed class ApplicationStartupHandlerSettings : SerializableConfigurationSection { public const string SectionName = "Composite.Core.Application.Plugins.ApplicationStartupHandlerConfiguration"; private const string _applicationStartupPluginPluginsProperty = "ApplicationStartupHandlerPlugins"; [ConfigurationProperty(_applicationStartupPluginPluginsProperty)] public NameTypeManagerTypeConfigurationElementCollection ApplicationStartupHandlerPlugins { get { return (NameTypeManagerTypeConfigurationElementCollection)base[_applicationStartupPluginPluginsProperty]; } } } } ================================================ FILE: Composite/Core/Application/ShutdownGuard.cs ================================================ using System; using System.Reflection; using System.Web; using System.Web.Hosting; namespace Composite.Core.Application { /// /// Postpones raising of shutdown event for ASP.NET /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ShutdownGuard : IDisposable { private readonly HttpRuntime _runtime; private readonly FieldInfo _shutdownWebEventRaised_FieldInfo; private readonly HostingEnvironment _hostingEnvironment; private readonly FieldInfo _shutdownInitiated_FieldInfo; //private readonly object _fileChangesManager; //private readonly FieldInfo _callbackFieldInfo; //private readonly FieldInfo _isFCNDisabledFieldInfo; //private readonly object _savedCallbackValue; /// public ShutdownGuard() { if (!HostingEnvironment.IsHosted) { return; } const BindingFlags getStaticFieldValue = BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField; _runtime = (HttpRuntime)typeof(HttpRuntime).InvokeMember("_theRuntime", getStaticFieldValue, null, null, null); _hostingEnvironment = (HostingEnvironment)typeof(HostingEnvironment).InvokeMember("_theHostingEnvironment", getStaticFieldValue, null, null, null); const BindingFlags privateField = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField; _shutdownWebEventRaised_FieldInfo = typeof(HttpRuntime).GetField("_shutdownWebEventRaised", privateField); // In .NET 3.5 the field is called "_shutdownInitated" // .NET 4.0 the field is called "_shutdownInitiated" _shutdownInitiated_FieldInfo = typeof(HostingEnvironment).GetField("_shutdownInitiated", privateField) ?? typeof(HostingEnvironment).GetField("_shutdownInitated", privateField); // Simulating situation, when all events to unload current AppDomain were already raised. _shutdownWebEventRaised_FieldInfo.SetValue(_runtime, true); _shutdownInitiated_FieldInfo.SetValue(_hostingEnvironment, true); //_fileChangesManager = runtime.GetType().GetField("_fcm", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField).GetValue(runtime); //_callbackFieldInfo = _fileChangesManager.GetType().GetField("_callbackRenameOrCriticaldirChange", // BindingFlags.NonPublic | // BindingFlags.Instance | // BindingFlags.GetField); //_isFCNDisabledFieldInfo = _fileChangesManager.GetType().GetField("_FCNMode", // BindingFlags.NonPublic | // BindingFlags.Instance | // BindingFlags.GetField); //_savedCallbackValue = _callbackFieldInfo.GetValue(_fileChangesManager); //_callbackFieldInfo.SetValue(_fileChangesManager, null); //// Turning off file change notifications. http://support.microsoft.com/kb/911272 //_isFCNDisabledFieldInfo.SetValue(_fileChangesManager, (Int32)1); } /// public void Dispose() { #if LeakCheck GC.SuppressFinalize(this); #endif if (!HostingEnvironment.IsHosted) { return; } _shutdownWebEventRaised_FieldInfo.SetValue(_runtime, false); _shutdownInitiated_FieldInfo.SetValue(_hostingEnvironment, false); //_callbackFieldInfo.SetValue(_fileChangesManager, _savedCallbackValue); //_isFCNDisabledFieldInfo.SetValue(_fileChangesManager, (Int32)0); } #if LeakCheck private string stack = Environment.StackTrace; /// ~ShutdownGuard() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } ================================================ FILE: Composite/Core/Application/SystemGlobalSemaphore.cs ================================================ using System; using System.Threading; using System.ComponentModel; namespace Composite.Core.Application { /// /// This is a OS system wide named semaphore. /// [EditorBrowsable(EditorBrowsableState.Never)] internal class SystemGlobalSemaphore { private readonly string _id; private readonly Semaphore _eventWaitHandle; /// /// /// The system wide id of the semaphore public SystemGlobalSemaphore(string id) { _id = id; if (!_id.StartsWith(@"Global\", StringComparison.InvariantCultureIgnoreCase)) { _id = @"Global\" + _id; } _eventWaitHandle = new Semaphore(1, 1, _id); } /// /// Enter the semaphore. Blocking. Returns false if entering the semaphore failed due to timeout. /// /// Timeout in milliseconds /// If this is true, the method will throw an excepion on timeout /// True if entering successed. False if entering timed out. public bool Enter(int timeout, bool throwOnTimeout = false) { bool entered = _eventWaitHandle.WaitOne(timeout); if (!entered && throwOnTimeout) throw new TimeoutException( $"Failed to obtain the system global semaphore with id '{_id}'"); return entered; } /// /// Leave the semaphore. /// public void Leave() { _eventWaitHandle.Release(); } /// /// The used id used for naming the semaphore. /// public string Id => _id; } } ================================================ FILE: Composite/Core/Application/TempDirectoryFacade.cs ================================================ using System; using System.IO; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.WebClient; namespace Composite.Core.Application { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class TempDirectoryFacade { private static TimeSpan TemporaryFileExpirationTimeSpan = TimeSpan.FromHours(24.0); /// public static string CreateTempDirectory() { string directory = Path.Combine(TempDirectoryPath, UrlUtils.CompressGuid(Guid.NewGuid())); C1Directory.CreateDirectory(directory); return directory; } internal static string GetTempFileName(string extension) { return Path.Combine(TempDirectoryPath, UrlUtils.CompressGuid(Guid.NewGuid()).Substring(0, 8)) + (extension ?? ""); } /// public static void OnApplicationStart() { string tempDirectoryName = TempDirectoryPath; if (!C1Directory.Exists(tempDirectoryName)) { C1Directory.CreateDirectory(tempDirectoryName); } } /// public static void OnApplicationEnd() { // Deleting everything that is older than 24 hours string tempDirectoryName = TempDirectoryPath; if (!C1Directory.Exists(tempDirectoryName)) { return; } foreach (string filename in C1Directory.GetFiles(tempDirectoryName)) { try { if (DateTime.Now > C1File.GetLastWriteTime(filename) + TemporaryFileExpirationTimeSpan) { C1File.Delete(filename); } } catch { } } foreach (string directoryPath in C1Directory.GetDirectories(tempDirectoryName)) { try { if (DateTime.Now > C1Directory.GetCreationTime(directoryPath) + TemporaryFileExpirationTimeSpan) { C1Directory.Delete(directoryPath, true); } } catch { } } } internal static string TempDirectoryPath { get { return PathUtil.Resolve(GlobalSettingsFacade.TempDirectory); } } } } ================================================ FILE: Composite/Core/Caching/CacheManager.cs ================================================ using System; using System.Collections.Generic; using Composite.Core.Caching.Design; namespace Composite.Core.Caching { internal static class CacheManager { private static readonly Dictionary _cacheCollection = new Dictionary(); /// /// Builds a cache instance from a configuration file. /// /// Key type. /// Value type. /// The name of the cache. public static ICache Get(string name) where TValue : class { throw new NotImplementedException(); } public static ICache Get(string name, CacheSettings cacheOptions) where TValue : class { name = name ?? string.Empty; bool isNamed = name != string.Empty; lock(_cacheCollection) { if(isNamed) { if (_cacheCollection.ContainsKey(name)) { return (ICache)_cacheCollection[name]; } } ICache result; switch (cacheOptions.CacheType) { case CacheType.Lightweight: result = new LightweightCache(name, cacheOptions); break; case CacheType.Mixed: Verify.That(typeof(TKey) == typeof(string), "In mixed cache the key can only bee of type 'System.String'"); result = new MixedCache(name, cacheOptions) as ICache; break; case CacheType.Undefined: throw new InvalidOperationException("Cache type is undefined"); default: throw new NotImplementedException(); } Verify.That(result != null, "Failed to create a cache"); _cacheCollection.Add(name != string.Empty ? name : "unnamed cache", result); return result; } } public static ICache[] GetAll() { lock(_cacheCollection) { ICollection values = _cacheCollection.Values; ICache[] result = new ICache[values.Count]; values.CopyTo(result, 0); return result; } } } } ================================================ FILE: Composite/Core/Caching/CachePriority.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Composite.Core.Caching { internal enum CachePriority { Undefined = 0, WeakReference = 1, Low = 2, Default = 3, High = 4, NeverExpires = 5 } } ================================================ FILE: Composite/Core/Caching/CacheSettings.cs ================================================ using System; namespace Composite.Core.Caching { internal sealed class CacheSettings { public CacheType CacheType { get; private set; } public CachePriority DefaultPriority { get; private set; } public int Size { get; set; } // Has sense only for lightweight/mixed cache public TimeSpan SlidingExpritationPeriod { get; set; } // Has sense for AspNet/Mixed cache public CacheSettings(CacheType cacheType) { CacheType = cacheType; SlidingExpritationPeriod = TimeSpan.Zero; DefaultPriority = CachePriority.Default; Size = -1; // Unlimited } public static CacheSettings AspNet { get { return new CacheSettings(CacheType.AspNet); } } public static CacheSettings Mixed { get { return new CacheSettings(CacheType.Mixed); } } public static CacheSettings WeakReferenceBased(int size) { return new CacheSettings(CacheType.Mixed) {Size = size, DefaultPriority = CachePriority.WeakReference}; } public CacheSettings LightWeight(int size) { return new CacheSettings(CacheType.Lightweight) { Size = size }; } } } ================================================ FILE: Composite/Core/Caching/CacheStatistic.cs ================================================ namespace Composite.Core.Caching { internal abstract class CacheStatistic { public virtual string CacheName { get { return string.Empty; } } public virtual int Size { get { return -1; } } public virtual int Elements { get { return -1; } } public virtual int AmountOfFlushes { get { return -1; } } public virtual int Hits { get { return -1; } } public virtual int Misses { get { return -1; } } public virtual long ApproximatedMemoryUsage { get { return -1; } } } } ================================================ FILE: Composite/Core/Caching/CacheType.cs ================================================ namespace Composite.Core.Caching { internal enum CacheType { Undefined = 0, /// /// For "lightweight" objects /// Lightweight = 1, /// /// Standard ASP .NET cache /// AspNet = 2, /// /// For "heavy" objects - based on weak references + asp.net caching /// Mixed = 3, } } ================================================ FILE: Composite/Core/Caching/Design/LightweightCache.cs ================================================ using System; namespace Composite.Core.Caching.Design { internal class LightweightCache : ICache where TValue : class { protected readonly Data.Caching.Cache _innerCache; public LightweightCache(string name, CacheSettings cacheOptions) { _innerCache = new Data.Caching.Cache(name, cacheOptions.Size); } public TValue Get(TKey key) { return _innerCache.Get(key); } public bool TryGet(TKey key, out TValue value) { value = _innerCache.Get(key); return value != null; } public void Add(TKey key, TValue value) { _innerCache.Add(key, value); } public void Add(TKey key, TValue value, CachePriority cachePriority) { Add(key, value); } public void Remove(TKey key) { _innerCache.Remove(key); } public void Clear() { _innerCache.Clear(); } public string Name { get { return _innerCache.Name; } } public CacheStatistic GetStatistic() { throw new NotImplementedException(); } } } ================================================ FILE: Composite/Core/Caching/Design/MixedCache.cs ================================================ using System; using System.Web; using System.Web.Caching; using Composite.Data.Caching; namespace Composite.Core.Caching.Design { internal class MixedCache : ICache where TValue : class { private readonly WeakRefCache _weakReferenceCache; private readonly CachePriority _defaultPriority; private readonly TimeSpan _slidingExpirationTime; private readonly bool _useAspNetCacheByDefault; private string _aspNetCachePrefix; public MixedCache(string name, CacheSettings settings) { _weakReferenceCache = new WeakRefCache(name, settings.Size); _defaultPriority = settings.DefaultPriority; _slidingExpirationTime = settings.SlidingExpritationPeriod; _aspNetCachePrefix = "MixedCache" + Name; _useAspNetCacheByDefault = _defaultPriority != CachePriority.WeakReference && _defaultPriority != CachePriority.Undefined; } public TValue Get(string key) { TValue value = _weakReferenceCache.Get(key); // "Pinping" asp.net cache if(value != null) { var aspNetCachedValue = HttpRuntime.Cache.Get(GetAspNetKey(key)) as TValue; if(_useAspNetCacheByDefault && aspNetCachedValue == null) { // Putting resurrected item back to ASP .NET cache as a "Low" priority HttpRuntime.Cache.Add(key, value, null, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.Low, null); } } return value; } public bool TryGet(string key, out TValue value) { value = Get(key); return value != null; } public void Add(string key, TValue value) { Add(key, value, _defaultPriority); } public void Add(string key, TValue value, CachePriority cachePriority) { _weakReferenceCache.Add(key, value); if(cachePriority == CachePriority.WeakReference || cachePriority == CachePriority.Undefined) { return; } CacheItemPriority aspNetCachePriority; switch (cachePriority) { case CachePriority.Low: aspNetCachePriority = CacheItemPriority.Low; break; case CachePriority.High: aspNetCachePriority = CacheItemPriority.High; break; case CachePriority.NeverExpires: aspNetCachePriority = CacheItemPriority.NotRemovable; break; default: aspNetCachePriority = CacheItemPriority.Default; break; } string aspNetKey = GetAspNetKey(key); HttpRuntime.Cache.Add(aspNetKey, value, null, DateTime.MaxValue, _slidingExpirationTime, aspNetCachePriority, null); } private string GetAspNetKey(string key) { return _aspNetCachePrefix + key; } public void Remove(string key) { _weakReferenceCache.Remove(key); HttpRuntime.Cache.Remove(GetAspNetKey(key)); } public void Clear() { _weakReferenceCache.Clear(); } public string Name { get { return _weakReferenceCache.Name; } } public CacheStatistic GetStatistic() { throw new NotImplementedException(); } } } ================================================ FILE: Composite/Core/Caching/FileRelatedDataCache.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using Composite.Core.Configuration; using Composite.Core.IO; namespace Composite.Core.Caching { /// /// Caching for the data, related to specific files. Canche invalidated when LastWriteTime property of the file changes /// /// Type of the cached data internal class FileRelatedDataCache where CachedData: class { private static readonly string LogTitle = typeof(FileRelatedDataCache<>).Name; private readonly string _cachefolder; private readonly string _cacheName; private readonly Action _serializer; private readonly Func _deserializer; /// /// Initializes a new instance of the class. /// /// Name of the folder to which cached files will be put. /// Name of the cache, used in the naming of cached files. /// To file serializer. /// From file deserializer. public FileRelatedDataCache(string cacheDirectoryName, string cacheName, Action toFileSerializer, Func fromFileDeserializer) { _cacheName = cacheName; _serializer = toFileSerializer; _deserializer = fromFileDeserializer; string path = PathUtil.Resolve(GlobalSettingsFacade.CacheDirectory); if (!string.IsNullOrEmpty(cacheDirectoryName)) { path = Path.Combine(path, cacheDirectoryName); } _cachefolder = path; if (!C1Directory.Exists(_cachefolder)) { C1Directory.CreateDirectory(_cachefolder); } } public void Add(string key, string relatedFile, CachedData cachedData) { Add(key, GetLastModifiedUtc(relatedFile), cachedData); } public void Add(string key, IEnumerable relatedFiles, CachedData cachedData) { Add(key, GetLastModifiedUtc(relatedFiles), cachedData); } private void Add(string key, DateTime lastModifiedUtc, CachedData cachedData) { string cacheFilePath = GetCacheFilePath(key); try { _serializer(cachedData, cacheFilePath); C1File.SetCreationTimeUtc(cacheFilePath, lastModifiedUtc); } catch (Exception ex) { Log.LogWarning(LogTitle, "Failed to add data to cache '{0}'. Key: '{1}'", _cacheName, key); Log.LogWarning(LogTitle, ex); } } public bool Get(string key, string relatedFile, out CachedData cachedData) { return Get(key, new[] { relatedFile }, out cachedData); } public bool Get(string key, string[] relatedFiles, out CachedData cachedData) { return Get(key, GetLastModifiedUtc(relatedFiles), out cachedData); } private static DateTime GetLastModifiedUtc(string filePath) { return C1File.GetLastWriteTimeUtc(filePath); } private static DateTime GetLastModifiedUtc(IEnumerable relatedFiles) { DateTime maxLastModifiedUtc = DateTime.MinValue; foreach (var filePath in relatedFiles) { if (!string.IsNullOrWhiteSpace(filePath) && C1File.Exists(filePath)) { DateTime lastModifiedUtc = C1File.GetLastWriteTimeUtc(filePath); if (lastModifiedUtc > maxLastModifiedUtc) { maxLastModifiedUtc = lastModifiedUtc; } } } return maxLastModifiedUtc; } private bool Get(string key, DateTime lastModifiedUtc, out CachedData cachedData) { string cacheFileName = GetCacheFilePath(key); try { if (!C1File.Exists(cacheFileName) || C1File.GetCreationTimeUtc(cacheFileName) != lastModifiedUtc) { cachedData = null; return false; } cachedData = _deserializer(cacheFileName); } catch (Exception ex) { Log.LogWarning(LogTitle, $"Failed to load cached data. Cache '{key}', file: '{cacheFileName}'"); Log.LogWarning(LogTitle, ex); cachedData = null; return false; } return true; } private string GetCacheFilePath(string key) { string nameHash = key.GetHashCode().ToString(CultureInfo.InvariantCulture); return Path.Combine(_cachefolder, _cacheName + nameHash); } } } ================================================ FILE: Composite/Core/Caching/ICache.cs ================================================ namespace Composite.Core.Caching { internal interface ICache { string Name { get; } CacheStatistic GetStatistic(); } internal interface ICache : ICache where TValue : class { TValue Get(TKey key); bool TryGet(TKey key, out TValue value); void Add(TKey key, TValue value); void Add(TKey key, TValue value, CachePriority cachePriority); void Remove(TKey key); void Clear(); } } ================================================ FILE: Composite/Core/Caching/RequestLifetimeCache.cs ================================================ using System; using System.Collections.Generic; using System.Web; using System.Runtime.Remoting.Messaging; namespace Composite.Core.Caching { // See http://piers7.blogspot.dk/2005/11/threadstatic-callcontext-and_02.html for details on HttpContext.Items vs. CallContext vs. ThreadStatic /// /// Cache for storing objects with a longevity limited to a single request. /// Objects cached here are subject to garbage collection at some point after the request has completed. /// Uses HttpContext.Items when available, otherwise . /// public static class RequestLifetimeCache { /// /// Add an item to the cache. /// /// Key for item. Used when retrieving/clearing item later. /// The item to store. public static void Add(object key, object value) { Verify.ArgumentNotNull(key, "key"); var httpContext = HttpContext.Current; if (httpContext != null) { httpContext.Items.Add(key, value); } else { FallbackCache.Add(key, value); } } /// /// Checks if the cache has the provided key. /// /// Key for item /// True when item exist in cache. Otherwise false. public static bool HasKey(object key) { Verify.ArgumentNotNull(key, "key"); var httpContext = HttpContext.Current; if (httpContext != null) { return httpContext.Items.Contains(key); } return FallbackCache.ContainsKey(key); } /// /// Returns cached item based on the provided key or null if item is not known. /// /// Key for item /// Cached item or null if not found. public static object TryGet(object key) { Verify.ArgumentNotNull(key, "key"); var context = HttpContext.Current; if (context != null) { return context.Items[key]; } return (FallbackCache.ContainsKey(key) ? FallbackCache[key] : null); } /// /// Returns cached item based on the provided key or null if item is not known. /// /// /// Key for item /// Cached item or null if not found. public static T TryGet(object key) { Verify.ArgumentNotNull(key, "key"); object result = TryGet(key); if (result != null) { return (T)result; } return default(T); } /// /// Returns cached item based on the provided key or a new instance which gets added to the cache using the key. /// The returned item is guaranteed to exist in the cache. /// /// /// Key for item /// Cached item or a new instance if not found. internal static T GetCachedOrNew(object key) where T : new() { Verify.ArgumentNotNull(key, "key"); var httpContext = HttpContext.Current; if (httpContext != null) { if (!httpContext.Items.Contains(key)) { lock (httpContext.Items) { if (!httpContext.Items.Contains(key)) { T result = new T(); httpContext.Items.Add(key, result); return result; } } } return (T)httpContext.Items[key]; } // FallbackCache is thread specific so no need to have a critical section var fallbackCache = FallbackCache; if (!fallbackCache.ContainsKey(key)) { T result = new T(); fallbackCache.Add(key, result); return result; } return (T)fallbackCache[key]; } /// /// Remove a named item from the cache. /// /// Key for item to remove public static void Remove(object key) { Verify.ArgumentNotNull(key, "key"); var context = HttpContext.Current; if (context != null) { context.Items.Remove(key); } else { FallbackCache.Remove(key); } } private static Dictionary FallbackCache { get { Dictionary fallback = CallContext.GetData("RequestLifetimeCache:Fallback") as Dictionary; if (fallback==null) { fallback = new Dictionary(); CallContext.SetData("RequestLifetimeCache:Fallback", fallback); } return fallback; } } /// [Obsolete("Should no longer be used", true)] public static void ClearAll() { } } } ================================================ FILE: Composite/Core/Collections/Generic/CastEnumerable.cs ================================================ using System.Collections; using System.Collections.Generic; namespace Composite.Core.Collections.Generic { internal sealed class CastEnumerable : IEnumerable { IEnumerable _enumerable; public CastEnumerable(IEnumerable enumerable) { _enumerable = enumerable; } IEnumerator IEnumerable.GetEnumerator() { return new CastEnumerator(_enumerable.GetEnumerator()); } IEnumerator IEnumerable.GetEnumerator() { return new CastEnumerator(_enumerable.GetEnumerator()); } } } ================================================ FILE: Composite/Core/Collections/Generic/CastEnumerator.cs ================================================ using System.Collections; using System.Collections.Generic; namespace Composite.Core.Collections.Generic { internal sealed class CastEnumerator : IEnumerator { IEnumerator _enumerator; public CastEnumerator(IEnumerator enumerator) { _enumerator = enumerator; } public T Current { get { return (T)_enumerator.Current; } } public void Dispose() { _enumerator = null; #if LeakCheck System.GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = System.Environment.StackTrace; /// ~CastEnumerator() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif object IEnumerator.Current { get { return _enumerator.Current; } } public bool MoveNext() { return _enumerator.MoveNext(); } public void Reset() { _enumerator.Reset(); } } } ================================================ FILE: Composite/Core/Collections/Generic/DictionaryExtensionMethods.cs ================================================ using System; using System.Collections.Generic; namespace Composite.Core.Collections.Generic { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DictionaryExtensionMethods { /// public static void AddDictionary(this Dictionary targetDictionary, Dictionary sourceDictionary) { if (targetDictionary == null) throw new ArgumentNullException("targetDictionary"); if (sourceDictionary == null) throw new ArgumentNullException("sourceDictionary"); foreach (KeyValuePair kvp in sourceDictionary) { targetDictionary.Add(kvp.Key, kvp.Value); } } /// public static TValue EnsureValue(this Dictionary dictionary, TKey key, Func createValue) { // TODO: Syncronization logic here??? TValue value; if (dictionary.TryGetValue(key, out value) == false) { value = createValue(); dictionary.Add(key, value); } return value; } /// public static TValue EnsureValue(this Hashtable dictionary, TKey key, Func createValue) { TValue value; if (!dictionary.TryGetValue(key, out value)) { lock(dictionary) { if (!dictionary.TryGetValue(key, out value)) { value = createValue(); dictionary.Add(key, value); } } } return value; } } } ================================================ FILE: Composite/Core/Collections/Generic/Hashset.cs ================================================ using System.Collections; using System.Collections.Generic; namespace Composite.Core.Collections.Generic { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Hashset { private readonly Hashtable _table = new Hashtable(); /// public Hashset() { } /// public Hashset(IEnumerable enumerable) { foreach (T element in enumerable) { Add(element); } } /// public bool Contains(T key) { return _table.ContainsKey(key); } /// public void Add(T key) { _table.Add(key, string.Empty); } /// public void Remove(T key) { _table.Remove(key); } /// public ICollection GetKeys() { var result = new List(); foreach(object key in _table.Keys) { result.Add((T)key); } return result; } } } ================================================ FILE: Composite/Core/Collections/Generic/Hashtable.cs ================================================ using System; using System.Collections; using System.Collections.Generic; namespace Composite.Core.Collections.Generic { /// /// Alternative to the standard Dictinary class. Allows simultaneous read operations from many threads, and add/remove/update from a single thread. /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Hashtable//: Hashtable { private readonly Hashtable _table; private static readonly object NullValue = new object(); // A value which represents "null" value private static readonly bool IsValueType = typeof (TValue).IsValueType; /// public Hashtable() { _table = new Hashtable(); } /// public Hashtable(int capacity) { _table = new Hashtable(capacity); } /// public void Add(TKey key, TValue value) { if (!IsValueType && (value == null)) { _table.Add(key, NullValue); } else { _table.Add(key, value); } } /// public TValue this[TKey key] { get { object result = _table[key]; if(result == null || result == NullValue) { return default(TValue); } return (TValue)result; } set { _table[key] = value; } } /// public bool TryGetValue(TKey key, out TValue value) { object result = _table[key]; if(result == null) { value = default(TValue); return false; } if(result == NullValue) { value = default(TValue); return true; } value = (TValue)result; return true; } /// /// Thread safe way to "get or add" a value, unlike ConcurrentDictionary, valueFactory won't be called twice for the same key. /// /// /// /// public TValue GetOrAddSync(TKey key, Func valueFactory) { TValue result; if (!TryGetValue(key, out result)) { lock (this) { if (!TryGetValue(key, out result)) { result = valueFactory(key); Add(key, result); } } } return result; } /// public bool ContainsKey(TKey key) { return _table.ContainsKey(key); } /// public void Remove(TKey key) { _table.Remove(key); } /// public void Clear() { _table.Clear(); } /// public bool Any() { return _table.Count > 0; } /// /// Getting the case collection. This operation is not thread safe. /// /// public ICollection GetKeys() { var result = new List(_table.Count); foreach(object key in _table.Keys) { result.Add((TKey)key); } return result; } /// public ICollection GetValues() { var result = new List(_table.Count); foreach (object value in _table.Values) { result.Add((TValue)value); } return result; } /// public int Count { get { return _table.Count; } } } } ================================================ FILE: Composite/Core/Collections/Generic/ReadOnlyDictionary.cs ================================================ using System; using System.Collections; using System.Collections.Generic; namespace Composite.Core.Collections.Generic { internal sealed class ReadOnlyDictionary : IDictionary { Dictionary _dictionary; public ReadOnlyDictionary(Dictionary dictionary) { if (dictionary == null) throw new ArgumentNullException("dictionary"); _dictionary = dictionary; } public void Add(TKey key, TValue value) { throw new InvalidOperationException("This is not allowed on a ReadOnlyDictionary"); } public bool ContainsKey(TKey key) { return _dictionary.ContainsKey(key); } public ICollection Keys { get { return _dictionary.Keys; } } public bool Remove(TKey key) { throw new InvalidOperationException("This is not allowed on a ReadOnlyDictionary"); } public bool TryGetValue(TKey key, out TValue value) { return _dictionary.TryGetValue(key, out value); } public ICollection Values { get { return _dictionary.Values; } } public TValue this[TKey key] { get { return _dictionary[key]; } set { throw new InvalidOperationException("This is not allowed on a ReadOnlyDictionary"); } } public void Add(KeyValuePair item) { throw new InvalidOperationException("This is not allowed on a ReadOnlyDictionary"); } public void Clear() { throw new InvalidOperationException("This is not allowed on a ReadOnlyDictionary"); } public bool Contains(KeyValuePair item) { return ((IDictionary)_dictionary).Contains(item); } public void CopyTo(KeyValuePair[] array, int arrayIndex) { ((IDictionary)_dictionary).CopyTo(array, arrayIndex); } public int Count { get { return _dictionary.Count; } } public bool IsReadOnly { get { return true; } } public bool Remove(KeyValuePair item) { throw new InvalidOperationException("This is not allowed on a ReadOnlyDictionary"); } public IEnumerator> GetEnumerator() { return _dictionary.GetEnumerator(); } IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)_dictionary).GetEnumerator(); } } } ================================================ FILE: Composite/Core/Collections/Generic/ReadOnlyList.cs ================================================ using System; using System.Collections; using System.Collections.Generic; namespace Composite.Core.Collections.Generic { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Use standard System.Collections.ObjectModel.ReadOnlyCollection")] public sealed class ReadOnlyList : IList { private List _list; /// public ReadOnlyList(List list) { if (list == null) throw new ArgumentNullException("list"); _list = list; } /// public int IndexOf(T item) { return _list.IndexOf(item); } /// public void Insert(int index, T item) { throw new InvalidOperationException("This is not allowed on a ReadOnlyList"); } /// public void RemoveAt(int index) { throw new InvalidOperationException("This is not allowed on a ReadOnlyList"); } /// public T this[int index] { get { return _list[index]; } set { throw new InvalidOperationException("This is not allowed on a ReadOnlyList"); } } /// public void Add(T item) { throw new InvalidOperationException("This is not allowed on a ReadOnlyList"); } /// public void Clear() { throw new InvalidOperationException("This is not allowed on a ReadOnlyList"); } /// public bool Contains(T item) { return _list.Contains(item); } /// public void CopyTo(T[] array, int arrayIndex) { _list.CopyTo(array, arrayIndex); } /// public int Count { get { return _list.Count; } } /// public bool IsReadOnly { get { return true; } } /// public bool Remove(T item) { throw new InvalidOperationException("This is not allowed on a ReadOnlyList"); } /// public IEnumerator GetEnumerator() { return _list.GetEnumerator(); } /// IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_list).GetEnumerator(); } } } ================================================ FILE: Composite/Core/Collections/Generic/ResourceLocker.cs ================================================ using System; using System.Threading; namespace Composite.Core.Collections.Generic { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ResourceLocker where T : class { /// public delegate void InitializerDelegate(T resources); private readonly T _resources; private readonly InitializerDelegate _initializerDelegate; private readonly bool _requireCoreReaderLock; private bool _initialized; private bool _initializing; private Exception _initializationException; private readonly object _lock = new object(); /// public ResourceLocker(T resources, InitializerDelegate initializerDelegate, bool requireCoreReaderLock) { _resources = resources; _initializerDelegate = initializerDelegate; _requireCoreReaderLock = requireCoreReaderLock; } /// public ResourceLocker(T resources, InitializerDelegate initializerDelegate): this(resources, initializerDelegate, true) { } /// public T Resources { get { if (!_initialized) { Initialize(); } if (_initializationException != null) { throw new InvalidOperationException("Error initializing resources", _initializationException); } return _resources; } } /// public bool IsInitialized => _initialized; /// public void Initialize() { if (_initialized) return; IDisposable globalReaderLock = null; try { if(_requireCoreReaderLock) { globalReaderLock = GlobalInitializerFacade.CoreNotLockedScope; } lock (_lock) { Verify.IsFalse(_initializing, "Initialize is already being executed on this thread! Please examine the stack!"); if (_initialized) return; _initializing = true; _initializationException = null; try { _initializerDelegate(_resources); } catch (Exception exception) { _initializationException = exception; throw; } finally { _initialized = true; _initializing = false; } } } finally { globalReaderLock?.Dispose(); } } /// public IDisposable Locker => new ResourceLockerToken(this); /// public IDisposable ReadLocker => new ResourceLockerToken(this); /// public void ResetInitialization() { lock (_lock) { _initialized = false; } } private void TryEnterLock(int timeoutInMilliseconds, ref bool success) { Monitor.TryEnter(_lock, timeoutInMilliseconds, ref success); } private void Exit() { Monitor.Exit(_lock); } private sealed class ResourceLockerToken : IDisposable { private readonly ResourceLocker _resourceLocker; internal ResourceLockerToken(ResourceLocker resourceLocker) { _resourceLocker = resourceLocker ?? throw new ArgumentNullException(nameof(resourceLocker)); int tires = 120; bool success = false; while (!success && tires-- > 0) { IDisposable coreLock = null; try { if (_resourceLocker._requireCoreReaderLock) { coreLock = GlobalInitializerFacade.CoreNotLockedScope; } _resourceLocker.TryEnterLock(500, ref success); } finally { coreLock?.Dispose(); } if (!success) { Thread.Sleep(1); } } if (!success) { throw new TimeoutException("Failed to obtain a required resource lock. Aborting to avoid system deadlocks."); } } public void Dispose() { _resourceLocker.Exit(); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~ResourceLockerToken() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } } ================================================ FILE: Composite/Core/Collections/INamespaceTreeBuilderLeafInfo.cs ================================================ namespace Composite.Core.Collections { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface INamespaceTreeBuilderLeafInfo { /// string Name { get; } /// string Namespace { get; } } } ================================================ FILE: Composite/Core/Collections/NamespaceTreeBuilder.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Core.Extensions; namespace Composite.Core.Collections { internal sealed class NamespaceTreeBuilder { private NamespaceTreeBuilderFolder _rootFolder; private char _namespaceSeparator; public NamespaceTreeBuilder(IEnumerable namespaceTreeBuilderInfos) : this(namespaceTreeBuilderInfos, '.') { } public NamespaceTreeBuilder(IEnumerable namespaceTreeBuilderInfos, char namespaceSeparator) { if (namespaceTreeBuilderInfos == null) throw new ArgumentNullException("namespaceTreeBuilderInfos"); _namespaceSeparator = namespaceSeparator; _rootFolder = new NamespaceTreeBuilderFolder("", ""); foreach (INamespaceTreeBuilderLeafInfo namespaceTreeBuilderInfo in namespaceTreeBuilderInfos) { NamespaceTreeBuilderFolder folderNode = GetOrCreateFolder(namespaceTreeBuilderInfo.Namespace); folderNode.Leafs.Add(namespaceTreeBuilderInfo); } } public NamespaceTreeBuilderFolder RootFolder { get { return _rootFolder; } } public NamespaceTreeBuilderFolder GetFolder(string namespaceName) { if (namespaceName == null) throw new ArgumentNullException("namespaceName"); if (namespaceName.IsCorrectNamespace(_namespaceSeparator) == false) throw new ArgumentException(string.Format("The namespace '{0}' is not correctly formattet", namespaceName)); NamespaceTreeBuilderFolder currentNode = _rootFolder; string[] namespaceComponents = namespaceName.Split(_namespaceSeparator); foreach (string namespaceComponent in namespaceComponents.Where(s => s != "")) { currentNode = currentNode.SubFolders.Where(n => n.Name == namespaceComponent).FirstOrDefault(); if (currentNode == null) { return null; } } return currentNode; } public NamespaceTreeBuilderFolder FindFolder(Func predicate) { return FindFolder(_rootFolder, predicate); } private NamespaceTreeBuilderFolder FindFolder(NamespaceTreeBuilderFolder currentFolder, Func predicate) { if (predicate(currentFolder)) return currentFolder; foreach (NamespaceTreeBuilderFolder subFolder in currentFolder.SubFolders) { NamespaceTreeBuilderFolder foundFolder = FindFolder(subFolder, predicate); if (foundFolder != null) { return foundFolder; } } return null; } private NamespaceTreeBuilderFolder GetOrCreateFolder(string namespaceName) { if (namespaceName.IsCorrectNamespace(_namespaceSeparator) == false) throw new ArgumentException(string.Format("The namespace '{0}' is not correctly formattet", namespaceName != null ? namespaceName : "(null)")); string[] namespaceComponents = namespaceName.Split(_namespaceSeparator); if ((namespaceComponents.Length == 1) && (namespaceComponents[0] == "")) { return _rootFolder; } NamespaceTreeBuilderFolder currentNode = _rootFolder; string currentNamespace = ""; foreach (string namespaceComponent in namespaceComponents) { NamespaceTreeBuilderFolder node = currentNode.SubFolders.Where(n => n.Name == namespaceComponent).FirstOrDefault(); if (node == null) { node = new NamespaceTreeBuilderFolder(namespaceComponent, currentNamespace); currentNode.SubFolders.Add(node); } if (currentNamespace == "") { currentNamespace = namespaceComponent; } else { currentNamespace = string.Format("{0}{1}{2}", currentNamespace, _namespaceSeparator, namespaceComponent); } currentNode = node; } return currentNode; } } } ================================================ FILE: Composite/Core/Collections/NamespaceTreeBuilderFolder.cs ================================================ using System.Diagnostics; using System.Collections.Generic; namespace Composite.Core.Collections { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DebuggerDisplay("Name = {Name}, Namespace = {Namespace}")] public sealed class NamespaceTreeBuilderFolder { internal NamespaceTreeBuilderFolder(string name, string namespaceName) { this.Name = name; this.Namespace = namespaceName; this.Leafs = new List(); this.SubFolders = new List(); } /// public string Name { get; private set; } /// public string Namespace { get; private set; } /// public List Leafs { get; private set; } /// public List SubFolders { get; private set; } } } ================================================ FILE: Composite/Core/Configuration/AppCodeTypeNotFoundConfigurationException.cs ================================================ using System; namespace Composite.Core.Configuration { internal class AppCodeTypeNotFoundConfigurationException : Exception // Does not inherit ConfigurationErrorsException/ConfigurationException since that would lead to loosing exception type // during rethow by System.Configuration classes { public AppCodeTypeNotFoundConfigurationException(string message) : base(message) { } } } ================================================ FILE: Composite/Core/Configuration/BuildinPlugins/GlobalSettingsProvider/BuildinCacheSettings.cs ================================================ namespace Composite.Core.Configuration.BuildinPlugins.GlobalSettingsProvider { internal class BuildinCacheSettings: ICacheSettings { public BuildinCacheSettings(string name, bool enabled, int size) { Name = name; Enabled = enabled; Size = size; } public string Name { get; set; } public bool Enabled { get; set; } public int Size { get; set; } } } ================================================ FILE: Composite/Core/Configuration/BuildinPlugins/GlobalSettingsProvider/BuildinCachingSettings.cs ================================================ using System.Collections.Generic; namespace Composite.Core.Configuration.BuildinPlugins.GlobalSettingsProvider { internal class BuildinCachingSettings: ICachingSettings { private bool _enabled; private IEnumerable _cacheSettingsCollection = new ICacheSettings[0]; public bool Enabled { get { return _enabled; } set { _enabled = value; } } public IEnumerable Caches { get { return _cacheSettingsCollection; } set { _cacheSettingsCollection = value; } } } } ================================================ FILE: Composite/Core/Configuration/BuildinPlugins/GlobalSettingsProvider/BuildinGlobalSettingsProvider.cs ================================================ using System; using System.Collections.Generic; using System.Threading; using Composite.Core.Configuration.Plugins.GlobalSettingsProvider; namespace Composite.Core.Configuration.BuildinPlugins.GlobalSettingsProvider { internal sealed class BuildinGlobalSettingsProvider : IGlobalSettingsProvider { private string _applicationName = "C1 CMS"; private string _applicationShortName = "C1"; private string _brandedVersionAssemblySource = "Composite"; private string _configurationDirectory = "~"; private string _generatedAssembliesDirectory = "~/GeneratedAssemblies"; private string _serializedWorkflowsDirectory = "~"; private string _appCodeDirectory = "App_Code"; private string _binDirectory = "~"; private string _tempDirectory = "~/Temp"; private string _cacheDirectory = "~/Cache/Startup"; private string _packageDirectory = "~/Packages"; private string _autoPackageInstallDirectory = "~/AutoInstallPackages"; private string _treeDefinitionsDirectory = "~/TreeDefinitions"; private string _pageTemplateFeaturesDirectory = "~/PageTemplateFeaturesDirectory"; private string _dataMetaDataDirectory = "~/DataMetaData"; private string _inlineCSharpFunctionDirectory = "~/InlineCSharpFunctions"; private string _packageLicenseDirectory = "~/PackageLicenses"; private readonly ICachingSettings _cachingSettings = new BuildinCachingSettings(); private readonly List _nonProbableAssemblyNames = new List(); private readonly int _consoleMessageQueueSecondToLive = (int) TimeSpan.FromMinutes(10).TotalSeconds; private bool _enableDataTypesAutoUpdate = false; private bool _broadcastConsoleElementChanges = true; private bool _prettifyPublicMarkup = true; private bool _prettifyRenderFunctionExceptions = true; private bool _functionPreviewEnabled = false; private TimeZoneInfo _timezone = TimeZoneInfo.Local; public string ApplicationName => _applicationName; public string ApplicationShortName => _applicationShortName; public string BrandedVersionAssemblySource => _brandedVersionAssemblySource; public string DefaultCultureName => Thread.CurrentThread.CurrentCulture.Name; public string ConfigurationDirectory { get { return string.Format("{0}/{1}", _configurationDirectory, Guid.NewGuid()); } } public string GeneratedAssembliesDirectory => _generatedAssembliesDirectory; public string SerializedWorkflowsDirectory { get { return string.Format("{0}/{1}", _serializedWorkflowsDirectory, Guid.NewGuid()); } } public string AppCodeDirectory => _appCodeDirectory; public string BinDirectory => _binDirectory; public string TempDirectory => _tempDirectory; public string CacheDirectory => _cacheDirectory; public string PackageDirectory => _packageDirectory; public string AutoPackageInstallDirectory => _autoPackageInstallDirectory; public string TreeDefinitionsDirectory => _treeDefinitionsDirectory; public string PageTemplateFeaturesDirectory => _pageTemplateFeaturesDirectory; public string DataMetaDataDirectory => _dataMetaDataDirectory; public string InlineCSharpFunctionDirectory => _inlineCSharpFunctionDirectory; public string PackageLicenseDirectory => _packageLicenseDirectory; public IEnumerable NonProbableAssemblyNames => _nonProbableAssemblyNames; public int ConsoleMessageQueueItemSecondToLive => _consoleMessageQueueSecondToLive; public bool EnableDataTypesAutoUpdate => _enableDataTypesAutoUpdate; public bool BroadcastConsoleElementChanges => _broadcastConsoleElementChanges; public string AutoCreatedAdministratorUserName => null; public string SerializedConsoleMessagesDirectory => $"{_serializedWorkflowsDirectory}/{Guid.NewGuid()}"; public string WorkflowTimeout => "7.00:00:00"; public string ConsoleTimeout => "00:01:00"; public bool OnlyTranslateWhenApproved => false; public bool AllowChildPagesTranslationWithoutParent => false; public ICachingSettings Caching => _cachingSettings; public int ImageQuality => 80; public bool PrettifyPublicMarkup => _prettifyPublicMarkup; public bool PrettifyRenderFunctionExceptions => _prettifyRenderFunctionExceptions; public bool FunctionPreviewEnabled => _functionPreviewEnabled; public TimeZoneInfo TimeZone => _timezone; public bool InheritGlobalReadPermissionOnHiddenPerspectives => false; public bool OmitAspNetWebFormsSupport => false; public bool ProtectResizedImagesWithHash => false; } } ================================================ FILE: Composite/Core/Configuration/C1Configuration.cs ================================================ using System.Configuration; using Composite.Core.Implementation; namespace Composite.Core.Configuration { /// /// This class is a almost one to one version of System.Configuration.Configuration. Using this implementation instead /// of System.Configuration.Configuration, will ensure that your code will work both on Standard Windows deployment /// and Windows Azure deployment. /// See System.Configuration.Configuration for more documentation on the methods of this class. /// See . /// public class C1Configuration : ImplementationContainer { /// /// Creates a C1Configuration /// /// Path to configuration file. public C1Configuration(string path) : base(() => ImplementationFactory.CurrentFactory.CreateC1Configuration(path)) { } /// /// Gets the path to the configuration file. /// public string FilePath { get { return this.Implementation.FilePath; } } /// /// Returns true if the configuration file exists. /// public bool HasFile { get { return this.Implementation.HasFile; } } /// /// Returns the app setttings section. /// public AppSettingsSection AppSettings { get { return this.Implementation.AppSettings; } } /// /// Returns the connection string section. /// public ConnectionStringsSection ConnectionStrings { get { return this.Implementation.ConnectionStrings; } } /// /// Returns the configuration sections. /// public ConfigurationSectionCollection Sections { get { return this.Implementation.Sections; } } /// /// Returns the configuration section group. /// public ConfigurationSectionGroup RootSectionGroup { get { return this.Implementation.RootSectionGroup; } } /// /// Returns the configuration slection groups. /// public ConfigurationSectionGroupCollection SectionGroups { get { return this.Implementation.SectionGroups; } } /// /// Gets a named configuration section. /// /// Name of section to get. /// Returns the configuration section. public ConfigurationSection GetSection(string sectionName) { return this.Implementation.GetSection(sectionName); } /// /// Gets a named configuration section group. /// /// Name of configuration section group to get. /// Returns the configuration section group. public ConfigurationSectionGroup GetSectionGroup(string sectionGroupName) { return this.Implementation.GetSectionGroup(sectionGroupName); } /// /// Saves the configuration. /// public void Save() { this.Implementation.Save(); } /// /// Saves the configuration. /// /// Save mode to use when saving the configuration. public void Save(ConfigurationSaveMode saveMode) { this.Implementation.Save(saveMode); } /// /// Saves the configuration. /// /// Save mode to use when saving the configuration. /// Saves all sections, even non touched. public void Save(ConfigurationSaveMode saveMode, bool forceSaveAll) { this.Implementation.Save(saveMode, forceSaveAll); } /// /// Saves the configuration to a new file. /// /// Path to new configuration filename. public void SaveAs(string filename) { this.Implementation.SaveAs(filename); } /// /// Saves the configuration to a new file. /// /// Path to new configuration filename. /// Save mode to use when saving the configuration. public void SaveAs(string filename, ConfigurationSaveMode saveMode) { this.Implementation.SaveAs(filename, saveMode); } /// /// Saves the configuration to a new file. /// /// Path to new configuration filename. /// Save mode to use when saving the configuration. /// Saves all sections, even non touched. public void SaveAs(string filename, ConfigurationSaveMode saveMode, bool forceSaveAll) { this.Implementation.SaveAs(filename, saveMode, forceSaveAll); } } } ================================================ FILE: Composite/Core/Configuration/Configuration.cs ================================================ using System.Configuration; namespace Composite.Core.Configuration { /* /// /// This should be a part of the I/O layer /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class C1Configuration { System.Configuration.Configuration _configuration; [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationManagerClass:DoNotUseConfigurationManagerClass", Justification = "The implementation may use it")] public static C1Configuration Load(string path) { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = path; System.Configuration.Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); return new C1Configuration(configuration); } protected C1Configuration(System.Configuration.Configuration configuration) { _configuration = configuration; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "The implementation may use it")] public ConfigurationSectionCollection Sections { get { return _configuration.Sections; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "The implementation may use it")] public ConfigurationSection GetSection(string sectionName) { return _configuration.GetSection(sectionName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "The implementation may use it")] public void Save() { _configuration.Save(); } }*/ } ================================================ FILE: Composite/Core/Configuration/ConfigurationServices.cs ================================================ using System; using System.Configuration; using System.Xml; using System.Xml.Linq; using System.Xml.Xsl; using Composite.C1Console.Events; using Composite.Core.IO; using Composite.Core.Xml; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using System.IO; namespace Composite.Core.Configuration { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ConfigurationServices { private static IConfigurationSource _configurationSource = null; private static string _fileConfigurationSourcePath; private static readonly object _lock = new object(); /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass", Justification = "The configuration is needed to boot the IO layer, so we cant use it here")] static ConfigurationServices() { if (RuntimeInformation.IsUnittest) { _configurationSource = ConfigurationSourceFactory.Create(); return; } _fileConfigurationSourcePath = GetFileConfigurationSourcePath(); Verify.IsNotNull(_fileConfigurationSourcePath, "Configuration file is not defined"); FileAttributes fileAttributes = File.GetAttributes(_fileConfigurationSourcePath); if ((fileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { fileAttributes ^= FileAttributes.ReadOnly; File.SetAttributes(_fileConfigurationSourcePath, fileAttributes); } _configurationSource = new FileConfigurationSource(_fileConfigurationSourcePath); } /// public static IConfigurationSource ConfigurationSource { get { return _configurationSource; } set { // Unit test code only! // if (RuntimeInformation.IsUnittest == false) throw new InvalidOperationException("Intented for unit testing only"); lock (_lock) { _configurationSource = value; string fileConfigurationSourcePath = null; if (_configurationSource != null) { fileConfigurationSourcePath = GetFileConfigurationSourcePath(); } if (fileConfigurationSourcePath != null) { FileUtils.RemoveReadOnly(fileConfigurationSourcePath); } // GlobalEventSystemFacade.FlushTheSystem(); _fileConfigurationSourcePath = fileConfigurationSourcePath; } } } internal static string FileConfigurationSourcePath { get { if ((_configurationSource != null) && (_fileConfigurationSourcePath == null)) { throw new InvalidOperationException("Unable to locate the ConfigurationSourceSection"); } return _fileConfigurationSourcePath; } set { if (Composite.RuntimeInformation.IsUnittest == false) throw new InvalidOperationException("FileConfigurationSourcePath set is for unit testing only."); _fileConfigurationSourcePath = value; } } /// public static void SaveConfigurationSection(string sectionName, ConfigurationSection configurationSection) { using (GlobalInitializerFacade.CoreLockScope) { lock (_lock) { string tempFilePath = ConfigurationServices.TempRandomConfigFilePath; C1File.Copy(FileConfigurationSourcePath, tempFilePath); FileConfigurationParameter configurationParameter = new FileConfigurationParameter(tempFilePath); ConfigurationServices.ConfigurationSource.Add(configurationParameter, sectionName, configurationSection); // Kill monitoring of file changes: // FileConfigurationSource.ResetImplementation(ConfigurationServices.FileConfigurationSourcePath, false); C1File.Copy(tempFilePath, ConfigurationServices.FileConfigurationSourcePath, true); DeleteTempConfigurationFile(tempFilePath); _configurationSource = new FileConfigurationSource(ConfigurationServices.FileConfigurationSourcePath); // Kill monitoring of file changes: // FileConfigurationSource.ResetImplementation(ConfigurationServices.FileConfigurationSourcePath, false); } } } /// /// Transforms the current configuration file based on the supplied XSLT document. The resulting /// configuration document is validated and no errors are tollerated. Configurationerrors are handled /// as exceptions. /// /// XSLT document to apply to the configuration document /// When true the configuration transformation will only be validated, not executed. When false, the configuration change will be persisted. public static void TransformConfiguration(XDocument xsltDocument, bool simulationOnly) { using (GlobalInitializerFacade.CoreLockScope) { lock (_lock) { XslCompiledTransform transformer = new XslCompiledTransform(); XDocument resultDocument = new XDocument(); using (XmlReader reader = xsltDocument.CreateReader()) { transformer.Load(reader); } using (XmlWriter writer = resultDocument.CreateWriter()) { transformer.Transform(ConfigurationServices.FileConfigurationSourcePath, writer); } ValidateConfigurationFile(resultDocument); if (simulationOnly == false) { // Kill monitoring of file changes: // FileConfigurationSource.ResetImplementation(ConfigurationServices.FileConfigurationSourcePath, false); resultDocument.SaveToFile(ConfigurationServices.FileConfigurationSourcePath); _configurationSource = new FileConfigurationSource(ConfigurationServices.FileConfigurationSourcePath); // Kill monitoring of file changes: // FileConfigurationSource.ResetImplementation(ConfigurationServices.FileConfigurationSourcePath, false); } } } } /// public static void TransformConfiguration(Func transformer) { using (GlobalInitializerFacade.CoreLockScope) { lock (_lock) { XDocument document = XDocumentUtils.Load(ConfigurationServices.FileConfigurationSourcePath); if (transformer(document)) { ValidateConfigurationFile(document); // Kill monitoring of file changes: // FileConfigurationSource.ResetImplementation(ConfigurationServices.FileConfigurationSourcePath, false); document.SaveToFile(ConfigurationServices.FileConfigurationSourcePath); _configurationSource = new FileConfigurationSource(ConfigurationServices.FileConfigurationSourcePath); // Kill monitoring of file changes: // FileConfigurationSource.ResetImplementation(ConfigurationServices.FileConfigurationSourcePath, false); GlobalEventSystemFacade.ShutDownTheSystem(); } } } } private static void ValidateConfigurationFile(XDocument resultDocument) { string tempValidationFilePath = TempRandomConfigFilePath; resultDocument.SaveToFile(tempValidationFilePath); try { IConfigurationSource testConfigSource = new FileConfigurationSource(tempValidationFilePath); foreach (XElement sectionElement in resultDocument.Root.Element("configSections").Elements()) { if (sectionElement.Attribute("name") != null) { string sectionName = sectionElement.Attribute("name").Value; try { testConfigSource.GetSection(sectionName); } catch (ConfigurationErrorsException exception) { if(exception.InnerException != null && exception.InnerException is AppCodeTypeNotFoundConfigurationException) { // App_Code classes aren't compiled during package installation, therefore related exceptions are ignored } else { throw; } } } } DeleteTempConfigurationFile(tempValidationFilePath); } catch (Exception) { DeleteTempConfigurationFile(tempValidationFilePath); throw; } } private static string TempRandomConfigFilePath { get { return string.Format("{0}.test.{1}.xml", ConfigurationServices.FileConfigurationSourcePath, Guid.NewGuid()); } } private static void DeleteTempConfigurationFile(string tempValidationFilePath) { try { // FileConfigurationSource.ResetImplementation(tempValidationFilePath, false); //turn file monitoring off C1File.Delete(tempValidationFilePath); } catch (Exception) { } } private static string GetFileConfigurationSourcePath() { // Not using the web.config in order not to make solution depend on specific version of Microsoft Enterprice Library return PathUtil.Resolve("~/App_Data/Composite/Composite.config"); //lock (_lock) //{ // ConfigurationSourceSection configurationSourceSection = GetActiveConfigurationSourceSection(); // if (configurationSourceSection != null) // { // string systemSourceName = configurationSourceSection.SelectedSource; // ConfigurationSourceElement objectConfiguration = configurationSourceSection.Sources.Get(systemSourceName); // if (objectConfiguration != null) // { // FileConfigurationSourceElement fileConfigurationInfo = objectConfiguration as FileConfigurationSourceElement; // if (fileConfigurationInfo == null) throw new InvalidOperationException("Expected EntLib configuration source configuration to be of type " + typeof(FileConfigurationSourceElement).Name); // string relativePath = fileConfigurationInfo.FilePath; // string tildePath = (Path.IsPathRooted(relativePath) ? "~" + relativePath : "~/" + relativePath); // return PathUtil.Resolve(tildePath); // } // } // return null; //} } //private static ConfigurationSourceSection GetActiveConfigurationSourceSection() //{ // ConfigurationSourceSection configurationSourceSection = ConfigurationSourceSection.GetConfigurationSourceSection(); // if (configurationSourceSection == null && ConfigurationSource != null) // { // configurationSourceSection = (ConfigurationSourceSection)ConfigurationSource.GetSection(ConfigurationSourceSection.SectionName); // } // return configurationSourceSection; //} } } ================================================ FILE: Composite/Core/Configuration/FileConfigurationSource.cs ================================================ //=============================================================================== // Microsoft patterns & practices Enterprise Library // Core //=============================================================================== // Copyright © Microsoft Corporation. All rights reserved. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. //=============================================================================== using System; using System.Collections.Generic; using System.IO; using Composite.Core.IO; namespace Composite.Core.Configuration { /// /// This should be a part of the I/O layer /// internal class FileConfigurationSource : Microsoft.Practices.EnterpriseLibrary.Common.Configuration.IConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common.Configuration.IProtectedConfigurationSource { private static Dictionary implementationByFilepath = new Dictionary(StringComparer.OrdinalIgnoreCase); private string configurationFilepath; private static object lockObject = new object(); [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass", Justification = "The configuration is needed to boot the IO layer, so we cant use it here")] public FileConfigurationSource(string configurationFilepath) { if (string.IsNullOrEmpty(configurationFilepath)) throw new ArgumentNullException("configurationFilepath"); this.configurationFilepath = RootConfigurationFilePath(configurationFilepath); if (!File.Exists(this.configurationFilepath)) throw new FileNotFoundException("File not found", this.configurationFilepath); EnsureImplementation(this.configurationFilepath); } public System.Configuration.ConfigurationSection GetSection(string sectionName) { return implementationByFilepath[configurationFilepath].GetSection(sectionName); } public void AddSectionChangeHandler(string sectionName, Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationChangedEventHandler handler) { implementationByFilepath[configurationFilepath].AddSectionChangeHandler(sectionName, handler); } public void RemoveSectionChangeHandler(string sectionName, Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationChangedEventHandler handler) { implementationByFilepath[configurationFilepath].RemoveSectionChangeHandler(sectionName, handler); } public void Save(string fileName, string section, System.Configuration.ConfigurationSection configurationSection) { ValidateArgumentsAndFileExists(fileName, section, configurationSection); InternalSave(fileName, section, configurationSection, string.Empty); } public void Save(string fileName, string section, System.Configuration.ConfigurationSection configurationSection, string protectionProvider) { ValidateArgumentsAndFileExists(fileName, section, configurationSection); if (string.IsNullOrEmpty(protectionProvider)) throw new ArgumentNullException("protectionProvider"); InternalSave(fileName, section, configurationSection, protectionProvider); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "The implementation may use it")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationManagerClass:DoNotUseConfigurationManagerClass", Justification = "The implementation may use it")] private void InternalSave(string fileName, string section, System.Configuration.ConfigurationSection configurationSection, string protectionProvider) { System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap(); fileMap.ExeConfigFilename = fileName; System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None); if (typeof(System.Configuration.ConnectionStringsSection) == configurationSection.GetType()) { config.Sections.Remove(section); UpdateConnectionStrings(section, configurationSection, config, protectionProvider); } else if (typeof(System.Configuration.AppSettingsSection) == configurationSection.GetType()) { UpdateApplicationSettings(section, configurationSection, config, protectionProvider); } else { config.Sections.Remove(section); config.Sections.Add(section, configurationSection); ProtectConfigurationSection(configurationSection, protectionProvider); } config.Save(); UpdateImplementation(fileName); } private static void ProtectConfigurationSection(System.Configuration.ConfigurationSection configurationSection, string protectionProvider) { if (!string.IsNullOrEmpty(protectionProvider)) { if(configurationSection.SectionInformation.ProtectionProvider == null || configurationSection.SectionInformation.ProtectionProvider.Name != protectionProvider) { configurationSection.SectionInformation.ProtectSection(protectionProvider); } } else { if(configurationSection.SectionInformation.ProtectionProvider != null) { configurationSection.SectionInformation.UnprotectSection(); } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "The implementation may use it")] private void UpdateApplicationSettings(string section, System.Configuration.ConfigurationSection configurationSection, System.Configuration.Configuration config, string protectionProvider) { System.Configuration.AppSettingsSection current = config.AppSettings; if (current == null) { config.Sections.Add(section, configurationSection); ProtectConfigurationSection(configurationSection, protectionProvider); } else { System.Configuration.AppSettingsSection newApplicationSettings = configurationSection as System.Configuration.AppSettingsSection; if (current.File != newApplicationSettings.File) { current.File = newApplicationSettings.File; } List newKeys = new List(newApplicationSettings.Settings.AllKeys); List currentKeys = new List(current.Settings.AllKeys); foreach (string keyInCurrent in currentKeys) { if (!newKeys.Contains(keyInCurrent)) { current.Settings.Remove(keyInCurrent); } } foreach (string newKey in newKeys) { if (!currentKeys.Contains(newKey)) { current.Settings.Add(newKey, newApplicationSettings.Settings[newKey].Value); } else { if (current.Settings[newKey].Value != newApplicationSettings.Settings[newKey].Value) { current.Settings[newKey].Value = newApplicationSettings.Settings[newKey].Value; } } } ProtectConfigurationSection(current, protectionProvider); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "The implementation may use it")] private void UpdateConnectionStrings(string section, System.Configuration.ConfigurationSection configurationSection, System.Configuration.Configuration config, string protectionProvider) { System.Configuration.ConnectionStringsSection current = config.ConnectionStrings; if (current == null) { config.Sections.Add(section, configurationSection); ProtectConfigurationSection(configurationSection, protectionProvider); } else { System.Configuration.ConnectionStringsSection newConnectionStrings = (System.Configuration.ConnectionStringsSection)configurationSection; foreach (System.Configuration.ConnectionStringSettings connectionString in newConnectionStrings.ConnectionStrings) { if (current.ConnectionStrings[connectionString.Name] == null) { current.ConnectionStrings.Add(connectionString); } } ProtectConfigurationSection(current, protectionProvider); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "The implementation may use it")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationManagerClass:DoNotUseConfigurationManagerClass", Justification = "The implementation may use it")] public void Remove(string fileName, string section) { if (string.IsNullOrEmpty(fileName)) throw new ArgumentNullException("fileName"); if (string.IsNullOrEmpty(section)) throw new ArgumentNullException("section"); System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap(); fileMap.ExeConfigFilename = fileName; System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None); if (config.Sections.Get(section) != null) { config.Sections.Remove(section); config.Save(); UpdateImplementation(fileName); } } public void Add(Microsoft.Practices.EnterpriseLibrary.Common.Configuration.IConfigurationParameter saveParameter, string sectionName, System.Configuration.ConfigurationSection configurationSection) { Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationParameter parameter = saveParameter as Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationParameter; if (null == parameter) throw new ArgumentNullException("saveParameter"); Save(parameter.FileName, sectionName, configurationSection); } public void Add(Microsoft.Practices.EnterpriseLibrary.Common.Configuration.IConfigurationParameter saveParameter, string sectionName, System.Configuration.ConfigurationSection configurationSection, string protectionProviderName) { Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationParameter parameter = saveParameter as Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationParameter; if (null == parameter) throw new ArgumentNullException("saveParameter"); Save(parameter.FileName, sectionName, configurationSection, protectionProviderName); } public void Remove(Microsoft.Practices.EnterpriseLibrary.Common.Configuration.IConfigurationParameter removeParameter, string sectionName) { Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationParameter parameter = removeParameter as Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationParameter; if (null == parameter) throw new ArgumentNullException("saveParameter"); Remove(parameter.FileName, sectionName); } public static void ResetImplementation(string configurationFilepath, bool refreshing) { string rootedConfigurationFilepath = RootConfigurationFilePath(configurationFilepath); FileConfigurationSourceImplementation currentImplementation = null; implementationByFilepath.TryGetValue(rootedConfigurationFilepath, out currentImplementation); implementationByFilepath[rootedConfigurationFilepath] = new FileConfigurationSourceImplementation(rootedConfigurationFilepath, refreshing); if (currentImplementation != null) { currentImplementation.Dispose(); } } internal Microsoft.Practices.EnterpriseLibrary.Common.Configuration.BaseFileConfigurationSourceImplementation Implementation { get { return implementationByFilepath[configurationFilepath]; } } internal static Microsoft.Practices.EnterpriseLibrary.Common.Configuration.BaseFileConfigurationSourceImplementation GetImplementation(string configurationFilepath) { string rootedConfigurationFilepath = RootConfigurationFilePath(configurationFilepath); EnsureImplementation(rootedConfigurationFilepath); return implementationByFilepath[rootedConfigurationFilepath]; } private static void ValidateArgumentsAndFileExists(string fileName, string section, System.Configuration.ConfigurationSection configurationSection) { if (string.IsNullOrEmpty(fileName)) throw new ArgumentNullException("fileName"); if (string.IsNullOrEmpty(section)) throw new ArgumentNullException("section"); if (null == configurationSection) throw new ArgumentNullException("configurationSection"); if (!C1File.Exists(fileName)) throw new FileNotFoundException(string.Format("", "Resources.ExceptionConfigurationFileNotFound", section), fileName); } private static string RootConfigurationFilePath(string configurationFile) { string rootedConfigurationFile = (string)configurationFile.Clone(); if (!Path.IsPathRooted(rootedConfigurationFile)) { rootedConfigurationFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, rootedConfigurationFile); } return rootedConfigurationFile; } private static void EnsureImplementation(string rootedConfigurationFile) { if (!implementationByFilepath.ContainsKey(rootedConfigurationFile)) { lock (lockObject) { if (!implementationByFilepath.ContainsKey(rootedConfigurationFile)) { FileConfigurationSourceImplementation implementation = new FileConfigurationSourceImplementation(rootedConfigurationFile); implementationByFilepath.Add(rootedConfigurationFile, implementation); } } } } private static void UpdateImplementation(string fileName) { FileConfigurationSourceImplementation implementation; implementationByFilepath.TryGetValue(fileName, out implementation); if (implementation != null) { implementation.UpdateCache(); } } } } ================================================ FILE: Composite/Core/Configuration/FileConfigurationSourceImplementation.cs ================================================ //=============================================================================== // Microsoft patterns & practices Enterprise Library // Core //=============================================================================== // Copyright © Microsoft Corporation. All rights reserved. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. //=============================================================================== using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using System.Collections.Generic; namespace Composite.Core.Configuration { /// /// This should be a part of the I/O layer /// internal class FileConfigurationSourceImplementation : Microsoft.Practices.EnterpriseLibrary.Common.Configuration.BaseFileConfigurationSourceImplementation { private string configurationFilepath; private System.Configuration.ExeConfigurationFileMap fileMap; private System.Configuration.Configuration cachedConfiguration; private object cachedConfigurationLock = new object(); public FileConfigurationSourceImplementation(string configurationFilepath) : this(configurationFilepath, true) { } public FileConfigurationSourceImplementation(string configurationFilepath, bool refresh) : base(configurationFilepath, refresh) { this.configurationFilepath = configurationFilepath; this.fileMap = new System.Configuration.ExeConfigurationFileMap(); fileMap.ExeConfigFilename = configurationFilepath; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "The implementation may use it")] public override System.Configuration.ConfigurationSection GetSection(string sectionName) { System.Configuration.Configuration configuration = GetConfiguration(); System.Configuration.ConfigurationSection configurationSection; try { configurationSection = configuration.GetSection(sectionName) as System.Configuration.ConfigurationSection; } catch { // retry once UpdateCache(); configuration = GetConfiguration(); configurationSection = configuration.GetSection(sectionName) as System.Configuration.ConfigurationSection; } SetConfigurationWatchers(sectionName, configurationSection); return configurationSection; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "The implementation may use it")] protected override void RefreshAndValidateSections(IDictionary localSectionsToRefresh, IDictionary externalSectionsToRefresh, out ICollection sectionsToNotify, out IDictionary sectionsWithChangedConfigSource) { UpdateCache(); sectionsToNotify = new List(); sectionsWithChangedConfigSource = new Dictionary(); // refresh local sections and determine what to do. foreach (KeyValuePair sectionMapping in localSectionsToRefresh) { System.Configuration.ConfigurationSection section = cachedConfiguration.GetSection(sectionMapping.Key) as System.Configuration.ConfigurationSection; string refreshedConfigSource = section != null ? section.SectionInformation.ConfigSource : NullConfigSource; if (!sectionMapping.Value.Equals(refreshedConfigSource)) { sectionsWithChangedConfigSource.Add(sectionMapping.Key, refreshedConfigSource); } // notify anyway, since it might have been updated. sectionsToNotify.Add(sectionMapping.Key); } // refresh external sections and determine what to do. foreach (KeyValuePair sectionMapping in externalSectionsToRefresh) { System.Configuration.ConfigurationSection section = cachedConfiguration.GetSection(sectionMapping.Key) as System.Configuration.ConfigurationSection; string refreshedConfigSource = section != null ? section.SectionInformation.ConfigSource : NullConfigSource; if (!sectionMapping.Value.Equals(refreshedConfigSource)) { sectionsWithChangedConfigSource.Add(sectionMapping.Key, refreshedConfigSource); // notify only if che config source changed sectionsToNotify.Add(sectionMapping.Key); } } } protected override void RefreshExternalSections(string[] sectionsToRefresh) { UpdateCache(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationManagerClass:DoNotUseConfigurationManagerClass", Justification = "The implementation may use it")] private System.Configuration.Configuration GetConfiguration() { if (cachedConfiguration == null) { lock (cachedConfigurationLock) { if (cachedConfiguration == null) { cachedConfiguration = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None); } } } return cachedConfiguration; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationManagerClass:DoNotUseConfigurationManagerClass", Justification = "The implementation may use it")] internal void UpdateCache() { System.Configuration.Configuration newConfiguration = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None); lock (cachedConfigurationLock) { cachedConfiguration = newConfiguration; } } } } ================================================ FILE: Composite/Core/Configuration/Foundation/PluginFacades/GlobalSettingsProviderPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.C1Console.Events; using Composite.Core.Configuration.BuildinPlugins.GlobalSettingsProvider; using Composite.Core.Configuration.Plugins.GlobalSettingsProvider; using Composite.Core.Configuration.Plugins.GlobalSettingsProvider.Runtime; namespace Composite.Core.Configuration.Foundation.PluginFacades { internal sealed class GlobalSettingsProviderPluginFacade { private static readonly ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize, false); static GlobalSettingsProviderPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } public static string ApplicationName { get { return UseReaderLock(provider => provider.ApplicationName); } } public static string ApplicationShortName { get { return UseReaderLock(provider => provider.ApplicationShortName); } } public static string BrandedVersionAssemblySource { get { return UseReaderLock(provider => provider.BrandedVersionAssemblySource); } } public static string AutoCreatedAdministratorUserName { get { return UseReaderLock(provider => provider.AutoCreatedAdministratorUserName); } } public static string DefaultCultureName { get { return UseReaderLock(provider => provider.DefaultCultureName); } } public static string ConfigurationDirectory { get { return UseReaderLock(provider => provider.ConfigurationDirectory); } } public static string GeneratedAssembliesDirectory { get { return UseReaderLock(provider => provider.GeneratedAssembliesDirectory); } } public static string SerializedWorkflowsDirectory { get { return UseReaderLock(provider => provider.SerializedWorkflowsDirectory); } } public static string SerializedConsoleMessagesDirectory { get { return UseReaderLock(provider => provider.SerializedConsoleMessagesDirectory); } } public static string AppCodeDirectory { get { return UseReaderLock(provider => provider.AppCodeDirectory); } } public static string BinDirectory { get { return UseReaderLock(provider => provider.BinDirectory); } } public static string TempDirectory { get { return UseReaderLock(provider => provider.TempDirectory); } } public static string CacheDirectory { get { return UseReaderLock(provider => provider.CacheDirectory); } } public static string PackageDirectory { get { return UseReaderLock(provider => provider.PackageDirectory); } } public static string AutoPackageInstallDirectory { get { return UseReaderLock(provider => provider.AutoPackageInstallDirectory); } } public static string TreeDefinitionsDirectory { get { return UseReaderLock(provider => provider.TreeDefinitionsDirectory); } } public static string PageTemplateFeaturesDirectory { get { return UseReaderLock(provider => provider.PageTemplateFeaturesDirectory); } } public static string DataMetaDataDirectory { get { return UseReaderLock(provider => provider.DataMetaDataDirectory); } } public static string InlineCSharpFunctionDirectory { get { return UseReaderLock(provider => provider.InlineCSharpFunctionDirectory); } } public static string PackageLicenseDirectory { get { return UseReaderLock(provider => provider.PackageLicenseDirectory); } } public static IEnumerable NonProbableAssemblyNames { get { return UseReaderLock(provider => provider.NonProbableAssemblyNames); } } public static int ConsoleMessageQueueItemSecondToLive { get { return UseReaderLock(provider => provider.ConsoleMessageQueueItemSecondToLive); } } public static bool EnableDataTypesAutoUpdate { get { return UseReaderLock(provider => provider.EnableDataTypesAutoUpdate); } } public static bool BroadcastConsoleElementChanges { get { return UseReaderLock(provider => provider.BroadcastConsoleElementChanges); } } public static bool OnlyTranslateWhenApproved { get { return UseReaderLock(provider => provider.OnlyTranslateWhenApproved); } } public static bool AllowChildPagesTranslationWithoutParent { get { return UseReaderLock(provider => provider.AllowChildPagesTranslationWithoutParent); } } public static string WorkflowTimeout { get { return UseReaderLock(provider => provider.WorkflowTimeout); } } public static string ConsoleTimeout { get { return UseReaderLock(provider => provider.ConsoleTimeout); } } public static ICachingSettings Caching { get { return UseReaderLock(provider => provider.Caching); } } public static int ImageQuality { get { return UseReaderLock(provider => provider.ImageQuality); } } public static bool PrettifyPublicMarkup { get { return UseReaderLock(provider => provider.PrettifyPublicMarkup); } } public static bool PrettifyRenderFunctionExceptions { get { return UseReaderLock(provider => provider.PrettifyRenderFunctionExceptions); } } public static bool FunctionPreviewEnabled => UseReaderLock(p => p.FunctionPreviewEnabled); public static TimeZoneInfo TimeZone => UseReaderLock(p => p.TimeZone); public static bool InheritGlobalReadPermissionOnHiddenPerspectives => UseReaderLock(p => p.InheritGlobalReadPermissionOnHiddenPerspectives); public static bool OmitAspNetWebFormsSupport => UseReaderLock(p => p.OmitAspNetWebFormsSupport); public static bool ProtectResizedImagesWithHash => UseReaderLock(p => p.ProtectResizedImagesWithHash); private static void Flush() { _resourceLocker.ResetInitialization(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException($"Failed to load the configuration section '{GlobalSettingsProviderSettings.SectionName}' from the configuration.", ex); } private delegate T ExecuteDelegate(IGlobalSettingsProvider provider); private static T UseReaderLock(ExecuteDelegate function) { using (_resourceLocker.ReadLocker) { return function(_resourceLocker.Resources.Provider); } } private sealed class Resources { public GlobalSettingsProviderFactory Factory { get; set; } public IGlobalSettingsProvider Provider { get; set; } public static void Initialize(Resources resources) { var configSource = ConfigurationServices.ConfigurationSource; if (RuntimeInformation.IsUnittest && configSource?.GetSection(GlobalSettingsProviderSettings.SectionName) == null) { resources.Provider = new BuildinGlobalSettingsProvider(); } else { try { resources.Factory = new GlobalSettingsProviderFactory(); resources.Provider = resources.Factory.CreateDefault(); } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } } } } } ================================================ FILE: Composite/Core/Configuration/GlobalSettingsFacade.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Globalization; using Composite.Core.PageTemplates; using Composite.Plugins.PageTemplates.Razor; namespace Composite.Core.Configuration { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class CachingSettings { /// public const int DefaultCacheSize = -1; /// public const int NoCacheSize = 0; internal CachingSettings(bool enabled, int size) { this.Enabled = enabled; this.Size = size; } /// public bool Enabled { get; } /// /// One of three values: /// NoCacheSize: The caller should use not use caching /// DefaultCacheSize: The caller should use its own default size /// All other values (> 0): The caller should use this size /// See /// public int Size { get; } /// /// Returns the configured size or if the configured size is default size, then it uses /// the value. /// /// /// public int GetSize(int defaultSize) { if (this.Size == DefaultCacheSize) return defaultSize; return this.Size; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class GlobalSettingsFacade { private static IGlobalSettingsFacade _globalSettingsFacade = new GlobalSettingsFacadeImpl(); internal static IGlobalSettingsFacade Implementation { get => _globalSettingsFacade; set => _globalSettingsFacade = value; } /// /// The name of the application to be displayed in the UI. /// public static string ApplicationName => _globalSettingsFacade.ApplicationName; /// /// The short name of the application to be displayed in the UI. /// public static string ApplicationShortName => _globalSettingsFacade.ApplicationShortName; /// /// Name of an assembly file, which version should displayed as a product version in UI. /// public static string BrandedVersionAssemblySource => _globalSettingsFacade.BrandedVersionAssemblySource; /// public static CultureInfo DefaultCultureInfo => _globalSettingsFacade.DefaultCultureInfo; /// public static string DefaultCultureName => _globalSettingsFacade.DefaultCultureName; /// public static string ConfigurationDirectory => _globalSettingsFacade.ConfigurationDirectory; /// public static string GeneratedAssembliesDirectory => _globalSettingsFacade.GeneratedAssembliesDirectory; /// public static string SerializedWorkflowsDirectory => _globalSettingsFacade.SerializedWorkflowsDirectory; /// public static string SerializedConsoleMessagesDirectory => _globalSettingsFacade.SerializedConsoleMessagesDirectory; /// public static string AppCodeDirectory => _globalSettingsFacade.AppCodeDirectory; /// public static string BinDirectory => _globalSettingsFacade.BinDirectory; /// public static string TempDirectory => _globalSettingsFacade.TempDirectory; /// public static string CacheDirectory => _globalSettingsFacade.CacheDirectory; /// public static string PackageDirectory => _globalSettingsFacade.PackageDirectory; /// public static string AutoPackageInstallDirectory => _globalSettingsFacade.AutoPackageInstallDirectory; /// public static string TreeDefinitionsDirectory => _globalSettingsFacade.TreeDefinitionsDirectory; /// public static string PageTemplateFeaturesDirectory => _globalSettingsFacade.PageTemplateFeaturesDirectory; /// public static string DataMetaDataDirectory => _globalSettingsFacade.DataMetaDataDirectory; /// public static string InlineCSharpFunctionDirectory => _globalSettingsFacade.InlineCSharpFunctionDirectory; /// public static string PackageLicenseDirectory => _globalSettingsFacade.PackageLicenseDirectory; /// public static IEnumerable NonProbableAssemblyNames => _globalSettingsFacade.NonProbableAssemblyNames; /// public static void AddNonProbableAssemblyName(string assemblyNamePatern) { _globalSettingsFacade.AddNonProbableAssemblyName(assemblyNamePatern); } /// public static void RemoveNonProbableAssemblyName(string assemblyNamePatern) { _globalSettingsFacade.RemoveNonProbableAssemblyName(assemblyNamePatern); } /// public static int ConsoleMessageQueueItemSecondToLive => _globalSettingsFacade.ConsoleMessageQueueItemSecondToLive; /// public static bool EnableDataTypesAutoUpdate => _globalSettingsFacade.EnableDataTypesAutoUpdate; /// public static bool BroadcastConsoleElementChanges => _globalSettingsFacade.BroadcastConsoleElementChanges; /// public static string AutoCreatedAdministratorUserName => _globalSettingsFacade.AutoCreatedAdministratorUserName; /// public static TimeSpan WorkflowTimeout => _globalSettingsFacade.WorkflowTimeout; /// public static TimeSpan ConsoleTimeout => _globalSettingsFacade.ConsoleTimeout; /// public static TimeSpan DefaultReaderLockWaitTimeout => TimeSpan.FromMinutes(5); /// public static TimeSpan DefaultWriterLockWaitTimeout => TimeSpan.FromMinutes(5); /// public static ICachingSettings Caching => _globalSettingsFacade.Caching; /// public static int ImageQuality => _globalSettingsFacade.ImageQuality; /// /// When true only pages that are published or awaiting publication can be translated in console. /// public static bool OnlyTranslateWhenApproved => _globalSettingsFacade.OnlyTranslateWhenApproved; /// /// When true child pages can be translated without translated parent page. /// public static bool AllowChildPagesTranslationWithoutParent => _globalSettingsFacade.AllowChildPagesTranslationWithoutParent; /// /// The maximum number of characters the path to the application root (like 'C:\InetPub\MySite') can contain. /// C1 CMS create files below this path, some of which have very long paths - if the root path is long enough the combined length /// can exceed a limitation in Microsoft Windows - see http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx#paths /// public static int MaximumRootPathLength => 90; /// /// When true the output XHTML markup will be formatted. /// public static bool PrettifyPublicMarkup => _globalSettingsFacade.PrettifyPublicMarkup; /// /// When true exceptions thrown by C1 Functions during a page rendering will be prettified - ensuring the rest of the page render okay. /// For unauthenticated requests this will become "error", while authenticated users get error info. /// public static bool PrettifyRenderFunctionExceptions => _globalSettingsFacade.PrettifyRenderFunctionExceptions; /// public static bool FunctionPreviewEnabled => _globalSettingsFacade.FunctionPreviewEnabled; /// public static TimeZoneInfo TimeZone => _globalSettingsFacade.TimeZone; /// public static bool InheritGlobalReadPermissionOnHiddenPerspectives => _globalSettingsFacade.InheritGlobalReadPermissionOnHiddenPerspectives; /// /// When true, a page request handler that doesn't support UserControl functions will be used. /// Applicable for -s, that return renderer-s implementing interface /// (f.e. ). /// public static bool OmitAspNetWebFormsSupport => _globalSettingsFacade.OmitAspNetWebFormsSupport; /// /// When true, image URLs with resizing options will have a hash appended to ensure that the URLs are generated by the website. /// public static bool ProtectResizedImagesWithHash => _globalSettingsFacade.ProtectResizedImagesWithHash; // Overload /// public static CachingSettings GetNamedCaching(string name) { ICacheSettings cacheSettings = Caching.Caches.FirstOrDefault(f => f.Name == name); bool enabled = Caching.Enabled; int size = CachingSettings.DefaultCacheSize; if (enabled && cacheSettings != null) { enabled = cacheSettings.Enabled && cacheSettings.Size != CachingSettings.NoCacheSize; size = cacheSettings.Size; } var cachingSettings = new CachingSettings(enabled, size); return cachingSettings; } } } ================================================ FILE: Composite/Core/Configuration/GlobalSettingsFacadeImpl.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using Composite.Core.Configuration.Foundation.PluginFacades; namespace Composite.Core.Configuration { internal sealed class GlobalSettingsFacadeImpl : IGlobalSettingsFacade { private readonly List _addedNonProbableAssemblyNames = new List(); private readonly object _lock = new object(); public string ApplicationName => GlobalSettingsProviderPluginFacade.ApplicationName; public string ApplicationShortName => GlobalSettingsProviderPluginFacade.ApplicationShortName; public string BrandedVersionAssemblySource => GlobalSettingsProviderPluginFacade.BrandedVersionAssemblySource; public CultureInfo DefaultCultureInfo { get { string defaultCultureName = GlobalSettingsProviderPluginFacade.DefaultCultureName; return CultureInfo.CreateSpecificCulture(defaultCultureName); } } public string DefaultCultureName { get { string defaultCultureName = GlobalSettingsProviderPluginFacade.DefaultCultureName; var defaultCulture = CultureInfo.CreateSpecificCulture(defaultCultureName); return defaultCulture.Name; } } public string ConfigurationDirectory => GlobalSettingsProviderPluginFacade.ConfigurationDirectory; public string GeneratedAssembliesDirectory => GlobalSettingsProviderPluginFacade.GeneratedAssembliesDirectory; public string SerializedWorkflowsDirectory => GlobalSettingsProviderPluginFacade.SerializedWorkflowsDirectory; public string SerializedConsoleMessagesDirectory => GlobalSettingsProviderPluginFacade.SerializedConsoleMessagesDirectory; public string AppCodeDirectory => GlobalSettingsProviderPluginFacade.AppCodeDirectory; public string BinDirectory => GlobalSettingsProviderPluginFacade.BinDirectory; public string TempDirectory => GlobalSettingsProviderPluginFacade.TempDirectory; public string CacheDirectory => GlobalSettingsProviderPluginFacade.CacheDirectory; public string PackageDirectory => GlobalSettingsProviderPluginFacade.PackageDirectory; public string AutoPackageInstallDirectory => GlobalSettingsProviderPluginFacade.AutoPackageInstallDirectory; public string TreeDefinitionsDirectory => GlobalSettingsProviderPluginFacade.TreeDefinitionsDirectory; public string PageTemplateFeaturesDirectory => GlobalSettingsProviderPluginFacade.PageTemplateFeaturesDirectory; public string DataMetaDataDirectory => GlobalSettingsProviderPluginFacade.DataMetaDataDirectory; public string InlineCSharpFunctionDirectory => GlobalSettingsProviderPluginFacade.InlineCSharpFunctionDirectory; public string PackageLicenseDirectory => GlobalSettingsProviderPluginFacade.PackageLicenseDirectory; public IEnumerable NonProbableAssemblyNames { get { foreach (string nonProbableAssemblyName in GlobalSettingsProviderPluginFacade.NonProbableAssemblyNames) { yield return nonProbableAssemblyName; } lock (_lock) { foreach (string nonProbableAssemblyName in _addedNonProbableAssemblyNames) { yield return nonProbableAssemblyName; } } } } public void AddNonProbableAssemblyName(string assemblyNamePatern) { lock (_lock) { _addedNonProbableAssemblyNames.Add(assemblyNamePatern); } } public void RemoveNonProbableAssemblyName(string assemblyNamePatern) { lock (_lock) { if (!_addedNonProbableAssemblyNames.Contains(assemblyNamePatern)) { throw new InvalidOperationException("The assembly name pattern has not been added"); } _addedNonProbableAssemblyNames.Remove(assemblyNamePatern); } } public int ConsoleMessageQueueItemSecondToLive => GlobalSettingsProviderPluginFacade.ConsoleMessageQueueItemSecondToLive; public bool EnableDataTypesAutoUpdate => GlobalSettingsProviderPluginFacade.EnableDataTypesAutoUpdate; public bool BroadcastConsoleElementChanges => GlobalSettingsProviderPluginFacade.BroadcastConsoleElementChanges; public string AutoCreatedAdministratorUserName => GlobalSettingsProviderPluginFacade.AutoCreatedAdministratorUserName; public TimeSpan WorkflowTimeout => TimeSpan.Parse(GlobalSettingsProviderPluginFacade.WorkflowTimeout); public TimeSpan ConsoleTimeout => TimeSpan.Parse(GlobalSettingsProviderPluginFacade.ConsoleTimeout); public bool OnlyTranslateWhenApproved => GlobalSettingsProviderPluginFacade.OnlyTranslateWhenApproved; public bool AllowChildPagesTranslationWithoutParent => GlobalSettingsProviderPluginFacade.AllowChildPagesTranslationWithoutParent; public ICachingSettings Caching => GlobalSettingsProviderPluginFacade.Caching; public int ImageQuality => GlobalSettingsProviderPluginFacade.ImageQuality; public bool PrettifyPublicMarkup => GlobalSettingsProviderPluginFacade.PrettifyPublicMarkup; public bool PrettifyRenderFunctionExceptions => GlobalSettingsProviderPluginFacade.PrettifyRenderFunctionExceptions; public bool FunctionPreviewEnabled => GlobalSettingsProviderPluginFacade.FunctionPreviewEnabled; public TimeZoneInfo TimeZone => GlobalSettingsProviderPluginFacade.TimeZone; public bool InheritGlobalReadPermissionOnHiddenPerspectives => GlobalSettingsProviderPluginFacade.InheritGlobalReadPermissionOnHiddenPerspectives; public bool OmitAspNetWebFormsSupport => GlobalSettingsProviderPluginFacade.OmitAspNetWebFormsSupport; public bool ProtectResizedImagesWithHash => GlobalSettingsProviderPluginFacade.ProtectResizedImagesWithHash; } } ================================================ FILE: Composite/Core/Configuration/ICachingSettings.cs ================================================ using System.Collections.Generic; namespace Composite.Core.Configuration { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface ICachingSettings { /// bool Enabled { get; } /// IEnumerable Caches { get; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface ICacheSettings { /// string Name { get; } /// bool Enabled { get; } /// int Size { get; } } } ================================================ FILE: Composite/Core/Configuration/IGlobalSettingsFacade.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; namespace Composite.Core.Configuration { internal interface IGlobalSettingsFacade { string ApplicationName { get; } string ApplicationShortName { get; } string BrandedVersionAssemblySource { get; } CultureInfo DefaultCultureInfo { get; } string DefaultCultureName { get; } string ConfigurationDirectory { get; } string GeneratedAssembliesDirectory { get; } string SerializedWorkflowsDirectory { get; } string SerializedConsoleMessagesDirectory { get; } string BinDirectory { get; } string AppCodeDirectory { get; } string TempDirectory { get; } string CacheDirectory { get; } string PackageDirectory { get; } string AutoPackageInstallDirectory { get; } string TreeDefinitionsDirectory { get; } string PageTemplateFeaturesDirectory { get; } string DataMetaDataDirectory { get; } string InlineCSharpFunctionDirectory { get; } string PackageLicenseDirectory { get; } IEnumerable NonProbableAssemblyNames { get; } void AddNonProbableAssemblyName(string assemblyNamePatern); void RemoveNonProbableAssemblyName(string assemblyNamePatern); int ConsoleMessageQueueItemSecondToLive { get; } bool EnableDataTypesAutoUpdate { get; } bool BroadcastConsoleElementChanges { get; } string AutoCreatedAdministratorUserName { get; } TimeSpan WorkflowTimeout { get; } TimeSpan ConsoleTimeout { get; } bool OnlyTranslateWhenApproved { get; } bool AllowChildPagesTranslationWithoutParent { get; } ICachingSettings Caching { get; } int ImageQuality { get; } bool PrettifyPublicMarkup { get; } bool PrettifyRenderFunctionExceptions { get; } bool FunctionPreviewEnabled { get; } TimeZoneInfo TimeZone { get; } bool InheritGlobalReadPermissionOnHiddenPerspectives { get; } bool OmitAspNetWebFormsSupport { get; } bool ProtectResizedImagesWithHash { get; } } } ================================================ FILE: Composite/Core/Configuration/InstallationInformationFacade.cs ================================================ using System; using System.IO; using System.Xml.Linq; using Composite.Core.IO; using Composite.Core.Xml; namespace Composite.Core.Configuration { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class InstallationInformationFacade { private static Guid _installationId; static InstallationInformationFacade() { string filepath = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.ConfigurationDirectory), "InstallationInformation.xml"); if (C1File.Exists(filepath)) { XDocument doc = XDocumentUtils.Load(filepath); XAttribute idAttribute = doc.Root.Attribute("installationId"); _installationId = (Guid)idAttribute; } else { InitializeNewFile(filepath); } } /// public static Guid InstallationId { get { return _installationId; } } private static void InitializeNewFile(string filepath) { _installationId = Guid.NewGuid(); string directory = Path.GetDirectoryName(filepath); if (C1Directory.Exists(directory) == false) { C1Directory.CreateDirectory(directory); } XDocument doc = new XDocument( new XElement("InstallationInformation", new XAttribute("installationId", _installationId) ) ); doc.SaveToFile(filepath); } } } ================================================ FILE: Composite/Core/Configuration/NameTypeManagerTypeConfigurationElement.cs ================================================ using System; using System.Configuration; using System.ComponentModel; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Configuration { /// /// Represents a that has a name and type known to . /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class NameTypeManagerTypeConfigurationElement : NamedConfigurationElement, IObjectWithNameAndType { private const string _typePropertyName = "type"; /// /// Gets or sets the the element is the configuration for. /// /// /// The the element is the configuration for. /// [ConfigurationProperty(_typePropertyName, IsRequired = true)] [TypeConverter(typeof(TypeManagerTypeNameConverter))] public Type Type { get { return (Type)this[_typePropertyName]; } set { this[_typePropertyName] = value; } } } } ================================================ FILE: Composite/Core/Configuration/NameTypeManagerTypeConfigurationElementCollection.cs ================================================ using System; using System.Configuration; using System.Xml; using Composite.Core.Extensions; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Configuration { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class NameTypeManagerTypeConfigurationElementCollection : PolymorphicConfigurationElementCollection where T : NameTypeManagerTypeConfigurationElement, new() { private const string typeAttribute = "type"; /// /// Get the configuration object for each object in the collection. /// /// The that is deserializing the element. protected override Type RetrieveConfigurationElementType(XmlReader reader) { Type configurationElementType = null; if (reader.AttributeCount > 0) { // expect the first attribute to be the name for (bool go = reader.MoveToFirstAttribute(); go; go = reader.MoveToNextAttribute()) { if (typeAttribute.Equals(reader.Name)) { string typeReference = reader.Value; Type providerType = Type.GetType(typeReference); if (providerType == null) { Log.LogCritical("Configuration", "Could not resolve type '{0}' ", typeReference); throw GetExceptionOnTypeNotFound(typeReference); } Attribute attribute = Attribute.GetCustomAttribute(providerType, typeof(ConfigurationElementTypeAttribute)); if (attribute == null) { Type dataElementType = typeof(T); attribute = Attribute.GetCustomAttribute(dataElementType, typeof(ConfigurationElementTypeAttribute)); } if (attribute == null) { throw new ConfigurationErrorsException(string.Format("The type {0} does not contain the ConfigurationElementTypeAttribute.", providerType.Name)); } configurationElementType = ((ConfigurationElementTypeAttribute)attribute).ConfigurationType; break; } } if (configurationElementType == null) { throw new ConfigurationErrorsException(string.Format("The type attribute does not exist on the element {0}.", reader.Name)); } // cover the traces ;) reader.MoveToElement(); } return configurationElementType; } static Exception GetExceptionOnTypeNotFound(string typeReference) { string trimmedTypeReference = typeReference.Trim(); if(trimmedTypeReference.Length > 0) { int commaOffset = typeReference.IndexOf(','); if(commaOffset < 0) { return new ConfigurationErrorsException("Type '{0}' could not be resolved. Assembly name is not specified, " + "if type is defined in '/App_Code' folder, specify type reference as '{0},App_Code'".FormatWith(typeReference)); } string assemblyInfo = trimmedTypeReference.Substring(commaOffset + 1); if(assemblyInfo.ToLowerInvariant().Contains("app_code")) { return new AppCodeTypeNotFoundConfigurationException("Type '{0}' could not be resolved".FormatWith(typeReference)); } } return new ConfigurationErrorsException("Type '{0}' could not be resolved".FormatWith(typeReference)); } } } ================================================ FILE: Composite/Core/Configuration/Plugins/GlobalSettingsProvider/GlobalSettingsProviderData.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Configuration.Plugins.GlobalSettingsProvider { internal class GlobalSettingsProviderData : NameTypeConfigurationElement { } } ================================================ FILE: Composite/Core/Configuration/Plugins/GlobalSettingsProvider/IGlobalSettingsProvider.cs ================================================ using System; using System.Collections.Generic; using Composite.Core.Configuration.Plugins.GlobalSettingsProvider.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Configuration.Plugins.GlobalSettingsProvider { [CustomFactory(typeof(GlobalSettingsProviderCustomFactory))] [ConfigurationNameMapper(typeof(GlobalSettingsProviderDefaultNameRetriever))] internal interface IGlobalSettingsProvider { string ApplicationName { get; } string ApplicationShortName { get; } string BrandedVersionAssemblySource { get; } string DefaultCultureName { get; } string ConfigurationDirectory { get; } string GeneratedAssembliesDirectory { get; } string SerializedWorkflowsDirectory { get; } string SerializedConsoleMessagesDirectory { get; } string AppCodeDirectory { get; } string BinDirectory { get; } string TempDirectory { get; } string CacheDirectory { get; } string PackageDirectory { get; } string AutoPackageInstallDirectory { get; } string TreeDefinitionsDirectory { get; } string PageTemplateFeaturesDirectory { get; } string DataMetaDataDirectory { get; } string InlineCSharpFunctionDirectory { get; } string PackageLicenseDirectory { get; } /// /// List of assembly names to exclude from type probing. Use "*" as wildcard, like. "System.*" /// IEnumerable NonProbableAssemblyNames { get; } int ConsoleMessageQueueItemSecondToLive { get; } bool EnableDataTypesAutoUpdate { get; } bool BroadcastConsoleElementChanges { get; } /// /// If specified, the system will accept this user with any password on a clean system, that has a writeable login provider /// The user will then be created. /// string AutoCreatedAdministratorUserName { get; } string WorkflowTimeout { get; } string ConsoleTimeout { get; } /// /// When true only pages that are published or awaiting publication can be translated in console. /// bool OnlyTranslateWhenApproved { get; } /// /// Allow child pages to be translated without translated parent page /// bool AllowChildPagesTranslationWithoutParent { get; } ICachingSettings Caching { get; } int ImageQuality { get; } bool PrettifyPublicMarkup { get; } bool PrettifyRenderFunctionExceptions { get; } bool FunctionPreviewEnabled { get; } TimeZoneInfo TimeZone { get; } bool InheritGlobalReadPermissionOnHiddenPerspectives { get; } bool OmitAspNetWebFormsSupport { get; } bool ProtectResizedImagesWithHash { get; } } } ================================================ FILE: Composite/Core/Configuration/Plugins/GlobalSettingsProvider/NonConfigurableGlobalSettingsProvider.cs ================================================ using System; using Microsoft.Practices.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Configuration.Plugins.GlobalSettingsProvider { [Assembler(typeof(NonConfigurableGlobalSettingsProviderAssembler))] internal sealed class NonConfigurableGlobalSettingsProvider : GlobalSettingsProviderData { } internal sealed class NonConfigurableGlobalSettingsProviderAssembler : IAssembler { public IGlobalSettingsProvider Assemble(IBuilderContext context, GlobalSettingsProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IGlobalSettingsProvider)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/Core/Configuration/Plugins/GlobalSettingsProvider/Runtime/GlobalSettingsProviderCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Configuration.Plugins.GlobalSettingsProvider.Runtime { internal sealed class GlobalSettingsProviderCustomFactory : AssemblerBasedCustomFactory { protected override GlobalSettingsProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { GlobalSettingsProviderSettings settings = configurationSource.GetSection(GlobalSettingsProviderSettings.SectionName) as GlobalSettingsProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", GlobalSettingsProviderSettings.SectionName)); } return settings.GlobalSettingsProviderPlugins.Get(name); } } } ================================================ FILE: Composite/Core/Configuration/Plugins/GlobalSettingsProvider/Runtime/GlobalSettingsProviderDefaultNameRetriever.cs ================================================ using System; using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Configuration.Plugins.GlobalSettingsProvider.Runtime { internal sealed class GlobalSettingsProviderDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { if (null == configSource) throw new ArgumentNullException("configSource"); if (null != name) { return name; } else { GlobalSettingsProviderSettings settings = configSource.GetSection(GlobalSettingsProviderSettings.SectionName) as GlobalSettingsProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("Could not load configuration section {0}", GlobalSettingsProviderSettings.SectionName)); } return settings.DefaultGlobalSettingsProvider; } } } } ================================================ FILE: Composite/Core/Configuration/Plugins/GlobalSettingsProvider/Runtime/GlobalSettingsProviderFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Configuration.Plugins.GlobalSettingsProvider.Runtime { internal sealed class GlobalSettingsProviderFactory : NameTypeFactoryBase { public GlobalSettingsProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/Core/Configuration/Plugins/GlobalSettingsProvider/Runtime/GlobalSettingsProviderSettings.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Configuration.Plugins.GlobalSettingsProvider.Runtime { internal sealed class GlobalSettingsProviderSettings : SerializableConfigurationSection { public const string SectionName = "Composite.Core.Configuration.Plugins.GlobalSettingsProviderConfiguration"; private const string _defaultGlobalSettingsProviderProperty = "defaultGlobalSettingsProvider"; [ConfigurationProperty(_defaultGlobalSettingsProviderProperty, IsRequired = true)] public string DefaultGlobalSettingsProvider { get { return (string)base[_defaultGlobalSettingsProviderProperty]; } set { base[_defaultGlobalSettingsProviderProperty] = value; } } private const string _globalSettingsProviderPluginsProperty = "GlobalSettingsProviderPlugins"; [ConfigurationProperty(_globalSettingsProviderPluginsProperty, IsRequired = true)] public NameTypeConfigurationElementCollection GlobalSettingsProviderPlugins { get { return (NameTypeConfigurationElementCollection)base[_globalSettingsProviderPluginsProperty]; } } } } ================================================ FILE: Composite/Core/Configuration/SimpleNameTypeConfigurationElement.cs ================================================ using System; using System.Configuration; using System.ComponentModel; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Configuration { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class SimpleNameTypeConfigurationElement : ConfigurationElement { private const string _namePropertyName = "name"; /// [ConfigurationProperty(_namePropertyName, IsRequired=true)] public string Name { get { return (string)base[_namePropertyName]; } set { base[_namePropertyName] = value; } } private const string _typePropertyName = "type"; /// [ConfigurationProperty(_typePropertyName, IsRequired=true)] [TypeConverter(typeof(AssemblyQualifiedTypeNameConverter))] public Type Type { get { return (Type)base[_typePropertyName]; } set { base[_typePropertyName] = value; } } } } ================================================ FILE: Composite/Core/Configuration/SimpleNameTypeConfigurationElementCollection.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; namespace Composite.Core.Configuration { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class SimpleNameTypeConfigurationElementCollection : ConfigurationElementCollection, IEnumerable { /// public void Add(string name, Type type) { var element = new SimpleNameTypeConfigurationElement(); element.Name = name; element.Type = type; BaseAdd(element); } /// protected override ConfigurationElement CreateNewElement() { return new SimpleNameTypeConfigurationElement(); } /// protected override object GetElementKey(ConfigurationElement element) { return (element as SimpleNameTypeConfigurationElement).Name; } IEnumerator IEnumerable.GetEnumerator() { return this.OfType().GetEnumerator(); } } } ================================================ FILE: Composite/Core/Configuration/SystemSetupFacade.cs ================================================ using System; using System.IO; using System.Xml.Linq; using Composite.Core.IO; using Composite.Core.Xml; namespace Composite.Core.Configuration { /// /// This class may not depended on the system being initialized. /// Any call to the class will never result in the system being initialized /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class SystemSetupFacade { private static readonly object _lock = new object(); private static bool? _isSystemFirstTimeInitialized; /// static SystemSetupFacade() { } /// public static bool IsSystemFirstTimeInitialized { get { if (_isSystemFirstTimeInitialized == null) { try { _isSystemFirstTimeInitialized = C1File.Exists(SystemInitializedFilePath); } catch (Exception) { _isSystemFirstTimeInitialized = false; } } return _isSystemFirstTimeInitialized.Value; } set { Verify.IsTrue(value, "Only 'true' value is expected"); lock (_lock) { if (!C1File.Exists(SystemInitializedFilePath)) { string directory = Path.GetDirectoryName(SystemInitializedFilePath); C1Directory.CreateDirectory(directory); var doc = new XDocument( new XElement("Root", new XAttribute("Status", true)) ); doc.SaveToFile(SystemInitializedFilePath); } _isSystemFirstTimeInitialized = true; } } } /// public static bool SetupIsRunning { get; set; } private static string SystemInitializedFilePath { get { return PathUtil.Resolve("~/App_Data/Composite/Configuration/SystemInitialized.xml"); } } /// /// This method is used to record the very first time the system is started. /// Ths time can later be used to several things like finding files that have been written to etc. /// public static void SetFirstTimeStart() { if (!C1File.Exists(FirstTimeStartFilePath)) { string directory = Path.GetDirectoryName(FirstTimeStartFilePath); if (!C1Directory.Exists(directory)) { C1Directory.CreateDirectory(directory); } var doc = new XDocument(new XElement("Root", new XAttribute("time", DateTime.Now))); doc.SaveToFile(FirstTimeStartFilePath); } } /// /// Returns the time the system was startet the very first time /// /// The very first time the system has been started [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass", Justification = "This is intended")] public static DateTime GetFirstTimeStart() { Verify.That(File.Exists(FirstTimeStartFilePath), "File '{0}' is missing", FirstTimeStartFilePath); var doc = XDocumentUtils.Load(FirstTimeStartFilePath); return (DateTime)doc.Element("Root").Attribute("time"); } private static string FirstTimeStartFilePath { get { return PathUtil.Resolve("~/App_Data/Composite/Configuration/FirstTimeStart.xml"); } } } } ================================================ FILE: Composite/Core/Configuration/TypeManagerTypeNameConverter.cs ================================================ using System; using System.ComponentModel; using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Properties; using Composite.Core.Types; namespace Composite.Core.Configuration { /// /// Represents a configuration converter that converts a string to using the Composite Type Manager. /// internal class TypeManagerTypeNameConverter : ConfigurationConverterBase { /// /// Returns the name for the passed in Type. /// /// The container representing this System.ComponentModel.TypeDescriptor. /// Culture info for assembly /// Value to convert. /// Type to convert to. /// Assembly Qualified Name as a string public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { Type typeValue = value as Type; if (typeValue == null) { throw new ArgumentException("Can not convert type"); } if (typeValue != null) return (typeValue).AssemblyQualifiedName; return null; } /// /// Returns a type based on the name passed in as data. /// /// The container representing this System.ComponentModel.TypeDescriptor. /// Culture info for assembly. /// Data to convert. /// Type of the data public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { string stringValue = (string)value; Type result = TypeManager.GetType(stringValue); if (result == null) { throw new ArgumentException(string.Format("Type \"{0}\" not found.", stringValue)); } return result; } } } ================================================ FILE: Composite/Core/EmptyDisposable.cs ================================================ using System; namespace Composite.Core { internal class EmptyDisposable : IDisposable { public static readonly EmptyDisposable Instance = new EmptyDisposable(); public void Dispose() { } } } ================================================ FILE: Composite/Core/Extensions/ByteArrayExtensionMethods.cs ================================================ using System; using System.Collections.Generic; namespace Composite.Core.Extensions { internal static class ByteArrayExtensionMethods { public static IEnumerable Split(this byte[] bytes, byte splitByte) { int lastIndex = 0; int index = IndexOf(bytes, splitByte, lastIndex); while (index != -1) { int size = index - lastIndex; byte[] subBytes = new byte[size]; Array.Copy(bytes, lastIndex, subBytes, 0, size); lastIndex = index + 1; index = IndexOf(bytes, splitByte, lastIndex); yield return subBytes; } if (lastIndex < bytes.Length) { int size = bytes.Length - lastIndex; byte[] subBytes = new byte[size]; Array.Copy(bytes, lastIndex, subBytes, 0, size); yield return subBytes; } } public static int IndexOf(this byte[] bytes, byte byteToFind) { return IndexOf(bytes, byteToFind, 0); } public static int IndexOf(this byte[] bytes, byte byteToFind, int startIndex) { if (bytes == null) throw new ArgumentNullException("bytes"); if (startIndex > bytes.Length) throw new ArgumentNullException("startIndex exceeds the length of the bytes"); for (int i = startIndex; i < bytes.Length; i++) { if (bytes[i] == byteToFind) return i; } return -1; } } } ================================================ FILE: Composite/Core/Extensions/DateTimeExtensionMethods.cs ================================================ using System; using Composite.Core.Configuration; using Composite.Core.ResourceSystem; namespace Composite.Core.Extensions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DateTimeExtensionMethods { /// private static string TimeZoneAbbreviatedName() { return StringResourceSystemFacade.GetString("Composite.Plugins.TimezoneAbbreviations", "TimezoneAbbreviations." + GlobalSettingsFacade.TimeZone.Id); } /// public static string ToTimeZoneDateTimeString(this DateTime? dateTime) { return dateTime?.ToTimeZoneDateTimeString(); } /// public static string ToTimeZoneDateTimeString(this DateTime dateTime) { var convertedToShow = dateTime.ToTimeZone(); return $"{convertedToShow.ToShortDateString()} {convertedToShow.ToShortTimeString()} {TimeZoneAbbreviatedName()}"; } /// public static string ToTimeZoneDateString(this DateTime? dateTime) { return dateTime?.ToTimeZoneDateString(); } /// public static string ToTimeZoneDateString(this DateTime dateTime) { var convertedToShow = dateTime.ToTimeZone(); return convertedToShow.ToShortDateString(); } /// public static DateTime FromTimeZoneToUtc(this DateTime dateTime) { return TimeZoneInfo.ConvertTime(dateTime, GlobalSettingsFacade.TimeZone, TimeZoneInfo.Utc); } /// public static DateTime ToTimeZone(this DateTime dateTime) { return TimeZoneInfo.ConvertTime(dateTime, GlobalSettingsFacade.TimeZone); } /// public static bool TryParseInTimeZone(string s, out DateTime result) { return DateTime.TryParse(s.Replace(TimeZoneAbbreviatedName(), ""), out result); } } } ================================================ FILE: Composite/Core/Extensions/DictionaryExtensionMethods.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; namespace Composite.Core.Extensions { internal static class DictionaryExtensionMethods { public static TValue GetOrAdd(this IDictionary dictionary, TKey key, Func createValue) { if (dictionary is ConcurrentDictionary concurrentDictionary) { return concurrentDictionary.GetOrAdd(key, k => createValue()); } TValue value; if (dictionary.TryGetValue(key, out value)) { return value; } lock (dictionary) { if (dictionary.TryGetValue(key, out value)) { return value; } value = createValue(); dictionary.Add(key, value); } return value; } public static TValue GetOrAdd(this IDictionary dictionary, TKey key, Func createValue) { if (dictionary is ConcurrentDictionary concurrentDictionary) { return concurrentDictionary.GetOrAdd(key, createValue); } TValue value; if (dictionary.TryGetValue(key, out value)) { return value; } lock (dictionary) { if (dictionary.TryGetValue(key, out value)) { return value; } value = createValue(key); dictionary.Add(key, value); } return value; } public static List> SortByKeys(this Dictionary dictionary) { var result = dictionary.ToList(); result.Sort((a, b) => string.CompareOrdinal(a.Key, b.Key)); return result; } } } ================================================ FILE: Composite/Core/Extensions/ExpressionExtensionMethods.cs ================================================ using System; using System.Linq; using System.Linq.Expressions; namespace Composite.Core.Extensions { internal static class ExpressionExtensionMethods { public static Expression> Or(this Expression> expression1, Expression> expression2) { var invokedExpression = Expression.Invoke(expression2, expression1.Parameters.Cast()); return Expression.Lambda> (Expression.Or(expression1.Body, invokedExpression), expression1.Parameters); } public static Expression> And(this Expression> expression1, Expression> expression2) { var invokedExpression = Expression.Invoke(expression2, expression1.Parameters.Cast()); return Expression.Lambda> (Expression.And(expression1.Body, invokedExpression), expression1.Parameters); } } } ================================================ FILE: Composite/Core/Extensions/HttpContextExtensionMethods.cs ================================================ using System.Reflection; using System.Web; namespace Composite.Core.Extensions { /// public static class HttpContextExtensionMethods { private static readonly FieldInfo HideRequestResponseFieldInfo = typeof(HttpContext).GetField("HideRequestResponse", BindingFlags.Instance | BindingFlags.NonPublic); /// public static bool RequestIsAvaliable(this HttpContext httpContext) { return !(bool) HideRequestResponseFieldInfo.GetValue(httpContext); } } } ================================================ FILE: Composite/Core/Extensions/IApplicationHostExtensionMethods.cs ================================================ using System; using System.Reflection; using System.Web.Hosting; namespace Composite.Core.Extensions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class IApplicationHostExtensionMethods { static readonly PropertyInfo _shutdownInitiatedPropertyInfo = typeof(HostingEnvironment).GetProperty("ShutdownInitiated", BindingFlags.NonPublic | BindingFlags.Static); private static bool _processExit; static IApplicationHostExtensionMethods() { AppDomain.CurrentDomain.ProcessExit += (s, a) => _processExit = true; } /// public static bool ShutdownInitiated(this IApplicationHost host) { if (!HostingEnvironment.IsHosted) { return _processExit; } return (bool)_shutdownInitiatedPropertyInfo.GetValue(null, null); } } } ================================================ FILE: Composite/Core/Extensions/IEnumerableExtensionMethods.cs ================================================ using System; using System.Collections.Generic; using System.Linq; namespace Composite.Core.Extensions { internal static class IEnumerableExtensionMethods { public static List ToList(this IEnumerable source, Func objectCreator) { if (source == null) throw new ArgumentNullException("source"); List targetList = new List(); foreach (TSource sourceElement in source) { TTarget target = objectCreator(sourceElement); targetList.Add(target); } return targetList; } public static void ForEach(this IEnumerable source, Action action) { foreach (TSource element in source) { action(element); } } public static IEnumerable ConcatOrDefault(this IEnumerable enumerable, IEnumerable enumerableToAppend) { if (enumerable == null) return enumerableToAppend; if (enumerableToAppend == null) return enumerable; return enumerable.Concat(enumerableToAppend); } } } ================================================ FILE: Composite/Core/Extensions/IQueryableExtensionMethods.cs ================================================ using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Core.Types; using Composite.Data; using Composite.Data.Caching; using Composite.Data.Foundation; namespace Composite.Core.Extensions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class IQueryableExtensionMethods { private static readonly MethodInfo _miQueryableAny = (from methodInfo in typeof (Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public) where methodInfo.Name == "Any" && methodInfo.GetParameters().Length == 1 select methodInfo).First(); /// public static IQueryable Random(this IQueryable source) where T : class, IData { Verify.ArgumentNotNull(source, "source"); return source.OrderBy(element => Guid.NewGuid()); } /// public static IQueryable TakeRandom(this IQueryable source, int elementsToTake) where T : class, IData { return source.Random().Take(elementsToTake); } /// public static bool IsEnumerableQuery(this IQueryable query) { if(query == null) return false; if(query is DataFacadeQueryable) { return (query as DataFacadeQueryable).IsEnumerableQuery; } return query is CachingQueryable || query is EnumerableQuery; } /// public static bool Any(this IQueryable queryable) { var type = queryable.GetType(); if(type.IsGenericType) { var genericArguments = type.GetGenericArguments(); if(genericArguments.Length == 1) { var queryType = typeof (IQueryable<>).MakeGenericType(genericArguments); if(queryType.IsAssignableFrom(type)) { MethodInfo genericAnyMethod = _miQueryableAny.MakeGenericMethod(genericArguments); return (bool)genericAnyMethod.Invoke(null, new object[] { queryable }); } } } foreach(object element in queryable) { return true; } return false; } /// public static IOrderedQueryable OrderBy(this IQueryable source, Type dataType, string property) { return ApplyOrder(source, dataType, property, "OrderBy"); } /// public static IOrderedQueryable OrderBy(this IQueryable source, Type dataType, string property, bool descending) { string methodName = descending ? "OrderByDescending" : "OrderBy"; return ApplyOrder(source, dataType, property, methodName); } /// public static IOrderedQueryable OrderByDescending(this IQueryable source, Type dataType, string property) { return ApplyOrder(source, dataType, property, "OrderByDescending"); } /// public static IOrderedQueryable ThenBy(this IOrderedQueryable source, Type dataType, string property) { return ApplyOrder(source, dataType, property, "ThenBy"); } /// public static IOrderedQueryable ThenBy(this IOrderedQueryable source, Type dataType, string property, bool descending) { string methodName = descending ? "ThenByDescending" : "ThenBy"; return ApplyOrder(source, dataType, property, methodName); } /// public static IOrderedQueryable ThenByDescending(this IOrderedQueryable source, Type dataType, string property) { return ApplyOrder(source, dataType, property, "ThenByDescending"); } /// public static IOrderedQueryable OrderBy(this IQueryable source, string property) { return ApplyOrder(source, property, "OrderBy"); } /// public static IOrderedQueryable OrderByDescending(this IQueryable source, string property) { return ApplyOrder(source, property, "OrderByDescending"); } /// public static IOrderedQueryable ThenBy(this IOrderedQueryable source, string property) { return ApplyOrder(source, property, "ThenBy"); } /// public static IOrderedQueryable ThenByDescending(this IOrderedQueryable source, string property) { return ApplyOrder(source, property, "ThenByDescending"); } /// private static IOrderedQueryable ApplyOrder(IQueryable source, string property, string methodName) { return (IOrderedQueryable)ApplyOrder(source, typeof(T), property, methodName); } private static IOrderedQueryable ApplyOrder(IQueryable source, Type type, string property, string methodName) { Verify.IsNotNull(property, "property cannot be null"); Verify.IsNotNull(type, "type cannot be null"); string[] props = property.Split('.'); Type parameterType = type; ParameterExpression arg = Expression.Parameter(parameterType, "x"); Expression expr = arg; foreach (string prop in props) { // use reflection (not ComponentModel) to mirror LINQ PropertyInfo pi = parameterType.GetPropertiesRecursively(f=>f.Name == prop).FirstOrDefault(); Verify.IsNotNull(pi, "Could not find property '{0}' on type '{1}'", property, type); expr = Expression.Property(expr, pi); parameterType = pi.PropertyType; } Type delegateType = typeof(Func<,>).MakeGenericType(type, parameterType); LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg); object result = typeof(Queryable).GetMethods().Single( method => method.Name == methodName && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 2 && method.GetParameters().Length == 2) .MakeGenericMethod(type, parameterType) .Invoke(null, new object[] { source, lambda }); return (IOrderedQueryable)result; } } } ================================================ FILE: Composite/Core/Extensions/MethodInfoExtensionMethods.cs ================================================ using System; using System.Reflection; using System.Text; namespace Composite.Core.Extensions { internal static class MethodInfoExtensionMethods { public static string ToExceptionString(this MethodInfo methodInfo) { if (methodInfo == null) throw new ArgumentNullException("methodInfo"); StringBuilder sb = new StringBuilder(); sb.Append(methodInfo.DeclaringType.FullName); sb.Append("."); sb.Append(methodInfo.Name); Type[] genericArguments = methodInfo.GetGenericArguments(); if (genericArguments.Length > 0) { sb.Append("["); bool firstGenericParameter = true; foreach (Type type in genericArguments) { if (firstGenericParameter == false) { sb.Append(", "); } else { firstGenericParameter = false; } sb.Append(type.Name); } sb.Append("]"); } sb.Append("("); bool firstParameter = true; foreach (ParameterInfo parameterInfo in methodInfo.GetParameters()) { if (firstParameter == false) { sb.Append(", "); } else { firstParameter = false; } sb.Append(parameterInfo.ParameterType.Name); sb.Append(" "); sb.Append(parameterInfo.Name); } sb.Append(")"); return sb.ToString(); } } } ================================================ FILE: Composite/Core/Extensions/PageUrlDataExtensionMethods.cs ================================================ using Composite.Core.Routing; using Composite.Data; using Composite.Data.Types; namespace Composite.Core.Extensions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PageUrlDataExtensionMethods { /// public static IPage GetPage(this PageUrlData pageUrlData) { Verify.ArgumentNotNull(pageUrlData, nameof(pageUrlData)); using (new DataScope(pageUrlData.PublicationScope, pageUrlData.LocalizationScope)) { if (pageUrlData.VersionId != null) { return PageManager.GetPageById(pageUrlData.PageId, pageUrlData.VersionId.Value); } return PageManager.GetPageById(pageUrlData.PageId); } } } } ================================================ FILE: Composite/Core/Extensions/StackTraceExtensionMethods.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Composite.Core.Extensions { internal static class StackTraceExtensionMethods { public static IEnumerable AsEnumerable(this StackTrace stackTrace) { if (stackTrace == null) throw new ArgumentNullException("stackTrace"); for (int i = 0; i < stackTrace.FrameCount; i++) { yield return stackTrace.GetFrame(i); } } public static IQueryable AsQueryable(this StackTrace stackTrace) { if (stackTrace == null) throw new ArgumentNullException("stackTrace"); return stackTrace.AsEnumerable().AsQueryable(); } } } ================================================ FILE: Composite/Core/Extensions/StreamExtensionMethods.cs ================================================ using System; using System.IO; namespace Composite.Core.Extensions { internal static class StreamExtensionMethods { public static void CopyTo(this Stream stream, Stream toStream) { int offset = 0; int remaining = (int)stream.Length; const int chunkSize = 8192; byte[] data = new byte[chunkSize]; while (remaining > 0) { int toRead = Math.Min(chunkSize, remaining); int read = stream.Read(data, 0, toRead); if (read <= 0) throw new EndOfStreamException(String.Format("End of stream reached with {0} bytes left to read", remaining)); toStream.Write(data, 0, read); remaining -= read; offset += read; } } } } ================================================ FILE: Composite/Core/Extensions/StringExtensionMethods.cs ================================================ using System; using System.Globalization; using System.IO; using System.Text; using JetBrains.Annotations; namespace Composite.Core.Extensions { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class StringExtensionMethods { /// [StringFormatMethod("format")] public static string FormatWith(this string format, params object[] args) { Verify.ArgumentNotNull(format, "format"); return string.Format(CultureInfo.InvariantCulture, format, args); } /// public static bool IsNullOrEmpty(this string str) { return string.IsNullOrEmpty(str); } /// public static bool StartsWith(this string str, string value, bool ignoreCase) { return str.StartsWith(value, ignoreCase, CultureInfo.InvariantCulture); } /// public static bool EndsWith(this string str, string value, bool ignoreCase) { return str.EndsWith(value, ignoreCase, CultureInfo.InvariantCulture); } /// public static bool IsCorrectNamespace(this string s, char separator) { if (s == null) return false; if (s == "") return true; string[] splits = s.Split(separator); foreach (string split in splits) { if (split == "") return false; } return true; } /// public static string CreateNamespace(string namespaceName, string name, char separator) { if (string.IsNullOrEmpty(namespaceName)) { return name; } return string.Format("{0}{1}{2}", namespaceName, separator, name); } /// /// Default separator is '.' /// /// /// /// public static string CreateNamespace(string namespaceName, string name) { return CreateNamespace(namespaceName, name, '.'); } /// public static string GetNameFromNamespace(this string s) { int index = s.LastIndexOf(".", StringComparison.Ordinal); if (index < 0) { return s; } return s.Substring(index + 1); } /// public static string GetNamespace(this string s) { int index = s.LastIndexOf(".", StringComparison.Ordinal); if (index <= 0) { return string.Empty; } string result = s.Substring(0, index); if (result.EndsWith(".")) { result = result.Substring(0, result.Length); } return result; } /// public static bool IsCorrectFolderName(this string s, char separator) { if (s == null) return false; if (s == "/") return true; if (!s.StartsWith("/")) return false; if (s.Length > 1 && s.EndsWith("/")) return false; string[] splits = s.Split(separator); for (int i = 1; i < splits.Length; i++) { if (splits[i] == "") return false; } return true; } /// public static bool IsDirectChildOf(this string s, string possibleParentPath, char separator) { if (possibleParentPath.Length > s.Length) { return false; } if (s == possibleParentPath) { return false; } if (!s.StartsWith(possibleParentPath)) { return false; } if (possibleParentPath == separator.ToString()) { string remaining = s.Remove(0, possibleParentPath.Length); if (!remaining.Contains(separator.ToString())) { return true; } } if (s[possibleParentPath.Length] == '/') { string remaining = s.Remove(0, possibleParentPath.Length + 1); if (!remaining.Contains(separator.ToString())) { return true; } } return false; } /// public static bool IsParentOf(this string s, string possibleChild, char separator) { return possibleChild.IsDirectChildOf(s, separator); } /// public static string GetFolderName(this string s, char separator) { if (s.Length == 1 && s[0] == separator) { return null; } if (!s.Contains(separator.ToString())) { return "/"; } string[] foldernames = s.Split(separator); if (foldernames[foldernames.Length - 1] == "") { if (foldernames.Length >= 2) { return foldernames[foldernames.Length - 2]; } throw new System.NotImplementedException(); } return foldernames[foldernames.Length - 1]; } /// public static string GetNameWithoutExtension(this string s) { string name = Path.GetFileName(s); if (Path.HasExtension(name)) { int lastIndex = name.LastIndexOf('.'); return name.Remove(lastIndex); } return name; } /// public static string GetDirectory(this string s, char separator) { Verify.ArgumentNotNull(s, "s"); int lastIndex = s.LastIndexOf(separator); if (lastIndex > 0) { return s.Remove(lastIndex); } if (lastIndex == 0 && s.Length > 1) { return "/"; } if (lastIndex == 0 && s.Length == 1) { return ""; } if (s.IndexOf(separator) == -1) { return ""; } return s; } /// /// Combines URL paths using / as seperator /// /// /// /// /// public static string Combine(this string path, string otherPath, char separator) { Verify.ArgumentNotNull(path, "path"); Verify.ArgumentNotNull(otherPath, "otherPath"); string childPath = otherPath; if (otherPath.StartsWith("/")) { childPath = otherPath.Substring(1, otherPath.Length - 1); } if (childPath.EndsWith("/")) { childPath = otherPath.Substring(0, otherPath.Length - 1); } if (path.Length == 1 && path[0] == separator) { return path + childPath; } if (otherPath == "/" || otherPath == string.Empty) { return path; } return path + "/" + childPath; } /// /// Replaces old value with new value using the specified string comparison method for searching for the oldValue. /// /// The string. /// The old subsvalue. /// The new value. /// The comparison. /// public static string Replace(this string str, string oldValue, string newValue, StringComparison comparison) { int index = str.IndexOf(oldValue, comparison); if (index == -1) { return str; } int previousIndex = 0; var sb = new StringBuilder(); while (index != -1) { sb.Append(str, previousIndex, index - previousIndex); sb.Append(newValue); index += oldValue.Length; previousIndex = index; index = str.IndexOf(oldValue, index, comparison); } sb.Append(str, previousIndex, str.Length - previousIndex); return sb.ToString(); } } } ================================================ FILE: Composite/Core/HashingHelper.cs ================================================ using System; using System.Security.Cryptography; using System.Text; namespace Composite.Core { internal static class HashingHelper { [ThreadStatic] private static MD5 _md5; /// /// Gets a cached instance of an MD5 algorithm /// private static MD5 MD5 { get { var value = _md5; if (value == null) { _md5 = value = MD5.Create(); } return value; } } public static Guid ComputeMD5Hash(string str, Encoding textEncoding) { var bytes = textEncoding.GetBytes(str); var hash = MD5.ComputeHash(bytes); return new Guid(hash); } } } ================================================ FILE: Composite/Core/IMailer.cs ================================================ using System.Net.Mail; using System.Threading.Tasks; namespace Composite.Core { /// /// A contract for sending email messages. /// public interface IMailer { /// /// Sends the specified /// /// The message to send void Send(MailMessage message); /// /// Sends the specified an asynchronous operation. /// /// The message to send /// The task object representing the asynchronous operation. Task SendAsync(MailMessage message); } } ================================================ FILE: Composite/Core/IO/C1Directory.cs ================================================ using System; using System.IO; using Composite.Core.Implementation; namespace Composite.Core.IO { /// /// This class is a almost one to one version of System.IO.Directory. Using this implementation instead /// of System.IO.Directory, will ensure that your code will work both on Standard Windows deployment /// and Windows Azure deployment. /// See System.IO.Directory for more documentation on the methods of this class. /// See . /// public static class C1Directory { /// /// Creates a directory. /// /// Path to directory to create. /// Returns a C1DirectoryInfo to the specified path. public static C1DirectoryInfo CreateDirectory(string path) { return ImplementationFactory.CurrentFactory.StatelessC1Directory.CreateDirectory(path); } /// /// Moves a file or directory from the given source path to the given destination path. /// /// Path of file or directory to move. /// Target path of file or directory to be moved to. public static void Move(string sourceDirName, string destDirName) { ImplementationFactory.CurrentFactory.StatelessC1Directory.Move(sourceDirName, destDirName); } /// /// Deletes an empty directory on the given path. /// /// Path of empty directory to delete. public static void Delete(string path) { ImplementationFactory.CurrentFactory.StatelessC1Directory.Delete(path); } /// /// Deletes the directory and if specified subdirectories and file on the given path. /// /// Path of directory to delete. /// Include subdirectories and files. public static void Delete(string path, bool recursive) { ImplementationFactory.CurrentFactory.StatelessC1Directory.Delete(path, recursive); } /// /// Determines if the directory in the given path exists or not. /// /// Path to directory to test. /// public static bool Exists(string path) { return ImplementationFactory.CurrentFactory.StatelessC1Directory.Exists(path); } /// /// Returns the current directory. /// /// The current directory. public static string GetCurrentDirectory() { return ImplementationFactory.CurrentFactory.StatelessC1Directory.GetCurrentDirectory(); } /// /// Sets the current directory /// /// Path to new current directory. public static void SetCurrentDirectory(string path) { ImplementationFactory.CurrentFactory.StatelessC1Directory.SetCurrentDirectory(path); } /// /// Gets the parent of the given directory. /// /// Path of directory to get parent of. /// The parent of the given directory. public static C1DirectoryInfo GetParent(string path) { return ImplementationFactory.CurrentFactory.StatelessC1Directory.GetParent(path); } /// /// Returns volume and/or root information of the given directory. /// /// Path of directory to get root information of. /// Volume and/or root information. public static string GetDirectoryRoot(string path) { return ImplementationFactory.CurrentFactory.StatelessC1Directory.GetDirectoryRoot(path); } /// /// Gets the subdirectories of the given directory. /// /// Path to directory to get subdirectories. /// Subdirectories of the given directory. public static string[] GetDirectories(string path) { return ImplementationFactory.CurrentFactory.StatelessC1Directory.GetDirectories(path); } /// /// Gets the subdirectories of the given directory with the given search pattern. /// /// Path to directory to get subdirectories. /// Search pattern to use. /// Subdirectories of the given directory with the given search parrern. public static string[] GetDirectories(string path, string searchPattern) { return ImplementationFactory.CurrentFactory.StatelessC1Directory.GetDirectories(path, searchPattern); } /// /// Gets the subdirectories of the given directory with the given search pattern and options. /// /// Path to directory to get subdirectories. /// Search pattern to use. /// Search options to use. /// Subdirectories of the given directory with the given search parrern and options. public static string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) { return ImplementationFactory.CurrentFactory.StatelessC1Directory.GetDirectories(path, searchPattern, searchOption); } /// /// Gets the files in the given directory. /// /// Path to directory go get files from. /// Files in the given directory. public static string[] GetFiles(string path) { return ImplementationFactory.CurrentFactory.StatelessC1Directory.GetFiles(path); } /// /// Gets the files in the given directory with the given search pattern. /// /// Path to directory go get files from. /// Search pattern to use. /// Files in the given directory with the given search pattern. public static string[] GetFiles(string path, string searchPattern) { return ImplementationFactory.CurrentFactory.StatelessC1Directory.GetFiles(path, searchPattern); } /// /// Gets the files in the given directory with the given search pattern and options. /// /// Path to directory go get files from. /// Search pattern to use. /// Search options to use. /// Files in the given directory with the given search pattern and options. public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption) { return ImplementationFactory.CurrentFactory.StatelessC1Directory.GetFiles(path, searchPattern, searchOption); } /// /// Returns the creation date and time of the given directory. /// /// Path of directory. /// Creation date and time of the given directory. public static DateTime GetCreationTime(string path) { return ImplementationFactory.CurrentFactory.StatelessC1Directory.GetCreationTime(path); } /// /// Returns the creation date and utc time of the given directory. /// /// Path of directory. /// Creation date and time of the given directory. public static DateTime GetCreationTimeUtc(string path) { return ImplementationFactory.CurrentFactory.StatelessC1Directory.GetCreationTimeUtc(path); } //public static IEnumerable EnumerateDirectories(string path) //{ // throw new NotImplementedException(); //} //public static IEnumerable EnumerateDirectories(string path, string searchPattern) //{ // throw new NotImplementedException(); //} //public static IEnumerable EnumerateDirectories(string path, string searchPattern, SearchOption searchOption) //{ // throw new NotImplementedException(); //} //public static IEnumerable EnumerateFiles(string path) //{ // throw new NotImplementedException(); //} //public static IEnumerable EnumerateFiles(string path, string searchPattern) //{ // throw new NotImplementedException(); //} //public static IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOption) //{ // throw new NotImplementedException(); //} //public static IEnumerable EnumerateFileSystemEntries(string path) //{ // throw new NotImplementedException(); //} //public static IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) //{ // throw new NotImplementedException(); //} //public static IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption) //{ // throw new NotImplementedException(); //} //public static string[] GetFileSystemEntries(string path) //{ // throw new NotImplementedException(); //} //public static string[] GetFileSystemEntries(string path, string searchPattern) //{ // throw new NotImplementedException(); //} //public static string[] GetFileSystemEntries(string path, string searchPattern, SearchOption searchOption) //{ // throw new NotImplementedException(); //} //public static DirectorySecurity GetAccessControl(string path) //{ // throw new NotImplementedException(); //} //public static DirectorySecurity GetAccessControl(string path, AccessControlSections includeSections) //{ // throw new NotImplementedException(); //} //public static void SetAccessControl(string path, DirectorySecurity directorySecurity) //{ // throw new NotImplementedException(); //} /// /// Sets the creation date and time for the specified file or directory. /// /// The file or directory for which to set the creation date and time information. /// An object that contains the value to set for the creation date and time of path. This value is expressed in local time. public static void SetCreationTime(string path, DateTime creationTime) { ImplementationFactory.CurrentFactory.StatelessC1Directory.SetCreationTime(path, creationTime); } /// /// Sets the creation date and time, in Coordinated Universal Time (UTC) format, for the specified file or directory. /// /// The file or directory for which to set the creation date and time information. /// An object that contains the value to set for the creation date and time of path. This value is expressed in UTC time. public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc) { ImplementationFactory.CurrentFactory.StatelessC1Directory.SetCreationTimeUtc(path, creationTimeUtc); } //public static string[] GetLogicalDrives() //{ // throw new NotImplementedException(); //} //public static DateTime GetLastAccessTime(string path) //{ // throw new NotImplementedException(); //} //public static void SetLastAccessTime(string path, DateTime lastAccessTime) //{ // throw new NotImplementedException(); //} //public static DateTime GetLastAccessTimeUtc(string path) //{ // throw new NotImplementedException(); //} //public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) //{ // throw new NotImplementedException(); //} //public static DateTime GetLastWriteTime(string path) //{ // throw new NotImplementedException(); //} //public static void SetLastWriteTime(string path, DateTime lastWriteTime) //{ // throw new NotImplementedException(); //} //public static DateTime GetLastWriteTimeUtc(string path) //{ // throw new NotImplementedException(); //} //public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) //{ // throw new NotImplementedException(); //} } } ================================================ FILE: Composite/Core/IO/C1DirectoryInfo.cs ================================================ using System; using System.IO; using System.Runtime.Serialization; using Composite.Core.Implementation; namespace Composite.Core.IO { /// /// This class is a almost one to one version of System.IO.DirectoryInfo. Using this implementation instead /// of System.IO.DirectoryInfo, will ensure that your code will work both on Standard Windows deployment /// and Windows Azure deployment. /// See System.IO.DirectoryInfo for more documentation on the methods of this class. /// See . /// public class C1DirectoryInfo : C1FileSystemInfo { private ImplementationContainer _implementation; /// /// Creates and initialize a new C1DirectoryInfo. /// /// Path to use. public C1DirectoryInfo(string path) { _implementation = new ImplementationContainer(() => ImplementationFactory.CurrentFactory.CreateC1DirectoryInfo(path)); _implementation.CreateImplementation(); } /// /// The name of the directory. /// public string Name { get { return _implementation.Implementation.Name; } } /// /// Full path of the directory. /// public override string FullName { get { return _implementation.Implementation.FullName; } } /// /// The extension of the directory. /// public override string Extension { get { return _implementation.Implementation.Extension; } } /// /// Tells if the directory exists or not. /// public override bool Exists { get { return _implementation.Implementation.Exists; } } /// /// The root directory of the directory. /// public C1DirectoryInfo Root { get { return _implementation.Implementation.Root; } } /// /// The parent directory of the directory. /// public C1DirectoryInfo Parent { get { return _implementation.Implementation.Parent; } } /// /// File attributes of the directory. /// public override FileAttributes Attributes { get { return _implementation.Implementation.Attributes; } set { _implementation.Implementation.Attributes = value; } } /// /// Returns the subdirectories of the directory. /// /// Subdirectories of the directory. public C1DirectoryInfo[] GetDirectories() { return _implementation.Implementation.GetDirectories(); } /// /// Returns the subdirectores of the directory given the search pattern. /// /// Search pattern to use. /// Subdirectories of the directory. public C1DirectoryInfo[] GetDirectories(string searchPattern) { return _implementation.Implementation.GetDirectories(searchPattern); } /// /// Returns the subdirectores of the directory given the search pattern and options. /// /// The search pattern to use. /// The search options to use. /// Subdirectories of the directory. public C1DirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption) { return _implementation.Implementation.GetDirectories(searchPattern, searchOption); } /// /// Returns the files in the directory. /// /// Files in the directory. public C1FileInfo[] GetFiles() { return _implementation.Implementation.GetFiles(); } /// /// Returns the files in the directory given the search pattern. /// /// The search pattern to use. /// Files in the directory given the search pattern. public C1FileInfo[] GetFiles(string searchPattern) { return _implementation.Implementation.GetFiles(searchPattern); } /// /// Returns the files in the directory given the search pattern and options. /// /// The search pattern to use. /// The search options to use. /// Files in the directory given the search pattern and options. public C1FileInfo[] GetFiles(string searchPattern, SearchOption searchOption) { return _implementation.Implementation.GetFiles(searchPattern, searchOption); } /// /// Creates the directory. /// public void Create() { _implementation.Implementation.Create(); } /// /// Creates a subdirectory. /// /// Path to directory to create. /// public C1DirectoryInfo CreateSubdirectory(string path) { return _implementation.Implementation.CreateSubdirectory(path); } /// /// Moves the directory to the given path. /// /// Destination directory name. public void MoveTo(string destDirName) { _implementation.Implementation.MoveTo(destDirName); } /// /// Deletes the directory if empty. /// public override void Delete() { _implementation.Implementation.Delete(); } /// /// Deletes the directory, files and subdirectories if specified. /// /// If true, a recursive delete will be performced. public void Delete(bool recursive) { _implementation.Implementation.Delete(recursive); } /// /// The creation time of the directory. /// public override DateTime CreationTime { get { return _implementation.Implementation.CreationTime; } set { _implementation.Implementation.CreationTime = value; } } /// /// The creation utc time of the directory. /// public override DateTime CreationTimeUtc { get { return _implementation.Implementation.CreationTimeUtc; } set { _implementation.Implementation.CreationTimeUtc = value; } } /// /// Last access time of the directory. /// public override DateTime LastAccessTime { get { return _implementation.Implementation.LastAccessTime; } set { _implementation.Implementation.LastAccessTime = value; } } /// /// Last access utc time of the directory. /// public override DateTime LastAccessTimeUtc { get { return _implementation.Implementation.LastAccessTimeUtc; } set { _implementation.Implementation.LastAccessTimeUtc = value; } } /// /// Last write time of the directory. /// public override DateTime LastWriteTime { get { return _implementation.Implementation.LastWriteTime; } set { _implementation.Implementation.LastWriteTime = value; } } /// /// Last write utc time of the directory. /// public override DateTime LastWriteTimeUtc { get { return _implementation.Implementation.LastWriteTimeUtc; } set { _implementation.Implementation.LastWriteTimeUtc = value; } } /// /// public override void GetObjectData(SerializationInfo info, StreamingContext context) { _implementation.Implementation.GetObjectData(info, context); } /// /// public override void Refresh() { _implementation.Implementation.Refresh(); } // public C1DirectoryInfo CreateSubdirectory(string path, DirectorySecurity directorySecurity); // public FileSystemInfo[] GetFileSystemInfos(); // public FileSystemInfo[] GetFileSystemInfos(string searchPattern); // public void Create(DirectorySecurity directorySecurity); // public DirectorySecurity GetAccessControl(AccessControlSections includeSections); // public void SetAccessControl(DirectorySecurity directorySecurity); // public DirectorySecurity GetAccessControl(); } } ================================================ FILE: Composite/Core/IO/C1File.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Text; using Composite.Core.Implementation; namespace Composite.Core.IO { /// /// This class is a almost one to one version of System.IO.File. Using this implementation instead /// of System.IO.File, will ensure that your code will work both on Standard Windows deployment /// and Windows Azure deployment. /// See System.IO.File for more documentation on the methods of this class. /// See . /// public static class C1File { /// /// Determins if the given file exists or not. /// /// Path to the file. /// Returns true if the file exists, false if not. public static bool Exists(string path) { return ImplementationFactory.CurrentFactory.StatelessC1File.Exists(path); } /// /// This is not a port of the System.IO.File. This method can be used to 'touch' an /// existing file. This is a way of telling the C1 IO system that the file has been /// touched and C1 uses this to handle other than standard Windows deployments, like /// Windows Azure. /// /// Path to file to touch. public static void Touch(string path) { ImplementationFactory.CurrentFactory.StatelessC1File.Touch(path); } /// /// Copies a file. /// /// Source path of file to copy. /// Target path of the file to be copied to. public static void Copy(string sourceFileName, string destFileName) { ImplementationFactory.CurrentFactory.StatelessC1File.Copy(sourceFileName, destFileName); } /// /// Copies a file. /// /// Source path of file to copy. /// Target path of the file to be copied to. /// If this is true and the target path exists, it will be overwritten without any exceptions. public static void Copy(string sourceFileName, string destFileName, bool overwrite) { ImplementationFactory.CurrentFactory.StatelessC1File.Copy(sourceFileName, destFileName, overwrite); } /// /// Moves a file. /// /// Path of file to move. /// Destination path to move the file to. public static void Move(string sourceFileName, string destFileName) { ImplementationFactory.CurrentFactory.StatelessC1File.Move(sourceFileName, destFileName); } /// /// Replace a file with another file. /// /// Path to source file. /// Path to file to replace. /// public static void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { ImplementationFactory.CurrentFactory.StatelessC1File.Replace(sourceFileName, destinationFileName, destinationBackupFileName); } /// /// Replace a file with another file. /// /// Path to source file. /// Path to file to replace. /// /// public static void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { ImplementationFactory.CurrentFactory.StatelessC1File.Replace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors); } /// /// Deletes the given file. /// /// Path to file to delete. public static void Delete(string path) { ImplementationFactory.CurrentFactory.StatelessC1File.Delete(path); } /// /// Creates a new file and returns a file stream to it . /// /// Path to file to create. /// Returns the newly created stream. public static C1FileStream Create(string path) { return ImplementationFactory.CurrentFactory.StatelessC1File.Create(path); } /// /// Creates a new file and returns a file stream to it . /// /// Path to file to create. /// Buffer size of returned stream. /// Returns the newly created stream. public static C1FileStream Create(string path, int bufferSize) { return ImplementationFactory.CurrentFactory.StatelessC1File.Create(path, bufferSize); } /// /// Creates a new file and returns a file stream to it . /// /// Path to file to create. /// Buffer size of returned stream. /// File options of returned stream. /// Returns the newly created stream. public static C1FileStream Create(string path, int bufferSize, FileOptions options) { return ImplementationFactory.CurrentFactory.StatelessC1File.Create(path, bufferSize, options); } /// /// Creates a new file and returns a stream writer to it . /// /// Path to file to create. /// Returns the newly created . public static C1StreamWriter CreateText(string path) { return ImplementationFactory.CurrentFactory.StatelessC1File.CreateText(path); } /// /// Opens a for appending. /// /// Path to file to append to. /// Returns the newly opned . public static C1StreamWriter AppendText(string path) { return ImplementationFactory.CurrentFactory.StatelessC1File.AppendText(path); } /// /// Appends content to a file. /// /// Path to file to append to. /// Content to append to file. public static void AppendAllText(string path, string contents) { ImplementationFactory.CurrentFactory.StatelessC1File.AppendAllText(path, contents); } /// /// Appends content to a file. /// /// Path to file to append to. /// Content to append to file. /// Encoding to use when appending. public static void AppendAllText(string path, string contents, Encoding encoding) { ImplementationFactory.CurrentFactory.StatelessC1File.AppendAllText(path, contents, encoding); } /// /// Appends content to a file. /// /// Path to file to append to. /// Content to append to file. public static void AppendAllLines(string path, IEnumerable contents) { ImplementationFactory.CurrentFactory.StatelessC1File.AppendAllLines(path, contents); } /// /// Appends content to a file. /// /// Path to file to append to. /// Content to append to file. /// Encoding to use when appending. public static void AppendAllLines(string path, IEnumerable contents, Encoding encoding) { ImplementationFactory.CurrentFactory.StatelessC1File.AppendAllLines(path, contents, encoding); } /// /// Opens a file. /// /// Path to file to open. /// File mode to use. /// Returns the newly opened . public static C1FileStream Open(string path, FileMode mode) { return ImplementationFactory.CurrentFactory.StatelessC1File.Open(path, mode); } /// /// Opens a file. /// /// Path to file to open. /// File mode to use. /// File access to use. /// Returns the newly opened . public static C1FileStream Open(string path, FileMode mode, FileAccess access) { return ImplementationFactory.CurrentFactory.StatelessC1File.Open(path, mode, access); } /// /// Opens a file. /// /// Path to file to open. /// File mode to use. /// File access to use. /// File share to use. /// Returns the newly opened . public static C1FileStream Open(string path, FileMode mode, FileAccess access, FileShare share) { return ImplementationFactory.CurrentFactory.StatelessC1File.Open(path, mode, access, share); } /// /// Opens a file for reading. /// /// Path to file to open. /// Returns the newly opened . public static C1FileStream OpenRead(string path) { return ImplementationFactory.CurrentFactory.StatelessC1File.OpenRead(path); } /// /// Opens a file. /// /// Path to file to open. /// Returns the newly opened . public static C1StreamReader OpenText(string path) { return ImplementationFactory.CurrentFactory.StatelessC1File.OpenText(path); } /// /// Opens a file for writing. /// /// Path to file to open. /// Returns the newly opened . public static C1FileStream OpenWrite(string path) { return ImplementationFactory.CurrentFactory.StatelessC1File.OpenWrite(path); } /// /// Read all bytes from a file. /// /// Path to file to read from. /// Returns read bytes. public static byte[] ReadAllBytes(string path) { return ImplementationFactory.CurrentFactory.StatelessC1File.ReadAllBytes(path); } /// /// Read all lines from a file. /// /// Path to file to read from. /// Returns read lines. public static string[] ReadAllLines(string path) { return ImplementationFactory.CurrentFactory.StatelessC1File.ReadAllLines(path); } /// /// Read all lines from a file. /// /// Path to file to read from. /// Encoding to use when reading. /// Returns read lines. public static string[] ReadAllLines(string path, Encoding encoding) { return ImplementationFactory.CurrentFactory.StatelessC1File.ReadAllLines(path, encoding); } /// /// Read all text from a file. /// /// Path to file to read from. /// The content of the file. public static string ReadAllText(string path) { return ImplementationFactory.CurrentFactory.StatelessC1File.ReadAllText(path); } /// /// Read all text from a file. /// /// Path to file to read from. /// Encoding to use when reading. /// The content of the file. public static string ReadAllText(string path, Encoding encoding) { return ImplementationFactory.CurrentFactory.StatelessC1File.ReadAllText(path, encoding); } /// /// Read all lines from a file. /// /// Path to file to read from. /// Returns all read lines. public static IEnumerable ReadLines(string path) { return ImplementationFactory.CurrentFactory.StatelessC1File.ReadLines(path); } /// /// Read all lines from a file. /// /// Path to file to read from. /// Encoding to use when reading. /// Returns all read lines. public static IEnumerable ReadLines(string path, Encoding encoding) { return ImplementationFactory.CurrentFactory.StatelessC1File.ReadLines(path, encoding); } /// /// Writes bytes to a file. /// /// Path to file to write to. /// Bytes to write. public static void WriteAllBytes(string path, byte[] bytes) { ImplementationFactory.CurrentFactory.StatelessC1File.WriteAllBytes(path, bytes); } /// /// Writes lines to a file. /// /// Path to file to write to. /// Lines to write. public static void WriteAllLines(string path, IEnumerable contents) { ImplementationFactory.CurrentFactory.StatelessC1File.WriteAllLines(path, contents); } /// /// Writes lines to a file. /// /// Path to file to write to. /// Lines to write. public static void WriteAllLines(string path, string[] contents) { ImplementationFactory.CurrentFactory.StatelessC1File.WriteAllLines(path, contents); } /// /// Writes lines to a file. /// /// Path to file to write to. /// Lines to write. /// Encoding to use when writing. public static void WriteAllLines(string path, IEnumerable contents, Encoding encoding) { ImplementationFactory.CurrentFactory.StatelessC1File.WriteAllLines(path, contents, encoding); } /// /// Writes lines to a file. /// /// Path to file to write to. /// Lines to write. /// Encoding to use when writing. public static void WriteAllLines(string path, string[] contents, Encoding encoding) { ImplementationFactory.CurrentFactory.StatelessC1File.WriteAllLines(path, contents, encoding); } /// /// Writes text to a file. /// /// Path to file to write to. /// Text to write. public static void WriteAllText(string path, string contents) { ImplementationFactory.CurrentFactory.StatelessC1File.WriteAllText(path, contents); } /// /// Writes text to a file. /// /// Path to file to write to. /// Text to write. /// Encoding to use when writing. public static void WriteAllText(string path, string contents, Encoding encoding) { ImplementationFactory.CurrentFactory.StatelessC1File.WriteAllText(path, contents, encoding); } /// /// Gets the file attributes. /// /// Path to file to get attributes from. /// Returns the file attributes. See System.IO.FileAttributes public static FileAttributes GetAttributes(string path) { return ImplementationFactory.CurrentFactory.StatelessC1File.GetAttributes(path); } /// /// Sets the file attributes. /// /// Path to file to set attributes on. /// File attributes to set. public static void SetAttributes(string path, FileAttributes fileAttributes) { ImplementationFactory.CurrentFactory.StatelessC1File.SetAttributes(path, fileAttributes); } /// /// Gets the creation time of the file. /// /// Path to file. /// Returns the creation time of the given file. public static DateTime GetCreationTime(string path) { return ImplementationFactory.CurrentFactory.StatelessC1File.GetCreationTime(path); } /// /// Gets the creation utc time of the file. /// /// Path to file. /// Returns the creation utc time of the given file. public static DateTime GetCreationTimeUtc(string path) { return ImplementationFactory.CurrentFactory.StatelessC1File.GetCreationTimeUtc(path); } /// /// Sets the creation time of the file. /// /// Path to file. /// New creation time. public static void SetCreationTime(string path, DateTime creationTime) { ImplementationFactory.CurrentFactory.StatelessC1File.SetCreationTime(path, creationTime); } /// /// Sets the creation utc time of the file. /// /// Path to file. /// New creation utc time. public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc) { ImplementationFactory.CurrentFactory.StatelessC1File.SetCreationTimeUtc(path, creationTimeUtc); } /// /// Gets the last access time. /// /// Path to file. /// Returns the last access time of the file. public static DateTime GetLastAccessTime(string path) { return ImplementationFactory.CurrentFactory.StatelessC1File.GetLastAccessTime(path); } /// /// Gets the last access utc time. /// /// Path to file. /// Returns the last access utc time of the file. public static DateTime GetLastAccessTimeUtc(string path) { return ImplementationFactory.CurrentFactory.StatelessC1File.GetLastAccessTimeUtc(path); } /// /// Sets the last access time of the file. /// /// Path to file. /// New last access time. public static void SetLastAccessTime(string path, DateTime lastAccessTime) { ImplementationFactory.CurrentFactory.StatelessC1File.SetLastAccessTime(path, lastAccessTime); } /// /// Sets the last access utc time of the file. /// /// Path to file. /// New last access utc time. public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) { ImplementationFactory.CurrentFactory.StatelessC1File.SetLastAccessTimeUtc(path, lastAccessTimeUtc); } /// /// Get last write time of the file. /// /// Path to file. /// Returns the last write time of the file. public static DateTime GetLastWriteTime(string path) { return ImplementationFactory.CurrentFactory.StatelessC1File.GetLastWriteTime(path); } /// /// Get last write utc time of the file. /// /// Path to file. /// Returns the last write utc time of the file. public static DateTime GetLastWriteTimeUtc(string path) { return ImplementationFactory.CurrentFactory.StatelessC1File.GetLastWriteTimeUtc(path); } /// /// Sets the last write time of the file. /// /// Path to file. /// New last write time. public static void SetLastWriteTime(string path, DateTime lastWriteTime) { ImplementationFactory.CurrentFactory.StatelessC1File.SetLastWriteTime(path, lastWriteTime); } /// /// Sets the last write utc time of the file. /// /// Path to file. /// New last write utc time. public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) { ImplementationFactory.CurrentFactory.StatelessC1File.SetLastWriteTimeUtc(path, lastWriteTimeUtc); } //public static FileStream Create(string path, int bufferSize, System.IO.FileOptions options, System.Security.AccessControl.FileSecurity fileSecurity) //{ // throw new NotImplementedException(); //} //public static void Encrypt(string path) //{ // throw new NotImplementedException(); //} //public static void Decrypt(string path) //{ // throw new NotImplementedException(); //} //public static System.Security.AccessControl.FileSecurity GetAccessControl(string path) //{ // throw new NotImplementedException(); //} //public static System.Security.AccessControl.FileSecurity GetAccessControl(string path, System.Security.AccessControl.AccessControlSections includeSections) //{ // throw new NotImplementedException(); //} //public static void SetAccessControl(string path, System.Security.AccessControl.FileSecurity fileSecurity) //{ // throw new NotImplementedException(); //} } } ================================================ FILE: Composite/Core/IO/C1FileInfo.cs ================================================ using System; using System.IO; using System.Runtime.Serialization; using Composite.Core.Implementation; namespace Composite.Core.IO { /// /// This class is a almost one to one version of System.IO.FileInfo. Using this implementation instead /// of System.IO.FileInfo, will ensure that your code will work both on Standard Windows deployment /// and Windows Azure deployment. /// See System.IO.FileInfo for more documentation on the methods of this class. /// See . /// public class C1FileInfo : C1FileSystemInfo { private ImplementationContainer _implementation; /// /// Creates a C1FileInfo. /// /// Path to file. public C1FileInfo(string fileName) { _implementation = new ImplementationContainer(() => ImplementationFactory.CurrentFactory.CreateC1FileInfo(fileName)); _implementation.CreateImplementation(); } /// /// Returns the directory name of the file. /// public string DirectoryName { get { return _implementation.Implementation.DirectoryName; } } /// /// Returns a of the file. /// public C1DirectoryInfo Directory { get { return _implementation.Implementation.Directory; } } /// /// Returns the name of the file. /// public string Name { get { return _implementation.Implementation.Name; } } /// /// Returns the full path and name of the file. /// public override string FullName { get { return _implementation.Implementation.FullName; } } /// /// Returns true if the file exists. Otherwise false. /// public override bool Exists { get { return _implementation.Implementation.Exists; } } /// /// Returns the extension of the file. /// public override string Extension { get { return _implementation.Implementation.Extension; } } /// /// Returns true if and only if the file is read only. /// public bool IsReadOnly { get { return _implementation.Implementation.IsReadOnly; } } /// /// Returns the size of the file in bytes. /// public long Length { get { return _implementation.Implementation.Length; } } /// /// Gets or sets the file attributes on the file. /// public override FileAttributes Attributes { get { return _implementation.Implementation.Attributes; } set { _implementation.Implementation.Attributes = value; } } /// /// Creates a file stream . /// /// Returns a newly created . public C1FileStream Create() { return _implementation.Implementation.Create(); } /// /// Creates a file stream . /// /// Returns a newly created . public C1StreamWriter CreateText() { return _implementation.Implementation.CreateText(); } /// /// Creates a file stream for appending. /// /// Returns a newly created for appending. public C1StreamWriter AppendText() { return _implementation.Implementation.AppendText(); } /// /// Creates a file stream . /// /// File mode to use. /// Returns a newly created . public C1FileStream Open(FileMode mode) { return _implementation.Implementation.Open(mode); } /// /// Creates a file stream . /// /// File mode to use. /// File access to use. /// Returns a newly created . public C1FileStream Open(FileMode mode, FileAccess access) { return _implementation.Implementation.Open(mode, access); } /// /// Creates a file stream . /// /// File mode to use. /// File access to use. /// File share to use. /// Returns a newly created . public C1FileStream Open(FileMode mode, FileAccess access, FileShare share) { return _implementation.Implementation.Open(mode, access, share); } /// /// Creates a file stream . /// /// Returns a newly created for reading. public C1FileStream OpenRead() { return _implementation.Implementation.OpenRead(); } /// /// Creates a file stream . /// /// Returns a newly created . public C1StreamReader OpenText() { return _implementation.Implementation.OpenText(); } /// /// Creates a file stream . /// /// Returns a newly created for writing. public C1FileStream OpenWrite() { return _implementation.Implementation.OpenWrite(); } /// /// Copies the file to the given path. /// /// Destination path. /// A new for the destination file. public C1FileInfo CopyTo(string destFileName) { return _implementation.Implementation.CopyTo(destFileName); } /// /// Copies the file to the given path and overwrites any existing file if specified. /// /// Destination path. /// If true, any existing file will be overwritten. /// A new for the destination file. public C1FileInfo CopyTo(string destFileName, bool overwrite) { return _implementation.Implementation.CopyTo(destFileName, overwrite); } /// /// Moves the file to the given path. /// /// Destination path. public void MoveTo(string destFileName) { _implementation.Implementation.MoveTo(destFileName); } /// /// Replaces the given file with this one. /// /// Destination path to file to replace. /// Path to backup file. /// A new for the destination file. public C1FileInfo Replace(string destinationFileName, string destinationBackupFileName) { return _implementation.Implementation.Replace(destinationFileName, destinationBackupFileName); } /// /// Replaces the given file with this one. /// /// Destination path to file to replace. /// Path to backup file. /// /// A new for the destination file. public C1FileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { return _implementation.Implementation.Replace(destinationFileName, destinationBackupFileName, ignoreMetadataErrors); } /// /// Deletes the file. /// public override void Delete() { _implementation.Implementation.Delete(); } /// /// Gets or sets the creation time of the file. /// public override DateTime CreationTime { get { return _implementation.Implementation.CreationTime; } set { _implementation.Implementation.CreationTime = value; } } /// /// Gets or sets the creation utc time of the file. /// public override DateTime CreationTimeUtc { get { return _implementation.Implementation.CreationTimeUtc; } set { _implementation.Implementation.CreationTimeUtc = value; } } /// /// Gets or sets the last access time of the file. /// public override DateTime LastAccessTime { get { return _implementation.Implementation.LastAccessTime; } set { _implementation.Implementation.LastAccessTime = value; } } /// /// Gets or sets the last access utc time of the file. /// public override DateTime LastAccessTimeUtc { get { return _implementation.Implementation.LastAccessTimeUtc; } set { _implementation.Implementation.LastAccessTimeUtc = value; } } /// /// Gets or sets the last write time of the file. /// public override DateTime LastWriteTime { get { return _implementation.Implementation.LastWriteTime; } set { _implementation.Implementation.LastWriteTime = value; } } /// /// Gets or sets the last write utc time of the file. /// public override DateTime LastWriteTimeUtc { get { return _implementation.Implementation.LastWriteTimeUtc; } set { _implementation.Implementation.LastWriteTimeUtc = value; } } /// /// public override void Refresh() { _implementation.Implementation.Refresh(); } /// /// /// /// public override void GetObjectData(SerializationInfo info, StreamingContext context) { _implementation.Implementation.GetObjectData(info, context); } //public FileSecurity GetAccessControl(); //public FileSecurity GetAccessControl(AccessControlSections includeSections); //public void SetAccessControl(FileSecurity fileSecurity); //public void Decrypt(); //public void Encrypt(); } } ================================================ FILE: Composite/Core/IO/C1FileStream.cs ================================================ using System; using System.IO; using Composite.Core.Implementation; namespace Composite.Core.IO { /// /// This class is a almost one to one version of System.IO.FileStream. Using this implementation instead /// of System.IO.FileStream, will ensure that your code will work both on Standard Windows deployment /// and Windows Azure deployment. /// See System.IO.FileStream for more documentation on the methods of this class. /// See . /// public class C1FileStream : Stream { private bool _disposed; private readonly ImplementationContainer _implementation; /// /// Creates a new C1FileStream. /// /// Path to file. /// File mode to use. public C1FileStream(string path, FileMode mode) : this(path, mode, (mode == FileMode.Append) ? FileAccess.Write : FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.None) { } /// /// Creates a new C1FileStream. /// /// Path to file. /// File mode to use. /// File access to use. public C1FileStream(string path, FileMode mode, FileAccess access) : this(path, mode, access, FileShare.Read, 4096, FileOptions.None) { } /// /// Creates a new C1FileStream. /// /// Path to file. /// File mode to use. /// File access to use. /// File share to use. public C1FileStream(string path, FileMode mode, FileAccess access, FileShare share) : this(path, mode, access, share, 4096, FileOptions.None) { } /// /// Creates a new C1FileStream. /// /// Path to file. /// File mode to use. /// File access to use. /// File share to use. /// Buffer size to use. public C1FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) : this(path, mode, access, share, bufferSize, FileOptions.None) { } /// /// Creates a new C1FileStream. /// /// Path to file. /// File mode to use. /// File access to use. /// File share to use. /// Buffer size to use. /// File options to use. public C1FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { _implementation = new ImplementationContainer(() => ImplementationFactory.CurrentFactory.CreateC1FileStream(path, mode, access, share, bufferSize, options)); _implementation.CreateImplementation(); } /// /// Name of the file. /// public string Name => _implementation.Implementation.Name; /// /// Size of the file in bytes. /// public override long Length => _implementation.Implementation.Length; /// /// Sets the length of the file in bytes. /// /// New length of file stream. public override void SetLength(long value) { _implementation.Implementation.SetLength(value); } /// /// Gets or sets the current read/write position in the file stream. /// public override long Position { get { return _implementation.Implementation.Position; } set { _implementation.Implementation.Position = value; } } /// /// Reads a block of bytes from the file stream. /// /// Target buffer of read bytes. /// Offset in the buffer to put read bytes. /// Number of bytes to read. /// Number of bytes read. public override int Read(byte[] array, int offset, int count) { return _implementation.Implementation.Read(array, offset, count); } /// /// Reads a byte form the file stream. /// /// The read byte value. public override int ReadByte() { return _implementation.Implementation.ReadByte(); } /// /// Writes a block of bytes to the file stream. /// /// Bytes to write to the file. /// Offset in buffer to write from. /// Number of bytes to write. public override void Write(byte[] array, int offset, int count) { _implementation.Implementation.Write(array, offset, count); } /// /// Writes a byte to the file stream. /// /// Byte value to write. public override void WriteByte(byte value) { _implementation.Implementation.WriteByte(value); } /// /// Seeks to a position in the file stream. /// /// Offset to seek. /// Origin to seek from. /// The new position in the stream. public override long Seek(long offset, SeekOrigin origin) { return _implementation.Implementation.Seek(offset, origin); } /// /// Returns true if its possible to read from the stream. /// public override bool CanRead => _implementation.Implementation.CanRead; /// /// Returns true if its possible to seek in the stream. /// public override bool CanSeek => _implementation.Implementation.CanSeek; /// /// Returns true if its possible to write to the stream. /// public override bool CanWrite => _implementation.Implementation.CanWrite; /// /// Flushes the buffered bytes to the file. /// public override void Flush() { _implementation.Implementation.Flush(); } /// /// Flushes the buffered bytes to the file. /// /// public virtual void Flush(bool flushToDisk) { _implementation.Implementation.Flush(flushToDisk); } /// /// Disposes the file stream. /// /// protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; _implementation.DisposeImplementation(); } } } } ================================================ FILE: Composite/Core/IO/C1FileSystemInfo.cs ================================================ using System; using System.IO; using System.Runtime.Serialization; namespace Composite.Core.IO { /// /// This class is a almost one to one version of System.IO.FileSystemInfo. Using this implementation instead /// of System.IO.FileSystemInfo, will ensure that your code will work both on Standard Windows deployment /// and Windows Azure deployment. /// See System.IO.FileSystemInfo for more documentation on the methods of this class. /// public abstract class C1FileSystemInfo { /// /// Full path name. /// public abstract string FullName { get; } /// /// Extension. /// public abstract string Extension { get; } /// /// Returns true if the file system item exitst. /// public abstract bool Exists { get; } /// /// File attributes of the file system item. /// public abstract FileAttributes Attributes { get; set; } /// /// Deletes the file system item. /// public abstract void Delete(); /// /// Gets or sets the creation time of the file system item. /// public abstract DateTime CreationTime { get; set; } /// /// Gets or sets the creation utc time of the file system item. /// public abstract DateTime CreationTimeUtc { get; set; } /// /// Gets or sets the last access time of the file system item. /// public abstract DateTime LastAccessTime { get; set; } /// /// Gets or sets the last access utc time of the file system item. /// public abstract DateTime LastAccessTimeUtc { get; set; } /// /// Gets or sets the last write time of the file system item. /// public abstract DateTime LastWriteTime { get; set; } /// /// Gets or sets the last write utc time of the file system item. /// public abstract DateTime LastWriteTimeUtc { get; set; } /// /// public abstract void GetObjectData(SerializationInfo info, StreamingContext context); /// /// public abstract void Refresh(); } } ================================================ FILE: Composite/Core/IO/C1FileSystemWatcher.cs ================================================ using System; using System.IO; using Composite.Core.Implementation; namespace Composite.Core.IO { /// /// This class is a almost one to one version of System.IO.FileSystemWatcher. Using this implementation instead /// of System.IO.FileSystemWatcher, will ensure that your code will work both on Standard Windows deployment /// and Windows Azure deployment. /// See System.IO.FileSystemWatcher for more documentation on the methods of this class. /// See . /// public class C1FileSystemWatcher : ImplementationContainer, IDisposable { /// /// Creates a new file system watcher given the path. /// /// Path to watch. public C1FileSystemWatcher(string path) : this(path, null) { } /// /// Creates a new file system watcher given the path. /// /// Path to watch. /// Filter to use. public C1FileSystemWatcher(string path, string filter) : base(() => ImplementationFactory.CurrentFactory.CreateC1FileSystemWatcher(path, filter)) { } /// /// Gets or sets if events should be raised or not. /// public bool EnableRaisingEvents { get { return this.Implementation.EnableRaisingEvents; } set { this.Implementation.EnableRaisingEvents = value; } } /// /// Path to watch. /// public string Path { get { return this.Implementation.Path; } set { this.Implementation.Path = value; } } /// /// Filter to use. /// public string Filter { get { return this.Implementation.Filter; } set { this.Implementation.Filter = value; } } /// /// Gets or sets of subdirectories should also be watched. /// public bool IncludeSubdirectories { get { return this.Implementation.IncludeSubdirectories; } set { this.Implementation.IncludeSubdirectories = value; } } /// /// Gets or sets the size of an internal buffer. /// public int InternalBufferSize { get { return this.Implementation.InternalBufferSize; } set { this.Implementation.InternalBufferSize = value; } } /// /// Adds or removes an event handler when new items are created. /// public event FileSystemEventHandler Created { add { this.Implementation.Created += value; } remove { this.Implementation.Created -= value; } } /// /// Adds or removes an event handler when new items changed. /// public event FileSystemEventHandler Changed { add { this.Implementation.Changed += value; } remove { this.Implementation.Changed -= value; } } /// /// Adds or removes an event handler when new items are renamed. /// public event RenamedEventHandler Renamed { add { this.Implementation.Renamed += value; } remove { this.Implementation.Renamed -= value; } } /// /// Adds or removes an event handler when new items are deleted. /// public event FileSystemEventHandler Deleted { add { this.Implementation.Deleted += value; } remove { this.Implementation.Deleted -= value; } } /// /// Adds or removes an event handler when an error occur. /// public event ErrorEventHandler Error { add { this.Implementation.Error += value; } remove { this.Implementation.Error -= value; } } /// /// Gets or sets the notify filter. /// public NotifyFilters NotifyFilter { get { return this.Implementation.NotifyFilter; } set { this.Implementation.NotifyFilter = value; } } /// /// Begins the initialization. /// public void BeginInit() { Log.LogInformation("C1FileSystemWatcher", "BeginInit starting"); this.Implementation.BeginInit(); Log.LogInformation("C1FileSystemWatcher", "BeginInit done"); } /// /// Ends the initialization. /// public void EndInit() { this.Implementation.EndInit(); } /// /// /// /// public C1WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) { return this.Implementation.WaitForChanged(changeType); } /// /// /// /// /// public C1WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout) { return this.Implementation.WaitForChanged(changeType, timeout); } void IDisposable.Dispose() { Dispose(true); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// /// Destructor. /// ~C1FileSystemWatcher() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); Dispose(false); } #endif /// /// Disposes the stream. /// /// True if the stream is disposing. protected void Dispose(bool disposing) { if (disposing) { DisposeImplementation(); } } } } ================================================ FILE: Composite/Core/IO/C1StreamReader.cs ================================================ using System; using System.IO; using System.Runtime.InteropServices; using System.Text; using Composite.Core.Implementation; namespace Composite.Core.IO { /// /// This class is a almost one to one version of System.IO.StreamReader. Using this implementation instead /// of System.IO.StreamReader, will ensure that your code will work both on Standard Windows deployment /// and Windows Azure deployment. /// See System.IO.StreamReader for more documentation on the methods of this class. /// See . /// public class C1StreamReader : TextReader, IDisposable { private ImplementationContainer _implementation; /// /// Creates a C1StreamReader. /// /// Path to file. public C1StreamReader(string path) : this(path, Encoding.UTF8, true, 1024) { } /// /// Creates a C1StreamReader. /// /// Path to file. /// If true, the encoding will be deteced by the content of the file. public C1StreamReader(string path, bool detectEncodingFromByteOrderMarks) : this(path, Encoding.UTF8, detectEncodingFromByteOrderMarks, 1024) { } /// /// Creates a C1StreamReader. /// /// Path to the file. /// Encoding to use. public C1StreamReader(string path, Encoding encoding) : this(path, encoding, true, 1024) { } /// /// Creates a C1StreamReader. /// /// Path to the file. /// Encoding to use. /// If true, the encoding will be deteced by the content of the file. public C1StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks) : this(path, encoding, detectEncodingFromByteOrderMarks, 1024) { } /// /// Creates a C1StreamReader. /// /// Path to the file. /// Encoding to use. /// If true, the encoding will be deteced by the content of the file. /// Buffer size to use. public C1StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { _implementation = new ImplementationContainer(() => ImplementationFactory.CurrentFactory.CreateC1StreamReader(path, encoding, detectEncodingFromByteOrderMarks, bufferSize)); } /// /// Creates a C1StreamReader. /// /// Stream to ream from. public C1StreamReader(Stream stream) : this(stream, Encoding.UTF8, true, 1024) { } /// /// Creates a C1StreamReader. /// /// Stream to ream from. /// If true, the encoding will be deteced by the content of the file. public C1StreamReader(Stream stream, bool detectEncodingFromByteOrderMarks) : this(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks, 1024) { } /// /// Creates a C1StreamReader. /// /// Stream to ream from. /// Encoding to use. public C1StreamReader(Stream stream, Encoding encoding) : this(stream, encoding, true, 1024) { } /// /// Creates a C1StreamReader. /// /// Stream to ream from. /// Encoding to use. /// If true, the encoding will be deteced by the content of the file. public C1StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks) : this(stream, encoding, detectEncodingFromByteOrderMarks, 1024) { } /// /// Creates a C1StreamReader. /// /// Stream to ream from. /// Encoding to use. /// If true, the encoding will be deteced by the content of the file. /// Buffer size to use. public C1StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { _implementation = new ImplementationContainer(() => ImplementationFactory.CurrentFactory.CreateC1StreamReader(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize)); } /// /// Reads a byte from the stream. /// /// Returns the read byte. public override int Read() { return _implementation.Implementation.Read(); } /// /// Reads a block from the file. /// /// Buffer to read into. /// Index in buffer to start storing bytes. /// Number of bytes to read. /// Returns the number read bytes. public override int Read(char[] buffer, int index, int count) { return _implementation.Implementation.Read(buffer, index, count); } /// /// Read a line from the file. /// /// Returns the read line. public override string ReadLine() { return _implementation.Implementation.ReadLine(); } /// /// Read all the content of the file into a strng. /// /// The content of the file. public override string ReadToEnd() { return _implementation.Implementation.ReadToEnd(); } /// /// Reads a block from the file. /// /// Buffer to store read chars. /// Index in buffer to start storing chars. /// Number of chars to read. /// Returns the number of read chars. public override int ReadBlock(char[] buffer, int index, int count) { return _implementation.Implementation.ReadBlock(buffer, index, count); } /// /// Peeks the current byte. /// /// The current byte. public override int Peek() { return _implementation.Implementation.Peek(); } /// /// Returns true if the stream is at the end of stream. /// public bool EndOfStream { get { return _implementation.Implementation.EndOfStream; } } /// /// Closes the stream. /// public override void Close() { _implementation.Implementation.Close(); } /// /// Returns the base stream. /// public virtual Stream BaseStream { get { return _implementation.Implementation.BaseStream; } } /// /// Returns the current encoding of the stream. /// public virtual Encoding CurrentEncoding { get { return _implementation.Implementation.CurrentEncoding; } } #if LeakCheck private string stack = Environment.StackTrace; /// /// Destructor. /// ~C1StreamReader() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); Dispose(false); } #endif /// /// Disposes the stream. /// /// Ttrue if the stream is disposing. protected override void Dispose(bool disposing) { if (disposing) { _implementation.DisposeImplementation(); } } //public void DiscardBufferedData() //{ // throw new NotImplementedException(); //} } } ================================================ FILE: Composite/Core/IO/C1StreamWriter.cs ================================================ using System; using System.IO; using System.Text; using Composite.Core.Implementation; namespace Composite.Core.IO { /// /// This class is a almost one to one version of System.IO.StreamWriter. Using this implementation instead /// of System.IO.StreamWriter, will ensure that your code will work both on Standard Windows deployment /// and Windows Azure deployment. /// See System.IO.StreamWriter for more documentation on the methods of this class. /// See . /// public class C1StreamWriter : TextWriter, IDisposable { private ImplementationContainer _implementation; /// /// Creates a C1StreamWriter. /// /// Path to file. public C1StreamWriter(string path) : this(path, false, Encoding.UTF8, 1024) { } /// /// Creates a C1StreamWriter. /// /// Path to file. /// If this is true, any writing will be appended to the file. public C1StreamWriter(string path, bool append) : this(path, append, Encoding.UTF8, 1024) { } /// /// Creates a C1StreamWriter. /// /// Path to file. /// If this is true, any writing will be appended to the file. /// Encoding to use. public C1StreamWriter(string path, bool append, Encoding encoding) : this(path, append, encoding, 1024) { } /// /// Creates a C1StreamWriter. /// /// Path to file. /// If this is true, any writing will be appended to the file. /// Encoding to use. /// Buffer size to use. public C1StreamWriter(string path, bool append, Encoding encoding, int bufferSize) { _implementation = new ImplementationContainer(() => ImplementationFactory.CurrentFactory.CreateC1StreamWriter(path, append, encoding, bufferSize)); } /// /// Creates a C1StreamWriter. /// /// Stream to use. public C1StreamWriter(Stream stream) : this(stream, Encoding.UTF8, 1024) { } /// /// Creates a C1StreamWriter. /// /// Stream to use. /// Encoding to use. public C1StreamWriter(Stream stream, Encoding encoding) : this(stream, encoding, 1024) { } /// /// Creates a C1StreamWriter. /// /// Stream to use. /// Encoding to use. /// Buffer size to use. public C1StreamWriter(Stream stream, Encoding encoding, int bufferSize) { _implementation = new ImplementationContainer(() => ImplementationFactory.CurrentFactory.CreateC1StreamWriter(stream, encoding, bufferSize)); } /// /// Writes a string to the stream. /// /// String to write. public override void Write(string value) { _implementation.Implementation.Write(value); } /// /// Writes a formatted string to the stream. /// /// String with formatting to write. /// String format argument. public override void Write(string format, object arg0) { _implementation.Implementation.Write(format, arg0); } /// /// Writes a formatted string to the stream. /// /// String with formatting to write. /// String format argument. /// String format argument. public override void Write(string format, object arg0, object arg1) { _implementation.Implementation.Write(format, arg0, arg1); } /// /// Writes a formatted string to the stream. /// /// String with formatting to write. /// String format argument. /// String format argument. /// String format argument. public override void Write(string format, object arg0, object arg1, object arg2) { _implementation.Implementation.Write(format, arg0, arg1, arg2); } /// /// Writes a formatted string to the stream. /// /// String with formatting to write. /// String format arguments. public override void Write(string format, params object[] arg) { _implementation.Implementation.Write(format, arg); } /// /// Writes a char to the stream. /// /// The char value to write. public override void Write(char value) { _implementation.Implementation.Write(value); } /// /// Writes a char array to the stream. /// /// Char array to write. public override void Write(char[] buffer) { _implementation.Implementation.Write(buffer); } /// /// Writes a char array to the stream. /// /// Char array to write. /// Start index in the buffer to start writing from. /// Number of chars to write. public override void Write(char[] buffer, int index, int count) { _implementation.Implementation.Write(buffer, index, count); } /// /// Writes a boolean to the stream. /// /// Boolean value to write. public override void Write(bool value) { _implementation.Implementation.Write(value); } /// /// Writes an integer to the stream. /// /// Integer value to write. public override void Write(int value) { _implementation.Implementation.Write(value); } /// /// Writes an unsigned integer to the stream. /// /// Unsigned integer value to write public override void Write(uint value) { _implementation.Implementation.Write(value); } /// /// Writes a long to the stream. /// /// Long value to write. public override void Write(long value) { _implementation.Implementation.Write(value); } /// /// Writes an unsigned long to the stream. /// /// Unsigned long value to write. public override void Write(ulong value) { _implementation.Implementation.Write(value); } /// /// Writes a float to the stream. /// /// Float value to write. public override void Write(float value) { _implementation.Implementation.Write(value); } /// /// Writes a double to the stream. /// /// Double value to write. public override void Write(double value) { _implementation.Implementation.Write(value); } /// /// Writes a decimal to the stream. /// /// Decimal value to write. public override void Write(decimal value) { _implementation.Implementation.Write(value); } /// /// Write an object to the stream. /// /// Object value to write. public override void Write(object value) { _implementation.Implementation.Write(value); } /// /// Writes a line break to the stream. /// public override void WriteLine() { _implementation.Implementation.WriteLine(); } /// /// Writes a string with a line break to the stream. /// /// String value to write. public override void WriteLine(string value) { _implementation.Implementation.WriteLine(value); } /// /// Writes a string with a line break to the stream. /// /// String with formatting to write. /// String format argument. public override void WriteLine(string format, object arg0) { _implementation.Implementation.WriteLine(format, arg0); } /// /// Writes a string with a line break to the stream. /// /// String with formatting to write. /// String format argument. /// String format argument. public override void WriteLine(string format, object arg0, object arg1) { _implementation.Implementation.WriteLine(format, arg0, arg1); } /// /// Writes a string with a line break to the stream. /// /// String with formatting to write. /// String format argument. /// String format argument. /// String format argument. public override void WriteLine(string format, object arg0, object arg1, object arg2) { _implementation.Implementation.WriteLine(format, arg0, arg1, arg2); } /// /// Writes a string with a line break to the stream. /// /// String with formatting to write. /// String format arguments. public override void WriteLine(string format, params object[] arg) { _implementation.Implementation.WriteLine(format, arg); } /// /// Writes a char with a line break to the stream. /// /// Char value to write. public override void WriteLine(char value) { _implementation.Implementation.WriteLine(value); } /// /// Writes a char array with a line break to the stream. /// /// Char array to write. public override void WriteLine(char[] buffer) { _implementation.Implementation.WriteLine(buffer); } /// /// Writes a char array with a line break to the stream. /// /// Char array to write. /// Index in the char array to start writing from. /// Number of chars to write. public override void WriteLine(char[] buffer, int index, int count) { _implementation.Implementation.WriteLine(buffer, index, count); } /// /// Writes a bool with a line break to the stream. /// /// Bool value to write. public override void WriteLine(bool value) { _implementation.Implementation.WriteLine(value); } /// /// Writes an integer with a line break to the stream. /// /// Integer value to write. public override void WriteLine(int value) { _implementation.Implementation.WriteLine(value); } /// /// Writes an unsigned integer with a line break to the stream. /// /// Unsigned integer to write. public override void WriteLine(uint value) { _implementation.Implementation.WriteLine(value); } /// /// Writes a long with a line break to the stream. /// /// Long value to write. public override void WriteLine(long value) { _implementation.Implementation.WriteLine(value); } /// /// Writes an unsigned long with a line break to the stream. /// /// Unsigned long value to write. public override void WriteLine(ulong value) { _implementation.Implementation.WriteLine(value); } /// /// Writes a float with a line break to the stream. /// /// Float value to write. public override void WriteLine(float value) { _implementation.Implementation.WriteLine(value); } /// /// Writes a double with a line break to the stream. /// /// Double value to write. public override void WriteLine(double value) { _implementation.Implementation.WriteLine(value); } /// /// Writes a decimal with a line break to the stream. /// /// Decimal value to write. public override void WriteLine(decimal value) { _implementation.Implementation.WriteLine(value); } /// /// Writes an object with a line break to the stream. /// /// Object value to write. public override void WriteLine(object value) { _implementation.Implementation.WriteLine(value); } /// /// Gets or sets the line break value. /// public override string NewLine { get { return _implementation.Implementation.NewLine; } set { _implementation.Implementation.NewLine = value; } } /// /// Gets the format provider used. /// public override IFormatProvider FormatProvider { get { return _implementation.Implementation.FormatProvider; } } /// /// Flushes the stream. /// public override void Flush() { _implementation.Implementation.Flush(); } /// /// Gets or sets whether the stream is auto flushed or not /// public virtual bool AutoFlush { get { return _implementation.Implementation.AutoFlush; } set { _implementation.Implementation.AutoFlush = value; } } /// /// Closes the stream. /// public override void Close() { _implementation.Implementation.Close(); } /// /// The base streawm. /// public virtual Stream BaseStream { get { return _implementation.Implementation.BaseStream; } } /// /// Gets the encoding used. /// public override Encoding Encoding { get { return _implementation.Implementation.Encoding; } } #if LeakCheck private string stack = Environment.StackTrace; /// /// Desctructor. /// ~C1StreamWriter() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); Dispose(false); } #endif /// /// Disposes the stream. /// /// True if the stream is disposing. protected override void Dispose(bool disposing) { if (disposing) { _implementation.DisposeImplementation(); } } } } ================================================ FILE: Composite/Core/IO/C1WaitForChangedResult.cs ================================================ using System.IO; using System.Runtime.InteropServices; namespace Composite.Core.IO { /// /// This class is a almost one to one version of System.IO.WaitForChangedResult. Using this implementation instead /// of System.IO.WaitForChangedResult, will ensure that your code will work both on Standard Windows deployment /// and Windows Azure deployment. /// See System.IO.WaitForChangedResult for more documentation on the methods of this class. /// Used by /// [StructLayout(LayoutKind.Sequential)] public struct C1WaitForChangedResult { /// /// Gets or sets the name of the changed file system item. /// public string Name { get; set; } /// /// Gets or sets the old name of the changed file system item. /// public string OldName { get; set; } /// /// Gets or sets the type of the change. /// public WatcherChangeTypes ChangeType { get; set; } /// /// Gets or sets whether the operation timed out. /// public bool TimedOut { get; set; } } } ================================================ FILE: Composite/Core/IO/DirectoryUtils.cs ================================================ using System; using System.IO; using System.Text; using Composite.Core.Logging; using System.Collections.Generic; namespace Composite.Core.IO { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DirectoryUtils { /// /// Ensures that the directories in the path exists and if they dont they will be created /// public static void EnsurePath(string filePath) { string directory = Path.GetDirectoryName(filePath); EnsureDirectoryExists(directory); } /// /// Ensures that the directory exists /// public static void EnsureDirectoryExists(string directory) { string[] directories = directory.Split(Path.DirectorySeparatorChar); if (directories.Length == 2) return; string currentPath = string.Format("{0}{1}", directories[0], Path.DirectorySeparatorChar); for (int i = 1; i < directories.Length; ++i) { currentPath = string.Format("{0}{1}{2}", currentPath, directories[i], Path.DirectorySeparatorChar); if (currentPath.StartsWith(PathUtil.BaseDirectory, StringComparison.InvariantCultureIgnoreCase)) // don't touch dirs outside our own folder! { if (C1Directory.Exists(currentPath) == false) { C1Directory.CreateDirectory(currentPath); } } } } /// /// Delete a file. If the deleteEmptyDirectoresRecursively is true all empty directories /// from buttom up are also deleted. /// /// /// public static void DeleteFile(string path, bool deleteEmptyDirectoresRecursively) { LoggingService.LogVerbose("DirectoryUtil", string.Format("Deleting file '{0}'", path)); C1File.Delete(path); if (deleteEmptyDirectoresRecursively) { string directory = Path.GetDirectoryName(path); string[] directories = directory.Split(Path.DirectorySeparatorChar); for (int i = directories.Length; i > 1; --i) { StringBuilder stringBuilder = new StringBuilder(); for (int j = 0; j < i; ++j) { stringBuilder.Append(directories[j]); stringBuilder.Append(Path.DirectorySeparatorChar); } string currentPath = stringBuilder.ToString(); if (C1Directory.GetFiles(currentPath).Length == 0) { LoggingService.LogVerbose("DirectoryUtil", string.Format("Deleting directory '{0}'", currentPath)); C1Directory.Delete(currentPath); } else { break; } } } } /// /// Deletes all files recursively leaving all sub directories. /// /// public static void DeleteFilesRecursively(string directoryPath) { foreach (string file in C1Directory.GetFiles(directoryPath)) { C1File.Delete(file); } foreach (string directory in C1Directory.GetDirectories(directoryPath)) { DeleteFilesRecursively(directory); } } /// public static void RemoveReadOnlyRecursively(string directoryPath) { foreach (string file in C1Directory.GetFiles(directoryPath)) { FileUtils.RemoveReadOnly(file); } foreach (string directory in C1Directory.GetDirectories(directoryPath)) { RemoveReadOnlyRecursively(directory); } } /// public static IEnumerable GetFilesRecursively(string path) { foreach (string filePath in Directory.GetFiles(path)) { yield return filePath; } foreach (string subPath in Directory.GetDirectories(path)) { foreach (string filePath in GetFilesRecursively(subPath)) { yield return filePath; } } } } } ================================================ FILE: Composite/Core/IO/FileUtils.cs ================================================ using System.IO; namespace Composite.Core.IO { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class FileUtils { /// public static bool RemoveReadOnly(string filePath) { if (C1File.Exists(filePath) == false) return false; FileAttributes fileAttributes = C1File.GetAttributes(filePath); if ((fileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { fileAttributes ^= FileAttributes.ReadOnly; C1File.SetAttributes(filePath, fileAttributes); } return true; } /// public static void Delete(string filePath) { if (C1File.Exists(filePath)) { RemoveReadOnly(filePath); C1File.Delete(filePath); } } } } ================================================ FILE: Composite/Core/IO/Foundation/PluginFacades/IOProviderPluginFacade.cs ================================================ using System; using System.Configuration; using System.IO; using System.Text; using Composite.C1Console.Events; using Composite.Core.IO.Plugins.IOProvider; using Composite.Core.IO.Plugins.IOProvider.Runtime; using Composite.Plugins.IO.IOProviders.LocalIOProvider; namespace Composite.Core.IO.Foundation.PluginFacades { internal static class IOProviderPluginFacade { private static IOProviderFactory _factory; private static IIOProvider _ioProvider; private static readonly object _lock = new object(); static IOProviderPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static IC1Directory C1Directory { get { IIOProvider ioProvider = GetIOProvider(); return ioProvider.C1Directory; } } public static IC1File C1File { get { IIOProvider ioProvider = GetIOProvider(); return ioProvider.C1File; } } public static IC1FileInfo CreateFileInfo(string path) { IIOProvider ioProvider = GetIOProvider(); return ioProvider.CreateFileInfo(path); } public static IC1DirectoryInfo CreateDirectoryInfo(string path) { IIOProvider ioProvider = GetIOProvider(); return ioProvider.CreateDirectoryInfo(path); } public static IC1FileStream CreateFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { IIOProvider ioProvider = GetIOProvider(); return ioProvider.CreateFileStream(path, mode, access, share, bufferSize, options); } public static IC1FileSystemWatcher CreateFileSystemWatcher(string path, string filter) { IIOProvider ioProvider = GetIOProvider(); return ioProvider.CreateFileSystemWatcher(path, filter); } public static IC1StreamReader CreateStreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { IIOProvider ioProvider = GetIOProvider(); return ioProvider.CreateStreamReader(path, encoding, detectEncodingFromByteOrderMarks, bufferSize); } public static IC1StreamReader CreateStreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { IIOProvider ioProvider = GetIOProvider(); return ioProvider.CreateStreamReader(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize); } public static IC1StreamWriter CreateStreamWriter(string path, bool append, Encoding encoding, int bufferSize) { IIOProvider ioProvider = GetIOProvider(); return ioProvider.CreateStreamWriter(path, append, encoding, bufferSize); } public static IC1StreamWriter CreateStreamWriter(Stream stream, Encoding encoding, int bufferSize) { IIOProvider ioProvider = GetIOProvider(); return ioProvider.CreateStreamWriter(stream, encoding, bufferSize); } public static IC1Configuration CreateConfiguration(string path) { IIOProvider ioProvider = GetIOProvider(); return ioProvider.CreateConfiguration(path); } private static IIOProvider GetIOProvider() { if (_ioProvider == null) { lock (_lock) { if (RuntimeInformation.IsUnittest) { return _ioProvider = new LocalIOProvider(); } if (_ioProvider == null) { try { _factory = new IOProviderFactory(); _ioProvider = _factory.CreateDefault(); } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } } } return _ioProvider; } private static void Flush() { _factory = null; _ioProvider = null; } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", IOProviderSettings.SectionName), ex); } } } ================================================ FILE: Composite/Core/IO/IOFacade.cs ================================================ using System.IO; using System.Text; using Composite.Core.IO.Plugins.IOProvider; using Composite.Plugins.IO.IOProviders.LocalIOProvider; using Composite.Core.IO.Foundation.PluginFacades; namespace Composite.Core.IO { internal static class IOFacade { public static IC1Directory C1Directory { get { return IOProviderPluginFacade.C1Directory; } } public static IC1File C1File { get { return IOProviderPluginFacade.C1File; } } public static IC1FileInfo CreateC1FileInfo(string path) { return IOProviderPluginFacade.CreateFileInfo(path); } public static IC1DirectoryInfo CreateC1DirectoryInfo(string path) { return IOProviderPluginFacade.CreateDirectoryInfo(path); } public static IC1FileStream CreateC1FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { return IOProviderPluginFacade.CreateFileStream(path, mode, access, share, bufferSize, options); } public static IC1FileSystemWatcher CreateC1FileSystemWatcher(string path, string filter) { return IOProviderPluginFacade.CreateFileSystemWatcher(path, filter); } public static IC1StreamReader CreateC1StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { return IOProviderPluginFacade.CreateStreamReader(path, encoding, detectEncodingFromByteOrderMarks, bufferSize); } public static IC1StreamReader CreateC1StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { return IOProviderPluginFacade.CreateStreamReader(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize); } public static IC1StreamWriter CreateC1StreamWriter(string path, bool append, Encoding encoding, int bufferSize) { return IOProviderPluginFacade.CreateStreamWriter(path, append, encoding, bufferSize); } public static IC1StreamWriter CreateC1StreamWriter(Stream stream, Encoding encoding, int bufferSize) { return IOProviderPluginFacade.CreateStreamWriter(stream, encoding, bufferSize); } public static IC1Configuration CreateC1Configuration(string path) { return IOProviderPluginFacade.CreateConfiguration(path); } } } ================================================ FILE: Composite/Core/IO/MimeTypeInfo.cs ================================================ using System.Collections.Concurrent; using System.Collections.Generic; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.Web; using System.Web.Configuration; using System.Web.Hosting; using System.Xml.Linq; using Composite.C1Console.Forms.CoreUiControls; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; namespace Composite.Core.IO { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class MimeTypeInfo { private static readonly string LogTitle = typeof (MimeTypeInfo).Name; private static readonly IDictionary _toCanonical = new Dictionary(); private static readonly IDictionary _extensionToCanonical = new Dictionary(); private static readonly IDictionary _mimeTypeToResourceName = new Dictionary(); private static readonly IDictionary _mimeTypeToExtension = new Dictionary(); private static readonly ConcurrentDictionary _iisServeableExtensions = new ConcurrentDictionary(); private static List _textMimeTypes = new List { MimeTypeInfo.Css, MimeTypeInfo.Js, MimeTypeInfo.Json, MimeTypeInfo.Xml, MimeTypeInfo.Text, MimeTypeInfo.Html, MimeTypeInfo.Sass, MimeTypeInfo.Ascx, MimeTypeInfo.Ashx, MimeTypeInfo.Asmx, MimeTypeInfo.Aspx, MimeTypeInfo.Asax, MimeTypeInfo.CSharp, MimeTypeInfo.Resx, MimeTypeInfo.MasterPage, MimeTypeInfo.CsHtml, MimeTypeInfo.Svg }; // file types we don't expect IIS to block private static readonly HashSet _iisServeableTypes = new HashSet(); private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } /// public static string Default => "application/octet-stream"; /// public static string Jpeg => "image/jpeg"; /// public static string Gif => "image/gif"; /// public static string Bmp => "image/bmp"; /// public static string Png => "image/png"; /// public static string Tiff => "image/tiff"; /// public static string Css => "text/css"; /// public static string Sass => "text/x-sass"; /// public static string Js => "text/js"; /// public static string Json => "application/json"; /// public static string Xml => "text/xml"; /// public static string Text => "text/plain"; /// public static string Html => "text/html"; /// public static string Flash => "application/x-shockwave-flash"; /// public static string QuickTime => "video/quicktime"; /// public static string Pdf = "application/pdf"; /// public static string Wmv => "video/x-ms-wmv"; /// public static string Asf => "video/x-ms-asf"; /// public static string Avi => "video/x-msvideo"; /// public static string Flv => "video/x-flv"; /// public static string Director => "application/x-director"; /// public static string CSharp => "text/x-csharp"; /// public static string CsHtml => "application/x-cshtml"; /// public static string Svg => "image/svg+xml"; /// public static string Ascx => "application/x-ascx"; /// public static string Aspx => "application/x-aspx"; /// public static string Asax => "application/x-asax"; /// public static string Ashx => "application/x-ashx"; /// public static string Asmx => "application/x-asmx"; /// public static string Resx => "application/x-resx"; /// public static string MasterPage => "application/x-master-page"; /// static MimeTypeInfo() { LoadExtensionMappingsFromWebConfig(); // Image formats _toCanonical.Add("image/pjpg", Jpeg); _toCanonical.Add("image/pjpeg", Jpeg); _toCanonical.Add("image/jpg", Jpeg); RegisterMimeType(MimeTypeInfo.Jpeg, new [] {"jpg", "jpe", "jpeg"}, "mimetype-jpeg", true); RegisterMimeType(MimeTypeInfo.Gif, "gif", "mimetype-gif", true); RegisterMimeType(MimeTypeInfo.Bmp, "bmp", "mimetype-bmp", true); _toCanonical.Add("image/x-png", Png); RegisterMimeType(MimeTypeInfo.Png, "png", "mimetype-png", true); RegisterMimeType(MimeTypeInfo.Svg, "svg", "mimetype-svg", true); _toCanonical.Add("image/tif", MimeTypeInfo.Tiff); RegisterMimeType(MimeTypeInfo.Tiff, "tif", "mimetype-tiff", true); // Web RegisterMimeType(MimeTypeInfo.Css, new[] { "css", "less" }, "mimetype-css", true); RegisterMimeType(MimeTypeInfo.Sass, new[] { "scss" }, "mimetype-css", true); RegisterMimeType(MimeTypeInfo.Resx, "resx", "mimetype-resx"); _toCanonical.Add("application/x-javascript", MimeTypeInfo.Js); RegisterMimeType(MimeTypeInfo.Js, "js", "mimetype-js", true); RegisterMimeType(MimeTypeInfo.Json, new[] { "json" }, "mimetype-js"); RegisterMimeType(MimeTypeInfo.Html, new[] { "htm", "html", "xhtml" }, "mimetype-html", true); // Audio/Video RegisterMimeType("audio/x-wav", "wav", null, true); RegisterMimeType("audio/x-pn-realaudio", new[] { "ram", "rm" }, "mimetype-ram", true); RegisterMimeType("audio/mpeg", "mp3", "mimetype-mp3", true); RegisterMimeType("video/mpeg", new[] { "mpeg", "mpg" }, "mimetype-mpeg", true); RegisterMimeType(MimeTypeInfo.Flv, "flv", null, true); RegisterMimeType(MimeTypeInfo.Asf, "asf", "mimetype-asf", true); RegisterMimeType(MimeTypeInfo.Avi, "avi", "mimetype-movie", true); RegisterMimeType(MimeTypeInfo.Wmv, "wmv", "mimetype-wmv", true); // Applications RegisterMimeType("application/postscript", "eps", "mimetype-pps", true); RegisterMimeType("application/msaccess", "mdb", "mimetype-mdb", true); RegisterMimeType(Pdf, "pdf", "mimetype-pdf", true); RegisterMimeType("application/vnd.ms-powerpoint", "ppt", "mimetype-ppt", true); RegisterMimeType("application/vnd.openxmlformats-officedocument.presentationml.presentation", "pptx", "mimetype-ppt", true); RegisterMimeType("application/msword", "doc", "mimetype-doc", true); RegisterMimeType("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx", "mimetype-doc", true); RegisterMimeType("application/rtf", "rtf", "mimetype-rtf", true); RegisterMimeType("application/vnd.visio", "vsd", "mimetype-vsd", true); RegisterMimeType("application/x-font-woff", "woff"); RegisterMimeType("application/vnd.ms-excel", "xls", "mimetype-xls", true); RegisterMimeType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx", "mimetype-xls", true); RegisterMimeType(MimeTypeInfo.QuickTime, "mov", "mimetype-mov", true); RegisterMimeType(MimeTypeInfo.Flash, "swf", "mimetype-swf", true); RegisterMimeType(MimeTypeInfo.Director, new[] { "dcr", "dir" }, "mimetype-dir"); RegisterMimeType("text/xml", new[] { "xml", "config", "xsl", "xslt" }, "mimetype-xml"); const string mimeTypeZip = "application/zip"; _toCanonical.Add("application/x-zip-compressed", mimeTypeZip); RegisterMimeType(mimeTypeZip, "zip", "mimetype-zip", true); _toCanonical.Add("text/txt", "text/plain"); _toCanonical.Add("text/text", "text/plain"); RegisterMimeType("text/plain", "txt", "mimetype-txt", true); // .Cs and asp.net files RegisterMimeType(MimeTypeInfo.Ascx, "ascx", "mimetype-ascx"); RegisterMimeType(MimeTypeInfo.Aspx, "aspx", "mimetype-aspx"); RegisterMimeType(MimeTypeInfo.Asax, "asax", "mimetype-asax"); RegisterMimeType(MimeTypeInfo.Ashx, "ashx"); RegisterMimeType(MimeTypeInfo.Asmx, "asmx"); RegisterMimeType(MimeTypeInfo.MasterPage, "master"); RegisterMimeType(MimeTypeInfo.CSharp, "cs"); RegisterMimeType(MimeTypeInfo.CsHtml, "cshtml", "mimetype-cshtml"); AddExtensionMapping("mp4", "video/mp4"); AddExtensionMapping("ogg", "audio/ogg"); AddExtensionMapping("ogv", "video/ogg"); AddExtensionMapping("webm", "video/webm"); AddExtensionMapping("svg", "image/svg+xml"); AddExtensionMapping("svgz", "image/svg+xml"); AddExtensionMapping("flv4", "video/mp4"); AddExtensionMapping("eot", "application/vnd.ms-fontobject"); } private static void RegisterMimeType(string canonicalMimeTypeName, string extension, string resourceName = null, bool iisServable = false) { RegisterMimeType(canonicalMimeTypeName, new [] { extension }, resourceName, iisServable); } private static void RegisterMimeType(string canonicalMimeTypeName, string[] extensions, string resourceName, bool iisServable = false) { _toCanonical.Add(canonicalMimeTypeName, canonicalMimeTypeName); foreach(string extension in extensions) { AddExtensionMapping(extension, canonicalMimeTypeName); } if(resourceName != null) { _mimeTypeToResourceName.Add(canonicalMimeTypeName, resourceName); } if (iisServable) { _iisServeableTypes.Add(canonicalMimeTypeName); } } private static bool AddExtensionMapping(string extension, string mimeType) { _mimeTypeToExtension[mimeType] = extension; if (!_extensionToCanonical.ContainsKey(extension)) { _extensionToCanonical.Add(extension, mimeType); return true; } return false; } [SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass")] private static void LoadExtensionMappingsFromWebConfig() { ConfigurationSection config; try { config = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath).GetSection("system.webServer"); } catch { // Silent return; } var configRawXml = config?.SectionInformation.GetRawXml(); if (configRawXml == null) { return; } XElement webServerConfig = XElement.Parse(configRawXml); XElement staticContentConfig = webServerConfig.Element("staticContent"); if(staticContentConfig == null) { return; } foreach(XElement mimeMapping in staticContentConfig.Elements("mimeMap")) { string extension = mimeMapping.Attribute("fileExtension").Value.ToLowerInvariant(); string mimeType = mimeMapping.Attribute("mimeType").Value; if(extension.StartsWith(".")) { extension = extension.Substring(1); } if (!AddExtensionMapping(extension, mimeType)) { Log.LogWarning(typeof(MimeTypeInfo).Name, "MimeType for extension '{0}' has already been defined", extension); } else { _iisServeableTypes.Add(mimeType); } } } /// public static string GetCanonical(string mimeType) { if (string.IsNullOrEmpty(mimeType)) { return MimeTypeInfo.Default; } mimeType = mimeType.ToLowerInvariant(); if (_toCanonical.ContainsKey(mimeType)) { return _toCanonical[mimeType]; } return mimeType; } /// public static ResourceHandle GetResourceHandleFromMimeType(string mimeType) { if (mimeType != null && _mimeTypeToResourceName.ContainsKey(mimeType)) { return GetIconHandle(_mimeTypeToResourceName[mimeType]); } return GetIconHandle("mimetype-unknown"); } /// public static string GetExtensionFromMimeType(string mimeType) { return _mimeTypeToExtension.TryGetValue(mimeType, out string extension) ? extension : null; } /// public static string GetCanonicalFromExtension(string extension) { if (extension == null) { return MimeTypeInfo.Default; } extension = extension.ToLowerInvariant(); if (extension.StartsWith(".")) { extension = extension.Substring(1); } string mimeType; if (_extensionToCanonical.TryGetValue(extension, out mimeType)) { return mimeType; } string fileName = "filename." + extension; return MimeMapping.GetMimeMapping(fileName); } /// public static string GetMimeType(UploadedFile uploadedFile) { string fileName = System.IO.Path.GetFileName(uploadedFile.FileName); string mimeTypeFromExtension = GetCanonicalFromExtension(System.IO.Path.GetExtension(fileName)); if (mimeTypeFromExtension != MimeTypeInfo.Default) { Log.LogInformation(LogTitle, $"Uploading file '{fileName}'. MIME type from extension: '{mimeTypeFromExtension}'"); return mimeTypeFromExtension; } string mimeTypeFromBrowser = GetCanonical(uploadedFile.ContentType); // Default MIME type for Chrome is "application/xml" // Default MIME type for IE is "text/plain" // for the rest it is "application/octet-stream" if (mimeTypeFromBrowser != "application/xml" && mimeTypeFromBrowser != "text/plain") { Log.LogInformation(LogTitle, $"Uploading file '{fileName}'. " + $"Browser provided MIME type: '{uploadedFile.ContentType}'. " + $"Canonical MIME type: '{mimeTypeFromBrowser}'"); return mimeTypeFromBrowser; } Log.LogInformation(LogTitle, $"Uploading file '{fileName}'. Applying default MIME type '{Default}'"); return MimeTypeInfo.Default; } /// /// Indicates whether a file of a specific MIME type can be edited with a text editor /// /// /// public static bool IsTextFile(string mimeType) { string canonicalMimeType = GetCanonical(mimeType); return canonicalMimeType.StartsWith("text") || _textMimeTypes.Contains(canonicalMimeType); } /// /// Indicates whether a file of a given mime type can be previewed by browser in an iframe. /// /// /// public static bool IsBrowserPreviewableFile(string mimeType) { return mimeType == Pdf || mimeType == Html || mimeType == Text; } internal static string TryGetLocalizedName(string mimeType) { return StringResourceSystemFacade.GetString("MimeTypes", mimeType, false); } /// /// Indicates whether a file of a specific extension is expected to be allowed by IIS /// /// The extension. /// /// true if the extension is 'IIS serveable'; otherwise, false. /// internal static bool IsIisServeable(string extension) { extension = extension.ToLowerInvariant(); if (extension.StartsWith(".")) { extension = extension.Substring(1); } return _iisServeableExtensions.GetOrAdd(extension, ext => { string mimeType = GetCanonicalFromExtension(extension); return _iisServeableTypes.Contains(mimeType); }); } } } ================================================ FILE: Composite/Core/IO/PathUtil.cs ================================================ using System; using System.ComponentModel; using System.IO; using System.Security.AccessControl; using System.Security.Principal; using System.Text; using System.Web.Hosting; using Composite.Core.Extensions; namespace Composite.Core.IO { /// /// /// [EditorBrowsable(EditorBrowsableState.Never)] public static class PathUtil { private static readonly string _appBasePath; /// static PathUtil() { if (HostingEnvironment.IsHosted) { _appBasePath = HostingEnvironment.ApplicationPhysicalPath; } else { _appBasePath = AppDomain.CurrentDomain.BaseDirectory; } } /// /// Root directory of website /// /// public static string BaseDirectory { get { return _appBasePath; } } /// /// Resolves a (tilde based) partial path to a full file system path. /// /// /// public static string Resolve(string path) { if (String.IsNullOrEmpty(path)) throw new ArgumentNullException("path"); if (path.StartsWith("~")) { if (path == "~") { return BaseDirectory; } string tildeLessPath = path.Remove(0, 1); if (Path.IsPathRooted(tildeLessPath) == false) throw new ArgumentException("Tilde based paths must start with tilde (~) and then a directory separator , like ~/folder/file.txt", "path"); string appRootRelativePath = tildeLessPath.Remove(0, 1); if (Path.IsPathRooted(appRootRelativePath)) throw new ArgumentException("Invalid path", "path"); appRootRelativePath = appRootRelativePath.Replace( '/', '\\' ); return Path.Combine(_appBasePath, appRootRelativePath); } if (Path.IsPathRooted(path) == false) throw new ArgumentException("Relative paths must start with tilde (~), like ~/folder/file.txt", "path"); return path.Replace('/', '\\'); } /// public static string CleanFileName(string s) { return CleanFileName(s, false); } /// public static string CleanFileName(string s, bool allowUnicodeLetters) { var sb = new StringBuilder(); foreach (var c in s) { if ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -_.1234567890".IndexOf(c) > -1 || (allowUnicodeLetters && Char.IsLetter(c))) { sb.Append(c); } } return sb.Length > 0 ? sb.ToString() : null; } /// public static string GetWebsitePath(string path) { string s = path.Remove(0, BaseDirectory.Length); s = s.Replace('\\', '/'); if (s.StartsWith("'/'") == false) { s = "/" + s; } return s; } /// /// Indicates whether current Windows user has the NTFS write permission to a file or a folder /// /// Path to a file or a folder /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] public static bool WritePermissionGranted(string fileOrDirectoryPath) { try { AuthorizationRuleCollection rules; if (C1File.Exists(fileOrDirectoryPath)) { FileSystemSecurity security = File.GetAccessControl(fileOrDirectoryPath); rules = security.GetAccessRules(true, true, typeof(NTAccount)); } else if (C1Directory.Exists(fileOrDirectoryPath)) { DirectorySecurity security = Directory.GetAccessControl(fileOrDirectoryPath); rules = security.GetAccessRules(true, true, typeof(NTAccount)); } else { throw new FileNotFoundException("File or directory '{0}' does not exist".FormatWith(fileOrDirectoryPath)); } var currentuser = new WindowsPrincipal(WindowsIdentity.GetCurrent()); bool result = false; foreach (FileSystemAccessRule rule in rules) { if ((rule.FileSystemRights & (FileSystemRights.WriteData | FileSystemRights.Write)) == 0) { continue; } if (rule.IdentityReference.Value.StartsWith("S-1-")) { var sid = new SecurityIdentifier(rule.IdentityReference.Value); if (!currentuser.IsInRole(sid)) { continue; } } else { if (!currentuser.IsInRole(rule.IdentityReference.Value)) { continue; } } if (rule.AccessControlType == AccessControlType.Deny) return false; if (rule.AccessControlType == AccessControlType.Allow) result = true; } return result; } catch { return false; } } } } ================================================ FILE: Composite/Core/IO/Plugins/IOProvider/IC1Configuration.cs ================================================ using System.Configuration; namespace Composite.Core.IO.Plugins.IOProvider { /// Implementations of this interface is used by C1 through /// to provide the behavior of . /// See for more information. public interface IC1Configuration { /// /// Gets the path to the configuration file. /// string FilePath { get; } /// /// Returns true if the configuration file exists. /// bool HasFile { get; } /// /// Returns the app setttings section. /// AppSettingsSection AppSettings { get; } /// /// Returns the connection string section. /// ConnectionStringsSection ConnectionStrings { get; } /// /// Returns the configuration sections. /// ConfigurationSectionCollection Sections { get; } /// /// Returns the configuration section group. /// ConfigurationSectionGroup RootSectionGroup { get; } /// /// Returns the configuration slection groups. /// ConfigurationSectionGroupCollection SectionGroups { get; } /// /// Gets a named configuration section. /// /// Name of section to get. /// Returns the configuration section. ConfigurationSection GetSection(string sectionName); /// /// Gets a named configuration section group. /// /// Name of configuration section group to get. /// Returns the configuration section group. ConfigurationSectionGroup GetSectionGroup(string sectionGroupName); /// /// Saves the configuration. /// void Save(); /// /// Saves the configuration. /// /// Save mode to use when saving the configuration. void Save(ConfigurationSaveMode saveMode); /// /// Saves the configuration. /// /// Save mode to use when saving the configuration. /// Saves all sections, even non touched. void Save(ConfigurationSaveMode saveMode, bool forceSaveAll); /// /// Saves the configuration to a new file. /// /// Path to new configuration filename. void SaveAs(string filename); /// /// Saves the configuration to a new file. /// /// Path to new configuration filename. /// Save mode to use when saving the configuration. void SaveAs(string filename, ConfigurationSaveMode saveMode); /// /// Saves the configuration to a new file. /// /// Path to new configuration filename. /// Save mode to use when saving the configuration. /// Saves all sections, even non touched. void SaveAs(string filename, ConfigurationSaveMode saveMode, bool forceSaveAll); } } ================================================ FILE: Composite/Core/IO/Plugins/IOProvider/IC1Directory.cs ================================================ using System; using System.IO; namespace Composite.Core.IO.Plugins.IOProvider { /// /// Implementations of this interface is used by C1 through /// to provide the behavior of . /// See for more information. /// public interface IC1Directory { /// /// Creates a directory. /// /// Path to directory to create. /// Returns a C1DirectoryInfo to the specified path. C1DirectoryInfo CreateDirectory(string path); /// /// Deletes an empty directory on the given path. /// /// Path of empty directory to delete. void Delete(string path); /// /// Deletes the directory and if specified subdirectories and file on the given path. /// /// Path of directory to delete. /// Include subdirectories and files. void Delete(string path, bool recursive); /// /// Moves a file or directory from the given source path to the given destination path. /// /// Path of file or directory to move. /// Target path of file or directory to be moved to. void Move(string sourceDirName, string destDirName); /// /// Determines if the directory in the given path exists or not. /// /// Path to directory to test. /// bool Exists(string path); /// /// Returns the current directory. /// /// The current directory. string GetCurrentDirectory(); /// /// Sets the current directory /// /// Path to new current directory. void SetCurrentDirectory(string path); /// /// Gets the parent of the given directory. /// /// Path of directory to get parent of. /// The parent of the given directory. C1DirectoryInfo GetParent(string path); /// /// Returns volume and/or root information of the given directory. /// /// Path of directory to get root information of. /// Volume and/or root information. string GetDirectoryRoot(string path); /// /// Gets the subdirectories of the given directory. /// /// Path to directory to get subdirectories. /// Subdirectories of the given directory. string[] GetDirectories(string path); /// /// Gets the subdirectories of the given directory with the given search pattern. /// /// Path to directory to get subdirectories. /// Search pattern to use. /// Subdirectories of the given directory with the given search parrern. string[] GetDirectories(string path, string searchPattern); /// /// Gets the subdirectories of the given directory with the given search pattern and options. /// /// Path to directory to get subdirectories. /// Search pattern to use. /// Search options to use. /// Subdirectories of the given directory with the given search parrern and options. string[] GetDirectories(string path, string searchPattern, SearchOption searchOption); /// /// Gets the files in the given directory. /// /// Path to directory go get files from. /// Files in the given directory. string[] GetFiles(string path); /// /// Gets the files in the given directory with the given search pattern. /// /// Path to directory go get files from. /// Search pattern to use. /// Files in the given directory with the given search pattern. string[] GetFiles(string path, string searchPattern); /// /// Gets the files in the given directory with the given search pattern and options. /// /// Path to directory go get files from. /// Search pattern to use. /// Search options to use. /// Files in the given directory with the given search pattern and options. string[] GetFiles(string path, string searchPattern, SearchOption searchOption); /// /// Returns the creation date and time of the given directory. /// /// Path of directory. /// Creation date and time of the given directory. DateTime GetCreationTime(string path); /// /// Returns the creation date and utc time of the given directory. /// /// Path of directory. /// Creation date and time of the given directory. DateTime GetCreationTimeUtc(string path); /// /// Sets the creation date and time for the specified file or directory. /// /// The file or directory for which to set the creation date and time information. /// An object that contains the value to set for the creation date and time of path. This value is expressed in local time. void SetCreationTime(string path, DateTime creationTime); /// /// Sets the creation date and time, in Coordinated Universal Time (UTC) format, for the specified file or directory. /// /// The file or directory for which to set the creation date and time information. /// An object that contains the value to set for the creation date and time of path. This value is expressed in UTC time. void SetCreationTimeUtc(string path, DateTime creationTimeUtc); } } ================================================ FILE: Composite/Core/IO/Plugins/IOProvider/IC1DirectoryInfo.cs ================================================ using System; using System.IO; using System.Runtime.Serialization; namespace Composite.Core.IO.Plugins.IOProvider { /// /// Implementations of this interface is used by C1 through /// to provide the behavior of . /// See for more information. /// public interface IC1DirectoryInfo { /// /// The name of the directory. /// string Name { get; } /// /// Full path of the directory. /// string FullName { get; } /// /// The extension of the directory. /// string Extension { get; } /// /// Tells if the directory exists or not. /// bool Exists { get; } /// /// The root directory of the directory. /// C1DirectoryInfo Root { get; } /// /// The parent directory of the directory. /// C1DirectoryInfo Parent { get; } /// /// File attributes of the directory. /// FileAttributes Attributes { get; set; } /// /// Returns the subdirectories of the directory. /// /// Subdirectories of the directory. C1DirectoryInfo[] GetDirectories(); /// /// Returns the subdirectores of the directory given the search pattern. /// /// Search pattern to use. /// Subdirectories of the directory. C1DirectoryInfo[] GetDirectories(string searchPattern); /// /// Returns the subdirectores of the directory given the search pattern and options. /// /// The search pattern to use. /// The search options to use. /// Subdirectories of the directory. C1DirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption); /// /// Returns the files in the directory. /// /// Files in the directory. C1FileInfo[] GetFiles(); /// /// Returns the files in the directory given the search pattern. /// /// The search pattern to use. /// Files in the directory given the search pattern. C1FileInfo[] GetFiles(string searchPattern); /// /// Returns the files in the directory given the search pattern and options. /// /// The search pattern to use. /// The search options to use. /// Files in the directory given the search pattern and options. C1FileInfo[] GetFiles(string searchPattern, SearchOption searchOption); /// /// Creates the directory. /// void Create(); /// /// Creates a subdirectory. /// /// Path to directory to create. /// C1DirectoryInfo CreateSubdirectory(string path); /// /// Moves the directory to the given path. /// /// Destination directory name. void MoveTo(string destDirName); /// /// Deletes the directory if empty. /// void Delete(); /// /// Deletes the directory, files and subdirectories if specified. /// /// If true, a recursive delete will be performced. void Delete(bool recursive); /// /// The creation time of the directory. /// DateTime CreationTime { get; set; } /// /// The creation utc time of the directory. /// DateTime CreationTimeUtc { get; set; } /// /// Last access time of the directory. /// DateTime LastAccessTime { get; set; } /// /// Last access utc time of the directory. /// DateTime LastAccessTimeUtc { get; set; } /// /// Last write time of the directory. /// DateTime LastWriteTime { get; set; } /// /// Last write utc time of the directory. /// DateTime LastWriteTimeUtc { get; set; } /// /// void GetObjectData(SerializationInfo info, StreamingContext context); /// /// void Refresh(); } } ================================================ FILE: Composite/Core/IO/Plugins/IOProvider/IC1File.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Composite.Core.IO.Plugins.IOProvider { /// /// Implementations of this interface is used by C1 through /// to provide the behavior of . /// See for more information. /// public interface IC1File { /// /// Determins if the given file exists or not. /// /// Path to the file. /// Returns true if the file exists, false if not. bool Exists(string path); /// /// This is not a port of the System.IO.File. This method can be used to 'touch' an /// existing file. This is a way of telling the C1 IO system that the file has been /// touched and C1 uses this to handle other than standard Windows deployments, like /// Windows Azure. /// /// Path to file to touch. void Touch(string path); /// /// Copies a file. /// /// Source path of file to copy. /// Target path of the file to be copied to. void Copy(string sourceFileName, string destFileName); /// /// Copies a file. /// /// Source path of file to copy. /// Target path of the file to be copied to. /// If this is true and the target path exists, it will be overwritten without any exceptions. void Copy(string sourceFileName, string destFileName, bool overwrite); /// /// Moves a file. /// /// Path of file to move. /// Destination path to move the file to. void Move(string sourceFileName, string destFileName); /// /// Replace a file with another file. /// /// Path to source file. /// Path to file to replace. /// void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName); /// /// Replace a file with another file. /// /// Path to source file. /// Path to file to replace. /// /// void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); /// /// Deletes the given file. /// /// Path to file to delete. void Delete(string path); /// /// Creates a new file and returns a file stream to it . /// /// Path to file to create. /// Returns the newly created stream. C1FileStream Create(string path); /// /// Creates a new file and returns a file stream to it . /// /// Path to file to create. /// Buffer size of returned stream. /// Returns the newly created stream. C1FileStream Create(string path, int bufferSize); /// /// Creates a new file and returns a file stream to it . /// /// Path to file to create. /// Buffer size of returned stream. /// File options of returned stream. /// Returns the newly created stream. C1FileStream Create(string path, int bufferSize, FileOptions options); /// /// Creates a new file and returns a stream writer to it . /// /// Path to file to create. /// Returns the newly created . C1StreamWriter CreateText(string path); /// /// Opens a for appending. /// /// Path to file to append to. /// Returns the newly opned . C1StreamWriter AppendText(string path); /// /// Appends content to a file. /// /// Path to file to append to. /// Content to append to file. void AppendAllText(string path, string contents); /// /// Appends content to a file. /// /// Path to file to append to. /// Content to append to file. /// Encoding to use when appending. void AppendAllText(string path, string contents, Encoding encoding); /// /// Appends content to a file. /// /// Path to file to append to. /// Content to append to file. void AppendAllLines(string path, IEnumerable contents); /// /// Appends content to a file. /// /// Path to file to append to. /// Content to append to file. /// Encoding to use when appending. void AppendAllLines(string path, IEnumerable contents, Encoding encoding); /// /// Opens a file. /// /// Path to file to open. /// File mode to use. /// Returns the newly opened . C1FileStream Open(string path, FileMode mode); /// /// Opens a file. /// /// Path to file to open. /// File mode to use. /// File access to use. /// Returns the newly opened . C1FileStream Open(string path, FileMode mode, FileAccess access); /// /// Opens a file. /// /// Path to file to open. /// File mode to use. /// File access to use. /// File share to use. /// Returns the newly opened . C1FileStream Open(string path, FileMode mode, FileAccess access, FileShare share); /// /// Opens a file for reading. /// /// Path to file to open. /// Returns the newly opened . C1FileStream OpenRead(string path); /// /// Opens a file. /// /// Path to file to open. /// Returns the newly opened . C1StreamReader OpenText(string path); /// /// Opens a file for writing. /// /// Path to file to open. /// Returns the newly opened . C1FileStream OpenWrite(string path); /// /// Read all bytes from a file. /// /// Path to file to read from. /// Returns read bytes. byte[] ReadAllBytes(string path); /// /// Read all lines from a file. /// /// Path to file to read from. /// Returns read lines. string[] ReadAllLines(string path); /// /// Read all lines from a file. /// /// Path to file to read from. /// Encoding to use when reading. /// Returns read lines. string[] ReadAllLines(string path, Encoding encoding); /// /// Read all text from a file. /// /// Path to file to read from. /// The content of the file. string ReadAllText(string path); /// /// Read all text from a file. /// /// Path to file to read from. /// Encoding to use when reading. /// The content of the file. string ReadAllText(string path, Encoding encoding); /// /// Read all lines from a file. /// /// Path to file to read from. /// Returns all read lines. IEnumerable ReadLines(string path); /// /// Read all lines from a file. /// /// Path to file to read from. /// Encoding to use when reading. /// Returns all read lines. IEnumerable ReadLines(string path, Encoding encoding); /// /// Writes bytes to a file. /// /// Path to file to write to. /// Bytes to write. void WriteAllBytes(string path, byte[] bytes); /// /// Writes lines to a file. /// /// Path to file to write to. /// Lines to write. void WriteAllLines(string path, IEnumerable contents); /// /// Writes lines to a file. /// /// Path to file to write to. /// Lines to write. /// Encoding to use when writing. void WriteAllLines(string path, IEnumerable contents, Encoding encoding); /// /// Writes lines to a file. /// /// Path to file to write to. /// Lines to write. void WriteAllLines(string path, string[] contents); /// /// Writes lines to a file. /// /// Path to file to write to. /// Lines to write. /// Encoding to use when writing. void WriteAllLines(string path, string[] contents, Encoding encoding); /// /// Writes text to a file. /// /// Path to file to write to. /// Text to write. void WriteAllText(string path, string contents); /// /// Writes text to a file. /// /// Path to file to write to. /// Text to write. /// Encoding to use when writing. void WriteAllText(string path, string contents, Encoding encoding); /// /// Gets the file attributes. /// /// Path to file to get attributes from. /// Returns the file attributes. See System.IO.FileAttributes FileAttributes GetAttributes(string path); /// /// Sets the file attributes. /// /// Path to file to set attributes on. /// File attributes to set. void SetAttributes(string path, FileAttributes fileAttributes); /// /// Gets the creation time of the file. /// /// Path to file. /// Returns the creation time of the given file. DateTime GetCreationTime(string path); /// /// Gets the creation utc time of the file. /// /// Path to file. /// Returns the creation utc time of the given file. DateTime GetCreationTimeUtc(string path); /// /// Sets the creation time of the file. /// /// Path to file. /// New creation time. void SetCreationTime(string path, DateTime creationTime); /// /// Sets the creation utc time of the file. /// /// Path to file. /// New creation utc time. void SetCreationTimeUtc(string path, DateTime creationTimeUtc); /// /// Gets the last access time. /// /// Path to file. /// Returns the last access time of the file. DateTime GetLastAccessTime(string path); /// /// Gets the last access utc time. /// /// Path to file. /// Returns the last access utc time of the file. DateTime GetLastAccessTimeUtc(string path); /// /// Sets the last access time of the file. /// /// Path to file. /// New last access time. void SetLastAccessTime(string path, DateTime lastAccessTime); /// /// Sets the last access utc time of the file. /// /// Path to file. /// New last access utc time. void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc); /// /// Get last write time of the file. /// /// Path to file. /// Returns the last write time of the file. DateTime GetLastWriteTime(string path); /// /// Get last write utc time of the file. /// /// Path to file. /// Returns the last write utc time of the file. DateTime GetLastWriteTimeUtc(string path); /// /// Sets the last write time of the file. /// /// Path to file. /// New last write time. void SetLastWriteTime(string path, DateTime lastWriteTime); /// /// Sets the last write utc time of the file. /// /// Path to file. /// New last write utc time. void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc); } } ================================================ FILE: Composite/Core/IO/Plugins/IOProvider/IC1FileInfo.cs ================================================ using System; using System.IO; using System.Runtime.Serialization; namespace Composite.Core.IO.Plugins.IOProvider { /// /// Implementations of this interface is used by C1 through /// to provide the behavior of . /// See for more information. /// public interface IC1FileInfo { /// /// Returns the directory name of the file. /// string DirectoryName { get; } /// /// Returns a of the file. /// C1DirectoryInfo Directory { get; } /// /// Returns the name of the file. /// string Name { get; } /// /// Returns the full path and name of the file. /// string FullName { get; } /// /// Returns true if the file exists. Otherwise false. /// bool Exists { get; } /// /// Returns the extension of the file. /// string Extension { get; } /// /// Returns true if and only if the file is read only. /// bool IsReadOnly { get; set; } /// /// Returns the size of the file in bytes. /// long Length { get; } /// /// Gets or sets the file attributes on the file. /// FileAttributes Attributes { get; set; } /// /// Creates a file stream . /// /// Returns a newly created . C1FileStream Create(); /// /// Creates a file stream . /// /// Returns a newly created . C1StreamWriter CreateText(); /// /// Creates a file stream for appending. /// /// Returns a newly created for appending. C1StreamWriter AppendText(); /// /// Creates a file stream . /// /// File mode to use. /// Returns a newly created . C1FileStream Open(FileMode mode); /// /// Creates a file stream . /// /// File mode to use. /// File access to use. /// Returns a newly created . C1FileStream Open(FileMode mode, FileAccess access); /// /// Creates a file stream . /// /// File mode to use. /// File access to use. /// File share to use. /// Returns a newly created . C1FileStream Open(FileMode mode, FileAccess access, FileShare share); /// /// Creates a file stream . /// /// Returns a newly created for reading. C1FileStream OpenRead(); /// /// Creates a file stream . /// /// Returns a newly created . C1StreamReader OpenText(); /// /// Creates a file stream . /// /// Returns a newly created for writing. C1FileStream OpenWrite(); /// /// Copies the file to the given path. /// /// Destination path. /// A new for the destination file. C1FileInfo CopyTo(string destFileName); /// /// Copies the file to the given path and overwrites any existing file if specified. /// /// Destination path. /// If true, any existing file will be overwritten. /// A new for the destination file. C1FileInfo CopyTo(string destFileName, bool overwrite); /// /// Moves the file to the given path. /// /// Destination path. void MoveTo(string destFileName); /// /// Replaces the given file with this one. /// /// Destination path to file to replace. /// Path to backup file. /// A new for the destination file. C1FileInfo Replace(string destinationFileName, string destinationBackupFileName); /// /// Replaces the given file with this one. /// /// Destination path to file to replace. /// Path to backup file. /// /// A new for the destination file. C1FileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); /// /// Deletes the file. /// void Delete(); /// /// Gets or sets the creation time of the file. /// DateTime CreationTime { get; set; } /// /// Gets or sets the creation utc time of the file. /// DateTime CreationTimeUtc { get; set; } /// /// Gets or sets the last access time of the file. /// DateTime LastAccessTime { get; set; } /// /// Gets or sets the last access utc time of the file. /// DateTime LastAccessTimeUtc { get; set; } /// /// Gets or sets the last write time of the file. /// DateTime LastWriteTime { get; set; } /// /// Gets or sets the last write utc time of the file. /// DateTime LastWriteTimeUtc { get; set; } /// /// void Refresh(); /// /// /// /// void GetObjectData(SerializationInfo info, StreamingContext context); } } ================================================ FILE: Composite/Core/IO/Plugins/IOProvider/IC1FileStream.cs ================================================ using System; using System.IO; namespace Composite.Core.IO.Plugins.IOProvider { /// /// Implementations of this interface is used by C1 through /// to provide the behavior of . /// See for more information. /// public interface IC1FileStream : IDisposable { /// /// Name of the file. /// string Name { get; } /// /// Size of the file in bytes. /// long Length { get; } /// /// Sets the length of the file in bytes. /// /// New length of file stream. void SetLength(long value); /// /// Gets or sets the current read/write position in the file stream. /// long Position { get; set; } /// /// Reads a block of bytes from the file stream. /// /// Target buffer of read bytes. /// Offset in the buffer to put read bytes. /// Number of bytes to read. /// Number of bytes read. int Read(byte[] array, int offset, int count); /// /// Reads a byte form the file stream. /// /// The read byte value. int ReadByte(); /// /// Writes a block of bytes to the file stream. /// /// Bytes to write to the file. /// Offset in buffer to write from. /// Number of bytes to write. void Write(byte[] array, int offset, int count); /// /// Writes a byte to the file stream. /// /// Byte value to write. void WriteByte(byte value); /// /// Seeks to a position in the file stream. /// /// Offset to seek. /// Origin to seek from. /// The new position in the stream. long Seek(long offset, SeekOrigin origin); /// /// Returns true if its possible to read from the stream. /// bool CanRead { get; } /// /// Returns true if its possible to seek in the stream. /// bool CanSeek { get; } /// /// Returns true if its possible to write to the stream. /// bool CanWrite { get; } /// /// Flushes the buffered bytes to the file. /// void Flush(); /// /// Flushes the buffered bytes to the file. /// /// void Flush(bool flushToDisk); /// /// Closes the file stream. /// void Close(); } } ================================================ FILE: Composite/Core/IO/Plugins/IOProvider/IC1FileSystemWatcher.cs ================================================ using System.IO; namespace Composite.Core.IO.Plugins.IOProvider { /// /// Implementations of this interface is used by C1 through /// to provide the behavior of . /// See for more information. /// public interface IC1FileSystemWatcher { /// /// Gets or sets if events should be raised or not. /// bool EnableRaisingEvents { get; set; } /// /// Path to watch. /// string Path { get; set; } /// /// Filter to use. /// string Filter { get; set; } /// /// Gets or sets of subdirectories should also be watched. /// bool IncludeSubdirectories { get; set; } /// /// Gets or sets the size of an internal buffer. /// int InternalBufferSize { get; set; } /// /// Adds or removes an event handler when new items are created. /// event FileSystemEventHandler Created; /// /// Adds or removes an event handler when new items changed. /// event FileSystemEventHandler Changed; /// /// Adds or removes an event handler when new items are renamed. /// event RenamedEventHandler Renamed; /// /// Adds or removes an event handler when new items are deleted. /// event FileSystemEventHandler Deleted; /// /// Adds or removes an event handler when an error occure. /// event ErrorEventHandler Error; /// /// Gets or sets the notify filter. /// NotifyFilters NotifyFilter { get; set; } /// /// Begins the initialization. /// void BeginInit(); /// /// Ends the initialization. /// void EndInit(); /// /// /// /// C1WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType); /// /// /// /// /// C1WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout); } } ================================================ FILE: Composite/Core/IO/Plugins/IOProvider/IC1StreamReader.cs ================================================ using System; using System.IO; using System.Text; namespace Composite.Core.IO.Plugins.IOProvider { /// /// Implementations of this interface is used by C1 through /// to provide the behavior of . /// See for more information. /// public interface IC1StreamReader : IDisposable { /// /// Reads a byte from the stream. /// /// Returns the read byte. int Read(); /// /// Reads a block from the file. /// /// Buffer to read into. /// Index in buffer to start storing bytes. /// Number of bytes to read. /// Returns the number read bytes. int Read(char[] buffer, int index, int count); /// /// Read a line from the file. /// /// Returns the read line. string ReadLine(); /// /// Read all the content of the file into a strng. /// /// The content of the file. string ReadToEnd(); /// /// Reads a block from the file. /// /// Buffer to store read chars. /// Index in buffer to start storing chars. /// Number of chars to read. /// Returns the number of read chars. int ReadBlock(char[] buffer, int index, int count); /// /// Peeks the current byte. /// /// The current byte. int Peek(); /// /// Returns true if the stream is at the end of stream. /// bool EndOfStream { get; } /// /// Closes the stream. /// void Close(); /// /// Returns the base stream. /// Stream BaseStream { get; } /// /// Returns the current encoding of the stream. /// Encoding CurrentEncoding { get; } } } ================================================ FILE: Composite/Core/IO/Plugins/IOProvider/IC1StreamWriter.cs ================================================ using System; using System.IO; using System.Text; namespace Composite.Core.IO.Plugins.IOProvider { /// /// Implementations of this interface is used by C1 through /// to provide the behavior of . /// See for more information. /// public interface IC1StreamWriter : IDisposable { /// /// Writes a string to the stream. /// /// String to write. void Write(string value); /// /// Writes a formatted string to the stream. /// /// String with formatting to write. /// String format arguments. void Write(string format, params object[] arg); /// /// Writes a formatted string to the stream. /// /// String with formatting to write. /// String format argument. void Write(string format, object arg0); /// /// Writes a formatted string to the stream. /// /// String with formatting to write. /// String format argument. /// String format argument. void Write(string format, object arg0, object arg1); /// /// Writes a formatted string to the stream. /// /// String with formatting to write. /// String format argument. /// String format argument. /// String format argument. void Write(string format, object arg0, object arg1, object arg2); /// /// Writes a char to the stream. /// /// The char value to write. void Write(char value); /// /// Writes a char array to the stream. /// /// Char array to write. void Write(char[] buffer); /// /// Writes a char array to the stream. /// /// Char array to write. /// Start index in the buffer to start writing from. /// Number of chars to write. void Write(char[] buffer, int index, int count); /// /// Writes a boolean to the stream. /// /// Boolean value to write. void Write(bool value); /// /// Writes an integer to the stream. /// /// Integer value to write. void Write(int value); /// /// Writes an unsigned integer to the stream. /// /// Unsigned integer value to write void Write(uint value); /// /// Writes a long to the stream. /// /// Long value to write. void Write(long value); /// /// Writes an unsigned long to the stream. /// /// Unsigned long value to write. void Write(ulong value); /// /// Writes a float to the stream. /// /// Float value to write. void Write(float value); /// /// Writes a double to the stream. /// /// Double value to write. void Write(double value); /// /// Writes a decimal to the stream. /// /// Decimal value to write. void Write(decimal value); /// /// Write an object to the stream. /// /// Object value to write. void Write(object value); /// /// Writes a line break to the stream. /// void WriteLine(); /// /// Writes a string with a line break to the stream. /// /// String value to write. void WriteLine(string value); /// /// Writes a string with a line break to the stream. /// /// String with formatting to write. /// String format argument. void WriteLine(string format, object arg0); /// /// Writes a string with a line break to the stream. /// /// String with formatting to write. /// String format argument. /// String format argument. void WriteLine(string format, object arg0, object arg1); /// /// Writes a string with a line break to the stream. /// /// String with formatting to write. /// String format argument. /// String format argument. /// String format argument. void WriteLine(string format, object arg0, object arg1, object arg2); /// /// Writes a string with a line break to the stream. /// /// String with formatting to write. /// String format arguments. void WriteLine(string format, params object[] arg); /// /// Writes a char with a line break to the stream. /// /// Char value to write. void WriteLine(char value); /// /// Writes a char array with a line break to the stream. /// /// Char array to write. void WriteLine(char[] buffer); /// /// Writes a char array with a line break to the stream. /// /// Char array to write. /// Index in the char array to start writing from. /// Number of chars to write. void WriteLine(char[] buffer, int index, int count); /// /// Writes a bool with a line break to the stream. /// /// Bool value to write. void WriteLine(bool value); /// /// Writes an integer with a line break to the stream. /// /// Integer value to write. void WriteLine(int value); /// /// Writes an unsigned integer with a line break to the stream. /// /// Unsigned integer to write. void WriteLine(uint value); /// /// Writes a long with a line break to the stream. /// /// Long value to write. void WriteLine(long value); /// /// Writes an unsigned long with a line break to the stream. /// /// Unsigned long value to write. void WriteLine(ulong value); /// /// Writes a float with a line break to the stream. /// /// Float value to write. void WriteLine(float value); /// /// Writes a double with a line break to the stream. /// /// Double value to write. void WriteLine(double value); /// /// Writes a decimal with a line break to the stream. /// /// Decimal value to write. void WriteLine(decimal value); /// /// Writes an object with a line break to the stream. /// /// Object value to write. void WriteLine(object value); /// /// Gets or sets the line break value. /// string NewLine { get; set; } /// /// Gets the format provider used. /// IFormatProvider FormatProvider { get; } /// /// Gets or sets whether the stream is auto flushed or not /// bool AutoFlush { get; set; } /// /// Flushes the stream. /// void Flush(); /// /// Closes the stream. /// void Close(); /// /// The base streawm. /// Stream BaseStream { get; } /// /// Gets the encoding used. /// Encoding Encoding { get; } } } ================================================ FILE: Composite/Core/IO/Plugins/IOProvider/IIOProvider.cs ================================================ using System.IO; using System.Text; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Composite.Core.IO.Plugins.IOProvider.Runtime; namespace Composite.Core.IO.Plugins.IOProvider { /// /// Implement this interface to overwrite the default behavior of IO in C1. /// This provides implementations of the following classes: /// /// /// /// /// /// /// /// /// /// /// Here is an minimal implementaion example: /// /// [ConfigurationElementType(typeof(NonConfigurableIOProvider))] /// internal class LocalIOProvider : IIOProvider /// { /// /* Implementation goes here */ /// } /// /// /// [CustomFactory(typeof(IOProviderCustomFactory))] [ConfigurationNameMapper(typeof(IOProviderDefaultNameRetriever))] public interface IIOProvider { /// /// Returns a custom implementation of . /// IC1Directory C1Directory { get; } /// /// Returns a custom implementation of . /// IC1File C1File { get; } /// /// Returns a custom implementation of . /// /// Path to file to use. /// Returns a custom implementation of . IC1FileInfo CreateFileInfo(string fileName); /// /// Returns a custom implementation of . /// /// Path to directory to use. /// Returns a custom implementation of . IC1DirectoryInfo CreateDirectoryInfo(string path); /// /// Returns a custom implementation of . /// /// Path to file. /// File mode to use. /// File access to use. /// File share to use. /// Buffer size to use. /// File options to use. /// Returns a custom implementation of . IC1FileStream CreateFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options); /// /// Returns a custom implementation of . /// /// Path to file or directory to watch. /// Filter to use. /// Returns a custom implementation of . IC1FileSystemWatcher CreateFileSystemWatcher(string path, string filter); /// /// Returns a custom implementation of . /// /// Path to file to read from. /// Encoding to use when reading. /// If true, encoding will be detected from the file stream. /// Buffer size to use when reading. /// Returns a custom implementation of . IC1StreamReader CreateStreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize); /// /// Returns a custom implementation of . /// /// Stream to read from. /// Encoding to use when reading. /// If true, encoding will be detected from the file stream. /// Buffer size to use when reading. /// Returns a custom implementation of . IC1StreamReader CreateStreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize); /// /// Returns a custom implementation of . /// /// Path of file to write to. /// If true, writte data will be appended to the end of the file. /// Encoding to use when writing. /// Buffer size to use when writing. /// Returns a custom implementation of . IC1StreamWriter CreateStreamWriter(string path, bool append, Encoding encoding, int bufferSize); /// /// Returns a custom implementation of . /// /// Stream to write to. /// Encoding to use when writing. /// Buffer size to use when writing. /// Returns a custom implementation of . IC1StreamWriter CreateStreamWriter(Stream stream, Encoding encoding, int bufferSize); /// /// Returns a custom implementation of . /// /// Path of configuration file. /// Returns a custom implementation of . IC1Configuration CreateConfiguration(string path); } } ================================================ FILE: Composite/Core/IO/Plugins/IOProvider/IOProviderData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.IO.Plugins.IOProvider { /// /// Use this to make custom configuration of an implementation. /// [ConfigurationElementType(typeof(NonConfigurableIOProvider))] public class IOProviderData: NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/Core/IO/Plugins/IOProvider/NonConfigurableIOProvider.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Core.IO.Plugins.IOProvider { /// /// This is a default non configurable version of /// [Assembler(typeof(NonConfigurableIOProviderAssembler))] public class NonConfigurableIOProvider : IOProviderData { } /// /// This is a default non configurable assembler version of /// public sealed class NonConfigurableIOProviderAssembler : IAssembler { /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IIOProvider Assemble(IBuilderContext context, IOProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IIOProvider)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/Core/IO/Plugins/IOProvider/Runtime/IOProviderCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.IO.Plugins.IOProvider.Runtime { internal sealed class IOProviderCustomFactory : AssemblerBasedCustomFactory { protected override IOProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { IOProviderSettings settings = configurationSource.GetSection(IOProviderSettings.SectionName) as IOProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", IOProviderSettings.SectionName)); } return settings.IOProviderPlugins.Get(name); } } } ================================================ FILE: Composite/Core/IO/Plugins/IOProvider/Runtime/IOProviderDefaultNameRetriever.cs ================================================ using System; using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.IO.Plugins.IOProvider.Runtime { internal sealed class IOProviderDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { if (null == configSource) throw new ArgumentNullException("configSource"); if (null != name) { return name; } else { IOProviderSettings settings = configSource.GetSection(IOProviderSettings.SectionName) as IOProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("Could not load configuration section {0}", IOProviderSettings.SectionName)); } return settings.DefaultIOProvider; } } } } ================================================ FILE: Composite/Core/IO/Plugins/IOProvider/Runtime/IOProviderFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.IO.Plugins.IOProvider.Runtime { internal sealed class IOProviderFactory: NameTypeFactoryBase { public IOProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/Core/IO/Plugins/IOProvider/Runtime/IOProviderSettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.IO.Plugins.IOProvider.Runtime { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class IOProviderSettings : SerializableConfigurationSection { /// public const string SectionName = "Composite.Core.IO.Plugins.IOProviderConfiguration"; private const string _defaultIOProviderProviderProperty = "defaultIOProvider"; /// /// [ConfigurationProperty(_defaultIOProviderProviderProperty, IsRequired = true)] public string DefaultIOProvider { get { return (string)base[_defaultIOProviderProviderProperty]; } set { base[_defaultIOProviderProviderProperty] = value; } } private const string _ioProviderPluginsProperty = "IOProviderPlugins"; /// /// [ConfigurationProperty(_ioProviderPluginsProperty)] public NameTypeManagerTypeConfigurationElementCollection IOProviderPlugins { get { return (NameTypeManagerTypeConfigurationElementCollection)base[_ioProviderPluginsProperty]; } } } } ================================================ FILE: Composite/Core/IO/ReparsePointUtils.cs ================================================ using System; using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; using System.Text; using Microsoft.Win32.SafeHandles; namespace Composite.Core.IO { internal static class ReparsePointUtils { public static bool DirectoryIsReparsePoint(string directoryPath) { return (new C1DirectoryInfo(directoryPath).Attributes & FileAttributes.ReparsePoint) > 0; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseDirectoryInfoClass:DotNotUseDirectoryInfoClass")] public static string GetDirectoryReparsePointTarget(string directoryPath) { var dirInfo = new DirectoryInfo(directoryPath); return GetSymbolicLinkTarget(dirInfo); } private const int CREATION_DISPOSITION_OPEN_EXISTING = 3; private const int FILE_FLAG_BACKUP_SEMANTICS = 0x02000000; // http://msdn.microsoft.com/en-us/library/aa364962%28VS.85%29.aspx [DllImport("kernel32.dll", EntryPoint = "GetFinalPathNameByHandleW", CharSet = CharSet.Unicode, SetLastError = true)] private static extern int GetFinalPathNameByHandle(IntPtr handle, [In, Out] StringBuilder path, int bufLen, int flags); // http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx [DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)] private static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, IntPtr SecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile); [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseDirectoryInfoClass:DotNotUseDirectoryInfoClass")] private static string GetSymbolicLinkTarget(DirectoryInfo symlink) { SafeFileHandle directoryHandle = CreateFile(symlink.FullName, 0, 2, System.IntPtr.Zero, CREATION_DISPOSITION_OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, System.IntPtr.Zero); if (directoryHandle.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error()); var path = new StringBuilder(512); int size = GetFinalPathNameByHandle(directoryHandle.DangerousGetHandle(), path, path.Capacity, 0); if (size < 0) throw new Win32Exception(Marshal.GetLastWin32Error()); // The remarks section of GetFinalPathNameByHandle mentions the return being prefixed with "\\?\" // More information about "\\?\" here -> http://msdn.microsoft.com/en-us/library/aa365247(v=VS.85).aspx if (path[0] == '\\' && path[1] == '\\' && path[2] == '?' && path[3] == '\\') { return path.ToString().Substring(4); } return path.ToString(); } } } ================================================ FILE: Composite/Core/IO/StreamUtils.cs ================================================ using System.IO; namespace Composite.Core.IO { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class StreamUtils { /// public static void CopyStream(Stream input, Stream output) { byte[] buffer = new byte[8192]; while (true) { int read = input.Read(buffer, 0, buffer.Length); if (read <= 0) return; output.Write(buffer, 0, read); } } } } ================================================ FILE: Composite/Core/IO/Zip/IZipFileSystem.cs ================================================ using System.Collections.Generic; using System.IO; namespace Composite.Core.IO.Zip { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IZipFileSystem { /// bool ContainsFile(string filePath); /// bool ContainsDirectory(string directoryName); /// IEnumerable GetFilenames(); /// IEnumerable GetFilenames(string directoryName); /// IEnumerable GetDirectoryNames(); /// Stream GetFileStream(string filename); /// void WriteFileToDisk(string filename, string targetFilename); } } ================================================ FILE: Composite/Core/IO/Zip/ZipFileSystem.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; namespace Composite.Core.IO.Zip { internal sealed class ZipFileSystem : IZipFileSystem { private const int CopyBufferSize = 4096; private readonly HashSet _entryNames = new HashSet(); private readonly Dictionary _denormalizedEntryNames = new Dictionary(); private string ZipFilename { get; } private static string NormalizePathDelimiters(string path) => path.Replace('\\', '/'); public ZipFileSystem(string zipFilename) { Verify.ArgumentNotNullOrEmpty(zipFilename, "zipFilename"); ZipFilename = zipFilename; Initialize(); } public bool ContainsFile(string filename) { filename = NormalizePathDelimiters(filename); return GetFilenames().Any(f => f.Equals(filename, StringComparison.OrdinalIgnoreCase)); } public bool ContainsDirectory(string directoryName) { directoryName = NormalizePathDelimiters(directoryName); return GetDirectoryNames().Any(f => f.Equals(directoryName, StringComparison.OrdinalIgnoreCase)); } public IEnumerable GetFilenames() { foreach (var filename in _entryNames.Where(s => !s.EndsWith("/"))) { yield return $"~/{filename}"; } } public IEnumerable GetFilenames(string directoryName) { directoryName = NormalizePathDelimiters(directoryName); foreach (var filename in GetFilenames()) { if (filename.StartsWith(directoryName)) { yield return filename; } } } public IEnumerable GetDirectoryNames() { foreach (string directoryName in _entryNames.Where(e => e.EndsWith("/"))) { yield return $"~/{directoryName}"; } } /// /// /// /// /// Format: /// ~\Filename.txt /// ~\Directory1\Directory2\Filename.txt /// ~/Filename.txt /// ~/Directory1/Directory2/Filename.txt /// /// public Stream GetFileStream(string filename) { var parstedFilename = ParseFilename(filename); if (!_entryNames.Contains(parstedFilename)) { string note = ""; var entryWithAnotherCasing = _entryNames .FirstOrDefault(en => en.Equals(parstedFilename, StringComparison.InvariantCultureIgnoreCase)); if (entryWithAnotherCasing != null) { note = $" There's another entry with different casing '{entryWithAnotherCasing}'."; } throw new ArgumentException($"The file '{filename}' does not exist in the zip." + note); } var zipArchive = new ZipArchive(C1File.Open(ZipFilename, FileMode.Open, FileAccess.Read)); var normalizedEntryPath = NormalizePathDelimiters(filename.Substring(2)); if(!_denormalizedEntryNames.TryGetValue(normalizedEntryPath, out string entryPath)) { throw new InvalidOperationException($"Entry '{normalizedEntryPath}' not found"); } var entry = zipArchive.GetEntry(entryPath); if (entry == null) { zipArchive.Dispose(); throw new InvalidOperationException($"Failed to extract entry '{entryPath}' from zip archive"); } return new StreamWrapper(entry.Open(), () => zipArchive.Dispose()); } /// /// /// /// /// Format: /// ~\Filename.txt /// ~\Directory1\Directory2\Filename.txt /// ~/Filename.txt /// ~/Directory1/Directory2/Filename.txt /// /// /// /// public void WriteFileToDisk(string filename, string targetFilename) { using (var stream = GetFileStream(filename)) { using (var fileStream = new C1FileStream(targetFilename, FileMode.Create, FileAccess.Write)) { var buffer = new byte[CopyBufferSize]; int readBytes; while ((readBytes = stream.Read(buffer, 0, CopyBufferSize)) > 0) { fileStream.Write(buffer, 0, readBytes); } } } } private void Initialize() { using (var fileStream = C1File.Open(ZipFilename, FileMode.Open, FileAccess.Read)) { using (var zipArchive = new ZipArchive(fileStream)) { foreach (var entry in zipArchive.Entries) { var normalizedEntryPath = NormalizePathDelimiters(entry.FullName); _denormalizedEntryNames[normalizedEntryPath] = entry.FullName; _entryNames.Add(normalizedEntryPath); } } } } private static string ParseFilename(string filename) { if (!filename.StartsWith("~")) { throw new ArgumentException("filename should start with a '~/' or '~\\'"); } filename = NormalizePathDelimiters(filename.Substring(1)); if (!filename.StartsWith("/")) { throw new ArgumentException("filename should start with a '~/' or '~\\'"); } return filename.Substring(1); } private class StreamWrapper : Stream, IDisposable { private readonly Stream _innerStream; private readonly Action _disposeAction; public StreamWrapper(Stream innerStream, Action disposeAction) { _innerStream = innerStream; _disposeAction = disposeAction; } public override void Flush() { _innerStream.Flush(); } public override long Seek(long offset, SeekOrigin origin) { return _innerStream.Seek(offset, origin); } public override void SetLength(long value) { _innerStream.SetLength(value); } public override int Read(byte[] buffer, int offset, int count) { return _innerStream.Read(buffer, offset, count); } public override void Write(byte[] buffer, int offset, int count) { _innerStream.Write(buffer, offset, count); } public override bool CanRead => _innerStream.CanRead; public override bool CanSeek => _innerStream.CanSeek; public override bool CanWrite => _innerStream.CanWrite; public override long Length => _innerStream.Length; public override long Position { get { return _innerStream.Position; } set { _innerStream.Position = value; } } void IDisposable.Dispose() { _innerStream.Dispose(); _disposeAction(); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~StreamWrapper() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } } ================================================ FILE: Composite/Core/Implementation/C1ConfigurationImplementation.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using Composite.Core.IO; using Composite.Core.IO.Plugins.IOProvider; namespace Composite.Core.Implementation { /// /// Implementation of . /// public class C1ConfigurationImplementation { private IC1Configuration _configuration; /// /// See . /// /// /// public C1ConfigurationImplementation(string path) { _configuration = IOFacade.CreateC1Configuration(path); } /// /// See . /// public virtual string FilePath { get { return _configuration.FilePath; } } /// /// See . /// public virtual bool HasFile { get { return _configuration.HasFile; } } /// /// See . /// public virtual AppSettingsSection AppSettings { get { return _configuration.AppSettings; } } /// /// See . /// public virtual ConnectionStringsSection ConnectionStrings { get { return _configuration.ConnectionStrings; } } /// /// See . /// public virtual ConfigurationSectionCollection Sections { get { return _configuration.Sections; } } /// /// See . /// public virtual ConfigurationSectionGroup RootSectionGroup { get { return _configuration.RootSectionGroup; } } /// /// See . /// public virtual ConfigurationSectionGroupCollection SectionGroups { get { return _configuration.SectionGroups; } } /// /// See . /// /// /// public virtual ConfigurationSection GetSection(string sectionName) { return _configuration.GetSection(sectionName); } /// /// See . /// /// /// public virtual ConfigurationSectionGroup GetSectionGroup(string sectionGroupName) { return _configuration.GetSectionGroup(sectionGroupName); } /// /// See . /// public virtual void Save() { _configuration.Save(); } /// /// See . /// /// public virtual void Save(ConfigurationSaveMode saveMode) { _configuration.Save(saveMode); } /// /// See . /// /// /// public virtual void Save(ConfigurationSaveMode saveMode, bool forceSaveAll) { _configuration.Save(saveMode, forceSaveAll); } /// /// See . /// /// public virtual void SaveAs(string fileName) { _configuration.SaveAs(fileName); } /// /// See . /// /// /// public virtual void SaveAs(string fileName, ConfigurationSaveMode saveMode) { _configuration.SaveAs(fileName, saveMode); } /// /// See . /// /// /// /// public virtual void SaveAs(string fileName, ConfigurationSaveMode saveMode, bool forceSaveAll) { _configuration.SaveAs(fileName, saveMode, forceSaveAll); } } } ================================================ FILE: Composite/Core/Implementation/C1DirectoryImplementation.cs ================================================ using System; using System.IO; using Composite.Core.IO; namespace Composite.Core.Implementation { /// /// Implementation of . /// public class C1DirectoryImplementation { /// /// See . /// /// /// public virtual C1DirectoryInfo CreateDirectory(string path) { return IOFacade.C1Directory.CreateDirectory(path); } /// /// See . /// /// /// public virtual void Move(string sourceDirName, string destinationDirName) { IOFacade.C1Directory.Move(sourceDirName, destinationDirName); } /// /// See . /// /// public virtual void Delete(string path) { IOFacade.C1Directory.Delete(path); } /// /// See . /// /// /// public virtual void Delete(string path, bool recursive) { IOFacade.C1Directory.Delete(path, recursive); } /// /// See . /// /// /// public virtual bool Exists(string path) { return IOFacade.C1Directory.Exists(path); } /// /// See . /// /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public virtual string GetCurrentDirectory() { return IOFacade.C1Directory.GetCurrentDirectory(); } /// /// See . /// /// public virtual void SetCurrentDirectory(string path) { IOFacade.C1Directory.SetCurrentDirectory(path); } /// /// See . /// /// /// public virtual C1DirectoryInfo GetParent(string path) { return IOFacade.C1Directory.GetParent(path); } /// /// See . /// /// /// public virtual string GetDirectoryRoot(string path) { return IOFacade.C1Directory.GetDirectoryRoot(path); } /// /// See . /// /// /// public virtual string[] GetDirectories(string path) { return IOFacade.C1Directory.GetDirectories(path); } /// /// See . /// /// /// /// public virtual string[] GetDirectories(string path, string searchPattern) { return IOFacade.C1Directory.GetDirectories(path, searchPattern); } /// /// See . /// /// /// /// /// public virtual string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) { return IOFacade.C1Directory.GetDirectories(path, searchPattern, searchOption); } /// /// See . /// /// /// public virtual string[] GetFiles(string path) { return IOFacade.C1Directory.GetFiles(path); } /// /// See . /// /// /// /// public virtual string[] GetFiles(string path, string searchPattern) { return IOFacade.C1Directory.GetFiles(path, searchPattern); } /// /// See . /// /// /// /// /// public virtual string[] GetFiles(string path, string searchPattern, SearchOption searchOption) { return IOFacade.C1Directory.GetFiles(path, searchPattern, searchOption); } /// /// See . /// /// /// public virtual DateTime GetCreationTime(string path) { return IOFacade.C1Directory.GetCreationTime(path); } /// /// See . /// /// /// public virtual DateTime GetCreationTimeUtc(string path) { return IOFacade.C1Directory.GetCreationTimeUtc(path); } //public virtual IEnumerable EnumerateDirectories(string path) //{ // throw new NotImplementedException(); //} //public virtual IEnumerable EnumerateDirectories(string path, string searchPattern) //{ // throw new NotImplementedException(); //} //public virtual IEnumerable EnumerateDirectories(string path, string searchPattern, SearchOption searchOption) //{ // throw new NotImplementedException(); //} //public virtual IEnumerable EnumerateFiles(string path) //{ // throw new NotImplementedException(); //} //public virtual IEnumerable EnumerateFiles(string path, string searchPattern) //{ // throw new NotImplementedException(); //} //public virtual IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOption) //{ // throw new NotImplementedException(); //} //public virtual IEnumerable EnumerateFileSystemEntries(string path) //{ // throw new NotImplementedException(); //} //public virtual IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) //{ // throw new NotImplementedException(); //} //public virtual IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption) //{ // throw new NotImplementedException(); //} //public virtual string[] GetFileSystemEntries(string path) //{ // throw new NotImplementedException(); //} //public virtual string[] GetFileSystemEntries(string path, string searchPattern) //{ // throw new NotImplementedException(); //} //public virtual string[] GetFileSystemEntries(string path, string searchPattern, SearchOption searchOption) //{ // throw new NotImplementedException(); //} //public virtual DirectorySecurity GetAccessControl(string path) //{ // throw new NotImplementedException(); //} //public virtual DirectorySecurity GetAccessControl(string path, AccessControlSections includeSections) //{ // throw new NotImplementedException(); //} //public virtual void SetAccessControl(string path, DirectorySecurity directorySecurity) //{ // throw new NotImplementedException(); //} /// public virtual void SetCreationTime(string path, DateTime creationTime) { IOFacade.C1Directory.SetCreationTime(path, creationTime); } /// public virtual void SetCreationTimeUtc(string path, DateTime creationTimeUtc) { IOFacade.C1Directory.SetCreationTimeUtc(path, creationTimeUtc); } //public virtual string[] GetLogicalDrives() //{ // throw new NotImplementedException(); //} //public virtual DateTime GetLastAccessTime(string path) //{ // throw new NotImplementedException(); //} //public virtual void SetLastAccessTime(string path, DateTime lastAccessTime) //{ // throw new NotImplementedException(); //} //public virtual DateTime GetLastAccessTimeUtc(string path) //{ // throw new NotImplementedException(); //} //public virtual void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) //{ // throw new NotImplementedException(); //} //public virtual DateTime GetLastWriteTime(string path) //{ // throw new NotImplementedException(); //} //public virtual void SetLastWriteTime(string path, DateTime lastWriteTime) //{ // throw new NotImplementedException(); //} //public virtual DateTime GetLastWriteTimeUtc(string path) //{ // throw new NotImplementedException(); //} //public virtual void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) //{ // throw new NotImplementedException(); //} } } ================================================ FILE: Composite/Core/Implementation/C1DirectoryInfoImplementation.cs ================================================ using System; using System.IO; using System.Runtime.Serialization; using Composite.Core.IO; using Composite.Core.IO.Plugins.IOProvider; namespace Composite.Core.Implementation { /// /// Implementation of . /// public class C1DirectoryInfoImplementation { private IC1DirectoryInfo _directoryInfo; /// /// See . /// /// public C1DirectoryInfoImplementation(string path) { _directoryInfo = IOFacade.CreateC1DirectoryInfo(path); } /// /// See . /// public string Name { get { return _directoryInfo.Name; } } /// /// See . /// public string FullName { get { return _directoryInfo.FullName; } } /// /// See . /// public string Extension { get { return _directoryInfo.Extension; } } /// /// See . /// public bool Exists { get { return _directoryInfo.Exists; } } /// /// See . /// public C1DirectoryInfo Root { get { return _directoryInfo.Root; } } /// /// See . /// public C1DirectoryInfo Parent { get { return _directoryInfo.Parent; } } /// /// See . /// public FileAttributes Attributes { get { return _directoryInfo.Attributes; } set { _directoryInfo.Attributes = value; } } /// /// See . /// /// public C1DirectoryInfo[] GetDirectories() { return _directoryInfo.GetDirectories(); } /// /// See . /// /// /// public C1DirectoryInfo[] GetDirectories(string searchPattern) { return _directoryInfo.GetDirectories(searchPattern); } /// /// See . /// /// /// /// public C1DirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption) { return _directoryInfo.GetDirectories(searchPattern, searchOption); } /// /// See . /// /// public C1FileInfo[] GetFiles() { return _directoryInfo.GetFiles(); } /// /// See . /// /// /// public C1FileInfo[] GetFiles(string searchPattern) { return _directoryInfo.GetFiles(searchPattern); } /// /// See . /// /// /// /// public C1FileInfo[] GetFiles(string searchPattern, SearchOption searchOption) { return _directoryInfo.GetFiles(searchPattern, searchOption); } /// /// See . /// public void Create() { _directoryInfo.Create(); } /// /// See . /// /// /// public C1DirectoryInfo CreateSubdirectory(string path) { return _directoryInfo.CreateSubdirectory(path); } /// /// See . /// /// public void MoveTo(string destinationDirName) { _directoryInfo.MoveTo(destinationDirName); } /// /// See . /// public void Delete() { _directoryInfo.Delete(); } /// /// See . /// /// public void Delete(bool recursive) { _directoryInfo.Delete(recursive); } /// /// See . /// public DateTime CreationTime { get { return _directoryInfo.CreationTime; } set { _directoryInfo.CreationTime = value; } } /// /// See . /// public DateTime CreationTimeUtc { get { return _directoryInfo.CreationTimeUtc; } set { _directoryInfo.CreationTimeUtc = value; } } /// /// See . /// public DateTime LastAccessTime { get { return _directoryInfo.LastAccessTime; } set { _directoryInfo.LastAccessTime = value; } } /// /// See . /// public DateTime LastAccessTimeUtc { get { return _directoryInfo.LastAccessTimeUtc; } set { _directoryInfo.LastAccessTimeUtc = value; } } /// /// See . /// public DateTime LastWriteTime { get { return _directoryInfo.LastWriteTime; } set { _directoryInfo.LastWriteTime = value; } } /// /// See . /// public DateTime LastWriteTimeUtc { get { return _directoryInfo.LastWriteTimeUtc; } set { _directoryInfo.LastWriteTimeUtc = value; } } /// /// See . /// public void GetObjectData(SerializationInfo info, StreamingContext context) { _directoryInfo.GetObjectData(info, context); } /// /// See . /// public void Refresh() { _directoryInfo.Refresh(); } } } ================================================ FILE: Composite/Core/Implementation/C1FileImplementation.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Text; using Composite.Core.IO; namespace Composite.Core.Implementation { /// /// Implementation of . /// public class C1FileImplementation { /// /// See . /// /// /// public virtual bool Exists(string path) { return IOFacade.C1File.Exists(path); } /// /// See . /// /// public virtual void Touch(string path) { IOFacade.C1File.Touch(path); } /// /// See . /// /// /// public virtual void Copy(string sourceFileName, string destinationFileName) { IOFacade.C1File.Copy(sourceFileName, destinationFileName); } /// /// See . /// /// /// /// public virtual void Copy(string sourceFileName, string destinationFileName, bool overwrite) { IOFacade.C1File.Copy(sourceFileName, destinationFileName, overwrite); } /// /// See . /// /// /// public virtual void Move(string sourceFileName, string destinationFileName) { IOFacade.C1File.Move(sourceFileName, destinationFileName); } /// /// See . /// /// /// /// public virtual void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { IOFacade.C1File.Replace(sourceFileName, destinationFileName, destinationBackupFileName); } /// /// See . /// /// /// /// /// public virtual void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { IOFacade.C1File.Replace(sourceFileName, destinationBackupFileName, destinationBackupFileName, ignoreMetadataErrors); } /// /// See . /// /// public virtual void Delete(string path) { IOFacade.C1File.Delete(path); } /// /// See . /// /// /// public virtual C1FileStream Create(string path) { return IOFacade.C1File.Create(path); } /// /// See . /// /// /// /// public virtual C1FileStream Create(string path, int bufferSize) { return IOFacade.C1File.Create(path, bufferSize); } /// /// See . /// /// /// /// /// public virtual C1FileStream Create(string path, int bufferSize, FileOptions options) { return IOFacade.C1File.Create(path, bufferSize, options); } /// /// See . /// /// /// public virtual C1StreamWriter CreateText(string path) { return IOFacade.C1File.CreateText(path); } /// /// See . /// /// /// public virtual C1StreamWriter AppendText(string path) { return IOFacade.C1File.AppendText(path); } /// /// See . /// /// /// public virtual void AppendAllText(string path, string contents) { IOFacade.C1File.AppendAllText(path, contents); } /// /// See . /// /// /// /// public virtual void AppendAllText(string path, string contents, Encoding encoding) { IOFacade.C1File.AppendAllText(path, contents, encoding); } /// /// See . /// /// /// public virtual void AppendAllLines(string path, IEnumerable contents) { IOFacade.C1File.AppendAllLines(path, contents); } /// /// See . /// /// /// /// public virtual void AppendAllLines(string path, IEnumerable contents, Encoding encoding) { IOFacade.C1File.AppendAllLines(path, contents, encoding); } /// /// See . /// /// /// /// public virtual C1FileStream Open(string path, FileMode mode) { return IOFacade.C1File.Open(path, mode); } /// /// See . /// /// /// /// /// public virtual C1FileStream Open(string path, FileMode mode, FileAccess access) { return IOFacade.C1File.Open(path, mode, access); } /// /// See . /// /// /// /// /// /// public virtual C1FileStream Open(string path, FileMode mode, FileAccess access, FileShare share) { return IOFacade.C1File.Open(path, mode, access, share); } /// /// See . /// /// /// public virtual C1FileStream OpenRead(string path) { return IOFacade.C1File.OpenRead(path); } /// /// See . /// /// /// public virtual C1StreamReader OpenText(string path) { return IOFacade.C1File.OpenText(path); } /// /// See . /// /// /// public virtual C1FileStream OpenWrite(string path) { return IOFacade.C1File.OpenWrite(path); } /// /// See . /// /// /// public virtual byte[] ReadAllBytes(string path) { return IOFacade.C1File.ReadAllBytes(path); } /// /// See . /// /// /// public virtual string[] ReadAllLines(string path) { return IOFacade.C1File.ReadAllLines(path); } /// /// See . /// /// /// /// public virtual string[] ReadAllLines(string path, Encoding encoding) { return IOFacade.C1File.ReadAllLines(path, encoding); } /// /// See . /// /// /// public virtual string ReadAllText(string path) { return IOFacade.C1File.ReadAllText(path); } /// /// See . /// /// /// /// public virtual string ReadAllText(string path, Encoding encoding) { return IOFacade.C1File.ReadAllText(path, encoding); } /// /// See . /// /// /// public virtual IEnumerable ReadLines(string path) { return IOFacade.C1File.ReadLines(path); } /// /// See . /// /// /// /// public virtual IEnumerable ReadLines(string path, Encoding encoding) { return IOFacade.C1File.ReadLines(path, encoding); } /// /// See . /// /// /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "bytes")] public virtual void WriteAllBytes(string path, byte[] bytes) { IOFacade.C1File.WriteAllBytes(path, bytes); } /// /// See . /// /// /// public virtual void WriteAllLines(string path, IEnumerable contents) { IOFacade.C1File.WriteAllLines(path, contents); } /// /// See . /// /// /// public virtual void WriteAllLines(string path, string[] contents) { IOFacade.C1File.WriteAllLines(path, contents); } /// /// See . /// /// /// /// public virtual void WriteAllLines(string path, IEnumerable contents, Encoding encoding) { IOFacade.C1File.WriteAllLines(path, contents, encoding); } /// /// See . /// /// /// /// public virtual void WriteAllLines(string path, string[] contents, Encoding encoding) { IOFacade.C1File.WriteAllLines(path, contents, encoding); } /// /// See . /// /// /// public virtual void WriteAllText(string path, string contents) { IOFacade.C1File.WriteAllText(path, contents); } /// /// See . /// /// /// /// public virtual void WriteAllText(string path, string contents, Encoding encoding) { IOFacade.C1File.WriteAllText(path, contents, encoding); } /// /// See . /// /// /// public virtual FileAttributes GetAttributes(string path) { return IOFacade.C1File.GetAttributes(path); } /// /// See . /// /// /// public virtual void SetAttributes(string path, FileAttributes fileAttributes) { IOFacade.C1File.SetAttributes(path, fileAttributes); } /// /// See . /// /// /// public virtual DateTime GetCreationTime(string path) { return IOFacade.C1File.GetCreationTime(path); } /// /// See . /// /// /// public virtual DateTime GetCreationTimeUtc(string path) { return IOFacade.C1File.GetCreationTimeUtc(path); } /// /// See . /// /// /// public virtual void SetCreationTime(string path, DateTime creationTime) { IOFacade.C1File.SetCreationTime(path, creationTime); } /// /// See . /// /// /// public virtual void SetCreationTimeUtc(string path, DateTime creationTimeUtc) { IOFacade.C1File.SetCreationTimeUtc(path, creationTimeUtc); } /// /// See . /// /// /// public virtual DateTime GetLastAccessTime(string path) { return IOFacade.C1File.GetLastAccessTime(path); } /// /// See . /// /// /// public virtual DateTime GetLastAccessTimeUtc(string path) { return IOFacade.C1File.GetLastAccessTimeUtc(path); } /// /// See . /// /// /// public virtual void SetLastAccessTime(string path, DateTime lastAccessTime) { IOFacade.C1File.SetLastAccessTime(path, lastAccessTime); } /// /// See . /// /// /// public virtual void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) { IOFacade.C1File.SetLastAccessTimeUtc(path, lastAccessTimeUtc); } /// /// See . /// /// /// public virtual DateTime GetLastWriteTime(string path) { return IOFacade.C1File.GetLastWriteTime(path); } /// /// See . /// /// /// public virtual DateTime GetLastWriteTimeUtc(string path) { return IOFacade.C1File.GetLastWriteTimeUtc(path); } /// /// See . /// /// /// public virtual void SetLastWriteTime(string path, DateTime lastWriteTime) { IOFacade.C1File.SetLastWriteTime(path, lastWriteTime); } /// /// See . /// /// /// public virtual void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) { IOFacade.C1File.SetLastWriteTimeUtc(path, lastWriteTimeUtc); } //public virtual FileStream Create(string path, int bufferSize, System.IO.FileOptions options, System.Security.AccessControl.FileSecurity fileSecurity) //{ // throw new NotImplementedException(); //} //public virtual void Encrypt(string path) //{ // throw new NotImplementedException(); //} //public virtual void Decrypt(string path) //{ // throw new NotImplementedException(); //} //public virtual System.Security.AccessControl.FileSecurity GetAccessControl(string path) //{ // throw new NotImplementedException(); //} //public virtual System.Security.AccessControl.FileSecurity GetAccessControl(string path, System.Security.AccessControl.AccessControlSections includeSections) //{ // throw new NotImplementedException(); //} //public virtual void SetAccessControl(string path, System.Security.AccessControl.FileSecurity fileSecurity) //{ // throw new NotImplementedException(); //} } } ================================================ FILE: Composite/Core/Implementation/C1FileInfoImplementation.cs ================================================ using System; using System.IO; using System.Runtime.Serialization; using Composite.Core.IO; using Composite.Core.IO.Plugins.IOProvider; namespace Composite.Core.Implementation { /// /// Implementation of . /// public class C1FileInfoImplementation { private IC1FileInfo _fileInfo; /// /// See . /// /// public C1FileInfoImplementation(string path) { _fileInfo = IOFacade.CreateC1FileInfo(path); } /// /// See . /// public string DirectoryName { get { return _fileInfo.DirectoryName; } } /// /// See . /// public C1DirectoryInfo Directory { get { return _fileInfo.Directory; } } /// /// See . /// public string Name { get { return _fileInfo.Name; } } /// /// See . /// public string FullName { get { return _fileInfo.FullName; } } /// /// See . /// public bool Exists { get { return _fileInfo.Exists; } } /// /// See . /// public string Extension { get { return _fileInfo.Extension; } } /// /// See . /// public bool IsReadOnly { get { return _fileInfo.IsReadOnly; } set { _fileInfo.IsReadOnly = value; } } /// /// See . /// public long Length { get { return _fileInfo.Length; } } /// /// See . /// public FileAttributes Attributes { get { return _fileInfo.Attributes; } set { _fileInfo.Attributes = value; } } /// /// See . /// /// public C1FileStream Create() { return _fileInfo.Create(); } /// /// See . /// /// public C1StreamWriter CreateText() { return _fileInfo.CreateText(); } /// /// See . /// /// public C1StreamWriter AppendText() { return _fileInfo.AppendText(); } /// /// See . /// /// /// public C1FileStream Open(FileMode mode) { return _fileInfo.Open(mode); } /// /// See . /// /// /// /// public C1FileStream Open(FileMode mode, FileAccess access) { return _fileInfo.Open(mode, access); } /// /// See . /// /// /// /// /// public C1FileStream Open(FileMode mode, FileAccess access, FileShare share) { return _fileInfo.Open(mode, access, share); } /// /// See . /// /// public C1FileStream OpenRead() { return _fileInfo.OpenRead(); } /// /// See . /// /// public C1StreamReader OpenText() { return _fileInfo.OpenText(); } /// /// See . /// /// public C1FileStream OpenWrite() { return _fileInfo.OpenWrite(); } /// /// See . /// /// /// public C1FileInfo CopyTo(string destinationFileName) { return _fileInfo.CopyTo(destinationFileName); } /// /// See . /// /// /// /// public C1FileInfo CopyTo(string destinationFileName, bool overwrite) { return _fileInfo.CopyTo(destinationFileName, overwrite); } /// /// See . /// /// public void MoveTo(string destinationFileName) { _fileInfo.MoveTo(destinationFileName); } /// /// See . /// /// /// /// public C1FileInfo Replace(string destinationFileName, string destinationBackupFileName) { return _fileInfo.Replace(destinationFileName, destinationBackupFileName); } /// /// See . /// /// /// /// /// public C1FileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { return _fileInfo.Replace(destinationFileName, destinationBackupFileName, ignoreMetadataErrors); } /// /// See . /// public void Delete() { _fileInfo.Delete(); } /// /// See . /// public void Refresh() { _fileInfo.Refresh(); } /// /// See . /// /// /// public void GetObjectData(SerializationInfo info, StreamingContext context) { _fileInfo.GetObjectData(info, context); } /// /// See . /// public DateTime CreationTime { get { return _fileInfo.CreationTime; } set { _fileInfo.CreationTime = value; } } /// /// See . /// public DateTime CreationTimeUtc { get { return _fileInfo.CreationTimeUtc; } set { _fileInfo.CreationTimeUtc = value; } } /// /// See . /// public DateTime LastAccessTime { get { return _fileInfo.LastAccessTime; } set { _fileInfo.LastAccessTime = value; } } /// /// See . /// public DateTime LastAccessTimeUtc { get { return _fileInfo.LastAccessTimeUtc; } set { _fileInfo.LastAccessTimeUtc = value; } } /// /// See . /// public DateTime LastWriteTime { get { return _fileInfo.LastWriteTime; } set { _fileInfo.LastWriteTime = value; } } /// /// See . /// public DateTime LastWriteTimeUtc { get { return _fileInfo.LastWriteTimeUtc; } set { _fileInfo.LastWriteTimeUtc = value; } } } } ================================================ FILE: Composite/Core/Implementation/C1FileStreamImplementation.cs ================================================ using System; using System.IO; using System.Runtime.InteropServices; using Composite.Core.IO; using Composite.Core.IO.Plugins.IOProvider; namespace Composite.Core.Implementation { /// /// Implementation of . /// public class C1FileStreamImplementation : IDisposable { private IC1FileStream _fileStream; /// /// See . /// /// /// /// /// /// /// public C1FileStreamImplementation(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { _fileStream = IOFacade.CreateC1FileStream(path, mode, access, share, bufferSize, options); } /// /// See . /// public virtual string Name { get { return _fileStream.Name; } } /// /// See . /// public virtual long Length { get { return _fileStream.Length; } } /// /// See . /// /// public virtual void SetLength(long value) { _fileStream.SetLength(value); } /// /// See . /// public virtual long Position { get { return _fileStream.Position; } set { _fileStream.Position = value; } } /// /// See . /// /// /// /// /// public virtual int Read(byte[] array, int offset, int count) { return _fileStream.Read(array, offset, count); } /// /// See . /// /// public virtual int ReadByte() { return _fileStream.ReadByte(); } /// /// See . /// /// /// /// public virtual void Write(byte[] array, int offset, int count) { _fileStream.Write(array, offset, count); } /// /// See . /// /// public virtual void WriteByte(byte value) { _fileStream.WriteByte(value); } /// /// See . /// /// /// /// public virtual long Seek(long offset, SeekOrigin origin) { return _fileStream.Seek(offset, origin); } /// /// See . /// public virtual bool CanRead { get { return _fileStream.CanRead; } } /// /// See . /// public virtual bool CanSeek { get { return _fileStream.CanSeek; } } /// /// See . /// public virtual bool CanWrite { get { return _fileStream.CanWrite; } } /// /// See . /// public virtual void Flush() { _fileStream.Flush(); } /// /// See . /// /// public virtual void Flush(bool flushToDisk) { _fileStream.Flush(flushToDisk); } /// /// See . /// public virtual void Close() { _fileStream.Close(); } /// public void Dispose() { Dispose(true); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~C1FileStreamImplementation() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); Dispose(false); } #endif /// protected virtual void Dispose(bool disposing) { if (disposing) { _fileStream.Dispose(); } } //public virtual bool IsAsync //{ // get // { // throw new NotImplementedException(); // } //} ////[Obsolete("This property has been deprecated. Please use FileStream's SafeFileHandle property instead. http://go.microsoft.com/fwlink/?linkid=14202")] //public virtual IntPtr Handle //{ // get // { // throw new NotImplementedException(); // } //} //public virtual FileSecurity GetAccessControl() //{ // throw new NotImplementedException(); //} //public virtual void SetAccessControl(FileSecurity fileSecurity) //{ // throw new NotImplementedException(); //} //public virtual void Lock(long position, long length) //{ // throw new NotImplementedException(); //} //public virtual void Unlock(long position, long length) //{ // throw new NotImplementedException(); //} } } ================================================ FILE: Composite/Core/Implementation/C1FileSystemWatcherImplementation.cs ================================================ using System.IO; using Composite.Core.IO; using Composite.Core.IO.Plugins.IOProvider; namespace Composite.Core.Implementation { /// /// Implementation of . /// public class C1FileSystemWatcherImplementation { private readonly IC1FileSystemWatcher _fileSystemWatcher; /// /// See . /// /// /// public C1FileSystemWatcherImplementation(string path, string filter) { _fileSystemWatcher = IOFacade.CreateC1FileSystemWatcher(path, filter); } /// /// See . /// public virtual bool EnableRaisingEvents { get { return _fileSystemWatcher.EnableRaisingEvents; } set { _fileSystemWatcher.EnableRaisingEvents = value; } } /// /// See . /// public virtual string Path { get { return _fileSystemWatcher.Path; } set { _fileSystemWatcher.Path = value; } } /// /// See . /// public virtual string Filter { get { return _fileSystemWatcher.Filter; } set { _fileSystemWatcher.Filter = value; } } /// /// See . /// public virtual bool IncludeSubdirectories { get { return _fileSystemWatcher.IncludeSubdirectories; } set { _fileSystemWatcher.IncludeSubdirectories = value; } } /// /// See . /// public virtual int InternalBufferSize { get { return _fileSystemWatcher.InternalBufferSize; } set { _fileSystemWatcher.InternalBufferSize = value; } } /// /// See . /// public virtual event FileSystemEventHandler Created { add { _fileSystemWatcher.Created += value; } remove { _fileSystemWatcher.Created -= value; } } /// /// See . /// public virtual event FileSystemEventHandler Changed { add { _fileSystemWatcher.Changed += value; } remove { _fileSystemWatcher.Changed -= value; } } /// /// See . /// public virtual event RenamedEventHandler Renamed { add { _fileSystemWatcher.Renamed += value; } remove { _fileSystemWatcher.Renamed -= value; } } /// /// See . /// public virtual event FileSystemEventHandler Deleted { add { _fileSystemWatcher.Deleted += value; } remove { _fileSystemWatcher.Deleted -= value; } } /// /// See . /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] public virtual event ErrorEventHandler Error { add { _fileSystemWatcher.Error += value; } remove { _fileSystemWatcher.Error -= value; } } /// /// See . /// public virtual NotifyFilters NotifyFilter { get { return _fileSystemWatcher.NotifyFilter; } set { _fileSystemWatcher.NotifyFilter = value; } } /// /// See . /// public virtual void BeginInit() { _fileSystemWatcher.BeginInit(); } /// /// See . /// public virtual void EndInit() { _fileSystemWatcher.EndInit(); } /// /// See . /// /// /// public virtual C1WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) { return _fileSystemWatcher.WaitForChanged(changeType); } /// /// See . /// /// /// /// public virtual C1WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout) { return _fileSystemWatcher.WaitForChanged(changeType, timeout); } } } ================================================ FILE: Composite/Core/Implementation/C1StreamReaderImplementation.cs ================================================ using System; using System.IO; using System.Runtime.InteropServices; using System.Text; using Composite.Core.IO; using Composite.Core.IO.Plugins.IOProvider; namespace Composite.Core.Implementation { /// /// Implementation of . /// public class C1StreamReaderImplementation : IDisposable { private IC1StreamReader _streamReader; /// /// See . /// /// /// /// /// public C1StreamReaderImplementation(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { _streamReader = IOFacade.CreateC1StreamReader(path, encoding, detectEncodingFromByteOrderMarks, bufferSize); } /// /// See . /// /// /// /// /// public C1StreamReaderImplementation(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { _streamReader = IOFacade.CreateC1StreamReader(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize); } /// /// See . /// /// public virtual int Read() { return _streamReader.Read(); } /// /// See . /// /// /// /// /// public virtual int Read(char[] buffer, int index, int count) { return _streamReader.Read(buffer, index, count); } /// /// See . /// /// public virtual string ReadLine() { return _streamReader.ReadLine(); } /// /// See . /// /// public virtual string ReadToEnd() { return _streamReader.ReadToEnd(); } /// /// See . /// /// /// /// /// public virtual int ReadBlock(char[] buffer, int index, int count) { return _streamReader.ReadBlock(buffer, index, count); } /// /// See . /// /// public virtual int Peek() { return _streamReader.Peek(); } /// /// See . /// public virtual bool EndOfStream { get { return _streamReader.EndOfStream; } } /// /// See . /// public virtual void Close() { _streamReader.Close(); } /// /// See . /// public virtual Stream BaseStream { get { return _streamReader.BaseStream; } } /// /// See . /// public virtual Encoding CurrentEncoding { get { return _streamReader.CurrentEncoding; } } /// /// See . /// public void Dispose() { Dispose(true); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~C1StreamReaderImplementation() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); Dispose(false); } #endif /// /// See . /// /// protected virtual void Dispose(bool disposing) { if (disposing) { _streamReader.Dispose(); } } } } ================================================ FILE: Composite/Core/Implementation/C1StreamWriterImplementation.cs ================================================ using System; using System.IO; using System.Text; using Composite.Core.IO; using Composite.Core.IO.Plugins.IOProvider; namespace Composite.Core.Implementation { /// /// Implementation of . /// public class C1StreamWriterImplementation : IDisposable { private IC1StreamWriter _streamWriter; /// /// See . /// /// /// /// /// public C1StreamWriterImplementation(string path, bool append, Encoding encoding, int bufferSize) { _streamWriter = IOFacade.CreateC1StreamWriter(path, append, encoding, bufferSize); } /// /// See . /// /// /// /// public C1StreamWriterImplementation(Stream stream, Encoding encoding, int bufferSize) { _streamWriter = IOFacade.CreateC1StreamWriter(stream, encoding, bufferSize); } /// /// See . /// /// public virtual void Write(string value) { _streamWriter.Write(value); } /// /// See . /// /// /// public virtual void Write(string format, object arg0) { _streamWriter.Write(format, arg0); } /// /// See . /// /// /// /// public virtual void Write(string format, object arg0, object arg1) { _streamWriter.Write(format, arg0, arg1); } /// /// See . /// /// /// /// /// public virtual void Write(string format, object arg0, object arg1, object arg2) { _streamWriter.Write(format, arg0, arg1, arg2); } /// /// See . /// /// /// public virtual void Write(string format, params object[] arg) { _streamWriter.Write(format, arg); } /// /// See . /// /// public virtual void Write(char value) { _streamWriter.Write(value); } /// /// See . /// /// public virtual void Write(char[] buffer) { _streamWriter.Write(buffer); } /// /// See . /// /// /// /// public virtual void Write(char[] buffer, int index, int count) { _streamWriter.Write(buffer, index, count); } /// /// See . /// /// public virtual void Write(bool value) { _streamWriter.Write(value); } /// /// See . /// /// public virtual void Write(int value) { _streamWriter.Write(value); } /// /// See . /// /// public virtual void Write(uint value) { _streamWriter.Write(value); } /// /// See . /// /// public virtual void Write(long value) { _streamWriter.Write(value); } /// /// See . /// /// public virtual void Write(ulong value) { _streamWriter.Write(value); } /// /// See . /// /// public virtual void Write(float value) { _streamWriter.Write(value); } /// /// See . /// /// public virtual void Write(double value) { _streamWriter.Write(value); } /// /// See . /// /// public virtual void Write(decimal value) { _streamWriter.Write(value); } /// /// See . /// /// public virtual void Write(object value) { _streamWriter.Write(value); } /// /// See . /// public virtual void WriteLine() { _streamWriter.WriteLine(); } /// /// See . /// /// public virtual void WriteLine(string value) { _streamWriter.WriteLine(value); } /// /// See . /// /// /// public virtual void WriteLine(string format, object arg0) { _streamWriter.WriteLine(format, arg0); } /// /// See . /// /// /// /// public virtual void WriteLine(string format, object arg0, object arg1) { _streamWriter.WriteLine(format, arg0, arg1); } /// /// See . /// /// /// /// /// public virtual void WriteLine(string format, object arg0, object arg1, object arg2) { _streamWriter.WriteLine(format, arg0, arg1, arg2); } /// /// See . /// /// /// public virtual void WriteLine(string format, params object[] arg) { _streamWriter.WriteLine(format, arg); } /// /// See . /// /// public virtual void WriteLine(char value) { _streamWriter.WriteLine(value); } /// /// See . /// /// public virtual void WriteLine(char[] buffer) { _streamWriter.WriteLine(buffer); } /// /// See . /// /// /// /// public virtual void WriteLine(char[] buffer, int index, int count) { _streamWriter.WriteLine(buffer, index, count); } /// /// See . /// /// public virtual void WriteLine(bool value) { _streamWriter.WriteLine(value); } /// /// See . /// /// public virtual void WriteLine(int value) { _streamWriter.WriteLine(value); } /// /// See . /// /// public virtual void WriteLine(uint value) { _streamWriter.WriteLine(value); } /// /// See . /// /// public virtual void WriteLine(long value) { _streamWriter.WriteLine(value); } /// /// See . /// /// public virtual void WriteLine(ulong value) { _streamWriter.WriteLine(value); } /// /// See . /// /// public virtual void WriteLine(float value) { _streamWriter.WriteLine(value); } /// /// See . /// /// public virtual void WriteLine(double value) { _streamWriter.WriteLine(value); } /// /// See . /// /// public virtual void WriteLine(decimal value) { _streamWriter.WriteLine(value); } /// /// See . /// /// public virtual void WriteLine(object value) { _streamWriter.WriteLine(value); } /// /// See . /// public virtual string NewLine { get { return _streamWriter.NewLine; } set { _streamWriter.NewLine = value; } } /// /// See . /// public virtual IFormatProvider FormatProvider { get { return _streamWriter.FormatProvider; } } /// /// See . /// public virtual void Flush() { _streamWriter.Flush(); } /// /// See . /// public virtual bool AutoFlush { get { return _streamWriter.AutoFlush; } set { _streamWriter.AutoFlush = value; } } /// /// See . /// public virtual void Close() { _streamWriter.Close(); } /// /// See . /// public virtual Stream BaseStream { get { return _streamWriter.BaseStream; } } /// /// See . /// public virtual Encoding Encoding { get { return _streamWriter.Encoding; } } /// /// See . /// public void Dispose() { Dispose(true); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~C1StreamWriterImplementation() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); Dispose(false); } #endif /// /// See . /// /// protected virtual void Dispose(bool disposing) { if (disposing) { _streamWriter.Dispose(); } } } } ================================================ FILE: Composite/Core/Implementation/DataConnectionBase.cs ================================================ using System; using System.Globalization; using Composite.Core.Extensions; using Composite.Data; namespace Composite.Core.Implementation { /// /// Documentation pending /// public class DataConnectionBase { /// /// Documentation pending /// protected void InitializeScope() { this.PublicationScope = Data.PublicationScope.Unpublished; this.DataScopeIdentifier = DataScopeIdentifier.Administrated; this.Locale = null; } /// /// Documentation pending /// /// /// protected void InitializeScope(PublicationScope scope, CultureInfo locale) { this.PublicationScope = scope; SetDataScopeIdentifier(scope); this.Locale = locale; } /// /// Documentation pending /// protected PublicationScope PublicationScope { get; private set; } /// /// Documentation pending /// protected DataScopeIdentifier DataScopeIdentifier { get; private set; } /// /// Documentation pending /// protected CultureInfo Locale { get; private set; } private void SetDataScopeIdentifier(PublicationScope scope) { switch (scope) { case PublicationScope.Published: this.DataScopeIdentifier = DataScopeIdentifier.Public; break; case PublicationScope.Unpublished: this.DataScopeIdentifier = DataScopeIdentifier.Administrated; break; default: throw new ArgumentException("PublicationScope {0} not supported".FormatWith(scope), "scope"); } } } } ================================================ FILE: Composite/Core/Implementation/DataConnectionImplementation.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Composite.Core.Threading; using Composite.Data; namespace Composite.Core.Implementation { /// /// Documentation pending /// public class DataConnectionImplementation : DataConnectionBase, IDisposable { private IDisposable _threadDataManager; private readonly IDisposable _serviceScope; private readonly DataScope _dataScope; internal DataScope DataScope => _dataScope; /// /// Documentation pending /// /// /// public DataConnectionImplementation(PublicationScope scope, CultureInfo locale) { InitializeThreadData(); InitializeScope(scope, locale); _dataScope = new DataScope(this.DataScopeIdentifier, locale); _serviceScope = ServiceLocator.EnsureThreadDataServiceScope(); } private void InitializeThreadData() { _threadDataManager = ThreadDataManager.EnsureInitialize(); } /// /// Documentation pending /// /// /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get", Justification = "This is what we want")] public virtual IQueryable Get() where TData : class, IData { // using (new DataScope(this.DataScopeIdentifier, this.Locale)) { return DataFacade.GetData(); } } /// /// Documentation pending /// /// /// /// public virtual TData Add(TData item) where TData : class, IData { // using (new DataScope(this.DataScopeIdentifier, this.Locale)) { return DataFacade.AddNew(item); } } /// /// Documentation pending /// /// /// /// public virtual IList Add(IEnumerable items) where TData : class, IData { // using (new DataScope(this.DataScopeIdentifier, this.Locale)) { return DataFacade.AddNew(items); } } /// /// Documentation pending /// /// /// public virtual void Update(TData item) where TData : class, IData { // using (new DataScope(this.DataScopeIdentifier, this.Locale)) { DataFacade.Update(item); } } /// /// Documentation pending /// /// /// public virtual void Update(IEnumerable items) where TData : class, IData { // using (new DataScope(this.DataScopeIdentifier, this.Locale)) { DataFacade.Update(items); } } /// /// Documentation pending /// /// /// public virtual void Delete(TData item) where TData : class, IData { // using (new DataScope(this.DataScopeIdentifier, this.Locale)) { DataFacade.Delete(item); } } /// /// Documentation pending /// /// /// public virtual void Delete(IEnumerable items) where TData : class, IData { // using (new DataScope(this.DataScopeIdentifier, this.Locale)) { DataFacade.Delete(items); } } /// /// Documentation pending /// public virtual PublicationScope CurrentPublicationScope => this.PublicationScope; /// /// Documentation pending /// public virtual CultureInfo CurrentLocale => this.Locale; /// /// Documentation pending /// public void Dispose() { Dispose(true); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~DataConnectionImplementation() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); Dispose(false); } #endif /// /// Documentation pending /// /// protected virtual void Dispose(bool disposing) { if (disposing) { _serviceScope?.Dispose(); _dataScope.Dispose(); _threadDataManager.Dispose(); } } } } ================================================ FILE: Composite/Core/Implementation/DataEventsImplementation.cs ================================================ using System; using System.Globalization; using Composite.Data; namespace Composite.Core.Implementation { /// /// Implementation pending /// /// public class DataEventsImplementation where TData : class, IData { /// /// Implementation pending /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly", Justification = "We had to be backwards compatible")] public virtual event DataEventHandler OnBeforeAdd { add { DataEventSystemFacade.SubscribeToDataBeforeAdd(value, true); } remove { DataEventSystemFacade.UnsubscribeToDataBeforeAdd(typeof(TData), value); } } /// /// Implementation pending /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly", Justification = "We had to be backwards compatible")] public virtual event DataEventHandler OnAfterAdd { add { DataEventSystemFacade.SubscribeToDataAfterAdd(value, true); } remove { DataEventSystemFacade.UnsubscribeToDataAfterAdd(typeof(TData), value); } } /// /// Implementation pending /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly", Justification = "We had to be backwards compatible")] public virtual event DataEventHandler OnBeforeUpdate { add { DataEventSystemFacade.SubscribeToDataBeforeUpdate(value, true); } remove { DataEventSystemFacade.UnsubscribeToDataBeforeUpdate(typeof(TData), value); } } /// /// Implementation pending /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly", Justification = "We had to be backwards compatible")] public virtual event DataEventHandler OnAfterUpdate { add { DataEventSystemFacade.SubscribeToDataAfterUpdate(value, true); } remove { DataEventSystemFacade.UnsubscribeToDataAfterUpdate(typeof(TData), value); } } /// /// Implementation pending /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly", Justification = "We had to be backwards compatible")] public virtual event DataEventHandler OnDeleted { add { DataEventSystemFacade.SubscribeToDataDeleted(value, true); } remove { DataEventSystemFacade.UnsubscribeToDataDeleted(typeof(TData), value); } } /// /// Implementation pending /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly", Justification = "We had to be backwards compatible")] public virtual event StoreEventHandler OnStoreChanged { add { DataEventSystemFacade.SubscribeToStoreChanged(value, true); } remove { DataEventSystemFacade.UnsubscribeToStoreChanged(typeof(TData), value); } } /// /// Implementation pending /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly", Justification = "We had to be backwards compatible")] public virtual event DataEventHandler OnNew { add { DataEventSystemFacade.SubscribeToDataAfterBuildNew(value, true); } remove { DataEventSystemFacade.UnsubscribeToDataAfterBuildNew(typeof(TData), value); } } /// /// Implementation pending /// public virtual void FireExternalStoreChangeEvent(PublicationScope publicationScope, CultureInfo locale) { DataEventSystemFacade.FireExternalStoreChangedEvent(typeof(TData), publicationScope, locale); } } } ================================================ FILE: Composite/Core/Implementation/ImplementationContainer.cs ================================================ using System; namespace Composite.Core.Implementation { /// /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ImplementationContainer where T : class { private T _implementation; private bool _disposed; private readonly Func _create; internal ImplementationContainer(Func create) { _create = create; } internal T Implementation { get { if (_implementation == null) { CreateImplementation(); } return _implementation; } } internal void CreateImplementation() { if (_disposed) throw new InvalidOperationException("Already disposed"); _implementation = _create(); } internal void DisposeImplementation() { _disposed = true; (_implementation as IDisposable)?.Dispose(); _implementation = null; } } } ================================================ FILE: Composite/Core/Implementation/ImplementationFactory.cs ================================================ using System.Globalization; using Composite.Data; using System.IO; using System.Text; using System; namespace Composite.Core.Implementation { /// /// Documentation pending /// public class ImplementationFactory { static ImplementationFactory() { CurrentFactory = new ImplementationFactory(); } /// /// Use this to change the current factory; /// public static ImplementationFactory CurrentFactory { get; set; } /// /// Documentation pending /// public virtual LogImplementation StatelessLog { get { return new LogImplementation(); } } /// /// Documentation pending /// public virtual StatelessDataConnectionImplementation StatelessDataConnection => new StatelessDataConnectionImplementation(); internal object ResolveService(Type t) { return DataServiceScopeManager.GetService(t); } /// /// Documentation pending /// /// /// /// public virtual DataConnectionImplementation CreateDataConnection(PublicationScope? scope, CultureInfo locale) { PublicationScope scopeToUse = ResolvePublicationScope(scope); CultureInfo localeToUse = ResolveLocale(locale); return new DataConnectionImplementation(scopeToUse, localeToUse); } /// /// Documentation pending /// /// /// public virtual DataEventsImplementation CreateStatelessDataEvents() where T : class, IData { return new DataEventsImplementation(); } //public virtual PageDataConnectionImplementation StatelessPageDataConnection //{ // get // { // return new PageDataConnectionImplementation(); // } //} //public virtual PageDataConnectionImplementation CreatePageDataConnection(PublicationScope? scope, CultureInfo locale) //{ // PublicationScope scopeToUse = ResolvePublicationScope(scope); // CultureInfo localeToUse = ResolveLocale(locale); // return new PageDataConnectionImplementation(scopeToUse, localeToUse); //} /// /// Documentation pending /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Sitemap")] public virtual SitemapNavigatorImplementation StatelessSitemapNavigator { get { return new SitemapNavigatorImplementation(); } } /// /// Documentation pending /// /// /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Sitemap")] public virtual SitemapNavigatorImplementation CreateSitemapNavigator(DataConnection connection) { return new SitemapNavigatorImplementation(connection); } /// /// Documentation pending /// /// /// public virtual PublicationScope ResolvePublicationScope(PublicationScope? scope) { PublicationScope scopeToUse = PublicationScope.Published; if (scope.HasValue) { scopeToUse = scope.Value; } else { if (DataScopeManager.CurrentDataScope.Equals(DataScopeIdentifier.Administrated)) { scopeToUse = PublicationScope.Unpublished; } else if (DataScopeManager.CurrentDataScope.Equals(DataScopeIdentifier.Public)) { scopeToUse = PublicationScope.Published; } } return scopeToUse; } /// /// Documentation pending /// /// /// public virtual CultureInfo ResolveLocale(CultureInfo locale) { CultureInfo localeToUse = locale ?? LocalizationScopeManager.CurrentLocalizationScope; if (localeToUse == null || localeToUse.Equals(CultureInfo.InvariantCulture)) { localeToUse = DataLocalizationFacade.DefaultLocalizationCulture; } return localeToUse; } #region IO /// /// Documentation pending /// public virtual C1DirectoryImplementation StatelessC1Directory { get { return new C1DirectoryImplementation(); } } /// /// Documentation pending /// public virtual C1FileImplementation StatelessC1File { get { return new C1FileImplementation(); } } /// /// Documentation pending /// /// /// public virtual C1FileInfoImplementation CreateC1FileInfo(string path) { return new C1FileInfoImplementation(path); } /// /// Documentation pending /// /// /// public virtual C1DirectoryInfoImplementation CreateC1DirectoryInfo(string path) { return new C1DirectoryInfoImplementation(path); } /// /// Documentation pending /// /// /// /// /// /// /// /// public virtual C1FileStreamImplementation CreateC1FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { return new C1FileStreamImplementation(path, mode, access, share, bufferSize, options); } /// /// Documentation pending /// /// /// /// public virtual C1FileSystemWatcherImplementation CreateC1FileSystemWatcher(string path, string filter) { return new C1FileSystemWatcherImplementation(path, filter); } /// /// Documentation pending /// /// /// /// /// /// public virtual C1StreamReaderImplementation CreateC1StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { return new C1StreamReaderImplementation(path, encoding, detectEncodingFromByteOrderMarks, bufferSize); } /// /// Documentation pending /// /// /// /// /// /// public virtual C1StreamReaderImplementation CreateC1StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { return new C1StreamReaderImplementation(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize); } /// /// Documentation pending /// /// /// /// /// /// public virtual C1StreamWriterImplementation CreateC1StreamWriter(string path, bool append, Encoding encoding, int bufferSize) { return new C1StreamWriterImplementation(path, append, encoding, bufferSize); } /// /// Documentation pending /// /// /// /// /// public virtual C1StreamWriterImplementation CreateC1StreamWriter(Stream stream, Encoding encoding, int bufferSize) { return new C1StreamWriterImplementation(stream, encoding, bufferSize); } /// /// Documentation pending /// /// /// public virtual C1ConfigurationImplementation CreateC1Configuration(string path) { return new C1ConfigurationImplementation(path); } #endregion /// /// Documentation pending /// public virtual PackageLicenseHelperImplementation StatelessPackageLicenseHelper { get { return new PackageLicenseHelperImplementation(); } } /// /// Documentation pending /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Utils")] public virtual PackageUtilsImplementation StatelessPackageUtils { get { return new PackageUtilsImplementation(); } } } } ================================================ FILE: Composite/Core/Implementation/LogImplementation.cs ================================================ using System; using System.Globalization; using Composite.Core.Logging; using Microsoft.Extensions.DependencyInjection; namespace Composite.Core.Implementation { /// /// Implementation pending /// public class LogImplementation : ILog { /// /// Stateless constructor. This is used when implementations of static methods needs to be called /// public LogImplementation() { } /// /// Implementation pending /// /// /// public virtual void LogInformation(string title, string message) { LoggingService.LogInformation(title, message); } /// /// Implementation pending /// /// /// /// public virtual void LogInformation(string title, string messageFormat, params object[] args) { LoggingService.LogInformation(title, string.Format(CultureInfo.InvariantCulture, messageFormat, args)); } /// /// Implementation pending /// /// /// public virtual void LogVerbose(string title, string message) { LoggingService.LogVerbose(title, message); } /// /// Implementation pending /// /// /// /// public virtual void LogVerbose(string title, string messageFormat, params object[] args) { LoggingService.LogVerbose(title, string.Format(CultureInfo.InvariantCulture, messageFormat, args)); } /// /// Implementation pending /// /// /// public virtual void LogWarning(string title, string message) { LoggingService.LogWarning(title, message); } /// /// Implementation pending /// /// /// /// public virtual void LogWarning(string title, string messageFormat, params object[] args) { LogWarning(title, string.Format(CultureInfo.InvariantCulture, messageFormat, args)); } /// /// Implementation pending /// /// /// public virtual void LogWarning(string title, Exception exception) { LoggingService.LogWarning(title, exception); } /// /// Implementation pending /// /// /// public virtual void LogError(string title, string message) { LoggingService.LogError(title, message); } /// /// Implementation pending /// /// /// /// public virtual void LogError(string title, string messageFormat, params object[] args) { LogError(title, string.Format(CultureInfo.InvariantCulture, messageFormat, args)); } /// /// Implementation pending /// /// /// public virtual void LogError(string title, Exception exception) { LoggingService.LogError(title, exception); } /// /// Implementation pending /// /// /// public virtual void LogCritical(string title, string message) { LoggingService.LogCritical(title, message); } /// /// Implementation pending /// /// /// /// public virtual void LogCritical(string title, string messageFormat, params object[] args) { LoggingService.LogCritical(title, string.Format(CultureInfo.InvariantCulture, messageFormat, args)); } /// /// Implementation pending /// /// /// public virtual void LogCritical(string title, Exception exception) { LoggingService.LogCritical(title, exception); } } /// /// IServiceCollection extensions /// public static class ServiceCollectionExtensions { /// /// Registers logging service /// /// Collection onto register service public static void AddLogging(this IServiceCollection serviceCollection) { serviceCollection.AddSingleton(typeof(ILog), typeof(LogImplementation)); } } } ================================================ FILE: Composite/Core/Implementation/PackageLicenseHelperImplementation.cs ================================================ using System; using System.Security.Cryptography; using Composite.Core.PackageSystem; namespace Composite.Core.Implementation { /// /// This is the default implementation of PackageLicenseHelper /// public class PackageLicenseHelperImplementation { /// /// /// /// /// public virtual PackageLicenseDefinition GetLicenseDefinition(Guid productId) { return LicenseDefinitionManager.GetLicenseDefinition(productId); } /// /// /// /// public virtual void StoreLicenseDefinition(PackageLicenseDefinition licenseDefinition) { LicenseDefinitionManager.StoreLicenseDefinition(licenseDefinition); } /// /// /// /// public virtual void RemoveLicenseDefinition(Guid productId) { LicenseDefinitionManager.RemoveLicenseDefintion(productId); } /// /// /// /// /// public virtual object CreateSignatureHashAlgorithm(string publicKeyXml) { return LicenseDefinitionUtils.CreateSignatureHashAlgorithm(publicKeyXml); } /// /// /// /// /// public virtual byte[] GetLicenseKeyBytes(string licenseKey) { return LicenseDefinitionUtils.GetLicenseKeyBytes(licenseKey); } /// /// /// /// /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "string", Justification = "We want to call it signatureString")] public virtual byte[] CreateSignatureBytes(string signatureString) { return LicenseDefinitionUtils.CreateSignatureBytes(signatureString); } } } ================================================ FILE: Composite/Core/Implementation/PackageUtilsImplementation.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Plugins.Elements.ElementProviders.PackageElementProvider; using Composite.Core.PackageSystem; namespace Composite.Core.Implementation { /// /// This is the default implementaion for PackageUtils /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Utils")] public class PackageUtilsImplementation { /// /// /// /// /// public virtual PackageElementProviderInstalledPackageItemEntityToken GetInstalledPackageEntityToken(Guid packageId, string groupName) { PackageElementProviderAvailablePackagesItemEntityToken castedEntityToken = new PackageElementProviderAvailablePackagesItemEntityToken(packageId.ToString(), groupName); InstalledPackageInformation installedPackage = PackageManager.GetInstalledPackages().FirstOrDefault(f => f.Id == castedEntityToken.PackageId); PackageElementProviderInstalledPackageItemEntityToken installedPackageEntityToken = new PackageElementProviderInstalledPackageItemEntityToken( installedPackage.Id, installedPackage.GroupName, installedPackage.IsLocalInstalled, installedPackage.CanBeUninstalled); return installedPackageEntityToken; } } } ================================================ FILE: Composite/Core/Implementation/PageDataConnectionImplementation.cs ================================================ using System; using System.Globalization; using System.Linq; using Composite.Data; namespace Composite.Core.Implementation { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class PageDataConnectionImplementation : DataConnectionBase, IDisposable { /// public PageDataConnectionImplementation() { InitializeScope(); } /// public PageDataConnectionImplementation(PublicationScope scope, CultureInfo locale) { InitializeScope(scope, locale); } /* public TData GetPageMetaData(string fieldName) where TData : IPageMetaData { throw new NotImplementedException(); } public TData GetPageMetaData(string fieldName, Guid pageId) where TData : IPageMetaData { throw new NotImplementedException(); } public IQueryable GetPageMetaData(string fieldName, SitemapScope scope) where TData : IPageMetaData { throw new NotImplementedException(); } public IQueryable GetPageMetaData(string fieldName, SitemapScope scope, Guid pageId) where TData : IPageMetaData { throw new NotImplementedException(); } public IQueryable GetPageData() where TData : IPageData { throw new NotImplementedException(); } public IQueryable GetPageData(SitemapScope scope) where TData : IPageData { throw new NotImplementedException(); } public IQueryable GetPageData(SitemapScope scope, Guid sourcePageId) where TData : IPageData { throw new NotImplementedException(); }*/ /// public void Dispose() { Dispose(true); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~PageDataConnectionImplementation() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); Dispose(false); } #endif /// protected virtual void Dispose(bool disposing) { if (disposing) { // Dispose stuff } } } } ================================================ FILE: Composite/Core/Implementation/SitemapNavigatorImplementation.cs ================================================ using System; using System.Collections.ObjectModel; using System.Linq; using System.Xml.Linq; using System.Collections.Generic; using Composite.Data; using Composite.Data.Types; using Composite.Core.Extensions; using Composite.Core.WebClient.Renderings.Page; namespace Composite.Core.Implementation { /// /// Documentation pending /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Sitemap", Justification = "We have decided to use Sitemap, not SiteMap")] public class SitemapNavigatorImplementation { private readonly Lazy> _sitemap; private readonly DataConnection _connection; /// /// Stateless constructor. This is used when implementations of static methods needs to be called /// Used when CurrentPageId and CurrentHomePageId are called /// public SitemapNavigatorImplementation() { } /// /// Documentation pending /// /// public SitemapNavigatorImplementation(DataConnection connection) { _sitemap = new Lazy>(() => { using (new DataScope(connection.CurrentPublicationScope, connection.CurrentLocale)) { return PageStructureInfo.GetSiteMap().ToList(); } }); _connection = connection; } /// /// Documentation pending /// /// /// public virtual PageNode GetPageNodeById(Guid id) { var page = PageManager.GetPageById(id); if (page == null) { return null; } return new PageNode(page, this); } /// /// Documentation pending /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "HomePage")] public virtual IEnumerable HomePageNodes { get { return HomePageIds.Select(GetPageNodeById).Where(p => p != null); } } /// /// Documentation pending /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "HomePage")] public virtual IEnumerable HomePageIds { get { return PageManager.GetChildrenIDs(Guid.Empty); } } /// /// Documentation pending /// public virtual PageNode CurrentPageNode { get { Verify.IsNotNull(_sitemap, "Missing sitemap. This class may have invalid state due to wrong construction."); return this.GetPageNodeById(PageRenderer.CurrentPageId); } } /// /// Documentation pending /// /// /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Hostname")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "hostname")] public virtual PageNode GetPageNodeByHostname(string hostname) { Guid pageId = Guid.Empty; hostname = hostname.ToUpperInvariant(); // Getting the longest not-empty hostname that matches the right part of the current hostname List hostNameMatches = (from binding in _connection.Get() as IEnumerable where !binding.Hostname.IsNullOrEmpty() && hostname.EndsWith(binding.Hostname.ToUpperInvariant(), StringComparison.Ordinal) orderby binding.Hostname.Length descending select binding).Take(1).ToList(); if (hostNameMatches.Count > 0) { pageId = hostNameMatches[0].HomePageId; } if (pageId == Guid.Empty) { pageId = HomePageIds.FirstOrDefault(); } return GetPageNodeById(pageId); } /// /// Documentation pending /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "HomePage")] public virtual PageNode CurrentHomePageNode { get { var homePageId = CurrentHomePageId; if (homePageId == Guid.Empty) { return null; } return GetPageNodeById(homePageId); } } /// /// Documentation pending /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Sitemaps")] public virtual ReadOnlyCollection AllSitemapsXml { get { return _sitemap.Value.AsReadOnly(); } } /// /// Documentation pending /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Sitemap")] public virtual XElement SitemapXml { get { Verify.IsNotNull(_sitemap, "Missing sitemap. This class may have invalid state due to wrong construction."); Verify.That(this.CurrentPageId != Guid.Empty, "No current page Id could be located"); XElement pageElement = this.GetElementByPageId(this.CurrentPageId); while (pageElement.Parent!=null) { pageElement = pageElement.Parent; } return pageElement; } } /// /// Documentation pending /// public virtual Guid CurrentPageId { get { return PageRenderer.CurrentPageId; } } /// /// Documentation pending /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "HomePage")] public virtual Guid CurrentHomePageId { get { Guid pageId = this.CurrentPageId; while (true) { Guid parentId = PageManager.GetParentId(pageId); if (parentId == Guid.Empty) { return pageId; } pageId = parentId; } } } internal XElement GetElementByPageId(Guid id) { string idString = id.ToString(); XAttribute matchAttribute = _sitemap.Value.DescendantsAndSelf(PageStructureInfo.ElementNames.Page) .Attributes(PageStructureInfo.AttributeNames.Id) .FirstOrDefault(f => f.Value == idString); return matchAttribute != null ? matchAttribute.Parent : null ; } } } ================================================ FILE: Composite/Core/Implementation/StatelessDataConnectionImplementation.cs ================================================ using System.Collections.Generic; using System.Globalization; using Composite.Data; namespace Composite.Core.Implementation { /// /// Base class for the implementation of the static methods on the class. /// public class StatelessDataConnectionImplementation { /// /// Creates a new data object of the given type. /// /// The data type. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "New", Justification = "This is what we want")] public virtual TData New() where TData : class, IData { return DataFacade.BuildNew(); } /// /// All locales added to C1. /// public virtual IEnumerable AllLocales => DataLocalizationFacade.ActiveLocalizationCultures; } } ================================================ FILE: Composite/Core/Instrumentation/DisposableResourceTracer.cs ================================================ using Composite.C1Console.Events; using Composite.Core.IO; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace Composite.Core.Instrumentation { #if LeakCheck /// /// This class only provide functionality if the conditional compilation symbol #LeakCheck is defined. /// See the method for how to feed this class data. /// When appPool shuts down a xml file with stack traces and count will be written to the root. This file indicate areas where (tooled) IDisposable classes were not /// disposed as expected. /// public static class DisposableResourceTracer { private static Dictionary stacks = new Dictionary(); private static object _lock = new object(); private static object _dumpLock = new object(); private static bool dumpAlways = false; private const string _redundant = @" at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo) at System.Environment.get_StackTrace() "; /// public static readonly DateTime TraceStart = DateTime.Now; static DisposableResourceTracer() { GlobalEventSystemFacade.SubscribeToShutDownEvent(OnShutDownEvent); } private static void OnShutDownEvent(ShutDownEventArgs args) { dumpAlways = true; DumpStacks(); } /// Register a stack trace - expected usage if for this to be called from IDisposable finalizers, indicating they did not dispose as expected from user code. /// /// #if LeakCheck /// private string stack = Environment.StackTrace; /// ~MyDisposableClass() /// { /// Composite.Core.Instrumentation.DisposableResourceTracer.Register(stack); /// } /// #endif /// /// You should ensure finalizer is not called, when Dispose() execute as expected. Put the following inside your Dispose() method: /// /// #if LeakCheck /// GC.SuppressFinalize(this); /// #endif /// public static void RegisterFinalizerExecution(string stack) { lock (_lock) { string topStack = GetMinimalStackTop(stack); int count = 0; if (stacks.TryGetValue(topStack, out count)) { stacks[topStack] = count + 1; } else { stacks.Add(topStack, 1); } } if (dumpAlways) DumpStacks(); } private static void DumpStacks() { string rootDir = PathUtil.Resolve("~/"); string fileName = String.Format("DisposableResourceTrace_{0}.xml", TraceStart.ToString("yyyy_MM_dd_HH_mm_ss")); string fullPath = Path.Combine(rootDir, fileName); var stacks = GetStacks(); var ordered = stacks.OrderByDescending(f => f.Value); XElement dumpDoc = new XElement("DisposableResourceTrace" , new XAttribute("start", TraceStart) , new XAttribute("end", DateTime.Now) , new XAttribute("seconds", (DateTime.Now - TraceStart).TotalSeconds) ); dumpDoc.Add( ordered.Select(f => new XElement("Trace", new XAttribute("count", f.Value), f.Key)) ); lock (_dumpLock) { dumpDoc.Save(fullPath); } } private static string GetMinimalStackTop(string stack) { string[] stackLines = stack.Replace(_redundant,"").Split(new string[] { Environment.NewLine }, StringSplitOptions.None); bool foundCaller = false; int lineNum = 1; StringBuilder sb = new StringBuilder(stackLines[0]+"\n"); while(!foundCaller && lineNum < stackLines.Length) { string line = stackLines[lineNum]; sb.AppendLine(line); foundCaller = line.TrimStart().StartsWith("at Composite.") && !line.Contains("..ctor") && !line.Contains(".get_") && !line.Contains(".Threading."); lineNum++; } return sb.ToString(); } /// /// Returns the currently registered stacks - since stacks are typically only registered when GC Generation 2 heap is cleaned - and this happens rarely - the result here is not guaranteed to be complete... /// /// public static Dictionary GetStacks() { lock (_lock) { return new Dictionary(stacks); } } } #endif } ================================================ FILE: Composite/Core/Instrumentation/Foundation/IPerformanceCounterProviderRegistry.cs ================================================  namespace Composite.Core.Instrumentation.Foundation { internal interface IPerformanceCounterProviderRegistry { string DefaultPerformanceCounterProviderName { get; } void Flush(); } } ================================================ FILE: Composite/Core/Instrumentation/Foundation/NoopTimerProfiler.cs ================================================ namespace Composite.Core.Instrumentation.Foundation { internal sealed class NoopTimerProfiler : TimerProfiler { public static NoopTimerProfiler Instance { get; } = new NoopTimerProfiler(); public override void Dispose() { } } } ================================================ FILE: Composite/Core/Instrumentation/Foundation/PerformanceCounterProviderRegistry.cs ================================================ using Composite.C1Console.Events; namespace Composite.Core.Instrumentation.Foundation { internal static class PerformanceCounterProviderRegistry { private static IPerformanceCounterProviderRegistry _implementation = new PerformanceCounterProviderRegistryImpl(); internal static IPerformanceCounterProviderRegistry Implementation { get { return _implementation; } set { _implementation = value; } } static PerformanceCounterProviderRegistry() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static string DefaultPerformanceCounterProviderName { get { return _implementation.DefaultPerformanceCounterProviderName; } } private static void Flush() { _implementation.Flush(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } } } ================================================ FILE: Composite/Core/Instrumentation/Foundation/PerformanceCounterProviderRegistryImpl.cs ================================================ using Composite.Core.Configuration; using Composite.Core.Instrumentation.Plugin.Runtime; namespace Composite.Core.Instrumentation.Foundation { internal sealed class PerformanceCounterProviderRegistryImpl : IPerformanceCounterProviderRegistry { private string _defaultPerformanceCounterProviderName = null; public string DefaultPerformanceCounterProviderName { get { if (_defaultPerformanceCounterProviderName == null) { PerformanceCounterProviderSettings parallelizationProviderSettings = ConfigurationServices.ConfigurationSource.GetSection(PerformanceCounterProviderSettings.SectionName) as PerformanceCounterProviderSettings; _defaultPerformanceCounterProviderName = parallelizationProviderSettings.DefaultPerformanceCounterProviderName; } return _defaultPerformanceCounterProviderName; } } public void Flush() { _defaultPerformanceCounterProviderName = null; } } } ================================================ FILE: Composite/Core/Instrumentation/Foundation/PluginFacades/PerformanceCounterProviderPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.C1Console.Events; using Composite.Core.Instrumentation.Plugin; using Composite.Core.Instrumentation.Plugin.Runtime; namespace Composite.Core.Instrumentation.Foundation.PluginFacades { internal static class PerformanceCounterProviderPluginFacade { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); static PerformanceCounterProviderPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static void SystemStartupIncrement(string providerName) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); using (_resourceLocker.Locker) { IPerformanceCounterProvider provider = GetPerformanceCounterProvider(providerName); provider.SystemStartupIncrement(); } } public static IPerformanceCounterToken BeginElementCreation(string providerName) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); using (_resourceLocker.Locker) { IPerformanceCounterProvider provider = GetPerformanceCounterProvider(providerName); return provider.BeginElementCreation(); } } public static void EndElementCreation(string providerName, IPerformanceCounterToken performanceToken, int resultElementCount, int totalElementCount) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); using (_resourceLocker.Locker) { IPerformanceCounterProvider provider = GetPerformanceCounterProvider(providerName); provider.EndElementCreation(performanceToken, resultElementCount, totalElementCount); } } public static IPerformanceCounterToken BeginAspNetControlCompile(string providerName) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); using (_resourceLocker.Locker) { IPerformanceCounterProvider provider = GetPerformanceCounterProvider(providerName); return provider.BeginAspNetControlCompile(); } } public static void EndAspNetControlCompile(string providerName, IPerformanceCounterToken performanceToken, int controlsCompiledCount) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); using (_resourceLocker.Locker) { IPerformanceCounterProvider provider = GetPerformanceCounterProvider(providerName); provider.EndAspNetControlCompile(performanceToken, controlsCompiledCount); } } public static IPerformanceCounterToken BeginPageHookCreation(string providerName) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); using (_resourceLocker.Locker) { IPerformanceCounterProvider provider = GetPerformanceCounterProvider(providerName); return provider.BeginPageHookCreation(); } } public static void EndPageHookCreation(string providerName, IPerformanceCounterToken performanceToken, int controlsCompiledCount) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); using (_resourceLocker.Locker) { IPerformanceCounterProvider provider = GetPerformanceCounterProvider(providerName); provider.EndPageHookCreation(performanceToken, controlsCompiledCount); } } public static void EntityTokenParentCacheHitIncrement(string providerName) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); using (_resourceLocker.Locker) { IPerformanceCounterProvider provider = GetPerformanceCounterProvider(providerName); provider.EntityTokenParentCacheHitIncrement(); } } public static void EntityTokenParentCacheMissIncrement(string providerName) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); using (_resourceLocker.Locker) { IPerformanceCounterProvider provider = GetPerformanceCounterProvider(providerName); provider.EntityTokenParentCacheMissIncrement(); } } private static IPerformanceCounterProvider GetPerformanceCounterProvider(string providerName) { IPerformanceCounterProvider provider; if (_resourceLocker.Resources.ProviderCache.TryGetValue(providerName, out provider) == false) { try { provider = _resourceLocker.Resources.Factory.Create(providerName); using (_resourceLocker.Locker) { if (_resourceLocker.Resources.ProviderCache.ContainsKey(providerName) == false) { _resourceLocker.Resources.ProviderCache.Add(providerName, provider); } } } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } return provider; } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", PerformanceCounterProviderSettings.SectionName), ex); } private sealed class Resources { public PerformanceCounterProviderFactory Factory { get; set; } public Dictionary ProviderCache { get; set; } public static void Initialize(Resources resources) { try { resources.Factory = new PerformanceCounterProviderFactory(); } catch (NullReferenceException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } resources.ProviderCache = new Dictionary(); } } } } ================================================ FILE: Composite/Core/Instrumentation/IPerformanceCounterFacade.cs ================================================ using Composite.Core.Instrumentation.Plugin; namespace Composite.Core.Instrumentation { internal interface IPerformanceCounterFacade { void SystemStartupIncrement(); IPerformanceCounterToken BeginElementCreation(); void EndElementCreation(IPerformanceCounterToken performanceToken, int resultElementCount, int totalElementCount); IPerformanceCounterToken BeginAspNetControlCompile(); void EndAspNetControlCompile(IPerformanceCounterToken performanceToken, int controlsCompiledCount); IPerformanceCounterToken BeginPageHookCreation(); void EndPageHookCreation(IPerformanceCounterToken performanceToken, int controlsCompiledCount); void EntityTokenParentCacheHitIncrement(); void EntityTokenParentCacheMissIncrement(); void Flush(); } } ================================================ FILE: Composite/Core/Instrumentation/IPerformanceCounterToken.cs ================================================ using System; namespace Composite.Core.Instrumentation { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IPerformanceCounterToken : IDisposable { } } ================================================ FILE: Composite/Core/Instrumentation/LogExecutionTime.cs ================================================ using System; using Composite.Core.Extensions; namespace Composite.Core.Instrumentation { /// /// Logs execution time of the nested code /// internal class LogExecutionTime : IDisposable { private readonly string _message; private readonly int _startTime; private readonly string _logTitle; public LogExecutionTime(string logTitle, string message) { _logTitle = logTitle; _message = message; _startTime = Environment.TickCount; Log.LogVerbose(_logTitle, "Starting: " + _message); } public void Dispose() { int executionTime = Environment.TickCount - _startTime; Log.LogVerbose(_logTitle, "Finished: " + _message + " ({0} ms)".FormatWith(executionTime)); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~LogExecutionTime() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } ================================================ FILE: Composite/Core/Instrumentation/Measurement.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security; namespace Composite.Core.Instrumentation { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Measurement { private List _nodes; private List _parallelNodes; /// public Measurement(string name) { Name = name; } /// /// Total execution time in microseconds (10^-6) /// public long TotalTime; /// public long MemoryUsage; /// public string Name { get; set; } /// public Func EntityTokenFactory { get; set; } /// public List Nodes { get { if(_nodes == null) { _nodes = new List(); } return _nodes; } } /// public object SyncRoot { get { return this; } } /// public List ParallelNodes { get { if (_parallelNodes == null) { _parallelNodes = new List(); } return _parallelNodes; } } } } ================================================ FILE: Composite/Core/Instrumentation/PerformanceCounterFacade.cs ================================================ using Composite.C1Console.Events; namespace Composite.Core.Instrumentation { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PerformanceCounterFacade { private static IPerformanceCounterFacade _implementation = new PerformanceCounterFacadeImpl(); internal static IPerformanceCounterFacade Implementation { get { return _implementation; } set { _implementation = value; } } static PerformanceCounterFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } /// public static void SystemStartupIncrement() { _implementation.SystemStartupIncrement(); } /// public static IPerformanceCounterToken BeginElementCreation() { return _implementation.BeginElementCreation(); } /// /// /// /// The token returned by BeginElementCreation /// Element count after security filtering /// Element count before security filtering public static void EndElementCreation(IPerformanceCounterToken performanceToken, int resultElementCount, int totalElementCount) { _implementation.EndElementCreation(performanceToken, resultElementCount, totalElementCount); } /// public static IPerformanceCounterToken BeginAspNetControlCompile() { return _implementation.BeginAspNetControlCompile(); } /// public static void EndAspNetControlCompile(IPerformanceCounterToken performanceToken, int controlsCompiledCount) { _implementation.EndAspNetControlCompile(performanceToken, controlsCompiledCount); } /// public static IPerformanceCounterToken BeginPageHookCreation() { return _implementation.BeginPageHookCreation(); } /// public static void EndPageHookCreation(IPerformanceCounterToken performanceToken, int controlsCompiledCount) { _implementation.EndPageHookCreation(performanceToken, controlsCompiledCount); } /// public static void EntityTokenParentCacheHitIncrement() { _implementation.EntityTokenParentCacheHitIncrement(); } /// public static void EntityTokenParentCacheMissIncrement() { _implementation.EntityTokenParentCacheMissIncrement(); } private static void OnFlushEvent(FlushEventArgs args) { _implementation.Flush(); } } } ================================================ FILE: Composite/Core/Instrumentation/PerformanceCounterFacadeImpl.cs ================================================ using Composite.Core.Instrumentation.Foundation; using Composite.Core.Instrumentation.Foundation.PluginFacades; namespace Composite.Core.Instrumentation { internal sealed class PerformanceCounterFacadeImpl : IPerformanceCounterFacade { public void SystemStartupIncrement() { string providerName = PerformanceCounterProviderRegistry.DefaultPerformanceCounterProviderName; PerformanceCounterProviderPluginFacade.SystemStartupIncrement(providerName); } public IPerformanceCounterToken BeginElementCreation() { string providerName = PerformanceCounterProviderRegistry.DefaultPerformanceCounterProviderName; return PerformanceCounterProviderPluginFacade.BeginElementCreation(providerName); } public void EndElementCreation(IPerformanceCounterToken performanceToken, int resultElementCount, int totalElementCount) { string providerName = PerformanceCounterProviderRegistry.DefaultPerformanceCounterProviderName; PerformanceCounterProviderPluginFacade.EndElementCreation(providerName, performanceToken, resultElementCount, totalElementCount); } public IPerformanceCounterToken BeginAspNetControlCompile() { string providerName = PerformanceCounterProviderRegistry.DefaultPerformanceCounterProviderName; return PerformanceCounterProviderPluginFacade.BeginAspNetControlCompile(providerName); } public void EndAspNetControlCompile(IPerformanceCounterToken performanceToken, int controlsCompiledCount) { string providerName = PerformanceCounterProviderRegistry.DefaultPerformanceCounterProviderName; PerformanceCounterProviderPluginFacade.EndAspNetControlCompile(providerName, performanceToken, controlsCompiledCount); } public IPerformanceCounterToken BeginPageHookCreation() { string providerName = PerformanceCounterProviderRegistry.DefaultPerformanceCounterProviderName; return PerformanceCounterProviderPluginFacade.BeginPageHookCreation(providerName); } public void EndPageHookCreation(IPerformanceCounterToken performanceToken, int controlsCompiledCount) { string providerName = PerformanceCounterProviderRegistry.DefaultPerformanceCounterProviderName; PerformanceCounterProviderPluginFacade.EndPageHookCreation(providerName, performanceToken, controlsCompiledCount); } public void EntityTokenParentCacheHitIncrement() { string providerName = PerformanceCounterProviderRegistry.DefaultPerformanceCounterProviderName; PerformanceCounterProviderPluginFacade.EntityTokenParentCacheHitIncrement(providerName); } public void EntityTokenParentCacheMissIncrement() { string providerName = PerformanceCounterProviderRegistry.DefaultPerformanceCounterProviderName; PerformanceCounterProviderPluginFacade.EntityTokenParentCacheMissIncrement(providerName); } public void Flush() { } } } ================================================ FILE: Composite/Core/Instrumentation/Plugin/IPerformanceCounterProvider.cs ================================================ using Composite.Core.Instrumentation.Plugin.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Instrumentation.Plugin { [CustomFactory(typeof(PerformanceCounterProviderCustomFactory))] [ConfigurationNameMapper(typeof(PerformanceCounterProviderDefaultNameRetriever))] internal interface IPerformanceCounterProvider { void SystemStartupIncrement(); IPerformanceCounterToken BeginElementCreation(); void EndElementCreation(IPerformanceCounterToken performanceToken, int resultElementCount, int totalElementCount); IPerformanceCounterToken BeginAspNetControlCompile(); void EndAspNetControlCompile(IPerformanceCounterToken performanceToken, int controlsCompiledCount); IPerformanceCounterToken BeginPageHookCreation(); void EndPageHookCreation(IPerformanceCounterToken performanceToken, int pageCount); void EntityTokenParentCacheHitIncrement(); void EntityTokenParentCacheMissIncrement(); } } ================================================ FILE: Composite/Core/Instrumentation/Plugin/NonConfigurablePerformanceCounterProvider.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Core.Instrumentation.Plugin { [Assembler(typeof(NonConfigurablePerformanceCounterProviderAssembler))] internal class NonConfigurablePerformanceCounterProvider : PerformanceCounterProviderData { } internal sealed class NonConfigurablePerformanceCounterProviderAssembler : IAssembler { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IPerformanceCounterProvider Assemble(IBuilderContext context, PerformanceCounterProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IPerformanceCounterProvider)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/Core/Instrumentation/Plugin/PerformanceCounterProviderData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Instrumentation.Plugin { [ConfigurationElementType(typeof(NonConfigurablePerformanceCounterProvider))] internal class PerformanceCounterProviderData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/Core/Instrumentation/Plugin/Runtime/PerformanceCounterProviderCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Instrumentation.Plugin.Runtime { internal sealed class PerformanceCounterProviderCustomFactory : AssemblerBasedCustomFactory { protected override PerformanceCounterProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { PerformanceCounterProviderSettings settings = configurationSource.GetSection(PerformanceCounterProviderSettings.SectionName) as PerformanceCounterProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", PerformanceCounterProviderSettings.SectionName)); } return settings.PerformanceCounterProviderPlugins.Get(name); } } } ================================================ FILE: Composite/Core/Instrumentation/Plugin/Runtime/PerformanceCounterProviderDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Instrumentation.Plugin.Runtime { internal sealed class PerformanceCounterProviderDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/Core/Instrumentation/Plugin/Runtime/PerformanceCounterProviderFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Instrumentation.Plugin.Runtime { internal sealed class PerformanceCounterProviderFactory : NameTypeFactoryBase { public PerformanceCounterProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/Core/Instrumentation/Plugin/Runtime/PerformanceCounterProviderSettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Instrumentation.Plugin.Runtime { internal sealed class PerformanceCounterProviderSettings : SerializableConfigurationSection { public const string SectionName = "Composite.Core.Instrumentation.Plugin.Runtime.PerformanceCounterProviderConfiguration"; private const string _defaultPerformanceCounterProviderNameProperty = "defaultPerformanceCounterProviderName"; [ConfigurationProperty(_defaultPerformanceCounterProviderNameProperty, IsRequired = true)] public string DefaultPerformanceCounterProviderName { get { return (string)base[_defaultPerformanceCounterProviderNameProperty]; } set { base[_defaultPerformanceCounterProviderNameProperty] = value; } } private const string _performanceCounterProviderPluginsProperty = "PerformanceCounterProviderPlugins"; [ConfigurationProperty(_performanceCounterProviderPluginsProperty)] public NameTypeManagerTypeConfigurationElementCollection PerformanceCounterProviderPlugins { get { return (NameTypeManagerTypeConfigurationElementCollection)base[_performanceCounterProviderPluginsProperty]; } } } } ================================================ FILE: Composite/Core/Instrumentation/Profiler.cs ================================================ #define ProfileMemory using System; using System.Collections.Generic; using System.Diagnostics; using Composite.C1Console.Security; using Composite.Core.Threading; namespace Composite.Core.Instrumentation { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Profiler { private static readonly string ProfilerKey = typeof (Profiler).FullName; // private static readonly IEnumerable EmptyReport = new Measurement[0]; /// public static void BeginProfiling() { if (Disabled) return; ThreadDataManagerData threadData = ThreadDataManager.Current; Verify.That(!threadData.HasValue(ProfilerKey), "Profiler has already been initialized"); var stack = new Stack(); stack.Push(new Measurement("Root") { MemoryUsage = GC.GetTotalMemory(true) }); threadData.SetValue(ProfilerKey, stack); } /// public static Measurement EndProfiling() { var threadData = ThreadDataManager.GetCurrentNotNull(); var stack = threadData[ProfilerKey] as Stack; Verify.That(stack.Count == 1, "Performance node stack should have exactly one (the root) node"); threadData.SetValue(ProfilerKey, null); var measurement = stack.Pop(); measurement.MemoryUsage = GC.GetTotalMemory(false) - measurement.MemoryUsage; return measurement; } /// public static IDisposable Measure(string name) { return Measure(name, null); } /// public static IDisposable Measure(string name, Func entityTokenFactory) { if (Disabled) return EmptyDisposable.Instance; Measurement currentNode; Stack stack; bool isInParallel; if (!GetCurrentNode(out currentNode, out stack, out isInParallel)) { return EmptyDisposable.Instance; } Stack newNodeStack; if (isInParallel) { ThreadDataManagerData currentThreadData = ThreadDataManager.Current; if (currentThreadData.HasValue(currentThreadData)) { newNodeStack = currentThreadData[ProfilerKey] as Stack; } else { newNodeStack = new Stack(); currentThreadData.SetValue(ProfilerKey, newNodeStack); } } else { newNodeStack = stack; } return new InfoCollector(currentNode, name, isInParallel, newNodeStack, entityTokenFactory); } private static bool GetCurrentNode( out Measurement parentNode, out Stack stack, out bool isInParallel) { if (Disabled) { parentNode = null; stack = null; isInParallel = false; return false; } ThreadDataManagerData currentThreadData = ThreadDataManager.Current; ThreadDataManagerData threadData = currentThreadData; isInParallel = false; while (threadData != null) { if (threadData.HasValue(ProfilerKey)) { stack = threadData[ProfilerKey] as Stack; if (stack.Count > 0) { parentNode = stack.Peek(); return true; } } // Going to parent thread threadData = threadData.Parent; isInParallel = true; } stack = null; parentNode = null; return false; } private class InfoCollector : IDisposable { private readonly Measurement _node; private readonly Stopwatch _stopwatch; private readonly Stack _stack; public InfoCollector(Measurement parentNode, string name, bool isInParallel, Stack stack, Func entityTokenFactory) { _stack = stack; _node = new Measurement(name) { EntityTokenFactory = entityTokenFactory, #if ProfileMemory MemoryUsage = GC.GetTotalMemory(false) #endif }; if (isInParallel) { lock (parentNode.SyncRoot) { parentNode.ParallelNodes.Add(_node); } } else { parentNode.Nodes.Add(_node); } stack.Push(_node); _stopwatch = Stopwatch.StartNew(); } public void Dispose() { _stopwatch.Stop(); _node.TotalTime = (_stopwatch.ElapsedTicks*1000000) / Stopwatch.Frequency; #if ProfileMemory _node.MemoryUsage = GC.GetTotalMemory(false) - _node.MemoryUsage; #endif _stack.Pop(); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~InfoCollector() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } internal static void AddSubMeasurement(Measurement measurement) { Verify.ArgumentNotNull(measurement, "measurement"); Measurement currentNode; Stack stack; bool isInParallel; if (!GetCurrentNode(out currentNode, out stack, out isInParallel)) { return; } if (isInParallel) { lock (currentNode.SyncRoot) { currentNode.ParallelNodes.Add(measurement); } } else { currentNode.Nodes.Add(measurement); } } private static bool Disabled => false; } } ================================================ FILE: Composite/Core/Instrumentation/ProfilerReport.cs ================================================ using System; using System.Linq; using System.Xml.Linq; using Composite.C1Console.Security; using Composite.Core.WebClient; namespace Composite.Core.Instrumentation { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ProfilerReport { private static readonly string ProfilerXslPath = UrlUtils.AdminRootPath + "/Transformations/page_profiler.xslt"; /// public static string BuildReport(Measurement measurement, string url) { string xmlHeader = $@" "; XElement reportXml = ProfilerReport.BuildReportXml(measurement); reportXml.Add(new XAttribute("url", url), new XAttribute("consoleUrl", UrlUtils.AdminRootPath)); return xmlHeader + reportXml; } /// public static XElement BuildReportXml(Measurement measurement) { int index = 0; var result = new XElement("Measurements", new XAttribute("MemoryUsageKb", measurement.MemoryUsage / 1024)); foreach (var node in measurement.Nodes) { result.Add(BuildReportXmlRec(node, node.TotalTime, node.TotalTime, false, index.ToString())); index++; } foreach (var node in measurement.ParallelNodes) { result.Add(BuildReportXmlRec(node, node.TotalTime, node.TotalTime, true, index.ToString())); index++; } return result; } private static XElement BuildReportXmlRec(Measurement measurement, /* int level,*/ long totalTime, long parentTime, bool parallel, string id) { long persentTotal = (measurement.TotalTime * 100) / totalTime; long ownTime = measurement.TotalTime - measurement.Nodes.Select(childNode => childNode.TotalTime).Sum(); var entityToken = measurement.EntityTokenFactory?.Invoke(); string serializedEntityToken = entityToken != null ? EntityTokenSerializer.Serialize(entityToken, true) : null; var result = new XElement("Measurement", new XAttribute("_id", id), new XAttribute("title", measurement.Name), new XAttribute("totalTime", measurement.TotalTime), new XAttribute("ownTime", ownTime), new XAttribute("persentFromTotal", persentTotal), new XAttribute("parallel", parallel.ToString().ToLowerInvariant())); if (serializedEntityToken != null) { result.Add(new XAttribute("entityToken", serializedEntityToken)); } if (measurement.MemoryUsage != 0) { result.Add(new XAttribute("memoryUsageKb", measurement.MemoryUsage / 1024)); } int index = 0; foreach (var childNode in measurement.Nodes) // .OrderByDescending(c => c.TotalTime) { result.Add(BuildReportXmlRec(childNode, totalTime, measurement.TotalTime, false, (id + "|" + index))); index++; } foreach (var childNode in measurement.ParallelNodes) // .OrderByDescending(c => c.TotalTime) { result.Add(BuildReportXmlRec(childNode, totalTime, measurement.TotalTime, true, (id + "|" + index))); index++; } return result; } } } ================================================ FILE: Composite/Core/Instrumentation/TimerProfiler.cs ================================================ using System; namespace Composite.Core.Instrumentation { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class TimerProfiler : IDisposable { internal TimerProfiler() { } /// public abstract void Dispose(); } } ================================================ FILE: Composite/Core/Instrumentation/TimerProfilerFacade.cs ================================================ //#define PROFILE_MODE using Composite.Core.Instrumentation.Foundation; namespace Composite.Core.Instrumentation { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class TimerProfilerFacade { /// public static TimerProfiler CreateTimerProfiler() { #if PROFILE_MODE if (RuntimeInformation.IsDebugBuild) { return new XmlTimerProfiler(); } #endif return NoopTimerProfiler.Instance; } /// public static TimerProfiler CreateTimerProfiler(string message) { #if PROFILE_MODE if (RuntimeInformation.IsDebugBuild) { return new XmlTimerProfiler(message); } #endif return NoopTimerProfiler.Instance; } } } ================================================ FILE: Composite/Core/Linq/ExpressionBuilder.cs ================================================ using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Composite.Core.Linq { internal class ExpressionBuilder { private Type _currentQueryableType; private readonly IQueryable _sourceQueryable; private Expression _currentExpression; private static readonly PropertyInfo _dateDateTimePropertyInfo = typeof(DateTime).GetProperty("Date"); public ExpressionBuilder(Type queryableType, IQueryable sourceQueryable) { _sourceQueryable = sourceQueryable; _currentExpression = _sourceQueryable.Expression; _currentQueryableType = queryableType; } public Type QueryableType { get; private set; } public ExpressionBuilder Where(PropertyInfoValueCollection propertyInfoValueCollection) { return Where(propertyInfoValueCollection, false); } public ExpressionBuilder Where(PropertyInfoValueCollection propertyInfoValueCollection, bool useInnerDateTimeDate) { ParameterExpression parameterExpression = Expression.Parameter(_currentQueryableType, "w"); Expression currentExpression = null; foreach (var kvp in propertyInfoValueCollection.PropertyValues) { Expression left = LambdaExpression.Property(parameterExpression, kvp.Key); Expression right = Expression.Constant(kvp.Value, kvp.Key.PropertyType); if (useInnerDateTimeDate && kvp.Key.PropertyType == typeof(DateTime)) { left = InnerDateTimeDateExpression(left); right = InnerDateTimeDateExpression(right); } Expression filter = Expression.Equal(left, right); if (currentExpression == null) { currentExpression = filter; } else { currentExpression = Expression.And(currentExpression, filter); } } LambdaExpression lambdaExpression = Expression.Lambda(currentExpression, parameterExpression); MethodCallExpression methodCallExpression = Expression.Call ( typeof(Queryable), "Where", new Type[] { _currentQueryableType, }, _currentExpression, Expression.Quote(lambdaExpression) ); _currentExpression = methodCallExpression; return this; } public ExpressionBuilder OrderBy(PropertyInfo orderByPropertyInfo, bool useInnerDateTimeDate, bool orderDescending) { ParameterExpression parameter = Expression.Parameter(_currentQueryableType, "o"); Expression expression = Expression.Property(parameter, orderByPropertyInfo); if ((useInnerDateTimeDate) && (orderByPropertyInfo.PropertyType == typeof(DateTime))) { expression = InnerDateTimeDateExpression(expression); } LambdaExpression lambdaExpression = Expression.Lambda(expression, parameter); MethodCallExpression methodCallExpression = Expression.Call ( typeof(Queryable), (orderDescending ? "OrderByDescending" : "OrderBy"), new Type[] { _currentQueryableType, orderByPropertyInfo.PropertyType }, _currentExpression, Expression.Quote(lambdaExpression) ); _currentExpression = methodCallExpression; return this; } public ExpressionBuilder Select(PropertyInfo selectPropertyInfo) { return Select(selectPropertyInfo, false); } public ExpressionBuilder Select(PropertyInfo selectPropertyInfo, bool useInnerDateTimeDate) { ParameterExpression parameter = Expression.Parameter(_currentQueryableType, "s"); Expression expression = Expression.Property(parameter, selectPropertyInfo); if (useInnerDateTimeDate && selectPropertyInfo.PropertyType == typeof(DateTime)) { expression = InnerDateTimeDateExpression(expression); } LambdaExpression lambdaExpression = Expression.Lambda(expression, parameter); MethodCallExpression methodCallExpression = Expression.Call ( typeof(Queryable), "Select", new Type[] { _currentQueryableType, selectPropertyInfo.PropertyType }, _currentExpression, Expression.Quote(lambdaExpression) ); _currentExpression = methodCallExpression; _currentQueryableType = selectPropertyInfo.PropertyType; return this; } public ExpressionBuilder Distinct() { MethodCallExpression methodCallExpression = Expression.Call ( typeof(Queryable), "Distinct", new Type[] { _currentQueryableType }, _currentExpression ); _currentExpression = methodCallExpression; return this; } public IQueryable CreateQuery() { return _sourceQueryable.Provider.CreateQuery(_currentExpression); } private Expression InnerDateTimeDateExpression(Expression expression) { return Expression.Property(expression, _dateDateTimePropertyInfo); } } } ================================================ FILE: Composite/Core/Linq/ExpressionCreator.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace Composite.Core.Linq { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ExpressionCreator { /// public static Expression Select(Expression source, LambdaExpression selector) { Type type = TypeHelpers.FindElementType(source); return Expression.Call( typeof(Queryable), "Select", new Type[] { type, selector.Body.Type }, source, Expression.Quote(selector) ); } /// public static Expression Where(Expression source, LambdaExpression predicate) { Type type = TypeHelpers.FindElementType(source); return Expression.Call( typeof(Queryable), "Where", new Type[] { type }, source, Expression.Quote(predicate) ); } /// public static Expression Count(Expression source, LambdaExpression predicate) { Type type = TypeHelpers.FindElementType(source); return Expression.Call( typeof(Queryable), "Count", new Type[] { type }, source, Expression.Quote(predicate) ); } /// public static Expression Distinct(Expression source) { Type type = TypeHelpers.FindElementType(source); return Expression.Call( typeof(Queryable), "Distinct", new Type[] { type }, source ); } /// public static Expression OrderBy(Expression source, LambdaExpression keySelector) { Type type = TypeHelpers.FindElementType(source); return Expression.Call( typeof(Queryable), "OrderBy", new Type[] { type, keySelector.Body.Type }, source, keySelector ); } /// public static Expression OrderByDescending(Expression source, LambdaExpression keySelector) { Type type = TypeHelpers.FindElementType(source); return Expression.Call( typeof(Queryable), "OrderByDescending", new Type[] { type, keySelector.Body.Type }, source, keySelector ); } /// public static Expression ThenBy(Expression source, LambdaExpression keySelector) { Type type = TypeHelpers.FindElementType(source); return Expression.Call( typeof(Queryable), "ThenBy", new Type[] { type, keySelector.Body.Type }, source, keySelector ); } /// public static Expression ThenByDescending(Expression source, LambdaExpression keySelector) { Type type = TypeHelpers.FindElementType(source); return Expression.Call( typeof(Queryable), "ThenByDescending", new Type[] { type, keySelector.Body.Type }, source, keySelector ); } /// public static Expression Join(Expression outerSource, Expression innerSource, LambdaExpression outerKeySelector, LambdaExpression innerKeySelector, LambdaExpression resultSelector) { Type outerType = TypeHelpers.FindElementType(outerSource); Type innerType = TypeHelpers.FindElementType(innerSource); Type keyType = outerKeySelector.Body.Type; Type resultType = resultSelector.ReturnType; // public static IEnumerable Join( // IEnumerable outer, // IEnumerable inner, // Func outerKeySelector, // Func innerKeySelector, // Func resultSelector); Type outerFullType = typeof(IEnumerable<>).MakeGenericType(outerType); Type innerFullType = typeof(IEnumerable<>).MakeGenericType(innerType); Type outerKeySelectorFullType = typeof(Func<,>).MakeGenericType(outerType, keyType); Type innerKeySelectorFullType = typeof(Func<,>).MakeGenericType(innerType, keyType); Type resultSelectorFullType = typeof(Func<,,>).MakeGenericType(outerType, innerType, resultType); #if DEBUG var b1 = outerFullType.IsAssignableFrom(outerSource.Type); var b2 = innerFullType.IsAssignableFrom(innerSource.Type); var b3 = outerKeySelector.Type == outerKeySelectorFullType; var b4 = innerKeySelector.Type == innerKeySelectorFullType; var b5 = resultSelector.Type == resultSelectorFullType; #endif return Expression.Call( typeof(Queryable), "Join", new Type[] { outerType, innerType, keyType, resultType }, outerSource, innerSource, Expression.Quote(outerKeySelector), Expression.Quote(innerKeySelector), Expression.Quote(resultSelector) ); } } } ================================================ FILE: Composite/Core/Linq/ExpressionExtensionMethods.cs ================================================ using System; using System.Linq.Expressions; using Composite.Core.Linq.ExpressionVisitors; using Composite.Core.Logging; namespace Composite.Core.Linq { internal static class ExpressionExtensionMethods { public static Expression NestedAnd(this Expression leftExpression, Expression rightExpression) { if ((leftExpression == null) && (rightExpression == null)) throw new ArgumentNullException("rightExpression"); if (leftExpression == null) return rightExpression; if (rightExpression == null) return leftExpression; return Expression.And(leftExpression, rightExpression); } public static Expression NestedOr(this Expression leftExpression, Expression rightExpression) { if ((leftExpression == null) && (rightExpression == null)) throw new ArgumentNullException("rightExpression"); if (leftExpression == null) return rightExpression; if (rightExpression == null) return leftExpression; return Expression.Or(leftExpression, rightExpression); } public static void DebugLogExpression(this Expression expression, string title, string label = "Expression") { if (RuntimeInformation.IsDebugBuild) { if (expression != null) { Core.Logging.LoggingService.LogVerbose(title, label + " = " + expression.ToString()); } else { Core.Logging.LoggingService.LogVerbose(title, label + " = null"); } } } public static string BuildCacheKey(this Expression expression) { try { return CacheKeyBuilderExpressionVisitor.ExpressionToString(expression); } catch (Exception e) { var exeptionToLog = new InvalidOperationException("Failed while building a cache key for expression " + expression, e); LoggingService.LogError(typeof(ExpressionExtensionMethods).FullName, exeptionToLog); return null; } } } } ================================================ FILE: Composite/Core/Linq/ExpressionExtractor.cs ================================================ using System.Linq.Expressions; namespace Composite.Core.Linq { internal static class ExpressionExtractor { public static LambdaExpression GetLambdaExpression(Expression expression) { if ((expression is LambdaExpression)) { return (LambdaExpression)expression; } if ((expression is UnaryExpression)) { return GetLambdaExpression(((UnaryExpression)expression).Operand); } return null; } } } ================================================ FILE: Composite/Core/Linq/ExpressionHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Data; namespace Composite.Core.Linq { internal static class ExpressionHelper { public static List GetCastedObjects(Type interfaceType, Expression sourceExpression) { return DataFacade.GetData(interfaceType).Provider .CreateQuery(sourceExpression) .Cast().ToList(); } public static Expression CreatePropertyExpression(string fieldName, Expression parameterExpression) { Type interfaceType = parameterExpression.Type; if (interfaceType.GetProperties().Any(f => f.Name == fieldName)) { return Expression.Property(parameterExpression, fieldName); } foreach (Type superInterfaceType in interfaceType.GetInterfaces()) { if (superInterfaceType.GetProperties().Any(f => f.Name == fieldName)) { return Expression.Property(Expression.Convert(parameterExpression, superInterfaceType), fieldName); } } throw new InvalidOperationException($"The interface '{parameterExpression.Type}' or any of its superinterfaces does not contain a field named '{fieldName}'"); } public static Expression CreatePropertyExpression(Type currentInterfaceType, Type actualPropertyDeclaringType, string fieldName, ParameterExpression parameterExpression) { Expression fieldParameterExpression = GetPropertyParameterExpression(currentInterfaceType, actualPropertyDeclaringType, parameterExpression); Expression expression = CreatePropertyExpression(fieldName, fieldParameterExpression); return expression; } public static Expression GetPropertyParameterExpression(Type currentInterfaceType, Type actualPropertyDeclaringType, ParameterExpression parameterExpression) { if (currentInterfaceType == actualPropertyDeclaringType) return parameterExpression; return Expression.Convert(parameterExpression, actualPropertyDeclaringType); } public static Expression CreateWhereExpression(Expression sourceExpression, ParameterExpression parameterExpression, Expression filterExpression) { if (filterExpression == null) return sourceExpression; LambdaExpression whereLambdaExpression = Expression.Lambda(filterExpression, parameterExpression); Expression whereExpression = ExpressionCreator.Where(sourceExpression, whereLambdaExpression); return whereExpression; } public static Expression CreateSelectExpression(Expression sourceExpression, Expression bodyExpression, ParameterExpression parameterExpression) { LambdaExpression selectLambdaExpression = Expression.Lambda(bodyExpression, parameterExpression); Expression selectExpression = ExpressionCreator.Select(sourceExpression, selectLambdaExpression); return selectExpression; } public static Expression CreateDistinctExpression(Expression sourceExpression) { Expression distinctExpression = ExpressionCreator.Distinct(sourceExpression); return distinctExpression; } public static Expression CreateOrderByExpression(Expression sourceExpression, LambdaExpression keySelector) { Expression orderByExpression = ExpressionCreator.OrderBy(sourceExpression, keySelector); return orderByExpression; } public static Expression CreateOrderByDescendingExpression(Expression sourceExpression, LambdaExpression keySelector) { return ExpressionCreator.OrderByDescending(sourceExpression, keySelector); } public static Expression ThenByExpression(Expression sourceExpression, LambdaExpression keySelector) { return ExpressionCreator.ThenBy(sourceExpression, keySelector); } public static Expression ThenByDescendingExpression(Expression sourceExpression, LambdaExpression keySelector) { return ExpressionCreator.ThenByDescending(sourceExpression, keySelector); } public static Expression CreateJoinExpression(Expression outerSource, Expression innerSource, LambdaExpression outerKeySelector, LambdaExpression innerKeySelector, LambdaExpression resultSelector) { Expression joinExpression = ExpressionCreator.Join(outerSource, innerSource, outerKeySelector, innerKeySelector, resultSelector); return joinExpression; } public static Expression CreatePropertyPredicate(ParameterExpression parameterExpression, IEnumerable> propertiesWithValues) { Expression currentExpression = null; foreach (var kvp in propertiesWithValues) { PropertyInfo propertyInfo = kvp.Item1; object value = kvp.Item2; var left = Expression.Property(parameterExpression, propertyInfo); var right = Expression.Constant(value); var filter = Expression.Equal(left, right); currentExpression = currentExpression == null ? filter : Expression.And(currentExpression, filter); } return currentExpression; } } } ================================================ FILE: Composite/Core/Linq/ExpressionVisitors/CacheKeyBuilderExpressionVisitor.cs ================================================ using System; using System.Linq.Expressions; using System.Reflection; using Composite.Core.WebClient.Renderings.Page; using Composite.Core.Types; namespace Composite.Core.Linq.ExpressionVisitors { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class CacheKeyBuilderExpressionVisitor : ExpressionVisitor { private static readonly MethodInfo ConstantWrapperMethod = StaticReflection.GetGenericMethodInfo(() => CacheKeyBuilderExpressionVisitor.A(string.Empty)); /// public interface ICacheKeyProvider { /// string GetCacheKey(); } private static readonly object[] EmptyObjectArray = new object[0]; private bool _cacheKeyCanBeCreated = true; /// protected CacheKeyBuilderExpressionVisitor() { } internal static string ExpressionToString(Expression expression) { CacheKeyBuilderExpressionVisitor builder = new CacheKeyBuilderExpressionVisitor(); Expression cachableExpression = builder.Visit(expression); return (builder._cacheKeyCanBeCreated ? cachableExpression : expression).ToString(); } /// public override Expression Visit(Expression node) { // Don't do anything if the expression is considered as not appropriate if (!_cacheKeyCanBeCreated) { return node; } return base.Visit(node); } /// protected override Expression VisitMember(MemberExpression node) { // Replacing output like "value(SomeNamespace.Filters+<>c__DisplayClassa).SomeField" with its actual value if(node.Expression is ConstantExpression && node.Member is FieldInfo) { object obj = (node.Expression as ConstantExpression).Value; object value = (node.Member as FieldInfo).GetValue(obj); if(IsSimpleType(node.Type)) { return Expression.Constant(value); } if (value != null && value is ICacheKeyProvider) { return Out((value as ICacheKeyProvider).GetCacheKey(), node.Type); } } // Replacing output like "value(SomeNamespace.Filters+<>c__DisplayClassa).SomeField.SomeOtherField" with its actual value if(node.Expression is MemberExpression && node.Member is PropertyInfo && IsSimpleType(node.Type)) { MemberExpression innerExpression = node.Expression as MemberExpression; if (innerExpression.Expression is ConstantExpression && innerExpression.Member is FieldInfo) { object obj = (innerExpression.Expression as ConstantExpression).Value; object containerValue = (innerExpression.Member as FieldInfo).GetValue(obj); object value = (node.Member as PropertyInfo).GetValue(containerValue, EmptyObjectArray); return Expression.Constant(value); } } // Replacing RageRenderer.CurrentPageId with its actual value if (node.Expression == null && node.Member.DeclaringType == typeof(PageRenderer) && node.Member.Name == "CurrentPageId") { return Expression.Constant(PageRenderer.CurrentPageId); } return base.VisitMember(node); } /// protected override Expression VisitConstant(ConstantExpression node) { if(node.Value != null && !IsSimpleType(node.Type)) { _cacheKeyCanBeCreated = false; return node; } return base.VisitConstant(node); } /// public override string ToString() { return _cacheKeyCanBeCreated ? base.ToString() : null; } private static bool IsSimpleType(Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { type = type.GetGenericArguments()[0]; } return type == typeof(Guid) || type == typeof(string) || type == typeof(bool) || type == typeof(DateTime) || type == typeof(byte) || type == typeof(Int32) || type == typeof(Int64) || type == typeof(Double); } /// /// Used for creating cache keys for LINQ expressions, it has a short name to keep the keys short /// private static T A(string cacheKeyPart) { throw new InvalidOperationException("This method is not supposed to be called, used only for building a cache key via ExpressionStringBuilder"); } private static Expression Out(string value, Type type) { // TODO: check whether it has sense to cache MakeGenericMethod call var methodInfo = ConstantWrapperMethod.MakeGenericMethod(type); return Expression.Call(methodInfo, Expression.Constant(value)); } } } ================================================ FILE: Composite/Core/Linq/ExpressionVisitors/FindFirstParameterExpressionVisitor.cs ================================================ using System.Linq.Expressions; namespace Composite.Core.Linq.ExpressionVisitors { internal sealed class FindFirstParameterExpressionVisitor : ExpressionVisitor { private ParameterExpression _foundParameter = null; public ParameterExpression FoundParameter { get { return _foundParameter; } } protected override Expression VisitParameter(ParameterExpression p) { if (null == _foundParameter) { _foundParameter = p; } return p; } } } ================================================ FILE: Composite/Core/Linq/Extensions.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; namespace Composite.Core.Linq { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DictionaryExtensions { /// public static int GetContentHashCode(this IDictionary dictionary) { int hash = 0; foreach (DictionaryEntry entry in dictionary) { hash = hash ^ entry.Key.GetHashCode() ^ entry.Value.GetHashCode(); } return hash; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class IEnumerableExtensions { /// /// Returns an evaluated collection. It allows avoiding of multiple calculations for the same enumerator. /// /// Element type. /// Enumerable object to be evaluated. /// Evaluated collection. public static ICollection Evaluate(this IEnumerable enumerable) { Verify.ArgumentNotNull(enumerable, nameof(enumerable)); if (enumerable is T[] array) { return array; } if (enumerable is ICollection collection) { return collection; } return new List(enumerable); } /// public static IEnumerable EvaluateOrNull(this IEnumerable enumerable) { if (enumerable == null) return null; if (enumerable is T[] || enumerable is List) { return enumerable; } return new List(enumerable); } /// /// Extends standard IQueryable.Single method, allows specifying exception text. /// /// /// Exception format for not a single row found /// Exception format for multiple rows found /// /// [StringFormatMethod("formatArgs")] public static T SingleOrException(this IQueryable query, string exceptionOnEmpty, string exceptionOnMultipleResults, params object[] formatArgs) { var result = query.ToList(); if (result.Count == 0) throw new InvalidOperationException(string.Format(exceptionOnEmpty, formatArgs)); if (result.Count == 1) return result[0]; throw new InvalidOperationException(string.Format(exceptionOnMultipleResults, formatArgs)); } /// /// Extends standard IQueryable.Single method, allows specifying exception text. /// /// /// Exception format for not a single row found /// Exception format for multiple rows found /// /// [StringFormatMethod("formatArgs")] public static T SingleOrException(this IEnumerable query, string exceptionOnEmpty, string exceptionOnMultipleResults, params object[] formatArgs) { var result = query.ToList(); if (result.Count == 0) throw new InvalidOperationException(string.Format(exceptionOnEmpty, formatArgs)); if (result.Count == 1) return result[0]; throw new InvalidOperationException(string.Format(exceptionOnMultipleResults, formatArgs)); } /// /// Extends standard IQueryable.Single method, allows specifying exception text. /// /// /// Exception format for multiple rows found /// Format arguments /// [StringFormatMethod("exceptionOnMultipleResults")] public static T SingleOrDefaultOrException(this IEnumerable query, string exceptionOnMultipleResults, params object[] formatArgs) { var result = query.ToList(); if (result.Count == 0) return default(T); if (result.Count == 1) return result[0]; throw new InvalidOperationException(string.Format(exceptionOnMultipleResults, formatArgs)); } /// /// Extends standard IEnumerable.First() method, allows specifying exception text. /// /// /// Exception format for not a single row found /// Format arguments /// [StringFormatMethod("formatArgs")] public static T FirstOrException(this IEnumerable query, string exceptionOnEmpty, params object[] formatArgs) where T : class { var result = query.FirstOrDefault(); if (result == null) throw new InvalidOperationException(string.Format(exceptionOnEmpty, formatArgs)); return result; } internal static IEnumerable ExcludeDuplicateKeys(this IEnumerable sequence, Func getKeyFunc) { var keys = new HashSet(); foreach (var el in sequence) { TKey key = getKeyFunc(el); if (keys.Contains(key)) continue; keys.Add(key); yield return el; } } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ListExtensions { /// public static List ToList(this IEnumerable source, Func convertor) { return source.Select(convertor).ToList(); } /// public static List ToListOfObjects(this IEnumerable enumerable) { return enumerable.Cast().ToList(); } /// public static IEnumerable ToEnumerableOfObjects(this IEnumerable enumerable) { return enumerable.Cast(); } } } ================================================ FILE: Composite/Core/Linq/PropertyInfoValueCollectioncs.cs ================================================ using System; using System.Collections.Generic; using System.Reflection; namespace Composite.Core.Linq { internal sealed class PropertyInfoValueCollection { private Dictionary _propertyValues = new Dictionary(); public void AddPropertyValue(PropertyInfo propertyInfo, object value) { if (propertyInfo == null) throw new ArgumentNullException("propertyInfo"); // allow null values if (_propertyValues.ContainsKey(propertyInfo)) throw new ArgumentException(string.Format("The property name '{0}' has already been added", propertyInfo.Name)); _propertyValues.Add(propertyInfo, value); } public IEnumerable> PropertyValues { get { foreach (KeyValuePair kvp in _propertyValues) { yield return kvp; } } } public PropertyInfoValueCollection Clone() { PropertyInfoValueCollection propertyInfoValueCollection = new PropertyInfoValueCollection(); foreach (var kvp in this.PropertyValues) { propertyInfoValueCollection.AddPropertyValue(kvp.Key, kvp.Value); } return propertyInfoValueCollection; } } } ================================================ FILE: Composite/Core/Linq/TypeExtensions.cs ================================================ using System; using System.Runtime.CompilerServices; using Composite.Core.Collections.Generic; namespace Composite.Core.Linq { internal static class TypeExtensions { private static readonly Hashtable _typeIsCompiledCache = new Hashtable(); public static bool IsCompilerGeneratedType(this Type type) { string key = type.FullName + type.Assembly.FullName; bool? result = _typeIsCompiledCache[key]; if(result != null) { return (bool)result; } lock(_typeIsCompiledCache) { result = _typeIsCompiledCache[key]; if (result != null) return (bool) result; result = type.GetCustomAttributes(typeof (CompilerGeneratedAttribute), true).Length > 0; _typeIsCompiledCache.Add(key, result); return (bool)result; } } } } ================================================ FILE: Composite/Core/Linq/TypeHelpers.cs ================================================ using System; using System.Linq; using System.Linq.Expressions; using System.Collections.Generic; namespace Composite.Core.Linq { internal static class TypeHelpers { public static Type FindElementType(Expression expression) { Type elementType = expression.Type; if (!elementType.IsGenericType) { return null; } Type defintion = elementType.GetGenericTypeDefinition(); if ((typeof (IQueryable<>) == defintion) || (typeof (IEnumerable<>) == defintion)) { return elementType.GetGenericArguments()[0]; } Type[] interfaces = elementType.GetInterfaces(); foreach (Type interf in interfaces) { Type def = interf; if (interf.IsGenericType) { def = interf.GetGenericTypeDefinition(); } if ((typeof (IQueryable<>) == def) || (typeof (IEnumerable<>) == def)) { return elementType.GetGenericArguments()[0]; } } throw new NotImplementedException("Expression type could not be found"); } } } ================================================ FILE: Composite/Core/Localization/LocalizationFacade.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Transactions; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.Types; using Composite.Data.Transactions; using Composite.C1Console.Users; namespace Composite.Core.Localization { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class LocalizationFacade { /// /// Returns true if the given locale is already installed /// /// /// public static bool IsLocaleInstalled(string cultureName) { return IsLocaleInstalled(CultureInfo.CreateSpecificCulture(cultureName)); } /// /// Returns true if the given locale is already installed /// /// /// public static bool IsLocaleInstalled(CultureInfo cultureInfo) { return DataFacade.GetData().Any(f => f.CultureName == cultureInfo.Name); } /// /// Returns true if the given url mapping name has already been used /// /// /// public static bool IsUrlMappingNameInUse(string urlMappingName) { return DataLocalizationFacade.UrlMappingNames.Contains(urlMappingName); } /// /// Returns true if the given url mapping name has already been used /// /// This locale is disregarding when checking if url mapping is already used. /// This is usefull when renaming the url mapping name for a given locale /// /// public static bool IsUrlMappingNameInUse(CultureInfo cultureInfoToExclude, string urlMappingName) { return IsUrlMappingNameInUse(cultureInfoToExclude.Name, urlMappingName); } /// /// Returns true if the given url mapping name has already been used /// /// This locale is disregarding when checking if url mapping is already used. /// This is usefull when renaming the url mapping name for a given locale /// /// public static bool IsUrlMappingNameInUse(string cultureNameToExclude, string urlMappingName) { return DataFacade.GetData() .Any(f => f.CultureName != cultureNameToExclude && f.UrlMappingName == urlMappingName); } /// /// Adds a locale to the system. Throws exception if the given locale has already been installed or /// if the given url mapping name has already been used. If the given locale is the first, its set /// to be the default locale. /// /// /// /// public static void AddLocale(string cultureName, string urlMappingName, bool addAccessToAllUsers = true) { AddLocale(CultureInfo.CreateSpecificCulture(cultureName), urlMappingName, addAccessToAllUsers); } /// /// Use this method to rename the url mapping name of a given installed locale. Throws exception if /// the given locale is not installed or if the given url mapping name is already used. /// /// /// public static void RenameUrlMappingNameForLocale(string cultureName, string newUrlMappingName) { Verify.That(IsLocaleInstalled(cultureName), "The locale '{0}' is not installed and the url mapping name can not be renamed", cultureName); Verify.That(!IsUrlMappingNameInUse(cultureName, newUrlMappingName), "The url mapping '{0}' is already used", newUrlMappingName); ISystemActiveLocale systemActiveLocale = DataFacade.GetData().Single(f => f.CultureName == cultureName); systemActiveLocale.UrlMappingName = newUrlMappingName; DataFacade.Update(systemActiveLocale); } /// /// Adds a locale to the system. Throws exception if the given locale has already been installed or /// if the given url mapping name has already been used. If the given locale is the first, its set /// to be the default locale. /// /// /// /// /// public static void AddLocale(CultureInfo cultureInfo, string urlMappingName, bool addAccessToAllUsers = true, bool makeFlush = true) { AddLocale(cultureInfo, urlMappingName, addAccessToAllUsers, makeFlush, false); } /// /// Adds a locale to the system. Throws exception if the given locale has already been installed or /// if the given url mapping name has already been used. If the given locale is the first, its set /// to be the default locale. /// /// /// /// /// /// internal static void AddLocale(CultureInfo cultureInfo, string urlMappingName, bool addAccessToAllUsers, bool makeFlush, bool isDefault) { using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { Verify.That(!IsLocaleInstalled(cultureInfo), "The locale '{0}' has already been added to the system", cultureInfo); Verify.That(!IsUrlMappingNameInUse(urlMappingName), "The url mapping name '{0}' has already been used in the system", urlMappingName); if (!DataLocalizationFacade.ActiveLocalizationCultures.Any()) { addAccessToAllUsers = true; } var systemActiveLocale = DataFacade.BuildNew(); systemActiveLocale.Id = Guid.NewGuid(); systemActiveLocale.CultureName = cultureInfo.Name; systemActiveLocale.UrlMappingName = urlMappingName; systemActiveLocale.IsDefault = isDefault; DataFacade.AddNew(systemActiveLocale); if (addAccessToAllUsers) { List usernames = (from u in DataFacade.GetData() select u.Username).ToList(); foreach (string username in usernames) { UserSettings.AddActiveLocaleCultureInfo(username, cultureInfo); if (UserSettings.GetCurrentActiveLocaleCultureInfo(username) == null) { UserSettings.SetCurrentActiveLocaleCultureInfo(username, cultureInfo); UserSettings.SetForeignLocaleCultureInfo(username, cultureInfo); } } List usergroupids = (from u in DataFacade.GetData() select u.Id).ToList(); foreach (Guid usergroupid in usergroupids) { var groupLang = DataFacade.BuildNew(); groupLang.Id = Guid.NewGuid(); groupLang.CultureName = cultureInfo.ToString(); groupLang.UserGroupId = usergroupid; DataFacade.AddNew(groupLang); } } if (DataLocalizationFacade.DefaultLocalizationCulture == null) { DataLocalizationFacade.DefaultLocalizationCulture = cultureInfo; } transactionScope.Complete(); } DynamicTypeManager.AddLocale(cultureInfo); if (makeFlush) { C1Console.Events.GlobalEventSystemFacade.FlushTheSystem(false); } } /// /// Sets the given locale as default locale. Returns true if setted, false if the given locale is already the default locale. /// /// /// public static bool SetDefaultLocale(CultureInfo cultureInfo) { Verify.That(IsLocaleInstalled(cultureInfo), "The locale '{0}' is not installed and can not be set as default", cultureInfo); if (!IsDefaultLocale(cultureInfo)) { DataLocalizationFacade.DefaultLocalizationCulture = cultureInfo; return true; } return false; } /// /// Returns true if the given locale is default. Default locales can not be removed. /// /// /// public static bool IsDefaultLocale(CultureInfo cultureInfo) { return IsDefaultLocale(cultureInfo.Name); } /// /// Returns true if the given locale is default. Default locales can not be removed. /// /// /// public static bool IsDefaultLocale(string cultureName) { return DataLocalizationFacade.DefaultLocalizationCulture != null && cultureName == DataLocalizationFacade.DefaultLocalizationCulture.Name; } /// /// Returns true if only one installed locale is left. The last locale can not be removed. /// /// public static bool IsLastLocale() { return DataFacade.GetData().Count() == 1; } /// /// Returns true if any types is localized. /// /// public static bool IsTypesUsingLocalization() { return DataFacade.GetAllInterfaces().Any(DataLocalizationFacade.IsLocalized); } /// /// Returns true if the given locale is the only active locale for any user. /// If this is the case, the locale can not be removed /// /// /// public static bool IsOnlyActiveLocaleForSomeUsers(string cultureName) { return IsOnlyActiveLocaleForSomeUsers(CultureInfo.CreateSpecificCulture(cultureName)); } /// /// Returns true if the given locale is the only active locale for any user. /// If this is the case, the locale can not be removed /// /// /// public static bool IsOnlyActiveLocaleForSomeUsers(CultureInfo cultureInfo) { List usernames = (from u in DataFacade.GetData() select u.Username).ToList(); foreach (string username in usernames) { List activeLocales = UserSettings.GetActiveLocaleCultureInfos(username).ToList(); if (activeLocales.Count == 1 && activeLocales[0].Equals(cultureInfo)) { return true; } } return false; } /// /// Removes the given locale, all data is lost /// /// public static void RemoveLocale(string cultureName) { RemoveLocale(CultureInfo.CreateSpecificCulture(cultureName)); } /// /// Removes the given locale, all data is lost /// /// /// public static void RemoveLocale(CultureInfo cultureInfo, bool makeFlush = true) { Verify.That(!IsDefaultLocale(cultureInfo), "The locale '{0}' is the default locale and can not be removed", cultureInfo); Verify.That(!IsOnlyActiveLocaleForSomeUsers(cultureInfo), "The locale '{0}' is the only locale for some user(s) and can not be removed", cultureInfo); using (var transactionScope = TransactionsFacade.CreateNewScope()) { string cultureName = cultureInfo.Name; var systemActiveLocale = DataFacade.GetData().SingleOrDefault(f => f.CultureName == cultureName); Verify.IsNotNull(systemActiveLocale, "The locale '{0}' has not beed added and can not be removed", cultureInfo); List usernames = (from u in DataFacade.GetData() select u.Username).ToList(); foreach (string username in usernames) { if (cultureInfo.Equals(UserSettings.GetCurrentActiveLocaleCultureInfo(username))) { CultureInfo fallbackCultureInfo = UserSettings.GetActiveLocaleCultureInfos(username).First(f => !f.Equals(cultureInfo)); UserSettings.SetCurrentActiveLocaleCultureInfo(username, fallbackCultureInfo); } if (cultureInfo.Equals(UserSettings.GetForeignLocaleCultureInfo(username))) { UserSettings.SetForeignLocaleCultureInfo(username, null); } UserSettings.RemoveActiveLocaleCultureInfo(username, cultureInfo); } DataFacade.Delete(systemActiveLocale); transactionScope.Complete(); } DynamicTypeManager.RemoveLocale(cultureInfo); if (makeFlush) { C1Console.Events.GlobalEventSystemFacade.FlushTheSystem(false); } } } } ================================================ FILE: Composite/Core/Localization/LocalizationParser.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Xml.Linq; using Composite.Data; using Composite.Core.ResourceSystem; namespace Composite.Core.Localization { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class LocalizationParser { private static readonly Regex _attributRegex = new Regex(@"\$\((?[^:]+):(?[^\)]+)\)"); /// public static void Parse(XContainer container) { IEnumerable elements = container.Descendants().ToList(); foreach (XElement element in elements) { if (element.Name.Namespace == LocalizationXmlConstants.XmlNamespace) { if (element.Name.LocalName == "string") { HandleStringElement(element); } else if (element.Name.LocalName == "switch") { HandleSwitchElement(element); } } IEnumerable attributes = element.Attributes().ToList(); foreach (XAttribute attribute in attributes) { Match match = _attributRegex.Match(attribute.Value); if (match.Success && match.Groups["type"].Value == "lang") { string newValue = StringResourceSystemFacade.ParseString($"${{{match.Groups["id"].Value}}}"); attribute.SetValue(newValue); } } } } private static void HandleStringElement(XElement element) { XAttribute attribute = element.Attribute("key"); if (attribute == null) throw new InvalidOperationException($"Missing attibute named 'key' at {element}"); string newValue = StringResourceSystemFacade.ParseString($"${{{attribute.Value}}}"); element.ReplaceWith(newValue); } private static void HandleSwitchElement(XElement element) { XElement defaultElement = element.Element((XNamespace)LocalizationXmlConstants.XmlNamespace + "default"); Verify.IsNotNull(defaultElement, "Missing element named 'default' at {0}", element); XElement newValueParent = defaultElement; CultureInfo currentCultureInfo = LocalizationScopeManager.CurrentLocalizationScope; foreach (XElement whenElement in element.Elements((XNamespace)LocalizationXmlConstants.XmlNamespace + "when")) { XAttribute cultureAttribute = whenElement.Attribute("culture"); Verify.IsNotNull(cultureAttribute, "Missing attriubte named 'culture' at {0}", whenElement); CultureInfo cultureInfo = new CultureInfo(cultureAttribute.Value); if (cultureInfo.Equals(currentCultureInfo)) { newValueParent = whenElement; break; } } element.ReplaceWith(newValueParent.Nodes()); } } } ================================================ FILE: Composite/Core/Localization/LocalizationXmlConstants.cs ================================================ using Composite.Core.Xml; namespace Composite.Core.Localization { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class LocalizationXmlConstants { /// public static string XmlNamespace { get { return Namespaces.Localization10.ToString(); } } } } ================================================ FILE: Composite/Core/Log.cs ================================================ using System; using System.Globalization; using Composite.Core.Implementation; using JetBrains.Annotations; namespace Composite.Core { /// /// Provide write access to the C1 CMS log. Note that 'verbose' messages are typically only shown in run-time log viewers. /// public static class Log { /// /// Logs a 'information' message to the C1 CMS log. /// /// Title of log message /// Message to log public static void LogInformation(string title, string message) { ImplementationFactory.CurrentFactory.StatelessLog.LogInformation(title, message); } /// /// Logs a 'information' message to the C1 CMS log. /// /// Title of log message /// Message to log in a String.Format() style using {0} etc. /// Arguments to put into the message [StringFormatMethod("messageFormat")] public static void LogInformation(string title, string messageFormat, params object[] args) { ImplementationFactory.CurrentFactory.StatelessLog.LogInformation(title, messageFormat, args); } /// /// Logs a 'verbose' message to the C1 CMS log. Verbose messages are typically only shown in developer log viewers. /// /// Title of log message /// Message to log public static void LogVerbose(string title, string message) { ImplementationFactory.CurrentFactory.StatelessLog.LogVerbose(title, message); } /// /// Logs a 'verbose' message to the C1 CMS log. /// /// Title of log message /// Message to log in a String.Format() style using {0} etc. /// Arguments to put into the message [StringFormatMethod("messageFormat")] public static void LogVerbose(string title, string messageFormat, params object[] args) { ImplementationFactory.CurrentFactory.StatelessLog.LogVerbose(title, string.Format(CultureInfo.InvariantCulture, messageFormat, args)); } /// /// Logs a 'warning' message to the C1 CMS log. /// /// Title of log message /// Message to log public static void LogWarning(string title, string message) { ImplementationFactory.CurrentFactory.StatelessLog.LogWarning(title, message); } /// /// Logs a 'warning' message to the C1 CMS log. /// /// Title of log message /// Message to log in a String.Format() style using {0} etc. /// Arguments to put into the message [StringFormatMethod("messageFormat")] public static void LogWarning(string title, string messageFormat, params object[] args) { ImplementationFactory.CurrentFactory.StatelessLog.LogWarning(title, messageFormat, args); } /// /// Logs a 'verbose' message to the C1 CMS log. /// /// Title of log message /// Exception to log public static void LogWarning(string title, Exception exception) { ImplementationFactory.CurrentFactory.StatelessLog.LogWarning(title, exception); } /// /// Logs a 'error' message to the C1 CMS log. /// /// Title of log message /// Message to log public static void LogError(string title, string message) { ImplementationFactory.CurrentFactory.StatelessLog.LogError(title, message); } /// /// Logs a 'error' message to the C1 CMS log. /// /// Title of log message /// Message to log in a String.Format() style using {0} etc. /// Arguments to put into the message [StringFormatMethod("messageFormat")] public static void LogError(string title, string messageFormat, params object[] args) { ImplementationFactory.CurrentFactory.StatelessLog.LogError(title, messageFormat, args); } /// /// Logs a 'error' message to the C1 CMS log. /// /// Title of log message /// Exception to log public static void LogError(string title, Exception exception) { ImplementationFactory.CurrentFactory.StatelessLog.LogError(title, exception); } /// /// Logs a 'critical' message to the C1 CMS log. You should only use 'critical' when a major system failure occur. /// /// Title of log message /// Message to log public static void LogCritical(string title, string message) { ImplementationFactory.CurrentFactory.StatelessLog.LogCritical(title, message); } /// /// Logs a 'critical' message to the C1 CMS log. You should only use 'critical' when a major system failure occur. /// /// Title of log message /// Message to log in a String.Format() style using {0} etc. /// Arguments to put into the message [StringFormatMethod("messageFormat")] public static void LogCritical(string title, string messageFormat, params object[] args) { ImplementationFactory.CurrentFactory.StatelessLog.LogCritical(title, messageFormat, args); } /// /// Logs a 'critical' message to the C1 CMS log. You should only use 'critical' when a major system failure occur. /// /// Title of log message /// Exception to log public static void LogCritical(string title, Exception exception) { ImplementationFactory.CurrentFactory.StatelessLog.LogCritical(title, exception); } } } ================================================ FILE: Composite/Core/Logging/DebugLoggingScope.cs ================================================ using System; using System.Diagnostics; namespace Composite.Core.Logging { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DebugLoggingScope : IDisposable { /// public static IDisposable CompletionTime( Type callingType, string actionInfo ) { if (RuntimeInformation.IsDebugBuild) { return new DebugLoggingScope(callingType.Name, actionInfo, false, TimeSpan.MinValue); } return EmptyDisposable.Instance; } /// public static IDisposable CompletionTime(Type callingType, string actionInfo, TimeSpan loggingThreshold) { if (RuntimeInformation.IsDebugBuild) { return new DebugLoggingScope(callingType.Name, actionInfo, false, loggingThreshold); } return EmptyDisposable.Instance; } /// public static IDisposable MethodInfoScope { get { if (RuntimeInformation.IsDebugBuild) { var stackTrace = new StackTrace(); var method = stackTrace.GetFrame(1).GetMethod(); string scopeName = $"{method.DeclaringType.Name}.{method.Name}"; return new DebugLoggingScope(scopeName, "Method", true, TimeSpan.MinValue); } return EmptyDisposable.Instance; } } private readonly int _startTickCount; private readonly string _scopeName; private readonly string _actionInfo; private readonly TimeSpan _threshold; private DebugLoggingScope(string scopeName, string actionInfo, bool logStart, TimeSpan threshold) { _startTickCount = Environment.TickCount; _scopeName = scopeName; _actionInfo = actionInfo; _threshold = threshold; if (logStart) { Log.LogVerbose(_scopeName, $"Starting {_actionInfo}"); } } /// public void Dispose() { int endTickCount = Environment.TickCount; var totalMilliseconds = endTickCount - _startTickCount; if (totalMilliseconds >= _threshold.TotalMilliseconds) { Log.LogVerbose(_scopeName, $"Finished {_actionInfo} ({totalMilliseconds} ms)"); } #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~DebugLoggingScope() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } ================================================ FILE: Composite/Core/Logging/ILog.cs ================================================ using System; namespace Composite.Core.Logging { /// /// Provide access to write to the log /// public interface ILog { /// /// LogCritical /// /// title /// message void LogCritical(string title, string message); /// /// LogCritical /// /// title /// exception void LogCritical(string title, Exception exception); /// /// LogCritical /// /// title /// messageFormat /// args void LogCritical(string title, string messageFormat, params object[] args); /// /// LogError /// /// title /// message void LogError(string title, string message); /// /// LogError /// /// title /// exception void LogError(string title, Exception exception); /// /// LogError /// /// title /// messageFormat /// args void LogError(string title, string messageFormat, params object[] args); /// /// LogInformation /// /// title /// message void LogInformation(string title, string message); /// /// LogInformation /// /// title /// messageFormat /// args void LogInformation(string title, string messageFormat, params object[] args); /// /// LogVerbose /// /// title /// message void LogVerbose(string title, string message); /// /// LogVerbose /// /// title /// messageFormat /// args void LogVerbose(string title, string messageFormat, params object[] args); /// /// LogWarning /// /// title /// message void LogWarning(string title, string message); /// /// LogWarning /// /// title /// exception void LogWarning(string title, Exception exception); /// /// LogWarning /// /// title /// messageFormat /// args void LogWarning(string title, string messageFormat, params object[] args); } } ================================================ FILE: Composite/Core/Logging/LogEntry.cs ================================================ using System; using System.Globalization; using System.Runtime.Serialization; using System.Text; using System.Diagnostics; namespace Composite.Core.Logging { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class LogEntry { const char NonBreakingSpace = (char)160; private static readonly string DateTimeFormat = "yyyyMMdd" + NonBreakingSpace + "HH:mm:ss.ffff"; /// public DateTime TimeStamp { get; set; } /// public int ApplicationDomainId { get; set; } /// public int ThreadId { get; set; } /// public string Severity { get; set; } /// public string Title { get; set; } /// public string DisplayOptions { get; set; } /// public string Message { get; set; } /// public override string ToString() { int applicationDomainId = AppDomain.CurrentDomain.Id; int threadId = System.Threading.Thread.CurrentThread.ManagedThreadId; var sb = new StringBuilder(); sb.Append(TimeStamp.ToString(DateTimeFormat)); // It has one NonBreakingSpace inside sb.Append(NonBreakingSpace).Append(applicationDomainId); sb.Append(NonBreakingSpace).Append(threadId < 10 ? " " : string.Empty).Append(threadId); sb.Append(NonBreakingSpace).Append(Severity); sb.Append(NonBreakingSpace).Append(Title); sb.Append(NonBreakingSpace).Append(DisplayOptions); sb.Append(NonBreakingSpace).Append(Message/*.Replace("\n", @"\n")*/); return sb.ToString(); } /// [DebuggerStepThrough] public static LogEntry Parse(string serializedLogEntry) { Verify.ArgumentNotNull(serializedLogEntry, "serializedLogEntry"); if(serializedLogEntry.IndexOf((char)65533) == -1 && serializedLogEntry.IndexOf((char)160) == -1) { return null; } string[] parts = serializedLogEntry.Split((char)65533); if(parts.Length != 8) { parts = serializedLogEntry.Split((char)160); } if(parts.Length != 8) { return null; } var result = new LogEntry(); try { string date = parts[0] + parts[1]; DateTime timeStamp; if (!DateTime.TryParseExact(date, "yyyyMMddHH:mm:ss.ffff", CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out timeStamp)) { return null; } result.TimeStamp = timeStamp; result.ApplicationDomainId = int.Parse(parts[2]); result.ThreadId = int.Parse(parts[3]); result.Severity = parts[4]; result.Title = parts[5]; result.DisplayOptions = parts[6]; result.Message = parts[7]; } catch(Exception) { return null; } return result; } } } ================================================ FILE: Composite/Core/Logging/LogLevel.cs ================================================ namespace Composite.Core.Logging { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum LogLevel { /// Info, /// Debug, /// Fine, /// Warning, /// Error, /// Fatal } } ================================================ FILE: Composite/Core/Logging/LogManager.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Plugins.Logging.LogTraceListeners.FileLogTraceListener; namespace Composite.Core.Logging { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class LogManager { private static readonly string VerboseSeverity = "Verbose"; private static readonly TimeSpan LockedFileAwaitingPeriod = TimeSpan.FromSeconds(15); private static readonly DateTime _startTime = DateTime.Now; /// public static int LogLinesRequestLimit = 5000; private static int MaxLogEntriesToParse = 50000; private static LogFileReader[] _logFiles; private static readonly object _syncRoot = new object(); /// static LogManager() { FileLogger.OnReset += () => _logFiles = null; } private static FileLogger FileLogger => FileLogTraceListener.LoggerInstance; private static LogFileReader[] LogFiles { get { var result = _logFiles; if (result == null || result.Length == 0) { lock (_syncRoot) { result = _logFiles; if (result == null || result.Length == 0) { _logFiles = result = FileLogger?.GetLogFiles() ?? new LogFileReader[0]; } } } return result; } } /// public static bool DeleteLogFile(DateTime date) { date = date.Date; var filesToDelete = FileLogger.GetLogFiles().Where(file => file.Date.Date == date).ToArray(); bool updated = false; foreach (var file in filesToDelete) { updated |= file.Delete(); } if (updated) { lock (_syncRoot) { _logFiles = null; } } return updated; } internal static void Flush() { FileLogger?.Flush(true); } /// public static DateTime GetLastStartupTime() { return FileLogger.StartupTime; } /// public static DateTime[] GetLoggingDates() { return LogFiles.Select(entry => entry.Date).Distinct().OrderBy(date => date).ToArray(); } /// public static int GetLogEntriesCount(DateTime timeFrom, DateTime timeTo, bool includeVerbose) { throw new NotImplementedException(); } /// public static int GetLogEntriesCountByDate(DateTime date, bool includeVerbose) { date = date.Date; return LogFiles.Where(logFile => logFile.Date == date).Sum(logFile => logFile.EntriesCount); } /// public static LogEntry[] GetLogEntries(DateTime timeFrom, DateTime timeTo, bool includeVerbose, int maximumAmount) { if (maximumAmount == 0) { maximumAmount = LogLinesRequestLimit; } Verify.That(maximumAmount > 0 && maximumAmount <= LogLinesRequestLimit, "Maximum amount should be in range [1..{0}]", LogLinesRequestLimit); var files = LogFiles.Where(logFile => logFile.Date >= timeFrom.Date && logFile.Date <= timeTo.Date); var result = new List(); lock (_syncRoot) { foreach (var logFile in files) { try { if (!logFile.Open()) { if (DateTime.Now - _startTime < LockedFileAwaitingPeriod) { // Waiting for some time until all log files are released // This ensures that LogViewer will get all the logs from previous, currently being shutdown AppDomain(s) return Array.Empty(); } continue; } int entriesRead = 0; int entriesParsed = 0; foreach (var entry in logFile.GetLogEntries(timeFrom, timeTo)) { entriesParsed++; if (entriesParsed >= MaxLogEntriesToParse) { result.Add(new LogEntry { ApplicationDomainId = AppDomain.CurrentDomain.Id, ThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId, TimeStamp = DateTime.Now, Title = nameof(LogManager), Message = $"Maximum amount of parsed log entries reached ({MaxLogEntriesToParse})." }); break; } if (entry.TimeStamp >= timeFrom && entry.TimeStamp <= timeTo) { if (!includeVerbose && entry.Severity == VerboseSeverity) { continue; } result.Add(entry); entriesRead++; if (entriesRead == maximumAmount) break; } } } finally { logFile.Close(); } } } return result.OrderBy(entry => entry.TimeStamp).Take(maximumAmount).ToArray(); } } } ================================================ FILE: Composite/Core/Logging/LoggingService.cs ================================================ using System; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using Composite.C1Console.Events; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.Core.IO; using Microsoft.Practices.EnterpriseLibrary.Logging; using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration; namespace Composite.Core.Logging { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class LoggingService { /// [Flags] public enum Category { /// General = 0x1, /// Audit = 0x2, } private static readonly ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); private static readonly string BeginOfInnerExceptionMarker; private static readonly string EndOfInnerExceptionMarker; private static readonly MethodInfo ExceptionToStringInternal_MethodInfo; /// static LoggingService() { MethodInfo getRuntimeResourceStringMethodInfo = typeof(Environment) .GetMethod("GetRuntimeResourceString", BindingFlags.NonPublic | BindingFlags.Static, null, new[] { typeof(string) }, null); // NOTE: "Magic" strings, shouldn't be modified BeginOfInnerExceptionMarker = "---> "; EndOfInnerExceptionMarker = Environment.NewLine + " " + (string)getRuntimeResourceStringMethodInfo.Invoke(null, new object[] { "Exception_EndOfInnerExceptionStack" }); ExceptionToStringInternal_MethodInfo = typeof(Exception).GetMethod("ToString", BindingFlags.Instance | BindingFlags.NonPublic); GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlush); } /// public static void LogEntry(string title, string message, Category category, System.Diagnostics.TraceEventType severity, int priority, int eventid) { LogEntry(title, message, null, category, severity, priority, eventid); } /// static private void LogEntry(string title, string message, Exception exc, Category category, System.Diagnostics.TraceEventType severity) { LogEntry(title, message, exc, category, severity, -1, 0); } static private void LogEntry(string title, string message, Exception exc, Category category, System.Diagnostics.TraceEventType severity, int priority, int eventid) { var entry = new Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry { Title = $"({AppDomain.CurrentDomain.Id} - {Thread.CurrentThread.ManagedThreadId}) {title}", Message = message, Severity = severity, Priority = priority, EventId = eventid }; if ((category & Category.General) != 0) { entry.Categories.Add(nameof(Category.General)); } if ((category & Category.Audit) != 0) { entry.Categories.Add(nameof(Category.Audit)); } if (exc != null) { entry.ExtendedProperties.Add("Exception", exc); } _resourceLocker.Resources.Writer.Write(entry); } /// static public void LogEntry(string title, string message, Category category, System.Diagnostics.TraceEventType severity, int priority) { LogEntry(title, message, category, severity, priority, 0); } /// static public void LogEntry(string title, string message, Category category, System.Diagnostics.TraceEventType severity) { LogEntry(title, message, category, severity, -1, 0); } /// static public void LogError(string title, string message) { LogEntry(title, message, Category.General, System.Diagnostics.TraceEventType.Error); } /// static public void LogError(string title, string message, Category category) { LogEntry(title, message, category, System.Diagnostics.TraceEventType.Error); } /// static public void LogError(string title, string message, Category category, int priority) { LogEntry(title, message, category, System.Diagnostics.TraceEventType.Error, priority); } /// static public void LogError(string title, string message, Category category, int priority, int eventid) { LogEntry(title, message, category, System.Diagnostics.TraceEventType.Error, priority, eventid); } /// static public void LogError(string title, Exception e) { LogEntry(title, PrettyExceptionCallStack(e), e, Category.General, System.Diagnostics.TraceEventType.Error); } /// static public void LogCritical(string title, string message) { LogEntry(title, message, Category.General, System.Diagnostics.TraceEventType.Critical); } /// static public void LogCritical(string title, string message, Category category) { LogEntry(title, message, category, System.Diagnostics.TraceEventType.Critical); } /// static public void LogCritical(string title, string message, Category category, int priority) { LogEntry(title, message, category, System.Diagnostics.TraceEventType.Critical, priority); } /// static public void LogCritical(string title, string message, Category category, int priority, int eventid) { LogEntry(title, message, category, System.Diagnostics.TraceEventType.Critical, priority, eventid); } /// static public void LogCritical(string title, Exception e) { LogEntry(title, PrettyExceptionCallStack(e), e, Category.General, System.Diagnostics.TraceEventType.Critical); } /// static public void LogInformation(string title, string message) { LogEntry(title, message, Category.General, System.Diagnostics.TraceEventType.Information); } /// static public void LogVerbose(string title, string message) { LogEntry(title, message, Category.General, System.Diagnostics.TraceEventType.Verbose); } /// static public void LogVerbose(string title, string message, Category category) { LogEntry(title, message, category, System.Diagnostics.TraceEventType.Verbose); } /// static public void LogVerbose(string title, string message, Category category, int priority) { LogEntry(title, message, category, System.Diagnostics.TraceEventType.Verbose, priority); } /// static public void LogVerbose(string title, string message, Category category, int priority, int eventid) { LogEntry(title, message, category, System.Diagnostics.TraceEventType.Verbose, priority, eventid); } /// static public void LogWarning(string title, string message) { LogEntry(title, message, Category.General, System.Diagnostics.TraceEventType.Warning); } /// static public void LogWarning(string title, string message, Category category) { LogEntry(title, message, category, System.Diagnostics.TraceEventType.Warning); } /// static public void LogWarning(string title, string message, Category category, int priority) { LogEntry(title, message, category, System.Diagnostics.TraceEventType.Warning, priority); } /// static public void LogWarning(string title, string message, Category category, int priority, int eventid) { LogEntry(title, message, category, System.Diagnostics.TraceEventType.Warning, priority, eventid); } /// static public void LogWarning(string title, Exception e) { LogEntry(title, PrettyExceptionCallStack(e), e, Category.General, System.Diagnostics.TraceEventType.Warning); } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlush(FlushEventArgs args) { Flush(); } static string PrettyExceptionCallStack(Exception ex) { if (ex == null) return "[exception is null]"; string serializedException = ex.ToString(); if (ex.InnerException != null && ExcludeInnerExceptionInformation(ex, serializedException, out var cleanException)) { return PrettyExceptionCallStack(ex.InnerException) + Environment.NewLine + cleanException; } var loaderException = ex as ReflectionTypeLoadException; if (loaderException?.LoaderExceptions != null) { foreach (var innerEx in loaderException.LoaderExceptions) { serializedException += Environment.NewLine + PrettyExceptionCallStack(innerEx); } } return serializedException; } private static bool ExcludeInnerExceptionInformation(Exception exception, string serializedException, out string clearedSerializedException) { string innerExceptionText = exception is ExternalException ? BeginOfInnerExceptionMarker + InnerExceptionToString(exception.InnerException) : BeginOfInnerExceptionMarker + InnerExceptionToString(exception.InnerException) + EndOfInnerExceptionMarker; int offset = serializedException.IndexOf(innerExceptionText, StringComparison.InvariantCulture); if (offset < 0) { clearedSerializedException = null; return false; } clearedSerializedException = serializedException.Substring(0, offset) + serializedException.Substring(offset + innerExceptionText.Length); return true; } private static string InnerExceptionToString(Exception exception) { return (string)ExceptionToStringInternal_MethodInfo.Invoke(exception, new object[] { true, true }); } private sealed class Resources { public LogWriterFactory Factory { get; set; } public LogWriter Writer { get; set; } public static void Initialize(Resources resources) { LoggingSettings section = null; if (ConfigurationServices.ConfigurationSource != null) { section = ConfigurationServices.ConfigurationSource.GetSection(LoggingSettings.SectionName) as LoggingSettings; ; } if (section != null) { resources.Factory = new LogWriterFactory(ConfigurationServices.ConfigurationSource); resources.Writer = resources.Factory.Create(); } else { string path = Path.Combine(PathUtil.BaseDirectory, $"logging{Guid.NewGuid()}.config"); using (C1StreamWriter writer = new C1StreamWriter(path)) { Type type = typeof(LoggingService).Assembly .GetType("Composite.Plugins.Logging.LogTraceListeners.TcpLogTraceListener.TcpLogTraceListener", false); if ((type != null) && (RuntimeInformation.IsUnittest == false)) { #region config file writer.WriteLine(@"
"); #endregion } else { #region config file writer.WriteLine(@"
s "); #endregion } } resources.Factory = new LogWriterFactory(new FileConfigurationSource(path)); resources.Writer = resources.Factory.Create(); } } } } } ================================================ FILE: Composite/Core/Logging/NullLogTraceListener.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners; namespace Composite.Core.Logging { /// /// This is used when the Composite.Mocks.Plugins.Logging.LogTraceListeners.WinFormTraceListener.WinFormTraceListener /// is not available to the system. /// internal sealed class NullLogTraceListener : CustomTraceListener { public override void Write(string message) { } public override void WriteLine(string message) { } } } ================================================ FILE: Composite/Core/PackageSystem/Foundation/InstalledPackageInformationSerializerHandler.cs ================================================ using Composite.Core.Serialization; namespace Composite.Core.PackageSystem.Foundation { internal sealed class InstalledPackageInformationSerializerHandler : ISerializerHandler { public string Serialize(object objectToSerialize) { return ""; } public object Deserialize(string serializedObject) { return new InstalledPackageInformation(); } } } ================================================ FILE: Composite/Core/PackageSystem/Foundation/PackageManagerInstallProcessSerializerHandler.cs ================================================ using System.Collections.Generic; using Composite.Core.Serialization; namespace Composite.Core.PackageSystem.Foundation { /// /// This class is only for pleasing the workflow system. /// internal sealed class PackageManagerInstallProcessSerializerHandler : ISerializerHandler { public string Serialize(object objectToSerialize) { return ""; } public object Deserialize(string serializedObject) { return new PackageManagerInstallProcess(new List(), null); } } } ================================================ FILE: Composite/Core/PackageSystem/Foundation/PackageManagerUninstallProcessSerializerHandler.cs ================================================ using System.Collections.Generic; using Composite.Core.Serialization; namespace Composite.Core.PackageSystem.Foundation { /// /// This class is only for pleasing the workflow system. /// internal sealed class PackageManagerUninstallProcessSerializerHandler : ISerializerHandler { public string Serialize(object objectToSerialize) { return ""; } public object Deserialize(string serializedObject) { return new PackageManagerUninstallProcess(new List()); } } } ================================================ FILE: Composite/Core/PackageSystem/Foundation/PackageServerFacadeImplCache.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Globalization; using Composite.Core.Logging; namespace Composite.Core.PackageSystem.Foundation { internal class PackageServerFacadeImplCache { private TimeSpan _cacheLiveTime; private DateTime _packageDescriptionsCacheTimestamp = DateTime.MinValue; private Dictionary>>> _packageDescriptionsCache = new Dictionary>>>(); public PackageServerFacadeImplCache() { _cacheLiveTime = TimeSpan.FromMinutes(30); if (RuntimeInformation.IsDebugBuild) { _cacheLiveTime = TimeSpan.FromSeconds(30); } } public List GetCachedPackageDescription(string packageServerUrl, Guid installationId, CultureInfo userCulture) { if ((_packageDescriptionsCacheTimestamp + _cacheLiveTime) < DateTime.Now) { LoggingService.LogVerbose("PackageServerFacadeCache", "PackageDescription cache miss"); return null; } Dictionary>> dic1; if (_packageDescriptionsCache.TryGetValue(packageServerUrl, out dic1) == false) { dic1 = new Dictionary>>(); _packageDescriptionsCache.Add(packageServerUrl, dic1); } Dictionary> dic2; if (dic1.TryGetValue(installationId, out dic2) == false) { dic2 = new Dictionary>(); dic1.Add(installationId, dic2); } if (dic2.ContainsKey(userCulture) == false) { LoggingService.LogVerbose("PackageServerFacadeCache", "PackageDescription cache miss"); return null; } LoggingService.LogVerbose("PackageServerFacadeCache", "PackageDescription returned from cache"); return dic2[userCulture]; } public void AddCachedPackageDescription(string packageServerUrl, Guid installationId, CultureInfo userCulture, List packageDescription) { LoggingService.LogVerbose("PackageServerFacadeCache", "PackageDescription added to cache"); Dictionary>> dic1; if (_packageDescriptionsCache.TryGetValue(packageServerUrl, out dic1) == false) { dic1 = new Dictionary>>(); _packageDescriptionsCache.Add(packageServerUrl, dic1); } Dictionary> dic2; if (dic1.TryGetValue(installationId, out dic2) == false) { dic2 = new Dictionary>(); dic1.Add(installationId, dic2); } dic2[userCulture] = packageDescription; _packageDescriptionsCacheTimestamp = DateTime.Now; } public void Clear() { _packageDescriptionsCache = new Dictionary>>>(); } } } ================================================ FILE: Composite/Core/PackageSystem/Foundation/PackageSystemSettings.cs ================================================ namespace Composite.Core.PackageSystem.Foundation { internal static class PackageSystemSettings { public static string InstallFilename { get { return "install.xml"; } } public static string UninstallFilename { get { return "uninstall.xml"; } } public static string InstalledFilename { get { return "installed"; } } public static string ZipFilename { get { return "package.zip"; } } public static string BinariesDirectoryName { get { return "Binaries"; } } public static string XmlNamespace { get { return "http://www.composite.net/ns/management/packageinstaller/1.0"; } } public static string PackageInstallerElementName { get { return "PackageInstaller"; } } public static string PackageRequirementsElementName { get { return "PackageRequirements"; } } public static string PackageFragmentInstallerBinariesElementName { get { return "PackageFragmentInstallerBinaries"; } } public static string PackageFragmentInstallerBinariesAddElementName { get { return "Add"; } } public static string PackageFragmentInstallersElementName { get { return "PackageFragmentInstallers"; } } public static string PackageFragmentUninstallersElementName { get { return "PackageFragmentUninstallers"; } } public static string PackageFragmentInstallersAddElementName { get { return "Add"; } } public static string PackageFragmentUninstallersAddElementName { get { return "Add"; } } public static string PackageInformationElementName { get { return "PackageInformation"; } } public static string MinimumCompositeVersionAttributeName { get { return "minimumCompositeVersion"; } } public static string MaximumCompositeVersionAttributeName { get { return "maximumCompositeVersion"; } } public static string PathAttributeName { get { return "path"; } } public static string InstallerTypeAttributeName { get { return "installerType"; } } public static string UninstallerTypeAttributeName { get { return "uninstallerType"; } } public static string IdAttributeName { get { return "id"; } } public static string NameAttributeName { get { return "name"; } } public static string GroupNameAttributeName { get { return "groupName"; } } public static string AuthorAttributeName { get { return "author"; } } public static string WebsiteAttributeName { get { return "website"; } } public static string VersionAttributeName { get { return "version"; } } public static string CanBeUninstalledAttributeName { get { return "canBeUninstalled"; } } public static string SystemLockingAttributeName { get { return "systemLocking"; } } public static string FlushOnCompletionAttributeName { get { return "flushOnCompletion"; } } public static string ReloadConsoleOnCompletionAttributeName { get { return "reloadConsoleOnCompletion"; } } #region "info.xml" xml stuff public static string PackageInformationFilename { get { return "info.xml"; } } public static string PackageInfoElementName { get { return "PackageInfo"; } } public static string PackageInfo_NameAttributeName { get { return "name"; } } public static string PackageInfo_GroupNameAttributeName { get { return "groupName"; } } public static string PackageInfo_VersionAttributeName { get { return "version"; } } public static string PackageInfo_AuthorAttributeName { get { return "author"; } } public static string PackageInfo_WebsiteAttributeName { get { return "website"; } } public static string PackageInfo_DescriptionAttributeName { get { return "description"; } } public static string PackageInfo_InstallDateAttributeName { get { return "installDate"; } } public static string PackageInfo_InstalledByAttributeName { get { return "installedBy"; } } public static string PackageInfo_IsLocalInstalledAttributeName { get { return "isLocalInstalled"; } } public static string PackageInfo_CanBeUninstalledAttributeName { get { return "canBeUninstalled"; } } public static string PackageInfo_FlushOnCompletionAttributeName { get { return "flushOnCompletion"; } } public static string PackageInfo_ReloadConsoleOnCompletionAttributeName { get { return "reloadConsoleOnCompletion"; } } public static string PackageInfo_SystemLockingAttributeName { get { return "systemLocking"; } } public static string PackageInfo_PackageServerAddressAttributeName { get { return "packageServerAddress"; } } #endregion } } ================================================ FILE: Composite/Core/PackageSystem/Foundation/SystemLockingType.cs ================================================ using System.Xml.Linq; namespace Composite.Core.PackageSystem.Foundation { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum SystemLockingType { /// None, /// Soft, /// Hard } internal static class SystemLockingTypeExtensionMethods { public static bool TryDeserialize(this XAttribute attribute, out SystemLockingType systemLockingType) { systemLockingType = SystemLockingType.Hard; if (attribute == null) return true; if (attribute.Value == "soft") systemLockingType = SystemLockingType.Soft; else if (attribute.Value == "hard") systemLockingType = SystemLockingType.Hard; else if (attribute.Value == "none") systemLockingType = SystemLockingType.None; else return false; return true; } public static string Serialize(this SystemLockingType systemLockingType) { return systemLockingType.ToString().ToLowerInvariant(); } } } ================================================ FILE: Composite/Core/PackageSystem/Foundation/VersionStringHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Composite.Core.PackageSystem.Foundation { internal static class VersionStringHelper { public static bool ValidateVersion(string version, out string newVersion) { Regex shotVersionRegex = new Regex(@"[0-9]+"); Match shotVersionMatch = shotVersionRegex.Match(version); if ((shotVersionMatch.Success) && (shotVersionMatch.Value == version)) { newVersion = string.Format("{0}.0.0.0", version); return true; } Regex versionRegex = new Regex(@"[0-9]+\.[0-9]+\.*[0-9]*\.*[0-9]*"); Match versionMatch = versionRegex.Match(version); if ((versionMatch.Success) && (versionMatch.Groups[0].Value.Length == version.Length)) { newVersion = version; return true; } newVersion = null; return false; } } } ================================================ FILE: Composite/Core/PackageSystem/Foundation/XmlHelper.cs ================================================ using System; using System.Xml.Linq; using Composite.Core.IO; using Composite.Core.IO.Zip; namespace Composite.Core.PackageSystem.Foundation { internal static class XmlHelper { public static PackageFragmentValidationResult LoadInstallXml(string zipFilename, out XElement installElement) { installElement = null; ZipFileSystem zipFileSystem = null; try { zipFileSystem = new ZipFileSystem(zipFilename); } catch (Exception ex) { return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex); } string filename = string.Format("~/{0}", PackageSystemSettings.InstallFilename); if (zipFileSystem.ContainsFile(filename) == false) { return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format("Installation file '{0}' is missing from the zip file", filename)); } try { using (var stream = zipFileSystem.GetFileStream(filename)) using (var streamReader = new C1StreamReader(stream)) { string fileContent = streamReader.ReadToEnd(); installElement = XElement.Parse(fileContent); } } catch (Exception ex) { return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex); } return null; } } } ================================================ FILE: Composite/Core/PackageSystem/IPackageFragmentInstaller.cs ================================================ using System.Collections.Generic; using System.Xml.Linq; namespace Composite.Core.PackageSystem { internal interface IPackageFragmentInstaller { void Initialize(PackageInstallerContext packageInstallerContext, IEnumerable configuration, XElement configurationParent); IEnumerable Validate(); /// /// /// /// /// Returns uninstall information /// IEnumerable Install(); } } ================================================ FILE: Composite/Core/PackageSystem/IPackageFragmentUninstaller.cs ================================================ using System.Collections.Generic; using System.Xml.Linq; namespace Composite.Core.PackageSystem { internal interface IPackageFragmentUninstaller { void Initialize(PackageUninstallerContext packageUninstallerContext, IEnumerable configuration, XElement configurationParent); IEnumerable Validate(); void Uninstall(); bool ValidateFirst { get; } } } ================================================ FILE: Composite/Core/PackageSystem/IPackageInstaller.cs ================================================ using System.Collections.Generic; using Composite.Core.PackageSystem.Foundation; namespace Composite.Core.PackageSystem { internal interface IPackageInstaller { bool CanBeUninstalled { get; } bool FlushOnCompletion { get; } bool ReloadConsoleOnCompletion { get; } IEnumerable Validate(); PackageFragmentValidationResult Install(SystemLockingType systemLockingType); } } ================================================ FILE: Composite/Core/PackageSystem/IPackageInstallerUninstallerFactory.cs ================================================ namespace Composite.Core.PackageSystem { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IPackageInstallerUninstallerFactory { /// IPackageUninstaller CreateUninstaller(string zipFilename, string uninstallFilename, string packageInstallationDirectory, string tempDirectory, bool flushOnCompletion, bool reloadConsoleOnCompletion, bool useTransaction, PackageInformation packageInformation); } } ================================================ FILE: Composite/Core/PackageSystem/IPackageServerFacade.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.IO; namespace Composite.Core.PackageSystem { internal interface IPackageServerFacade { ServerUrlValidationResult ValidateServerUrl(string packageServerUrl); IEnumerable GetPackageDescriptions(string packageServerUrl, Guid installationId, CultureInfo userCulture); string GetEulaText(string packageServerUrl, Guid eulaId, CultureInfo userCulture); Stream GetInstallFileStream(string packageFileDownloadUrl); void RegisterPackageInstallationCompletion(string packageServerUrl, Guid installationId, Guid packageId, string localUserName, string localUserIp); void RegisterPackageInstallationFailure(string packageServerUrl, Guid installationId, Guid packageId, string localUserName, string localUserIp, string exceptionString); void RegisterPackageUninstall(string packageServerUrl, Guid installationId, Guid packageId, string localUserName, string localUserIp); void ClearCache(); } } ================================================ FILE: Composite/Core/PackageSystem/IPackageUninstaller.cs ================================================ using System.Collections.Generic; using Composite.Core.PackageSystem.Foundation; namespace Composite.Core.PackageSystem { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IPackageUninstaller { /// bool FlushOnCompletion { get; } /// bool ReloadConsoleOnCompletion { get; } /// IEnumerable Validate(); /// PackageFragmentValidationResult Uninstall(SystemLockingType systemLockingType); } } ================================================ FILE: Composite/Core/PackageSystem/InstalledPackageInformation.cs ================================================ using System; using Composite.Core.PackageSystem.Foundation; using Composite.Core.Serialization; namespace Composite.Core.PackageSystem { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SerializerHandler(typeof(InstalledPackageInformationSerializerHandler))] public sealed class InstalledPackageInformation { /// public Guid Id { get; internal set; } /// public string Name { get; internal set; } /// public string GroupName { get; internal set; } /// public string Version { get; internal set; } /// public string Author { get; internal set; } /// public string Website { get; internal set; } /// public string Description { get; internal set; } /// public DateTime InstallDate { get; internal set; } /// public string InstalledBy { get; internal set; } /// public bool IsLocalInstalled { get; internal set; } /// public bool CanBeUninstalled { get; internal set; } /// public bool FlushOnCompletion { get; internal set; } /// public bool ReloadConsoleOnCompletion { get; internal set; } /// public SystemLockingType SystemLockingType { get; internal set; } /// public string PackageServerAddress { get; internal set; } /// internal string PackageInstallPath { get; set; } } } ================================================ FILE: Composite/Core/PackageSystem/LicenseDefinitionManager.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.Xml; namespace Composite.Core.PackageSystem { internal static class LicenseDefinitionManager { private const string LicenseFileExtension = ".license"; private static readonly string LogTitle = typeof (LicenseDefinitionManager).Name; private static readonly string _packageLicenseDirectory; private static readonly int _maximumProductNameLength; static LicenseDefinitionManager() { _packageLicenseDirectory = PathUtil.Resolve(GlobalSettingsFacade.PackageLicenseDirectory); if (!C1Directory.Exists(_packageLicenseDirectory)) { C1Directory.CreateDirectory(_packageLicenseDirectory); } _maximumProductNameLength = 255 - (GlobalSettingsFacade.MaximumRootPathLength + (GlobalSettingsFacade.PackageLicenseDirectory.Length - 1) + LicenseFileExtension.Length); } public static PackageLicenseDefinition GetLicenseDefinition(Guid productId) { return GetLicenseDefinitions(productId).OrderByDescending(l => l.Expires).FirstOrDefault(); } public static PackageLicenseDefinition[] GetLicenseDefinitions(Guid productId) { var result = new List(); foreach (var file in C1Directory.GetFiles(_packageLicenseDirectory, "*" + LicenseFileExtension, SearchOption.TopDirectoryOnly)) { var license = TryLoadLicenseFile(file); if (license != null && license.ProductId == productId) { result.Add(license); } } string obsoloteFilename = GetObsoleteLicenseFilename(productId); if (C1File.Exists(obsoloteFilename)) { var license = TryLoadLicenseFile(obsoloteFilename); if (license != null) { if (license.ProductId == productId) { result.Add(license); } else { Log.LogError(LogTitle, "The license for the product '{0}' does not match the product in the license file '{1}'", productId, license.ProductId); } } } return result.ToArray(); } public static void StoreLicenseDefinition(PackageLicenseDefinition licenseDefinition) { XDocument doc = new XDocument( new XElement("License", new XElement("Name", licenseDefinition.ProductName), new XElement("InstallationId", licenseDefinition.InstallationId), new XElement("ProductId", licenseDefinition.ProductId), new XElement("Permanent", licenseDefinition.Permanent), new XElement("Expires", licenseDefinition.Expires), new XElement("LicenseKey", licenseDefinition.LicenseKey), new XElement("PurchaseUrl", licenseDefinition.PurchaseUrl) ) ); string filename = GetLicenseFilename(licenseDefinition); licenseDefinition.LicenseFileName = filename; doc.SaveToFile(filename); } private static PackageLicenseDefinition TryLoadLicenseFile(string filePath) { XDocument doc = XDocumentUtils.Load(filePath); var licenseDefinition = new PackageLicenseDefinition { ProductName = doc.Descendants("Name").Single().Value, InstallationId = (Guid)doc.Descendants("InstallationId").Single(), ProductId = (Guid)doc.Descendants("ProductId").Single(), Permanent = (bool)doc.Descendants("Permanent").Single(), Expires = (DateTime?)doc.Descendants("Expires").SingleOrDefault() ?? DateTime.MaxValue, LicenseKey = doc.Descendants("LicenseKey").Single().Value, PurchaseUrl = doc.Descendants("PurchaseUrl").SingleOrDefault()?.Value ?? "", LicenseFileName = filePath }; if (licenseDefinition.InstallationId != InstallationInformationFacade.InstallationId) { Log.LogError(LogTitle, $"The license for the product '{licenseDefinition.ProductId}' ({licenseDefinition.ProductName}) does not match the current installation"); return null; } return licenseDefinition; } public static void RemoveLicenseDefintion(Guid productId) { foreach (var license in GetLicenseDefinitions(productId)) { FileUtils.Delete(license.LicenseFileName); } } private static string GetLicenseFilename(PackageLicenseDefinition packageLicenseDefinition) { string productName = packageLicenseDefinition.ProductName; if (productName.Length > _maximumProductNameLength) { productName = productName.Substring(productName.Length - _maximumProductNameLength); } return Path.Combine(_packageLicenseDirectory, productName + LicenseFileExtension); } private static string GetObsoleteLicenseFilename(Guid productId) { return Path.Combine(_packageLicenseDirectory, $"{productId}.xml"); } } } ================================================ FILE: Composite/Core/PackageSystem/LicenseDefinitionUtils.cs ================================================ using System; using System.Xml.Linq; using System.Text; using System.Security.Cryptography; namespace Composite.Core.PackageSystem { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] internal static class LicenseDefinitionUtils { /// /// /// /// public static object CreateSignatureHashAlgorithm(string publicKeyXml) { return SHA256.Create(); } /// /// /// /// public static byte[] GetLicenseKeyBytes(string licenseKey) { return Convert.FromBase64String(licenseKey); } /// /// /// /// public static byte[] CreateSignatureBytes(string signatureString) { UTF8Encoding encoding = new UTF8Encoding(); byte[] signature = encoding.GetBytes(signatureString); return signature; } } } ================================================ FILE: Composite/Core/PackageSystem/LicenseServerFacade.cs ================================================ using System; using System.ServiceModel; using Composite.Core.PackageSystem.WebServiceClient; namespace Composite.Core.PackageSystem { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] internal static class LicenseServerFacade { public static string ValidateTrialLicenseDefinitionRequest(Guid installationId, Guid productId, string publicKeyXml) { var client = CreateClient(); return client.ValidateTrialLicenseDefinitionRequest(installationId, productId, publicKeyXml); } public static LicenseDefinitionDescriptor GetTrialLicenseDefinition(Guid installationId, Guid productId, string publicKeyXml) { var client = CreateClient(); return client.GetTrialLicenseDefinition(installationId, productId, publicKeyXml); } private static string LicenseServerUrl => "https://package.composite.net/PackageLicense/LicenseDefinitionService.asmx"; private static LicenseDefinitionServiceSoapClient CreateClient() { var timeout = TimeSpan.FromMinutes(RuntimeInformation.IsDebugBuild ? 2 : 1); var basicHttpBinding = new BasicHttpBinding { CloseTimeout = timeout, OpenTimeout = timeout, ReceiveTimeout = timeout, SendTimeout = timeout }; if (LicenseServerUrl.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { basicHttpBinding.Security.Mode = BasicHttpSecurityMode.Transport; } basicHttpBinding.MaxReceivedMessageSize = int.MaxValue; return new LicenseDefinitionServiceSoapClient(basicHttpBinding, new EndpointAddress(LicenseServerUrl)); } } } ================================================ FILE: Composite/Core/PackageSystem/PackageAssemblyHandler.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.C1Console.Events; using Composite.Core.Types.Foundation; namespace Composite.Core.PackageSystem { internal static class PackageAssemblyHandler { private static bool _initialized; private static readonly object _lock = new object(); private static AssemblyFilenameCollection _loadedAssemblyFilenames = new AssemblyFilenameCollection(); private static List _inMemoryAssemblies = new List(); public static void Initialize() { if (_initialized) return; lock (_lock) { if (_initialized) return; GlobalEventSystemFacade.SubscribeToFlushEvent(args => ClearAssemblyList()); AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve; AppDomain.CurrentDomain.AssemblyLoad += OnAssemblyLoad; _initialized = true; } } private static void OnAssemblyLoad(object sender, AssemblyLoadEventArgs args) { var asm = args.LoadedAssembly; if (!asm.IsDynamic) { Log.LogVerbose(nameof(PackageAssemblyHandler), $"Assembly loaded: {asm.Location}"); } } public static void AddAssembly(string assemblyFilePath) { Initialize(); lock (_lock) { _loadedAssemblyFilenames.Add(assemblyFilePath); } } public static Assembly TryGetAlreadyLoadedAssembly(string assemblyFileName) { string assemblyName = AssemblyFilenameCollection.GetAssemblyName(assemblyFileName); lock (_lock) { return _inMemoryAssemblies.FirstOrDefault(asm => asm.GetName().Name == assemblyName); } } private static Assembly OnAssemblyResolve(object sender, ResolveEventArgs args) { string filename = args.Name; string fn = filename; if (fn.Contains(",")) { fn = fn.Remove(fn.IndexOf(',')).Trim(); } if (_loadedAssemblyFilenames.ContainsAssemblyName(fn)) { filename = _loadedAssemblyFilenames.GetFilenameByAssemblyName(fn); } Assembly assembly = null; if (filename.Contains(@":\")) { try { assembly = Assembly.LoadFrom(filename); } catch (Exception ex) { Log.LogError(nameof(PackageAssemblyHandler), ex); } lock (_lock) { _inMemoryAssemblies.Add(assembly); } } return assembly; } public static void ClearAssemblyList() { lock (_lock) { _loadedAssemblyFilenames = new AssemblyFilenameCollection(); _inMemoryAssemblies = new List(); } } } } ================================================ FILE: Composite/Core/PackageSystem/PackageDescription.cs ================================================ using System; using Composite.Core.Serialization; using System.Collections.Generic; namespace Composite.Core.PackageSystem { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SerializerHandler(typeof(PropertySerializerHandler))] public sealed class PackageDescription { /// public string PackageFileDownloadUrl { get; set; } /// public string PackageVersion { get; set; } /// public string Description { get; set; } /// public Guid EulaId { get; set; } /// public string GroupName { get; set; } /// public Guid Id { get; set; } /// public bool InstallationRequireLicenseFileUpdate { get; set; } /// public bool IsFree { get; set; } /// public bool IsTrial { get; set; } /// public Guid LicenseRuleId { get; set; } /// public string MaxCompositeVersionSupported { get; set; } /// public string MinCompositeVersionSupported { get; set; } /// public string Name { get; set; } /// public decimal PriceAmmount { get; set; } /// public string PriceCurrency { get; set; } /// public string ReadMoreUrl { get; set; } /// public string TechicalDetails { get; set; } /// public int TrialPeriodDays { get; set; } /// public bool UpgradeAgreementMandatory { get; set; } /// public string Vendor { get; set; } /// public string ConsoleBrowserUrl { get; set; } /// public List AvailableInSubscriptions { get; set; } } /// public sealed class Subscription { /// public Guid Id { get; set; } /// public string Name { get; set; } /// public string DetailsUrl { get; set; } /// public bool Purchasable { get; set; } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/BasePackageFragmentInstaller.cs ================================================ using System.Collections.Generic; using System.Xml.Linq; using Composite.Core.ResourceSystem; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class BasePackageFragmentInstaller : IPackageFragmentInstaller { /// public void Initialize(PackageInstallerContext packageInstallerContext, IEnumerable configuration, XElement configurationParent) { Verify.ArgumentNotNull(packageInstallerContext, "packageInstallerContext"); Verify.ArgumentNotNull(configuration, "configuration"); Verify.ArgumentNotNull(configurationParent, "configurationParent"); this.InstallerContext = packageInstallerContext; this.Configuration = configuration; this.ConfigurationParent = configurationParent; } /// public abstract IEnumerable Validate(); /// public abstract IEnumerable Install(); /// protected PackageInstallerContext InstallerContext { get; private set; } /// protected IEnumerable Configuration { get; set; } /// protected XElement ConfigurationParent { get; set; } internal static string GetResourceString(string key) { return StringResourceSystemFacade.GetString("Composite.Core.PackageSystem.PackageFragmentInstallers", key); } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/BasePackageFragmentUninstaller.cs ================================================ using System.Collections.Generic; using System.Xml.Linq; using System; using Composite.Core.ResourceSystem; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class BasePackageFragmentUninstaller : IPackageFragmentUninstaller { /// public void Initialize(PackageUninstallerContext packageUninstallerContext, IEnumerable configuration, XElement configurationParent) { Verify.ArgumentNotNull(packageUninstallerContext, "packageUninstallerContext"); Verify.ArgumentNotNull(configuration, "configuration"); Verify.ArgumentNotNull(configurationParent, "configurationParent"); this.UninstallerContext = packageUninstallerContext; this.Configuration = configuration; this.ConfigurationParent = configurationParent; } /// public abstract IEnumerable Validate(); /// public abstract void Uninstall(); /// protected IEnumerable Configuration { get; set; } /// protected XElement ConfigurationParent { get; set; } /// public virtual bool ValidateFirst { get { return false; } } /// protected PackageUninstallerContext UninstallerContext { get; private set; } internal static string GetResourceString(string key) { return StringResourceSystemFacade.GetString("Composite.Core.PackageSystem.PackageFragmentInstallers", key); } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/ConfigurationTransformationPackageFragmentInstaller.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.IO.Zip; using Composite.Core.Xml; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ConfigurationTransformationPackageFragmentInstaller : BasePackageFragmentInstaller { private const string _installElementName = "Install"; private const string _uninstallElementName = "Uninstall"; private const string _xsltFilePathAttributeName = "xsltFilePath"; /// public override IEnumerable Validate() { List validationResults = new List(); if (this.Configuration.Count() > 2) { validationResults.AddFatal( GetResourceString("ConfigurationTransformationPackageFragmentInstaller.ExpectedExactlyTwoElements") .FormatWith(_installElementName, _uninstallElementName)); } ValidateXslt( validationResults, () => this.InstallElement, _installElementName, () => this.InstallElement.Attribute(_xsltFilePathAttributeName), () => this.InstallXsltFilePath, this.InstallerContext.ZipFileSystem, true); if (validationResults.Count == 0 && this.InstallerContext.PackageInformation.CanBeUninstalled) { ValidateXslt( validationResults, () => this.UninstallElement, _uninstallElementName, () => this.UninstallElement.Attribute(_xsltFilePathAttributeName), () => this.UninstallXsltFilePath, this.InstallerContext.ZipFileSystem, false); } return validationResults; } /// public override IEnumerable Install() { using (Stream xsltFileStream = this.InstallerContext.ZipFileSystem.GetFileStream(this.InstallXsltFilePath)) { using (TextReader xsltTextReader = new StreamReader(xsltFileStream)) { XDocument xslt = XDocument.Load(xsltTextReader); ConfigurationServices.TransformConfiguration(xslt, false); } } if (this.InstallerContext.PackageInformation.CanBeUninstalled) { yield return this.UninstallElement; } } internal static void ValidateXslt(List validationResults, Func elementProvider, string elementName, Func xsltPathAttributeProvider, Func xsltFilePathProvider, IZipFileSystem zipFileSystem, bool validateResultingConfigurationFile) { if (elementProvider() == null) { validationResults.AddFatal( GetResourceString("ConfigurationTransformationPackageFragmentInstaller.MissingElement") .FormatWith(elementName)); return; } string xslFilePath = xsltFilePathProvider(); if (xslFilePath == null) { validationResults.AddFatal( GetResourceString("ConfigurationTransformationPackageFragmentInstaller.MissingAttribute") .FormatWith(_xsltFilePathAttributeName), elementProvider()); return; } if (zipFileSystem.ContainsFile(xslFilePath) == false) { validationResults.AddFatal( GetResourceString("ConfigurationTransformationPackageFragmentInstaller.PathDoesNotExist") .FormatWith(xslFilePath), xsltPathAttributeProvider()); return; } if(!PathUtil.WritePermissionGranted(ConfigurationServices.FileConfigurationSourcePath)) { validationResults.AddFatal( GetResourceString("NotEnoughNtfsPermissions") .FormatWith(ConfigurationServices.FileConfigurationSourcePath)); return; } using (Stream xsltFileStream = zipFileSystem.GetFileStream(xslFilePath)) { using (TextReader xsltTextReader = new C1StreamReader(xsltFileStream)) { XDocument xslt = null; try { xslt = XDocument.Load(xsltTextReader); } catch (Exception ex) { validationResults.AddFatal( GetResourceString("ConfigurationTransformationPackageFragmentInstaller.UnableToParsXslt") .FormatWith(xslFilePath, ex.Message), xsltPathAttributeProvider()); } if (xslt != null && validateResultingConfigurationFile) { try { ConfigurationServices.TransformConfiguration(xslt, true); } //catch (ConfigurationException ex) //{ // validationResults.AddFatal( // GetResourceString("ConfigurationTransformationPackageFragmentInstaller.XsltWillGeneratedInvalid") // .FormatWith(xsltFilePathProvider(), ex.Message), xsltPathAttributeProvider()); //} catch (Exception ex) { validationResults.AddFatal( GetResourceString("ConfigurationTransformationPackageFragmentInstaller.XsltWillGeneratedInvalid") .FormatWith(xslFilePath, ex.Message), xsltPathAttributeProvider()); } } } } } private XElement InstallElement { get { return this.Configuration.FirstOrDefault(f => f.Name == _installElementName); } } private XElement UninstallElement { get { return this.Configuration.FirstOrDefault(f => f.Name == _uninstallElementName); } } private string InstallXsltFilePath { get { return InstallElement.GetAttributeValue(_xsltFilePathAttributeName); } } private string UninstallXsltFilePath { get { return this.UninstallElement.GetAttributeValue(_xsltFilePathAttributeName); } } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/ConfigurationTransformationPackageFragmentUninstaller.cs ================================================ using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.Xml; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ConfigurationTransformationPackageFragmentUninstaller : BasePackageFragmentUninstaller { private const string _uninstallElementName = "Uninstall"; private const string _xsltFilePathAttributeName = "xsltFilePath"; /// public override IEnumerable Validate() { List validationResults = new List(); ConfigurationTransformationPackageFragmentInstaller.ValidateXslt( validationResults, () => this.UninstallElement, _uninstallElementName, () => this.UninstallElement.Attribute(_xsltFilePathAttributeName), () => this.UninstallXsltFilePath, this.UninstallerContext.ZipFileSystem, true); return validationResults; } /// public override void Uninstall() { using (Stream xsltFileStream = this.UninstallerContext.ZipFileSystem.GetFileStream(this.UninstallXsltFilePath)) { using (TextReader xsltTextReader = new C1StreamReader(xsltFileStream)) { XDocument xslt = XDocument.Load(xsltTextReader); ConfigurationServices.TransformConfiguration(xslt, false); } } } private XElement UninstallElement { get { return this.Configuration.FirstOrDefault(f => f.Name == _uninstallElementName); } } private string UninstallXsltFilePath { get { return this.UninstallElement.GetAttributeValue(_xsltFilePathAttributeName); } } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/DataPackageFragmentInstaller.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Xml.Linq; using Composite.C1Console.Security; using Composite.C1Console.Users; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.ResourceSystem; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.ProcessControlled; using Composite.Data.Types; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Core_PackageSystem_PackageFragmentInstallers; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DataPackageFragmentInstaller : BasePackageFragmentInstaller { private static readonly string LogTitle = nameof(DataPackageFragmentInstaller); private List _dataTypes; private List _validationResult; private Dictionary _dataKeysToBeInstalled; private Dictionary _dataKeysToBeInstalledByTypeId; private Dictionary>> _missingDataReferences; private static readonly Dictionary _pageVersionIds = new Dictionary(); /// public override IEnumerable Validate() { _validationResult = new List(); _dataKeysToBeInstalled = new Dictionary(); _dataKeysToBeInstalledByTypeId = new Dictionary(); _missingDataReferences = new Dictionary>>(); if (this.Configuration.Count(f => f.Name == "Types") > 1) { _validationResult.AddFatal(Texts.DataPackageFragmentInstaller_OnlyOneElement); return _validationResult; } _dataTypes = new List(); ValidateAndLoadConfiguration(); foreach (DataType dataType in _dataTypes) { dataType.InterfaceType = TypeManager.TryGetType(dataType.InterfaceTypeName); if (dataType.IsDynamicAdded || this.InstallerContext.IsDataTypePending(dataType.InterfaceTypeName)) { ValidateDynamicAddedType(dataType); } else { ValidateNonDynamicAddedType(dataType); } } if (_validationResult.Count > 0) { _dataTypes = null; } return _validationResult; } /// public override IEnumerable Install() { Verify.IsNotNull(_dataTypes, "DataPackageFragmentInstaller has not been validated"); List typeElements = new List(); foreach (DataType dataType in _dataTypes) { Log.LogVerbose(LogTitle, $"Installing data for the type '{dataType.InterfaceType}'"); if (dataType.IsDynamicAdded || dataType.InterfaceType == null) { dataType.InterfaceType = this.InstallerContext.IsDataTypePending(dataType.InterfaceTypeName) ? this.InstallerContext.GetPendingDataType(dataType.InterfaceTypeName) : TypeManager.GetType(dataType.InterfaceTypeName); Verify.IsNotNull(dataType.InterfaceType, "Failed to get interface type by name: '{0}'", dataType.InterfaceTypeName); } XElement typeElement = new XElement("Type", new XAttribute("type", TypeManager.SerializeType(dataType.InterfaceType)), new XAttribute("dataScopeIdentifier", dataType.DataScopeIdentifier)); using (new DataScope(dataType.DataScopeIdentifier)) { if (dataType.AddToAllLocales) { foreach (CultureInfo locale in DataLocalizationFacade.ActiveLocalizationCultures) { using (new DataScope(locale)) { XElement element = AddData(dataType, locale); typeElement.Add(element); } } } else if (dataType.AddToCurrentLocale) { var currentLocale = DataLocalizationFacade.DefaultLocalizationCulture; if (UserValidationFacade.IsLoggedIn()) { currentLocale = UserSettings.ActiveLocaleCultureInfo; } using (new DataScope(currentLocale)) { XElement element = AddData(dataType, currentLocale); typeElement.Add(element); } } else if (dataType.Locale != null) { if (DataLocalizationFacade.ActiveLocalizationCultures.Contains(dataType.Locale)) { using (new DataScope(dataType.Locale)) { XElement element = AddData(dataType, dataType.Locale); typeElement.Add(element); } } } else { var locale = UserValidationFacade.IsLoggedIn() ? UserSettings.ActiveLocaleCultureInfo : DataLocalizationFacade.DefaultLocalizationCulture; using (new DataScope(locale)) { XElement element = AddData(dataType, null); typeElement.Add(element); } } } typeElements.Add(typeElement); } yield return new XElement("Types", typeElements); } private static Type GetInstalledVersionOfPendingType(Type interfaceType, IData data) { return data.GetType().GetInterfaces().FirstOrDefault(i => i.FullName == interfaceType.FullName); } private XElement AddData(DataType dataType, CultureInfo cultureInfo) { XElement datasElement = new XElement("Datas"); if (cultureInfo != null) { datasElement.Add(new XAttribute("locale", cultureInfo.Name)); } foreach (XElement addElement in dataType.Dataset) { var interfaceType = dataType.InterfaceType; IData data = DataFacade.BuildNew(interfaceType); if (!dataType.InterfaceType.IsInstanceOfType(data)) { dataType.InterfaceType = GetInstalledVersionOfPendingType(interfaceType, data); } var dataKey = PopulateAndReturnKeyPropertyValues(dataType, data, addElement); if (dataType.AllowOverwrite || dataType.OnlyUpdate) { List existingDataList = DataFacade.TryGetDataByLookupKeys(interfaceType, dataKey).ToList(); if (existingDataList.Count > 1) throw new InvalidOperationException("Got more than 1 existing data element when querying on key properties for " + addElement.ToString()); IData existingData = existingDataList.FirstOrDefault(); if (existingData != null) { PopulateAndReturnKeyPropertyValues(dataType, existingData, addElement); DataFacade.Update(existingData, false, true, false); continue; } if (dataType.OnlyUpdate) { continue; } } if (data is ILocalizedControlled localizedControlled) { localizedControlled.SourceCultureName = LocalizationScopeManager.MapByType(interfaceType).Name; } if (data is IVersioned versionedData) { UpdateVersionId(versionedData); } DataFacade.AddNew(data, false, true, false); // Ignore validation, this should have been done in the validation face XElement keysElement = new XElement("Keys"); foreach (PropertyInfo propertyInfo in data.GetKeyProperties()) { string keyName = propertyInfo.Name; object keyValue = propertyInfo.GetValue(data, null); XElement keyElement = new XElement("Key", new XAttribute("name", keyName), new XAttribute("value", keyValue)); keysElement.Add(keyElement); } datasElement.Add(keysElement); } return datasElement; } private void UpdateVersionId(IVersioned data) { if (data.VersionId != Guid.Empty) { return; } if (data is IPage page) { if (_pageVersionIds.TryGetValue(page.Id, out Guid versionId)) { page.VersionId = versionId; } else { page.VersionId = Guid.NewGuid(); _pageVersionIds[page.Id] = page.VersionId; } } else if (data is IPagePlaceholderContent pagePlaceholderContent) { if (_pageVersionIds.TryGetValue(pagePlaceholderContent.PageId, out Guid versionId)) { data.VersionId = versionId; } } else if (data is IPageData pageData) { if (_pageVersionIds.TryGetValue(pageData.PageId, out Guid versionId)) { data.VersionId = versionId; } } } private static DataPropertyValueCollection PopulateAndReturnKeyPropertyValues(DataType dataType, IData dataToPopulate, XElement addElement) { var dataKeyPropertyCollection = new DataPropertyValueCollection(); var properties = GetDataTypeProperties(dataType.InterfaceType); var keyPropertyNames = dataType.InterfaceType.GetKeyPropertyNames(); var versionKeyPropertyNames = dataType.InterfaceType.GetVersionKeyPropertyNames(); foreach (XAttribute attribute in addElement.Attributes()) { string fieldName = attribute.Name.LocalName; if (IsObsoleteField(dataType, fieldName)) { continue; } PropertyInfo propertyInfo = properties[fieldName]; object fieldValue = ValueTypeConverter.Convert(attribute.Value, propertyInfo.PropertyType); propertyInfo.SetValue(dataToPopulate, fieldValue, null); if (keyPropertyNames.Contains(fieldName) || versionKeyPropertyNames.Contains(fieldName)) { dataKeyPropertyCollection.AddKeyProperty(propertyInfo, fieldValue); } } return dataKeyPropertyCollection; } private void ValidateAndLoadConfiguration() { XElement typesElement = this.Configuration.SingleOrDefault(f => f.Name == "Types"); if (typesElement == null) { _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.MissingElement")); } if (typesElement == null) return; foreach (XElement typeElement in typesElement.Elements("Type")) { var typeAttribute = typeElement.Attribute("type"); if (typeAttribute == null) { _validationResult.AddFatal(Texts.DataPackageFragmentInstaller_MissingAttribute("type"), typeElement); continue; } XAttribute allowOverwriteAttribute = typeElement.Attribute("allowOverwrite"); XAttribute onlyUpdateAttribute = typeElement.Attribute("onlyUpdate"); bool allowOverwrite = allowOverwriteAttribute != null && (bool)allowOverwriteAttribute; bool onlyUpdate = onlyUpdateAttribute != null && (bool)onlyUpdateAttribute; string interfaceTypeName = typeAttribute.Value; interfaceTypeName = TypeManager.FixLegasyTypeName(interfaceTypeName); foreach (XElement dataElement in typeElement.Elements("Data")) { XAttribute dataScopeIdentifierAttribute = dataElement.Attribute("dataScopeIdentifier"); if (dataScopeIdentifierAttribute == null) { _validationResult.AddFatal(Texts.DataPackageFragmentInstaller_MissingAttribute("dataScopeIdentifier"), typeElement); continue; } DataScopeIdentifier dataScopeIdentifier; try { dataScopeIdentifier = DataScopeIdentifier.Deserialize(dataScopeIdentifierAttribute.Value); } catch (Exception) { _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.WrongDataScopeIdentifier").FormatWith(dataScopeIdentifierAttribute.Value), dataScopeIdentifierAttribute); continue; } CultureInfo locale = null; // null => do not use localization bool allLocales = false; bool currentLocale = false; XAttribute localeAttribute = dataElement.Attribute("locale"); if (localeAttribute != null) { if (localeAttribute.Value == "*") { allLocales = true; } else if (localeAttribute.Value == "?") { currentLocale = true; } else { try { locale = CultureInfo.CreateSpecificCulture(localeAttribute.Value); } catch (Exception) { _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.WrongLocale").FormatWith(localeAttribute.Value), localeAttribute); continue; } } } XAttribute dataFilenameAttribute = dataElement.Attribute("dataFilename"); if (dataFilenameAttribute == null) { _validationResult.AddFatal(Texts.DataPackageFragmentInstaller_MissingAttribute("dataFilename"), typeElement); continue; } if (!this.InstallerContext.ZipFileSystem.ContainsFile(dataFilenameAttribute.Value)) { _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.MissingFile").FormatWith(dataFilenameAttribute.Value), dataFilenameAttribute); continue; } XDocument doc; try { using (var stream = this.InstallerContext.ZipFileSystem.GetFileStream(dataFilenameAttribute.Value)) using (var reader = new C1StreamReader(stream)) { doc = XDocument.Load(reader); } } catch (Exception ex) { _validationResult.Add(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex)); continue; } XAttribute isDynamicAddedAttribute = typeElement.Attribute("isDynamicAdded"); bool isDynamicAdded = isDynamicAddedAttribute != null && (bool)isDynamicAddedAttribute; var dataType = new DataType { InterfaceTypeName = interfaceTypeName, DataScopeIdentifier = dataScopeIdentifier, Locale = locale, AddToAllLocales = allLocales, AddToCurrentLocale = currentLocale, IsDynamicAdded = isDynamicAdded, AllowOverwrite = allowOverwrite, OnlyUpdate = onlyUpdate, Dataset = doc.Root.Elements("Add") }; _dataTypes.Add(dataType); } } } private static string GetText(string stringId) { return StringResourceSystemFacade.GetString("Composite.Core.PackageSystem.PackageFragmentInstallers", stringId); } private void ValidateNonDynamicAddedType(DataType dataType) { if (dataType.InterfaceType == null) { _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.TypeNotConfigured").FormatWith(dataType.InterfaceTypeName)); return; } if (!typeof(IData).IsAssignableFrom(dataType.InterfaceType)) { _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.TypeNotInheriting").FormatWith(dataType.InterfaceType, typeof(IData))); return; } bool dataTypeLocalized = DataLocalizationFacade.IsLocalized(dataType.InterfaceType); if (!ValidateTargetLocaleInfo(dataType, dataTypeLocalized)) { return; } int itemsAlreadyPresentInDatabase = 0; DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.BuildNewDataTypeDescriptor(dataType.InterfaceType); bool isVersionedDataType = typeof (IVersioned).IsAssignableFrom(dataType.InterfaceType); var requiredPropertyNames = (from dfd in dataTypeDescriptor.Fields where !dfd.IsNullable && !(isVersionedDataType && dfd.Name == nameof(IVersioned.VersionId)) // Compatibility fix select dfd.Name).ToList(); var nonRequiredPropertyNames = dataTypeDescriptor.Fields.Select(f => f.Name) .Except(requiredPropertyNames).ToList(); foreach (XElement addElement in dataType.Dataset) { var dataKeyPropertyCollection = new DataKeyPropertyCollection(); bool propertyValidationPassed = true; var assignedPropertyNames = new List(); var fieldValues = new Dictionary(); var properties = GetDataTypeProperties(dataType.InterfaceType); foreach (XAttribute attribute in addElement.Attributes()) { string fieldName = attribute.Name.LocalName; PropertyInfo propertyInfo; if (!properties.TryGetValue(fieldName, out propertyInfo)) { // A compatibility fix if (IsObsoleteField(dataType, fieldName)) { continue; } _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.MissingProperty").FormatWith(dataType.InterfaceType, fieldName)); propertyValidationPassed = false; continue; } if (!propertyInfo.CanWrite) { _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.MissingWritableProperty").FormatWith(dataType.InterfaceType, fieldName)); propertyValidationPassed = false; continue; } object fieldValue; try { fieldValue = ValueTypeConverter.Convert(attribute.Value, propertyInfo.PropertyType); } catch (Exception) { _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.ConversionFailed").FormatWith(attribute.Value, propertyInfo.PropertyType)); propertyValidationPassed = false; continue; } if (dataType.InterfaceType.GetKeyPropertyNames().Contains(fieldName)) { dataKeyPropertyCollection.AddKeyProperty(fieldName, fieldValue); } assignedPropertyNames.Add(fieldName); fieldValues.Add(fieldName, fieldValue); } if (!propertyValidationPassed) { continue; } var notAssignedRequiredProperties = requiredPropertyNames.Except(assignedPropertyNames.Except(nonRequiredPropertyNames)).ToArray(); if (notAssignedRequiredProperties.Any()) { bool missingValues = false; foreach (string propertyName in notAssignedRequiredProperties) { PropertyInfo propertyInfo = dataType.InterfaceType.GetPropertiesRecursively().Single(f => f.Name == propertyName); if (propertyInfo.CanWrite) { var defaultValueAttribute = propertyInfo.GetCustomAttributesRecursively().SingleOrDefault(); if (defaultValueAttribute == null || !defaultValueAttribute.HasValue) { _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.MissingPropertyVaule").FormatWith(propertyName, dataType.InterfaceType)); missingValues = true; } } } if (missingValues) continue; } // Validating keys already present if (!dataType.AllowOverwrite && !dataType.OnlyUpdate) { bool dataLocaleExists = !DataLocalizationFacade.IsLocalized(dataType.InterfaceType) || (!dataType.AddToAllLocales && !dataType.AddToCurrentLocale) || (dataType.Locale != null && !this.InstallerContext.IsLocalePending(dataType.Locale)); if(dataLocaleExists) { using (new DataScope(dataType.DataScopeIdentifier, dataType.Locale)) { IData data = DataFacade.TryGetDataByUniqueKey(dataType.InterfaceType, dataKeyPropertyCollection); if (data != null) { itemsAlreadyPresentInDatabase++; } } } } RegisterKeyToBeAdded(dataType, null, dataKeyPropertyCollection); // Checking foreign key references foreach (var foreignKeyProperty in DataAttributeFacade.GetDataReferenceProperties(dataType.InterfaceType)) { if(!fieldValues.ContainsKey(foreignKeyProperty.SourcePropertyName)) continue; object propertyValue = fieldValues[foreignKeyProperty.SourcePropertyName]; if (propertyValue == null || propertyValue.Equals(foreignKeyProperty.NullReferenceValue)) { continue; } CheckForBrokenReference(dataType, foreignKeyProperty.TargetType, foreignKeyProperty.TargetKeyPropertyName, propertyValue); } } if(itemsAlreadyPresentInDatabase > 0) { _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.DataExists").FormatWith(dataType.InterfaceType, itemsAlreadyPresentInDatabase)); } } private void CheckForBrokenReference(DataType refereeType, Type type, string propertyName, object propertyValue) { Type referredType; string keyPropertyName; object referenceKey; MapReference(type, propertyName, propertyValue, out referredType, out keyPropertyName, out referenceKey); // Checking key in the keys to be installed var keyValuePair = new KeyValuePair(keyPropertyName, referenceKey); if (_missingDataReferences.TryGetValue(referredType, out var refs) && refs.Contains(keyValuePair)) { return; } if (_dataKeysToBeInstalled.TryGetValue(referredType, out var keys) && keys.KeyRegistered(refereeType, keyValuePair)) { return; } var typeId = referredType.GetImmutableTypeId(); if (_dataKeysToBeInstalledByTypeId.TryGetValue(typeId, out var dynamicTypeKeys) && dynamicTypeKeys.KeyRegistered(refereeType, keyValuePair)) { return; } using (GetDataScopeFromDataTypeElement(refereeType)) { if (DataFacade.TryGetDataByUniqueKey(type, propertyValue) == null) { _validationResult.AddFatal(Texts.DataPackageFragmentInstaller_ReferencedDataMissing( type.FullName, propertyName, propertyValue)); var missingReferences = _missingDataReferences.GetOrAdd(referredType, () => new HashSet>()); missingReferences.Add(keyValuePair); } } } private static bool IsObsoleteField(DataType dataType, string fieldName) { return typeof(ILocalizedControlled).IsAssignableFrom(dataType.InterfaceType) && fieldName == "CultureName"; } private static Dictionary GetDataTypeProperties(Type type) { return type.GetPropertiesRecursively().Where(property => !IsObsoleteProperty(property)).ToDictionary(prop => prop.Name); } private static bool IsObsoleteProperty(PropertyInfo propertyInfo) { return propertyInfo.Name == nameof(IPageData.PageId) && propertyInfo.DeclaringType == typeof(IPageData); } private static bool IsObsoleteField(DataTypeDescriptor dataTypeDescriptor, string fieldName) { return dataTypeDescriptor.SuperInterfaces.Any(type => type == typeof(ILocalizedControlled)) && fieldName == "CultureName"; } private static void MapReference(Type type, string propertyName, object key, out Type referenceType, out string keyPropertyName, out object referenceKey) { if ((type == typeof(IImageFile) || type == typeof(IMediaFile)) && ((string)key).StartsWith("MediaArchive:") && propertyName == nameof(IMediaFile.KeyPath)) { referenceType = typeof(IMediaFileData); referenceKey = new Guid(((string)key).Substring("MediaArchive:".Length)); keyPropertyName = nameof(IMediaFileData.Id); return; } referenceType = type; keyPropertyName = propertyName; referenceKey = key; } private DataScope GetDataScopeFromDataTypeElement(DataType dataType) { CultureInfo locale = dataType.Locale ?? LocalizationScopeManager.CurrentLocalizationScope; return new DataScope(dataType.DataScopeIdentifier, locale); } private void RegisterKeyToBeAdded(DataType dataType, DataTypeDescriptor dataTypeDescriptor, DataKeyPropertyCollection dataKeyPropertyCollection) { if (dataKeyPropertyCollection.Count != 1) return; TypeKeyInstallationData typeKeyInstallationData; if (dataType.InterfaceType != null) { // Static types typeKeyInstallationData = _dataKeysToBeInstalled.GetOrAdd(dataType.InterfaceType, () => new TypeKeyInstallationData(dataType.InterfaceType)); } else { // Dynamic types typeKeyInstallationData = _dataKeysToBeInstalledByTypeId.GetOrAdd(dataTypeDescriptor.DataTypeId, () => new TypeKeyInstallationData(dataTypeDescriptor)); } var keyValuePair = dataKeyPropertyCollection.KeyProperties.First(); typeKeyInstallationData.RegisterKeyUsage(dataType, keyValuePair); } private void ValidateDynamicAddedType(DataType dataType) { DataTypeDescriptor dataTypeDescriptor = this.InstallerContext.GetPendingDataTypeDescriptor(dataType.InterfaceTypeName); if (dataTypeDescriptor == null) { _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.MissingTypeDescriptor").FormatWith(dataType.InterfaceTypeName)); return; } bool dataTypeLocalized = dataTypeDescriptor.SuperInterfaces.Contains(typeof (ILocalizedControlled)); if (!ValidateTargetLocaleInfo(dataType, dataTypeLocalized)) { return; } foreach (XElement addElement in dataType.Dataset) { var dataKeyPropertyCollection = new DataKeyPropertyCollection(); bool propertyValidationPassed = true; var fieldValues = new Dictionary(); foreach (XAttribute attribute in addElement.Attributes()) { string fieldName = attribute.Name.LocalName; // A compatibility fix if (IsObsoleteField(dataTypeDescriptor, fieldName)) { continue; } DataFieldDescriptor dataFieldDescriptor = dataTypeDescriptor.Fields[fieldName]; if (dataFieldDescriptor == null) { _validationResult.AddFatal(Texts.DataPackageFragmentInstaller_MissingProperty(dataTypeDescriptor, fieldName)); propertyValidationPassed = false; continue; } object fieldValue; try { fieldValue = ValueTypeConverter.Convert(attribute.Value, dataFieldDescriptor.InstanceType); } catch (Exception) { _validationResult.AddFatal(Texts.DataPackageFragmentInstaller_ConversionFailed(attribute.Value, dataFieldDescriptor.InstanceType)); propertyValidationPassed = false; continue; } if (dataTypeDescriptor.KeyPropertyNames.Contains(fieldName)) { dataKeyPropertyCollection.AddKeyProperty(fieldName, fieldValue); } fieldValues.Add(fieldName, fieldValue); } if (!propertyValidationPassed) { continue; } if (!dataType.AllowOverwrite && !dataType.OnlyUpdate) { // TODO: implement check if the same key has already been added } RegisterKeyToBeAdded(dataType, dataTypeDescriptor, dataKeyPropertyCollection); // Checking foreign key references foreach (var referenceField in dataTypeDescriptor.Fields.Where(f => f.ForeignKeyReferenceTypeName != null)) { if (!fieldValues.TryGetValue(referenceField.Name, out object propertyValue) || propertyValue == null || (propertyValue is Guid guid && guid == Guid.Empty) || (propertyValue is string str && str == "")) { continue; } string referredTypeName = referenceField.ForeignKeyReferenceTypeName; var referredType = TypeManager.TryGetType(referredTypeName); if (referredType == null) { // TODO: implement reference check for dynamic types as well continue; } string targetKeyPropertyName = referredType.GetKeyPropertyNames().SingleOrDefault(); CheckForBrokenReference(dataType, referredType, targetKeyPropertyName, propertyValue); } } } private bool ValidateTargetLocaleInfo(DataType dataType, bool dataTypeLocalized) { bool localeInfoSpecified = dataType.Locale != null || dataType.AddToAllLocales || dataType.AddToCurrentLocale; if (dataTypeLocalized && !localeInfoSpecified) { _validationResult.AddFatal(Texts.DataPackageFragmentInstaller_TypeLocalizedWithoutLocale(dataType.InterfaceType)); return false; } if (!dataTypeLocalized && localeInfoSpecified) { _validationResult.AddFatal(Texts.DataPackageFragmentInstaller_TypeNonLocalizedWithLocale(dataType.InterfaceType)); return false; } return true; } [DebuggerDisplay("{InterfaceTypeName}")] private sealed class DataType { public string InterfaceTypeName { get; set; } public Type InterfaceType { get; set; } public DataScopeIdentifier DataScopeIdentifier { get; set; } public CultureInfo Locale { get; set; } public bool AddToAllLocales { get; set; } public bool AddToCurrentLocale { get; set; } public bool IsDynamicAdded { get; set; } public bool OnlyUpdate { get; set; } public bool AllowOverwrite { get; set; } public IEnumerable Dataset { get; set; } } /// /// Information about data keys to be installed for a given data type /// [DebuggerDisplay("TypeKeyInstallationData {_typeName} . DataScopes: {_dataScopes.Count}")] private class TypeKeyInstallationData { private const string AllLocalesKey = "all"; private readonly bool _isLocalized; private readonly bool _isPublishable; private readonly string _typeName; private readonly Dictionary>> _dataScopes = new Dictionary>>(); public TypeKeyInstallationData(Type type) { _isLocalized = DataLocalizationFacade.IsLocalized(type); _isPublishable = typeof(IPublishControlled).IsAssignableFrom(type); _typeName = type.FullName; } public TypeKeyInstallationData(DataTypeDescriptor typeDescriptor) { _isLocalized = typeDescriptor.SuperInterfaces.Contains(typeof(ILocalizedControlled)); _isPublishable = typeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled)); _typeName = typeDescriptor.Name; } public void RegisterKeyUsage(DataType dataType, KeyValuePair keyValuePair) { var dataScopeIdentifier = dataType.DataScopeIdentifier; if (!_isLocalized) { RegisterKeyUsage(dataType, "", dataScopeIdentifier, keyValuePair); return; } if (dataType.AddToCurrentLocale) { RegisterKeyUsage(dataType, LocalizationScopeManager.CurrentLocalizationScope.Name, dataScopeIdentifier, keyValuePair); return; } if (dataType.Locale != null) { RegisterKeyUsage(dataType, dataType.Locale.Name, dataScopeIdentifier, keyValuePair); return; } if (dataType.AddToAllLocales) { RegisterKeyUsage(dataType, AllLocalesKey, dataScopeIdentifier, keyValuePair); return; } throw new InvalidOperationException("Type is localized but no localization info specified"); } private void RegisterKeyUsage(DataType dataType, string localeName, DataScopeIdentifier publicationScope, KeyValuePair keyValuePair) { string dataScopeKey = GetDataScopeKey(publicationScope, localeName); var hashset = _dataScopes.GetOrAdd(dataScopeKey, () => new HashSet>()); Verify.That(!hashset.Contains(keyValuePair), "Item with the same key present twice. Data type: '{0}', field '{1}', value '{2}'", dataType.InterfaceTypeName ?? dataType.InterfaceTypeName ?? "null", keyValuePair.Key, keyValuePair.Value ?? "null"); hashset.Add(keyValuePair); } public bool KeyRegistered(DataType refereeDataType, KeyValuePair keyValuePair) { var dataScopeIdentifier = refereeDataType.DataScopeIdentifier; if (!_isLocalized) { return KeyRegistered(dataScopeIdentifier, "", keyValuePair); } if (KeyRegistered(refereeDataType.DataScopeIdentifier, AllLocalesKey, keyValuePair)) { return true; } if (refereeDataType.Locale != null) { return KeyRegistered(refereeDataType.DataScopeIdentifier, refereeDataType.Locale.Name, keyValuePair); } var currentLocale = LocalizationScopeManager.CurrentLocalizationScope; if (refereeDataType.AddToCurrentLocale) { return KeyRegistered(refereeDataType.DataScopeIdentifier, currentLocale.Name, keyValuePair); } if (DataLocalizationFacade.ActiveLocalizationCultures.Count() == 1 && KeyRegistered(refereeDataType.DataScopeIdentifier, currentLocale.Name, keyValuePair)) { return true; } return false; } private bool KeyRegistered(DataScopeIdentifier publicationScope, string languageName, KeyValuePair keyValuePair) { HashSet> hashset; if (languageName != AllLocalesKey && _isLocalized) { hashset = GetDataset(publicationScope, languageName); if (hashset != null && hashset.Contains(keyValuePair)) { return true; } } hashset = GetDataset(publicationScope, AllLocalesKey); return hashset != null && hashset.Contains(keyValuePair); } private HashSet> GetDataset(DataScopeIdentifier publicationScope, string localizationScope) { string key = GetDataScopeKey(publicationScope, localizationScope); return _dataScopes.ContainsKey(key) ? _dataScopes[key] : null; } private string GetDataScopeKey(DataScopeIdentifier publicationScope, string languageName) { string publicationScopeKey = _isPublishable ? publicationScope.Name : string.Empty; string languageScopeKey = _isLocalized ? languageName : string.Empty; return publicationScopeKey + languageScopeKey; } } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/DataPackageFragmentUninstaller.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Xml.Linq; using Composite.Core.Extensions; using Composite.Data; using Composite.Data.ProcessControlled; using Composite.Core.Types; using Composite.Data.Types; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Core_PackageSystem_PackageFragmentInstallers; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DataPackageFragmentUninstaller : BasePackageFragmentUninstaller { private List _dataToDelete; /// public override IEnumerable Validate() { var validationResult = new List(); if (this.Configuration.Count(f => f.Name == "Types") > 1) { validationResult.AddFatal(Texts.DataPackageFragmentUninstaller_OnlyOneElement); return validationResult; } _dataToDelete = new List(); XElement typesElement = this.Configuration.SingleOrDefault(f => f.Name == "Types"); if (typesElement == null) { return validationResult; } foreach (XElement typeElement in typesElement.Elements("Type").Reverse()) { XAttribute typeAttribute = typeElement.Attribute("type"); XAttribute dataScopeIdentifierAttribute = typeElement.Attribute("dataScopeIdentifier"); if (typeAttribute == null) { validationResult.AddFatal(Texts.DataPackageFragmentUninstaller_MissingAttribute("type"), typeElement); continue; } if (dataScopeIdentifierAttribute == null) { validationResult.AddFatal(Texts.DataPackageFragmentUninstaller_MissingAttribute("dataScopeIdentifier"), typeElement); continue; } Type type = TypeManager.TryGetType(typeAttribute.Value); if (type == null) continue; if (!DataFacade.GetAllInterfaces().Contains(type)) continue; DataScopeIdentifier dataScopeIdentifier; try { dataScopeIdentifier = DataScopeIdentifier.Deserialize(dataScopeIdentifierAttribute.Value); } catch (Exception) { validationResult.AddFatal("Wrong DataScopeIdentifier ({0}) name in the configuration".FormatWith(dataScopeIdentifierAttribute.Value), dataScopeIdentifierAttribute); continue; } foreach (XElement datasElement in typeElement.Elements("Datas").Reverse()) { CultureInfo locale = null; XAttribute localeAttribute = datasElement.Attribute("locale"); if (localeAttribute != null) { locale = CultureInfo.CreateSpecificCulture(localeAttribute.Value); } foreach (XElement keysElement in datasElement.Elements("Keys").Reverse()) { bool allKeyPropertiesValidated = true; var dataKeyPropertyCollection = new DataKeyPropertyCollection(); foreach (XElement keyElement in keysElement.Elements("Key")) { XAttribute keyNameAttribute = keyElement.Attribute("name"); XAttribute keyValueAttribute = keyElement.Attribute("value"); if (keyNameAttribute == null || keyValueAttribute == null) { if (keyNameAttribute == null) validationResult.AddFatal(GetText("DataPackageFragmentUninstaller.MissingAttribute").FormatWith("name"), keyElement); if (keyValueAttribute == null) validationResult.AddFatal(GetText("DataPackageFragmentUninstaller.MissingAttribute").FormatWith("value"), keyElement); allKeyPropertiesValidated = false; continue; } string keyName = keyNameAttribute.Value; PropertyInfo keyPropertyInfo = type.GetPropertiesRecursively().SingleOrDefault(f => f.Name == keyName); if (keyPropertyInfo == null) { validationResult.AddFatal(GetText("DataPackageFragmentUninstaller.MissingKeyProperty").FormatWith(type, keyName)); allKeyPropertiesValidated = false; } else { try { object keyValue = ValueTypeConverter.Convert(keyValueAttribute.Value, keyPropertyInfo.PropertyType); dataKeyPropertyCollection.AddKeyProperty(keyName, keyValue); } catch (Exception) { allKeyPropertiesValidated = false; validationResult.AddFatal(GetText("DataPackageFragmentUninstaller.DataPackageFragmentUninstaller").FormatWith(keyValueAttribute.Value, keyPropertyInfo.PropertyType)); } } } if (allKeyPropertiesValidated) { IData data; using (new DataScope(dataScopeIdentifier, locale)) { data = DataFacade.TryGetDataByUniqueKey(type, dataKeyPropertyCollection); } if (data != null) { CheckForPotentialBrokenReferences(data, validationResult, type, dataScopeIdentifier, locale, dataKeyPropertyCollection); } } } } } if (validationResult.Count > 0) { _dataToDelete = null; } return validationResult; } private void CheckForPotentialBrokenReferences(IData data, List validationResult, Type type, DataScopeIdentifier dataScopeIdentifier, CultureInfo locale, DataKeyPropertyCollection dataKeyPropertyCollection) { var pagesReferencingPageTypes = new HashSet(); var dataReferencingDataToBeUninstalled = new HashSet(); List referees = data.GetReferees(); bool addToDelete = true; foreach (IData referee in referees) { if (this.UninstallerContext.IsPendingForDeletionData(referee)) { continue; } addToDelete = false; if (referee is IPage && data is IPageType) { string pathToPage; using (new DataScope(referee.DataSourceId.PublicationScope, referee.DataSourceId.LocaleScope)) { pathToPage = GetPathToPage(referee as IPage); } if (!pagesReferencingPageTypes.Contains(pathToPage)) { validationResult.AddFatal(Texts.DataPackageFragmentUninstaller_PageTypeIsReferenced( data.GetLabel(), pathToPage)); pagesReferencingPageTypes.Add(pathToPage); } } else { var refereeType = referee.DataSourceId.InterfaceType; string label = referee.GetLabel(); string key = label + refereeType.FullName; if (!dataReferencingDataToBeUninstalled.Contains(key)) { validationResult.AddFatal(Texts.DataPackageFragmentUninstaller_DataIsReferenced( data.GetLabel(), type.FullName, label, refereeType.FullName)); dataReferencingDataToBeUninstalled.Add(key); } } } if (addToDelete) { AddDataToDelete(type, dataScopeIdentifier, locale, dataKeyPropertyCollection); } } private static string GetPathToPage(IPage page) { var parentPageId = PageManager.GetParentId(page.Id); if (parentPageId != Guid.Empty) { var parentPage = PageManager.GetPageById(parentPageId); if (parentPage != null) { return GetPathToPage(parentPage) + "/" + page.Title; } } return page.Title; } /// public override void Uninstall() { Verify.IsNotNull(_dataToDelete, "DataPackageFragmentUninstaller has not been validated"); foreach (DataType dataType in _dataToDelete) { using (new DataScope(dataType.DataScopeIdentifier, dataType.Locale)) { Log.LogVerbose("DataPackageFragmentUninstaller", "Uninstalling data for the type '{0}'", dataType.InterfaceType); foreach (DataKeyPropertyCollection dataKeyPropertyCollection in dataType.DataKeys) { IData data = DataFacade.TryGetDataByUniqueKey(dataType.InterfaceType, dataKeyPropertyCollection); if (data == null) { continue; } using (ProcessControllerFacade.NoProcessControllers) { DataFacade.Delete(data, CascadeDeleteType.Disable); } } } } } private void AddDataToDelete(Type interfaceType, DataScopeIdentifier dataScopeIdentifier, CultureInfo locale, DataKeyPropertyCollection dataKeyPropertyCollection) { DataType dataType = _dataToDelete.SingleOrDefault(dt => dt.InterfaceType == interfaceType && dt.DataScopeIdentifier.Equals(dataScopeIdentifier) && ((dt.Locale == null && locale == null) || (dt.Locale != null && dt.Locale.Equals(locale)))); if (dataType == null) { dataType = new DataType { InterfaceType = interfaceType, DataScopeIdentifier = dataScopeIdentifier, Locale = locale }; _dataToDelete.Add(dataType); } dataType.DataKeys.Add(dataKeyPropertyCollection); this.UninstallerContext.AddPendingForDeletionData(interfaceType, dataScopeIdentifier, locale, dataKeyPropertyCollection); } private static string GetText(string stringId) { return GetResourceString(stringId); } private sealed class DataType { public DataType() { this.DataKeys = new List(); } public Type InterfaceType { get; set; } public DataScopeIdentifier DataScopeIdentifier { get; set; } public CultureInfo Locale { get; set; } public List DataKeys { get; set; } } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/DataTypePackageFragmentInstaller.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.Core.Extensions; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.C1Console.Events; using Composite.Core.Types; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// Creates data stores for static data types. Can be used in combination with to install content. /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DataTypePackageFragmentInstaller : BasePackageFragmentInstaller { private List _typesToInstall = null; private static readonly string LogTitle = typeof (DataTypePackageFragmentInstaller).FullName; /// public override IEnumerable Validate() { var validationResult = new List(); if (this.Configuration.Count(f => f.Name == "Types") > 1) { validationResult.AddFatal(GetText("DataTypePackageFragmentInstaller.OnlyOneElement")); return validationResult; } XElement typesElement = this.Configuration.SingleOrDefault(f => f.Name == "Types"); if (typesElement == null) { validationResult.AddFatal(GetText("DataTypePackageFragmentInstaller.MissingElement")); return validationResult; } _typesToInstall = new List(); foreach (XElement typeElement in typesElement.Elements("Type")) { XAttribute nameAttribute = typeElement.Attribute("name"); if (nameAttribute == null) { validationResult.AddFatal(GetText("DataTypePackageFragmentInstaller.MissingAttribute").FormatWith("name"), typeElement); continue; } Type type = TypeManager.TryGetType(nameAttribute.Value); if (type == null) { validationResult.AddFatal(GetText("DataTypePackageFragmentInstaller.TypeNotConfigured").FormatWith(nameAttribute.Value)); } else if (!typeof(IData).IsAssignableFrom(type)) { validationResult.AddFatal(GetText("DataTypePackageFragmentInstaller.TypeNotInheriting").FormatWith(type, typeof(IData))); } else if (DataFacade.GetAllKnownInterfaces().Contains(type)) { validationResult.AddFatal(GetText("DataTypePackageFragmentInstaller.TypeExists").FormatWith(type)); } else { DataTypeDescriptor dataTypeDescriptor = null; try { dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(type); dataTypeDescriptor.Validate(); } catch(Exception ex) { validationResult.AddFatal(GetText("DataTypePackageFragmentInstaller.InterfaceCodeError").FormatWith(type)); validationResult.AddFatal(ex); Log.LogError(LogTitle, ex); } if (dataTypeDescriptor != null) { _typesToInstall.Add(dataTypeDescriptor); this.InstallerContext.AddPendingDataType(type); } } } if (validationResult.Count > 0) { _typesToInstall = null; } return validationResult; } /// public override IEnumerable Install() { Verify.IsNotNull(_typesToInstall, "DataTypePackageFragmentInstaller has not been validated"); string typeNames = string.Join(", ", _typesToInstall.Select(t => t.GetFullInterfaceName())); Log.LogVerbose(this.GetType().Name, "Installing types: '{0}'", typeNames); DynamicTypeManager.CreateStores(_typesToInstall, false); var typeElements = new List(); foreach (var dataTypeDescriptor in _typesToInstall) { var typeElement = new XElement("Type", new XAttribute("typeId", dataTypeDescriptor.DataTypeId)); typeElements.Add(typeElement); } GlobalEventSystemFacade.FlushTheSystem(true); yield return new XElement("Types", typeElements); } private static string GetText(string stringId) { return GetResourceString(stringId); } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/DataTypePackageFragmentUninstaller.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.C1Console.Events; using Composite.Core.Extensions; using Composite.Core.Xml; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DataTypePackageFragmentUninstaller : BasePackageFragmentUninstaller { private List _dataTypeDescriptorsToDelete; private List _validationResult; /// public override bool ValidateFirst { get { return true; } } /// public override IEnumerable Validate() { _validationResult = new List(); if (this.Configuration.Count(f => f.Name == "Types") > 1) { _validationResult.AddFatal(GetText("DataTypePackageFragmentUninstaller.OnlyOneElement")); return _validationResult; } XElement typesElement = this.Configuration.SingleOrDefault(f => f.Name == "Types"); _dataTypeDescriptorsToDelete = new List(); if (typesElement != null) { foreach (XElement typeElement in typesElement.Elements("Type").Reverse()) { XAttribute typeIdAttribute = typeElement.Attribute("typeId"); if (typeIdAttribute == null) { _validationResult.AddFatal(GetText("DataTypePackageFragmentUninstaller.MissingAttribute").FormatWith("typeId")); continue; } Guid typeId; if (!typeIdAttribute.TryGetGuidValue(out typeId)) { _validationResult.AddFatal(GetText("DataTypePackageFragmentUninstaller.WrongAttributeFormat"), typeIdAttribute); continue; } var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(typeId); if (dataTypeDescriptor == null) { continue; } _dataTypeDescriptorsToDelete.Add(dataTypeDescriptor); Type intefaceType = dataTypeDescriptor.GetInterfaceType(); var foreignRefereeTypes = DataReferenceFacade.GetRefereeTypes(intefaceType) .Where(f => !_dataTypeDescriptorsToDelete.Any(g => g.GetInterfaceType() == f)); foreach (Type foreignRefereeType in foreignRefereeTypes) { _validationResult.Add(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format("Data type '{0}' has references to type '{1}' about to be uninstalled. References must be removed before the package can be uninstalled.", foreignRefereeType, dataTypeDescriptor.TypeManagerTypeName), typeIdAttribute)); } UninstallerContext.AddPendingForDeletionDataType(intefaceType); } } if (_validationResult.Count > 0) { _dataTypeDescriptorsToDelete = null; } return _validationResult; } /// public override void Uninstall() { Verify.IsNotNull(_dataTypeDescriptorsToDelete, "DataTypePackageFragmentUninstaller has not been validated"); bool flushTheSystem = false; foreach (DataTypeDescriptor dataTypeDescriptor in _dataTypeDescriptorsToDelete) { Log.LogVerbose(this.GetType().Name, "Uninstalling the type '{0}'", dataTypeDescriptor); GeneratedTypesFacade.DeleteType(dataTypeDescriptor, false); flushTheSystem = true; } if (flushTheSystem) { GlobalEventSystemFacade.FlushTheSystem(true); } } private static string GetText(string stringId) { return GetResourceString(stringId); } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/DllPackageFragmentInstaller.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Xml.Linq; using Composite.Core.IO; using Composite.Core.Xml; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Core_PackageSystem_PackageFragmentInstallers; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// Installs a dll file. If there's already a dll with the same name, will override it only if the installed version is newer, /// also will add/update and assembly binding for the dll in web.config to ensure that the system will run. /// The specified dll files will not be uninstalled automatically to avoid potential website crash. /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DllPackageFragmentInstaller : BasePackageFragmentInstaller { private List _filesToCopy; private static readonly string LogTitle = nameof(DllPackageFragmentInstaller); /// public override IEnumerable Validate() { var validationResult = new List(); if (this.Configuration.Count(f => f.Name == "Files") > 1) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_OnlyOneFilesElement, this.ConfigurationParent); return validationResult; } XElement filesElement = this.Configuration.SingleOrDefault(f => f.Name == "Files"); _filesToCopy = new List(); if (filesElement != null) { foreach (XElement fileElement in filesElement.Elements("File")) { XAttribute sourceFilenameAttribute = fileElement.Attribute("sourceFilename"); XAttribute targetFilenameAttribute = fileElement.Attribute("targetFilename"); if (sourceFilenameAttribute == null) { validationResult.AddFatal( Texts.FilePackageFragmentInstaller_MissingAttribute("sourceFilename"), fileElement); continue; } if (targetFilenameAttribute == null) { validationResult.AddFatal( Texts.FilePackageFragmentInstaller_MissingAttribute("targetFilename"), fileElement); continue; } XAttribute allowOverwriteAttribute = fileElement.Attribute("allowOverwrite"); XAttribute assemblyLoadAttribute = fileElement.Attribute("assemblyLoad"); XAttribute onlyUpdateAttribute = fileElement.Attribute("onlyUpdate"); XAttribute addAssemblyBindingAttribute = fileElement.Attribute("addAssemblyBinding"); bool allowOverwrite = false; if (!ParseBoolAttribute(allowOverwriteAttribute, validationResult, ref allowOverwrite)) { continue; } bool loadAssembly = false; if (!ParseBoolAttribute(assemblyLoadAttribute, validationResult, ref loadAssembly)) { continue; } bool onlyUpdate = false; if (!ParseBoolAttribute(onlyUpdateAttribute, validationResult, ref onlyUpdate)) { continue; } bool addAssemblyBinding = false; if (!ParseBoolAttribute(addAssemblyBindingAttribute, validationResult, ref addAssemblyBinding)) { continue; } string sourceFilename = sourceFilenameAttribute.Value; if (!this.InstallerContext.ZipFileSystem.ContainsFile(sourceFilename)) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_MissingFile(sourceFilename), sourceFilenameAttribute); continue; } if (loadAssembly && onlyUpdate) { validationResult.AddFatal( Texts.FilePackageFragmentInstaller_OnlyUpdateNotAllowedWithLoadAssemlby, onlyUpdateAttribute); continue; } string targetFilename = PathUtil.Resolve(targetFilenameAttribute.Value); if (C1File.Exists(targetFilename)) { if (!allowOverwrite && !onlyUpdate) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_FileExists(targetFilename), targetFilenameAttribute); continue; } if (((C1File.GetAttributes(targetFilename) & FileAttributes.ReadOnly) > 0) && !allowOverwrite) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_FileReadOnly(targetFilename), targetFilenameAttribute); continue; } } else if (onlyUpdate) { Log.LogVerbose(LogTitle, "Skipping updating of the file '{0}' because it does not exist", targetFilename); continue; // Target file does not, so skip this } var fileToCopy = new FileToCopy { SourceFilename = sourceFilename, TargetRelativeFilePath = targetFilenameAttribute.Value, TargetFilePath = targetFilename, Overwrite = allowOverwrite || onlyUpdate, AddAssemblyBinding = addAssemblyBinding }; _filesToCopy.Add(fileToCopy); if (loadAssembly) { string tempFilename = Path.Combine(this.InstallerContext.TempDirectory, Path.GetFileName(targetFilename)); this.InstallerContext.ZipFileSystem.WriteFileToDisk(sourceFilename, tempFilename); PackageAssemblyHandler.AddAssembly(tempFilename); } } } if (validationResult.Count > 0) { _filesToCopy = null; } return validationResult; } private static bool ParseBoolAttribute(XAttribute attribute, List validationResult, ref bool resultValue) { if (attribute == null) return true; if (!attribute.TryGetBoolValue(out resultValue)) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_WrongAttributeBoolFormat, attribute); return false; } return true; } /// public override IEnumerable Install() { Verify.IsNotNull(_filesToCopy, "{0} has not been validated", this.GetType().Name); var asmBindingsToAdd = new List(); var fileElements = new List(); foreach (FileToCopy fileToCopy in _filesToCopy) { Log.LogVerbose(LogTitle, "Installing the file '{0}' to the target filename '{1}'", fileToCopy.SourceFilename, fileToCopy.TargetFilePath); // Extracting the dll file so version can be checked string tempFileName = Path.Combine(InstallerContext.TempDirectory, Path.GetRandomFileName()); this.InstallerContext.ZipFileSystem.WriteFileToDisk(fileToCopy.SourceFilename, tempFileName); // Checking for dll version here: var sourceAssemblyName = GetAssemblyNameWithErrorText(tempFileName, () => $"Source file name: '{fileToCopy.SourceFilename}'"); var sourceAssemblyVersion = sourceAssemblyName.Version; var sourceFileVersion = GetDllFileVersion(tempFileName); string targetDirectory = Path.GetDirectoryName(fileToCopy.TargetFilePath); if (!Directory.Exists(targetDirectory)) { Directory.CreateDirectory(targetDirectory); } string backupFileName = null; bool addAssemblyBinding = fileToCopy.AddAssemblyBinding; if (C1File.Exists(fileToCopy.TargetFilePath) && fileToCopy.Overwrite) { var existingAssemblyName = GetAssemblyNameWithErrorText(fileToCopy.TargetFilePath, () => $"TargetFilePath: '{fileToCopy.TargetFilePath}' "); var existingAssemblyVersion = existingAssemblyName.Version; var existingFileVersion = GetDllFileVersion(fileToCopy.TargetFilePath); if (existingAssemblyVersion == sourceAssemblyVersion && existingFileVersion >= sourceFileVersion) { Log.LogInformation(LogTitle, "Skipping installation for file '{0}' version '{1}'. An assembly with the same version already exists.", fileToCopy.TargetRelativeFilePath, sourceAssemblyVersion); continue; } if (existingAssemblyVersion > sourceAssemblyVersion) { Log.LogInformation(LogTitle, "Skipping installation for file '{0}' version '{1}', as a file with a newer version '{2}' already exists.", fileToCopy.TargetRelativeFilePath, sourceAssemblyVersion, existingAssemblyVersion); continue; } addAssemblyBinding = existingAssemblyVersion < sourceAssemblyVersion; if ((C1File.GetAttributes(fileToCopy.TargetFilePath) & FileAttributes.ReadOnly) > 0) { FileUtils.RemoveReadOnly(fileToCopy.TargetFilePath); } if (InstallerContext.PackageInformation.CanBeUninstalled) { backupFileName = GetBackupFileName(fileToCopy.TargetFilePath); string backupFilesFolder = this.InstallerContext.PackageDirectory + "\\FileBackup"; C1Directory.CreateDirectory(backupFilesFolder); C1File.Copy(fileToCopy.TargetFilePath, backupFilesFolder + "\\" + backupFileName); } Log.LogInformation(LogTitle, "Overwriting existing file '{0}' version '{2}', new version is '{1}'", fileToCopy.TargetRelativeFilePath, sourceFileVersion, existingFileVersion); } if (addAssemblyBinding) { asmBindingsToAdd.Add(sourceAssemblyName); } File.Delete(fileToCopy.TargetFilePath); File.Move(tempFileName, fileToCopy.TargetFilePath); var fileElement = new XElement("File", new XAttribute("filename", fileToCopy.TargetRelativeFilePath), new XAttribute("version", sourceFileVersion)); if (backupFileName != null) { fileElement.Add(new XAttribute("backupFile", backupFileName)); } fileElements.Add(fileElement); } UpdateBindingRedirects(asmBindingsToAdd); yield return new XElement("Files", fileElements); } private AssemblyName GetAssemblyNameWithErrorText(string filePath, Func getErrorText) { try { return AssemblyName.GetAssemblyName(filePath); } catch (Exception ex) { throw new InvalidOperationException("Failed to read AssemblyName from a DLL. " + getErrorText(), ex); } } private Version GetDllFileVersion(string dllFilePath) { var fileVersionInfo = FileVersionInfo.GetVersionInfo(dllFilePath); return new Version( fileVersionInfo.FileMajorPart, fileVersionInfo.FileMinorPart, fileVersionInfo.FileBuildPart, fileVersionInfo.FilePrivatePart); } private void UpdateBindingRedirects(IEnumerable assemblyNames) { string webConfigPath = PathUtil.Resolve("~/web.config"); var webConfig = XDocument.Load(webConfigPath); var assemblyBindingConfig = new AssemblyBindingConfiguration(webConfig); foreach (var assemblyName in assemblyNames) { assemblyBindingConfig.AddRedirectsForAssembly(assemblyName); } assemblyBindingConfig.SaveIfChanged(webConfigPath); } private string GetBackupFileName(string targetFilePath) { string fileName = Path.GetFileName(targetFilePath); string directory = targetFilePath.Substring(0, targetFilePath.Length - fileName.Length); return directory.GetHashCode() + "_" + fileName; } private sealed class FileToCopy { public string SourceFilename { get; set; } public string TargetRelativeFilePath { get; set; } public string TargetFilePath { get; set; } public bool AddAssemblyBinding { get; set; } public bool Overwrite { get; set; } } private class AssemblyBindingConfiguration { private static readonly XNamespace AssemblyBindingXNamespace = "urn:schemas-microsoft-com:asm.v1"; private readonly XDocument _document; private readonly XElement _assemblyBindingElement; private bool _changed; public AssemblyBindingConfiguration(XDocument configFile) { _document = configFile; var root = configFile.Root; var runtimeElement = root.Element("runtime"); if (runtimeElement == null) { root.Add(runtimeElement = new XElement("runtime")); } var assemblyBindingXname = AssemblyBindingXNamespace + "assemblyBinding"; var assemblyBindingElement = runtimeElement.Element(assemblyBindingXname); if (assemblyBindingElement == null) { runtimeElement.Add(assemblyBindingElement = XElement.Parse(@"")); } _assemblyBindingElement = assemblyBindingElement; } private DependantAssembly[] GetDependantAssemblies() { return _assemblyBindingElement.Elements(AssemblyBindingXNamespace + "dependentAssembly") .Select(e => new DependantAssembly(e)) .ToArray(); } public void AddRedirectsForAssembly(AssemblyName assemblyName) { var version = assemblyName.Version; string newTargetVersionStr = assemblyName.Version.ToString(); var existingBinding = GetDependantAssemblies().FirstOrDefault(a => a.Name == assemblyName.Name); if (existingBinding != null) { var oldRedirectToStr = existingBinding.NewVersion; if (oldRedirectToStr == null) { return; } var oldRedirectToVersion = new Version(existingBinding.NewVersion); if (oldRedirectToVersion == version) { return; } existingBinding.OldVersion = "0.0.0.0-" + newTargetVersionStr; existingBinding.NewVersion = newTargetVersionStr; _changed = true; return; } string publicKeyToken = GetPublicKeyToken(assemblyName); if (publicKeyToken != null) { _assemblyBindingElement.Add(XElement.Parse(string.Format(@" ", assemblyName.Name, publicKeyToken, newTargetVersionStr)).Elements().Single()); _changed = true; } } private string GetPublicKeyToken(AssemblyName assemblyName) { byte[] publicKeyTokenBytes = assemblyName.GetPublicKeyToken(); return publicKeyTokenBytes == null || publicKeyTokenBytes.Length == 0 ? "null" : string.Join("", publicKeyTokenBytes.Select(b => $"{b:x2}")); } public void SaveIfChanged(string fileName) { if (!_changed) return; _document.Save(fileName); _changed = false; } internal class DependantAssembly { private readonly XElement _assemblyIdentity; private readonly XElement _bindingRedirect; public DependantAssembly(XElement innerElement) { XElement innerElement1 = innerElement; _assemblyIdentity = innerElement1.Element(AssemblyBindingXNamespace + "assemblyIdentity"); _bindingRedirect = innerElement1.Element(AssemblyBindingXNamespace + "bindingRedirect"); } public string Name { get { return _assemblyIdentity != null ? (string)_assemblyIdentity.Attribute("name") : null; } } public string NewVersion { get { return _bindingRedirect != null ? (string)_bindingRedirect.Attribute("newVersion") : null; } set { _bindingRedirect.SetAttributeValue("newVersion", value); } } public string OldVersion { get { return _bindingRedirect != null ? (string)_bindingRedirect.Attribute("oldVersion") : null; } set { _bindingRedirect.SetAttributeValue("oldVersion", value); } } } } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/DllPackageFragmentUninstaller.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using Composite.Core.Extensions; using Composite.Core.IO; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Core_PackageSystem_PackageFragmentInstallers; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DllPackageFragmentUninstaller : BasePackageFragmentUninstaller { private string LogTitle { get { return this.GetType().Name; }} private List _filesToDelete; private List _filesToCopy; private class FileToCopy { public string BackupFilePath; public string FilePath; public string RelativeFilePath; } /// public override IEnumerable Validate() { var validationResult = new List(); if (this.Configuration.Count(f => f.Name == "Files") > 1) { validationResult.AddFatal(Texts.FilePackageFragmentUninstaller_OnlyOneFilesElement, ConfigurationParent); return validationResult; } XElement filesElement = this.Configuration.SingleOrDefault(f => f.Name == "Files"); _filesToDelete = new List(); _filesToCopy = new List(); if (filesElement != null) { foreach (XElement fileElement in filesElement.Elements("File").Reverse()) { XAttribute filenameAttribute = fileElement.Attribute("filename"); if (filenameAttribute == null) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_MissingAttribute("filename"), fileElement); continue; } string relativeFilePath = filenameAttribute.Value; string filePath = PathUtil.Resolve(relativeFilePath); string backupFile = (string) fileElement.Attribute("backupFile"); if (backupFile != null) { var backupFilePath = Path.Combine(UninstallerContext.PackageDirectory, "FileBackup", backupFile); if (!C1File.Exists(backupFilePath)) { validationResult.AddFatal("Missing backup file '{0}'".FormatWith(backupFilePath), fileElement); continue; } _filesToCopy.Add(new FileToCopy { BackupFilePath = backupFilePath, FilePath = filePath, RelativeFilePath = relativeFilePath }); } else { _filesToDelete.Add(filePath); } } } if (validationResult.Count > 0) { _filesToDelete = null; _filesToCopy = null; } return validationResult; } /// public override void Uninstall() { Verify.IsNotNull(_filesToDelete as object ?? _filesToCopy, "{0} has not been validated", this.GetType().Name); foreach (string filename in _filesToDelete) { Log.LogInformation(LogTitle, "Not uninstalling file '{0}' to avoid potential compilation errors", filename); // Log.LogVerbose(LogTitle, "Uninstalling the file '{0}'", filename); // FileUtils.Delete(filename); } foreach (var fileToCopy in _filesToCopy) { Log.LogInformation(LogTitle, "Not restoring the original version of '{0}' file to avoid potential compilation errors", fileToCopy.RelativeFilePath); // Log.LogVerbose(LogTitle, "Restoring file from a backup copy'{0}'", fileToCopy.FilePath); //if ((C1File.GetAttributes(targetFile) & FileAttributes.ReadOnly) > 0) //{ // FileUtils.RemoveReadOnly(targetFile); //} //C1File.Copy(fileToCopy.BackupFilePath, targetFile, true); } } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/DynamicDataTypePackageFragmentInstaller.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; using Composite.Core.Extensions; using Composite.Core.Types; using Composite.Data.Types; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Core_PackageSystem_PackageFragmentInstallers; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DynamicDataTypePackageFragmentInstaller : BasePackageFragmentInstaller { private static readonly string LogTitle = typeof (DynamicDataTypePackageFragmentInstaller).Name; private List _dataTypeDescriptors = null; /// public override IEnumerable Validate() { var validationResult = new List(); var foreignKeyReferences = new List(); 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(); 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; } /// public override IEnumerable Install() { if (_dataTypeDescriptors == null) throw new InvalidOperationException(LogTitle + " has not been validated"); string typeNames = string.Join(", ", _dataTypeDescriptors.Select(d => d.GetFullInterfaceName())); Log.LogVerbose(this.GetType().Name, $"Installing types: '{typeNames}'"); GeneratedTypesFacade.GenerateNewTypes(_dataTypeDescriptors, true); var typeElements = _dataTypeDescriptors.Select(d => new XElement("Type", new XAttribute("typeId", d.DataTypeId))); yield return new XElement("Types", typeElements); } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/DynamicDataTypePackageFragmentUninstaller.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.C1Console.Events; using Composite.Core.Extensions; using Composite.Core.Types; using Composite.Core.Xml; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DynamicDataTypePackageFragmentUninstaller : BasePackageFragmentUninstaller { private List _dataTypeDescriptorsToDelete; private List _validationResult; /// public override bool ValidateFirst { get { return true; } } /// public override IEnumerable Validate() { _validationResult = new List(); if (this.Configuration.Count(f => f.Name == "Types") > 1) { _validationResult.AddFatal(GetText("DynamicDataTypePackageFragmentUninstaller.OnlyOneElement")); return _validationResult; } XElement typesElement = this.Configuration.SingleOrDefault(f => f.Name == "Types"); _dataTypeDescriptorsToDelete = new List(); if (typesElement != null) { foreach (XElement typeElement in typesElement.Elements("Type").Reverse()) { XAttribute typeIdAttribute = typeElement.Attribute("typeId"); if (typeIdAttribute == null) { _validationResult.AddFatal(GetText("DynamicDataTypePackageFragmentUninstaller.MissingAttribute").FormatWith("typeId"), typeElement); continue; } Guid typeId; if (!typeIdAttribute.TryGetGuidValue(out typeId)) { _validationResult.AddFatal(GetText("DynamicDataTypePackageFragmentUninstaller.WrongAttributeFormat"), typeIdAttribute); continue; } var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(typeId); if (dataTypeDescriptor == null) { continue; } _dataTypeDescriptorsToDelete.Add(dataTypeDescriptor); Type interfaceType = dataTypeDescriptor.GetInterfaceType(); var foreignRefereeTypes = DataReferenceFacade.GetRefereeTypes(interfaceType).Where(f => !_dataTypeDescriptorsToDelete.Any(g => g.GetInterfaceType() == f)); foreach (Type foreignRefereeType in foreignRefereeTypes) { // TODO: localize _validationResult.AddFatal(string.Format("Data type '{0}' has references to type '{1}' about to be uninstalled. References must be removed before the package can be uninstalled.", foreignRefereeType, dataTypeDescriptor.TypeManagerTypeName), typeIdAttribute); } UninstallerContext.AddPendingForDeletionDataType(interfaceType); } } if (_validationResult.Count > 0) { _dataTypeDescriptorsToDelete = null; } return _validationResult; } /// public override void Uninstall() { Verify.IsNotNull(_dataTypeDescriptorsToDelete, "DynamicDataTypePackageFragmentUninstaller has not been validated"); bool flushTheSystem = false; foreach (DataTypeDescriptor dataTypeDescriptor in _dataTypeDescriptorsToDelete) { Log.LogVerbose(this.GetType().Name, "Uninstalling the type '{0}'", dataTypeDescriptor); GeneratedTypesFacade.DeleteType(dataTypeDescriptor, false); flushTheSystem = true; } if (flushTheSystem) { CodeGenerationManager.GenerateCompositeGeneratedAssembly(true); } } private static string GetText(string stringId) { return GetResourceString(stringId); } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/FileModifyPackageFragmentInstaller.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.Core.IO; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Core_PackageSystem_PackageFragmentInstallers; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// Package installer for appending content to text files. /// /// ///<mi:Add installerType="Composite.Core.PackageSystem.PackageFragmentInstallers.FileModifyPackageFragmentInstaller, Composite" /// uninstallerType="Composite.Core.PackageSystem.PackageFragmentInstallers.FileModifyPackageFragmentUninstaller, Composite"> /// <AppendText path="~/sdfdsfds.css" whenNotExist="create"> <!-- whenNotExist="fail,create,ignore" --> /// Line 1 /// Line 2 /// Line 3 /// </AppendText> ///</mi:Add> /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class FileModifyPackageFragmentInstaller : BasePackageFragmentInstaller { private enum ActionOnMissingFile { Fail = 0, Create = 1, Ignore = 2 } internal static readonly string AppendText_ElementName = "AppendText"; internal static readonly string TargetXml_AttributeName = "path"; internal static readonly string WhenNotExist_AttributeName = "whenNotExist"; private List _contentToAdd; /// public override IEnumerable Validate() { var validationResult = new List(); _contentToAdd = new List(); foreach (var element in this.Configuration) { if (element.Name != AppendText_ElementName) { validationResult.AddFatal(Texts.PackageFragmentInstaller_IncorrectElement(element.Name.LocalName, AppendText_ElementName), element); continue; } var pathAttr = element.Attribute(TargetXml_AttributeName); if (pathAttr == null) { validationResult.AddFatal(Texts.PackageFragmentInstaller_MissingAttribute(TargetXml_AttributeName), element); continue; } string path = (string)pathAttr; var actionOnMissingFile = ActionOnMissingFile.Fail; var whenNotExistsAttr = element.Attribute(WhenNotExist_AttributeName); if (whenNotExistsAttr != null) { actionOnMissingFile = (ActionOnMissingFile) Enum.Parse(typeof (ActionOnMissingFile), whenNotExistsAttr.Value, true); } string filePath = PathUtil.Resolve(path); if (!C1File.Exists(filePath)) { if (actionOnMissingFile == ActionOnMissingFile.Fail) { validationResult.AddFatal(Texts.FileModifyPackageFragmentInstaller_FileDoesNotExist(filePath), pathAttr); continue; } if (actionOnMissingFile == ActionOnMissingFile.Ignore) { continue; } } _contentToAdd.Add(new ContentToAdd { Path = filePath, Content = element.Value }); } if (validationResult.Any()) { _contentToAdd = null; } return validationResult; } /// public override IEnumerable Install() { Verify.IsNotNull(_contentToAdd, "FileModifyPackageFragmentInstaller has not been validated"); foreach (ContentToAdd content in _contentToAdd) { if (C1File.Exists(content.Path)) { using (C1StreamWriter sw = C1File.AppendText(content.Path)) { sw.Write(content.Content); sw.Close(); } } else { C1File.WriteAllText(content.Path, content.Content); } } return new[] { this.Configuration.FirstOrDefault() }; } internal sealed class ContentToAdd { public string Path { get; set; } public string Content { get; set; } } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/FileModifyPackageFragmentUninstaller.cs ================================================ using System.Collections.Generic; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class FileModifyPackageFragmentUninstaller : BasePackageFragmentUninstaller { /// public override IEnumerable Validate() { return new List(); } /// public override void Uninstall() { } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/FilePackageFragmentInstaller.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using Composite.Core.IO; using Composite.Core.Xml; using Composite.Data; using System.Reflection; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Core_PackageSystem_PackageFragmentInstallers; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class FilePackageFragmentInstaller : BasePackageFragmentInstaller { private List _filesToCopy; private List _directoriesToDelete; private static readonly string LogTitle = typeof(FilePackageFragmentInstaller).Name; private static readonly string[] DllsNotToLoad = { "System.", "Microsoft.", "Antlr3.", "WebGrease", "Composite.Web.BundlingAndMinification" }; /// public override IEnumerable Validate() { var validationResult = new List(); if (this.Configuration.Count(f => f.Name == "Files") > 1) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_OnlyOneFilesElement, this.ConfigurationParent); return validationResult; } if (this.Configuration.Count(f => f.Name == "Directories") > 1) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_OnlyOneDirectoriesElement, this.ConfigurationParent); return validationResult; } XElement filesElement = this.Configuration.SingleOrDefault(f => f.Name == "Files"); XElement directoriesElement = this.Configuration.SingleOrDefault(f => f.Name == "Directories"); _filesToCopy = new List(); _directoriesToDelete = new List(); if (filesElement != null) { foreach (XElement fileElement in filesElement.Elements("File")) { XAttribute sourceFilenameAttribute = fileElement.Attribute("sourceFilename"); XAttribute targetFilenameAttribute = fileElement.Attribute("targetFilename"); if (sourceFilenameAttribute == null) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_MissingAttribute("sourceFilename"), fileElement); continue; } if (targetFilenameAttribute == null) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_MissingAttribute("targetFilename"), fileElement); continue; } XAttribute allowOverwriteAttribute = fileElement.Attribute("allowOverwrite"); XAttribute assemblyLoadAttribute = fileElement.Attribute("assemblyLoad"); XAttribute deleteTargetDirectoryAttribute = fileElement.Attribute("deleteTargetDirectory"); XAttribute onlyUpdateAttribute = fileElement.Attribute("onlyUpdate"); XAttribute onlyAddAttribute = fileElement.Attribute("onlyAdd"); if (deleteTargetDirectoryAttribute != null) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_DeleteTargetDirectoryNotAllowed, fileElement); continue; } bool allowOverwrite = false; if (!ParseBoolAttribute(allowOverwriteAttribute, validationResult, ref allowOverwrite)) { continue; } bool loadAssembly = false; if (!ParseBoolAttribute(assemblyLoadAttribute, validationResult, ref loadAssembly)) { continue; } bool onlyUpdate = false; if (!ParseBoolAttribute(onlyUpdateAttribute, validationResult, ref onlyUpdate)) { continue; } bool onlyAdd = false; if (!ParseBoolAttribute(onlyAddAttribute, validationResult, ref onlyAdd)) { continue; } string sourceFilename = sourceFilenameAttribute.Value; if (!this.InstallerContext.ZipFileSystem.ContainsFile(sourceFilename)) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_MissingFile(sourceFilename), sourceFilenameAttribute); continue; } if (loadAssembly && onlyUpdate) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_OnlyUpdateNotAllowedWithLoadAssemlby, onlyUpdateAttribute); continue; } if (onlyAdd && onlyUpdate) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_OnlyUpdateAndOnlyAddNotAllowed, onlyUpdateAttribute); continue; } if (onlyAdd && allowOverwrite) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_OnlyAddAndAllowOverwriteNotAllowed, onlyAddAttribute); continue; } string targetFilename = PathUtil.Resolve(targetFilenameAttribute.Value); if (C1File.Exists(targetFilename)) { if (onlyAdd) { Log.LogVerbose(LogTitle, "Skipping adding of the file '{0}' because it already exist and is marked 'onlyAdd'", targetFilename); continue; // Target file does not, so skip this } if (!allowOverwrite && !onlyUpdate) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_FileExists(targetFilename), targetFilenameAttribute); continue; } if (((C1File.GetAttributes(targetFilename) & FileAttributes.ReadOnly) > 0) && !allowOverwrite) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_FileReadOnly(targetFilename), targetFilenameAttribute); continue; } } else if (onlyUpdate) { Log.LogVerbose(LogTitle, "Skipping updating of the file '{0}' because it does not exist", targetFilename); continue; // Target file does not, so skip this } var fileToCopy = new FileToCopy { SourceFilename = sourceFilename, TargetRelativeFilePath = targetFilenameAttribute.Value, TargetFilePath = targetFilename, Overwrite = allowOverwrite || onlyUpdate }; _filesToCopy.Add(fileToCopy); if (loadAssembly) { string tempFilename = Path.Combine(this.InstallerContext.TempDirectory, Path.GetFileName(targetFilename)); this.InstallerContext.ZipFileSystem.WriteFileToDisk(sourceFilename, tempFilename); PackageAssemblyHandler.AddAssembly(tempFilename); } } } if (directoriesElement != null) { foreach (XElement directoryElement in directoriesElement.Elements("Directory")) { XAttribute sourceDirectoryAttribute = directoryElement.Attribute("sourceDirectory"); XAttribute targetDirectoryAttribute = directoryElement.Attribute("targetDirectory"); if (sourceDirectoryAttribute == null) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_MissingAttribute("sourceDirectory"), directoryElement); continue; } if (targetDirectoryAttribute == null) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_MissingAttribute("targetDirectory"), directoryElement); continue; } XAttribute allowOverwriteAttribute = directoryElement.Attribute("allowOverwrite"); XAttribute assemblyLoadAttribute = directoryElement.Attribute("assemblyLoad"); XAttribute deleteTargetDirectoryAttribute = directoryElement.Attribute("deleteTargetDirectory"); XAttribute onlyUpdateAttribute = directoryElement.Attribute("onlyUpdate"); if (assemblyLoadAttribute != null) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_AssemblyLoadNotAllowed, directoryElement); continue; } if (onlyUpdateAttribute != null) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_OnlyUpdateNotAllowed, directoryElement); continue; } bool allowOverwrite = false; if (!ParseBoolAttribute(allowOverwriteAttribute, validationResult, ref allowOverwrite)) { continue; } bool deleteTargetDirectory = false; if (!ParseBoolAttribute(deleteTargetDirectoryAttribute, validationResult, ref deleteTargetDirectory)) { continue; } string sourceDirectory = sourceDirectoryAttribute.Value; if (!this.InstallerContext.ZipFileSystem.ContainsDirectory(sourceDirectory)) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_MissingDirectory(sourceDirectory), sourceDirectoryAttribute); continue; } string targetDirectory = PathUtil.Resolve(targetDirectoryAttribute.Value); if (deleteTargetDirectory) { if (C1Directory.Exists(targetDirectory)) { _directoriesToDelete.Add(targetDirectory); } } foreach (string sourceFilename in this.InstallerContext.ZipFileSystem.GetFilenames(sourceDirectory)) { string resolvedSourceFilename = sourceFilename.Remove(0, sourceDirectory.Length); if (resolvedSourceFilename.StartsWith("/")) { resolvedSourceFilename = resolvedSourceFilename.Remove(0, 1); } string targetFilename = Path.Combine(targetDirectory, resolvedSourceFilename); if (C1File.Exists(targetFilename) && !deleteTargetDirectory && !allowOverwrite) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_FileExists(targetFilename), targetDirectoryAttribute); continue; } var fileToCopy = new FileToCopy { SourceFilename = sourceFilename, TargetRelativeFilePath = Path.Combine(targetDirectoryAttribute.Value, resolvedSourceFilename), TargetFilePath = targetFilename, Overwrite = allowOverwrite }; _filesToCopy.Add(fileToCopy); } } } if (validationResult.Count > 0) { _filesToCopy = null; _directoriesToDelete = null; } return validationResult; } private static bool ParseBoolAttribute(XAttribute attribute, List validationResult, ref bool resultValue) { if (attribute == null) return true; if (!attribute.TryGetBoolValue(out resultValue)) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_WrongAttributeBoolFormat, attribute); return false; } return true; } /// public override IEnumerable Install() { Verify.IsNotNull(_filesToCopy, "{0} has not been validated", this.GetType().Name); foreach (string directoryToDelete in _directoriesToDelete) { Directory.Delete(directoryToDelete, true); } var fileElements = new List(); foreach (FileToCopy fileToCopy in _filesToCopy) { Log.LogVerbose(LogTitle, "Installing the file '{0}' to the target filename '{1}'", fileToCopy.SourceFilename, fileToCopy.TargetFilePath); string targetDirectory = Path.GetDirectoryName(fileToCopy.TargetFilePath); if (!Directory.Exists(targetDirectory)) { Directory.CreateDirectory(targetDirectory); } string backupFileName = null; if (C1File.Exists(fileToCopy.TargetFilePath) && fileToCopy.Overwrite) { if ((C1File.GetAttributes(fileToCopy.TargetFilePath) & FileAttributes.ReadOnly) > 0) { FileUtils.RemoveReadOnly(fileToCopy.TargetFilePath); } if (InstallerContext.PackageInformation.CanBeUninstalled) { backupFileName = GetBackupFileName(fileToCopy.TargetFilePath); string backupFilesFolder = this.InstallerContext.PackageDirectory + "\\FileBackup"; C1Directory.CreateDirectory(backupFilesFolder); C1File.Copy(fileToCopy.TargetFilePath, backupFilesFolder + "\\" + backupFileName); } } this.InstallerContext.ZipFileSystem.WriteFileToDisk(fileToCopy.SourceFilename, fileToCopy.TargetFilePath); // Searching for static IData interfaces string targetFilePath = fileToCopy.TargetFilePath; if (targetFilePath.StartsWith(Path.Combine(PathUtil.BaseDirectory, "Bin"), StringComparison.InvariantCultureIgnoreCase) && targetFilePath.EndsWith(".dll", StringComparison.InvariantCultureIgnoreCase)) { LoadDataTypesFromDll(targetFilePath); } var fileElement = new XElement("File", new XAttribute("filename", fileToCopy.TargetRelativeFilePath)); if (backupFileName != null) { fileElement.Add(new XAttribute("backupFile", backupFileName)); } fileElements.Add(fileElement); } yield return new XElement("Files", fileElements); } private void LoadDataTypesFromDll(string filePath) { string fileName = Path.GetFileName(filePath); if (DllsNotToLoad.Any(fileName.StartsWith)) return; var assembly = PackageAssemblyHandler.TryGetAlreadyLoadedAssembly(filePath); if(assembly == null) { try { assembly = Assembly.LoadFrom(filePath); } catch (Exception) { return; } } DataTypeTypesManager.AddNewAssembly(assembly, false); } private string GetBackupFileName(string targetFilePath) { string fileName = Path.GetFileName(targetFilePath); string directory = targetFilePath.Substring(0, targetFilePath.Length - fileName.Length); return directory.GetHashCode() + "_" + fileName; } private sealed class FileToCopy { public string SourceFilename { get; set; } public string TargetRelativeFilePath { get; set; } public string TargetFilePath { get; set; } public bool Overwrite { get; set; } } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/FilePackageFragmentUninstaller.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using Composite.Core.Extensions; using Composite.Core.IO; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Core_PackageSystem_PackageFragmentInstallers; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class FilePackageFragmentUninstaller : BasePackageFragmentUninstaller { private string LogTitle { get { return this.GetType().Name; } } private List _filesToDelete; private List> _filesToCopy; /// public override IEnumerable Validate() { var validationResult = new List(); if (this.Configuration.Count(f => f.Name == "Files") > 1) { validationResult.AddFatal(Texts.FilePackageFragmentUninstaller_OnlyOneFilesElement, ConfigurationParent); return validationResult; } XElement filesElement = this.Configuration.SingleOrDefault(f => f.Name == "Files"); _filesToDelete = new List(); _filesToCopy = new List>(); // NOTE: Packages, that were installed on version earlier than C1 1.2 SP3 have absolute file path references, f.e.: // // // List absoluteReferences = new List(); if (filesElement != null) { foreach (XElement fileElement in filesElement.Elements("File").Reverse()) { XAttribute filenameAttribute = fileElement.Attribute("filename"); if (filenameAttribute == null) { validationResult.AddFatal(Texts.FilePackageFragmentInstaller_MissingAttribute("filename"), fileElement); continue; } string filePath = filenameAttribute.Value; if (filePath.Contains(":\\")) { absoluteReferences.Add(filePath); continue; } filePath = PathUtil.Resolve(filePath); string backupFile = (string) fileElement.Attribute("backupFile"); if (backupFile != null) { var backupFilePath = Path.Combine(UninstallerContext.PackageDirectory, "FileBackup", backupFile); if (!C1File.Exists(backupFilePath)) { validationResult.AddFatal("Missing backup file '{0}'".FormatWith(backupFilePath), fileElement); continue; } _filesToCopy.Add(new Tuple(backupFilePath, filePath)); } else { _filesToDelete.Add(filePath); } } } if(absoluteReferences.Count > 0) { // Trying to resolve what was the old absolute path. // To do that the longest common beginning is calculated string longestCommonBegining; string firstPath = absoluteReferences[0]; if (absoluteReferences.Count == 1) { longestCommonBegining = firstPath; } else { int shortestPathLength = absoluteReferences.Min(path => path.Length); int commonStartLength = 0; for (; commonStartLength < shortestPathLength; commonStartLength++) { bool match = true; char symbol = firstPath[commonStartLength]; for (int i = 1; i < absoluteReferences.Count; i++) { if (absoluteReferences[i][commonStartLength] != symbol) { match = false; break; } } if (!match) break; } longestCommonBegining = firstPath.Substring(0, commonStartLength); } longestCommonBegining = longestCommonBegining.Replace('/', '\\'); if(!longestCommonBegining.EndsWith("\\")) { longestCommonBegining = longestCommonBegining.Substring(0, longestCommonBegining.LastIndexOf("\\", StringComparison.Ordinal) + 1); } string newRoot = PathUtil.BaseDirectory; if(!newRoot.EndsWith("\\")) { newRoot += "\\"; } // If the site hasn't been moved to another folder, just using the pathes if (longestCommonBegining.StartsWith(newRoot, StringComparison.OrdinalIgnoreCase)) { _filesToDelete.AddRange(absoluteReferences); } else { // If the longest common path looks like C:\inetpub\docs\Frontend\Composite\ // than we will the following pathes as site roots: // // C:\inetpub\docs\Frontend\Composite\ // C:\inetpub\docs\Frontend\ // C:\inetpub\docs\ // C:\inetpub\ // C:\ string oldRoot = longestCommonBegining; bool fileExists = false; while(!string.IsNullOrEmpty(oldRoot)) { for(int i=0; i < absoluteReferences.Count; i++) { if(C1File.Exists(ReplaceFolder(absoluteReferences[0], oldRoot, newRoot))) { fileExists = true; break; } } if(fileExists) break; oldRoot = ReducePath(oldRoot); } if(!fileExists) { // Showing a message if we don't have a match validationResult.AddFatal(Texts.FilePackageFragmentInstaller_WrongBasePath); } else { _filesToDelete.AddRange(absoluteReferences.Select(path => ReplaceFolder(path, oldRoot, newRoot))); } } } if (validationResult.Count > 0) { _filesToDelete = null; _filesToCopy = null; } return validationResult; } private static string ReplaceFolder(string filePath, string oldFolderPath, string newFolderPath) { return newFolderPath + filePath.Substring(oldFolderPath.Length); } private static string ReducePath(string path) { // C:\A\B\ -> C:\A\ int offset = path.LastIndexOf('\\', path.Length - 2); if(offset < 0) return null; return path.Substring(0, offset + 1); } /// public override void Uninstall() { Verify.IsNotNull(_filesToDelete as object ?? _filesToCopy, "{0} has not been validated", this.GetType().Name); foreach (string filename in _filesToDelete) { Log.LogVerbose(LogTitle, "Uninstalling the file '{0}'", filename); FileUtils.Delete(filename); } foreach (var fileToCopy in _filesToCopy) { string targetFile = fileToCopy.Item2; Log.LogVerbose(LogTitle, "Restoring file from a backup copy'{0}'", targetFile); if ((C1File.GetAttributes(targetFile) & FileAttributes.ReadOnly) > 0) { FileUtils.RemoveReadOnly(targetFile); } C1File.Copy(fileToCopy.Item1, targetFile, true); } } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/FileXslTransformationPackageFragmentInstaller.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; using System.Xml.Xsl; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Xml; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Core_PackageSystem_PackageFragmentInstallers; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class FileXslTransformationPackageFragmentInstaller : BasePackageFragmentInstaller { private static readonly string LogTitle = "XsltPackageFragmentInstaller"; internal static readonly string TargetXmlAttributeName = "pathXml"; internal static readonly string InputXmlAttributeName = "inputXml"; internal static readonly string OutputXmlAttributeName = "outputXml"; internal static readonly string TargetXslAttributeName = "pathXsl"; internal static readonly string InstallXslAttributeName = "installXsl"; internal static readonly string UninstallXslAttributeName = "uninstallXsl"; internal static readonly string SkipIfNotExistAttributeName = "skipIfNotExist"; internal static readonly string OverrideReadOnlyAttributeName = "overrideReadOnly"; private List _xslTransformations; /// public override IEnumerable Validate() { _xslTransformations = new List(); var validationResult = new List(); var filesElement = this.ConfigurationParent.GetSingleConfigurationElement("XslFiles", validationResult, false); if (filesElement == null) { return validationResult; } foreach (XElement fileElement in filesElement.GetConfigurationElements("XslFile", validationResult)) { XAttribute pathXMLAttribute = fileElement.Attribute(TargetXmlAttributeName); XAttribute inputXMLAttribute = fileElement.Attribute(InputXmlAttributeName); XAttribute outputXMLAttribute = fileElement.Attribute(OutputXmlAttributeName); XAttribute pathXSLAttribute = fileElement.Attribute(TargetXslAttributeName); XAttribute installXSLAttribute = fileElement.Attribute(InstallXslAttributeName); XAttribute uninstallXSLAttribute = fileElement.Attribute(UninstallXslAttributeName); XAttribute overrideReadOnlyAttribute = fileElement.Attribute(OverrideReadOnlyAttributeName); XAttribute skipIfNotExistAttribute = fileElement.Attribute(SkipIfNotExistAttributeName); bool skipIfNotExist = skipIfNotExistAttribute != null && skipIfNotExistAttribute.Value.ToLower() == "true"; if (pathXSLAttribute == null && installXSLAttribute == null) { validationResult.AddFatal(Texts.PackageFragmentInstaller_MissingAttribute(TargetXmlAttributeName), fileElement); continue; } if (outputXMLAttribute != null && uninstallXSLAttribute != null) { validationResult.AddFatal("Xsl installer does not suppurt simultaneous usage of attributes '{0}' and '{1}'" .FormatWith(OutputXmlAttributeName, UninstallXslAttributeName), fileElement); continue; } string xslFilePath = (pathXSLAttribute ?? installXSLAttribute).Value; XslTransformation xslFile; if (inputXMLAttribute != null) { if (outputXMLAttribute == null) { validationResult.AddFatal(Texts.PackageFragmentInstaller_MissingAttribute("outputFilename"), fileElement); continue; } xslFile = new XslTransformation { XslPath = xslFilePath, InputXmlPath = inputXMLAttribute.Value, OutputXmlPath = outputXMLAttribute.Value }; } else { if (pathXMLAttribute == null) { validationResult.AddFatal(Texts.PackageFragmentInstaller_MissingAttribute(TargetXmlAttributeName), fileElement); continue; } string pathToXmlFile = pathXMLAttribute.Value; xslFile = new XslTransformation { XslPath = xslFilePath, // UninstallXslPath = uninstallXSLAttribute != null ? uninstallXSLAttribute.Value : null, InputXmlPath = pathToXmlFile, OutputXmlPath = pathToXmlFile }; } if (!C1File.Exists(PathUtil.Resolve(xslFile.InputXmlPath))) { if (skipIfNotExist) continue; validationResult.AddFatal(Texts.FileXslTransformationPackageFragmentInstaller_FileNotFound(xslFile.InputXmlPath), fileElement); continue; } string outputXmlFullPath = PathUtil.Resolve(xslFile.OutputXmlPath); if (C1File.Exists(outputXmlFullPath) && (C1File.GetAttributes(outputXmlFullPath) & FileAttributes.ReadOnly) > 0) { if (overrideReadOnlyAttribute == null || overrideReadOnlyAttribute.Value != "true") { validationResult.AddFatal(Texts.FileXslTransformationPackageFragmentInstaller_FileReadOnly(xslFile.OutputXmlPath), fileElement); continue; } FileUtils.RemoveReadOnly(outputXmlFullPath); Log.LogWarning(LogTitle, Texts.FileXslTransformationPackageFragmentInstaller_FileReadOnlyOverride(xslFile.OutputXmlPath)); } if (!PathUtil.WritePermissionGranted(outputXmlFullPath)) { validationResult.AddFatal(Texts.NotEnoughNtfsPermissions(xslFile.OutputXmlPath), fileElement); continue; } _xslTransformations.Add(xslFile); } if (validationResult.Count > 0) { _xslTransformations = null; } return validationResult; } /// public override IEnumerable Install() { if (_xslTransformations == null) throw new InvalidOperationException("FileXslTransformationPackageFragmentInstaller has not been validated"); Stream stream; foreach (XslTransformation xslfile in _xslTransformations) { string messageFormat = xslfile.InputXmlPath == xslfile.OutputXmlPath ? "Performing XSL-transformation. xml-file: '{1}'; xsl-file: '{0}'" : "Performing XSL-transformation. xsl-file: '{0}'; input xml file: '{1}'; output xml file: '{2}'"; Log.LogVerbose(LogTitle, string.Format(messageFormat, xslfile.XslPath, xslfile.InputXmlPath, xslfile.OutputXmlPath)); string inputXml = PathUtil.Resolve(xslfile.InputXmlPath); string outputXml = PathUtil.Resolve(xslfile.OutputXmlPath); using (stream = this.InstallerContext.ZipFileSystem.GetFileStream(xslfile.XslPath)) { var xslt = new XslCompiledTransform(); using (XmlReader xslReader = XmlReader.Create(stream)) { xslt.Load(xslReader); } var resultDocument = new XDocument(); using (XmlWriter writer = resultDocument.CreateWriter()) { xslt.Transform(inputXml, writer); } resultDocument.SaveToFile(outputXml); Log.LogVerbose(LogTitle, resultDocument.ToString()); } } return new[] { this.Configuration.FirstOrDefault() }; } private sealed class XslTransformation { public string XslPath { get; set; } public string InputXmlPath { get; set; } public string OutputXmlPath { get; set; } } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/FileXslTransformationPackageFragmentUninstaller.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Linq; using System.Xml.Xsl; using Composite.Core.IO; using Composite.Core.Xml; using Installer = Composite.Core.PackageSystem.PackageFragmentInstallers.FileXslTransformationPackageFragmentInstaller; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Core_PackageSystem_PackageFragmentInstallers; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class FileXslTransformationPackageFragmentUninstaller : BasePackageFragmentUninstaller { private List _xsls; /// public override IEnumerable Validate() { _xsls = new List(); var validationResult = new List(); var filesElement = this.ConfigurationParent.GetSingleConfigurationElement("XslFiles", validationResult, false); if (filesElement == null) { return validationResult; } foreach (XElement fileElement in filesElement.Elements("XslFile")) { XAttribute pathXMLAttribute = fileElement.Attribute(Installer.TargetXmlAttributeName); XAttribute pathXSLAttribute = fileElement.Attribute(Installer.UninstallXslAttributeName); if (pathXMLAttribute == null) { validationResult.AddFatal(Texts.PackageFragmentInstaller_MissingAttribute(Installer.TargetXmlAttributeName), fileElement); continue; } if (pathXSLAttribute == null) { //if there isn no uninstall xsl continue; } string inputPathXMLAttributeValue = PathUtil.Resolve(pathXMLAttribute.Value); string inpuPathXSLAttributeValue = pathXSLAttribute.Value; _xsls.Add(new XslTransformation { pathXml = inputPathXMLAttributeValue, pathXsl = inpuPathXSLAttributeValue }); } if (validationResult.Count > 0) { _xsls = null; } return validationResult; } /// public override void Uninstall() { if (_xsls == null) throw new InvalidOperationException("FileXslTransformationPackageFragmentUninstaller has not been validated"); Stream stream; foreach (XslTransformation xslfile in _xsls) { Log.LogVerbose("XsltPackageFragmentInstaller", string.Format("Performing XSL-transformation. xml-file: '{0}'; xsl-file: '{1}'", xslfile.pathXml, xslfile.pathXsl)); string xmlFilePath = PathUtil.Resolve(xslfile.pathXml); using (stream = this.UninstallerContext.ZipFileSystem.GetFileStream(xslfile.pathXsl)) { var xslt = new XslCompiledTransform(); using (XmlReader xslReader = XmlReader.Create(stream)) { xslt.Load(xslReader); } var resultDocument = new XDocument(); using (XmlWriter writer = resultDocument.CreateWriter()) { xslt.Transform(xmlFilePath, writer); } resultDocument.SaveToFile(xmlFilePath); Log.LogVerbose("XsltTransformationResult", resultDocument.ToString()); } } } private sealed class XslTransformation { public string pathXml { get; set; } public string pathXsl { get; set; } } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/LocalePackageFragmentInstaller.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Xml.Linq; using Composite.Core.Localization; using Composite.Core.Xml; using Composite.Data; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Core_PackageSystem_PackageFragmentInstallers; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// Adds a content language to console. /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class LocalePackageFragmentInstaller : BasePackageFragmentInstaller { private static readonly string LogTitle = typeof (LocalePackageFragmentInstaller).Name; List> _localesToInstall; /// public override IEnumerable Validate() { var validationResult = new List(); if (this.Configuration.Count(f => f.Name == "Locales") > 1) { validationResult.AddFatal(Texts.PackageFragmentInstaller_OnlyOneElementAllowed("Locales")); return validationResult; } XElement areasElement = this.Configuration.SingleOrDefault(f => f.Name == "Locales"); _localesToInstall = new List>(); if (areasElement != null) { foreach (XElement localeElement in areasElement.Elements("Locale")) { XAttribute nameAttribute = localeElement.Attribute("name"); XAttribute urlMappingNameAttribute = localeElement.Attribute("urlMappingName"); XAttribute defaultAttribute = localeElement.Attribute("default"); if (nameAttribute == null) { // Missing attribute validationResult.AddFatal(Texts.PackageFragmentInstaller_MissingAttribute("name"), localeElement); continue; } CultureInfo cultureInfo; try { cultureInfo = CultureInfo.CreateSpecificCulture(nameAttribute.Value); } catch { // Name error validationResult.AddFatal(Texts.PackageFragmentInstaller_MissingAttribute("name"), nameAttribute); continue; } if (LocalizationFacade.IsLocaleInstalled(cultureInfo)) { continue; // Skip it, it is installed } if (_localesToInstall.Any(f => f.Item1.Equals(cultureInfo))) { // Already installed or going to be installed validationResult.AddFatal(Texts.PackageFragmentInstaller_MissingAttribute("name"), nameAttribute); continue; } string urlMappingName = cultureInfo.Name; if (urlMappingNameAttribute != null) { urlMappingName = urlMappingNameAttribute.Value; } if (LocalizationFacade.IsUrlMappingNameInUse(urlMappingName) || _localesToInstall.Any(f => f.Item2 == urlMappingName)) { // Url mapping name already used or going to be used validationResult.AddFatal(Texts.PackageFragmentInstaller_MissingAttribute("urlMappingName"), urlMappingNameAttribute); continue; } bool isDefault = false; if (defaultAttribute != null) { if (!defaultAttribute.TryGetBoolValue(out isDefault)) { // Wrong attribute value validationResult.AddFatal(Texts.PackageFragmentInstaller_MissingAttribute("default"), defaultAttribute); continue; } } if (isDefault && _localesToInstall.Any(f => f.Item3)) { // More than one is specified as default validationResult.AddFatal(Texts.PackageFragmentInstaller_MissingAttribute("default"), defaultAttribute); continue; } _localesToInstall.Add(new Tuple(cultureInfo, urlMappingName, isDefault)); this.InstallerContext.AddPendingLocale(cultureInfo); } } if (validationResult.Count > 0) { _localesToInstall = null; } return validationResult; } /// public override IEnumerable Install() { Verify.IsNotNull(_localesToInstall, typeof(LocalePackageFragmentInstaller).Name + " has not been validated"); XAttribute oldDefaultAttribute = null; if (DataLocalizationFacade.DefaultLocalizationCulture != null) { oldDefaultAttribute = new XAttribute("oldDefault", DataLocalizationFacade.DefaultLocalizationCulture.Name); } var localeElements = new List(); foreach (Tuple tuple in _localesToInstall) { Log.LogVerbose(LogTitle, "Adding the locale '{0}'", tuple.Item1); LocalizationFacade.AddLocale(tuple.Item1, tuple.Item2, true, false); if (tuple.Item3) { Log.LogVerbose(LogTitle, "Setting new default locale to '{0}'", tuple.Item1); LocalizationFacade.SetDefaultLocale(tuple.Item1); } localeElements.Add(new XElement("Locale", new XAttribute("name", tuple.Item1.Name))); } var element = new XElement("Locales", localeElements); if (oldDefaultAttribute != null) { element.Add(oldDefaultAttribute); } yield return element; } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/LocalePackageFragmentUninstaller.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using System.Globalization; using Composite.Core.Localization; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class LocalePackageFragmentUninstaller : BasePackageFragmentUninstaller { private List _culturesToUninstall = null; private CultureInfo _oldDefaultCultureInfo = null; /// public override IEnumerable Validate() { List validationResults = new List(); if (this.Configuration.Count(f => f.Name == "Locales") > 1) { validationResults.AddFatal(GetText("VirtualElementProviderNodePackageFragmentUninstaller.OnlyOneElement")); return validationResults; } XElement localesElement = this.Configuration.SingleOrDefault(f => f.Name == "Locales"); _culturesToUninstall = new List(); if (localesElement != null) { XAttribute oldDefaultAttribute = localesElement.Attribute("oldDefault"); if (oldDefaultAttribute != null) { _oldDefaultCultureInfo = CultureInfo.CreateSpecificCulture(oldDefaultAttribute.Value); } foreach (XElement localeElement in localesElement.Elements("Locale").Reverse()) { CultureInfo locale = CultureInfo.CreateSpecificCulture(localeElement.Attribute("name").Value); if ((_oldDefaultCultureInfo == null) && (LocalizationFacade.IsDefaultLocale(locale))) { // Locale is default -> not possible to unintall validationResults.AddFatal(GetText("VirtualElementProviderNodePackageFragmentUninstaller.OnlyOneElement")); continue; } if (LocalizationFacade.IsOnlyActiveLocaleForSomeUsers(locale)) { // only active for the a user validationResults.AddFatal(GetText("VirtualElementProviderNodePackageFragmentUninstaller.OnlyOneElement")); continue; } if (LocalizationFacade.IsLocaleInstalled(locale)) { _culturesToUninstall.Add(locale); } } } if (validationResults.Count > 0) { _culturesToUninstall = null; _oldDefaultCultureInfo = null; } return validationResults; } /// public override void Uninstall() { if (_oldDefaultCultureInfo != null) { Log.LogVerbose("LocalePackageFragmentUninstaller", string.Format("Restoring default locale to '{0}'", _oldDefaultCultureInfo)); LocalizationFacade.SetDefaultLocale(_oldDefaultCultureInfo); } foreach (CultureInfo locale in _culturesToUninstall.Reverse()) { Log.LogVerbose("LocalePackageFragmentUninstaller", string.Format("Removing the locale '{0}'", locale)); LocalizationFacade.RemoveLocale(locale, false); } } private static string GetText(string stringId) { return GetResourceString(stringId); } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/PackageFragmentValidationExtension.cs ================================================ using System; using System.Collections.Generic; using System.Xml.Linq; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Core_PackageSystem_PackageFragmentInstallers; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// public static class PackageFragmentValidationExtension { internal static void AddFatal(this IList validationResults, Exception exception) { validationResults.Add(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, exception)); } internal static void AddFatal(this IList validationResults, string message) { validationResults.Add(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, message)); } internal static void AddFatal(this IList validationResults, string message, XObject configurationObject) { validationResults.Add(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, message, configurationObject)); } /// /// Gets a single configuration element. Elements other than the specified one will cause validation errors. /// internal static XElement GetSingleConfigurationElement(this XElement configurationElement, string elementName, IList validationResult, bool required) { XElement result = null; foreach (var element in configurationElement.Elements()) { if (element.Name.LocalName != elementName) { validationResult.AddFatal(Texts.PackageFragmentInstaller_IncorrectElement(element.Name.LocalName, elementName), element); continue; } if (result != null) { validationResult.AddFatal(Texts.PackageFragmentInstaller_OnlyOneElementAllowed(elementName)); return null; } result = element; } if (required && result == null) { validationResult.AddFatal(Texts.PackageFragmentInstaller_MissingElement(elementName)); } return result; } /// /// Gets a child configuration elements. Elements with names other than the specified one will cause validation errors. /// internal static IEnumerable GetConfigurationElements(this XElement configurationElement, string elementName, IList validationResult) { var result = new List(); foreach (var element in configurationElement.Elements()) { if (element.Name.LocalName != elementName) { validationResult.AddFatal(Texts.PackageFragmentInstaller_IncorrectElement(element.Name.LocalName, elementName), element); continue; } result.Add(element); } return result; } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/PackageLicenseFragmentInstaller.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.Core.Configuration; using Composite.Core.PackageSystem.WebServiceClient; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// Used for commercial packages distributed by Composite. /// Checks if a valid license file is present, if not, requests a trial license from Composite server. /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class PackageLicenseFragmentInstaller : BasePackageFragmentInstaller { private string _publicKeyXml; private bool _licenseFileExists; /// public override IEnumerable Validate() { var validationResult = new List(); Guid packageId = this.InstallerContext.PackageInformation.Id; if(LicenseDefinitionManager.GetLicenseDefinition(packageId) != null) { _licenseFileExists = true; return validationResult; } XElement publicKeyElement = this.Configuration.SingleOrDefault(f => f.Name == "RSAKeyValue"); if (publicKeyElement == null) { validationResult.AddFatal(GetResourceString("PackageLicenseFragmentInstaller.MissingPublicKeyElement")); return validationResult; } _publicKeyXml = publicKeyElement.ToString(); string validated = LicenseServerFacade.ValidateTrialLicenseDefinitionRequest(InstallationInformationFacade.InstallationId, packageId, _publicKeyXml); if (validated != "OK") { validationResult.Add(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, validated)); } return validationResult; } /// public override IEnumerable Install() { if(_licenseFileExists) { return new XElement[0]; } LicenseDefinitionDescriptor descriptor = LicenseServerFacade.GetTrialLicenseDefinition(InstallationInformationFacade.InstallationId, this.InstallerContext.PackageInformation.Id, _publicKeyXml); var definition = new PackageLicenseDefinition { ProductName = this.InstallerContext.PackageInformation.Name, InstallationId = descriptor.InstallationId, ProductId = descriptor.ProductId, LicenseFileName = "", Permanent = descriptor.Permanent, Expires = descriptor.Expires, LicenseKey = descriptor.LicenseKey, PurchaseUrl = descriptor.PurchaseUrl }; LicenseDefinitionManager.StoreLicenseDefinition(definition); return new XElement[] { }; } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/PackageLicenseFragmentUninstaller.cs ================================================ using System.Collections.Generic; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class PackageLicenseFragmentUninstaller : BasePackageFragmentUninstaller { /// public override IEnumerable Validate() { return new PackageFragmentValidationResult[] { }; } /// public override void Uninstall() { PackageLicenseDefinition licenseDefinition = LicenseDefinitionManager.GetLicenseDefinition(this.UninstallerContext.PackageInformation.Id); if ((licenseDefinition != null) && (licenseDefinition.Permanent == false)) { LicenseDefinitionManager.RemoveLicenseDefintion(this.UninstallerContext.PackageInformation.Id); } } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/PackageVersionBumperFragmentInstaller.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.PackageSystem.Foundation; using Composite.Core.Xml; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Core_PackageSystem_PackageFragmentInstallers; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// Updates the version number for an already installed package. /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class PackageVersionBumperFragmentInstaller : BasePackageFragmentInstaller { private Dictionary _packagesToBumb; private Dictionary _installedPackages; /// public override IEnumerable Validate() { var validationResult = new List(); if (this.Configuration.Count(f => f.Name == "PackageVersions") > 1) { validationResult.AddFatal(Texts.PackageVersionBumperFragmentUninstaller_OnlyOneElement, this.ConfigurationParent); return validationResult; } XElement packageVersionsElement = this.Configuration.SingleOrDefault(f => f.Name == "PackageVersions"); _packagesToBumb = new Dictionary(); if (packageVersionsElement != null) { foreach (XElement packageVersionElement in packageVersionsElement.Elements("PackageVersion")) { XAttribute packageIdAttribute = packageVersionElement.Attribute("packageId"); XAttribute newVersionAttribute = packageVersionElement.Attribute("newVersion"); if (packageIdAttribute == null) { validationResult.AddFatal(Texts.PackageVersionBumperFragmentUninstaller_MissingAttribute("packageId"), packageVersionElement); continue; } if (newVersionAttribute == null) { validationResult.AddFatal(Texts.PackageVersionBumperFragmentUninstaller_MissingAttribute("newVersion"), packageVersionElement); continue; } Guid packageId; if (!packageIdAttribute.TryGetGuidValue(out packageId)) { validationResult.AddFatal(Texts.PackageVersionBumperFragmentUninstaller_WrongAttributeGuidFormat, packageIdAttribute); continue; } if (_packagesToBumb.ContainsKey(packageId)) { validationResult.AddFatal(Texts.PackageVersionBumperFragmentUninstaller_PackageIdDuplicate(packageId), packageIdAttribute); continue; } Version version; try { version = new Version(newVersionAttribute.Value); } catch { validationResult.AddFatal(Texts.PackageVersionBumperFragmentUninstaller_WrongAttributeVersionFormat, newVersionAttribute); continue; } _packagesToBumb.Add(packageId, version.ToString()); } } if (validationResult.Count > 0) { _packagesToBumb = null; } return validationResult; } /// public override IEnumerable Install() { Verify.IsNotNull(_packagesToBumb, this.GetType().Name + " has not been validated"); var installedElements = new List(); foreach (var kvp in _packagesToBumb) { if (this.InstalledPackages.ContainsKey(kvp.Key)) { XDocument doc = XDocumentUtils.Load(this.InstalledPackages[kvp.Key]); XElement element = doc.Root; if (element == null) continue; XAttribute attribute = element.Attribute(PackageSystemSettings.VersionAttributeName); if (attribute == null) continue; installedElements.Add( new XElement("PackageVersion", new XAttribute("packageId", kvp.Key), new XAttribute("oldVersion", attribute.Value)) ); attribute.Value = kvp.Value; doc.SaveToFile(this.InstalledPackages[kvp.Key]); } } yield return new XElement("PackageVersions", installedElements); } private Dictionary InstalledPackages { get { return _installedPackages ?? (_installedPackages = GetInstalledPackages()); } } internal static Dictionary GetInstalledPackages() { var result = new Dictionary(); string baseDirectory = PathUtil.Resolve(GlobalSettingsFacade.PackageDirectory); if (!C1Directory.Exists(baseDirectory)) return result; string[] packageDirectories = C1Directory.GetDirectories(baseDirectory); foreach (string packageDirecoty in packageDirectories) { if (C1File.Exists(Path.Combine(packageDirecoty, PackageSystemSettings.InstalledFilename))) { string filename = Path.Combine(packageDirecoty, PackageSystemSettings.PackageInformationFilename); if (C1File.Exists(filename)) { string path = packageDirecoty.Remove(0, baseDirectory.Length); if (path.StartsWith("\\")) { path = path.Remove(0, 1); } Guid id = new Guid(path); result.Add(id, filename); } } } return result; } private static string GetText(string stringId) { return GetResourceString(stringId); } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/PackageVersionBumperFragmentUninstaller.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.Core.PackageSystem.Foundation; using Composite.Core.Xml; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Core_PackageSystem_PackageFragmentInstallers; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { class PackageVersionBumperFragmentUninstaller : BasePackageFragmentUninstaller { private Dictionary _packageToRestore; private Dictionary _installedPackages; public override IEnumerable Validate() { var validationResult = new List(); if (this.Configuration.Count(f => f.Name == "PackageVersions") > 1) { validationResult.AddFatal(Texts.PackageVersionBumperFragmentInstaller_OnlyOneElement); return validationResult; } XElement packageVersionsElement = this.Configuration.SingleOrDefault(f => f.Name == "PackageVersions"); _packageToRestore = new Dictionary(); if (packageVersionsElement != null) { foreach (XElement packageVersionElement in packageVersionsElement.Elements("PackageVersion")) { XAttribute packageIdAttribute = packageVersionElement.Attribute("packageId"); XAttribute oldVersionAttribute = packageVersionElement.Attribute("oldVersion"); if (packageIdAttribute == null) { validationResult.AddFatal(Texts.PackageVersionBumperFragmentUninstaller_MissingAttribute("packageId"), packageVersionElement); continue; } if (oldVersionAttribute == null) { validationResult.AddFatal(Texts.PackageVersionBumperFragmentUninstaller_MissingAttribute("newVersion"), packageVersionElement); continue; } Guid packageId; if (!packageIdAttribute.TryGetGuidValue(out packageId)) { validationResult.AddFatal(Texts.PackageVersionBumperFragmentUninstaller_WrongAttributeGuidFormat, packageIdAttribute); continue; } if (_packageToRestore.ContainsKey(packageId)) { validationResult.AddFatal(Texts.PackageVersionBumperFragmentUninstaller_PackageIdDuplicate(packageId), packageIdAttribute); continue; } Version version; try { version = new Version(oldVersionAttribute.Value); } catch { validationResult.AddFatal(Texts.PackageVersionBumperFragmentUninstaller_WrongAttributeVersionFormat, oldVersionAttribute); continue; } _packageToRestore.Add(packageId, version.ToString()); } } if (validationResult.Count > 0) { _packageToRestore = null; _installedPackages = null; } return validationResult; } public override void Uninstall() { foreach (var kvp in _packageToRestore.Reverse()) { if (this.InstalledPackages.ContainsKey(kvp.Key)) { XDocument doc = XDocumentUtils.Load(this.InstalledPackages[kvp.Key]); XElement element = doc.Root; if (element == null) continue; XAttribute attribute = element.Attribute(PackageSystemSettings.VersionAttributeName); if (attribute == null) continue; attribute.Value = kvp.Value; doc.SaveToFile(this.InstalledPackages[kvp.Key]); } } } private Dictionary InstalledPackages { get { return _installedPackages ?? (_installedPackages = PackageVersionBumperFragmentInstaller.GetInstalledPackages()); } } private static string GetText(string stringId) { return GetResourceString(stringId); } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/UserGroupUserAdderFragmentInstaller.cs ================================================ using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.Core.Linq; using Composite.Data; using Composite.Data.Types; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// Adds all the users to the specified user group. Assign language permissions to those groups. Used in starter site packages. /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class UserGroupUserAdderFragmentInstaller : BasePackageFragmentInstaller { private readonly List _names = new List(); /// public override IEnumerable Validate() { XElement usergroupNamesElement = this.Configuration.FirstOrDefault(f => f.Name == "UsergroupNames"); if (usergroupNamesElement == null) yield break; foreach (XElement usergroupNameElement in usergroupNamesElement.Elements("UsergroupName")) { XAttribute nameAttribute = usergroupNameElement.Attribute("Name"); if (nameAttribute == null) continue; _names.Add(nameAttribute.Value); } } /// public override IEnumerable Install() { foreach (string usergroupName in _names) { IUserGroup userGroup = DataFacade.GetData().SingleOrDefault(f => f.Name == usergroupName); if (userGroup == null) continue; IEnumerable users = DataFacade.GetData().Evaluate(); foreach (IUser user in users) { var userUserGroupRelation = DataFacade.BuildNew(); userUserGroupRelation.UserId = user.Id; userUserGroupRelation.UserGroupId = userGroup.Id; DataFacade.AddNew(userUserGroupRelation); } foreach (var cultureInfo in DataLocalizationFacade.ActiveLocalizationCultures) { var userGroupActiveLocale = DataFacade.BuildNew(); userGroupActiveLocale.UserGroupId = userGroup.Id; userGroupActiveLocale.CultureName = cultureInfo.Name; DataFacade.AddNew(userGroupActiveLocale); } } yield break; } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/UserGroupUserAdderFragmentUninstaller.cs ================================================ using System; using System.Collections.Generic; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class UserGroupUserAdderFragmentUninstaller : BasePackageFragmentUninstaller { /// public override IEnumerable Validate() { throw new NotImplementedException(); } /// public override void Uninstall() { throw new NotImplementedException(); } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/XmlFileMergePackageFragmentInstaller.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Xml; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// Merges 2 xml files. New child elements and new attibutes are imported to the source. Conflicts are ignored (not merged). /// Used for applying changes to config files. /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class XmlFileMergePackageFragmentInstaller : BasePackageFragmentInstaller { internal static readonly string mergeContainerElementName = "XmlFileMerges"; internal static readonly string mergeElementName = "XmlFileMerge"; internal static readonly string changeDefFileAttributeName = "changeDefinitionPath"; internal static readonly string targetFileAttributeName = "targetFilePath"; private sealed class XmlFileMerge { public string ChangeFilePath { get; set; } public string TargetPath { get; set; } } private IList _xmlFileMerges; /// public override IEnumerable Install() { Verify.IsNotNull(_xmlFileMerges, "XmlFileMergePackageFragmentInstaller has not been validated"); foreach (XmlFileMerge xmlFileMerge in _xmlFileMerges) { string targetXmlFile = PathUtil.Resolve(xmlFileMerge.TargetPath); using (Stream stream = this.InstallerContext.ZipFileSystem.GetFileStream(xmlFileMerge.ChangeFilePath)) { XElement source = XElement.Load(stream); XDocument target = XDocumentUtils.Load(targetXmlFile); target.Root.ImportSubtree(source); target.SaveToFile(targetXmlFile); } } return new[] { this.Configuration.FirstOrDefault() }; } /// public override IEnumerable Validate() { var validationResult = new List(); if (Configuration.Count(f => f.Name == XmlFileMergePackageFragmentInstaller.mergeContainerElementName) > 1) { validationResult.Add(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, "OnlyOneFilesElement")); return validationResult; } IEnumerable filesElement = this.Configuration.Where(f => f.Name == XmlFileMergePackageFragmentInstaller.mergeContainerElementName); _xmlFileMerges = new List(); foreach (XElement fileElement in filesElement.Elements(mergeElementName)) { XAttribute sourceAttribute; XAttribute targetAttribute; if(!GetAttributeNotNull(fileElement, XmlFileMergePackageFragmentInstaller.changeDefFileAttributeName, validationResult, out sourceAttribute) || !GetAttributeNotNull(fileElement, XmlFileMergePackageFragmentInstaller.targetFileAttributeName, validationResult, out targetAttribute)) { continue; } var xmlFileMerge = new XmlFileMerge { ChangeFilePath = sourceAttribute.Value, TargetPath = targetAttribute.Value }; string filePath = PathUtil.Resolve(xmlFileMerge.TargetPath); if (!C1File.Exists(filePath)) { validationResult.Add(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, "File '{0}' not found".FormatWith(filePath), fileElement)); continue; } _xmlFileMerges.Add(xmlFileMerge); } if (validationResult.Count > 0) { _xmlFileMerges = null; } return validationResult; } private static bool GetAttributeNotNull(XElement element, string attributeName, List validationSummary, out XAttribute attribute) { attribute = element.Attribute(attributeName); if (attribute != null) return true; validationSummary.Add(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, "MissingAttribute '{0}'. XPath: '{1}' ".FormatWith(attributeName, element.GetXPath()))); return false; } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentInstallers/XmlFileMergePackageFragmentUninstaller.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using Composite.Core.IO; using Composite.Core.Xml; namespace Composite.Core.PackageSystem.PackageFragmentInstallers { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class XmlFileMergePackageFragmentUninstaller : BasePackageFragmentUninstaller { private sealed class XmlFileMerge { public string ChangeFilePath { get; set; } public string TargetPath { get; set; } } private IList _xmlFileMerges; /// public override void Uninstall() { if (_xmlFileMerges == null) throw new InvalidOperationException("XmlFileMergePackageFragmentUninstaller has not been validated"); foreach (XmlFileMerge xmlFileMerge in _xmlFileMerges) { string targetXml = PathUtil.Resolve(xmlFileMerge.TargetPath); using (Stream stream = this.UninstallerContext.ZipFileSystem.GetFileStream(xmlFileMerge.ChangeFilePath)) { XElement source = XElement.Load(stream); XDocument target = XDocumentUtils.Load(targetXml); target.Root.RemoveMatches(source); target.SaveToFile(targetXml); } } } /// public override IEnumerable Validate() { List validationResult = new List(); if (Configuration.Count(f => f.Name == XmlFileMergePackageFragmentInstaller.mergeContainerElementName) > 1) { validationResult.Add(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, "OnlyOneFilesElement")); return validationResult; } IEnumerable filesElement = this.Configuration.Where(f => f.Name == XmlFileMergePackageFragmentInstaller.mergeContainerElementName); _xmlFileMerges = new List(); foreach (var fileElement in filesElement.Elements(XmlFileMergePackageFragmentInstaller.mergeElementName)) { XAttribute changePathAttribute = fileElement.Attribute(XmlFileMergePackageFragmentInstaller.changeDefFileAttributeName); XAttribute targetAttribute = fileElement.Attribute(XmlFileMergePackageFragmentInstaller.targetFileAttributeName); if (changePathAttribute == null || targetAttribute == null) { validationResult.Add(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, "MissingAttribute", fileElement)); continue; } XmlFileMerge xmlFileMerge = new XmlFileMerge { ChangeFilePath = changePathAttribute.Value, TargetPath = targetAttribute.Value }; if (!C1File.Exists(PathUtil.Resolve(xmlFileMerge.TargetPath))) { validationResult.Add(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, "FileNotFound", fileElement)); continue; } _xmlFileMerges.Add(xmlFileMerge); } if (validationResult.Count > 0) { _xmlFileMerges = null; } return validationResult; } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentValidationResult.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Xml.Linq; using Composite.Core.Xml; using System.Reflection; namespace Composite.Core.PackageSystem { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DebuggerDisplay("ValidationResult = {ValidationResult}, Message = {Message}")] public sealed class PackageFragmentValidationResult { /// public PackageFragmentValidationResult(PackageFragmentValidationResultType validationResult, Exception exception) { Verify.ArgumentNotNull(exception, "exception"); if (exception is TargetInvocationException) { exception = exception.InnerException; } this.ValidationResult = validationResult; this.Message = exception.Message; this.Exception = exception; } /// public PackageFragmentValidationResult(PackageFragmentValidationResultType validationResult, string message) : this(validationResult, message, null) { } /// public PackageFragmentValidationResult(PackageFragmentValidationResultType validationResult, string message, XObject configurationObject) { Verify.ArgumentNotNullOrEmpty(message, "message"); this.ValidationResult = validationResult; this.Message = message; if (configurationObject != null) { this.XPath = configurationObject.GetXPath(); } this.Message = message; } /// public PackageFragmentValidationResultType ValidationResult { get; private set; } /// public string Message { get; private set; } /// public Exception Exception { get; private set; } /// public string XPath { get; private set; } /// public IEnumerable InnerResult { get; set; } } } ================================================ FILE: Composite/Core/PackageSystem/PackageFragmentValidationResultType.cs ================================================ namespace Composite.Core.PackageSystem { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum PackageFragmentValidationResultType { /// Fatal } } ================================================ FILE: Composite/Core/PackageSystem/PackageInformation.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Core.PackageSystem.Foundation; namespace Composite.Core.PackageSystem { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class PackageInformation { /// public Guid Id { get; set; } /// public string Name { get; set; } /// public string GroupName { get; set; } /// public string Author { get; set; } /// public string Website { get; set; } /// public string Description { get; set; } /// public string Version { get; set; } /// public bool CanBeUninstalled { get; set; } /// public SystemLockingType SystemLockingType { get; set; } /// public bool FlushOnCompletion { get; set; } /// public bool ReloadConsoleOnCompletion { get; set; } /// public Version MaxCompositeVersionSupported { get; set; } /// public Version MinCompositeVersionSupported { get; set; } } } ================================================ FILE: Composite/Core/PackageSystem/PackageInstaller.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using Composite.Core.Application; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.IO.Zip; using Composite.Core.Logging; using Composite.Core.PackageSystem.Foundation; using Composite.Core.PackageSystem.PackageFragmentInstallers; using Composite.Core.Types; using Composite.Core.Xml; using Composite.Data.Transactions; namespace Composite.Core.PackageSystem { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class PackageInstaller : IPackageInstaller { private static readonly string LogTitle = "PackageInstaller"; private bool _isInitialized = false; private PackageInstallerContext _packageInstallerContex; // IPackageFragmentInstaller -> uninstall type, null is allowed private Dictionary _packageFramentInstallers = new Dictionary(); private IPackageInstallerUninstallerFactory PackageInstallerUninstallerFactory { get; set; } private string ZipFilename { get; set; } private string PackageInstallDirectory { get; set; } private string TempDirectory { get; set; } private PackageInformation PackageInformation { get; set; } /// internal static event Action OnPackageInstallation; /// public PackageInstaller(IPackageInstallerUninstallerFactory packageInstallerUninstallerFactory, string zipFilename, string packageInstallDirectory, string tempDirectory, PackageInformation packageInformation) { if (packageInstallerUninstallerFactory == null) throw new ArgumentNullException("packageInstallerUninstallerFactory"); if (string.IsNullOrEmpty(zipFilename)) throw new ArgumentNullException("zipFilename"); if (string.IsNullOrEmpty(packageInstallDirectory)) throw new ArgumentNullException("packageInstallDirectory"); if (string.IsNullOrEmpty(tempDirectory)) throw new ArgumentNullException("tempDirectory"); if (packageInformation == null) throw new ArgumentNullException("packageInformation"); this.PackageInstallerUninstallerFactory = packageInstallerUninstallerFactory; this.ZipFilename = zipFilename; this.PackageInstallDirectory = packageInstallDirectory; this.TempDirectory = tempDirectory; this.PackageInformation = packageInformation; } /// public bool CanBeUninstalled { get { return this.PackageInformation.CanBeUninstalled; } } /// public bool FlushOnCompletion { get { return this.PackageInformation.FlushOnCompletion; } } /// public bool ReloadConsoleOnCompletion { get { return this.PackageInformation.ReloadConsoleOnCompletion; } } /// public IEnumerable Validate() { List validationResult = Initialize().ToList(); if (validationResult.Count > 0) { return validationResult; } foreach (IPackageFragmentInstaller packageFragmentInstaller in _packageFramentInstallers.Keys) { List result = null; try { result = packageFragmentInstaller.Validate().ToList(); } catch (Exception ex) { validationResult.Add(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex)); } if (result != null) { validationResult.AddRange(result); } } return validationResult; } /// public PackageFragmentValidationResult Install(SystemLockingType systemLockingType) { try { using (GlobalInitializerFacade.CoreLockScope) { var onPackageInstallation = OnPackageInstallation; if (onPackageInstallation != null) { onPackageInstallation(); } if (systemLockingType == SystemLockingType.None || !ApplicationOnlineHandlerFacade.IsApplicationOnline || SystemSetupFacade.SetupIsRunning) { return DoInstall(); } bool isSoftSystemLocking = systemLockingType == SystemLockingType.Soft; string errorMessage; if(!ApplicationOnlineHandlerFacade.CanPutApplicationOffline(isSoftSystemLocking, out errorMessage)) { return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, errorMessage); } using (ApplicationOnlineHandlerFacade.TurnOffScope(isSoftSystemLocking)) { return DoInstall(); } } } catch (Exception ex) { return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex); } } private PackageFragmentValidationResult DoInstall() { using (var transactionScope = TransactionsFacade.Create(true, TimeSpan.FromMinutes(30.0))) { string uninstallFilename = Path.Combine(this.PackageInstallDirectory, PackageSystemSettings.UninstallFilename); Exception installException = null; XElement uninstallElements = new XElement(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageFragmentUninstallersElementName)); try { foreach (var kvp in _packageFramentInstallers) { List uninstallInformation = kvp.Key.Install().ToList(); if (this.CanBeUninstalled) { XElement uninstallElement = new XElement(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings. PackageFragmentUninstallersAddElementName)); uninstallElement.Add(new XAttribute(PackageSystemSettings.UninstallerTypeAttributeName, TypeManager.SerializeType(kvp.Value))); uninstallElement.Add(uninstallInformation); uninstallElements.Add(uninstallElement); } } } catch (Exception ex) { installException = ex; LoggingService.LogError("Package installation failed", ex); } finally { if (this.CanBeUninstalled) { XDocument doc = new XDocument( new XElement( XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageInstallerElementName), uninstallElements)); doc.SaveToFile(uninstallFilename); } } if (installException != null) { if (this.CanBeUninstalled) { IPackageUninstaller packageUninstaller = this.PackageInstallerUninstallerFactory.CreateUninstaller( this.ZipFilename, uninstallFilename, this.PackageInstallDirectory, TempDirectoryFacade. CreateTempDirectory(), this.FlushOnCompletion, this.ReloadConsoleOnCompletion, false, this.PackageInformation); List validationResult = null; try { validationResult = packageUninstaller.Validate().ToList(); } catch (Exception ex) { return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex); } if (validationResult.Count == 0) { try { packageUninstaller.Uninstall(SystemLockingType.None); } catch (Exception ex) { return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex); } } else { LoggingService.LogError(LogTitle, "Failed to perform installation rollback."); foreach(var valResult in validationResult) { if(valResult.Exception != null) { LoggingService.LogError(LogTitle, new InvalidOperationException(valResult.Message ?? string.Empty, valResult.Exception)); } else { LoggingService.LogWarning(LogTitle, valResult.Message); } } return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, "Could not perform installation rollback. The details are in the log.") {InnerResult = validationResult}; } } return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, installException); } transactionScope.Complete(); } return null; } private IEnumerable Initialize() { if (_isInitialized) throw new InvalidOperationException("Initialize() may only be called once"); _isInitialized = true; Exception exception = null; try { _packageInstallerContex = new PackageInstallerContext(new ZipFileSystem(this.ZipFilename), this.PackageInstallDirectory, this.TempDirectory, this.PackageInformation); } catch (Exception ex) { exception = ex; } if (exception != null) return new [] { new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, exception) }; PackageAssemblyHandler.ClearAssemblyList(); XElement installElement; PackageFragmentValidationResult packageFragmentValidationResult = XmlHelper.LoadInstallXml(this.ZipFilename, out installElement); if (packageFragmentValidationResult != null) return new [] { packageFragmentValidationResult }; XElement packageFragmentInstallerBinariesElement = installElement.Element(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageFragmentInstallerBinariesElementName)); if (packageFragmentInstallerBinariesElement != null) { List result1 = LoadPackageFragmentInstallerBinaries(packageFragmentInstallerBinariesElement).ToList(); if (result1.Count > 0) return result1; } XElement packageFragmentInstallersElement = installElement.Element(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageFragmentInstallersElementName)); if (packageFragmentInstallersElement == null) return new [] { new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format("The {0} file is wrongly formatted", PackageSystemSettings.InstallFilename)) }; var result2 = LoadPackageFragmentInstallers(packageFragmentInstallersElement); if (result2.Count > 0) return result2; return new PackageFragmentValidationResult[] { }; } private IEnumerable LoadPackageFragmentInstallerBinaries(XElement packageFragmentInstallerBinariesElement) { var binaryElements = packageFragmentInstallerBinariesElement.Elements(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageFragmentInstallerBinariesAddElementName)).ToList(); if (!binaryElements.Any()) { return new PackageFragmentValidationResult[0]; } string binariesDirectory = Path.Combine(this.PackageInstallDirectory, PackageSystemSettings.BinariesDirectoryName); if (!C1Directory.Exists(binariesDirectory)) { C1Directory.CreateDirectory(binariesDirectory); } var result = new List(); foreach (XElement element in binaryElements) { XAttribute pathAttribute = element.Attribute(PackageSystemSettings.PathAttributeName); string sourceFilename = pathAttribute.Value; string targetFilename = Path.Combine(binariesDirectory, Path.GetFileName(sourceFilename)); ZipFileSystem zipFileSystem = new ZipFileSystem(this.ZipFilename); if (!zipFileSystem.ContainsFile(sourceFilename)) { result.AddFatal($"The file '{sourceFilename}' is missing from the zip file"); continue; } // Extracting dll to package temp folder if (C1File.Exists(targetFilename)) { bool success = false; try { FileUtils.Delete(targetFilename); success = true; } catch(UnauthorizedAccessException) {} if(!success) { result.AddFatal($"Access denied to file '{targetFilename}'"); continue; } } zipFileSystem.WriteFileToDisk(sourceFilename, targetFilename); string newTargetFilename = Path.Combine(this.TempDirectory, Path.GetFileName(targetFilename)); C1File.Copy(targetFilename, newTargetFilename); Log.LogVerbose("PackageInstaller", "Loading package uninstaller fragment assembly '{0}'", newTargetFilename); PackageAssemblyHandler.AddAssembly(newTargetFilename); } return result; } private IList LoadPackageFragmentInstallers(XElement packageFragmentInstallersElement) { var result = new List(); XName packageInstallerXName = XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageFragmentInstallersAddElementName); foreach (XElement element in packageFragmentInstallersElement.Elements(packageInstallerXName)) { XAttribute installerTypeAttribute = element.Attribute(PackageSystemSettings.InstallerTypeAttributeName); if (installerTypeAttribute == null) { result.AddFatal($"Missing attribute '{PackageSystemSettings.InstallerTypeAttributeName}'", element); continue; } Type installerType = TypeManager.TryGetType(installerTypeAttribute.Value); if (installerType == null) { result.AddFatal($"Could not find install fragment type '{installerTypeAttribute.Value}'", installerTypeAttribute); continue; } IPackageFragmentInstaller packageFragmentInstaller; try { packageFragmentInstaller = Activator.CreateInstance(installerType) as IPackageFragmentInstaller; } catch (Exception ex) { result.AddFatal(ex); continue; } if (packageFragmentInstaller == null) { result.AddFatal($"The type '{installerTypeAttribute.Value}' does not implement {typeof (IPackageFragmentInstaller)}", installerTypeAttribute); continue; } Type uninstallerType = null; if (this.CanBeUninstalled) { XAttribute uninstallerTypeAttribute = element.Attribute(PackageSystemSettings.UninstallerTypeAttributeName); if (uninstallerTypeAttribute == null) { result.AddFatal($"Missing attribute '{PackageSystemSettings.UninstallerTypeAttributeName}'", element); continue; } uninstallerType = TypeManager.TryGetType(uninstallerTypeAttribute.Value); if (uninstallerType == null) { result.AddFatal($"Could not find uninstall fragment type '{uninstallerTypeAttribute.Value}'", uninstallerTypeAttribute); continue; } IPackageFragmentUninstaller packageFragmentUninstaller; try { packageFragmentUninstaller = Activator.CreateInstance(uninstallerType) as IPackageFragmentUninstaller; } catch (Exception ex) { result.AddFatal(ex); continue; } if (packageFragmentUninstaller == null) { result.AddFatal($"The type '{uninstallerTypeAttribute.Value}' does not implement {typeof (IPackageFragmentUninstaller)}", uninstallerTypeAttribute); continue; } } try { packageFragmentInstaller.Initialize(_packageInstallerContex, element.Descendants(), element); } catch (Exception ex) { result.AddFatal(ex); continue; } _packageFramentInstallers.Add(packageFragmentInstaller, uninstallerType); } return result; } } } ================================================ FILE: Composite/Core/PackageSystem/PackageInstallerContext.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Data.DynamicTypes; using Composite.Core.IO.Zip; using System.Globalization; namespace Composite.Core.PackageSystem { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class PackageInstallerContext { private readonly Dictionary _pendingDataTypeDescriptors = new Dictionary(); private readonly List _pendingDataTypes = new List(); private readonly List _pendingLocales = new List(); internal PackageInstallerContext(IZipFileSystem zipFileSystem, string packageDirectory, string tempDirectory, PackageInformation packageInformation) { Verify.ArgumentNotNull(zipFileSystem, "zipFileSystem"); Verify.ArgumentNotNullOrEmpty(tempDirectory, "tempDirectory"); Verify.ArgumentNotNull(packageInformation, "packageInformation"); this.ZipFileSystem = zipFileSystem; this.PackageDirectory = packageDirectory; this.TempDirectory = tempDirectory; this.PackageInformation = packageInformation; } /// public IZipFileSystem ZipFileSystem { get; private set; } /// public string PackageDirectory { get; private set; } /// public string TempDirectory { get; private set; } /// public PackageInformation PackageInformation { get; private set; } /// /// Use this method to register data type descriptors that have been validated and will be /// intstalled. /// /// /// public void AddPendingDataTypeDescritpor(string interfaceName, DataTypeDescriptor dataTypeDescriptor) { Verify.ArgumentNotNullOrEmpty(interfaceName, "interfaceName"); Verify.ArgumentNotNull(dataTypeDescriptor, "dataTypeDescriptor"); _pendingDataTypeDescriptors.Add(interfaceName, dataTypeDescriptor); } /// /// This method returns data type descriptors for dynamic types this is pending /// installation (Has passed validaion). /// /// /// public DataTypeDescriptor GetPendingDataTypeDescriptor(string interfaceName) { Verify.ArgumentNotNullOrEmpty(interfaceName, "interfaceName"); DataTypeDescriptor dataTypeDescriptor; if (_pendingDataTypeDescriptors.TryGetValue(interfaceName, out dataTypeDescriptor)) { return dataTypeDescriptor; } Type interfaceType = _pendingDataTypes.FirstOrDefault(type => type.FullName == interfaceName); if (interfaceType == null) return null; return DynamicTypeManager.BuildNewDataTypeDescriptor(interfaceType); } /// public void AddPendingDataType(Type interfaceType) { Verify.ArgumentNotNull(interfaceType, "interfaceType"); if (_pendingDataTypes.Contains(interfaceType) == false) { _pendingDataTypes.Add(interfaceType); } } /// public bool IsDataTypePending(Type interfaceType) { Verify.ArgumentNotNull(interfaceType, "interfaceType"); return _pendingDataTypes.Contains(interfaceType); } /// public bool IsDataTypePending(string typeName) { Verify.ArgumentNotNull(typeName, "typeName"); return _pendingDataTypes.Any(type => type.FullName == typeName); } /// public Type GetPendingDataType(string typeName) { return _pendingDataTypes.FirstOrDefault(type => type.FullName == typeName); } /// public void AddPendingLocale(CultureInfo locale) { Verify.ArgumentNotNull(locale, "locale"); _pendingLocales.Add(locale); } /// public bool IsLocalePending(CultureInfo locale) { Verify.ArgumentNotNull(locale, "locale"); return _pendingLocales.Contains(locale); } } } ================================================ FILE: Composite/Core/PackageSystem/PackageInstallerUninstallerFactory.cs ================================================ using Composite.Core.PackageSystem.Foundation; namespace Composite.Core.PackageSystem { internal sealed class PackageInstallerUninstallerFactory : IPackageInstallerUninstallerFactory { public IPackageUninstaller CreateUninstaller(string zipFilename, string uninstallFilename, string packageInstallationDirectory, string tempDirectory, bool flushOnCompletion, bool reloadConsoleOnCompletion, bool useTransaction, PackageInformation packageInformation) { return new PackageUninstaller(zipFilename, uninstallFilename, packageInstallationDirectory, tempDirectory, flushOnCompletion, reloadConsoleOnCompletion, useTransaction, packageInformation); } } } ================================================ FILE: Composite/Core/PackageSystem/PackageLicenseDefinition.cs ================================================ using System; using Composite.Core.Implementation; namespace Composite.Core.PackageSystem { /// /// A package license key definition /// public class PackageLicenseDefinition { /// /// The name of the package. /// public string ProductName { get; set; } /// /// The local path of the license file. A serialized version of this class. /// public string LicenseFileName { get; set; } /// /// False if the license is a trail license. True if its a permanent license. /// public bool Permanent { get; set; } /// /// The id of the C1 installation where the package was installed. /// public Guid InstallationId { get; set; } /// /// The id of the pacakge. /// public Guid ProductId { get; set; } /// /// A RSA signed license key. This is used to verify that the license file has not been tampered with. /// public string LicenseKey { get; set; } /// /// Url to where to buy a license for the pacakge. /// public string PurchaseUrl { get; set; } /// /// If its a trail license this property contains the date when the pacakge experies in UTC. /// public DateTime Expires { get; set; } /// /// The serizlied to byte array. /// public byte[] LicenseKeyBytes { get { return ImplementationFactory.CurrentFactory.StatelessPackageLicenseHelper.GetLicenseKeyBytes(this.LicenseKey); } } } } ================================================ FILE: Composite/Core/PackageSystem/PackageLicenseHelper.cs ================================================ using System; using System.Security.Cryptography; using Composite.Core.Implementation; namespace Composite.Core.PackageSystem { /// /// This class contains methods for handling package licenses /// /// Here is an example of how a pacakge could validat if there is a valid license installed for the pacakge. /// This code should be compiled into the pacakge itself to prevent spoofing. /// /// Guid productId = ...; // A package should have this compiled into its assembly. /// string publicKeyXml = ...; // A package should have this compiled into its assembly. /// /// PackageLicenseDefinition licenseDefinition = PackageLicenseHelper.GetLicenseDefinition(productId); /// Guid installationId = licenseDefinition.InstallationId; /// bool isPermanent = licenseDefinition.Permanent; /// DateTime expiresTime = licenseDefinition.Expires; /// /// byte[] signedSignature = licenseDefinition.LicenseKeyBytes; /// /// // Create the signature string /// string signatureString; /// if (isPermanent) /// { /// signatureString = string.Format("{0}#{1}#{2}", installationId, productId, isPermanent); /// } /// else /// { /// signatureString = string.Format("{0}#{1}#{2}#{3}", installationId, productId, isPermanent, new XAttribute("date", expiresTime).Value); /// } /// byte[] signature = PackageLicenseHelper.CreateSignatureBytes(signatureString); /// /// // Create the provider to verify the signature string /// RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); /// provider.FromXmlString(publicKeyXml); /// /// object hashAlgorithm = PackageLicenseHelper.CreateSignatureHashAlgorithm(publicKeyXml); /// /// // isValidKey tells if the package license xml file has been tampered with /// bool isValidKey = provider.VerifyData(signature, hashAlgorithm, signedSignature); /// /// // isExpried tells if a trail license is expired, false if its a permanent license /// bool isExpired = !isPermanent < expiresTime < DateTime.Now; /// /// // isLicenseValid is a combination of isValidKey and isExpired and is only true if the package license xml file has not been tampered with and the license is not expired /// bool isLicenseValid = isValidKey & !isExpired; /// /// /// public static class PackageLicenseHelper { /// /// This method returns a license defintion for the given pacakge id /// /// The package id to locate licende definition for. /// The data for the license definition found. Null if no license is found. public static PackageLicenseDefinition GetLicenseDefinition(Guid productId) { return ImplementationFactory.CurrentFactory.StatelessPackageLicenseHelper.GetLicenseDefinition(productId); } /// /// Stores the given license defintion. /// /// The license definition to store public static void StoreLicenseDefinition(PackageLicenseDefinition licenseDefinition) { ImplementationFactory.CurrentFactory.StatelessPackageLicenseHelper.StoreLicenseDefinition(licenseDefinition); } /// /// Removes a license definition given the pacakge id /// /// Package id to which the license definition is to be removed public static void RemoveLicenseDefintion(Guid productId) { ImplementationFactory.CurrentFactory.StatelessPackageLicenseHelper.RemoveLicenseDefinition(productId); } /// /// This method returns a hash algorithm that can be used when validateting a package license definition. /// /// This is the public key to the private key used by the pacakge server to generate the license key /// A hash algorithm object public static object CreateSignatureHashAlgorithm(string publicKeyXml) { return ImplementationFactory.CurrentFactory.StatelessPackageLicenseHelper.CreateSignatureHashAlgorithm(publicKeyXml); } /// /// This method returns a byte representation of the . /// Here is an example of how to create an signature string: /// /// /// string signatureString; /// if (isPermanent) /// { /// signatureString = string.Format("{0}#{1}#{2}", installationId, productId, isPermanent); /// } /// else /// { /// signatureString = string.Format("{0}#{1}#{2}#{3}", installationId, productId, isPermanent, new XAttribute("date", expiresTime).Value); /// } /// /// /// /// A signature string /// public static byte[] CreateSignatureBytes(string signatureString) { return ImplementationFactory.CurrentFactory.StatelessPackageLicenseHelper.CreateSignatureBytes(signatureString); } } } ================================================ FILE: Composite/Core/PackageSystem/PackageManager.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using Composite.C1Console.Security; using Composite.Core.Application; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.PackageSystem.Foundation; using Composite.Core.ResourceSystem; using Composite.Core.Xml; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Core_PackageSystem_PackageFragmentInstallers; namespace Composite.Core.PackageSystem { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PackageManager { /// public static IEnumerable GetInstalledPackages() { string baseDirectory = PathUtil.Resolve(GlobalSettingsFacade.PackageDirectory); if (!C1Directory.Exists(baseDirectory)) yield break; string[] packageDirectories = C1Directory.GetDirectories(baseDirectory); foreach (string packageDirectory in packageDirectories) { if (C1File.Exists(Path.Combine(packageDirectory, PackageSystemSettings.InstalledFilename))) { string filename = Path.Combine(packageDirectory, PackageSystemSettings.PackageInformationFilename); if (C1File.Exists(filename)) { XDocument doc = XDocumentUtils.Load(filename); XElement packageInfoElement = doc.Root; if (packageInfoElement.Name != XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageInfoElementName)) throw new InvalidOperationException(string.Format("{0} is wrongly formattet", filename)); XAttribute nameAttribute = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_NameAttributeName); XAttribute groupNameAttribute = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_GroupNameAttributeName); XAttribute versionAttribute = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_VersionAttributeName); XAttribute authorAttribute = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_AuthorAttributeName); XAttribute websiteAttribute = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_WebsiteAttributeName); XAttribute descriptionAttribute = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_DescriptionAttributeName); XAttribute installDateAttribute = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_InstallDateAttributeName); XAttribute installedByAttribute = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_InstalledByAttributeName); XAttribute isLocalInstalledAttribute = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_IsLocalInstalledAttributeName); XAttribute canBeUninstalledAttribute = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_CanBeUninstalledAttributeName); XAttribute flushOnCompletionAttribute = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_FlushOnCompletionAttributeName); XAttribute reloadConsoleOnCompletionAttribute = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_ReloadConsoleOnCompletionAttributeName); XAttribute systemLockingAttribute = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_SystemLockingAttributeName); XAttribute packageServerAddressAttribute = packageInfoElement.Attribute(PackageSystemSettings.PackageInfo_PackageServerAddressAttributeName); SystemLockingType systemLockingType; if (systemLockingAttribute.TryDeserialize(out systemLockingType) == false) throw new InvalidOperationException("The systemLocking attibute value is wrong"); string path = packageDirectory.Remove(0, baseDirectory.Length); if (path.StartsWith("\\")) { path = path.Remove(0, 1); } Guid packageId; if (!Guid.TryParse(path, out packageId)) { continue; } yield return new InstalledPackageInformation { Id = packageId, Name = nameAttribute.Value, GroupName = groupNameAttribute.Value, Version = versionAttribute.Value, Author = authorAttribute.Value, Website = websiteAttribute.Value, Description = descriptionAttribute.Value, InstallDate = (DateTime)installDateAttribute, InstalledBy = installedByAttribute.Value, IsLocalInstalled = (bool)isLocalInstalledAttribute, CanBeUninstalled = (bool)canBeUninstalledAttribute, FlushOnCompletion = (bool)flushOnCompletionAttribute, ReloadConsoleOnCompletion = (bool)reloadConsoleOnCompletionAttribute, SystemLockingType = systemLockingType, PackageServerAddress = packageServerAddressAttribute?.Value, PackageInstallPath = packageDirectory }; } else { throw new InvalidOperationException($"'{filename}' does not exist"); } } else { // Make this cleanup in an other way, it works correctly if it is done between validation and installation. //LoggingService.LogVerbose("PackageManager", string.Format("Uncomlete installed add on found ('{0}'), deleting it", Path.GetFileName(packageDirecoty))); //try //{ // Directory.Delete(packageDirecoty, true); //} //catch (Exception) //{ //} } } } private static XAttribute GetAttributeNotNull(string fileName, XElement packageInfoElement, string attributeName) { XAttribute attribute = packageInfoElement.Attribute(attributeName); Verify.IsNotNull(attribute, "File: '{0}', failed to find '{1}' attribute.", fileName, attributeName); return attribute; } /// public static bool IsInstalled(Guid packageId) { InstalledPackageInformation installedPackageInformation = (from ao in GetInstalledPackages() where ao.Id == packageId select ao).SingleOrDefault(); return installedPackageInformation != null; } /// public static string GetCurrentVersion(Guid packageId) { string currentVersion = (from ao in GetInstalledPackages() where ao.Id == packageId select ao.Version).SingleOrDefault(); return currentVersion; } /// public static PackageManagerInstallProcess Install(Stream zipFileStream, bool isLocalInstall) { if (isLocalInstall == false) throw new ArgumentException("Non local install needs a packageServerAddress"); return Install(zipFileStream, isLocalInstall, null); } /// public static PackageManagerInstallProcess Install(Stream zipFileStream, bool isLocalInstall, string packageServerAddress) { if (!isLocalInstall && string.IsNullOrEmpty(packageServerAddress)) throw new ArgumentException("Non local install needs a packageServerAddress"); string zipFilename = null; try { PackageFragmentValidationResult packageFragmentValidationResult = SaveZipFile(zipFileStream, out zipFilename); if (packageFragmentValidationResult != null) return new PackageManagerInstallProcess(new List { packageFragmentValidationResult }, null); XElement installContent; packageFragmentValidationResult = XmlHelper.LoadInstallXml(zipFilename, out installContent); if (packageFragmentValidationResult != null) return new PackageManagerInstallProcess(new List { packageFragmentValidationResult }, zipFilename); PackageInformation packageInformation; packageFragmentValidationResult = ValidatePackageInformation(installContent, out packageInformation); if (packageFragmentValidationResult != null) return new PackageManagerInstallProcess(new List { packageFragmentValidationResult }, zipFilename); if (RuntimeInformation.ProductVersion < packageInformation.MinCompositeVersionSupported || RuntimeInformation.ProductVersion > packageInformation.MaxCompositeVersionSupported) { return new PackageManagerInstallProcess(new List { new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, Texts.PackageManager_CompositeVersionMisMatch( RuntimeInformation.ProductVersion, packageInformation.MinCompositeVersionSupported, packageInformation.MaxCompositeVersionSupported)) }, zipFilename); } bool updatingInstalledPackage = false; if (IsInstalled(packageInformation.Id)) { string currentVersionString = GetCurrentVersion(packageInformation.Id); Version currentVersion = new Version(currentVersionString); Version newVersion = new Version(packageInformation.Version); if (newVersion <= currentVersion) { string validationError = newVersion == currentVersion ? Texts.PackageManager_PackageAlreadyInstalled : Texts.PackageManager_NewerVersionInstalled; return new PackageManagerInstallProcess( new List { new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, validationError) }, zipFilename); } updatingInstalledPackage = true; } string originalInstallDirectory = null; string packageInstallDirectory = CreatePackageDirectoryName(packageInformation); if (updatingInstalledPackage) { originalInstallDirectory = packageInstallDirectory; packageInstallDirectory += "-" + packageInformation.Version; } C1Directory.CreateDirectory(packageInstallDirectory); string packageZipFilename = Path.Combine(packageInstallDirectory, Path.GetFileName(zipFilename)); C1File.Copy(zipFilename, packageZipFilename, true); string username = "Composite"; if (UserValidationFacade.IsLoggedIn()) { username = UserValidationFacade.GetUsername(); } var doc = new XDocument(); XElement packageInfoElement = new XElement(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageInfoElementName)); doc.Add(packageInfoElement); packageInfoElement.Add( new XAttribute(PackageSystemSettings.PackageInfo_NameAttributeName, packageInformation.Name), new XAttribute(PackageSystemSettings.PackageInfo_GroupNameAttributeName, packageInformation.GroupName), new XAttribute(PackageSystemSettings.PackageInfo_VersionAttributeName, packageInformation.Version), new XAttribute(PackageSystemSettings.PackageInfo_AuthorAttributeName, packageInformation.Author), new XAttribute(PackageSystemSettings.PackageInfo_WebsiteAttributeName, packageInformation.Website), new XAttribute(PackageSystemSettings.PackageInfo_DescriptionAttributeName, packageInformation.Description), new XAttribute(PackageSystemSettings.PackageInfo_InstallDateAttributeName, DateTime.Now), new XAttribute(PackageSystemSettings.PackageInfo_InstalledByAttributeName, username), new XAttribute(PackageSystemSettings.PackageInfo_IsLocalInstalledAttributeName, isLocalInstall), new XAttribute(PackageSystemSettings.PackageInfo_CanBeUninstalledAttributeName, packageInformation.CanBeUninstalled), new XAttribute(PackageSystemSettings.PackageInfo_FlushOnCompletionAttributeName, packageInformation.FlushOnCompletion), new XAttribute(PackageSystemSettings.PackageInfo_ReloadConsoleOnCompletionAttributeName, packageInformation.ReloadConsoleOnCompletion), new XAttribute(PackageSystemSettings.PackageInfo_SystemLockingAttributeName, packageInformation.SystemLockingType.Serialize())); if (!string.IsNullOrEmpty(packageServerAddress)) { packageInfoElement.Add(new XAttribute(PackageSystemSettings.PackageInfo_PackageServerAddressAttributeName, packageServerAddress)); } string infoFilename = Path.Combine(packageInstallDirectory, PackageSystemSettings.PackageInformationFilename); doc.SaveToFile(infoFilename); var packageInstaller = new PackageInstaller(new PackageInstallerUninstallerFactory(), packageZipFilename, packageInstallDirectory, TempDirectoryFacade.CreateTempDirectory(), packageInformation); return new PackageManagerInstallProcess( packageInstaller, packageInformation.SystemLockingType, zipFilename, packageInstallDirectory, packageInformation.Name, packageInformation.Version, packageInformation.Id, originalInstallDirectory); } catch (Exception ex) { return new PackageManagerInstallProcess(new List { new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex) }, zipFilename); } } /// public static PackageManagerUninstallProcess Uninstall(Guid id) { try { string absolutePath = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.PackageDirectory), id.ToString()); InstalledPackageInformation installedPackageInformation = (from package in GetInstalledPackages() where package.Id == id select package).SingleOrDefault(); if (installedPackageInformation == null) return new PackageManagerUninstallProcess(new List { new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.MissingPackageDirectory"), absolutePath)) }); Log.LogVerbose("PackageManager", "Uninstalling package: {0}, Id = {1}", installedPackageInformation.Name, installedPackageInformation.Id); if (installedPackageInformation.CanBeUninstalled == false) return new PackageManagerUninstallProcess(new List { new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, GetText("PackageManager.Uninstallable")) }); string zipFilePath = Path.Combine(absolutePath, PackageSystemSettings.ZipFilename); if (C1File.Exists(zipFilePath) == false) return new PackageManagerUninstallProcess(new List { new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.MissingZipFile"), zipFilePath)) }); string uninstallFilePath = Path.Combine(absolutePath, PackageSystemSettings.UninstallFilename); if (C1File.Exists(uninstallFilePath) == false) return new PackageManagerUninstallProcess(new List { new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.MissingUninstallFile"), uninstallFilePath)) }); PackageInformation packageInformation = new PackageInformation { Id = installedPackageInformation.Id, Name = installedPackageInformation.Name, GroupName = installedPackageInformation.GroupName, Author = installedPackageInformation.Author, Website = installedPackageInformation.Website, Description = installedPackageInformation.Description, Version = installedPackageInformation.Version, CanBeUninstalled = installedPackageInformation.CanBeUninstalled, SystemLockingType = installedPackageInformation.SystemLockingType, FlushOnCompletion = installedPackageInformation.FlushOnCompletion, ReloadConsoleOnCompletion = installedPackageInformation.ReloadConsoleOnCompletion, }; PackageUninstaller packageUninstaller = new PackageUninstaller(zipFilePath, uninstallFilePath, absolutePath, TempDirectoryFacade.CreateTempDirectory(), installedPackageInformation.FlushOnCompletion, installedPackageInformation.ReloadConsoleOnCompletion, true, packageInformation); PackageManagerUninstallProcess packageManagerUninstallProcess = new PackageManagerUninstallProcess(packageUninstaller, absolutePath, installedPackageInformation.SystemLockingType); return packageManagerUninstallProcess; } catch (Exception ex) { return new PackageManagerUninstallProcess(new List { new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex) }); } } internal static PackageFragmentValidationResult ValidatePackageInformation(XElement installContent, out PackageInformation packageInformation) { packageInformation = null; XElement packageInformationElement = installContent.Element(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageInformationElementName)); if (packageInformationElement == null) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.MissingElement"), PackageSystemSettings.PackageInformationElementName), installContent); XAttribute idAttribute = packageInformationElement.Attribute(PackageSystemSettings.IdAttributeName); XAttribute nameAttribute = packageInformationElement.Attribute(PackageSystemSettings.NameAttributeName); XAttribute groupNameAttribute = packageInformationElement.Attribute(PackageSystemSettings.GroupNameAttributeName); XAttribute authorAttribute = packageInformationElement.Attribute(PackageSystemSettings.AuthorAttributeName); XAttribute websiteAttribute = packageInformationElement.Attribute(PackageSystemSettings.WebsiteAttributeName); XAttribute versionAttribute = packageInformationElement.Attribute(PackageSystemSettings.VersionAttributeName); XAttribute canBeUninstalledAttribute = packageInformationElement.Attribute(PackageSystemSettings.CanBeUninstalledAttributeName); XAttribute systemLockingAttribute = packageInformationElement.Attribute(PackageSystemSettings.SystemLockingAttributeName); XAttribute flushOnCompletionAttribute = packageInformationElement.Attribute(PackageSystemSettings.FlushOnCompletionAttributeName); XAttribute reloadConsoleOnCompletionAttribute = packageInformationElement.Attribute(PackageSystemSettings.ReloadConsoleOnCompletionAttributeName); if (idAttribute == null) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.MissingAttribute"), PackageSystemSettings.IdAttributeName), packageInformationElement); if (nameAttribute == null) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.MissingAttribute"), PackageSystemSettings.NameAttributeName), packageInformationElement); if (groupNameAttribute == null) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.MissingAttribute"), PackageSystemSettings.GroupNameAttributeName), packageInformationElement); if (authorAttribute == null) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.MissingAttribute"), PackageSystemSettings.AuthorAttributeName), packageInformationElement); if (websiteAttribute == null) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.MissingAttribute"), PackageSystemSettings.WebsiteAttributeName), packageInformationElement); if (versionAttribute == null) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.MissingAttribute"), PackageSystemSettings.VersionAttributeName), packageInformationElement); if (canBeUninstalledAttribute == null) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.MissingAttribute"), PackageSystemSettings.CanBeUninstalledAttributeName), packageInformationElement); if (systemLockingAttribute == null) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.MissingAttribute"), PackageSystemSettings.SystemLockingAttributeName), packageInformationElement); if (string.IsNullOrEmpty(nameAttribute.Value)) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.InvalidAttributeValue"), PackageSystemSettings.NameAttributeName), nameAttribute); if (string.IsNullOrEmpty(groupNameAttribute.Value)) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.InvalidAttributeValue"), PackageSystemSettings.GroupNameAttributeName), groupNameAttribute); if (string.IsNullOrEmpty(authorAttribute.Value)) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.InvalidAttributeValue"), PackageSystemSettings.AuthorAttributeName), authorAttribute); if (string.IsNullOrEmpty(websiteAttribute.Value)) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.InvalidAttributeValue"), PackageSystemSettings.WebsiteAttributeName), websiteAttribute); if (string.IsNullOrEmpty(versionAttribute.Value)) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.InvalidAttributeValue"), PackageSystemSettings.VersionAttributeName), versionAttribute); if (string.IsNullOrEmpty(packageInformationElement.Value)) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.InvalidElementValue"), PackageSystemSettings.PackageInformationElementName), packageInformationElement); Guid id; if (idAttribute.TryGetGuidValue(out id) == false) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.InvalidAttributeValue"), PackageSystemSettings.IdAttributeName), idAttribute); string newVersion; if (VersionStringHelper.ValidateVersion(versionAttribute.Value, out newVersion)) versionAttribute.Value = newVersion; else return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.InvalidAttributeValue"), PackageSystemSettings.VersionAttributeName), versionAttribute); bool canBeUninstalled; if (canBeUninstalledAttribute.TryGetBoolValue(out canBeUninstalled) == false) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.InvalidAttributeValue"), PackageSystemSettings.CanBeUninstalledAttributeName), canBeUninstalledAttribute); SystemLockingType systemLockingType; if (systemLockingAttribute.TryDeserialize(out systemLockingType) == false) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.InvalidAttributeValue"), PackageSystemSettings.SystemLockingAttributeName), systemLockingAttribute); bool flushOnCompletion = false; if ((flushOnCompletionAttribute != null) && (flushOnCompletionAttribute.TryGetBoolValue(out flushOnCompletion) == false)) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.InvalidAttributeValue"), PackageSystemSettings.FlushOnCompletionAttributeName), flushOnCompletionAttribute); bool reloadConsoleOnCompletion = false; if ((reloadConsoleOnCompletionAttribute != null) && (reloadConsoleOnCompletionAttribute.TryGetBoolValue(out reloadConsoleOnCompletion) == false)) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.InvalidAttributeValue"), PackageSystemSettings.ReloadConsoleOnCompletionAttributeName), reloadConsoleOnCompletionAttribute); XElement packageRequirementsElement = installContent.Element(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageRequirementsElementName)); if (packageRequirementsElement == null) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.MissingElement"), PackageSystemSettings.PackageRequirementsElementName), installContent); XAttribute minimumCompositeVersionAttribute = packageRequirementsElement.Attribute(PackageSystemSettings.MinimumCompositeVersionAttributeName); XAttribute maximumCompositeVersionAttribute = packageRequirementsElement.Attribute(PackageSystemSettings.MaximumCompositeVersionAttributeName); if (minimumCompositeVersionAttribute == null) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.MissingAttribute"), PackageSystemSettings.MinimumCompositeVersionAttributeName), packageRequirementsElement); if (maximumCompositeVersionAttribute == null) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.MissingAttribute"), PackageSystemSettings.MaximumCompositeVersionAttributeName), packageRequirementsElement); if (string.IsNullOrEmpty(minimumCompositeVersionAttribute.Value)) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.InvalidAttributeValue"), PackageSystemSettings.MinimumCompositeVersionAttributeName), minimumCompositeVersionAttribute); if (string.IsNullOrEmpty(maximumCompositeVersionAttribute.Value)) return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.InvalidAttributeValue"), PackageSystemSettings.MaximumCompositeVersionAttributeName), maximumCompositeVersionAttribute); if (VersionStringHelper.ValidateVersion(minimumCompositeVersionAttribute.Value, out newVersion)) minimumCompositeVersionAttribute.Value = newVersion; else return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.InvalidAttributeValue"), PackageSystemSettings.VersionAttributeName), minimumCompositeVersionAttribute); if (VersionStringHelper.ValidateVersion(maximumCompositeVersionAttribute.Value, out newVersion)) maximumCompositeVersionAttribute.Value = newVersion; else return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.InvalidAttributeValue"), PackageSystemSettings.VersionAttributeName), maximumCompositeVersionAttribute); packageInformation = new PackageInformation { Id = id, Name = nameAttribute.Value, GroupName = groupNameAttribute.Value, Author = authorAttribute.Value, Website = websiteAttribute.Value, Version = versionAttribute.Value, CanBeUninstalled = canBeUninstalled, SystemLockingType = systemLockingType, Description = packageInformationElement.Value, FlushOnCompletion = flushOnCompletion, ReloadConsoleOnCompletion = reloadConsoleOnCompletion, MinCompositeVersionSupported = new Version(minimumCompositeVersionAttribute.Value), MaxCompositeVersionSupported = new Version(maximumCompositeVersionAttribute.Value) }; return null; } private static PackageFragmentValidationResult SaveZipFile(Stream zipFileStream, out string zipFilename) { zipFilename = null; try { zipFilename = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.PackageDirectory), PackageSystemSettings.ZipFilename); if (C1File.Exists(zipFilename)) { C1File.Delete(zipFilename); } if (C1Directory.Exists(Path.GetDirectoryName(zipFilename)) == false) { C1Directory.CreateDirectory(Path.GetDirectoryName(zipFilename)); } using (Stream readStream = zipFileStream) { using (C1FileStream fileStream = new C1FileStream(zipFilename, FileMode.Create)) { byte[] buffer = new byte[4096]; int readBytes; while ((readBytes = readStream.Read(buffer, 0, 4096)) > 0) { fileStream.Write(buffer, 0, readBytes); } } } return null; } catch (Exception ex) { return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex); } } private static string GetText(string stringId) { return StringResourceSystemFacade.GetString("Composite.Core.PackageSystem.PackageFragmentInstallers", stringId); } private static string CreatePackageDirectoryName(PackageInformation packageInformation) { string directoryName = $"{packageInformation.Id}"; return Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.PackageDirectory), directoryName); } } } ================================================ FILE: Composite/Core/PackageSystem/PackageManagerInstallProcess.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using Composite.Core.IO; using Composite.Core.PackageSystem.Foundation; using Composite.Core.Serialization; using System.ComponentModel; using System.Text; using System.Xml.Linq; using Composite.C1Console.Security; using Composite.Core.Application; namespace Composite.Core.PackageSystem { /// /// /// [EditorBrowsable(EditorBrowsableState.Never)] [SerializerHandler(typeof(PackageManagerInstallProcess))] public sealed class PackageManagerInstallProcess : ISerializerHandler { private static readonly string LogTitle = typeof(PackageManagerInstallProcess).Name; private readonly IPackageInstaller _packageInstaller; private readonly SystemLockingType _systemLockingType; private readonly string _zipFilename; private readonly string _packageInstallDirectory; private readonly string _packageName; private readonly string _packageVersion; private readonly Guid _packageId; private readonly string _originalPackageInstallDirectory; private readonly List _preInstallValidationResult; private List _validationResult; private List _installationResult; /// public string Serialize(object objectToSerialize) { var processToSerialize = objectToSerialize as PackageManagerInstallProcess; var sb = new StringBuilder(); StringConversionServices.SerializeKeyValuePair(sb, "ZipFileName", processToSerialize._zipFilename); StringConversionServices.SerializeKeyValuePair(sb, "PackageInstallDirectory", processToSerialize._packageInstallDirectory); StringConversionServices.SerializeKeyValuePair(sb, "HasBeenValidated", processToSerialize._validationResult != null); StringConversionServices.SerializeKeyValuePair(sb, "OriginalPackageInstallDirectory", processToSerialize._originalPackageInstallDirectory); return sb.ToString(); } /// public object Deserialize(string serializedObject) { Dictionary dic = StringConversionServices.ParseKeyValueCollection(serializedObject); string zipFilename = StringConversionServices.DeserializeValueString(dic["ZipFileName"]); string packageInstallDirectory = StringConversionServices.DeserializeValueString(dic["PackageInstallDirectory"]); bool hasBeenValidated = StringConversionServices.DeserializeValueBool(dic["HasBeenValidated"]); string originalPackageInstallDirectory = null; string serializedValue; if (dic.TryGetValue("OriginalPackageInstallDirectory", out serializedValue)) { originalPackageInstallDirectory = StringConversionServices.DeserializeValueString(serializedValue); } if (C1File.Exists(zipFilename)) { XElement installContent; XmlHelper.LoadInstallXml(zipFilename, out installContent); PackageInformation packageInformation; PackageManager.ValidatePackageInformation(installContent, out packageInformation); string packageZipFilename = Path.Combine(packageInstallDirectory, Path.GetFileName(zipFilename)); C1File.Copy(zipFilename, packageZipFilename, true); var packageInstaller = new PackageInstaller(new PackageInstallerUninstallerFactory(), packageZipFilename, packageInstallDirectory, TempDirectoryFacade.CreateTempDirectory(), packageInformation); var packageManagerInstallProcess = new PackageManagerInstallProcess( packageInstaller, packageInformation.SystemLockingType, zipFilename, packageInstallDirectory, packageInformation.Name, packageInformation.Version, packageInformation.Id, originalPackageInstallDirectory); if (hasBeenValidated) { packageManagerInstallProcess.Validate(); } return packageManagerInstallProcess; } return new PackageManagerInstallProcess(new List(), null);; } /// public PackageManagerInstallProcess() { } internal PackageManagerInstallProcess(List preInstallValidationResult, string zipFilename) { Verify.ArgumentNotNull(preInstallValidationResult, "preInstallValidationResult"); _preInstallValidationResult = preInstallValidationResult; _zipFilename = zipFilename; } internal PackageManagerInstallProcess( IPackageInstaller packageInstaller, SystemLockingType systemLockingType, string zipFilename, string packageInstallDirectory, string packageName, string packageVersion, Guid packageId, string originalPackageInstallDirectory) { Verify.ArgumentNotNull(packageInstaller, "packageInstaller"); Verify.ArgumentNotNullOrEmpty(packageInstallDirectory, "packageInstallDirectory"); _packageInstaller = packageInstaller; _systemLockingType = systemLockingType; _zipFilename = zipFilename; _packageInstallDirectory = packageInstallDirectory; _packageName = packageName; _packageVersion = packageVersion; _packageId = packageId; _originalPackageInstallDirectory = originalPackageInstallDirectory; _preInstallValidationResult = new List(); } /// public bool CanBeUninstalled { get { Verify.IsNotNull(_packageInstaller, "Pre installation did not validate"); return _packageInstaller.CanBeUninstalled; } } /// public bool FlushOnCompletion { get { Verify.IsNotNull(_packageInstaller, "Pre installation did not validate"); return _packageInstaller.FlushOnCompletion; } } /// public bool ReloadConsoleOnCompletion { get { Verify.IsNotNull(_packageInstaller, "Pre installation did not validate"); return _packageInstaller.ReloadConsoleOnCompletion; } } /// public List PreInstallValidationResult { get { return _preInstallValidationResult; } } /// public List Validate() { Verify.IsNotNull(_packageInstaller, "Pre installation did not validate"); Verify.IsNull(_validationResult, "Validate() may only be called once"); _validationResult = _packageInstaller.Validate().ToList(); if (_validationResult.Count > 0) { _validationResult.AddRange(FinalizeProcess(false)); } return _validationResult; } /// public List Install() { Verify.IsNotNull(_packageInstaller, "Pre installation did not validate"); Verify.IsNotNull(_validationResult, "Call validation first"); if (_validationResult.Count > 0) throw new InvalidOperationException("Installation did not validate"); Verify.IsNull(_installationResult, "Install may only be called once"); var userName = UserValidationFacade.IsLoggedIn() ? UserValidationFacade.GetUsername() : ""; Log.LogInformation(LogTitle, $"Installing package: {_packageName}, Version: {_packageVersion}, Id = {_packageId}; User name: '{userName}'"); PackageFragmentValidationResult result = _packageInstaller.Install(_systemLockingType); _installationResult = new List(); if (result != null) { _installationResult.Add(result); } _installationResult.AddRange(FinalizeProcess(true)); return _installationResult; } /// public void CancelInstallation() { if (_zipFilename != null && C1File.Exists(_zipFilename)) { C1File.Delete(_zipFilename); } if (C1Directory.Exists(_packageInstallDirectory)) { C1Directory.Delete(_packageInstallDirectory, true); } } private ICollection FinalizeProcess(bool install) { try { if (_zipFilename != null && C1File.Exists(_zipFilename)) { C1File.Delete(_zipFilename); } Func, bool> isNotEmpty = list => list != null && list.Count > 0; bool installationFailed = isNotEmpty(_preInstallValidationResult) || isNotEmpty(_validationResult) || isNotEmpty(_installationResult); if (installationFailed && C1Directory.Exists(_packageInstallDirectory)) { C1Directory.Delete(_packageInstallDirectory, true); } if(!installationFailed && install) { Log.LogInformation(LogTitle, "Package successfully installed"); C1File.WriteAllText(Path.Combine(_packageInstallDirectory, PackageSystemSettings.InstalledFilename), ""); // Moving package files to a proper location, if an newer version of an already installed package is installed if (_originalPackageInstallDirectory != null) { C1Directory.Delete(_originalPackageInstallDirectory, true); C1Directory.Move(_packageInstallDirectory, _originalPackageInstallDirectory); } } return new PackageFragmentValidationResult[0]; } catch (Exception ex) { return new [] { new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex) }; } } } } ================================================ FILE: Composite/Core/PackageSystem/PackageManagerUninstallProcess.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Core.IO; using Composite.Core.PackageSystem.Foundation; using Composite.Core.Serialization; namespace Composite.Core.PackageSystem { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SerializerHandler(typeof(PackageManagerUninstallProcessSerializerHandler))] public sealed class PackageManagerUninstallProcess { private static readonly string LogTitle = typeof (PackageManagerUninstallProcess).Name; private readonly IPackageUninstaller _packageUninstaller; private readonly string _packageInstallDirectory; private readonly SystemLockingType _systemLockingType; private readonly List _preUninstallValidationResult; private List _validationResult; private List _uninstallationResult; internal PackageManagerUninstallProcess(List preUninstallValidationResult) { if (preUninstallValidationResult == null) throw new ArgumentNullException("preUninstallValidationResult"); _preUninstallValidationResult = preUninstallValidationResult; } internal PackageManagerUninstallProcess(IPackageUninstaller packageUninstaller, string packageInstallDirectory, SystemLockingType systemLockingType) { if (packageUninstaller == null) throw new ArgumentNullException("packageUninstaller"); if (string.IsNullOrEmpty(packageInstallDirectory)) throw new ArgumentNullException("packageInstallDirectory"); _packageUninstaller = packageUninstaller; _packageInstallDirectory = packageInstallDirectory; _systemLockingType = systemLockingType; _preUninstallValidationResult = new List(); } /// public bool FlushOnCompletion { get { Verify.IsNotNull(_packageUninstaller, "Pre un-installation did not validate"); return _packageUninstaller.FlushOnCompletion; } } /// public bool ReloadConsoleOnCompletion { get { Verify.IsNotNull(_packageUninstaller, "Pre un-installation did not validate"); return _packageUninstaller.ReloadConsoleOnCompletion; } } /// public List PreUninstallValidationResult { get { return _preUninstallValidationResult; } } /// public List Validate() { Verify.IsNotNull(_packageUninstaller, "Pre un-installation did not validate"); if (_validationResult != null) throw new InvalidOperationException("Validate may only be called once"); _validationResult = _packageUninstaller.Validate().ToList(); return _validationResult; } /// public List Uninstall() { Verify.IsNotNull(_packageUninstaller, "Pre un-installation did not validate"); if (_validationResult == null) throw new InvalidOperationException("Call validation first"); if (_validationResult.Count > 0) throw new InvalidOperationException("Installation did not validate"); if (_uninstallationResult != null) throw new InvalidOperationException("Install may only be called onece"); PackageFragmentValidationResult result = _packageUninstaller.Uninstall(_systemLockingType); _uninstallationResult = new List(); if (result != null) { _uninstallationResult.Add( result ); } else { _uninstallationResult.AddRange( FinalizeProcess() ); } return _uninstallationResult; } private IEnumerable FinalizeProcess() { try { if (_packageInstallDirectory != null && (_preUninstallValidationResult == null || _preUninstallValidationResult.Count == 0) && (_validationResult == null || _validationResult.Count == 0) && (_uninstallationResult == null || _uninstallationResult.Count == 0)) { if (C1Directory.Exists(_packageInstallDirectory)) { C1Directory.Delete(_packageInstallDirectory, true); } Log.LogInformation(LogTitle, "Package successfully uninstalled"); } return new List(); } catch (Exception ex) { return new List { new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex) }; } } } } ================================================ FILE: Composite/Core/PackageSystem/PackageServerFacade.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using Composite.Core.IO; using Composite.Data; using Composite.Data.Types; namespace Composite.Core.PackageSystem { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum ServerUrlValidationResult { /// Http = 0, /// Https = 1, /// Invalid = 2 } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PackageServerFacade { private static IPackageServerFacade _packageServerFacade; /// static PackageServerFacade() { string testFilePath = Path.Combine(PathUtil.Resolve(PathUtil.BaseDirectory), "App_Data/Composite/PackageDescriptions.xml"); if (C1File.Exists(testFilePath)) { _packageServerFacade = new PackageServerFacadeLocalMock(testFilePath); } else { _packageServerFacade = new PackageServerFacadeImpl(); } } internal static IPackageServerFacade Implementation { get { return _packageServerFacade; } set { _packageServerFacade = value; } } /// /// Connects to the server using either https or http and /// checks to see if it supports the needed services /// /// /// Cleaned url (ex: www.composite.net) /// /// /// public static ServerUrlValidationResult ValidateServerUrl(string packageServerUrl) { return _packageServerFacade.ValidateServerUrl(packageServerUrl); } /// /// Given a cleaned url, returns a series of PackageDescriptions /// /// /// Cleaned url (ex: www.composite.net) /// /// /// /// public static IEnumerable GetPackageDescriptions(string packageServerUrl, Guid installationId, CultureInfo userCulture) { return _packageServerFacade.GetPackageDescriptions(packageServerUrl, installationId, userCulture); } // Overload /// public static IEnumerable GetAllPackageDescriptions(Guid installationId, CultureInfo userCulture) { List packageServerSources = DataFacade.GetData().ToList(); foreach (IPackageServerSource packageServerSource in packageServerSources) { foreach (PackageDescription packageDescription in GetPackageDescriptions(packageServerSource.Url, installationId, userCulture)) { yield return packageDescription; } } } /// public static string GetEulaText(string packageServerUrl, Guid eulaId, CultureInfo userCulture) { return _packageServerFacade.GetEulaText(packageServerUrl, eulaId, userCulture); } /// public static Stream GetInstallFileStream(string packageFileDownloadUrl) { return _packageServerFacade.GetInstallFileStream(packageFileDownloadUrl); } /// public static void RegisterPackageInstallationCompletion(string packageServerUrl, Guid installationId, Guid packageId, string localUserName, string localUserIp) { _packageServerFacade.RegisterPackageInstallationCompletion(packageServerUrl, installationId, packageId, localUserName, localUserIp); } /// public static void RegisterPackageInstallationFailure(string packageServerUrl, Guid installationId, Guid packageId, string localUserName, string localUserIp, string exceptionString) { _packageServerFacade.RegisterPackageInstallationFailure(packageServerUrl, installationId, packageId, localUserName, localUserIp, exceptionString); } /// public static void RegisterPackageUninstall(string packageServerUrl, Guid installationId, Guid packageId, string localUserName, string localUserIp) { _packageServerFacade.RegisterPackageUninstall(packageServerUrl, installationId, packageId, localUserName, localUserIp); } /// public static void ClearServerCache() { _packageServerFacade.ClearCache(); } } } ================================================ FILE: Composite/Core/PackageSystem/PackageServerFacadeImpl.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.ServiceModel; using Composite.Core.PackageSystem.Foundation; using Composite.Core.PackageSystem.WebServiceClient; namespace Composite.Core.PackageSystem { internal sealed class PackageServerFacadeImpl : IPackageServerFacade { const string LogTitle = nameof(PackageServerFacade); private readonly PackageServerFacadeImplCache _packageServerFacadeImplCache = new PackageServerFacadeImplCache(); public ServerUrlValidationResult ValidateServerUrl(string packageServerUrl) { try { var basicHttpBinding = new BasicHttpBinding { MaxReceivedMessageSize = int.MaxValue, Security = {Mode = BasicHttpSecurityMode.Transport} }; var client = new PackagesSoapClient(basicHttpBinding, new EndpointAddress($"https://{packageServerUrl}")); client.IsOperational(); return ServerUrlValidationResult.Https; } catch (Exception) { } try { var basicHttpBinding = new BasicHttpBinding { MaxReceivedMessageSize = int.MaxValue }; var client = new PackagesSoapClient(basicHttpBinding, new EndpointAddress($"http://{packageServerUrl}")); client.IsOperational(); return ServerUrlValidationResult.Http; } catch (Exception) { } return ServerUrlValidationResult.Invalid; } public IEnumerable GetPackageDescriptions(string packageServerUrl, Guid installationId, CultureInfo userCulture) { List packageDescriptions = _packageServerFacadeImplCache.GetCachedPackageDescription(packageServerUrl, installationId, userCulture); if (packageDescriptions != null) return packageDescriptions; PackageDescriptor[] packageDescriptors = null; try { PackagesSoapClient client = CreateClient(packageServerUrl); packageDescriptors = client.GetPackageList(installationId, userCulture.ToString()); } catch (Exception ex) { Log.LogError(LogTitle, ex); } packageDescriptions = new List(); if (packageDescriptors != null) { foreach (var packageDescriptor in packageDescriptors) { if (ValidatePackageDescriptor(packageDescriptor)) { var subscriptionList = new List(); if (packageDescriptor.Subscriptions !=null) { subscriptionList = packageDescriptor.Subscriptions.Select( f => new Subscription { Id = f.Id, Name = f.Name, DetailsUrl = f.DetailsUrl, Purchasable = f.Purchasable }).ToList(); } packageDescriptions.Add(new PackageDescription { PackageFileDownloadUrl = packageDescriptor.PackageFileDownloadUrl, PackageVersion = packageDescriptor.PackageVersion, Description = packageDescriptor.Description, EulaId = packageDescriptor.EulaId, GroupName = packageDescriptor.GroupName, Id = packageDescriptor.Id, InstallationRequireLicenseFileUpdate = packageDescriptor.InstallationRequireLicenseFileUpdate, IsFree = packageDescriptor.IsFree, IsTrial = packageDescriptor.IsTrial, LicenseRuleId = packageDescriptor.LicenseId, MaxCompositeVersionSupported = packageDescriptor.MaxCompositeVersionSupported, MinCompositeVersionSupported = packageDescriptor.MinCompositeVersionSupported, Name = packageDescriptor.Name, PriceAmmount = packageDescriptor.PriceAmmount, PriceCurrency = packageDescriptor.PriceCurrency, ReadMoreUrl = packageDescriptor.ReadMoreUrl, TechicalDetails = packageDescriptor.TechicalDetails, TrialPeriodDays = packageDescriptor.TrialPeriodDays ?? 0, UpgradeAgreementMandatory = packageDescriptor.UpgradeAgreementMandatory, Vendor = packageDescriptor.Author, ConsoleBrowserUrl = packageDescriptor.ConsoleBrowserUrl, AvailableInSubscriptions = subscriptionList }); } } _packageServerFacadeImplCache.AddCachedPackageDescription(packageServerUrl, installationId, userCulture, packageDescriptions); } return packageDescriptions; } public string GetEulaText(string packageServerUrl, Guid eulaId, CultureInfo userCulture) { PackagesSoapClient client = CreateClient(packageServerUrl); return client.GetEulaText(eulaId, userCulture.ToString()); } public Stream GetInstallFileStream(string packageFileDownloadUrl) { Log.LogVerbose(LogTitle, $"Downloading file: {packageFileDownloadUrl}"); var client = new System.Net.WebClient(); return client.OpenRead(packageFileDownloadUrl); } public void RegisterPackageInstallationCompletion(string packageServerUrl, Guid installationId, Guid packageId, string localUserName, string localUserIp) { PackagesSoapClient client = CreateClient(packageServerUrl); client.RegisterPackageInstallationCompletion(installationId, packageId, localUserName, localUserIp); } public void RegisterPackageInstallationFailure(string packageServerUrl, Guid installationId, Guid packageId, string localUserName, string localUserIp, string exceptionString) { PackagesSoapClient client = CreateClient(packageServerUrl); client.RegisterPackageInstallationFailure(installationId, packageId, localUserName, localUserIp, exceptionString); } public void RegisterPackageUninstall(string packageServerUrl, Guid installationId, Guid packageId, string localUserName, string localUserIp) { PackagesSoapClient client = CreateClient(packageServerUrl); client.RegisterPackageUninstall(installationId, packageId, localUserName, localUserIp); } public void ClearCache() { _packageServerFacadeImplCache.Clear(); } private bool ValidatePackageDescriptor(PackageDescriptor packageDescriptor) { string newVersion; if (!VersionStringHelper.ValidateVersion(packageDescriptor.PackageVersion, out newVersion)) { Log.LogWarning(LogTitle, $"The package '{packageDescriptor.Name}' ({packageDescriptor.Id}) did not validate and is skipped"); return false; } packageDescriptor.PackageVersion = newVersion; if (!VersionStringHelper.ValidateVersion(packageDescriptor.MinCompositeVersionSupported, out newVersion)) { Log.LogWarning(LogTitle, $"The package '{packageDescriptor.Name}' ({packageDescriptor.Id}) did not validate and is skipped"); return false; } packageDescriptor.MinCompositeVersionSupported = newVersion; if (!VersionStringHelper.ValidateVersion(packageDescriptor.MaxCompositeVersionSupported, out newVersion)) { Log.LogWarning(LogTitle, $"The package '{packageDescriptor.Name}' ({packageDescriptor.Id}) did not validate and is skipped"); return false; } packageDescriptor.MaxCompositeVersionSupported = newVersion; return true; } private PackagesSoapClient CreateClient(string packageServerUrl) { var timeout = TimeSpan.FromMinutes(RuntimeInformation.IsDebugBuild ? 2 : 1); var basicHttpBinding = new BasicHttpBinding { CloseTimeout = timeout, OpenTimeout = timeout, ReceiveTimeout = timeout, SendTimeout = timeout }; if (packageServerUrl.StartsWith("https")) { basicHttpBinding.Security.Mode = BasicHttpSecurityMode.Transport; } basicHttpBinding.MaxReceivedMessageSize = int.MaxValue; return new PackagesSoapClient(basicHttpBinding, new EndpointAddress(packageServerUrl)); } } } ================================================ FILE: Composite/Core/PackageSystem/PackageServerFacadeLocalMock.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Xml.Linq; using Composite.C1Console.Events; using Composite.Core.Logging; using Composite.Core.PackageSystem.Foundation; using Composite.Core.Xml; namespace Composite.Core.PackageSystem { internal sealed class PackageServerFacadeLocalMock : IPackageServerFacade { private sealed class ExtraInfo { public bool CanBeUninstalled { get; set; } public SystemLockingType SystemLockingType { get; set; } public bool FlushOnCompletion { get; set; } public bool ReloadConsoleOnCompletion { get; set; } } private string _configFilePath; private Dictionary>> _packageDescriptions = null; private Dictionary> _eulaTexts = null; internal PackageServerFacadeLocalMock(string configFilePath) { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlush); _configFilePath = configFilePath; } public ServerUrlValidationResult ValidateServerUrl(string packageServerUrl) { if (packageServerUrl.ToLowerInvariant().EndsWith("dk")) return ServerUrlValidationResult.Http; if (packageServerUrl.ToLowerInvariant().EndsWith("net")) return ServerUrlValidationResult.Https; if (packageServerUrl.ToLowerInvariant().EndsWith("xxx")) return ServerUrlValidationResult.Invalid; return ServerUrlValidationResult.Http; } public IEnumerable GetPackageDescriptions(string packageServerUrl, Guid installationId, CultureInfo userCulture) { Initialize(); packageServerUrl = packageServerUrl.ToLowerInvariant(); if (_packageDescriptions.ContainsKey(packageServerUrl)) { return _packageDescriptions[packageServerUrl].Select(f => f.Key); } else { return new List(); } } public string GetEulaText(string packageServerUrl, Guid eulaId, CultureInfo userCulture) { Initialize(); packageServerUrl = packageServerUrl.ToLowerInvariant(); if ((_eulaTexts.ContainsKey(packageServerUrl)) && (_eulaTexts[packageServerUrl].ContainsKey(eulaId))) { return _eulaTexts[packageServerUrl][eulaId]; } else { return "SERVER NOT FOUND"; } } public Stream GetInstallFileStream(string packageFileDownloadUrl) { Initialize(); PackageDescription packageDescription = null; ExtraInfo extraInfo = null; foreach (List> packageDescriptions in _packageDescriptions.Values) { KeyValuePair? q = (from desc in packageDescriptions where desc.Key.PackageFileDownloadUrl == packageFileDownloadUrl select desc).FirstOrDefault(); if (q != null) { packageDescription = q.Value.Key; extraInfo = q.Value.Value; break; } } XElement rootElement = new XElement(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageInstallerElementName), new XElement(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageRequirementsElementName), new XAttribute(PackageSystemSettings.MinimumCompositeVersionAttributeName, packageDescription.MinCompositeVersionSupported), new XAttribute(PackageSystemSettings.MaximumCompositeVersionAttributeName, packageDescription.MaxCompositeVersionSupported) ), new XElement(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageInformationElementName), new XAttribute(PackageSystemSettings.IdAttributeName, packageDescription.Id), new XAttribute(PackageSystemSettings.NameAttributeName, packageDescription.Name), new XAttribute(PackageSystemSettings.GroupNameAttributeName, packageDescription.GroupName), new XAttribute(PackageSystemSettings.AuthorAttributeName, packageDescription.Vendor), new XAttribute(PackageSystemSettings.WebsiteAttributeName, packageDescription.ReadMoreUrl), new XAttribute(PackageSystemSettings.VersionAttributeName, packageDescription.PackageVersion), new XAttribute(PackageSystemSettings.CanBeUninstalledAttributeName, extraInfo.CanBeUninstalled), new XAttribute(PackageSystemSettings.SystemLockingAttributeName, extraInfo.SystemLockingType.Serialize()), new XAttribute(PackageSystemSettings.FlushOnCompletionAttributeName, extraInfo.FlushOnCompletion), new XAttribute(PackageSystemSettings.ReloadConsoleOnCompletionAttributeName, extraInfo.ReloadConsoleOnCompletion), packageDescription.Description ), new XElement(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageFragmentInstallersElementName)) ); XDocument doc = new XDocument(rootElement); string content = doc.GetDocumentAsString(); UTF8Encoding encoding = new UTF8Encoding(); byte[] buffer = encoding.GetBytes(content); var outputStream = new MemoryStream(); var zipArchive = new ZipArchive(outputStream); var zipEntry = zipArchive.CreateEntry("install.xml"); using (var stream = zipEntry.Open()) { stream.Write(buffer, 0, buffer.Length); } zipEntry.LastWriteTime = DateTimeOffset.Now; outputStream.Seek(0, SeekOrigin.Begin); return outputStream; } public void RegisterPackageInstallationCompletion(string packageServerUrl, Guid installationId, Guid packageId, string localUserName, string localUserIp) { LoggingService.LogVerbose("PackageServerFacadeLocalMock", string.Format("RegisterPackageInstallationCompletion: installationId = {0}, packageId = {1}, localUserName = {2}, localUserIp = {3}", installationId, packageId, localUserName, localUserIp)); } public void RegisterPackageInstallationFailure(string packageServerUrl, Guid installationId, Guid packageId, string localUserName, string localUserIp, string exceptionString) { LoggingService.LogVerbose("PackageServerFacadeLocalMock", string.Format("RegisterPackageInstallationFailure: installationId = {0}, packageId = {1}, localUserName = {2}, localUserIp = {3}, error = {4}", installationId, packageId, localUserName, localUserIp, exceptionString)); } public void RegisterPackageUninstall(string packageServerUrl, Guid installationId, Guid packageId, string localUserName, string localUserIp) { LoggingService.LogVerbose("PackageServerFacadeLocalMock", string.Format("RegisterPackageUninstall: installationId = {0}, packageId = {1}, localUserName = {2}, localUserIp = {3}", installationId, packageId, localUserName, localUserIp)); } public void ClearCache() { throw new NotImplementedException(); } private void Initialize() { if (_packageDescriptions == null) { LoadXml(); } } private void LoadXml() { _packageDescriptions = new Dictionary>>(); _eulaTexts = new Dictionary>(); XDocument doc = XDocumentUtils.Load(_configFilePath); foreach (XElement element in doc.Root.Elements("Source")) { XAttribute urlAttribute = element.Attribute("url"); List> packageDescriptions = new List>(); foreach (XElement packageElement in element.Elements("PackageDescription")) { PackageDescription packageDescription = new PackageDescription(); packageDescription.PackageVersion = packageElement.Attribute("packageVersion").Value; packageDescription.PackageFileDownloadUrl = packageElement.Attribute("packageFileDownloadUrl").Value; packageDescription.Description = packageElement.Attribute("description").Value; packageDescription.EulaId = (Guid)packageElement.Attribute("eulaId"); packageDescription.GroupName = packageElement.Attribute("groupName").Value; packageDescription.Id = (Guid)packageElement.Attribute("id"); packageDescription.InstallationRequireLicenseFileUpdate = (bool)packageElement.Attribute("installationRequireLicenseFileUpdate"); packageDescription.IsFree = (bool)packageElement.Attribute("isFree"); packageDescription.IsTrial = (bool)packageElement.Attribute("isTrial"); packageDescription.LicenseRuleId = (Guid)packageElement.Attribute("licenseRuleId"); packageDescription.MaxCompositeVersionSupported = packageElement.Attribute("maxCompositeVersionSupported").Value; packageDescription.MinCompositeVersionSupported = packageElement.Attribute("minCompositeVersionSupported").Value; packageDescription.Name = packageElement.Attribute("name").Value; packageDescription.PriceAmmount = (decimal)packageElement.Attribute("priceAmmount"); packageDescription.PriceCurrency = packageElement.Attribute("priceCurrency").Value; packageDescription.ReadMoreUrl = packageElement.Attribute("readMoreUrl").Value; packageDescription.TechicalDetails = packageElement.Attribute("techicalDetails").Value; packageDescription.TrialPeriodDays = (int)packageElement.Attribute("trialPeriodDays"); packageDescription.UpgradeAgreementMandatory = (bool)packageElement.Attribute("upgradeAgreementMandatory"); packageDescription.Vendor = packageElement.Attribute("vendor").Value; ExtraInfo extraInfo = new ExtraInfo(); if (packageElement.Attribute("canBeUninstalled") != null) extraInfo.CanBeUninstalled = (bool)packageElement.Attribute("canBeUninstalled"); if (packageElement.Attribute("flushOnCompletion") != null) extraInfo.FlushOnCompletion = (bool)packageElement.Attribute("flushOnCompletion"); if (packageElement.Attribute("reloadConsoleOnCompletion") != null) extraInfo.ReloadConsoleOnCompletion = (bool)packageElement.Attribute("reloadConsoleOnCompletion"); if (packageElement.Attribute("systemLocking") != null) { SystemLockingType systemLockingType; packageElement.Attribute("systemLocking").TryDeserialize(out systemLockingType); extraInfo.SystemLockingType = systemLockingType; } packageDescriptions.Add(new KeyValuePair(packageDescription, extraInfo)); } _packageDescriptions.Add(element.Attribute("url").Value.ToLowerInvariant(), packageDescriptions); Dictionary eulaTexts = new Dictionary(); foreach (XElement eulaTextElement in element.Elements("EulaText")) { eulaTexts.Add( (Guid)eulaTextElement.Attribute("id"), eulaTextElement.Value ); } _eulaTexts.Add(element.Attribute("url").Value.ToLowerInvariant(), eulaTexts); } } private void OnFlush(FlushEventArgs args) { _packageDescriptions = null; } } } ================================================ FILE: Composite/Core/PackageSystem/PackageSystemServices.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Xml.Linq; using Composite.Data; using Composite.Data.Types; using Composite.Core.Configuration; using Composite.Core.PackageSystem.Foundation; using Composite.C1Console.Users; namespace Composite.Core.PackageSystem { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PackageSystemServices { /// public static IEnumerable GetAllAvailablePackages() { return PackageServerFacade.GetAllPackageDescriptions(InstallationInformationFacade.InstallationId, UserSettings.CultureInfo); } /// public static IEnumerable GetFilteredAllAvailablePackages() { List installedPackageInformation = PackageManager.GetInstalledPackages().ToList(); IEnumerable descriptions = from description in PackageServerFacade.GetAllPackageDescriptions(InstallationInformationFacade.InstallationId, UserSettings.CultureInfo) where installedPackageInformation.All(f => f.Id != description.Id) select description; Dictionary> packageDescriptions = new Dictionary>(); foreach (PackageDescription packageDescription in descriptions) { if ((new Version(packageDescription.MinCompositeVersionSupported) <= RuntimeInformation.ProductVersion) && (new Version(packageDescription.MaxCompositeVersionSupported) >= RuntimeInformation.ProductVersion)) { List decs; if (!packageDescriptions.TryGetValue(packageDescription.Id, out decs)) { decs = new List(); packageDescriptions.Add(packageDescription.Id, decs); } decs.Add(packageDescription); } } foreach (var kvp in packageDescriptions) { if (kvp.Value.Count > 1) { kvp.Value.Sort(delegate(PackageDescription x, PackageDescription y) { Version xVersion = new Version(x.PackageVersion); Version yVersion = new Version(y.PackageVersion); return xVersion.CompareTo(yVersion); }); } yield return kvp.Value.Last(); } } /// public static string GetPackageSourceNameByPackageId(Guid id, Guid installationId, CultureInfo userCulture) { List packageServerSources = DataFacade.GetData().ToList(); foreach (IPackageServerSource packageServerSource in packageServerSources) { PackageDescription foundPackageDescription = (from package in PackageServerFacade.GetPackageDescriptions(packageServerSource.Url, installationId, userCulture) where package.Id == id select package).FirstOrDefault(); if (foundPackageDescription != null) { return packageServerSource.Url; } } throw new InvalidOperationException("Source not found"); } /// public static string GetEulaText(PackageDescription packageDescription) { string packageSource = PackageSystemServices.GetPackageSourceNameByPackageId(packageDescription.Id, InstallationInformationFacade.InstallationId, UserSettings.CultureInfo); string text = PackageServerFacade.GetEulaText(packageSource, packageDescription.EulaId, UserSettings.CultureInfo); return text; } /// public static PackageInformation GetPackageInformationFromZipfile(string zipFilename) { XElement installContent; PackageFragmentValidationResult packageFragmentValidationResult = XmlHelper.LoadInstallXml(zipFilename, out installContent); if (packageFragmentValidationResult != null) throw new InvalidOperationException(packageFragmentValidationResult.Message); PackageInformation packageInformation; packageFragmentValidationResult = PackageManager.ValidatePackageInformation(installContent, out packageInformation); if (packageFragmentValidationResult != null) throw new InvalidOperationException(packageFragmentValidationResult.Message); return packageInformation; } } } ================================================ FILE: Composite/Core/PackageSystem/PackageUninstaller.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using Composite.C1Console.Security; using Composite.Core.Application; using Composite.Core.IO; using Composite.Core.IO.Zip; using Composite.Core.PackageSystem.Foundation; using Composite.Core.Types; using Composite.Core.Xml; using Composite.Data.Transactions; namespace Composite.Core.PackageSystem { internal sealed class PackageUninstaller : IPackageUninstaller { public static readonly string LogTitle = typeof (PackageUninstaller).Name; private bool _isInitialized; private readonly List _packageFramentUninstallers = new List(); private string ZipFilename { get; set; } private string UninstallFilename { get; set; } private string PackageInstallationDirectory { get; set; } private string TempDirectory { get; set; } private bool UseTransaction { get; set; } private PackageInformation PackageInformation { get; set; } public PackageUninstaller(string zipFilename, string uninstallFilename, string packageInstallationDirectory, string tempDirectory, bool flushOnCompletion, bool reloadConsoleOnCompletion, bool useTransaction, PackageInformation packageInformation) { Verify.ArgumentNotNullOrEmpty(zipFilename, "zipFilename"); Verify.ArgumentNotNullOrEmpty(uninstallFilename, "uninstallFilename"); Verify.ArgumentNotNullOrEmpty(packageInstallationDirectory, "packageInstallationDirectory"); Verify.ArgumentNotNullOrEmpty(tempDirectory, "tempDirectory"); this.ZipFilename = zipFilename; this.UninstallFilename = uninstallFilename; this.PackageInstallationDirectory = packageInstallationDirectory; this.TempDirectory = tempDirectory; this.FlushOnCompletion = flushOnCompletion; this.ReloadConsoleOnCompletion = reloadConsoleOnCompletion; this.UseTransaction = useTransaction; this.PackageInformation = packageInformation; } public bool FlushOnCompletion { get; set; } public bool ReloadConsoleOnCompletion { get; set; } public IEnumerable Validate() { List validationResult = Initialize().ToList(); if (validationResult.Count > 0) { return validationResult; } foreach (var packageFragmentUninstaller in _packageFramentUninstallers.OrderByDescending(p => p.ValidateFirst)) { try { validationResult.AddRange(packageFragmentUninstaller.Validate()); } catch (Exception ex) { validationResult.Add(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex)); } } return validationResult; } public PackageFragmentValidationResult Uninstall(SystemLockingType systemLockingType) { try { if (systemLockingType == SystemLockingType.None) { if (this.UseTransaction) { DoUninstall(); } else { DoUninstallWithoutTransaction(); } } else { bool isSoftSystemLocking = (systemLockingType == SystemLockingType.Soft); string errorMessage; if (!ApplicationOnlineHandlerFacade.CanPutApplicationOffline(isSoftSystemLocking, out errorMessage)) { return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, errorMessage); } using (ApplicationOnlineHandlerFacade.TurnOffScope(isSoftSystemLocking)) { if (this.UseTransaction) { DoUninstall(); } else { DoUninstallWithoutTransaction(); } } } } catch (Exception ex) { return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex); } return null; } private void DoUninstall() { using (var transactionScope = TransactionsFacade.CreateNewScope()) { DoUninstallWithoutTransaction(); transactionScope.Complete(); } } private void DoUninstallWithoutTransaction() { var userName = UserValidationFacade.IsLoggedIn() ? UserValidationFacade.GetUsername() : ""; Log.LogInformation(LogTitle, $"Uninstalling package '{PackageInformation.Name}', Id = {PackageInformation.Id}. User name: '{userName}'"); try { foreach (IPackageFragmentUninstaller packageFragmentUninstaller in _packageFramentUninstallers) { packageFragmentUninstaller.Uninstall(); } } catch (Exception ex) { Log.LogError(LogTitle, ex); throw; } Log.LogInformation(LogTitle, "Package uninstalled successfully."); } private IEnumerable Initialize() { if (_isInitialized) throw new InvalidOperationException("Initialize may only be called once"); _isInitialized = true; List result1 = LoadPackageFragmentInstallerBinaries().ToList(); if (result1.Count > 0) return result1; XElement uninstallElement = null; Exception exception = null; try { uninstallElement = LoadXml(); } catch (Exception ex) { exception = ex; } if (exception != null) { return new[] { new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, exception) }; } XElement packageFragmentUninstallersElement = uninstallElement.Element(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageFragmentUninstallersElementName)); if (packageFragmentUninstallersElement == null) { return new[] { new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format("The '{0}' file is wrongly formatted", this.UninstallFilename)) }; } List result2 = LoadPackageFramentUninstallers(packageFragmentUninstallersElement).ToList(); if (result2.Any()) return result2; _packageFramentUninstallers.Reverse(); return new PackageFragmentValidationResult[] { }; } private IEnumerable LoadPackageFragmentInstallerBinaries() { string binariesDirectory = Path.Combine(this.PackageInstallationDirectory, PackageSystemSettings.BinariesDirectoryName); if (!C1Directory.Exists(binariesDirectory)) { yield break; } foreach (string filename in C1Directory.GetFiles(binariesDirectory)) { string newFilename = Path.Combine(this.TempDirectory, Path.GetFileName(filename)); C1File.Copy(filename, newFilename); Log.LogVerbose("PackageUninstaller", "Loading package uninstaller fragment assembly '{0}'", newFilename); Exception exception = null; try { PackageAssemblyHandler.AddAssembly(newFilename); } catch (Exception ex) { exception = ex; } if (exception != null) { yield return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, exception); } } } private IEnumerable LoadPackageFramentUninstallers(XElement packageFragmentInstallersElement) { PackageUninstallerContext packageUninstallerContext = null; Exception exception = null; try { string packageDirectory = Path.GetDirectoryName(ZipFilename); packageUninstallerContext = new PackageUninstallerContext(new ZipFileSystem(this.ZipFilename), packageDirectory, this.PackageInformation); } catch (Exception ex) { exception = ex; } if (exception != null) { yield return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, exception); yield break; } foreach (XElement element in packageFragmentInstallersElement.Elements(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageFragmentUninstallersAddElementName))) { XAttribute uninstallerTypeAttribute = element.Attribute(PackageSystemSettings.UninstallerTypeAttributeName); if (uninstallerTypeAttribute == null) { yield return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format("Missing attribute '{0}'", PackageSystemSettings.UninstallerTypeAttributeName), element); continue; } Type uninstallerType = TypeManager.TryGetType(uninstallerTypeAttribute.Value); if (uninstallerType == null) { yield return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format("Could not find uninstall fragment type '{0}'", uninstallerTypeAttribute.Value), uninstallerTypeAttribute); continue; } exception = null; IPackageFragmentUninstaller packageFragmentUninstaller = null; try { packageFragmentUninstaller = Activator.CreateInstance(uninstallerType) as IPackageFragmentUninstaller; } catch (Exception ex) { exception = ex; } if (exception != null) { yield return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, exception); continue; } if (packageFragmentUninstaller == null) { yield return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format("The type '{0}' does not implement {1}", uninstallerTypeAttribute.Value, typeof(IPackageFragmentUninstaller)), uninstallerTypeAttribute); continue; } try { packageFragmentUninstaller.Initialize(packageUninstallerContext, element.Descendants(), element); } catch (Exception ex) { exception = ex; } if (exception != null) { yield return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, exception); continue; } _packageFramentUninstallers.Add(packageFragmentUninstaller); } } private XElement LoadXml() { XDocument doc = XDocumentUtils.Load(this.UninstallFilename); return doc.Root; } } } ================================================ FILE: Composite/Core/PackageSystem/PackageUninstallerContext.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using Composite.Core.Extensions; using Composite.Data; using Composite.Core.IO.Zip; namespace Composite.Core.PackageSystem { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class PackageUninstallerContext { private readonly Dictionary>>> _dataPendingForDeletion = new Dictionary>>>(); private readonly HashSet _typesToBeDeleted = new HashSet(); internal PackageUninstallerContext(IZipFileSystem zipFileSystem, string packageDirectory, PackageInformation packageInformation) { Verify.ArgumentNotNull(zipFileSystem, "zipFileSystem"); this.ZipFileSystem = zipFileSystem; this.PackageDirectory = packageDirectory; this.PackageInformation = packageInformation; } /// public IZipFileSystem ZipFileSystem { get; private set; } /// public string PackageDirectory { get; private set; } /// public PackageInformation PackageInformation { get; private set; } /// public void AddPendingForDeletionData(Type interfaceType, DataScopeIdentifier dataScopeIdentifier, CultureInfo locale, DataKeyPropertyCollection dataKeyPropertyCollection) { Verify.ArgumentNotNull(interfaceType, "interfaceType"); Verify.ArgumentNotNull(dataScopeIdentifier, "dataScopeIdentifier"); Verify.ArgumentNotNull(dataKeyPropertyCollection, "dataKeyPropertyCollection"); List dataKeyPropertyCollections = GetDataKeyPropertyCollection(interfaceType, dataScopeIdentifier, locale); if (dataKeyPropertyCollections.Contains(dataKeyPropertyCollection)) { throw new ArgumentException(string.Format("The data item of type '{0}' with the key '{1}' has already been added", interfaceType, dataKeyPropertyCollection)); } dataKeyPropertyCollections.Add(dataKeyPropertyCollection); } /// public bool IsPendingForDeletionData(IData data) { Verify.ArgumentNotNull(data, "data"); if (_typesToBeDeleted.Contains(data.DataSourceId.InterfaceType)) { return true; } DataKeyPropertyCollection dataKeyPropertyCollection = data.CreateDataKeyPropertyCollection(); return IsPendingForDeletionData(data.DataSourceId.InterfaceType, data.DataSourceId.DataScopeIdentifier, data.DataSourceId.LocaleScope, dataKeyPropertyCollection); } /// public bool IsPendingForDeletionData(Type interfaceType, DataScopeIdentifier dataScopeIdentifier, CultureInfo locale, DataKeyPropertyCollection dataKeyPropertyCollection) { Verify.ArgumentNotNull(interfaceType, "interfaceType"); Verify.ArgumentNotNull(dataScopeIdentifier, "dataScopeIdentifier"); Verify.ArgumentNotNull(dataKeyPropertyCollection, "dataKeyPropertyCollection"); List dataKeyPropertyCollections = GetDataKeyPropertyCollection(interfaceType, dataScopeIdentifier, locale); return dataKeyPropertyCollections.Contains(dataKeyPropertyCollection); } private List GetDataKeyPropertyCollection(Type interfaceType, DataScopeIdentifier dataScopeIdentifier, CultureInfo locale) { if (locale == null) { locale = CultureInfo.InvariantCulture; } return _dataPendingForDeletion .GetOrAdd(interfaceType, () => new Dictionary>>()) .GetOrAdd(dataScopeIdentifier, () => new Dictionary>()) .GetOrAdd(locale, () => new List()); } internal void AddPendingForDeletionDataType(Type intefaceType) { _typesToBeDeleted.Add(intefaceType); } } } ================================================ FILE: Composite/Core/PackageSystem/PackageUtils.cs ================================================ using System; using Composite.Core.Implementation; using Composite.Plugins.Elements.ElementProviders.PackageElementProvider; namespace Composite.Core.PackageSystem { /// /// This class contains helper methods for handling packages /// public static class PackageUtils { /// /// This method returns an entity token for a install package in the C1 console. /// /// The id of the package. /// The group name of the package. /// Returns an entity token for a installed package. public static PackageElementProviderInstalledPackageItemEntityToken GetInstalledPackageEntityToken(Guid packageId, string groupName) { return ImplementationFactory.CurrentFactory.StatelessPackageUtils.GetInstalledPackageEntityToken(packageId, groupName); } } } ================================================ FILE: Composite/Core/PackageSystem/WebServiceClient/LicenseDefinitionServiceSoapClient.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace Composite.Core.PackageSystem.WebServiceClient { using System.Runtime.Serialization; using System; /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name = "LicenseDefinitionDescriptor", Namespace = "http://www.composite.net/ns/managemen")] [System.SerializableAttribute()] public partial class LicenseDefinitionDescriptor : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; private System.Guid InstallationIdField; private System.Guid ProductIdField; private bool PermanentField; private System.DateTime ExpiresField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string LicenseKeyField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string PurchaseUrlField; /// [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } /// [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true)] public System.Guid InstallationId { get { return this.InstallationIdField; } set { if ((this.InstallationIdField.Equals(value) != true)) { this.InstallationIdField = value; this.RaisePropertyChanged("InstallationId"); } } } /// [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true)] public System.Guid ProductId { get { return this.ProductIdField; } set { if ((this.ProductIdField.Equals(value) != true)) { this.ProductIdField = value; this.RaisePropertyChanged("ProductId"); } } } /// [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true, Order = 2)] public bool Permanent { get { return this.PermanentField; } set { if ((this.PermanentField.Equals(value) != true)) { this.PermanentField = value; this.RaisePropertyChanged("Permanent"); } } } /// [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true, Order = 3)] public System.DateTime Expires { get { return this.ExpiresField; } set { if ((this.ExpiresField.Equals(value) != true)) { this.ExpiresField = value; this.RaisePropertyChanged("Expires"); } } } /// [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 4)] public string LicenseKey { get { return this.LicenseKeyField; } set { if ((object.ReferenceEquals(this.LicenseKeyField, value) != true)) { this.LicenseKeyField = value; this.RaisePropertyChanged("LicenseKey"); } } } /// [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 5)] public string PurchaseUrl { get { return this.PurchaseUrlField; } set { if ((object.ReferenceEquals(this.PurchaseUrlField, value) != true)) { this.PurchaseUrlField = value; this.RaisePropertyChanged("PurchaseUrl"); } } } /// public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; /// protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged != null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ServiceModel.ServiceContractAttribute(Namespace = "http://www.composite.net/ns/managemen", ConfigurationName = "Composite.Core.PackageSystem.WebServiceClient.LicenseDefinitionServiceSoap")] public interface LicenseDefinitionServiceSoap { // CODEGEN: Generating message contract since element name publicKeyXml from namespace http://www.composite.net/ns/managemen is not marked nillable /// [System.ServiceModel.OperationContractAttribute(Action = "http://www.composite.net/ns/managemen/ValidateTrialLicenseDefinitionRequest", ReplyAction = "*")] Composite.Core.PackageSystem.WebServiceClient.ValidateTrialLicenseDefinitionRequestResponse ValidateTrialLicenseDefinitionRequest(Composite.Core.PackageSystem.WebServiceClient.ValidateTrialLicenseDefinitionRequestRequest request); // CODEGEN: Generating message contract since element name publicKeyXml from namespace http://www.composite.net/ns/managemen is not marked nillable /// [System.ServiceModel.OperationContractAttribute(Action = "http://www.composite.net/ns/managemen/GetTrialLicenseDefinition", ReplyAction = "*")] Composite.Core.PackageSystem.WebServiceClient.GetTrialLicenseDefinitionResponse GetTrialLicenseDefinition(Composite.Core.PackageSystem.WebServiceClient.GetTrialLicenseDefinitionRequest request); } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] public partial class ValidateTrialLicenseDefinitionRequestRequest { /// [System.ServiceModel.MessageBodyMemberAttribute(Name = "ValidateTrialLicenseDefinitionRequest", Namespace = "http://www.composite.net/ns/managemen", Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.ValidateTrialLicenseDefinitionRequestRequestBody Body; /// public ValidateTrialLicenseDefinitionRequestRequest() { } /// public ValidateTrialLicenseDefinitionRequestRequest(Composite.Core.PackageSystem.WebServiceClient.ValidateTrialLicenseDefinitionRequestRequestBody Body) { this.Body = Body; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://www.composite.net/ns/managemen")] public partial class ValidateTrialLicenseDefinitionRequestRequestBody { /// [System.Runtime.Serialization.DataMemberAttribute(Order = 0)] public System.Guid installationId; /// [System.Runtime.Serialization.DataMemberAttribute(Order = 1)] public System.Guid productId; /// [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 2)] public string publicKeyXml; /// public ValidateTrialLicenseDefinitionRequestRequestBody() { } /// public ValidateTrialLicenseDefinitionRequestRequestBody(System.Guid installationId, System.Guid productId, string publicKeyXml) { this.installationId = installationId; this.productId = productId; this.publicKeyXml = publicKeyXml; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] public partial class ValidateTrialLicenseDefinitionRequestResponse { /// [System.ServiceModel.MessageBodyMemberAttribute(Name = "ValidateTrialLicenseDefinitionRequestResponse", Namespace = "http://www.composite.net/ns/managemen", Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.ValidateTrialLicenseDefinitionRequestResponseBody Body; /// public ValidateTrialLicenseDefinitionRequestResponse() { } /// public ValidateTrialLicenseDefinitionRequestResponse(Composite.Core.PackageSystem.WebServiceClient.ValidateTrialLicenseDefinitionRequestResponseBody Body) { this.Body = Body; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://www.composite.net/ns/managemen")] public partial class ValidateTrialLicenseDefinitionRequestResponseBody { /// [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 0)] public string ValidateTrialLicenseDefinitionRequestResult; /// public ValidateTrialLicenseDefinitionRequestResponseBody() { } /// public ValidateTrialLicenseDefinitionRequestResponseBody(string ValidateTrialLicenseDefinitionRequestResult) { this.ValidateTrialLicenseDefinitionRequestResult = ValidateTrialLicenseDefinitionRequestResult; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] public partial class GetTrialLicenseDefinitionRequest { /// [System.ServiceModel.MessageBodyMemberAttribute(Name = "GetTrialLicenseDefinition", Namespace = "http://www.composite.net/ns/managemen", Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.GetTrialLicenseDefinitionRequestBody Body; /// public GetTrialLicenseDefinitionRequest() { } /// public GetTrialLicenseDefinitionRequest(Composite.Core.PackageSystem.WebServiceClient.GetTrialLicenseDefinitionRequestBody Body) { this.Body = Body; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://www.composite.net/ns/managemen")] public partial class GetTrialLicenseDefinitionRequestBody { /// [System.Runtime.Serialization.DataMemberAttribute(Order = 0)] public System.Guid installationId; /// [System.Runtime.Serialization.DataMemberAttribute(Order = 1)] public System.Guid productId; /// [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 2)] public string publicKeyXml; /// public GetTrialLicenseDefinitionRequestBody() { } /// public GetTrialLicenseDefinitionRequestBody(System.Guid installationId, System.Guid productId, string publicKeyXml) { this.installationId = installationId; this.productId = productId; this.publicKeyXml = publicKeyXml; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] public partial class GetTrialLicenseDefinitionResponse { /// [System.ServiceModel.MessageBodyMemberAttribute(Name = "GetTrialLicenseDefinitionResponse", Namespace = "http://www.composite.net/ns/managemen", Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.GetTrialLicenseDefinitionResponseBody Body; /// public GetTrialLicenseDefinitionResponse() { } /// public GetTrialLicenseDefinitionResponse(Composite.Core.PackageSystem.WebServiceClient.GetTrialLicenseDefinitionResponseBody Body) { this.Body = Body; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://www.composite.net/ns/managemen")] public partial class GetTrialLicenseDefinitionResponseBody { /// [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.LicenseDefinitionDescriptor GetTrialLicenseDefinitionResult; /// public GetTrialLicenseDefinitionResponseBody() { } /// public GetTrialLicenseDefinitionResponseBody(Composite.Core.PackageSystem.WebServiceClient.LicenseDefinitionDescriptor GetTrialLicenseDefinitionResult) { this.GetTrialLicenseDefinitionResult = GetTrialLicenseDefinitionResult; } } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public interface LicenseDefinitionServiceSoapChannel : Composite.Core.PackageSystem.WebServiceClient.LicenseDefinitionServiceSoap, System.ServiceModel.IClientChannel { } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public partial class LicenseDefinitionServiceSoapClient : System.ServiceModel.ClientBase, Composite.Core.PackageSystem.WebServiceClient.LicenseDefinitionServiceSoap { /// public LicenseDefinitionServiceSoapClient() { } /// public LicenseDefinitionServiceSoapClient(string endpointConfigurationName) : base(endpointConfigurationName) { } /// public LicenseDefinitionServiceSoapClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } /// public LicenseDefinitionServiceSoapClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } /// public LicenseDefinitionServiceSoapClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } /// [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] Composite.Core.PackageSystem.WebServiceClient.ValidateTrialLicenseDefinitionRequestResponse Composite.Core.PackageSystem.WebServiceClient.LicenseDefinitionServiceSoap.ValidateTrialLicenseDefinitionRequest(Composite.Core.PackageSystem.WebServiceClient.ValidateTrialLicenseDefinitionRequestRequest request) { return base.Channel.ValidateTrialLicenseDefinitionRequest(request); } /// public string ValidateTrialLicenseDefinitionRequest(System.Guid installationId, System.Guid productId, string publicKeyXml) { Composite.Core.PackageSystem.WebServiceClient.ValidateTrialLicenseDefinitionRequestRequest inValue = new Composite.Core.PackageSystem.WebServiceClient.ValidateTrialLicenseDefinitionRequestRequest(); inValue.Body = new Composite.Core.PackageSystem.WebServiceClient.ValidateTrialLicenseDefinitionRequestRequestBody(); inValue.Body.installationId = installationId; inValue.Body.productId = productId; inValue.Body.publicKeyXml = publicKeyXml; Composite.Core.PackageSystem.WebServiceClient.ValidateTrialLicenseDefinitionRequestResponse retVal = ((Composite.Core.PackageSystem.WebServiceClient.LicenseDefinitionServiceSoap)(this)).ValidateTrialLicenseDefinitionRequest(inValue); return retVal.Body.ValidateTrialLicenseDefinitionRequestResult; } /// [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] Composite.Core.PackageSystem.WebServiceClient.GetTrialLicenseDefinitionResponse Composite.Core.PackageSystem.WebServiceClient.LicenseDefinitionServiceSoap.GetTrialLicenseDefinition(Composite.Core.PackageSystem.WebServiceClient.GetTrialLicenseDefinitionRequest request) { return base.Channel.GetTrialLicenseDefinition(request); } /// public Composite.Core.PackageSystem.WebServiceClient.LicenseDefinitionDescriptor GetTrialLicenseDefinition(System.Guid installationId, System.Guid productId, string publicKeyXml) { Composite.Core.PackageSystem.WebServiceClient.GetTrialLicenseDefinitionRequest inValue = new Composite.Core.PackageSystem.WebServiceClient.GetTrialLicenseDefinitionRequest(); inValue.Body = new Composite.Core.PackageSystem.WebServiceClient.GetTrialLicenseDefinitionRequestBody(); inValue.Body.installationId = installationId; inValue.Body.productId = productId; inValue.Body.publicKeyXml = publicKeyXml; Composite.Core.PackageSystem.WebServiceClient.GetTrialLicenseDefinitionResponse retVal = ((Composite.Core.PackageSystem.WebServiceClient.LicenseDefinitionServiceSoap)(this)).GetTrialLicenseDefinition(inValue); return retVal.Body.GetTrialLicenseDefinitionResult; } } } ================================================ FILE: Composite/Core/PackageSystem/WebServiceClient/Reference.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ #pragma warning disable 1591 namespace Composite.Core.PackageSystem.WebServiceClient { using System.Runtime.Serialization; using System; /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name = "PackageDescriptor", Namespace = "http://package.composite.net/package.asmx")] [System.SerializableAttribute()] public partial class PackageDescriptor : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; private System.Guid IdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string GroupNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string NameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string PackageVersionField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string AuthorField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DescriptionField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string TechicalDetailsField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string ConsoleBrowserUrlField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string ReadMoreUrlField; private bool IsTrialField; private System.Nullable TrialPeriodDaysField; private bool IsFreeField; private bool InstallationRequireLicenseFileUpdateField; private decimal PriceAmmountField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string PriceCurrencyField; private bool UpgradeAgreementMandatoryField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MinCompositeVersionSupportedField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MaxCompositeVersionSupportedField; [System.Runtime.Serialization.OptionalFieldAttribute()] private Composite.Core.PackageSystem.WebServiceClient.PackageReference[] RequiredPackagesField; private System.Guid EulaIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string PackageFileDownloadUrlField; private System.Guid LicenseIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string CultureField; private System.Guid UserIdField; private bool OnlineField; private bool SubscriptionOnlyField; [System.Runtime.Serialization.OptionalFieldAttribute()] private Composite.Core.PackageSystem.WebServiceClient.SubscriptionDescriptor[] SubscriptionsField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true)] public System.Guid Id { get { return this.IdField; } set { if ((this.IdField.Equals(value) != true)) { this.IdField = value; this.RaisePropertyChanged("Id"); } } } [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 1)] public string GroupName { get { return this.GroupNameField; } set { if ((object.ReferenceEquals(this.GroupNameField, value) != true)) { this.GroupNameField = value; this.RaisePropertyChanged("GroupName"); } } } [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 2)] public string Name { get { return this.NameField; } set { if ((object.ReferenceEquals(this.NameField, value) != true)) { this.NameField = value; this.RaisePropertyChanged("Name"); } } } [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 3)] public string PackageVersion { get { return this.PackageVersionField; } set { if ((object.ReferenceEquals(this.PackageVersionField, value) != true)) { this.PackageVersionField = value; this.RaisePropertyChanged("PackageVersion"); } } } [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 4)] public string Author { get { return this.AuthorField; } set { if ((object.ReferenceEquals(this.AuthorField, value) != true)) { this.AuthorField = value; this.RaisePropertyChanged("Author"); } } } [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 5)] public string Description { get { return this.DescriptionField; } set { if ((object.ReferenceEquals(this.DescriptionField, value) != true)) { this.DescriptionField = value; this.RaisePropertyChanged("Description"); } } } [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 6)] public string TechicalDetails { get { return this.TechicalDetailsField; } set { if ((object.ReferenceEquals(this.TechicalDetailsField, value) != true)) { this.TechicalDetailsField = value; this.RaisePropertyChanged("TechicalDetails"); } } } [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 7)] public string ConsoleBrowserUrl { get { return this.ConsoleBrowserUrlField; } set { if ((object.ReferenceEquals(this.ConsoleBrowserUrlField, value) != true)) { this.ConsoleBrowserUrlField = value; this.RaisePropertyChanged("ConsoleBrowserUrl"); } } } [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 8)] public string ReadMoreUrl { get { return this.ReadMoreUrlField; } set { if ((object.ReferenceEquals(this.ReadMoreUrlField, value) != true)) { this.ReadMoreUrlField = value; this.RaisePropertyChanged("ReadMoreUrl"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true, Order = 9)] public bool IsTrial { get { return this.IsTrialField; } set { if ((this.IsTrialField.Equals(value) != true)) { this.IsTrialField = value; this.RaisePropertyChanged("IsTrial"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true, Order = 10)] public System.Nullable TrialPeriodDays { get { return this.TrialPeriodDaysField; } set { if ((this.TrialPeriodDaysField.Equals(value) != true)) { this.TrialPeriodDaysField = value; this.RaisePropertyChanged("TrialPeriodDays"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true, Order = 11)] public bool IsFree { get { return this.IsFreeField; } set { if ((this.IsFreeField.Equals(value) != true)) { this.IsFreeField = value; this.RaisePropertyChanged("IsFree"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true, Order = 12)] public bool InstallationRequireLicenseFileUpdate { get { return this.InstallationRequireLicenseFileUpdateField; } set { if ((this.InstallationRequireLicenseFileUpdateField.Equals(value) != true)) { this.InstallationRequireLicenseFileUpdateField = value; this.RaisePropertyChanged("InstallationRequireLicenseFileUpdate"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true, Order = 13)] public decimal PriceAmmount { get { return this.PriceAmmountField; } set { if ((this.PriceAmmountField.Equals(value) != true)) { this.PriceAmmountField = value; this.RaisePropertyChanged("PriceAmmount"); } } } [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 14)] public string PriceCurrency { get { return this.PriceCurrencyField; } set { if ((object.ReferenceEquals(this.PriceCurrencyField, value) != true)) { this.PriceCurrencyField = value; this.RaisePropertyChanged("PriceCurrency"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true, Order = 15)] public bool UpgradeAgreementMandatory { get { return this.UpgradeAgreementMandatoryField; } set { if ((this.UpgradeAgreementMandatoryField.Equals(value) != true)) { this.UpgradeAgreementMandatoryField = value; this.RaisePropertyChanged("UpgradeAgreementMandatory"); } } } [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 16)] public string MinCompositeVersionSupported { get { return this.MinCompositeVersionSupportedField; } set { if ((object.ReferenceEquals(this.MinCompositeVersionSupportedField, value) != true)) { this.MinCompositeVersionSupportedField = value; this.RaisePropertyChanged("MinCompositeVersionSupported"); } } } [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 17)] public string MaxCompositeVersionSupported { get { return this.MaxCompositeVersionSupportedField; } set { if ((object.ReferenceEquals(this.MaxCompositeVersionSupportedField, value) != true)) { this.MaxCompositeVersionSupportedField = value; this.RaisePropertyChanged("MaxCompositeVersionSupported"); } } } [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 18)] public Composite.Core.PackageSystem.WebServiceClient.PackageReference[] RequiredPackages { get { return this.RequiredPackagesField; } set { if ((object.ReferenceEquals(this.RequiredPackagesField, value) != true)) { this.RequiredPackagesField = value; this.RaisePropertyChanged("RequiredPackages"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true, Order = 19)] public System.Guid EulaId { get { return this.EulaIdField; } set { if ((this.EulaIdField.Equals(value) != true)) { this.EulaIdField = value; this.RaisePropertyChanged("EulaId"); } } } [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 20)] public string PackageFileDownloadUrl { get { return this.PackageFileDownloadUrlField; } set { if ((object.ReferenceEquals(this.PackageFileDownloadUrlField, value) != true)) { this.PackageFileDownloadUrlField = value; this.RaisePropertyChanged("PackageFileDownloadUrl"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true, Order = 21)] public System.Guid LicenseId { get { return this.LicenseIdField; } set { if ((this.LicenseIdField.Equals(value) != true)) { this.LicenseIdField = value; this.RaisePropertyChanged("LicenseId"); } } } [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 22)] public string Culture { get { return this.CultureField; } set { if ((object.ReferenceEquals(this.CultureField, value) != true)) { this.CultureField = value; this.RaisePropertyChanged("Culture"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true, Order = 23)] public System.Guid UserId { get { return this.UserIdField; } set { if ((this.UserIdField.Equals(value) != true)) { this.UserIdField = value; this.RaisePropertyChanged("UserId"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true, Order = 24)] public bool Online { get { return this.OnlineField; } set { if ((this.OnlineField.Equals(value) != true)) { this.OnlineField = value; this.RaisePropertyChanged("Online"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true, Order = 25)] public bool SubscriptionOnly { get { return this.SubscriptionOnlyField; } set { if ((this.SubscriptionOnlyField.Equals(value) != true)) { this.SubscriptionOnlyField = value; this.RaisePropertyChanged("SubscriptionOnly"); } } } [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 26)] public Composite.Core.PackageSystem.WebServiceClient.SubscriptionDescriptor[] Subscriptions { get { return this.SubscriptionsField; } set { if ((object.ReferenceEquals(this.SubscriptionsField, value) != true)) { this.SubscriptionsField = value; this.RaisePropertyChanged("Subscriptions"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged != null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name = "PackageReference", Namespace = "http://package.composite.net/package.asmx")] [System.SerializableAttribute()] public partial class PackageReference : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; private System.Guid IdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string NameField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true)] public System.Guid Id { get { return this.IdField; } set { if ((this.IdField.Equals(value) != true)) { this.IdField = value; this.RaisePropertyChanged("Id"); } } } [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false)] public string Name { get { return this.NameField; } set { if ((object.ReferenceEquals(this.NameField, value) != true)) { this.NameField = value; this.RaisePropertyChanged("Name"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged != null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name = "SubscriptionDescriptor", Namespace = "http://package.composite.net/package.asmx")] [System.SerializableAttribute()] public partial class SubscriptionDescriptor : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; private System.Guid IdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string NameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DetailsUrlField; private bool PurchasableField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true)] public System.Guid Id { get { return this.IdField; } set { if ((this.IdField.Equals(value) != true)) { this.IdField = value; this.RaisePropertyChanged("Id"); } } } [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false)] public string Name { get { return this.NameField; } set { if ((object.ReferenceEquals(this.NameField, value) != true)) { this.NameField = value; this.RaisePropertyChanged("Name"); } } } [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 2)] public string DetailsUrl { get { return this.DetailsUrlField; } set { if ((object.ReferenceEquals(this.DetailsUrlField, value) != true)) { this.DetailsUrlField = value; this.RaisePropertyChanged("DetailsUrl"); } } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true, Order = 3)] public bool Purchasable { get { return this.PurchasableField; } set { if ((this.PurchasableField.Equals(value) != true)) { this.PurchasableField = value; this.RaisePropertyChanged("Purchasable"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged != null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ServiceModel.ServiceContractAttribute(Namespace = "http://package.composite.net/package.asmx", ConfigurationName = "Core.PackageSystem.WebServiceClient.PackagesSoap")] public interface PackagesSoap { // CODEGEN: Generating message contract since element name Culture from namespace http://package.composite.net/package.asmx is not marked nillable [System.ServiceModel.OperationContractAttribute(Action = "http://package.composite.net/package.asmx/GetPackageList", ReplyAction = "*")] Composite.Core.PackageSystem.WebServiceClient.GetPackageListResponse GetPackageList(Composite.Core.PackageSystem.WebServiceClient.GetPackageListRequest request); [System.ServiceModel.OperationContractAttribute(Action = "http://package.composite.net/package.asmx/GetPackageList", ReplyAction = "*")] System.Threading.Tasks.Task GetPackageListAsync(Composite.Core.PackageSystem.WebServiceClient.GetPackageListRequest request); [System.ServiceModel.OperationContractAttribute(Action = "http://package.composite.net/package.asmx/IsOperational", ReplyAction = "*")] bool IsOperational(); [System.ServiceModel.OperationContractAttribute(Action = "http://package.composite.net/package.asmx/IsOperational", ReplyAction = "*")] System.Threading.Tasks.Task IsOperationalAsync(); // CODEGEN: Generating message contract since element name userCulture from namespace http://package.composite.net/package.asmx is not marked nillable [System.ServiceModel.OperationContractAttribute(Action = "http://package.composite.net/package.asmx/GetEulaText", ReplyAction = "*")] Composite.Core.PackageSystem.WebServiceClient.GetEulaTextResponse GetEulaText(Composite.Core.PackageSystem.WebServiceClient.GetEulaTextRequest request); [System.ServiceModel.OperationContractAttribute(Action = "http://package.composite.net/package.asmx/GetEulaText", ReplyAction = "*")] System.Threading.Tasks.Task GetEulaTextAsync(Composite.Core.PackageSystem.WebServiceClient.GetEulaTextRequest request); // CODEGEN: Generating message contract since element name localUserName from namespace http://package.composite.net/package.asmx is not marked nillable [System.ServiceModel.OperationContractAttribute(Action = "http://package.composite.net/package.asmx/RegisterPackageUninstall", ReplyAction = "*")] Composite.Core.PackageSystem.WebServiceClient.RegisterPackageUninstallResponse RegisterPackageUninstall(Composite.Core.PackageSystem.WebServiceClient.RegisterPackageUninstallRequest request); [System.ServiceModel.OperationContractAttribute(Action = "http://package.composite.net/package.asmx/RegisterPackageUninstall", ReplyAction = "*")] System.Threading.Tasks.Task RegisterPackageUninstallAsync(Composite.Core.PackageSystem.WebServiceClient.RegisterPackageUninstallRequest request); // CODEGEN: Generating message contract since element name packageName from namespace http://package.composite.net/package.asmx is not marked nillable [System.ServiceModel.OperationContractAttribute(Action = "http://package.composite.net/package.asmx/PackageActivity", ReplyAction = "*")] Composite.Core.PackageSystem.WebServiceClient.PackageActivityResponse PackageActivity(Composite.Core.PackageSystem.WebServiceClient.PackageActivityRequest request); [System.ServiceModel.OperationContractAttribute(Action = "http://package.composite.net/package.asmx/PackageActivity", ReplyAction = "*")] System.Threading.Tasks.Task PackageActivityAsync(Composite.Core.PackageSystem.WebServiceClient.PackageActivityRequest request); // CODEGEN: Generating message contract since element name localUserName from namespace http://package.composite.net/package.asmx is not marked nillable [System.ServiceModel.OperationContractAttribute(Action = "http://package.composite.net/package.asmx/RequestLicenseUpdate", ReplyAction = "*")] Composite.Core.PackageSystem.WebServiceClient.RequestLicenseUpdateResponse RequestLicenseUpdate(Composite.Core.PackageSystem.WebServiceClient.RequestLicenseUpdateRequest request); [System.ServiceModel.OperationContractAttribute(Action = "http://package.composite.net/package.asmx/RequestLicenseUpdate", ReplyAction = "*")] System.Threading.Tasks.Task RequestLicenseUpdateAsync(Composite.Core.PackageSystem.WebServiceClient.RequestLicenseUpdateRequest request); // CODEGEN: Generating message contract since element name LocalUserName from namespace http://package.composite.net/package.asmx is not marked nillable [System.ServiceModel.OperationContractAttribute(Action = "http://package.composite.net/package.asmx/RegisterPackageInstallationCompletion", ReplyAction = "*")] Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationCompletionResponse RegisterPackageInstallationCompletion(Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationCompletionRequest request); [System.ServiceModel.OperationContractAttribute(Action = "http://package.composite.net/package.asmx/RegisterPackageInstallationCompletion", ReplyAction = "*")] System.Threading.Tasks.Task RegisterPackageInstallationCompletionAsync(Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationCompletionRequest request); // CODEGEN: Generating message contract since element name LocalUserName from namespace http://package.composite.net/package.asmx is not marked nillable [System.ServiceModel.OperationContractAttribute(Action = "http://package.composite.net/package.asmx/RegisterPackageInstallationFailure", ReplyAction = "*")] Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationFailureResponse RegisterPackageInstallationFailure(Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationFailureRequest request); [System.ServiceModel.OperationContractAttribute(Action = "http://package.composite.net/package.asmx/RegisterPackageInstallationFailure", ReplyAction = "*")] System.Threading.Tasks.Task RegisterPackageInstallationFailureAsync(Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationFailureRequest request); } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] public partial class GetPackageListRequest { [System.ServiceModel.MessageBodyMemberAttribute(Name = "GetPackageList", Namespace = "http://package.composite.net/package.asmx", Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.GetPackageListRequestBody Body; public GetPackageListRequest() { } public GetPackageListRequest(Composite.Core.PackageSystem.WebServiceClient.GetPackageListRequestBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://package.composite.net/package.asmx")] public partial class GetPackageListRequestBody { [System.Runtime.Serialization.DataMemberAttribute(Order = 0)] public System.Guid InstallationId; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 1)] public string Culture; public GetPackageListRequestBody() { } public GetPackageListRequestBody(System.Guid InstallationId, string Culture) { this.InstallationId = InstallationId; this.Culture = Culture; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] public partial class GetPackageListResponse { [System.ServiceModel.MessageBodyMemberAttribute(Name = "GetPackageListResponse", Namespace = "http://package.composite.net/package.asmx", Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.GetPackageListResponseBody Body; public GetPackageListResponse() { } public GetPackageListResponse(Composite.Core.PackageSystem.WebServiceClient.GetPackageListResponseBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://package.composite.net/package.asmx")] public partial class GetPackageListResponseBody { [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.PackageDescriptor[] GetPackageListResult; public GetPackageListResponseBody() { } public GetPackageListResponseBody(Composite.Core.PackageSystem.WebServiceClient.PackageDescriptor[] GetPackageListResult) { this.GetPackageListResult = GetPackageListResult; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] public partial class GetEulaTextRequest { [System.ServiceModel.MessageBodyMemberAttribute(Name = "GetEulaText", Namespace = "http://package.composite.net/package.asmx", Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.GetEulaTextRequestBody Body; public GetEulaTextRequest() { } public GetEulaTextRequest(Composite.Core.PackageSystem.WebServiceClient.GetEulaTextRequestBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://package.composite.net/package.asmx")] public partial class GetEulaTextRequestBody { [System.Runtime.Serialization.DataMemberAttribute(Order = 0)] public System.Guid eulaId; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 1)] public string userCulture; public GetEulaTextRequestBody() { } public GetEulaTextRequestBody(System.Guid eulaId, string userCulture) { this.eulaId = eulaId; this.userCulture = userCulture; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] public partial class GetEulaTextResponse { [System.ServiceModel.MessageBodyMemberAttribute(Name = "GetEulaTextResponse", Namespace = "http://package.composite.net/package.asmx", Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.GetEulaTextResponseBody Body; public GetEulaTextResponse() { } public GetEulaTextResponse(Composite.Core.PackageSystem.WebServiceClient.GetEulaTextResponseBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://package.composite.net/package.asmx")] public partial class GetEulaTextResponseBody { [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 0)] public string GetEulaTextResult; public GetEulaTextResponseBody() { } public GetEulaTextResponseBody(string GetEulaTextResult) { this.GetEulaTextResult = GetEulaTextResult; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] public partial class RegisterPackageUninstallRequest { [System.ServiceModel.MessageBodyMemberAttribute(Name = "RegisterPackageUninstall", Namespace = "http://package.composite.net/package.asmx", Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.RegisterPackageUninstallRequestBody Body; public RegisterPackageUninstallRequest() { } public RegisterPackageUninstallRequest(Composite.Core.PackageSystem.WebServiceClient.RegisterPackageUninstallRequestBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://package.composite.net/package.asmx")] public partial class RegisterPackageUninstallRequestBody { [System.Runtime.Serialization.DataMemberAttribute(Order = 0)] public System.Guid InstallationId; [System.Runtime.Serialization.DataMemberAttribute(Order = 1)] public System.Guid PackageId; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 2)] public string localUserName; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 3)] public string localUserIp; public RegisterPackageUninstallRequestBody() { } public RegisterPackageUninstallRequestBody(System.Guid InstallationId, System.Guid PackageId, string localUserName, string localUserIp) { this.InstallationId = InstallationId; this.PackageId = PackageId; this.localUserName = localUserName; this.localUserIp = localUserIp; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] public partial class RegisterPackageUninstallResponse { [System.ServiceModel.MessageBodyMemberAttribute(Name = "RegisterPackageUninstallResponse", Namespace = "http://package.composite.net/package.asmx", Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.RegisterPackageUninstallResponseBody Body; public RegisterPackageUninstallResponse() { } public RegisterPackageUninstallResponse(Composite.Core.PackageSystem.WebServiceClient.RegisterPackageUninstallResponseBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute()] public partial class RegisterPackageUninstallResponseBody { public RegisterPackageUninstallResponseBody() { } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] public partial class PackageActivityRequest { [System.ServiceModel.MessageBodyMemberAttribute(Name = "PackageActivity", Namespace = "http://package.composite.net/package.asmx", Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.PackageActivityRequestBody Body; public PackageActivityRequest() { } public PackageActivityRequest(Composite.Core.PackageSystem.WebServiceClient.PackageActivityRequestBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://package.composite.net/package.asmx")] public partial class PackageActivityRequestBody { [System.Runtime.Serialization.DataMemberAttribute(Order = 0)] public System.Guid installationId; [System.Runtime.Serialization.DataMemberAttribute(Order = 1)] public System.Guid packageId; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 2)] public string packageName; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 3)] public string ip; [System.Runtime.Serialization.DataMemberAttribute(Order = 4)] public int status; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 5)] public string exception; public PackageActivityRequestBody() { } public PackageActivityRequestBody(System.Guid installationId, System.Guid packageId, string packageName, string ip, int status, string exception) { this.installationId = installationId; this.packageId = packageId; this.packageName = packageName; this.ip = ip; this.status = status; this.exception = exception; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] public partial class PackageActivityResponse { [System.ServiceModel.MessageBodyMemberAttribute(Name = "PackageActivityResponse", Namespace = "http://package.composite.net/package.asmx", Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.PackageActivityResponseBody Body; public PackageActivityResponse() { } public PackageActivityResponse(Composite.Core.PackageSystem.WebServiceClient.PackageActivityResponseBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute()] public partial class PackageActivityResponseBody { public PackageActivityResponseBody() { } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] public partial class RequestLicenseUpdateRequest { [System.ServiceModel.MessageBodyMemberAttribute(Name = "RequestLicenseUpdate", Namespace = "http://package.composite.net/package.asmx", Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.RequestLicenseUpdateRequestBody Body; public RequestLicenseUpdateRequest() { } public RequestLicenseUpdateRequest(Composite.Core.PackageSystem.WebServiceClient.RequestLicenseUpdateRequestBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://package.composite.net/package.asmx")] public partial class RequestLicenseUpdateRequestBody { [System.Runtime.Serialization.DataMemberAttribute(Order = 0)] public System.Guid InstallationId; [System.Runtime.Serialization.DataMemberAttribute(Order = 1)] public System.Guid PackageId; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 2)] public string localUserName; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 3)] public string localUserIp; public RequestLicenseUpdateRequestBody() { } public RequestLicenseUpdateRequestBody(System.Guid InstallationId, System.Guid PackageId, string localUserName, string localUserIp) { this.InstallationId = InstallationId; this.PackageId = PackageId; this.localUserName = localUserName; this.localUserIp = localUserIp; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] public partial class RequestLicenseUpdateResponse { [System.ServiceModel.MessageBodyMemberAttribute(Name = "RequestLicenseUpdateResponse", Namespace = "http://package.composite.net/package.asmx", Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.RequestLicenseUpdateResponseBody Body; public RequestLicenseUpdateResponse() { } public RequestLicenseUpdateResponse(Composite.Core.PackageSystem.WebServiceClient.RequestLicenseUpdateResponseBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://package.composite.net/package.asmx")] public partial class RequestLicenseUpdateResponseBody { [System.Runtime.Serialization.DataMemberAttribute(Order = 0)] public bool RequestLicenseUpdateResult; public RequestLicenseUpdateResponseBody() { } public RequestLicenseUpdateResponseBody(bool RequestLicenseUpdateResult) { this.RequestLicenseUpdateResult = RequestLicenseUpdateResult; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] public partial class RegisterPackageInstallationCompletionRequest { [System.ServiceModel.MessageBodyMemberAttribute(Name = "RegisterPackageInstallationCompletion", Namespace = "http://package.composite.net/package.asmx", Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationCompletionRequestBody Body; public RegisterPackageInstallationCompletionRequest() { } public RegisterPackageInstallationCompletionRequest(Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationCompletionRequestBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://package.composite.net/package.asmx")] public partial class RegisterPackageInstallationCompletionRequestBody { [System.Runtime.Serialization.DataMemberAttribute(Order = 0)] public System.Guid InstallationId; [System.Runtime.Serialization.DataMemberAttribute(Order = 1)] public System.Guid PackageId; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 2)] public string LocalUserName; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 3)] public string localUserIp; public RegisterPackageInstallationCompletionRequestBody() { } public RegisterPackageInstallationCompletionRequestBody(System.Guid InstallationId, System.Guid PackageId, string LocalUserName, string localUserIp) { this.InstallationId = InstallationId; this.PackageId = PackageId; this.LocalUserName = LocalUserName; this.localUserIp = localUserIp; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] public partial class RegisterPackageInstallationCompletionResponse { [System.ServiceModel.MessageBodyMemberAttribute(Name = "RegisterPackageInstallationCompletionResponse", Namespace = "http://package.composite.net/package.asmx", Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationCompletionResponseBody Body; public RegisterPackageInstallationCompletionResponse() { } public RegisterPackageInstallationCompletionResponse(Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationCompletionResponseBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute()] public partial class RegisterPackageInstallationCompletionResponseBody { public RegisterPackageInstallationCompletionResponseBody() { } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] public partial class RegisterPackageInstallationFailureRequest { [System.ServiceModel.MessageBodyMemberAttribute(Name = "RegisterPackageInstallationFailure", Namespace = "http://package.composite.net/package.asmx", Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationFailureRequestBody Body; public RegisterPackageInstallationFailureRequest() { } public RegisterPackageInstallationFailureRequest(Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationFailureRequestBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://package.composite.net/package.asmx")] public partial class RegisterPackageInstallationFailureRequestBody { [System.Runtime.Serialization.DataMemberAttribute(Order = 0)] public System.Guid InstallationId; [System.Runtime.Serialization.DataMemberAttribute(Order = 1)] public System.Guid PackageId; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 2)] public string LocalUserName; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 3)] public string localUserIp; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 4)] public string exceptionString; public RegisterPackageInstallationFailureRequestBody() { } public RegisterPackageInstallationFailureRequestBody(System.Guid InstallationId, System.Guid PackageId, string LocalUserName, string localUserIp, string exceptionString) { this.InstallationId = InstallationId; this.PackageId = PackageId; this.LocalUserName = LocalUserName; this.localUserIp = localUserIp; this.exceptionString = exceptionString; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] public partial class RegisterPackageInstallationFailureResponse { [System.ServiceModel.MessageBodyMemberAttribute(Name = "RegisterPackageInstallationFailureResponse", Namespace = "http://package.composite.net/package.asmx", Order = 0)] public Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationFailureResponseBody Body; public RegisterPackageInstallationFailureResponse() { } public RegisterPackageInstallationFailureResponse(Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationFailureResponseBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute()] public partial class RegisterPackageInstallationFailureResponseBody { public RegisterPackageInstallationFailureResponseBody() { } } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public interface PackagesSoapChannel : Composite.Core.PackageSystem.WebServiceClient.PackagesSoap, System.ServiceModel.IClientChannel { } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public partial class PackagesSoapClient : System.ServiceModel.ClientBase, Composite.Core.PackageSystem.WebServiceClient.PackagesSoap { public PackagesSoapClient() { } public PackagesSoapClient(string endpointConfigurationName) : base(endpointConfigurationName) { } public PackagesSoapClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public PackagesSoapClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public PackagesSoapClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] Composite.Core.PackageSystem.WebServiceClient.GetPackageListResponse Composite.Core.PackageSystem.WebServiceClient.PackagesSoap.GetPackageList(Composite.Core.PackageSystem.WebServiceClient.GetPackageListRequest request) { return base.Channel.GetPackageList(request); } public Composite.Core.PackageSystem.WebServiceClient.PackageDescriptor[] GetPackageList(System.Guid InstallationId, string Culture) { Composite.Core.PackageSystem.WebServiceClient.GetPackageListRequest inValue = new Composite.Core.PackageSystem.WebServiceClient.GetPackageListRequest(); inValue.Body = new Composite.Core.PackageSystem.WebServiceClient.GetPackageListRequestBody(); inValue.Body.InstallationId = InstallationId; inValue.Body.Culture = Culture; Composite.Core.PackageSystem.WebServiceClient.GetPackageListResponse retVal = ((Composite.Core.PackageSystem.WebServiceClient.PackagesSoap)(this)).GetPackageList(inValue); return retVal.Body.GetPackageListResult; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] System.Threading.Tasks.Task Composite.Core.PackageSystem.WebServiceClient.PackagesSoap.GetPackageListAsync(Composite.Core.PackageSystem.WebServiceClient.GetPackageListRequest request) { return base.Channel.GetPackageListAsync(request); } public System.Threading.Tasks.Task GetPackageListAsync(System.Guid InstallationId, string Culture) { Composite.Core.PackageSystem.WebServiceClient.GetPackageListRequest inValue = new Composite.Core.PackageSystem.WebServiceClient.GetPackageListRequest(); inValue.Body = new Composite.Core.PackageSystem.WebServiceClient.GetPackageListRequestBody(); inValue.Body.InstallationId = InstallationId; inValue.Body.Culture = Culture; return ((Composite.Core.PackageSystem.WebServiceClient.PackagesSoap)(this)).GetPackageListAsync(inValue); } public bool IsOperational() { return base.Channel.IsOperational(); } public System.Threading.Tasks.Task IsOperationalAsync() { return base.Channel.IsOperationalAsync(); } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] Composite.Core.PackageSystem.WebServiceClient.GetEulaTextResponse Composite.Core.PackageSystem.WebServiceClient.PackagesSoap.GetEulaText(Composite.Core.PackageSystem.WebServiceClient.GetEulaTextRequest request) { return base.Channel.GetEulaText(request); } public string GetEulaText(System.Guid eulaId, string userCulture) { Composite.Core.PackageSystem.WebServiceClient.GetEulaTextRequest inValue = new Composite.Core.PackageSystem.WebServiceClient.GetEulaTextRequest(); inValue.Body = new Composite.Core.PackageSystem.WebServiceClient.GetEulaTextRequestBody(); inValue.Body.eulaId = eulaId; inValue.Body.userCulture = userCulture; Composite.Core.PackageSystem.WebServiceClient.GetEulaTextResponse retVal = ((Composite.Core.PackageSystem.WebServiceClient.PackagesSoap)(this)).GetEulaText(inValue); return retVal.Body.GetEulaTextResult; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] System.Threading.Tasks.Task Composite.Core.PackageSystem.WebServiceClient.PackagesSoap.GetEulaTextAsync(Composite.Core.PackageSystem.WebServiceClient.GetEulaTextRequest request) { return base.Channel.GetEulaTextAsync(request); } public System.Threading.Tasks.Task GetEulaTextAsync(System.Guid eulaId, string userCulture) { Composite.Core.PackageSystem.WebServiceClient.GetEulaTextRequest inValue = new Composite.Core.PackageSystem.WebServiceClient.GetEulaTextRequest(); inValue.Body = new Composite.Core.PackageSystem.WebServiceClient.GetEulaTextRequestBody(); inValue.Body.eulaId = eulaId; inValue.Body.userCulture = userCulture; return ((Composite.Core.PackageSystem.WebServiceClient.PackagesSoap)(this)).GetEulaTextAsync(inValue); } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] Composite.Core.PackageSystem.WebServiceClient.RegisterPackageUninstallResponse Composite.Core.PackageSystem.WebServiceClient.PackagesSoap.RegisterPackageUninstall(Composite.Core.PackageSystem.WebServiceClient.RegisterPackageUninstallRequest request) { return base.Channel.RegisterPackageUninstall(request); } public void RegisterPackageUninstall(System.Guid InstallationId, System.Guid PackageId, string localUserName, string localUserIp) { Composite.Core.PackageSystem.WebServiceClient.RegisterPackageUninstallRequest inValue = new Composite.Core.PackageSystem.WebServiceClient.RegisterPackageUninstallRequest(); inValue.Body = new Composite.Core.PackageSystem.WebServiceClient.RegisterPackageUninstallRequestBody(); inValue.Body.InstallationId = InstallationId; inValue.Body.PackageId = PackageId; inValue.Body.localUserName = localUserName; inValue.Body.localUserIp = localUserIp; Composite.Core.PackageSystem.WebServiceClient.RegisterPackageUninstallResponse retVal = ((Composite.Core.PackageSystem.WebServiceClient.PackagesSoap)(this)).RegisterPackageUninstall(inValue); } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] System.Threading.Tasks.Task Composite.Core.PackageSystem.WebServiceClient.PackagesSoap.RegisterPackageUninstallAsync(Composite.Core.PackageSystem.WebServiceClient.RegisterPackageUninstallRequest request) { return base.Channel.RegisterPackageUninstallAsync(request); } public System.Threading.Tasks.Task RegisterPackageUninstallAsync(System.Guid InstallationId, System.Guid PackageId, string localUserName, string localUserIp) { Composite.Core.PackageSystem.WebServiceClient.RegisterPackageUninstallRequest inValue = new Composite.Core.PackageSystem.WebServiceClient.RegisterPackageUninstallRequest(); inValue.Body = new Composite.Core.PackageSystem.WebServiceClient.RegisterPackageUninstallRequestBody(); inValue.Body.InstallationId = InstallationId; inValue.Body.PackageId = PackageId; inValue.Body.localUserName = localUserName; inValue.Body.localUserIp = localUserIp; return ((Composite.Core.PackageSystem.WebServiceClient.PackagesSoap)(this)).RegisterPackageUninstallAsync(inValue); } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] Composite.Core.PackageSystem.WebServiceClient.PackageActivityResponse Composite.Core.PackageSystem.WebServiceClient.PackagesSoap.PackageActivity(Composite.Core.PackageSystem.WebServiceClient.PackageActivityRequest request) { return base.Channel.PackageActivity(request); } public void PackageActivity(System.Guid installationId, System.Guid packageId, string packageName, string ip, int status, string exception) { Composite.Core.PackageSystem.WebServiceClient.PackageActivityRequest inValue = new Composite.Core.PackageSystem.WebServiceClient.PackageActivityRequest(); inValue.Body = new Composite.Core.PackageSystem.WebServiceClient.PackageActivityRequestBody(); inValue.Body.installationId = installationId; inValue.Body.packageId = packageId; inValue.Body.packageName = packageName; inValue.Body.ip = ip; inValue.Body.status = status; inValue.Body.exception = exception; Composite.Core.PackageSystem.WebServiceClient.PackageActivityResponse retVal = ((Composite.Core.PackageSystem.WebServiceClient.PackagesSoap)(this)).PackageActivity(inValue); } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] System.Threading.Tasks.Task Composite.Core.PackageSystem.WebServiceClient.PackagesSoap.PackageActivityAsync(Composite.Core.PackageSystem.WebServiceClient.PackageActivityRequest request) { return base.Channel.PackageActivityAsync(request); } public System.Threading.Tasks.Task PackageActivityAsync(System.Guid installationId, System.Guid packageId, string packageName, string ip, int status, string exception) { Composite.Core.PackageSystem.WebServiceClient.PackageActivityRequest inValue = new Composite.Core.PackageSystem.WebServiceClient.PackageActivityRequest(); inValue.Body = new Composite.Core.PackageSystem.WebServiceClient.PackageActivityRequestBody(); inValue.Body.installationId = installationId; inValue.Body.packageId = packageId; inValue.Body.packageName = packageName; inValue.Body.ip = ip; inValue.Body.status = status; inValue.Body.exception = exception; return ((Composite.Core.PackageSystem.WebServiceClient.PackagesSoap)(this)).PackageActivityAsync(inValue); } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] Composite.Core.PackageSystem.WebServiceClient.RequestLicenseUpdateResponse Composite.Core.PackageSystem.WebServiceClient.PackagesSoap.RequestLicenseUpdate(Composite.Core.PackageSystem.WebServiceClient.RequestLicenseUpdateRequest request) { return base.Channel.RequestLicenseUpdate(request); } public bool RequestLicenseUpdate(System.Guid InstallationId, System.Guid PackageId, string localUserName, string localUserIp) { Composite.Core.PackageSystem.WebServiceClient.RequestLicenseUpdateRequest inValue = new Composite.Core.PackageSystem.WebServiceClient.RequestLicenseUpdateRequest(); inValue.Body = new Composite.Core.PackageSystem.WebServiceClient.RequestLicenseUpdateRequestBody(); inValue.Body.InstallationId = InstallationId; inValue.Body.PackageId = PackageId; inValue.Body.localUserName = localUserName; inValue.Body.localUserIp = localUserIp; Composite.Core.PackageSystem.WebServiceClient.RequestLicenseUpdateResponse retVal = ((Composite.Core.PackageSystem.WebServiceClient.PackagesSoap)(this)).RequestLicenseUpdate(inValue); return retVal.Body.RequestLicenseUpdateResult; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] System.Threading.Tasks.Task Composite.Core.PackageSystem.WebServiceClient.PackagesSoap.RequestLicenseUpdateAsync(Composite.Core.PackageSystem.WebServiceClient.RequestLicenseUpdateRequest request) { return base.Channel.RequestLicenseUpdateAsync(request); } public System.Threading.Tasks.Task RequestLicenseUpdateAsync(System.Guid InstallationId, System.Guid PackageId, string localUserName, string localUserIp) { Composite.Core.PackageSystem.WebServiceClient.RequestLicenseUpdateRequest inValue = new Composite.Core.PackageSystem.WebServiceClient.RequestLicenseUpdateRequest(); inValue.Body = new Composite.Core.PackageSystem.WebServiceClient.RequestLicenseUpdateRequestBody(); inValue.Body.InstallationId = InstallationId; inValue.Body.PackageId = PackageId; inValue.Body.localUserName = localUserName; inValue.Body.localUserIp = localUserIp; return ((Composite.Core.PackageSystem.WebServiceClient.PackagesSoap)(this)).RequestLicenseUpdateAsync(inValue); } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationCompletionResponse Composite.Core.PackageSystem.WebServiceClient.PackagesSoap.RegisterPackageInstallationCompletion(Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationCompletionRequest request) { return base.Channel.RegisterPackageInstallationCompletion(request); } public void RegisterPackageInstallationCompletion(System.Guid InstallationId, System.Guid PackageId, string LocalUserName, string localUserIp) { Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationCompletionRequest inValue = new Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationCompletionRequest(); inValue.Body = new Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationCompletionRequestBody(); inValue.Body.InstallationId = InstallationId; inValue.Body.PackageId = PackageId; inValue.Body.LocalUserName = LocalUserName; inValue.Body.localUserIp = localUserIp; Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationCompletionResponse retVal = ((Composite.Core.PackageSystem.WebServiceClient.PackagesSoap)(this)).RegisterPackageInstallationCompletion(inValue); } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] System.Threading.Tasks.Task Composite.Core.PackageSystem.WebServiceClient.PackagesSoap.RegisterPackageInstallationCompletionAsync(Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationCompletionRequest request) { return base.Channel.RegisterPackageInstallationCompletionAsync(request); } public System.Threading.Tasks.Task RegisterPackageInstallationCompletionAsync(System.Guid InstallationId, System.Guid PackageId, string LocalUserName, string localUserIp) { Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationCompletionRequest inValue = new Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationCompletionRequest(); inValue.Body = new Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationCompletionRequestBody(); inValue.Body.InstallationId = InstallationId; inValue.Body.PackageId = PackageId; inValue.Body.LocalUserName = LocalUserName; inValue.Body.localUserIp = localUserIp; return ((Composite.Core.PackageSystem.WebServiceClient.PackagesSoap)(this)).RegisterPackageInstallationCompletionAsync(inValue); } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationFailureResponse Composite.Core.PackageSystem.WebServiceClient.PackagesSoap.RegisterPackageInstallationFailure(Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationFailureRequest request) { return base.Channel.RegisterPackageInstallationFailure(request); } public void RegisterPackageInstallationFailure(System.Guid InstallationId, System.Guid PackageId, string LocalUserName, string localUserIp, string exceptionString) { Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationFailureRequest inValue = new Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationFailureRequest(); inValue.Body = new Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationFailureRequestBody(); inValue.Body.InstallationId = InstallationId; inValue.Body.PackageId = PackageId; inValue.Body.LocalUserName = LocalUserName; inValue.Body.localUserIp = localUserIp; inValue.Body.exceptionString = exceptionString; Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationFailureResponse retVal = ((Composite.Core.PackageSystem.WebServiceClient.PackagesSoap)(this)).RegisterPackageInstallationFailure(inValue); } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] System.Threading.Tasks.Task Composite.Core.PackageSystem.WebServiceClient.PackagesSoap.RegisterPackageInstallationFailureAsync(Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationFailureRequest request) { return base.Channel.RegisterPackageInstallationFailureAsync(request); } public System.Threading.Tasks.Task RegisterPackageInstallationFailureAsync(System.Guid InstallationId, System.Guid PackageId, string LocalUserName, string localUserIp, string exceptionString) { Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationFailureRequest inValue = new Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationFailureRequest(); inValue.Body = new Composite.Core.PackageSystem.WebServiceClient.RegisterPackageInstallationFailureRequestBody(); inValue.Body.InstallationId = InstallationId; inValue.Body.PackageId = PackageId; inValue.Body.LocalUserName = LocalUserName; inValue.Body.localUserIp = localUserIp; inValue.Body.exceptionString = exceptionString; return ((Composite.Core.PackageSystem.WebServiceClient.PackagesSoap)(this)).RegisterPackageInstallationFailureAsync(inValue); } } } ================================================ FILE: Composite/Core/PageTemplates/Foundation/IPageTemplateProviderRegistry.cs ================================================ using System; using System.Collections.Generic; namespace Composite.Core.PageTemplates.Foundation { internal interface IPageTemplateProviderRegistry { void Flush(); void FlushTemplates(); IEnumerable ProviderNames { get; } IEnumerable PageTemplates { get; } IPageTemplateProvider GetProviderByTemplateId(Guid pageTemplateId); } } ================================================ FILE: Composite/Core/PageTemplates/Foundation/PageTemplateProviderRegistry.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Events; namespace Composite.Core.PageTemplates.Foundation { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PageTemplateProviderRegistry { private static readonly IPageTemplateProviderRegistry _registry = new PageTemplateProviderRegistryImpl(); static PageTemplateProviderRegistry() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => _registry.Flush()); } /// public static IEnumerable ProviderNames { get { return _registry.ProviderNames; } } /// public static IEnumerable PageTemplates { get { return _registry.PageTemplates; } } /// public static IPageTemplateProvider GetProviderByTemplateId(Guid pageTemplateId) { return _registry.GetProviderByTemplateId(pageTemplateId); } /// /// Flushes list of registered page templates /// public static void FlushTemplates() { _registry.FlushTemplates(); } } } ================================================ FILE: Composite/Core/PageTemplates/Foundation/PageTemplateProviderRegistryImpl.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.Core.PageTemplates.Plugins.Runtime; using Composite.Core.PageTemplates.Foundation.PluginFacade; namespace Composite.Core.PageTemplates.Foundation { internal class PageTemplateProviderRegistryImpl : IPageTemplateProviderRegistry { private readonly ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.DoInitialize); public void Flush() { _resourceLocker.ResetInitialization(); } public void FlushTemplates() { var resources = _resourceLocker.Resources; foreach (var providerName in resources.ProviderNames) { var provider = PageTemplateProviderPluginFacade.GetProvider(providerName); provider.FlushTemplates(); } resources.ResetTemplatesCache(); } public IEnumerable ProviderNames { get { return _resourceLocker.Resources.ProviderNames; } } private static IEnumerable GetProviderNames() { var settings = ConfigurationServices.ConfigurationSource.GetSection(PageTemplateProviderSettings.SectionName) as PageTemplateProviderSettings; return settings.PageTemplateProviders.Select(provider => provider.Name).ToList(); } public IEnumerable PageTemplates { get { return _resourceLocker.Resources.Templates.PageTemplates; } } public IPageTemplateProvider GetProviderByTemplateId(Guid pageTemplateId) { return _resourceLocker.Resources.Templates.ProviderByTemplate[pageTemplateId]; } private sealed class Resources { public IEnumerable ProviderNames { get; private set; } private volatile TemplatesCache _state; public TemplatesCache Templates { get { var state = _state; if (state != null) return state; lock(this) { state = _state ?? InitializePageTemplatesCache(); _state = state; } return state; } } public class TemplatesCache { public IEnumerable PageTemplates { get; set; } public Hashtable ProviderByTemplate { get; set; } } public void ResetTemplatesCache() { _state = null; } private TemplatesCache InitializePageTemplatesCache() { var pageTemplates = new List(); var providerByTemplate = new Hashtable(); foreach (string providerName in this.ProviderNames) { var provider = PageTemplateProviderPluginFacade.GetProvider(providerName); var templates = provider.GetPageTemplates().ToList(); pageTemplates.AddRange(templates); foreach (var template in templates) { Verify.That(!providerByTemplate.ContainsKey(template.Id), "There are muliple layouts with the same ID: '{0}'", template.Id); providerByTemplate.Add(template.Id, provider); } } return new TemplatesCache { PageTemplates = pageTemplates, ProviderByTemplate = providerByTemplate }; } public static void DoInitialize(Resources resources) { resources.ProviderNames = GetProviderNames(); } } } } ================================================ FILE: Composite/Core/PageTemplates/Foundation/PluginFacade/PageTemplateProviderPluginFacade.cs ================================================ using System; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.Core.Extensions; using Composite.Core.PageTemplates.Plugins.Runtime; using Composite.C1Console.Events; namespace Composite.Core.PageTemplates.Foundation.PluginFacade { internal static class PageTemplateProviderPluginFacade { private static readonly ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); static PageTemplateProviderPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } public static IPageTemplateProvider GetProvider(string providerName) { var resources = _resourceLocker; IPageTemplateProvider result = resources.Resources.ProviderCache[providerName]; if (result == null) { using (resources.Locker) { result = resources.Resources.ProviderCache[providerName]; if (result == null) { result = resources.Resources.Factory.Create(providerName); resources.Resources.ProviderCache.Add(providerName, result); } } } return result; } internal static void Flush() { _resourceLocker.ResetInitialization(); } private static void HandleConfigurationError(Exception ex) { Flush(); const string sectionName = PageTemplateProviderSettings.SectionName; throw new ConfigurationErrorsException( "Failed to load the configuration section '{0}' from the configuration.".FormatWith(sectionName), ex); } private sealed class Resources { public PageTemplateProviderFactory Factory { get; set; } public Hashtable ProviderCache { get; set; } public static void Initialize(Resources resources) { try { resources.Factory = new PageTemplateProviderFactory(); } catch (NullReferenceException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } resources.ProviderCache = new Hashtable(); } } } } ================================================ FILE: Composite/Core/PageTemplates/IPageRenderer.cs ================================================ using System.Xml.Linq; using Composite.Functions; namespace Composite.Core.PageTemplates { /// /// This class is responsible for rendering the provided job onto the provided ASP.NET Web Forms page. /// The AttachToPage method is called at page construction and is expected to hook on to asp.net page events (like PreInit) to drive the rendering. /// public interface IPageRenderer { /// /// Attaches rendering code to an instance of . /// /// The render target. /// The render job. void AttachToPage(System.Web.UI.Page renderTarget, PageContentToRender contentToRender); } /// /// A page renderer that does not rely of request being handled by ASP.NET Web Forms /// and does not support UserControl functions /// public interface ISlimPageRenderer : IPageRenderer { /// /// Rendering the content into an . /// /// The render job. /// The function context container. XDocument Render(PageContentToRender contentToRender, FunctionContextContainer functionContextContainer); } } ================================================ FILE: Composite/Core/PageTemplates/IPageTemplate.cs ================================================ using System; namespace Composite.Core.PageTemplates { /// /// Basic interface for classes that represent a page template /// public interface IPageTemplate { /// /// Gets the template id. /// Guid TemplateId { get; } /// /// Gets the template title. /// string TemplateTitle { get; } } } ================================================ FILE: Composite/Core/PageTemplates/IPageTemplateProvider.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Elements; using Composite.Core.PageTemplates.Plugins.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.PageTemplates { /// /// Defines page template provider /// [CustomFactory(typeof(PageTemplateProviderCustomFactory))] public interface IPageTemplateProvider { /// /// Gets the page template descriptors. /// /// IEnumerable GetPageTemplates(); /// /// Factory that give C1 CMS a IPageLayouter capable of rendering a C1 CMS page with the specified layout ID. /// The factory will be called for each individual page rendering /// /// IPageRenderer BuildPageRenderer(Guid templateId); /// /// Adds element actions on "Page templates" element /// IEnumerable GetRootActions(); /// /// Forces provider to reload all the page templates next time they are requested. /// void FlushTemplates(); /// /// Provider's label that is shown when adding a new page template /// string AddNewTemplateLabel { get; } /// /// Workflow for adding a new page template /// Type AddNewTemplateWorkflow { get; } } } ================================================ FILE: Composite/Core/PageTemplates/ISharedCodePageTemplateProvider.cs ================================================ using System; using System.Collections.Generic; namespace Composite.Core.PageTemplates { /// /// Represents a page template provider with shared code files /// public interface ISharedCodePageTemplateProvider: IPageTemplateProvider { /// /// Gets the list of shared files, those files will be shown in a "Shared code" folder under "Layout/Page Templates" /// /// IEnumerable GetSharedFiles(); } } ================================================ FILE: Composite/Core/PageTemplates/PageContentToRender.cs ================================================ using System; using System.Collections.Generic; using Composite.Data.Types; namespace Composite.Core.PageTemplates { /// /// Describe the page and content desired to be rendered. /// public class PageContentToRender { /// /// Initializes a new instance of the class. /// /// The page. /// The contents. /// if set to true the page should be rendered in preview mode. public PageContentToRender(IPage page, IEnumerable contents, bool isPreview) { this.Page = page; this.Contents = contents; this.IsPreview = isPreview; } /// /// The page to be rendered /// public IPage Page { get; private set; } /// /// Determines whether page is rendered in a preview mode /// public bool IsPreview { get; private set; } /// /// Page placeholders' content /// public IEnumerable Contents { get; private set; } } } ================================================ FILE: Composite/Core/PageTemplates/PageTemplateDescriptor.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Elements; using Composite.C1Console.Security; namespace Composite.Core.PageTemplates { /// /// Describes a page layout to the C1 CMS core so it may set up editing UI /// public class PageTemplateDescriptor { /// /// Used to identify page layouts. The value has to be unique for each page template. /// public Guid Id { get; set; } /// /// Gets or sets the title. /// /// /// The title. /// /// public string Title { get; set; } /// /// Gets or sets the placeholder descriptions. /// /// /// The placeholder descriptions. /// public virtual IEnumerable PlaceholderDescriptions { get; set; } /// /// The default is the placeholder to focus/use when users edit a page or a layout is used in ad hoc renderings. /// public virtual string DefaultPlaceholderId { get; set; } /// /// Gets or sets an exception that occurred during loading the template. /// public virtual Exception LoadingException { get; set; } /// /// Gets a value indicating whether page template is loaded correctly. /// Not valid templates should not be used in data as they can not be used in rendering and their IDs may not be valid. /// /// /// true if template is loaded; otherwise, false. /// public virtual bool IsValid { get { return LoadingException == null; } } /// /// Gets the entity token. /// /// public virtual EntityToken GetEntityToken() { return new PageTemplateEntityToken(Id); } /// /// Appends actions to a visual element. /// public virtual IEnumerable GetActions() { return new ElementAction[0]; } } } ================================================ FILE: Composite/Core/PageTemplates/PageTemplateEntityToken.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security; using Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider; using Newtonsoft.Json; namespace Composite.Core.PageTemplates { /// /// Entity token of a page template /// [SecurityAncestorProvider(typeof(PageTemplateEntityTokenSecurityAncestorProvider))] public sealed class PageTemplateEntityToken : EntityToken { private readonly string _id; /// /// Initializes a new instance of the class. /// /// The template id. public PageTemplateEntityToken(Guid templateId) { _id = templateId.ToString(); } /// /// Gets the template id. /// [JsonIgnore] public Guid TemplateId { get { return new Guid(_id); } } /// public override string Type { get { return ""; } } /// public override string Source { get { return ""; } } /// public override string Id { get { return _id; } } /// public override string Serialize() { return DoSerialize(); } /// public static EntityToken Deserialize(string serializedData) { string type, source, id; EntityToken.DoDeserialize(serializedData, out type, out source, out id); return new PageTemplateEntityToken(new Guid(id)); } } internal sealed class PageTemplateEntityTokenSecurityAncestorProvider : ISecurityAncestorProvider { public IEnumerable GetParents(EntityToken entityToken) { return new [] { new PageTemplateRootEntityToken() }; } } } ================================================ FILE: Composite/Core/PageTemplates/PageTemplateFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Core.PageTemplates.Foundation; using Composite.Core.PageTemplates.Foundation.PluginFacade; namespace Composite.Core.PageTemplates { /// /// Facade for accessing page templates /// public static class PageTemplateFacade { /// /// Gets the page templates. /// /// public static IEnumerable GetPageTemplates() { var result = new List(); foreach (string providerName in PageTemplateProviderRegistry.ProviderNames) { var provider = PageTemplateProviderPluginFacade.GetProvider(providerName); var templates = provider.GetPageTemplates(); result.AddRange(templates); } return result; } /// /// Gets the shared files. /// /// public static IEnumerable GetSharedFiles() { var result = new List(); foreach (string providerName in PageTemplateProviderRegistry.ProviderNames) { var provider = PageTemplateProviderPluginFacade.GetProvider(providerName); if(provider is ISharedCodePageTemplateProvider) { var sharedFiles = (provider as ISharedCodePageTemplateProvider).GetSharedFiles(); result.AddRange(sharedFiles); } } return result; } /// /// Builds the page renderer. /// /// The page template id. /// public static IPageRenderer BuildPageRenderer(Guid pageTemplateId) { var provider = PageTemplateProviderRegistry.GetProviderByTemplateId(pageTemplateId); Verify.IsNotNull(provider, "Failed to get page template with id '{0}'. The template may contain errors preventing it to compile. Check the C1 CMS log for possible compilation errors.", pageTemplateId); return provider.BuildPageRenderer(pageTemplateId); } /// /// Gets the page template. /// /// The page template id. /// public static PageTemplateDescriptor GetPageTemplate(Guid pageTemplateId) { var provider = PageTemplateProviderRegistry.GetProviderByTemplateId(pageTemplateId); if(provider == null) { return null; } return provider.GetPageTemplates().FirstOrDefault(t => t.Id == pageTemplateId); } /// /// Returns true is there's at least one valid page template. /// public static bool ValidTemplateExists { get { return GetPageTemplates().Any(template => template.IsValid); } } /// /// Gets the providers. /// /// internal static IEnumerable> GetProviders() { foreach (string providerName in PageTemplateProviderRegistry.ProviderNames) { var provider = PageTemplateProviderPluginFacade.GetProvider(providerName); yield return new KeyValuePair(providerName, provider); } } } } ================================================ FILE: Composite/Core/PageTemplates/PlaceholderAttribute.cs ================================================ using System; namespace Composite.Core.PageTemplates { /// /// Defines a placeholder property /// [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class PlaceholderAttribute : Attribute { /// /// Placeholder's ID. If this parameter is not set, the property name will be the ID /// public string Id { get; set; } /// /// Placeholder's label. Is used f.e. in EditPageWorkflow /// public string Title { get; set; } /// /// A comma seperated list of container class names. These class names are used to filter Component options in editors and to style the editing area. /// public string ContainerClasses { get; set; } /// /// Determines whether current placeholder is the default placeholder /// public bool IsDefault { get; set; } } } ================================================ FILE: Composite/Core/PageTemplates/PlaceholderDescriptor.cs ================================================ using System.Collections.Generic; namespace Composite.Core.PageTemplates { /// /// Describe a placeholder on a page template. /// public class PlaceholderDescriptor { /// /// Used to identify a layout placeholder. This has to be unique only within a page template. /// public string Id { get; set; } /// /// Gets or sets the title. /// /// /// The title. /// public string Title { get; set; } /// /// List of container class names. Used to clasify the placeholder to attach css classes to editor and to filter components /// public IList ContainerClasses { get; set; } } } ================================================ FILE: Composite/Core/PageTemplates/Plugins/NonConfigurablePageTemplateProvider.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Core.PageTemplates.Plugins { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Assembler(typeof(NonConfigurablePageTemplateProviderAssembler))] public class NonConfigurablePageTemplateProvider : PageTemplateProviderData { } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class NonConfigurablePageTemplateProviderAssembler : IAssembler { /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IPageTemplateProvider Assemble(IBuilderContext context, PageTemplateProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IPageTemplateProvider)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/Core/PageTemplates/Plugins/PageTemplateProviderData.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.PageTemplates.Plugins { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class PageTemplateProviderData : NameTypeConfigurationElement { } } ================================================ FILE: Composite/Core/PageTemplates/Plugins/Runtime/PageTemplateProviderCustomFactory.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Composite.Core.Extensions; namespace Composite.Core.PageTemplates.Plugins.Runtime { internal sealed class PageTemplateProviderCustomFactory : AssemblerBasedCustomFactory { protected override PageTemplateProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { string sectionName = PageTemplateProviderSettings.SectionName; PageTemplateProviderSettings settings = configurationSource.GetSection(sectionName) as PageTemplateProviderSettings; if (settings == null) { throw new ConfigurationErrorsException("The configuration section '{0}' was not found in the configuration".FormatWith(sectionName)); } return settings.PageTemplateProviders.Get(name); } } } ================================================ FILE: Composite/Core/PageTemplates/Plugins/Runtime/PageTemplateProviderDefaultNameRetriever.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.PageTemplates.Plugins.Runtime { internal sealed class PageTemplateProviderDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/Core/PageTemplates/Plugins/Runtime/PageTemplateProviderFactory.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Composite.Core.Configuration; namespace Composite.Core.PageTemplates.Plugins.Runtime { internal class PageTemplateProviderFactory: NameTypeFactoryBase { public PageTemplateProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/Core/PageTemplates/Plugins/Runtime/PageTemplateProviderSettings.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using System.Configuration; namespace Composite.Core.PageTemplates.Plugins.Runtime { internal class PageTemplateProviderSettings : SerializableConfigurationSection { public const string SectionName = "Composite.Core.PageTemplates.Plugins.PageTemplateProviderConfiguration"; private const string _pageTemplateProvidersProperty = "PageTemplateProviders"; [ConfigurationProperty(_pageTemplateProvidersProperty, IsRequired = true)] public NameTypeConfigurationElementCollection PageTemplateProviders { get { return (NameTypeConfigurationElementCollection)base[_pageTemplateProvidersProperty]; } } } } ================================================ FILE: Composite/Core/PageTemplates/SharedFile.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Elements; namespace Composite.Core.PageTemplates { /// /// Contains information about a code file shared between page template. /// public class SharedFile { /// /// Initializes a new instance of the class. /// /// The relative file path. public SharedFile(string relativeFilePath) { RelativeFilePath = relativeFilePath; DefaultEditAction = true; } /// /// Full path to the code file. /// public string RelativeFilePath { get; set; } /// /// Indicating whether the default edit action should be shown. /// public bool DefaultEditAction { get; set; } /// /// Gets the custom element actions. /// /// public virtual IEnumerable GetActions() { return new ElementAction[0]; } } } ================================================ FILE: Composite/Core/PageTemplates/TemplateDefinitionHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.C1Console.RichContent.ContainerClasses; using Composite.Core.Extensions; using Composite.Core.Instrumentation; using Composite.Core.WebClient.Renderings.Page; using Composite.Core.Xml; using Composite.Functions; namespace Composite.Core.PageTemplates { /// /// Helper class for working with page template definitions based on /// public static class TemplateDefinitionHelper { /// /// Builds a page template descriptor. Extracts template's properties and content placeholder properties. /// /// The template definition. /// The descriptor constructor. /// The placeholder properties. /// public static DescriptorType BuildPageTemplateDescriptor(IPageTemplate templateDefinition, Func descriptorConstructor, out IDictionary placeholderProperties) where DescriptorType : PageTemplateDescriptor { Verify.ArgumentNotNull(templateDefinition, "templateDefinition"); Verify.ArgumentNotNull(descriptorConstructor, "descriptorConstructor"); DescriptorType pageTemplate = descriptorConstructor(); Verify.ArgumentCondition(pageTemplate != null, "descriptorConstructor", "Not null object expected"); if (templateDefinition.TemplateId == null || templateDefinition.TemplateId == Guid.Empty) { throw new InvalidOperationException("TemplateId has not been correctly defined"); } pageTemplate.Id = templateDefinition.TemplateId; pageTemplate.Title = templateDefinition.TemplateTitle; string defaultPlaceholderId = null; var placeholders = new List(); placeholderProperties = new Dictionary(); var type = templateDefinition.GetType(); while (type.GetInterfaces().Contains(typeof(IPageTemplate))) { foreach (var property in type.GetProperties()) { if(property.ReflectedType != property.DeclaringType) continue; var placeholderAttributes = property.GetCustomAttributes(typeof(PlaceholderAttribute), true); if (placeholderAttributes.Length == 0) continue; Verify.That(placeholderAttributes.Length == 1, $"Multiple '{typeof(PlaceholderAttribute)}' attributes defined on property '{property.Name}'"); var placeholderAttribute = (PlaceholderAttribute)placeholderAttributes[0]; string placeholderId = placeholderAttribute.Id ?? property.Name; string placeholderLabel = placeholderAttribute.Title ?? property.Name; if (placeholderProperties.ContainsKey(placeholderId)) { throw new InvalidOperationException("Placeholder '{0}' defined multiple times".FormatWith(placeholderId)); } var containerClasses = ContainerClassManager.ParseToList(placeholderAttribute.ContainerClasses).ToList(); placeholderProperties.Add(placeholderId, property); placeholders.Add(new PlaceholderDescriptor { Id = placeholderId, Title = placeholderLabel, ContainerClasses = containerClasses }); if (placeholderAttribute.IsDefault) { Verify.IsNull(defaultPlaceholderId, "More than one placeholder is marked as default"); defaultPlaceholderId = placeholderId; } } type = type.BaseType; } if (defaultPlaceholderId == null && placeholders.Any()) { defaultPlaceholderId = placeholders.First().Id; } pageTemplate.DefaultPlaceholderId = defaultPlaceholderId; pageTemplate.PlaceholderDescriptions = placeholders; return pageTemplate; } /// /// Binds placeholders' content to the related properties on a template definition /// /// The template. /// The page rendering job. /// The placeholder properties. /// The function context container, if not null, nested functions fill be evaluated. public static void BindPlaceholders(IPageTemplate template, PageContentToRender pageContentToRender, IDictionary placeholderProperties, FunctionContextContainer functionContextContainer) { Verify.ArgumentNotNull(template, "template"); Verify.ArgumentNotNull(pageContentToRender, "pageContentToRender"); Verify.ArgumentNotNull(placeholderProperties, "placeholderProperties"); foreach (var placeholderContent in pageContentToRender.Contents) { string placeholderId = placeholderContent.PlaceHolderId; if (!placeholderProperties.ContainsKey(placeholderId)) continue; XhtmlDocument placeholderXhtml = PageRenderer.ParsePlaceholderContent(placeholderContent); if (functionContextContainer != null) { bool allFunctionsExecuted; using (Profiler.Measure($"Evaluating placeholder '{placeholderId}'")) { allFunctionsExecuted = PageRenderer.ExecuteCacheableFunctions(placeholderXhtml.Root, functionContextContainer); } if (allFunctionsExecuted) { using (Profiler.Measure("Normalizing XHTML document")) { PageRenderer.NormalizeXhtmlDocument(placeholderXhtml); } } } PageRenderer.ResolveRelativePaths(placeholderXhtml); PropertyInfo property = placeholderProperties[placeholderId]; if (!property.ReflectedType.IsInstanceOfType(template)) { string propertyName = property.Name; property = template.GetType().GetProperty(property.Name); Verify.IsNotNull(property, "Failed to find placeholder property '{0}'", propertyName); } property.SetValue(template, placeholderXhtml); } } } } ================================================ FILE: Composite/Core/Parallelization/AsyncLock.cs ================================================ using System; using System.Threading; using System.Threading.Tasks; namespace Composite.Core.Parallelization { internal sealed class AsyncLock { private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1); private readonly Task _releaser; public AsyncLock() { _releaser = Task.FromResult((IDisposable)new Releaser(this)); } public Task LockAsync() { var wait = _semaphore.WaitAsync(); return wait.IsCompleted ? _releaser : wait.ContinueWith((_, state) => (IDisposable)state, _releaser.Result, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } public IDisposable Lock() { _semaphore.Wait(); return new Releaser(this); } public bool Wait(int millisecondsTimeout) { return _semaphore.Wait(millisecondsTimeout); } public Task WaitAsync(int millisecondsTimeout) { return _semaphore.WaitAsync(millisecondsTimeout); } public void Release() { _semaphore.Release(); } private sealed class Releaser : IDisposable { private readonly AsyncLock _toRelease; internal Releaser(AsyncLock toRelease) { _toRelease = toRelease; } public void Dispose() { _toRelease.Release(); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~Releaser() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } } ================================================ FILE: Composite/Core/Parallelization/Foundation/IParallelizationProviderRegistry.cs ================================================ namespace Composite.Core.Parallelization.Foundation { internal interface IParallelizationProviderRegistry { string[] DisabledParallelizationPoints { get; } //string DefaultParallelizationProviderName { get; } bool Enabled { get; } void Flush(); } } ================================================ FILE: Composite/Core/Parallelization/Foundation/ParallelizationProviderRegistry.cs ================================================ using Composite.C1Console.Events; namespace Composite.Core.Parallelization.Foundation { internal static class ParallelizationProviderRegistry { private static IParallelizationProviderRegistry _implementation = new ParallelizationProviderRegistryImpl(); internal static IParallelizationProviderRegistry Implementation { get { return _implementation; } set { _implementation = value; } } static ParallelizationProviderRegistry() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static bool Enabled { get { return _implementation.Enabled; } } public static string[] DisabledParallelizationPoints { get { return _implementation.DisabledParallelizationPoints; } } private static void Flush() { _implementation.Flush(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } } } ================================================ FILE: Composite/Core/Parallelization/Foundation/ParallelizationProviderRegistryImpl.cs ================================================ using System.Linq; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.Core.Parallelization.Plugins.Runtime; namespace Composite.Core.Parallelization.Foundation { internal sealed class ParallelizationProviderRegistryImpl : IParallelizationProviderRegistry { // private string _defaultParallelizationProviderName = null; private string[] _disabledParallelizationPoints = null; private bool? _enabled = null; //public string DefaultParallelizationProviderName //{ // get // { // if (_defaultParallelizationProviderName == null) // { // ParallelizationProviderSettings parallelizationProviderSettings = ConfigurationServices.ConfigurationSource.GetSection(ParallelizationProviderSettings.SectionName) as ParallelizationProviderSettings; // _defaultParallelizationProviderName = parallelizationProviderSettings.DefaultParallelizationProviderName; // } // return _defaultParallelizationProviderName; // } //} public string[] DisabledParallelizationPoints { get { if (_disabledParallelizationPoints == null) { var parallelizationProviderSettings = ConfigurationServices.ConfigurationSource.GetSection(ParallelizationProviderSettings.SectionName) as ParallelizationProviderSettings; if (parallelizationProviderSettings != null && parallelizationProviderSettings.Parallelization != null) { var parConfigNode = parallelizationProviderSettings.Parallelization; _disabledParallelizationPoints = (from ParallelizationSettingsElement configElement in parConfigNode where !configElement.Enabled select configElement.Name).ToArray(); } else { _disabledParallelizationPoints = new string[0]; } } return _disabledParallelizationPoints; } } public bool Enabled { get { bool? enabled = _enabled; if (enabled == null) { var parallelizationProviderSettings = ConfigurationServices.ConfigurationSource.GetSection(ParallelizationProviderSettings.SectionName) as ParallelizationProviderSettings; if(parallelizationProviderSettings == null) { enabled = false; } else { enabled = parallelizationProviderSettings.Parallelization.Enabled; } _enabled = enabled; } return (bool)enabled; } } public void Flush() { _enabled = null; _disabledParallelizationPoints = null; } } } ================================================ FILE: Composite/Core/Parallelization/IndexEnumerator.cs ================================================ using System; using System.Collections.Generic; namespace Composite.Core.Parallelization { [Obsolete("To be removed.")] internal class IndexEnumerator: IEnumerable { private readonly int _elementsCount; public IndexEnumerator(int elementsCount) { _elementsCount = elementsCount; } public IEnumerator GetEnumerator() { for(int i = 0; i < _elementsCount; i++) { yield return i; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { for (int i = 0; i < _elementsCount; i++) { yield return i; } } public int Count { get { return _elementsCount; } } } } ================================================ FILE: Composite/Core/Parallelization/ParallelFacade.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Security.Principal; using System.Threading; using System.Web; using Composite.Core.Instrumentation; using Composite.Data; using Composite.Core.Parallelization.Foundation; using Composite.Core.Threading; using Composite.Core.Extensions; using System.Threading.Tasks; namespace Composite.Core.Parallelization { /// /// Allows running tasks in parallel while passing C1 data context to created tasks /// public static class ParallelFacade { private static readonly FieldInfo HttpContext_ItemsFieldInfo = typeof(HttpContext).GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance); private static bool ParralelizationPointEnabled(string parallelizationPointName) { return !ParallelizationProviderRegistry.DisabledParallelizationPoints.Any(name => name == parallelizationPointName); } /// /// Executes a for (For in Visual Basic) loop in which iterations may run in parallel. /// /// The start index, inclusive. /// The end index, exclusive. /// The delegate that is invoked once per iteration. public static void For(int fromInclusive, int toExclusive, Action body) { For(null, fromInclusive, toExclusive, body); } internal static void For(string parallelizationPointName, int fromInclusive, int toExclusive, Action body) { int count = toExclusive - fromInclusive; if(count <= 0) return; if(count == 1) { body(fromInclusive); return; } if (ParallelizationProviderRegistry.Enabled && (parallelizationPointName.IsNullOrEmpty() || ParralelizationPointEnabled(parallelizationPointName))) { EnsureHttpContextItemsCollectionIsThreadSafe(); using (Profiler.Measure(GetPerformanceMeasureTitle(parallelizationPointName))) { ThreadDataManagerData parentData = ThreadDataManager.Current; var threadWrapper = new ThreadWrapper(body, parentData); PromoteThreadAbortException(() => { Parallel.For(fromInclusive, toExclusive, threadWrapper.WrapperAction); }); } } else { for (int i=fromInclusive; i < toExclusive; i++) { body(i); } } } internal static void ForEach(string parallelizationPointName, IEnumerable source, Action body) { Verify.ArgumentNotNull(source, "source"); if (source is TSource[]) { int elementsCount = (source as TSource[]).Length; if (elementsCount == 0) return; if (elementsCount == 1) { body((source as TSource[])[0]); return; } } else if(source is ICollection) { int elementsCount = (source as ICollection).Count; if (elementsCount == 0) return; if(elementsCount == 1) { body((source as ICollection).First()); return; } } if (ParallelizationProviderRegistry.Enabled && (string.IsNullOrEmpty(parallelizationPointName) || ParralelizationPointEnabled(parallelizationPointName))) { EnsureHttpContextItemsCollectionIsThreadSafe(); using (Profiler.Measure(GetPerformanceMeasureTitle(parallelizationPointName))) { ThreadDataManagerData parentData = ThreadDataManager.Current; var threadWrapper = new ThreadWrapper(body, parentData); PromoteThreadAbortException(() => { Parallel.ForEach(source, threadWrapper.WrapperAction); }); } } else { foreach (var s in source) { body(s); } } } private static void EnsureHttpContextItemsCollectionIsThreadSafe() { var context = HttpContext.Current; if (context == null) return; var items = context.Items; if(items is Hashtable && items.GetType() == typeof(Hashtable)) { object synchronizedCollection = Hashtable.Synchronized((Hashtable) items); HttpContext_ItemsFieldInfo?.SetValue(context, synchronizedCollection); } } /// /// Executes a foreach (For Each in Visual Basic) operation on an IEnumerable in which iterations may run in parallel. /// /// The type of the data in the source. /// An enumerable data source. /// The delegate that is invoked once per iteration. public static void ForEach(IEnumerable source, Action body) { ForEach(null, source, body); } private sealed class ThreadWrapper { private readonly Action _body; private readonly ThreadDataManagerData _parentData; private readonly CultureInfo _parentThreadLocale; private readonly DataScopeIdentifier _parentThreadDataScope; private readonly HttpContext _parentThreadHttpContext; private readonly IPrincipal _parentThreadPrincipal; private readonly CultureInfo _parentThreadCulture; private readonly CultureInfo _parentThreadUiCulture; public ThreadWrapper(Action body, ThreadDataManagerData parentData) { _body = body; _parentData = parentData; _parentThreadLocale = LocalizationScopeManager.CurrentLocalizationScope; _parentThreadDataScope = DataScopeManager.CurrentDataScope; _parentThreadHttpContext = HttpContext.Current; _parentThreadPrincipal = Thread.CurrentPrincipal; var currentThread = System.Threading.Thread.CurrentThread; _parentThreadCulture = currentThread.CurrentCulture; _parentThreadUiCulture = currentThread.CurrentUICulture; } public void WrapperAction(TSource source) { var originalHttpContext = HttpContext.Current; bool dataScopePushed = false; bool languageScopePushed = false; var currentThread = System.Threading.Thread.CurrentThread; CultureInfo originalCulture = currentThread.CurrentCulture; CultureInfo originalUiCulture = currentThread.CurrentUICulture; var originalPrincipal = Thread.CurrentPrincipal; using (ThreadDataManager.Initialize(_parentData)) { try { DataScopeManager.EnterThreadLocal(); if (DataScopeManager.CurrentDataScope != _parentThreadDataScope) { DataScopeManager.PushDataScope(_parentThreadDataScope); dataScopePushed = true; } LocalizationScopeManager.EnterThreadLocal(); if (LocalizationScopeManager.CurrentLocalizationScope != _parentThreadLocale) { LocalizationScopeManager.PushLocalizationScope(_parentThreadLocale); languageScopePushed = true; } DataServiceScopeManager.EnterThreadLocal(); HttpContext.Current = _parentThreadHttpContext; currentThread.CurrentCulture = _parentThreadCulture; currentThread.CurrentUICulture = _parentThreadUiCulture; Thread.CurrentPrincipal = _parentThreadPrincipal; try { _body(source); } catch(ThreadAbortException threadAbort) { object state = threadAbort.ExceptionState; if(state != null) { Thread.ResetAbort(); // Throwing another exception because Thread.ResetAbort clears ThreadAbortException.ExceptionState throw new RethrowableThreadAbortException(state); } } } finally { currentThread.CurrentCulture = originalCulture; currentThread.CurrentUICulture = originalUiCulture; Thread.CurrentPrincipal = originalPrincipal; HttpContext.Current = originalHttpContext; if (dataScopePushed) { DataScopeManager.PopDataScope(); } if (languageScopePushed) { LocalizationScopeManager.PopLocalizationScope(); } DataScopeManager.ExitThreadLocal(); LocalizationScopeManager.ExitThreadLocal(); DataServiceScopeManager.ExitThreadLocal(); } } } } private static void PromoteThreadAbortException(ThreadStart action) { try { action(); } catch (AggregateException aggregateException) { var evaluatedListOfExceptions = aggregateException.Flatten().InnerExceptions.ToList(); foreach (var innerException in evaluatedListOfExceptions) { var threadAbort = innerException as RethrowableThreadAbortException; if (threadAbort != null) { // ToString will mark aggregateException as handled, so TPL will not tear down the whole application aggregateException.ToString(); threadAbort.Rethrow(); } } throw; } } private class RethrowableThreadAbortException : Exception { private object _exceptionState { get; set; } public RethrowableThreadAbortException(object exceptionState) { _exceptionState = exceptionState; } public void Rethrow() { Thread.CurrentThread.Abort(_exceptionState); } } private static string GetPerformanceMeasureTitle(string parallelizationPointName) { return (parallelizationPointName ?? "") + " [parallelization point]"; } } } ================================================ FILE: Composite/Core/Parallelization/Plugins/Runtime/ParallelizationProviderSettings.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Parallelization.Plugins.Runtime { internal sealed class ParallelizationProviderSettings : SerializableConfigurationSection { public const string SectionName = "Composite.Core.Parallelization.Plugins.ParallelizationProviderConfiguration"; private const string _parallelizationElementName = "Parallelization"; [ConfigurationProperty(_parallelizationElementName)] public ParallelizationConfigurationElement Parallelization { get { return (ParallelizationConfigurationElement)base[_parallelizationElementName]; } set { base[_parallelizationElementName] = value; } } } internal sealed class ParallelizationConfigurationElement : ConfigurationElementCollection { private const string _enabledPropertyName = "enabled"; [ConfigurationProperty(_enabledPropertyName, DefaultValue = "true")] public bool Enabled { get { return (bool)base[_enabledPropertyName]; } set { base[_enabledPropertyName] = value; } } protected override ConfigurationElement CreateNewElement() { return new ParallelizationSettingsElement(); } protected override object GetElementKey(ConfigurationElement element) { var parallelPointSettings = (ParallelizationSettingsElement)element; return parallelPointSettings.Name; } } internal sealed class ParallelizationSettingsElement : ConfigurationElement { private const string _namePropertyName = "name"; [ConfigurationProperty(_namePropertyName)] public string Name { get { return (string)base[_namePropertyName]; } set { base[_namePropertyName] = value; } } private const string _enabledPropertyName = "enabled"; [ConfigurationProperty(_enabledPropertyName, DefaultValue = "true")] public bool Enabled { get { return (bool)base[_enabledPropertyName]; } set { base[_enabledPropertyName] = value; } } } } ================================================ FILE: Composite/Core/ResourceSystem/Foundation/PluginFacades/ResourceProviderPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Threading; using Composite.C1Console.Events; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.ResourceSystem.Plugins.ResourceProvider; using Composite.Core.ResourceSystem.Plugins.ResourceProvider.Runtime; namespace Composite.Core.ResourceSystem.Foundation.PluginFacades { internal static class ResourceProviderPluginFacade { const string ApplicationNameReference = "{applicationname}"; private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize, false); static ResourceProviderPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } #region ILocalizationProvider methods private static IEnumerable GetLocalizationProviders() { foreach (string localizationProviderName in ResourceProviderRegistry.LocalizationProviderNames) { yield return GetResourceProvider(localizationProviderName); } } public static bool LocalizationSectionDefined(string section) { return GetLocalizationProviders().Any(p => p.GetSections().Contains(section)); } public static IEnumerable GetLocalizationSectionNames() { return GetLocalizationProviders().SelectMany(p => p.GetSections()).Distinct().ToList(); } public static string GetStringValue(string section, string stringId) { return GetStringValue(section, stringId, Thread.CurrentThread.CurrentUICulture); } public static string GetStringValue(string section, string stringId, CultureInfo cultureInfo) { Verify.ArgumentNotNullOrEmpty(section, "section"); Verify.ArgumentNotNullOrEmpty(stringId, "stringId"); foreach(var provider in GetLocalizationProviders()) { var result = provider.GetString(section, stringId, cultureInfo); if(result != null) { return ReplaceReferences(result); } } return null; } private static string ReplaceReferences(string localizedString) { if (localizedString == null) return null; if (localizedString.IndexOf(ApplicationNameReference, 0, StringComparison.Ordinal) > -1) { localizedString = localizedString.Replace(ApplicationNameReference, GlobalSettingsFacade.ApplicationName); } return localizedString; } public static IEnumerable GetSupportedStringCultures() { List cultures = new List(); foreach (string providerName in ResourceProviderRegistry.LocalizationProviderNames) { ILocalizationProvider provider = GetResourceProvider(providerName); cultures.AddRange(provider.GetSupportedCultures()); } return cultures.Distinct(); } public static IDictionary GetAllStrings(string section) { Verify.ArgumentNotNullOrEmpty(section, "section"); var currentCulture = Thread.CurrentThread.CurrentUICulture; IDictionary result = null; foreach (var localizationProvider in GetLocalizationProviders()) { var strings = localizationProvider.GetAllStrings(section, currentCulture); if (strings == null) continue; result = result ?? new Dictionary(); foreach(var kvp in strings) { if(!result.ContainsKey(kvp.Key)) { result.Add(kvp.Key, ReplaceReferences(kvp.Value)); } } } return result; } #endregion public static Type GetProviderType(string providerName) { IResourceProvider resourceProvider = GetResourceProvider(providerName); return resourceProvider.GetType(); } private static T GetResourceProvider(string providerName) where T : class, IResourceProvider { T provider = GetResourceProvider(providerName) as T; Verify.IsNotNull(provider, "The Resource Provider identified by the specified provider name ('{0}') does not implement the interface {1}" .FormatWith(providerName, typeof(T))); return provider; } private static IResourceProvider GetResourceProvider(string providerName) { IResourceProvider provider; if (_resourceLocker.Resources.ProviderCache.TryGetValue(providerName, out provider) == false) { try { provider = _resourceLocker.Resources.Factory.Create(providerName); using (_resourceLocker.Locker) { if (_resourceLocker.Resources.ProviderCache.ContainsKey(providerName) == false) _resourceLocker.Resources.ProviderCache.Add(providerName, provider); } } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } return provider; } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", ResourceProviderSettings.SectionName), ex); } private sealed class Resources { public ResourceProviderFactory Factory { get; set; } public Dictionary ProviderCache { get; set; } public static void Initialize(Resources resources) { try { resources.Factory = new ResourceProviderFactory(); } catch (NullReferenceException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } resources.ProviderCache = new Dictionary(); } } } } ================================================ FILE: Composite/Core/ResourceSystem/Foundation/ResourceProviderRegistry.cs ================================================ using System; using System.Collections.Generic; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.ResourceSystem.Foundation.PluginFacades; using Composite.Core.ResourceSystem.Plugins.ResourceProvider; using Composite.Core.ResourceSystem.Plugins.ResourceProvider.Runtime; using Composite.Core.Collections.Generic; using Composite.C1Console.Events; using Composite.Plugins.ResourceSystem.AggregationLocalizationProvider; namespace Composite.Core.ResourceSystem.Foundation { internal static class ResourceProviderRegistry { private static readonly ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize, false); private static readonly string LogTitle = typeof (ResourceProviderRegistry).Name; static ResourceProviderRegistry() { GlobalEventSystemFacade.SubscribeToFlushEvent(a => Flush()); } public static IEnumerable StringResourceProviderNames { get { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.StringResourceProviders; } } } public static IEnumerable LocalizationProviderNames { get { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.LocalizationProviders; } } } private static void Flush() { _resourceLocker.ResetInitialization(); } private sealed class Resources { public List StringResourceProviders; public List LocalizationProviders; public static void Initialize(Resources resources) { resources.StringResourceProviders = new List(); resources.LocalizationProviders = new List(); var configurationSource = ConfigurationServices.ConfigurationSource; if (configurationSource == null) { return; } var section = configurationSource.GetSection(ResourceProviderSettings.SectionName); if (section == null) { return; } var configuration = (ResourceProviderSettings)section; foreach (ResourceProviderData data in configuration.ResourceProviderPlugins) { Type type = ResourceProviderPluginFacade.GetProviderType(data.Name); if (typeof(IStringResourceProvider).IsAssignableFrom(type)) { Log.LogVerbose(LogTitle, ("String resource provider '{0}' definition ignored." + "\nEither remove it from Composite.config, or move the provider definition under a provider of type '{1}' ") .FormatWith(data.Name, typeof(AggregationLocalizationProvider).FullName)); resources.StringResourceProviders.Add(data.Name); } else if (typeof(ILocalizationProvider).IsAssignableFrom(type)) { resources.LocalizationProviders.Add(data.Name); } else { throw new NotSupportedException(string.Format("Unknown resource provider type '{0}'", type)); } } } } } } ================================================ FILE: Composite/Core/ResourceSystem/IIconResourceSystemFacade.cs ================================================ namespace Composite.Core.ResourceSystem { internal interface IIconResourceSystemFacade { ResourceHandle GetResourceHandle(string iconName); } } ================================================ FILE: Composite/Core/ResourceSystem/IconResourceSystemFacade.cs ================================================ namespace Composite.Core.ResourceSystem { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class IconResourceSystemFacade { private static IIconResourceSystemFacade _iconResourceSystemFacade = new IconResourceSystemFacadeImpl(); internal static IIconResourceSystemFacade Implementation { get { return _iconResourceSystemFacade; } set { _iconResourceSystemFacade = value; } } /// public static ResourceHandle GetResourceHandle(string iconName) { return _iconResourceSystemFacade.GetResourceHandle(iconName); } } } ================================================ FILE: Composite/Core/ResourceSystem/IconResourceSystemFacadeImpl.cs ================================================ using Composite.Core.Extensions; namespace Composite.Core.ResourceSystem { internal class IconResourceSystemFacadeImpl : IIconResourceSystemFacade { public ResourceHandle GetResourceHandle(string iconName) { if (string.IsNullOrEmpty(iconName)) return null; if (!iconName.IsCorrectNamespace('.')) { Log.LogWarning("IconResourceSystemFacade", "The namespace '{0}' is not correct.", iconName); return null; } string resourceName = iconName.GetNameFromNamespace(); string namespaceName = iconName.GetNamespace(); return new ResourceHandle(namespaceName, resourceName); } } } ================================================ FILE: Composite/Core/ResourceSystem/Icons/BuildInIconProviderName.cs ================================================ namespace Composite.Core.ResourceSystem.Icons { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class BuildInIconProviderName { /// public const string ProviderName = "Composite.Icons"; } } ================================================ FILE: Composite/Core/ResourceSystem/Icons/CommonCommandIcons.cs ================================================ namespace Composite.Core.ResourceSystem.Icons { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class CommonCommandIcons { /// public static ResourceHandle AddNew { get { return GetIconHandle("generic-add"); } } /// public static ResourceHandle Edit { get { return GetIconHandle("generic-edit"); } } /// public static ResourceHandle Refresh { get { return GetIconHandle("generic-refresh"); } } /// public static ResourceHandle Delete { get { return GetIconHandle("generic-delete"); } } /// public static ResourceHandle Search { get { return GetIconHandle("generic-search"); } } /// public static ResourceHandle SetSecurity { get { return GetIconHandle("generic-set-security"); } } /// public static ResourceHandle ShowHistory { get { return GetIconHandle("generic-show-history"); } } /// public static ResourceHandle ShowReport { get { return GetIconHandle("generic-show-report"); } } //private static ResourceHandle GetIconHandle() //{ // return new ResourceHandle(BuildInIconProviderName.ProviderName, "unknown"); //} private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } } } ================================================ FILE: Composite/Core/ResourceSystem/Icons/CommonElementIcons.cs ================================================ namespace Composite.Core.ResourceSystem.Icons { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class CommonElementIcons { /// public static ResourceHandle Advanced { get { return GetIconHandle("advanced"); } } /// public static ResourceHandle Clock { get { return GetIconHandle("clock"); } } /// public static ResourceHandle Cancel { get { return GetIconHandle("cancel"); } } /// public static ResourceHandle CancelDisabled { get { return GetIconHandle("cancel-disabled"); } } /// public static ResourceHandle Close { get { return GetIconHandle("close"); } } /// public static ResourceHandle Data { get { return GetIconHandle("data"); } } /// public static ResourceHandle DataAwaitingApproval { get { return GetIconHandle("data-awaiting-approval"); } } /// public static ResourceHandle DataAwaitingPublication { get { return GetIconHandle("data-awaiting-publication"); } } /// public static ResourceHandle DataDraft { get { return GetIconHandle("data-draft"); } } /// public static ResourceHandle DataPublished { get { return GetIconHandle("data-published"); } } /// public static ResourceHandle DeletedItems { get { return GetIconHandle("deleteditems"); } } /// public static ResourceHandle Earth { get { return GetIconHandle("earth"); } } /// public static ResourceHandle Error { get { return GetIconHandle("error"); } } /// public static ResourceHandle Folder { get { return GetIconHandle("folder"); } } /// public static ResourceHandle FolderOpen { get { return GetIconHandle("folder-open"); } } /// public static ResourceHandle FolderDisabled { get { return GetIconHandle("folder-disabled"); } } /// public static ResourceHandle MimeApplicationMsWord { get { return GetIconHandle("mimetype-doc"); } } /// public static ResourceHandle MimeApplicationPdf { get { return GetIconHandle("mimetype-pdf"); } } /// public static ResourceHandle MimeApplicationRtf { get { return GetIconHandle("mimetype-rtf"); } } /// public static ResourceHandle MimeApplicationVndMsExcel { get { return GetIconHandle("mimetype-xsl"); } } /// public static ResourceHandle MimeApplicationVndMsPowerpoint { get { return GetIconHandle("mimetype-ppt"); } } /// public static ResourceHandle MimeApplicationZip { get { return GetIconHandle("mimetype-zip"); } } /// public static ResourceHandle MimeImageBmp { get { return GetIconHandle("mimetype-bmp"); } } /// public static ResourceHandle MimeImageGif { get { return GetIconHandle("mimetype-gif"); } } /// public static ResourceHandle MimeImageJpeg { get { return GetIconHandle("mimetype-jpg"); } } /// public static ResourceHandle MimeImagePng { get { return GetIconHandle("mimetype-png"); } } /// public static ResourceHandle MimeTextPlain { get { return GetIconHandle("mimetype-txt"); } } /// public static ResourceHandle MimeTextXml { get { return GetIconHandle("mimetype-xml"); } } /// public static ResourceHandle Nodes { get { return GetIconHandle("nodes"); } } /// public static ResourceHandle Options { get { return GetIconHandle( "options" ); } } /// public static ResourceHandle Page { get { return GetIconHandle("page"); } } /// public static ResourceHandle Popup { get { return GetIconHandle("popup"); } } /// public static ResourceHandle Search { get { return GetIconHandle("generic-search"); } } /// public static ResourceHandle Report { get { return GetIconHandle("report"); } } /// public static ResourceHandle Template { get { return GetIconHandle("template"); } } /// public static ResourceHandle Tools { get { return GetIconHandle("tools"); } } /// public static ResourceHandle User { get { return GetIconHandle("user"); } } /// public static ResourceHandle UserDisabled { get { return GetIconHandle("user-disabled"); } } /// public static ResourceHandle UserGroup { get { return GetIconHandle("user-group"); } } /// public static ResourceHandle Question { get { return GetIconHandle("question"); } } private static ResourceHandle GetIconHandle() { return new ResourceHandle(BuildInIconProviderName.ProviderName, "unknown"); } private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } } } ================================================ FILE: Composite/Core/ResourceSystem/LocalizationFiles.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Composite.Core.ResourceSystem { /// /// Class generated from localization files /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class LocalizationFiles { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_C1Console_SecurityViolation { ///"Security violation" public static string LayoutLabel=>T("LayoutLabel"); ///"Not allowed" public static string Title=>T("Title"); ///"You do not have permission to execute the action. Contact your administrator for more information." public static string Description=>T("Description"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.C1Console.SecurityViolation", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_C1Console_Trees { ///"Error in tree" public static string KeyFacade_ErrorTreeNode_Label=>T("KeyFacade.ErrorTreeNode.Label"); ///"Show Message" public static string KeyFacade_ErrorTreeNode_ShowMessage_Label=>T("KeyFacade.ErrorTreeNode.ShowMessage.Label"); ///"Show Error Message" public static string KeyFacade_ErrorTreeNode_ShowMessage_ToolTip=>T("KeyFacade.ErrorTreeNode.ShowMessage.ToolTip"); ///"Error message" public static string KeyFacade_ErrorTreeNode_ShowMessage_Title=>T("KeyFacade.ErrorTreeNode.ShowMessage.Title"); ///"Unknown exception happened: '{0}'" public static string TreeValidationError_Common_UnknownException_Template=>T("TreeValidationError.Common.UnknownException"); ///"Unknown exception happened: '{0}'" public static string TreeValidationError_Common_UnknownException(object parameter0)=>string.Format(T("TreeValidationError.Common.UnknownException"), parameter0); ///"Unknown element '{0}'" public static string TreeValidationError_Common_UnknownElement_Template=>T("TreeValidationError.Common.UnknownElement"); ///"Unknown element '{0}'" public static string TreeValidationError_Common_UnknownElement(object parameter0)=>string.Format(T("TreeValidationError.Common.UnknownElement"), parameter0); ///"The required attribute '{0}' is missing" public static string TreeValidationError_Common_MissingAttribute_Template=>T("TreeValidationError.Common.MissingAttribute"); ///"The required attribute '{0}' is missing" public static string TreeValidationError_Common_MissingAttribute(object parameter0)=>string.Format(T("TreeValidationError.Common.MissingAttribute"), parameter0); ///"The attribute '{0}' has a value that is not allowed" public static string TreeValidationError_Common_WrongAttributeValue_Template=>T("TreeValidationError.Common.WrongAttributeValue"); ///"The attribute '{0}' has a value that is not allowed" public static string TreeValidationError_Common_WrongAttributeValue(object parameter0)=>string.Format(T("TreeValidationError.Common.WrongAttributeValue"), parameter0); ///"The type '{0}' does not contain a property named '{1}'" public static string TreeValidationError_Common_MissingProperty_Template=>T("TreeValidationError.Common.MissingProperty"); ///"The type '{0}' does not contain a property named '{1}'" public static string TreeValidationError_Common_MissingProperty(object parameter0,object parameter1)=>string.Format(T("TreeValidationError.Common.MissingProperty"), parameter0,parameter1); ///"The type '{0}' could not be found" public static string TreeValidationError_Common_UnknownInterfaceType_Template=>T("TreeValidationError.Common.UnknownInterfaceType"); ///"The type '{0}' could not be found" public static string TreeValidationError_Common_UnknownInterfaceType(object parameter0)=>string.Format(T("TreeValidationError.Common.UnknownInterfaceType"), parameter0); ///"The type '{0}' does not implement the interface '{1}'" public static string TreeValidationError_Common_NotImplementingIData_Template=>T("TreeValidationError.Common.NotImplementingIData"); ///"The type '{0}' does not implement the interface '{1}'" public static string TreeValidationError_Common_NotImplementingIData(object parameter0,object parameter1)=>string.Format(T("TreeValidationError.Common.NotImplementingIData"), parameter0,parameter1); ///"The value '{0}' is not allowed as a permission type value" public static string TreeValidationError_Common_WrongPermissionValue_Template=>T("TreeValidationError.Common.WrongPermissionValue"); ///"The value '{0}' is not allowed as a permission type value" public static string TreeValidationError_Common_WrongPermissionValue(object parameter0)=>string.Format(T("TreeValidationError.Common.WrongPermissionValue"), parameter0); ///"The value '{0}' is not allowed as a location value" public static string TreeValidationError_Common_WrongLocationValue_Template=>T("TreeValidationError.Common.WrongLocationValue"); ///"The value '{0}' is not allowed as a location value" public static string TreeValidationError_Common_WrongLocationValue(object parameter0)=>string.Format(T("TreeValidationError.Common.WrongLocationValue"), parameter0); ///"No function markup provided as a child element" public static string TreeValidationError_Common_MissingFunctionMarkup=>T("TreeValidationError.Common.MissingFunctionMarkup"); ///"The function could not be created for the provided function markup" public static string TreeValidationError_Common_WrongFunctionMarkup=>T("TreeValidationError.Common.WrongFunctionMarkup"); ///"Missing root element in tree markup" public static string TreeValidationError_Markup_NoRootElement=>T("TreeValidationError.Markup.NoRootElement"); ///"Syntax error: {0} at line {1} position {2}" public static string TreeValidationError_Markup_SchemaError_Template=>T("TreeValidationError.Markup.SchemaError"); ///"Syntax error: {0} at line {1} position {2}" public static string TreeValidationError_Markup_SchemaError(object parameter0,object parameter1,object parameter2)=>string.Format(T("TreeValidationError.Markup.SchemaError"), parameter0,parameter1,parameter2); ///"The attachment point '{0}' is unknown" public static string TreeValidationError_AutoAttachments_UnknownAttachmentPoint_Template=>T("TreeValidationError.AutoAttachments.UnknownAttachmentPoint"); ///"The attachment point '{0}' is unknown" public static string TreeValidationError_AutoAttachments_UnknownAttachmentPoint(object parameter0)=>string.Format(T("TreeValidationError.AutoAttachments.UnknownAttachmentPoint"), parameter0); ///"The attachment position '{0}' is unknown" public static string TreeValidationError_AutoAttachments_UnknownAttachmentPosition_Template=>T("TreeValidationError.AutoAttachments.UnknownAttachmentPosition"); ///"The attachment position '{0}' is unknown" public static string TreeValidationError_AutoAttachments_UnknownAttachmentPosition(object parameter0)=>string.Format(T("TreeValidationError.AutoAttachments.UnknownAttachmentPosition"), parameter0); ///"No elements are allowed in trees that are used with data attached trees" public static string TreeValidationError_DataAttachments_NoElementsAllowed=>T("TreeValidationError.DataAttachments.NoElementsAllowed"); ///"ShareRootElementById is only allowed if the tree has a single named attachment point" public static string TreeValidationError_ElementRoot_ShareRootElementByIdNotAllowed=>T("TreeValidationError.ElementRoot.ShareRootElementByIdNotAllowed"); ///"The value of the Id is not allowed. The Id should be non-empty, not start with NodeAutoId_ and not be RootTreeNode" public static string TreeValidationError_SimpleElement_WrongIdValue=>T("TreeValidationError.SimpleElement.WrongIdValue"); ///"The id value '{0}' has already been used in this tree" public static string TreeValidationError_SimpleElement_AlreadyUsedId_Template=>T("TreeValidationError.SimpleElement.AlreadyUsedId"); ///"The id value '{0}' has already been used in this tree" public static string TreeValidationError_SimpleElement_AlreadyUsedId(object parameter0)=>string.Format(T("TreeValidationError.SimpleElement.AlreadyUsedId"), parameter0); ///"The data interface '{0}' is used more than once as a child under the same parent element and this is not allowed" public static string TreeValidationError_DataElementsTreeNode_SameInterfaceUsedTwice_Template=>T("TreeValidationError.DataElementsTreeNode.SameInterfaceUsedTwice"); ///"The data interface '{0}' is used more than once as a child under the same parent element and this is not allowed" public static string TreeValidationError_DataElementsTreeNode_SameInterfaceUsedTwice(object parameter0)=>string.Format(T("TreeValidationError.DataElementsTreeNode.SameInterfaceUsedTwice"), parameter0); ///"The same interface '{0}' is used as parent type as parent filter and this is not allowed" public static string TreeValidationError_DataElementsTreeNode_SameParentFilterInterfaceUsedTwice_Template=>T("TreeValidationError.DataElementsTreeNode.SameParentFilterInterfaceUsedTwice"); ///"The same interface '{0}' is used as parent type as parent filter and this is not allowed" public static string TreeValidationError_DataElementsTreeNode_SameParentFilterInterfaceUsedTwice(object parameter0)=>string.Format(T("TreeValidationError.DataElementsTreeNode.SameParentFilterInterfaceUsedTwice"), parameter0); ///"More than one parent filter is pointing to the interface '{0}'. Change the Display value to Lazy" public static string TreeValidationError_DataElementsTreeNode_MoreThanOnParentFilterIsPointingToMe_Template=>T("TreeValidationError.DataElementsTreeNode.MoreThanOnParentFilterIsPointingToMe"); ///"More than one parent filter is pointing to the interface '{0}'. Change the Display value to Lazy" public static string TreeValidationError_DataElementsTreeNode_MoreThanOnParentFilterIsPointingToMe(object parameter0)=>string.Format(T("TreeValidationError.DataElementsTreeNode.MoreThanOnParentFilterIsPointingToMe"), parameter0); ///"Type attribute is missing" public static string TreeValidationError_DataFolderElements_MissingInterfaceType=>T("TreeValidationError.DataFolderElements.MissingInterfaceType"); ///"The interface type '{0}' does not match the parent elements interface type '{1}'" public static string TreeValidationError_DataFolderElements_WrongInterfaceType_Template=>T("TreeValidationError.DataFolderElements.WrongInterfaceType"); ///"The interface type '{0}' does not match the parent elements interface type '{1}'" public static string TreeValidationError_DataFolderElements_WrongInterfaceType(object parameter0,object parameter1)=>string.Format(T("TreeValidationError.DataFolderElements.WrongInterfaceType"), parameter0,parameter1); ///"DateFormat attribute requires that the property '{0}' should be of type '{1}' but is type '{2}'" public static string TreeValidationError_DataFolderElements_DateFormetNotAllowed_Template=>T("TreeValidationError.DataFolderElements.DateFormetNotAllowed"); ///"DateFormat attribute requires that the property '{0}' should be of type '{1}' but is type '{2}'" public static string TreeValidationError_DataFolderElements_DateFormetNotAllowed(object parameter0,object parameter1,object parameter2)=>string.Format(T("TreeValidationError.DataFolderElements.DateFormetNotAllowed"), parameter0,parameter1,parameter2); ///"The property '{0}' is of type Date and this requires the DateFormat attribute to be present" public static string TreeValidationError_DataFolderElements_DateFormetIsMissing_Template=>T("TreeValidationError.DataFolderElements.DateFormetIsMissing"); ///"The property '{0}' is of type Date and this requires the DateFormat attribute to be present" public static string TreeValidationError_DataFolderElements_DateFormetIsMissing(object parameter0)=>string.Format(T("TreeValidationError.DataFolderElements.DateFormetIsMissing"), parameter0); ///"Ranges and first-letter-only not allowed at the same time" public static string TreeValidationError_DataFolderElements_RangesAndFirstLetterOnlyNotAllowed=>T("TreeValidationError.DataFolderElements.RangesAndFirstLetterOnlyNotAllowed"); ///"First-letter-only requires that the property '{0}' should be of type '{1}' but is type '{2}'" public static string TreeValidationError_DataFolderElements_WrongFirstLetterOnlyPropertyType_Template=>T("TreeValidationError.DataFolderElements.WrongFirstLetterOnlyPropertyType"); ///"First-letter-only requires that the property '{0}' should be of type '{1}' but is type '{2}'" public static string TreeValidationError_DataFolderElements_WrongFirstLetterOnlyPropertyType(object parameter0,object parameter1,object parameter2)=>string.Format(T("TreeValidationError.DataFolderElements.WrongFirstLetterOnlyPropertyType"), parameter0,parameter1,parameter2); ///"Only data child elements with the same interface type as the folder grouping ('{0}') are allowed" public static string TreeValidationError_DataFolderElements_WrongDateChildInterfaceType_Template=>T("TreeValidationError.DataFolderElements.WrongDateChildInterfaceType"); ///"Only data child elements with the same interface type as the folder grouping ('{0}') are allowed" public static string TreeValidationError_DataFolderElements_WrongDateChildInterfaceType(object parameter0)=>string.Format(T("TreeValidationError.DataFolderElements.WrongDateChildInterfaceType"), parameter0); ///"Switching from the interface type '{0}' to a different interface type '{1}' is not allowed in the same folder grouping group" public static string TreeValidationError_DataFolderElements_InterfaceTypeSwitchNotAllowed_Template=>T("TreeValidationError.DataFolderElements.InterfaceTypeSwitchNotAllowed"); ///"Switching from the interface type '{0}' to a different interface type '{1}' is not allowed in the same folder grouping group" public static string TreeValidationError_DataFolderElements_InterfaceTypeSwitchNotAllowed(object parameter0,object parameter1)=>string.Format(T("TreeValidationError.DataFolderElements.InterfaceTypeSwitchNotAllowed"), parameter0,parameter1); ///"Using the field name '{0}' twice in the same grouping tree is not allowed" public static string TreeValidationError_DataFolderElements_SameFieldUsedTwice_Template=>T("TreeValidationError.DataFolderElements.SameFieldUsedTwice"); ///"Using the field name '{0}' twice in the same grouping tree is not allowed" public static string TreeValidationError_DataFolderElements_SameFieldUsedTwice(object parameter0)=>string.Format(T("TreeValidationError.DataFolderElements.SameFieldUsedTwice"), parameter0); ///"Maximum one parent id filter node can be used on data elements used in groupings" public static string TreeValidationError_DataFolderElements_TooManyParentIdFilters=>T("TreeValidationError.DataFolderElements.TooManyParentIdFilters"); ///"The type '{0}' is not in the parent tree of this node or specified as an attachment points type" public static string TreeValidationError_ParentIdFilterNode_TypeIsNotInParentTree_Template=>T("TreeValidationError.ParentIdFilterNode.TypeIsNotInParentTree"); ///"The type '{0}' is not in the parent tree of this node or specified as an attachment points type" public static string TreeValidationError_ParentIdFilterNode_TypeIsNotInParentTree(object parameter0)=>string.Format(T("TreeValidationError.ParentIdFilterNode.TypeIsNotInParentTree"), parameter0); ///"The operator '{0}' is unknown or not supported" public static string TreeValidationError_FieldFilter_UnknownOperatorName_Template=>T("TreeValidationError.FieldFilter.UnknownOperatorName"); ///"The operator '{0}' is unknown or not supported" public static string TreeValidationError_FieldFilter_UnknownOperatorName(object parameter0)=>string.Format(T("TreeValidationError.FieldFilter.UnknownOperatorName"), parameter0); ///"The string value '{0}' could not be converted to the type '{1}'" public static string TreeValidationError_FieldFilter_ValueCouldNotBeConverted_Template=>T("TreeValidationError.FieldFilter.ValueCouldNotBeConverted"); ///"The string value '{0}' could not be converted to the type '{1}'" public static string TreeValidationError_FieldFilter_ValueCouldNotBeConverted(object parameter0,object parameter1)=>string.Format(T("TreeValidationError.FieldFilter.ValueCouldNotBeConverted"), parameter0,parameter1); ///"The operator '{0}' is not supported for the type '{1}'" public static string TreeValidationError_FieldFilter_OperatorNotSupportedForType_Template=>T("TreeValidationError.FieldFilter.OperatorNotSupportedForType"); ///"The operator '{0}' is not supported for the type '{1}'" public static string TreeValidationError_FieldFilter_OperatorNotSupportedForType(object parameter0,object parameter1)=>string.Format(T("TreeValidationError.FieldFilter.OperatorNotSupportedForType"), parameter0,parameter1); ///"Function markup is missing" public static string TreeValidationError_FunctionFilter_MissingFunctionMarkup=>T("TreeValidationError.FunctionFilter.MissingFunctionMarkup"); ///"The function could not be created for the provided function markup" public static string TreeValidationError_FunctionFilter_WrongFunctionMarkup=>T("TreeValidationError.FunctionFilter.WrongFunctionMarkup"); ///"The function does not return value of the type '{0}'" public static string TreeValidationError_FunctionFilter_WrongReturnValue_Template=>T("TreeValidationError.FunctionFilter.WrongReturnValue"); ///"The function does not return value of the type '{0}'" public static string TreeValidationError_FunctionFilter_WrongReturnValue(object parameter0)=>string.Format(T("TreeValidationError.FunctionFilter.WrongReturnValue"), parameter0); ///"The return type of the expression returned by the function is '{0}', '{1}' was expected" public static string TreeValidationError_FunctionFilter_WrongFunctionReturnType_Template=>T("TreeValidationError.FunctionFilter.WrongFunctionReturnType"); ///"The return type of the expression returned by the function is '{0}', '{1}' was expected" public static string TreeValidationError_FunctionFilter_WrongFunctionReturnType(object parameter0,object parameter1)=>string.Format(T("TreeValidationError.FunctionFilter.WrongFunctionReturnType"), parameter0,parameter1); ///"The parameter count of expression returned by the function is '{0}', 1 was expected" public static string TreeValidationError_FunctionFilter_WrongFunctionParameterCount_Template=>T("TreeValidationError.FunctionFilter.WrongFunctionParameterCount"); ///"The parameter count of expression returned by the function is '{0}', 1 was expected" public static string TreeValidationError_FunctionFilter_WrongFunctionParameterCount(object parameter0)=>string.Format(T("TreeValidationError.FunctionFilter.WrongFunctionParameterCount"), parameter0); ///"The expressions parameter type returned by the function is '{0}', '{1}' was expected" public static string TreeValidationError_FunctionFilter_WrongFunctionParameterType_Template=>T("TreeValidationError.FunctionFilter.WrongFunctionParameterType"); ///"The expressions parameter type returned by the function is '{0}', '{1}' was expected" public static string TreeValidationError_FunctionFilter_WrongFunctionParameterType(object parameter0,object parameter1)=>string.Format(T("TreeValidationError.FunctionFilter.WrongFunctionParameterType"), parameter0,parameter1); ///"The file '{0}' does not exist" public static string TreeValidationError_CustomFormMarkup_MissingFile_Template=>T("TreeValidationError.CustomFormMarkup.MissingFile"); ///"The file '{0}' does not exist" public static string TreeValidationError_CustomFormMarkup_MissingFile(object parameter0)=>string.Format(T("TreeValidationError.CustomFormMarkup.MissingFile"), parameter0); ///"The custom markup path '{0}' is wrongly formatted. Use ~/Dir1/Dir2/File.xml" public static string TreeValidationError_CustomFormMarkup_BadMarkupPath_Template=>T("TreeValidationError.CustomFormMarkup.BadMarkupPath"); ///"The custom markup path '{0}' is wrongly formatted. Use ~/Dir1/Dir2/File.xml" public static string TreeValidationError_CustomFormMarkup_BadMarkupPath(object parameter0)=>string.Format(T("TreeValidationError.CustomFormMarkup.BadMarkupPath"), parameter0); ///"The file '{0}' does not contain valid XML markup." public static string TreeValidationError_CustomFormMarkup_InvalidXml_Template=>T("TreeValidationError.CustomFormMarkup.InvalidXml"); ///"The file '{0}' does not contain valid XML markup." public static string TreeValidationError_CustomFormMarkup_InvalidXml(object parameter0)=>string.Format(T("TreeValidationError.CustomFormMarkup.InvalidXml"), parameter0); ///"The function does not return value of the type '{0}'" public static string TreeValidationError_ReportFunctionAction_WrongReturnValue_Template=>T("TreeValidationError.ReportFunctionAction.WrongReturnValue"); ///"The function does not return value of the type '{0}'" public static string TreeValidationError_ReportFunctionAction_WrongReturnValue(object parameter0)=>string.Format(T("TreeValidationError.ReportFunctionAction.WrongReturnValue"), parameter0); ///"The edit data action only applies to elements that produce data elements" public static string TreeValidationError_GenericEditDataAction_OwnerIsNotDataNode=>T("TreeValidationError.GenericEditDataAction.OwnerIsNotDataNode"); ///"The delete data action only applies to elements that produce data elements" public static string TreeValidationError_GenericDeleteDataAction_OwnerIsNotDataNode=>T("TreeValidationError.GenericDeleteDataAction.OwnerIsNotDataNode"); ///"The dialog type '{0}' is not supported" public static string TreeValidationError_MessageBoxAction_UnknownDialogType_Template=>T("TreeValidationError.MessageBoxAction.UnknownDialogType"); ///"The dialog type '{0}' is not supported" public static string TreeValidationError_MessageBoxAction_UnknownDialogType(object parameter0)=>string.Format(T("TreeValidationError.MessageBoxAction.UnknownDialogType"), parameter0); ///"Too many '{0}' elements, only one is allowed" public static string TreeValidationError_CustomUrlAction_TooManyPostParameterElements_Template=>T("TreeValidationError.CustomUrlAction.TooManyPostParameterElements"); ///"Too many '{0}' elements, only one is allowed" public static string TreeValidationError_CustomUrlAction_TooManyPostParameterElements(object parameter0)=>string.Format(T("TreeValidationError.CustomUrlAction.TooManyPostParameterElements"), parameter0); ///"The view type '{0}' is not supported" public static string TreeValidationError_CustomUrlAction_UnknownViewType_Template=>T("TreeValidationError.CustomUrlAction.UnknownViewType"); ///"The view type '{0}' is not supported" public static string TreeValidationError_CustomUrlAction_UnknownViewType(object parameter0)=>string.Format(T("TreeValidationError.CustomUrlAction.UnknownViewType"), parameter0); ///"The direction value '{0}' is wrong, should be either 'ascending' or 'descending'" public static string TreeValidationError_FieldOrderBy_UnknownDirection_Template=>T("TreeValidationError.FieldOrderBy.UnknownDirection"); ///"The direction value '{0}' is wrong, should be either 'ascending' or 'descending'" public static string TreeValidationError_FieldOrderBy_UnknownDirection(object parameter0)=>string.Format(T("TreeValidationError.FieldOrderBy.UnknownDirection"), parameter0); ///"The type '{0}' does not contain a field named '{1}'" public static string TreeValidationError_FieldOrderBy_UnknownField_Template=>T("TreeValidationError.FieldOrderBy.UnknownField"); ///"The type '{0}' does not contain a field named '{1}'" public static string TreeValidationError_FieldOrderBy_UnknownField(object parameter0,object parameter1)=>string.Format(T("TreeValidationError.FieldOrderBy.UnknownField"), parameter0,parameter1); ///"'{0}' is in wrong format, use the format {1} for raw values or {2} for formatted values. For format options, see the .ToString() oprions for the field type, ex 'yyyy MMM' for DateTime" public static string TreeValidationError_DataFieldValueHelper_WrongFormat_Template=>T("TreeValidationError.DataFieldValueHelper.WrongFormat"); ///"'{0}' is in wrong format, use the format {1} for raw values or {2} for formatted values. For format options, see the .ToString() oprions for the field type, ex 'yyyy MMM' for DateTime" public static string TreeValidationError_DataFieldValueHelper_WrongFormat(object parameter0,object parameter1,object parameter2)=>string.Format(T("TreeValidationError.DataFieldValueHelper.WrongFormat"), parameter0,parameter1,parameter2); ///"The interface '{0}' is not contained in the current element or any of its parents" public static string TreeValidationError_DataFieldValueHelper_InterfaceNotInParentTree_Template=>T("TreeValidationError.DataFieldValueHelper.InterfaceNotInParentTree"); ///"The interface '{0}' is not contained in the current element or any of its parents" public static string TreeValidationError_DataFieldValueHelper_InterfaceNotInParentTree(object parameter0)=>string.Format(T("TreeValidationError.DataFieldValueHelper.InterfaceNotInParentTree"), parameter0); ///"The range value is wrongly formatted" public static string TreeValidationError_Range_WrongFormat=>T("TreeValidationError.Range.WrongFormat"); ///"The property '{0}' is of type '{1}' which does not support ranges" public static string TreeValidationError_Range_UnsupportedType_Template=>T("TreeValidationError.Range.UnsupportedType"); ///"The property '{0}' is of type '{1}' which does not support ranges" public static string TreeValidationError_Range_UnsupportedType(object parameter0,object parameter1)=>string.Format(T("TreeValidationError.Range.UnsupportedType"), parameter0,parameter1); ///"The value first value ({0}) in a range should be lesser than second value ({1})" public static string TreeValidationError_Range_MinMaxError_Template=>T("TreeValidationError.Range.MinMaxError"); ///"The value first value ({0}) in a range should be lesser than second value ({1})" public static string TreeValidationError_Range_MinMaxError(object parameter0,object parameter1)=>string.Format(T("TreeValidationError.Range.MinMaxError"), parameter0,parameter1); ///"The max value of a range should be less than the min value of the succeeding range" public static string TreeValidationError_Range_NextRangeError=>T("TreeValidationError.Range.NextRangeError"); ///"From {0} to {1}" public static string TreeRanges_IntRange_Closed_Template=>T("TreeRanges.IntRange.Closed"); ///"From {0} to {1}" public static string TreeRanges_IntRange_Closed(object parameter0,object parameter1)=>string.Format(T("TreeRanges.IntRange.Closed"), parameter0,parameter1); ///"{0} or less" public static string TreeRanges_IntRange_MinOpenEnded_Template=>T("TreeRanges.IntRange.MinOpenEnded"); ///"{0} or less" public static string TreeRanges_IntRange_MinOpenEnded(object parameter0)=>string.Format(T("TreeRanges.IntRange.MinOpenEnded"), parameter0); ///"{0} or more" public static string TreeRanges_IntRange_MaxOpenEnded_Template=>T("TreeRanges.IntRange.MaxOpenEnded"); ///"{0} or more" public static string TreeRanges_IntRange_MaxOpenEnded(object parameter0)=>string.Format(T("TreeRanges.IntRange.MaxOpenEnded"), parameter0); ///"Other" public static string TreeRanges_IntRange_Other=>T("TreeRanges.IntRange.Other"); ///"From {0} to {1}" public static string TreeRanges_StringRange_Closed_Template=>T("TreeRanges.StringRange.Closed"); ///"From {0} to {1}" public static string TreeRanges_StringRange_Closed(object parameter0,object parameter1)=>string.Format(T("TreeRanges.StringRange.Closed"), parameter0,parameter1); ///"{0} and before" public static string TreeRanges_StringRange_MinOpenEnded_Template=>T("TreeRanges.StringRange.MinOpenEnded"); ///"{0} and before" public static string TreeRanges_StringRange_MinOpenEnded(object parameter0)=>string.Format(T("TreeRanges.StringRange.MinOpenEnded"), parameter0); ///"{0} and after" public static string TreeRanges_StringRange_MaxOpenEnded_Template=>T("TreeRanges.StringRange.MaxOpenEnded"); ///"{0} and after" public static string TreeRanges_StringRange_MaxOpenEnded(object parameter0)=>string.Format(T("TreeRanges.StringRange.MaxOpenEnded"), parameter0); ///"Other" public static string TreeRanges_StringRange_Other=>T("TreeRanges.StringRange.Other"); ///"Add" public static string GenericAddDataAction_DefaultLabel=>T("GenericAddDataAction.DefaultLabel"); ///"Edit" public static string GenericEditDataAction_DefaultLabel=>T("GenericEditDataAction.DefaultLabel"); ///"Delete" public static string GenericDeleteDataAction_DefaultLabel=>T("GenericDeleteDataAction.DefaultLabel"); ///"Duplicate" public static string GenericDuplicateDataAction_DefaultLabel=>T("GenericDuplicateDataAction.DefaultLabel"); ///"Cascade delete error" public static string TreeGenericDelete_CascadeDeleteErrorTitle=>T("TreeGenericDelete.CascadeDeleteErrorTitle"); ///"The type is referenced by another type that does not allow cascade deletes. This operation is halted" public static string TreeGenericDelete_CascadeDeleteErrorMessage=>T("TreeGenericDelete.CascadeDeleteErrorMessage"); ///"Delete Data?" public static string TreeGenericDeleteConfirm_LabelFieldGroup=>T("TreeGenericDeleteConfirm.LabelFieldGroup"); ///"Delete" public static string TreeGenericDeleteConfirm_Text=>T("TreeGenericDeleteConfirm.Text"); ///"Delete data?" public static string TreeGenericDeleteConfirmDeletingRelatedData_LabelFieldGroup=>T("TreeGenericDeleteConfirmDeletingRelatedData.LabelFieldGroup"); ///"There is some referenced data that will also be deleted, do you want to continue?" public static string TreeGenericDeleteConfirmDeletingRelatedData_ConfirmationText=>T("TreeGenericDeleteConfirmDeletingRelatedData.ConfirmationText"); ///"Add" public static string TreeAddTreeDefinitionWorkflow_AddNew_Label=>T("TreeAddTreeDefinitionWorkflow.AddNew.Label"); ///"Add new tree definition" public static string TreeAddTreeDefinitionWorkflow_AddNew_ToolTip=>T("TreeAddTreeDefinitionWorkflow.AddNew.ToolTip"); ///"Add new tree definition" public static string TreeAddTreeDefinition_Layout_Label=>T("TreeAddTreeDefinition.Layout.Label"); ///"Add new tree definition" public static string TreeAddTreeDefinition_FieldGroup_Label=>T("TreeAddTreeDefinition.FieldGroup.Label"); ///"Definition name" public static string TreeAddTreeDefinition_NameTextBox_Label=>T("TreeAddTreeDefinition.NameTextBox.Label"); ///"Definition name" public static string TreeAddTreeDefinition_NameTextBox_Help=>T("TreeAddTreeDefinition.NameTextBox.Help"); ///"Template" public static string TreeAddTreeDefinition_TemplateSelector_Label=>T("TreeAddTreeDefinition.TemplateSelector.Label"); ///"Select a template to start with" public static string TreeAddTreeDefinition_TemplateSelector_Help=>T("TreeAddTreeDefinition.TemplateSelector.Help"); ///"Position" public static string TreeAddTreeDefinition_PositionSelector_Label=>T("TreeAddTreeDefinition.PositionSelector.Label"); ///"Position" public static string TreeAddTreeDefinition_PositionSelector_Help=>T("TreeAddTreeDefinition.PositionSelector.Help"); ///"Delete" public static string TreeDeleteTreeDefinitionWorkflow_Delete_Label=>T("TreeDeleteTreeDefinitionWorkflow.Delete.Label"); ///"Delete tree definition" public static string TreeDeleteTreeDefinitionWorkflow_Delete_ToolTip=>T("TreeDeleteTreeDefinitionWorkflow.Delete.ToolTip"); ///"Delete tree definition" public static string TreeDeleteTreeDefinition_Layout_Label=>T("TreeDeleteTreeDefinition.Layout.Label"); ///"Delete selected tree definition" public static string TreeDeleteTreeDefinition_Title=>T("TreeDeleteTreeDefinition.Title"); ///"Delete selected tree definition?" public static string TreeDeleteTreeDefinition_Description=>T("TreeDeleteTreeDefinition.Description"); ///"Edit" public static string TreeDeleteTreeDefinitionWorkflow_Edit_Label=>T("TreeDeleteTreeDefinitionWorkflow.Edit.Label"); ///"Edit tree definition" public static string TreeDeleteTreeDefinitionWorkflow_Edit_ToolTip=>T("TreeDeleteTreeDefinitionWorkflow.Edit.ToolTip"); ///"Add Application" public static string AddApplicationWorkflow_AddApplication_Label=>T("AddApplicationWorkflow.AddApplication.Label"); ///"Add new application" public static string AddApplicationWorkflow_AddApplication_ToolTip=>T("AddApplicationWorkflow.AddApplication.ToolTip"); ///"Add application" public static string AddApplication_Layout_Label=>T("AddApplication.Layout.Label"); ///"Select application" public static string AddApplication_FieldGroup_Label=>T("AddApplication.FieldGroup.Label"); ///"Application" public static string AddApplication_TreeIdSelector_Label=>T("AddApplication.TreeIdSelector.Label"); ///"Select the application that you wish to add" public static string AddApplication_TreeIdSelector_Help=>T("AddApplication.TreeIdSelector.Help"); ///"Position" public static string AddApplication_PositionSelector_Label=>T("AddApplication.PositionSelector.Label"); ///"The position to insert this application" public static string AddApplication_PositionSelector_Help=>T("AddApplication.PositionSelector.Help"); ///"No applications" public static string AddApplication_NoTrees_Title=>T("AddApplication.NoTrees.Title"); ///"You have added all available applications" public static string AddApplication_NoTrees_Message=>T("AddApplication.NoTrees.Message"); ///"Remove Application" public static string RemoveApplicationWorkflow_RemoveApplication_Label=>T("RemoveApplicationWorkflow.RemoveApplication.Label"); ///"Remove existing application" public static string RemoveApplicationWorkflow_RemoveApplication_ToolTip=>T("RemoveApplicationWorkflow.RemoveApplication.ToolTip"); ///"Remove application" public static string RemoveApplication_Layout_Label=>T("RemoveApplication.Layout.Label"); ///"Remove application" public static string RemoveApplication_FieldGroup_Label=>T("RemoveApplication.FieldGroup.Label"); ///"Application" public static string RemoveApplication_TreeIdSelector_Label=>T("RemoveApplication.TreeIdSelector.Label"); ///"Select the application that you wish to remove" public static string RemoveApplication_TreeIdSelector_Help=>T("RemoveApplication.TreeIdSelector.Help"); ///"No applications" public static string RemoveApplication_NoTrees_Title=>T("RemoveApplication.NoTrees.Title"); ///"You have removed all available applications" public static string RemoveApplication_NoTrees_Message=>T("RemoveApplication.NoTrees.Message"); ///"Translate data" public static string LocalizeDataWorkflow_LocalizeDataLabel=>T("LocalizeDataWorkflow.LocalizeDataLabel"); ///"Translate data" public static string LocalizeDataWorkflow_LocalizeDataToolTip=>T("LocalizeDataWorkflow.LocalizeDataToolTip"); ///"Not yet approved or published" public static string LocalizeDataWorkflow_DisabledData=>T("LocalizeDataWorkflow.DisabledData"); ///"Failed to translate data" public static string LocalizeData_ShowError_Layout_Label=>T("LocalizeData.ShowError.Layout.Label"); ///"Translation errors" public static string LocalizeData_ShowError_InfoTable_Caption=>T("LocalizeData.ShowError.InfoTable.Caption"); ///"The following fields has a reference to a data type. You should translate these data items before you can translate this data item" public static string LocalizeData_ShowError_Description=>T("LocalizeData.ShowError.Description"); ///"The field '{0}' is referencing data of type '{1}' with the label '{2}'" public static string LocalizeData_ShowError_FieldErrorFormat_Template=>T("LocalizeData.ShowError.FieldErrorFormat"); ///"The field '{0}' is referencing data of type '{1}' with the label '{2}'" public static string LocalizeData_ShowError_FieldErrorFormat(object parameter0,object parameter1,object parameter2)=>string.Format(T("LocalizeData.ShowError.FieldErrorFormat"), parameter0,parameter1,parameter2); ///"This data has already been translated. The translated version belongs to a different group." public static string LocalizeData_ShowError_AlreadyTranslated=>T("LocalizeData.ShowError.AlreadyTranslated"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.C1Console.Trees", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_C1Console_Users { ///"Change Password..." public static string ChangeOwnPasswordWorkflow_ElementActionLabel=>T("ChangeOwnPasswordWorkflow.ElementActionLabel"); ///"Change your password" public static string ChangeOwnPasswordWorkflow_ElementActionToolTip=>T("ChangeOwnPasswordWorkflow.ElementActionToolTip"); ///"Change Password" public static string ChangeOwnPasswordWorkflow_Dialog_Label=>T("ChangeOwnPasswordWorkflow.Dialog.Label"); ///"Existing password" public static string ChangeOwnPasswordWorkflow_Dialog_ExistingPassword_Label=>T("ChangeOwnPasswordWorkflow.Dialog.ExistingPassword.Label"); ///"For security reasons you must present your existing password before you can continue." public static string ChangeOwnPasswordWorkflow_Dialog_ExistingPassword_Help=>T("ChangeOwnPasswordWorkflow.Dialog.ExistingPassword.Help"); ///"New password" public static string ChangeOwnPasswordWorkflow_Dialog_NewPassword_Label=>T("ChangeOwnPasswordWorkflow.Dialog.NewPassword.Label"); ///"The password specified in this field must match the confirmation below." public static string ChangeOwnPasswordWorkflow_Dialog_NewPassword_Help=>T("ChangeOwnPasswordWorkflow.Dialog.NewPassword.Help"); ///"Confirm new password" public static string ChangeOwnPasswordWorkflow_Dialog_NewPasswordConfirmed_Label=>T("ChangeOwnPasswordWorkflow.Dialog.NewPasswordConfirmed.Label"); ///"The password specified in this field must match the one specified above." public static string ChangeOwnPasswordWorkflow_Dialog_NewPasswordConfirmed_Help=>T("ChangeOwnPasswordWorkflow.Dialog.NewPasswordConfirmed.Help"); ///"The specified password is incorrect." public static string ChangeOwnPasswordWorkflow_Dialog_Validation_IncorrectPassword=>T("ChangeOwnPasswordWorkflow.Dialog.Validation.IncorrectPassword"); ///"The new passwords you typed do not match." public static string ChangeOwnPasswordWorkflow_Dialog_Validation_NewPasswordFieldsNotMatch=>T("ChangeOwnPasswordWorkflow.Dialog.Validation.NewPasswordFieldsNotMatch"); ///"The old and the new passwords are the same." public static string ChangeOwnPasswordWorkflow_Dialog_Validation_PasswordsAreTheSame=>T("ChangeOwnPasswordWorkflow.Dialog.Validation.PasswordsAreTheSame"); ///"The new password may not be an empty string." public static string ChangeOwnPasswordWorkflow_Dialog_Validation_NewPasswordIsEmpty=>T("ChangeOwnPasswordWorkflow.Dialog.Validation.NewPasswordIsEmpty"); ///"The new password must be at least {0} characters long." public static string ChangeOwnPasswordWorkflow_Dialog_Validation_NewPasswordTooShort_Template=>T("ChangeOwnPasswordWorkflow.Dialog.Validation.NewPasswordTooShort"); ///"The new password must be at least {0} characters long." public static string ChangeOwnPasswordWorkflow_Dialog_Validation_NewPasswordTooShort(object parameter0)=>string.Format(T("ChangeOwnPasswordWorkflow.Dialog.Validation.NewPasswordTooShort"), parameter0); ///"Password change isn't supported." public static string ChangeOwnPasswordWorkflow_NotSupportedErrorLabel=>T("ChangeOwnPasswordWorkflow.NotSupportedErrorLabel"); ///"Password change isn't supported in current configuration." public static string ChangeOwnPasswordWorkflow_NotSupportedErrorText=>T("ChangeOwnPasswordWorkflow.NotSupportedErrorText"); ///"Profile Settings..." public static string ChangeOwnCultureWorkflow_ElementActionLabel=>T("ChangeOwnCultureWorkflow.ElementActionLabel"); ///"Set the C1 Console language and formatting of numbers, times and dates" public static string ChangeOwnCultureWorkflow_ElementActionToolTip=>T("ChangeOwnCultureWorkflow.ElementActionToolTip"); ///"Profile Settings" public static string ChangeOwnCultureWorkflow_Dialog_Label=>T("ChangeOwnCultureWorkflow.Dialog.Label"); ///"Display Preferences" public static string ChangeOwnCultureWorkflow_Dialog_CultureSelector_Label=>T("ChangeOwnCultureWorkflow.Dialog.CultureSelector.Label"); ///"Display for time, date, and number formats within the console" public static string ChangeOwnCultureWorkflow_Dialog_CultureSelector_Help=>T("ChangeOwnCultureWorkflow.Dialog.CultureSelector.Help"); ///"Console Language Preferences" public static string ChangeOwnCultureWorkflow_Dialog_C1ConsoleLanguageSelector_Label=>T("ChangeOwnCultureWorkflow.Dialog.C1ConsoleLanguageSelector.Label"); ///"Language displayed within your console for labels, help texts, dialogs, etc. The available options are limited to language packages installed. See Composite.Localization packages for more language options." public static string ChangeOwnCultureWorkflow_Dialog_C1ConsoleLanguageSelector_Help=>T("ChangeOwnCultureWorkflow.Dialog.C1ConsoleLanguageSelector.Help"); ///"Change application language" public static string ChangeOwnCultureWorkflow_Dialog_Confirm_Title=>T("ChangeOwnCultureWorkflow.Dialog.Confirm.Title"); ///"Are your sure you wish to change the settings? The application will restart and all your unsaved changes will be lost." public static string ChangeOwnCultureWorkflow_Dialog_Confirm_Text=>T("ChangeOwnCultureWorkflow.Dialog.Confirm.Text"); ///"Administrators" public static string AdministratorAutoCreator_DefaultGroupName=>T("AdministratorAutoCreator.DefaultGroupName"); ///"Translation..." public static string ChangeForeignLocaleWorkflow_ActionLabel=>T("ChangeForeignLocaleWorkflow.ActionLabel"); ///"Change source language" public static string ChangeForeignLocaleWorkflow_ActionToolTip=>T("ChangeForeignLocaleWorkflow.ActionToolTip"); ///"None" public static string ChangeForeignLocaleWorkflow_NoForeignLocaleLabel=>T("ChangeForeignLocaleWorkflow.NoForeignLocaleLabel"); ///"Translation" public static string ChangeForeignLocaleWorkflow_Dialog_Label=>T("ChangeForeignLocaleWorkflow.Dialog.Label"); ///"Select language to translate from" public static string ChangeForeignLocaleWorkflow_FieldGroup_Label=>T("ChangeForeignLocaleWorkflow.FieldGroup.Label"); ///"Multiple languages not installed" public static string ChangeForeignLocaleWorkflow_NoOrOneActiveLocales_Title=>T("ChangeForeignLocaleWorkflow.NoOrOneActiveLocales.Title"); ///"Two or more languages must be installed in order to support translations. Administrators can add more languages in the 'System' perspective." public static string ChangeForeignLocaleWorkflow_NoOrOneActiveLocales_Description=>T("ChangeForeignLocaleWorkflow.NoOrOneActiveLocales.Description"); ///"From-language" public static string ChangeForeignLocaleWorkflow_ForeignCultureSelector_Label=>T("ChangeForeignLocaleWorkflow.ForeignCultureSelector.Label"); ///"Pages written in the from-language will be indicated by globe icons in the Content tree. The associated "Translate Page" action imports the page into the current working language." public static string ChangeForeignLocaleWorkflow_ForeignCultureSelector_Help=>T("ChangeForeignLocaleWorkflow.ForeignCultureSelector.Help"); ///"The active language has been changed" public static string ChangeOwnActiveLocaleWorkflow_CloseAllViews_Message=>T("ChangeOwnActiveLocaleWorkflow.CloseAllViews.Message"); ///"Password should be at least {0} characters long." public static string PasswordRules_MinimumLength_Template=>T("PasswordRules.MinimumLength"); ///"Password should be at least {0} characters long." public static string PasswordRules_MinimumLength(object parameter0)=>string.Format(T("PasswordRules.MinimumLength"), parameter0); ///"Password should not match any of the previously used {0} passwords." public static string PasswordRules_EnforcePasswordHistory_Template=>T("PasswordRules.EnforcePasswordHistory"); ///"Password should not match any of the previously used {0} passwords." public static string PasswordRules_EnforcePasswordHistory(object parameter0)=>string.Format(T("PasswordRules.EnforcePasswordHistory"), parameter0); ///"Password should contain 3/4 of the following items: uppercase letters, lowercase letters, numbers, symbols." public static string PasswordRules_DifferentCharacterGroups=>T("PasswordRules.DifferentCharacterGroups"); ///"Password should not be based on a user name." public static string PasswordRules_DoNotUseUserName=>T("PasswordRules.DoNotUseUserName"); ///"Confirmation password mismatch" public static string ChangePasswordForm_ConfirmationPasswordMimatch=>T("ChangePasswordForm.ConfirmationPasswordMimatch"); ///"Username" public static string ChangePasswordForm_Username=>T("ChangePasswordForm.Username"); ///"Old Password" public static string ChangePasswordForm_OldPassword=>T("ChangePasswordForm.OldPassword"); ///"New Password" public static string ChangePasswordForm_NewPassword=>T("ChangePasswordForm.NewPassword"); ///"Confirm Password" public static string ChangePasswordForm_ConfirmPassword=>T("ChangePasswordForm.ConfirmPassword"); ///"Change Password" public static string ChangePasswordForm_ChangePasswordButton=>T("ChangePasswordForm.ChangePasswordButton"); ///"Password is older than {0} days. Please change your password." public static string ChangePasswordForm_PasswordExpiredMessage_Template=>T("ChangePasswordForm.PasswordExpiredMessage"); ///"Password is older than {0} days. Please change your password." public static string ChangePasswordForm_PasswordExpiredMessage(object parameter0)=>string.Format(T("ChangePasswordForm.PasswordExpiredMessage"), parameter0); ///"The old password is incorrect." public static string ChangePasswordForm_IncorrectOldPassword=>T("ChangePasswordForm.IncorrectOldPassword"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.C1Console.Users", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Core_PackageSystem_PackageFragmentInstallers { ///"The package composite version requirements does not match the current composite version '{0}'. Expected version range [{1} - {2}]" public static string PackageManager_CompositeVersionMisMatch_Template=>T("PackageManager.CompositeVersionMisMatch"); ///"The package composite version requirements does not match the current composite version '{0}'. Expected version range [{1} - {2}]" public static string PackageManager_CompositeVersionMisMatch(object parameter0,object parameter1,object parameter2)=>string.Format(T("PackageManager.CompositeVersionMisMatch"), parameter0,parameter1,parameter2); ///"Package is already installed" public static string PackageManager_PackageAlreadyInstalled=>T("PackageManager.PackageAlreadyInstalled"); ///"A newer version of the package is already installed" public static string PackageManager_NewerVersionInstalled=>T("PackageManager.NewerVersionInstalled"); ///"Could not locate the package directory path '{0}'" public static string PackageManager_MissingPackageDirectory_Template=>T("PackageManager.MissingPackageDirectory"); ///"Could not locate the package directory path '{0}'" public static string PackageManager_MissingPackageDirectory(object parameter0)=>string.Format(T("PackageManager.MissingPackageDirectory"), parameter0); ///"The package is marked as non uninstallable" public static string PackageManager_Uninstallable=>T("PackageManager.Uninstallable"); ///"Could not locate the package zip file path '{0}'" public static string PackageManager_MissingZipFile_Template=>T("PackageManager.MissingZipFile"); ///"Could not locate the package zip file path '{0}'" public static string PackageManager_MissingZipFile(object parameter0)=>string.Format(T("PackageManager.MissingZipFile"), parameter0); ///"Could not locate the package uninstall file path '{0}'" public static string PackageManager_MissingUninstallFile_Template=>T("PackageManager.MissingUninstallFile"); ///"Could not locate the package uninstall file path '{0}'" public static string PackageManager_MissingUninstallFile(object parameter0)=>string.Format(T("PackageManager.MissingUninstallFile"), parameter0); ///"Missing '{0}' element." public static string PackageManager_MissingElement_Template=>T("PackageManager.MissingElement"); ///"Missing '{0}' element." public static string PackageManager_MissingElement(object parameter0)=>string.Format(T("PackageManager.MissingElement"), parameter0); ///"Missing '{0}' attribute." public static string PackageManager_MissingAttribute_Template=>T("PackageManager.MissingAttribute"); ///"Missing '{0}' attribute." public static string PackageManager_MissingAttribute(object parameter0)=>string.Format(T("PackageManager.MissingAttribute"), parameter0); ///"'{0}' attribute value is not a valid value." public static string PackageManager_InvalidAttributeValue_Template=>T("PackageManager.InvalidAttributeValue"); ///"'{0}' attribute value is not a valid value." public static string PackageManager_InvalidAttributeValue(object parameter0)=>string.Format(T("PackageManager.InvalidAttributeValue"), parameter0); ///"'{0}' element value is not a valid value" public static string PackageManager_InvalidElementValue_Template=>T("PackageManager.InvalidElementValue"); ///"'{0}' element value is not a valid value" public static string PackageManager_InvalidElementValue(object parameter0)=>string.Format(T("PackageManager.InvalidElementValue"), parameter0); ///"Expected exactly two elements, '{0}' and '{1}'" public static string ConfigurationTransformationPackageFragmentInstaller_ExpectedExactlyTwoElements_Template=>T("ConfigurationTransformationPackageFragmentInstaller.ExpectedExactlyTwoElements"); ///"Expected exactly two elements, '{0}' and '{1}'" public static string ConfigurationTransformationPackageFragmentInstaller_ExpectedExactlyTwoElements(object parameter0,object parameter1)=>string.Format(T("ConfigurationTransformationPackageFragmentInstaller.ExpectedExactlyTwoElements"), parameter0,parameter1); ///"Missing '{0}' element." public static string ConfigurationTransformationPackageFragmentInstaller_MissingElement_Template=>T("ConfigurationTransformationPackageFragmentInstaller.MissingElement"); ///"Missing '{0}' element." public static string ConfigurationTransformationPackageFragmentInstaller_MissingElement(object parameter0)=>string.Format(T("ConfigurationTransformationPackageFragmentInstaller.MissingElement"), parameter0); ///"Missing '{0}' attribute." public static string ConfigurationTransformationPackageFragmentInstaller_MissingAttribute_Template=>T("ConfigurationTransformationPackageFragmentInstaller.MissingAttribute"); ///"Missing '{0}' attribute." public static string ConfigurationTransformationPackageFragmentInstaller_MissingAttribute(object parameter0)=>string.Format(T("ConfigurationTransformationPackageFragmentInstaller.MissingAttribute"), parameter0); ///"The path '{0}' does not exist in the ZIP." public static string ConfigurationTransformationPackageFragmentInstaller_PathDoesNotExist_Template=>T("ConfigurationTransformationPackageFragmentInstaller.PathDoesNotExist"); ///"The path '{0}' does not exist in the ZIP." public static string ConfigurationTransformationPackageFragmentInstaller_PathDoesNotExist(object parameter0)=>string.Format(T("ConfigurationTransformationPackageFragmentInstaller.PathDoesNotExist"), parameter0); ///"Unable to parse ZIP'ed XSLT file '{0}'. {1}" public static string ConfigurationTransformationPackageFragmentInstaller_UnableToParsXslt_Template=>T("ConfigurationTransformationPackageFragmentInstaller.UnableToParsXslt"); ///"Unable to parse ZIP'ed XSLT file '{0}'. {1}" public static string ConfigurationTransformationPackageFragmentInstaller_UnableToParsXslt(object parameter0,object parameter1)=>string.Format(T("ConfigurationTransformationPackageFragmentInstaller.UnableToParsXslt"), parameter0,parameter1); ///"The XSLT file '{0}' will generate an invalid Configuration file. {1}" public static string ConfigurationTransformationPackageFragmentInstaller_XsltWillGeneratedInvalid_Template=>T("ConfigurationTransformationPackageFragmentInstaller.XsltWillGeneratedInvalid"); ///"The XSLT file '{0}' will generate an invalid Configuration file. {1}" public static string ConfigurationTransformationPackageFragmentInstaller_XsltWillGeneratedInvalid(object parameter0,object parameter1)=>string.Format(T("ConfigurationTransformationPackageFragmentInstaller.XsltWillGeneratedInvalid"), parameter0,parameter1); ///"Only one 'Types' element allowed" public static string DataPackageFragmentInstaller_OnlyOneElement=>T("DataPackageFragmentInstaller.OnlyOneElement"); ///"Missing 'Types' element" public static string DataPackageFragmentInstaller_MissingElement=>T("DataPackageFragmentInstaller.MissingElement"); ///"Missing {0} attribute in the configuration" public static string DataPackageFragmentInstaller_MissingAttribute_Template=>T("DataPackageFragmentInstaller.MissingAttribute"); ///"Missing {0} attribute in the configuration" public static string DataPackageFragmentInstaller_MissingAttribute(object parameter0)=>string.Format(T("DataPackageFragmentInstaller.MissingAttribute"), parameter0); ///"Wrong DataScopeIdentifier ({0}) name in the configuration" public static string DataPackageFragmentInstaller_WrongDataScopeIdentifier_Template=>T("DataPackageFragmentInstaller.WrongDataScopeIdentifier"); ///"Wrong DataScopeIdentifier ({0}) name in the configuration" public static string DataPackageFragmentInstaller_WrongDataScopeIdentifier(object parameter0)=>string.Format(T("DataPackageFragmentInstaller.WrongDataScopeIdentifier"), parameter0); ///"Wrong culture ({0}) name in the configuration" public static string DataPackageFragmentInstaller_WrongLocale_Template=>T("DataPackageFragmentInstaller.WrongLocale"); ///"Wrong culture ({0}) name in the configuration" public static string DataPackageFragmentInstaller_WrongLocale(object parameter0)=>string.Format(T("DataPackageFragmentInstaller.WrongLocale"), parameter0); ///"Missing file '{0}' in the package zip" public static string DataPackageFragmentInstaller_MissingFile_Template=>T("DataPackageFragmentInstaller.MissingFile"); ///"Missing file '{0}' in the package zip" public static string DataPackageFragmentInstaller_MissingFile(object parameter0)=>string.Format(T("DataPackageFragmentInstaller.MissingFile"), parameter0); ///"The data interface type '{0}' has not been configured in the system" public static string DataPackageFragmentInstaller_TypeNotConfigured_Template=>T("DataPackageFragmentInstaller.TypeNotConfigured"); ///"The data interface type '{0}' has not been configured in the system" public static string DataPackageFragmentInstaller_TypeNotConfigured(object parameter0)=>string.Format(T("DataPackageFragmentInstaller.TypeNotConfigured"), parameter0); ///"The data interface type '{0}' does not inherit the interface '{1}'" public static string DataPackageFragmentInstaller_TypeNotInheriting_Template=>T("DataPackageFragmentInstaller.TypeNotInheriting"); ///"The data interface type '{0}' does not inherit the interface '{1}'" public static string DataPackageFragmentInstaller_TypeNotInheriting(object parameter0,object parameter1)=>string.Format(T("DataPackageFragmentInstaller.TypeNotInheriting"), parameter0,parameter1); ///"The data interface type '{0}' does not have a property named '{1}'" public static string DataPackageFragmentInstaller_MissingProperty_Template=>T("DataPackageFragmentInstaller.MissingProperty"); ///"The data interface type '{0}' does not have a property named '{1}'" public static string DataPackageFragmentInstaller_MissingProperty(object parameter0,object parameter1)=>string.Format(T("DataPackageFragmentInstaller.MissingProperty"), parameter0,parameter1); ///"The data interface type '{0}' does not have a writable property named '{1}'" public static string DataPackageFragmentInstaller_MissingWritableProperty_Template=>T("DataPackageFragmentInstaller.MissingWritableProperty"); ///"The data interface type '{0}' does not have a writable property named '{1}'" public static string DataPackageFragmentInstaller_MissingWritableProperty(object parameter0,object parameter1)=>string.Format(T("DataPackageFragmentInstaller.MissingWritableProperty"), parameter0,parameter1); ///"Could not convert the value '{0}' to the type '{1}'" public static string DataPackageFragmentInstaller_ConversionFailed_Template=>T("DataPackageFragmentInstaller.ConversionFailed"); ///"Could not convert the value '{0}' to the type '{1}'" public static string DataPackageFragmentInstaller_ConversionFailed(object parameter0,object parameter1)=>string.Format(T("DataPackageFragmentInstaller.ConversionFailed"), parameter0,parameter1); ///"The property '{0}' on the interface '{1}' is missing a value." public static string DataPackageFragmentInstaller_MissingPropertyVaule_Template=>T("DataPackageFragmentInstaller.MissingPropertyVaule"); ///"The property '{0}' on the interface '{1}' is missing a value." public static string DataPackageFragmentInstaller_MissingPropertyVaule(object parameter0,object parameter1)=>string.Format(T("DataPackageFragmentInstaller.MissingPropertyVaule"), parameter0,parameter1); ///"Data type '{0}': {1} record(s) already installed" public static string DataPackageFragmentInstaller_DataExists_Template=>T("DataPackageFragmentInstaller.DataExists"); ///"Data type '{0}': {1} record(s) already installed" public static string DataPackageFragmentInstaller_DataExists(object parameter0,object parameter1)=>string.Format(T("DataPackageFragmentInstaller.DataExists"), parameter0,parameter1); ///"Missing data type descriptor for the type {0}" public static string DataPackageFragmentInstaller_MissingTypeDescriptor_Template=>T("DataPackageFragmentInstaller.MissingTypeDescriptor"); ///"Missing data type descriptor for the type {0}" public static string DataPackageFragmentInstaller_MissingTypeDescriptor(object parameter0)=>string.Format(T("DataPackageFragmentInstaller.MissingTypeDescriptor"), parameter0); ///"The data type '{0}' is not localized but a locale is specified in the configuration" public static string DataPackageFragmentInstaller_TypeNonLocalizedWithLocale_Template=>T("DataPackageFragmentInstaller.TypeNonLocalizedWithLocale"); ///"The data type '{0}' is not localized but a locale is specified in the configuration" public static string DataPackageFragmentInstaller_TypeNonLocalizedWithLocale(object parameter0)=>string.Format(T("DataPackageFragmentInstaller.TypeNonLocalizedWithLocale"), parameter0); ///"The data type '{0}' is localized but no locale is specified in the configuration" public static string DataPackageFragmentInstaller_TypeLocalizedWithoutLocale_Template=>T("DataPackageFragmentInstaller.TypeLocalizedWithoutLocale"); ///"The data type '{0}' is localized but no locale is specified in the configuration" public static string DataPackageFragmentInstaller_TypeLocalizedWithoutLocale(object parameter0)=>string.Format(T("DataPackageFragmentInstaller.TypeLocalizedWithoutLocale"), parameter0); ///"Referenced data missing. Type: {0}, {1}: '{2}'" public static string DataPackageFragmentInstaller_ReferencedDataMissing_Template=>T("DataPackageFragmentInstaller.ReferencedDataMissing"); ///"Referenced data missing. Type: {0}, {1}: '{2}'" public static string DataPackageFragmentInstaller_ReferencedDataMissing(object parameter0,object parameter1,object parameter2)=>string.Format(T("DataPackageFragmentInstaller.ReferencedDataMissing"), parameter0,parameter1,parameter2); ///"Only one 'Types' element allowed" public static string DataPackageFragmentUninstaller_OnlyOneElement=>T("DataPackageFragmentUninstaller.OnlyOneElement"); ///"Missing {0} attribute in the configuration" public static string DataPackageFragmentUninstaller_MissingAttribute_Template=>T("DataPackageFragmentUninstaller.MissingAttribute"); ///"Missing {0} attribute in the configuration" public static string DataPackageFragmentUninstaller_MissingAttribute(object parameter0)=>string.Format(T("DataPackageFragmentUninstaller.MissingAttribute"), parameter0); ///"The data type '{0}' does not contain a key property named '{1}'" public static string DataPackageFragmentUninstaller_MissingKeyProperty_Template=>T("DataPackageFragmentUninstaller.MissingKeyProperty"); ///"The data type '{0}' does not contain a key property named '{1}'" public static string DataPackageFragmentUninstaller_MissingKeyProperty(object parameter0,object parameter1)=>string.Format(T("DataPackageFragmentUninstaller.MissingKeyProperty"), parameter0,parameter1); ///"Data item '{0}' of type {1} is referenced from a data item '{2}' of type '{3}'" public static string DataPackageFragmentUninstaller_DataIsReferenced_Template=>T("DataPackageFragmentUninstaller.DataIsReferenced"); ///"Data item '{0}' of type {1} is referenced from a data item '{2}' of type '{3}'" public static string DataPackageFragmentUninstaller_DataIsReferenced(object parameter0,object parameter1,object parameter2,object parameter3)=>string.Format(T("DataPackageFragmentUninstaller.DataIsReferenced"), parameter0,parameter1,parameter2,parameter3); ///"Page type '{0}' is referenced by page '{1}'" public static string DataPackageFragmentUninstaller_PageTypeIsReferenced_Template=>T("DataPackageFragmentUninstaller.PageTypeIsReferenced"); ///"Page type '{0}' is referenced by page '{1}'" public static string DataPackageFragmentUninstaller_PageTypeIsReferenced(object parameter0,object parameter1)=>string.Format(T("DataPackageFragmentUninstaller.PageTypeIsReferenced"), parameter0,parameter1); ///"Only one 'Types' element allowed" public static string DataTypePackageFragmentInstaller_OnlyOneElement=>T("DataTypePackageFragmentInstaller.OnlyOneElement"); ///"Missing 'Types' element" public static string DataTypePackageFragmentInstaller_MissingElement=>T("DataTypePackageFragmentInstaller.MissingElement"); ///"Missing {0} attribute in the configuration" public static string DataTypePackageFragmentInstaller_MissingAttribute_Template=>T("DataTypePackageFragmentInstaller.MissingAttribute"); ///"Missing {0} attribute in the configuration" public static string DataTypePackageFragmentInstaller_MissingAttribute(object parameter0)=>string.Format(T("DataTypePackageFragmentInstaller.MissingAttribute"), parameter0); ///"The data interface type '{0}' has not been configured in the system" public static string DataTypePackageFragmentInstaller_TypeNotConfigured_Template=>T("DataTypePackageFragmentInstaller.TypeNotConfigured"); ///"The data interface type '{0}' has not been configured in the system" public static string DataTypePackageFragmentInstaller_TypeNotConfigured(object parameter0)=>string.Format(T("DataTypePackageFragmentInstaller.TypeNotConfigured"), parameter0); ///"The data interface type '{0}' does not inherit the interface '{1}'" public static string DataTypePackageFragmentInstaller_TypeNotInheriting_Template=>T("DataTypePackageFragmentInstaller.TypeNotInheriting"); ///"The data interface type '{0}' does not inherit the interface '{1}'" public static string DataTypePackageFragmentInstaller_TypeNotInheriting(object parameter0,object parameter1)=>string.Format(T("DataTypePackageFragmentInstaller.TypeNotInheriting"), parameter0,parameter1); ///"The interface type '{0}' is already exists in the system" public static string DataTypePackageFragmentInstaller_TypeExists_Template=>T("DataTypePackageFragmentInstaller.TypeExists"); ///"The interface type '{0}' is already exists in the system" public static string DataTypePackageFragmentInstaller_TypeExists(object parameter0)=>string.Format(T("DataTypePackageFragmentInstaller.TypeExists"), parameter0); ///"Failed to build a data type descriptor for interface '{0}'" public static string DataTypePackageFragmentInstaller_InterfaceCodeError_Template=>T("DataTypePackageFragmentInstaller.InterfaceCodeError"); ///"Failed to build a data type descriptor for interface '{0}'" public static string DataTypePackageFragmentInstaller_InterfaceCodeError(object parameter0)=>string.Format(T("DataTypePackageFragmentInstaller.InterfaceCodeError"), parameter0); ///"Only one 'Types' element allowed" public static string DataTypePackageFragmentUninstaller_OnlyOneElement=>T("DataTypePackageFragmentUninstaller.OnlyOneElement"); ///"Missing {0} attribute in the configuration" public static string DataTypePackageFragmentUninstaller_MissingAttribute_Template=>T("DataTypePackageFragmentUninstaller.MissingAttribute"); ///"Missing {0} attribute in the configuration" public static string DataTypePackageFragmentUninstaller_MissingAttribute(object parameter0)=>string.Format(T("DataTypePackageFragmentUninstaller.MissingAttribute"), parameter0); ///"Wrong attribute format in the configuration" public static string DataTypePackageFragmentUninstaller_WrongAttributeFormat=>T("DataTypePackageFragmentUninstaller.WrongAttributeFormat"); ///"Only one 'Types' element allowed" public static string DynamicDataTypePackageFragmentInstaller_OnlyOneElement=>T("DynamicDataTypePackageFragmentInstaller.OnlyOneElement"); ///"Missing 'Types' element" public static string DynamicDataTypePackageFragmentInstaller_MissingElement=>T("DynamicDataTypePackageFragmentInstaller.MissingElement"); ///"Error xml parsing the dataTypeDescriptor attribute" public static string DynamicDataTypePackageFragmentInstaller_DataTypeDescriptorParseError=>T("DynamicDataTypePackageFragmentInstaller.DataTypeDescriptorParseError"); ///"Error while deserializing a DataType. Error text: {0}." public static string DynamicDataTypePackageFragmentInstaller_DataTypeDescriptorDeserializeError_Template=>T("DynamicDataTypePackageFragmentInstaller.DataTypeDescriptorDeserializeError"); ///"Error while deserializing a DataType. Error text: {0}." public static string DynamicDataTypePackageFragmentInstaller_DataTypeDescriptorDeserializeError(object parameter0)=>string.Format(T("DynamicDataTypePackageFragmentInstaller.DataTypeDescriptorDeserializeError"), parameter0); ///"Cannot find a referenced type '{0}'." public static string DynamicDataTypePackageFragmentInstaller_MissingReferencedType_Template=>T("DynamicDataTypePackageFragmentInstaller.MissingReferencedType"); ///"Cannot find a referenced type '{0}'." public static string DynamicDataTypePackageFragmentInstaller_MissingReferencedType(object parameter0)=>string.Format(T("DynamicDataTypePackageFragmentInstaller.MissingReferencedType"), parameter0); ///"The interface type '{0}' is already exists in the system" public static string DynamicDataTypePackageFragmentInstaller_TypeExists_Template=>T("DynamicDataTypePackageFragmentInstaller.TypeExists"); ///"The interface type '{0}' is already exists in the system" public static string DynamicDataTypePackageFragmentInstaller_TypeExists(object parameter0)=>string.Format(T("DynamicDataTypePackageFragmentInstaller.TypeExists"), parameter0); ///"Only one 'Types' element allowed" public static string DynamicDataTypePackageFragmentUninstaller_OnlyOneElement=>T("DynamicDataTypePackageFragmentUninstaller.OnlyOneElement"); ///"Missing {0} attribute in the configuration" public static string DynamicDataTypePackageFragmentUninstaller_MissingAttribute_Template=>T("DynamicDataTypePackageFragmentUninstaller.MissingAttribute"); ///"Missing {0} attribute in the configuration" public static string DynamicDataTypePackageFragmentUninstaller_MissingAttribute(object parameter0)=>string.Format(T("DynamicDataTypePackageFragmentUninstaller.MissingAttribute"), parameter0); ///"Wrong attribute format in the configuration" public static string DynamicDataTypePackageFragmentUninstaller_WrongAttributeFormat=>T("DynamicDataTypePackageFragmentUninstaller.WrongAttributeFormat"); ///"Only one 'Files' element allowed" public static string FilePackageFragmentInstaller_OnlyOneFilesElement=>T("FilePackageFragmentInstaller.OnlyOneFilesElement"); ///"Only one 'Directories' element allowed" public static string FilePackageFragmentInstaller_OnlyOneDirectoriesElement=>T("FilePackageFragmentInstaller.OnlyOneDirectoriesElement"); ///"Missing {0} attribute in the configuration" public static string FilePackageFragmentInstaller_MissingAttribute_Template=>T("FilePackageFragmentInstaller.MissingAttribute"); ///"Missing {0} attribute in the configuration" public static string FilePackageFragmentInstaller_MissingAttribute(object parameter0)=>string.Format(T("FilePackageFragmentInstaller.MissingAttribute"), parameter0); ///"The 'deleteTargetDirectory' attribute can only be applied to directories, not files" public static string FilePackageFragmentInstaller_DeleteTargetDirectoryNotAllowed=>T("FilePackageFragmentInstaller.DeleteTargetDirectoryNotAllowed"); ///"Wrong attribute value format, bool value expected" public static string FilePackageFragmentInstaller_WrongAttributeBoolFormat=>T("FilePackageFragmentInstaller.WrongAttributeBoolFormat"); ///"The install zip-file does not contain the file '{0}'" public static string FilePackageFragmentInstaller_MissingFile_Template=>T("FilePackageFragmentInstaller.MissingFile"); ///"The install zip-file does not contain the file '{0}'" public static string FilePackageFragmentInstaller_MissingFile(object parameter0)=>string.Format(T("FilePackageFragmentInstaller.MissingFile"), parameter0); ///"The file '{0}' already exists" public static string FilePackageFragmentInstaller_FileExists_Template=>T("FilePackageFragmentInstaller.FileExists"); ///"The file '{0}' already exists" public static string FilePackageFragmentInstaller_FileExists(object parameter0)=>string.Format(T("FilePackageFragmentInstaller.FileExists"), parameter0); ///"File '{0}' marked as 'Read Only' and therefore cannot be overwritten." public static string FilePackageFragmentInstaller_FileReadOnly_Template=>T("FilePackageFragmentInstaller.FileReadOnly"); ///"File '{0}' marked as 'Read Only' and therefore cannot be overwritten." public static string FilePackageFragmentInstaller_FileReadOnly(object parameter0)=>string.Format(T("FilePackageFragmentInstaller.FileReadOnly"), parameter0); ///"The 'assemblyLoad' attribute can only be applied to files, not directories" public static string FilePackageFragmentInstaller_AssemblyLoadNotAllowed=>T("FilePackageFragmentInstaller.AssemblyLoadNotAllowed"); ///"The 'onlyUpdate' attribute can only be applied to files, not directories" public static string FilePackageFragmentInstaller_OnlyUpdateNotAllowed=>T("FilePackageFragmentInstaller.OnlyUpdateNotAllowed"); ///"The 'onlyUpdate' attribute is not allowed in combination with the 'loadAssembly' attribute" public static string FilePackageFragmentInstaller_OnlyUpdateNotAllowedWithLoadAssemlby=>T("FilePackageFragmentInstaller.OnlyUpdateNotAllowedWithLoadAssemlby"); ///"The 'onlyUpdate' and 'onlyAdd' attributes are now allowed on the same element" public static string FilePackageFragmentInstaller_OnlyUpdateAndOnlyAddNotAllowed=>T("FilePackageFragmentInstaller.OnlyUpdateAndOnlyAddNotAllowed"); ///"The 'onlyAdd' and 'allowOverwrite' attributes are now allowed on the same element" public static string FilePackageFragmentInstaller_OnlyAddAndAllowOverwriteNotAllowed=>T("FilePackageFragmentInstaller.OnlyAddAndAllowOverwriteNotAllowed"); ///"The install zip-file does not contain the directory '{0}'" public static string FilePackageFragmentInstaller_MissingDirectory_Template=>T("FilePackageFragmentInstaller.MissingDirectory"); ///"The install zip-file does not contain the directory '{0}'" public static string FilePackageFragmentInstaller_MissingDirectory(object parameter0)=>string.Format(T("FilePackageFragmentInstaller.MissingDirectory"), parameter0); ///"Uninstall.xml contains file pathes, binded to the original website location, and therefore the package cannot be uninstalled safely." public static string FilePackageFragmentInstaller_WrongBasePath=>T("FilePackageFragmentInstaller.WrongBasePath"); ///"Only one 'Files' element allowed" public static string FilePackageFragmentUninstaller_OnlyOneFilesElement=>T("FilePackageFragmentUninstaller.OnlyOneFilesElement"); ///"Only one 'Areas' element allowed" public static string VirtualElementProviderNodePackageFragmentInstaller_OnlyOneElement=>T("VirtualElementProviderNodePackageFragmentInstaller.OnlyOneElement"); ///"Could not find the type '{0}'" public static string VirtualElementProviderNodePackageFragmentInstaller_MissingType_Template=>T("VirtualElementProviderNodePackageFragmentInstaller.MissingType"); ///"Could not find the type '{0}'" public static string VirtualElementProviderNodePackageFragmentInstaller_MissingType(object parameter0)=>string.Format(T("VirtualElementProviderNodePackageFragmentInstaller.MissingType"), parameter0); ///"Could not find the icon '{0}'" public static string VirtualElementProviderNodePackageFragmentInstaller_MissingIcon_Template=>T("VirtualElementProviderNodePackageFragmentInstaller.MissingIcon"); ///"Could not find the icon '{0}'" public static string VirtualElementProviderNodePackageFragmentInstaller_MissingIcon(object parameter0)=>string.Format(T("VirtualElementProviderNodePackageFragmentInstaller.MissingIcon"), parameter0); ///"Only one 'Areas' element allowed" public static string VirtualElementProviderNodePackageFragmentUninstaller_OnlyOneElement=>T("VirtualElementProviderNodePackageFragmentUninstaller.OnlyOneElement"); ///"Missing {0} attribute in the configuration" public static string VirtualElementProviderNodePackageFragmentUninstaller_MissingAttribute_Template=>T("VirtualElementProviderNodePackageFragmentUninstaller.MissingAttribute"); ///"Missing {0} attribute in the configuration" public static string VirtualElementProviderNodePackageFragmentUninstaller_MissingAttribute(object parameter0)=>string.Format(T("VirtualElementProviderNodePackageFragmentUninstaller.MissingAttribute"), parameter0); ///"File '{0}' not found" public static string FileXslTransformationPackageFragmentInstaller_FileNotFound_Template=>T("FileXslTransformationPackageFragmentInstaller.FileNotFound"); ///"File '{0}' not found" public static string FileXslTransformationPackageFragmentInstaller_FileNotFound(object parameter0)=>string.Format(T("FileXslTransformationPackageFragmentInstaller.FileNotFound"), parameter0); ///"File '{0}' marked as 'Read Only' and therefore cannot be overwritten." public static string FileXslTransformationPackageFragmentInstaller_FileReadOnly_Template=>T("FileXslTransformationPackageFragmentInstaller.FileReadOnly"); ///"File '{0}' marked as 'Read Only' and therefore cannot be overwritten." public static string FileXslTransformationPackageFragmentInstaller_FileReadOnly(object parameter0)=>string.Format(T("FileXslTransformationPackageFragmentInstaller.FileReadOnly"), parameter0); ///"File '{0}' was marked as 'Read Only'. This file attribute was explicitly removed and the file was updated normally." public static string FileXslTransformationPackageFragmentInstaller_FileReadOnlyOverride_Template=>T("FileXslTransformationPackageFragmentInstaller.FileReadOnlyOverride"); ///"File '{0}' was marked as 'Read Only'. This file attribute was explicitly removed and the file was updated normally." public static string FileXslTransformationPackageFragmentInstaller_FileReadOnlyOverride(object parameter0)=>string.Format(T("FileXslTransformationPackageFragmentInstaller.FileReadOnlyOverride"), parameter0); ///"Only one 'PackageVersions' element allowed" public static string PackageVersionBumperFragmentInstaller_OnlyOneElement=>T("PackageVersionBumperFragmentInstaller.OnlyOneElement"); ///"Missing {0} attribute in the configuration" public static string PackageVersionBumperFragmentInstaller_MissingAttribute_Template=>T("PackageVersionBumperFragmentInstaller.MissingAttribute"); ///"Missing {0} attribute in the configuration" public static string PackageVersionBumperFragmentInstaller_MissingAttribute(object parameter0)=>string.Format(T("PackageVersionBumperFragmentInstaller.MissingAttribute"), parameter0); ///"Wrong attribute value format, Guid value expected" public static string PackageVersionBumperFragmentInstaller_WrongAttributeGuidFormat=>T("PackageVersionBumperFragmentInstaller.WrongAttributeGuidFormat"); ///"The package id duplicate: '{0}'" public static string PackageVersionBumperFragmentInstaller_PackageIdDuplicate_Template=>T("PackageVersionBumperFragmentInstaller.PackageIdDuplicate"); ///"The package id duplicate: '{0}'" public static string PackageVersionBumperFragmentInstaller_PackageIdDuplicate(object parameter0)=>string.Format(T("PackageVersionBumperFragmentInstaller.PackageIdDuplicate"), parameter0); ///"Wrong attribute value format, Version value expected (x.y.z)" public static string PackageVersionBumperFragmentInstaller_WrongAttributeVersionFormat=>T("PackageVersionBumperFragmentInstaller.WrongAttributeVersionFormat"); ///"Only one 'PackageVersions' element allowed" public static string PackageVersionBumperFragmentUninstaller_OnlyOneElement=>T("PackageVersionBumperFragmentUninstaller.OnlyOneElement"); ///"Missing {0} attribute in the configuration" public static string PackageVersionBumperFragmentUninstaller_MissingAttribute_Template=>T("PackageVersionBumperFragmentUninstaller.MissingAttribute"); ///"Missing {0} attribute in the configuration" public static string PackageVersionBumperFragmentUninstaller_MissingAttribute(object parameter0)=>string.Format(T("PackageVersionBumperFragmentUninstaller.MissingAttribute"), parameter0); ///"Wrong attribute value format, Guid value expected" public static string PackageVersionBumperFragmentUninstaller_WrongAttributeGuidFormat=>T("PackageVersionBumperFragmentUninstaller.WrongAttributeGuidFormat"); ///"The package id duplicate: '{0}'" public static string PackageVersionBumperFragmentUninstaller_PackageIdDuplicate_Template=>T("PackageVersionBumperFragmentUninstaller.PackageIdDuplicate"); ///"The package id duplicate: '{0}'" public static string PackageVersionBumperFragmentUninstaller_PackageIdDuplicate(object parameter0)=>string.Format(T("PackageVersionBumperFragmentUninstaller.PackageIdDuplicate"), parameter0); ///"Wrong attribute value format, Version value expected (x.y.z)" public static string PackageVersionBumperFragmentUninstaller_WrongAttributeVersionFormat=>T("PackageVersionBumperFragmentUninstaller.WrongAttributeVersionFormat"); ///"A public RSA key is missing in the package configuration" public static string PackageLicenseFragmentInstaller_MissingPublicKeyElement=>T("PackageLicenseFragmentInstaller.MissingPublicKeyElement"); ///"File '{0}' does not exist." public static string FileModifyPackageFragmentInstaller_FileDoesNotExist_Template=>T("FileModifyPackageFragmentInstaller.FileDoesNotExist"); ///"File '{0}' does not exist." public static string FileModifyPackageFragmentInstaller_FileDoesNotExist(object parameter0)=>string.Format(T("FileModifyPackageFragmentInstaller.FileDoesNotExist"), parameter0); ///"Invalid license key" public static string License_InvalidKeyTitle=>T("License.InvalidKeyTitle"); ///"The license key is invalid. You need to obtain a valid license key." public static string License_InvalidKeyMessage=>T("License.InvalidKeyMessage"); ///"Trial period has expired" public static string License_ExpiredTitle=>T("License.ExpiredTitle"); ///"The trial period of the package has expired. You need to obtain a valid license." public static string License_ExpiredMessage=>T("License.ExpiredMessage"); ///"Failed to get license information. ProductId: {0}" public static string License_Failed_Template=>T("License.Failed"); ///"Failed to get license information. ProductId: {0}" public static string License_Failed(object parameter0)=>string.Format(T("License.Failed"), parameter0); ///"The Windows user under which this C1 instance is running does not have write permission to file or folder '{0}'." public static string NotEnoughNtfsPermissions_Template=>T("NotEnoughNtfsPermissions"); ///"The Windows user under which this C1 instance is running does not have write permission to file or folder '{0}'." public static string NotEnoughNtfsPermissions(object parameter0)=>string.Format(T("NotEnoughNtfsPermissions"), parameter0); ///"Only one '{0}' element allowed" public static string PackageFragmentInstaller_OnlyOneElementAllowed_Template=>T("PackageFragmentInstaller.OnlyOneElementAllowed"); ///"Only one '{0}' element allowed" public static string PackageFragmentInstaller_OnlyOneElementAllowed(object parameter0)=>string.Format(T("PackageFragmentInstaller.OnlyOneElementAllowed"), parameter0); ///"Unexpected element name '{0}', only allowed element name is '{1}'" public static string PackageFragmentInstaller_IncorrectElement_Template=>T("PackageFragmentInstaller.IncorrectElement"); ///"Unexpected element name '{0}', only allowed element name is '{1}'" public static string PackageFragmentInstaller_IncorrectElement(object parameter0,object parameter1)=>string.Format(T("PackageFragmentInstaller.IncorrectElement"), parameter0,parameter1); ///"Missing '{0}' attribute." public static string PackageFragmentInstaller_MissingAttribute_Template=>T("PackageFragmentInstaller.MissingAttribute"); ///"Missing '{0}' attribute." public static string PackageFragmentInstaller_MissingAttribute(object parameter0)=>string.Format(T("PackageFragmentInstaller.MissingAttribute"), parameter0); ///"Missing element '{0}'." public static string PackageFragmentInstaller_MissingElement_Template=>T("PackageFragmentInstaller.MissingElement"); ///"Missing element '{0}'." public static string PackageFragmentInstaller_MissingElement(object parameter0)=>string.Format(T("PackageFragmentInstaller.MissingElement"), parameter0); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Core.PackageSystem.PackageFragmentInstallers", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Cultures { ///"Afrikaans, South Africa" public static string af_ZA=>T("af-ZA"); ///"Albanian, Albania" public static string sq_AL=>T("sq-AL"); ///"Arabic, Algeria" public static string ar_DZ=>T("ar-DZ"); ///"Arabic, Bahrain" public static string ar_BH=>T("ar-BH"); ///"Arabic, Egypt" public static string ar_EG=>T("ar-EG"); ///"Arabic, Iraq" public static string ar_IQ=>T("ar-IQ"); ///"Arabic, Jordan" public static string ar_JO=>T("ar-JO"); ///"Arabic, Kuwait" public static string ar_KW=>T("ar-KW"); ///"Arabic, Lebanon" public static string ar_LB=>T("ar-LB"); ///"Arabic, Libya" public static string ar_LY=>T("ar-LY"); ///"Arabic, Morocco" public static string ar_MA=>T("ar-MA"); ///"Arabic, Oman" public static string ar_OM=>T("ar-OM"); ///"Arabic, Qatar" public static string ar_QA=>T("ar-QA"); ///"Arabic, Saudi Arabia" public static string ar_SA=>T("ar-SA"); ///"Arabic, Syria" public static string ar_SY=>T("ar-SY"); ///"Arabic, Tunisia" public static string ar_TN=>T("ar-TN"); ///"Arabic, U.A.E." public static string ar_AE=>T("ar-AE"); ///"Arabic, Yemen" public static string ar_YE=>T("ar-YE"); ///"Armenian, Armenia" public static string hy_AM=>T("hy-AM"); ///"Azeri, Cyrillic Azerbaijan" public static string az_Cyrl_AZ=>T("az-Cyrl-AZ"); ///"Azeri, Latin Azerbaijan" public static string az_Latn_AZ=>T("az-Latn-AZ"); ///"Basque, Basque" public static string eu_ES=>T("eu-ES"); ///"Belarusian, Belarus" public static string be_BY=>T("be-BY"); ///"Bosnian, Bosnia and Herzegovina" public static string bs_Latn_BA=>T("bs-Latn-BA"); ///"Bosnian (Cyrillic) (Bosnia and Herzegovina)" public static string bs_Cyrl_BA=>T("bs-Cyrl-BA"); ///"Bulgarian, Bulgaria" public static string bg_BG=>T("bg-BG"); ///"Catalan, Catalan" public static string ca_ES=>T("ca-ES"); ///"Chinese, Hong Kong S.A.R." public static string zh_HK=>T("zh-HK"); ///"Chinese, Macao S.A.R." public static string zh_MO=>T("zh-MO"); ///"Chinese, People's Republic of China" public static string zh_CN=>T("zh-CN"); ///"Chinese, Singapore" public static string zh_SG=>T("zh-SG"); ///"Chinese, Taiwan" public static string zh_TW=>T("zh-TW"); ///"Croatian, Bosnia and Herzegovina" public static string hr_BA=>T("hr-BA"); ///"Croatian, Croatia" public static string hr_HR=>T("hr-HR"); ///"Czech, Czech Republic" public static string cs_CZ=>T("cs-CZ"); ///"Danish" public static string da_DK=>T("da-DK"); ///"Divehi, Maldives" public static string dv_MV=>T("dv-MV"); ///"Dutch, Belgium" public static string nl_BE=>T("nl-BE"); ///"Dutch" public static string nl_NL=>T("nl-NL"); ///"English, Australia" public static string en_AU=>T("en-AU"); ///"English, Belize" public static string en_BZ=>T("en-BZ"); ///"English, Canada" public static string en_CA=>T("en-CA"); ///"English, Caribbean" public static string en_029=>T("en-029"); ///"English, Ireland" public static string en_IE=>T("en-IE"); ///"English, Jamaica" public static string en_JM=>T("en-JM"); ///"English, New Zealand" public static string en_NZ=>T("en-NZ"); ///"English, Republic of the Philippines" public static string en_PH=>T("en-PH"); ///"English, South Africa" public static string en_ZA=>T("en-ZA"); ///"English, Trinidad and Tobago" public static string en_TT=>T("en-TT"); ///"English, UK" public static string en_GB=>T("en-GB"); ///"English, US" public static string en_US=>T("en-US"); ///"English, Zimbabwe" public static string en_ZW=>T("en-ZW"); ///"Estonian, Estonia" public static string et_EE=>T("et-EE"); ///"Faroese, Faroe Islands" public static string fo_FO=>T("fo-FO"); ///"Filipino, Philippines" public static string fil_PH=>T("fil-PH"); ///"Finnish" public static string fi_FI=>T("fi-FI"); ///"French, Belgium" public static string fr_BE=>T("fr-BE"); ///"French, Canada" public static string fr_CA=>T("fr-CA"); ///"French" public static string fr_FR=>T("fr-FR"); ///"French, Luxembourg" public static string fr_LU=>T("fr-LU"); ///"French, Principality of Monaco" public static string fr_MC=>T("fr-MC"); ///"French, Switzerland" public static string fr_CH=>T("fr-CH"); ///"Frisian, Netherlands" public static string fy_NL=>T("fy-NL"); ///"Gaelic, United Kingdom" public static string gd_GB=>T("gd-GB"); ///"Galician, Galician" public static string gl_ES=>T("gl-ES"); ///"Georgian, Georgia" public static string ka_GE=>T("ka-GE"); ///"German, Austria" public static string de_AT=>T("de-AT"); ///"German" public static string de_DE=>T("de-DE"); ///"German, Liechtenstein" public static string de_LI=>T("de-LI"); ///"German, Luxembourg" public static string de_LU=>T("de-LU"); ///"German, Switzerland" public static string de_CH=>T("de-CH"); ///"Greek, Greece" public static string el_GR=>T("el-GR"); ///"Greenlandic" public static string kl_GL=>T("kl-GL"); ///"Gujarati, India" public static string gu_IN=>T("gu-IN"); ///"Hebrew, Israel" public static string he_IL=>T("he-IL"); ///"Hindi, India" public static string hi_IN=>T("hi-IN"); ///"Hungarian, Hungary" public static string hu_HU=>T("hu-HU"); ///"Icelandic, Iceland" public static string is_IS=>T("is-IS"); ///"Indonesian, Indonesia" public static string id_ID=>T("id-ID"); ///"Inuktitut (Latin) (Canada)" public static string iu_Latn_CA=>T("iu-Latn-CA"); ///"Irish, Ireland" public static string ga_IE=>T("ga-IE"); ///"Italian" public static string it_IT=>T("it-IT"); ///"Italian, Switzerland" public static string it_CH=>T("it-CH"); ///"Japanese, Japan" public static string ja_JP=>T("ja-JP"); ///"Kannada, India" public static string kn_IN=>T("kn-IN"); ///"Kazakh, Kazakhstan" public static string kk_KZ=>T("kk-KZ"); ///"Kiswahili, Kenya" public static string sw_KE=>T("sw-KE"); ///"Konkani, India" public static string kok_IN=>T("kok-IN"); ///"Korean, Korea" public static string ko_KR=>T("ko-KR"); ///"Kyrgyz, Kyrgyzstan" public static string ky_KG=>T("ky-KG"); ///"Latvian, Latvia" public static string lv_LV=>T("lv-LV"); ///"Lithuanian, Lithuania" public static string lt_LT=>T("lt-LT"); ///"Luxembourgish, Luxembourg" public static string lb_LU=>T("lb-LU"); ///"Macedonian, Former Yugoslav Republic of Macedonia" public static string mk_MK=>T("mk-MK"); ///"Malay, Brunei Darussalam" public static string ms_BN=>T("ms-BN"); ///"Malay, Malaysia" public static string ms_MY=>T("ms-MY"); ///"Maltese, Malta" public static string mt_MT=>T("mt-MT"); ///"Maori, New Zealand" public static string mi_NZ=>T("mi-NZ"); ///"Mapudungun, Chile" public static string arn_CL=>T("arn-CL"); ///"Marathi, India" public static string mr_IN=>T("mr-IN"); ///"Mohawk, Canada" public static string moh_CA=>T("moh-CA"); ///"Mongolian, Cyrillic Mongolia" public static string mn_MN=>T("mn-MN"); ///"Norwegian Bokmål" public static string nb_NO=>T("nb-NO"); ///"Norwegian Nynorsk, Norway" public static string nn_NO=>T("nn-NO"); ///"Persian, Iran" public static string fa_IR=>T("fa-IR"); ///"Polish, Poland" public static string pl_PL=>T("pl-PL"); ///"Portuguese, Brazil" public static string pt_BR=>T("pt-BR"); ///"Portuguese, Portugal" public static string pt_PT=>T("pt-PT"); ///"Punjabi, India" public static string pa_IN=>T("pa-IN"); ///"Quechua, Bolivia" public static string quz_BO=>T("quz-BO"); ///"Quechua, Ecuador" public static string quz_EC=>T("quz-EC"); ///"Quechua, Peru" public static string quz_PE=>T("quz-PE"); ///"Romanian, Romania" public static string ro_RO=>T("ro-RO"); ///"Romansh, Switzerland" public static string rm_CH=>T("rm-CH"); ///"Russian, Russia" public static string ru_RU=>T("ru-RU"); ///"Sami (Inari) (Finland)" public static string smn_FI=>T("smn-FI"); ///"Sami (Lule) (Norway)" public static string smj_NO=>T("smj-NO"); ///"Sami (Lule) (Sweden)" public static string smj_SE=>T("smj-SE"); ///"Sami (Northern) (Finland)" public static string se_FI=>T("se-FI"); ///"Sami (Northern) (Norway)" public static string se_NO=>T("se-NO"); ///"Sami" public static string se_SE=>T("se-SE"); ///"Sami (Skolt) (Finland)" public static string sms_FI=>T("sms-FI"); ///"Sami (Southern) (Norway)" public static string sma_NO=>T("sma-NO"); ///"Sami (Southern) (Sweden)" public static string sma_SE=>T("sma-SE"); ///"Sanskrit, India" public static string sa_IN=>T("sa-IN"); ///"Serbian, Cyrillic (Bosnia and Herzegovina)" public static string sr_Cyrl_BA=>T("sr-Cyrl-BA"); ///"Serbian, Cyrillic (Montenegro)" public static string sr_Cyrl_ME=>T("sr-Cyrl-ME"); ///"Serbian, Cyrillic (Serbia and Montenegro - former)" public static string sr_Cyrl_CS=>T("sr-Cyrl-CS"); ///"Serbian, Cyrillic (Serbia)" public static string sr_Cyrl_RS=>T("sr-Cyrl-RS"); ///"Serbian, Latin (Bosnia and Herzegovina)" public static string sr_Latn_BA=>T("sr-Latn-BA"); ///"Serbian, Latin (Montenegro)" public static string sr_Latn_ME=>T("sr-Latn-ME"); ///"Serbian, Latin (Serbia and Montenegro - former)" public static string sr_Latn_CS=>T("sr-Latn-CS"); ///"Serbian, Latin (Serbia)" public static string sr_Latn_RS=>T("sr-Latn-RS"); ///"Sesotho sa Leboa, South Africa" public static string ns_ZA=>T("ns-ZA"); ///"Setswana, South Africa" public static string tn_ZA=>T("tn-ZA"); ///"Slovak, Slovakia" public static string sk_SK=>T("sk-SK"); ///"Slovenian, Slovenia" public static string sl_SI=>T("sl-SI"); ///"Spanish, Argentina" public static string es_AR=>T("es-AR"); ///"Spanish, Bolivia" public static string es_BO=>T("es-BO"); ///"Spanish, Chile" public static string es_CL=>T("es-CL"); ///"Spanish, Colombia" public static string es_CO=>T("es-CO"); ///"Spanish, Costa Rica" public static string es_CR=>T("es-CR"); ///"Spanish, Dominican Republic" public static string es_DO=>T("es-DO"); ///"Spanish, Ecuador" public static string es_EC=>T("es-EC"); ///"Spanish, El Salvador" public static string es_SV=>T("es-SV"); ///"Spanish, Guatemala" public static string es_GT=>T("es-GT"); ///"Spanish, Honduras" public static string es_HN=>T("es-HN"); ///"Spanish, Mexico" public static string es_MX=>T("es-MX"); ///"Spanish, Nicaragua" public static string es_NI=>T("es-NI"); ///"Spanish, Panama" public static string es_PA=>T("es-PA"); ///"Spanish, Paraguay" public static string es_PY=>T("es-PY"); ///"Spanish, Peru" public static string es_PE=>T("es-PE"); ///"Spanish, Puerto Rico" public static string es_PR=>T("es-PR"); ///"Spanish" public static string es_ES=>T("es-ES"); ///"Spanish, Uruguay" public static string es_UY=>T("es-UY"); ///"Spanish, Venezuela" public static string es_VE=>T("es-VE"); ///"Swedish, Finland" public static string sv_FI=>T("sv-FI"); ///"Swedish" public static string sv_SE=>T("sv-SE"); ///"Syriac, Syria" public static string syr_SY=>T("syr-SY"); ///"Tamil, India" public static string ta_IN=>T("ta-IN"); ///"Tatar, Russia" public static string tt_RU=>T("tt-RU"); ///"Telugu, India" public static string te_IN=>T("te-IN"); ///"Thai, Thailand" public static string th_TH=>T("th-TH"); ///"Turkish, Turkey" public static string tr_TR=>T("tr-TR"); ///"Ukrainian, Ukraine" public static string uk_UA=>T("uk-UA"); ///"Urdu, Islamic Republic of Pakistan" public static string ur_PK=>T("ur-PK"); ///"Uzbek, Cyrillic Uzbekistan" public static string uz_Cyrl_UZ=>T("uz-Cyrl-UZ"); ///"Uzbek, Latin Uzbekistan" public static string uz_Latn_UZ=>T("uz-Latn-UZ"); ///"Vietnamese, Vietnam" public static string vi_VN=>T("vi-VN"); ///"Welsh, United Kingdom" public static string cy_GB=>T("cy-GB"); ///"Xhosa, South Africa" public static string xh_ZA=>T("xh-ZA"); ///"Zulu, South Africa" public static string zu_ZA=>T("zu-ZA"); ///"Alsatian, France" public static string gsw_FR=>T("gsw-FR"); ///"Amharic, Ethiopia" public static string am_ET=>T("am-ET"); ///"Assamese, India" public static string as_IN=>T("as-IN"); ///"Bashkir, Russia" public static string ba_RU=>T("ba-RU"); ///"Bengali, Bangladesh" public static string bn_BD=>T("bn-BD"); ///"Bengali, India" public static string bn_IN=>T("bn-IN"); ///"Breton, France" public static string br_FR=>T("br-FR"); ///"Corsican, France" public static string co_FR=>T("co-FR"); ///"Dari, Afghanistan" public static string prs_AF=>T("prs-AF"); ///"English, India" public static string en_IN=>T("en-IN"); ///"English, Malaysia" public static string en_MY=>T("en-MY"); ///"English, Singapore" public static string en_SG=>T("en-SG"); ///"Hausa (Latin) (Nigeria)" public static string ha_Latn_NG=>T("ha-Latn-NG"); ///"Igbo, Nigeria" public static string ig_NG=>T("ig-NG"); ///"Inuktitut, Canada" public static string iu_Cans_CA=>T("iu-Cans-CA"); ///"Khmer, Cambodia" public static string km_KH=>T("km-KH"); ///"K'iche, Guatemala" public static string qut_GT=>T("qut-GT"); ///"Kinyarwanda, Rwanda" public static string rw_RW=>T("rw-RW"); ///"Lao, Lao P.D.R." public static string lo_LA=>T("lo-LA"); ///"Lower Sorbian, Germany" public static string dsb_DE=>T("dsb-DE"); ///"Malayalam, India" public static string ml_IN=>T("ml-IN"); ///"Mongolian (Traditional Mongolian) (People's Republic of China)" public static string mn_Mong_CN=>T("mn-Mong-CN"); ///"Nepali, Nepal" public static string ne_NP=>T("ne-NP"); ///"Occitan, France" public static string oc_FR=>T("oc-FR"); ///"Oriya, India" public static string or_IN=>T("or-IN"); ///"Pashto, Afghanistan" public static string ps_AF=>T("ps-AF"); ///"Sesotho sa Leboa, South Africa" public static string nso_ZA=>T("nso-ZA"); ///"Sinhala, Sri Lanka" public static string si_LK=>T("si-LK"); ///"Spanish, United States" public static string es_US=>T("es-US"); ///"Tajik (Cyrillic) (Tajikistan)" public static string tg_Cyrl_TJ=>T("tg-Cyrl-TJ"); ///"Tamazight (Latin) (Algeria)" public static string tzm_Latn_DZ=>T("tzm-Latn-DZ"); ///"Tibetan, People's Republic of China" public static string bo_CN=>T("bo-CN"); ///"Turkmen, Turkmenistan" public static string tk_TM=>T("tk-TM"); ///"Uighur, People's Republic of China" public static string ug_CN=>T("ug-CN"); ///"Upper Sorbian, Germany" public static string hsb_DE=>T("hsb-DE"); ///"Wolof, Senegal" public static string wo_SN=>T("wo-SN"); ///"Yakut, Russia" public static string sah_RU=>T("sah-RU"); ///"Yi, People's Republic of China" public static string ii_CN=>T("ii-CN"); ///"Yoruba, Nigeria" public static string yo_NG=>T("yo-NG"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Cultures", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_EntityTokenLocked { ///"This item is currently being edited" public static string LayoutLabel=>T("LayoutLabel"); ///"Information" public static string LockedByUsername_FieldGroupLabel=>T("LockedByUsername.FieldGroupLabel"); ///"The item is edited by:" public static string LockedByUsername_Label=>T("LockedByUsername.Label"); ///"Another user is editing this item. Press OK to proceed or cancel to abort." public static string LockedByUsername_Help=>T("LockedByUsername.Help"); ///"You are editing this item in another tab - continue?" public static string SameUserHeading_Title=>T("SameUserHeading.Title"); ///"Press OK to proceed opening the item or Cancel to abort." public static string SameUserHeading_Description=>T("SameUserHeading.Description"); ///"Another user is editing this item - continue?" public static string AnotherUserHeading_Title=>T("AnotherUserHeading.Title"); ///"If the item is changed simultaneously by multiple users changes may get lost. Press OK to proceed or cancel to abort." public static string AnotherUserHeading_Description=>T("AnotherUserHeading.Description"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.EntityTokenLocked", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_GeneratedTypes { ///"One or more types are referencing this type. Renaming is not possible" public static string TypesAreReferencing=>T("TypesAreReferencing"); ///"The type name '{0}' appears in the namespace '{1}' - this is not allowed" public static string TypeNameInNamespace_Template=>T("TypeNameInNamespace"); ///"The type name '{0}' appears in the namespace '{1}' - this is not allowed" public static string TypeNameInNamespace(object parameter0,object parameter1)=>string.Format(T("TypeNameInNamespace"), parameter0,parameter1); ///"A type with the same name already exists" public static string TypesNameClash=>T("TypesNameClash"); ///"No fields added" public static string MissingFields=>T("MissingFields"); ///"The type name '{0}' is not a valid identifier." public static string TypeNameIsInvalidIdentifier_Template=>T("TypeNameIsInvalidIdentifier"); ///"The type name '{0}' is not a valid identifier." public static string TypeNameIsInvalidIdentifier(object parameter0)=>string.Format(T("TypeNameIsInvalidIdentifier"), parameter0); ///"The field name '{0}' can not be used" public static string FieldNameCannotBeUsed_Template=>T("FieldNameCannotBeUsed"); ///"The field name '{0}' can not be used" public static string FieldNameCannotBeUsed(object parameter0)=>string.Format(T("FieldNameCannotBeUsed"), parameter0); ///"The specified 'Type namespace' is already in use as a 'Type name' (namespace + name). Consider changing the name of '{0}' to '{0}.Item'." public static string NameSpaceIsTypeTypeName_Template=>T("NameSpaceIsTypeTypeName"); ///"The specified 'Type namespace' is already in use as a 'Type name' (namespace + name). Consider changing the name of '{0}' to '{0}.Item'." public static string NameSpaceIsTypeTypeName(object parameter0)=>string.Format(T("NameSpaceIsTypeTypeName"), parameter0); ///"Type name belongs to a reserved namespace." public static string NamespaceIsReserved=>T("NamespaceIsReserved"); ///"Cannot add a data type since it will cause some compilation errors." public static string CompileErrorWhileAddingType=>T("CompileErrorWhileAddingType"); ///"Cannot change a data type since it will cause some compilation errors." public static string CompileErrorWhileChangingType=>T("CompileErrorWhileChangingType"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.GeneratedTypes", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Management { ///"Edit Permissions" public static string ManageUserPermissions_ManageUserPermissionsOnBranchLabel=>T("ManageUserPermissions.ManageUserPermissionsOnBranchLabel"); ///"Edit Permissions" public static string ManageUserPermissions_ManageUserPermissionsOnItemLabel=>T("ManageUserPermissions.ManageUserPermissionsOnItemLabel"); ///"User Permission Settings" public static string ManageUserPermissions_ManageGlobalUserPermissionsLabel=>T("ManageUserPermissions.ManageGlobalUserPermissionsLabel"); ///"Manage user permissions" public static string ManageUserPermissions_ManageUserPermissionsToolTip=>T("ManageUserPermissions.ManageUserPermissionsToolTip"); ///"Metadata" public static string DataCompositionVisabilityFacade_DefaultContainerLabel=>T("DataCompositionVisabilityFacade.DefaultContainerLabel"); ///"Delete User?" public static string Website_Forms_Administrative_DeleteUserStep1_LabelFieldGroup=>T("Website.Forms.Administrative.DeleteUserStep1.LabelFieldGroup"); ///"Delete the selected user?" public static string Website_Forms_Administrative_DeleteUserStep1_Text=>T("Website.Forms.Administrative.DeleteUserStep1.Text"); ///"Cascade delete error" public static string DeleteUserWorkflow_CascadeDeleteErrorTitle=>T("DeleteUserWorkflow.CascadeDeleteErrorTitle"); ///"The type is referenced by another type that does not allow cascade deletes. This operation is halted" public static string DeleteUserWorkflow_CascadeDeleteErrorMessage=>T("DeleteUserWorkflow.CascadeDeleteErrorMessage"); ///"Cannot delete a user" public static string DeleteUserWorkflow_DeleteSelfTitle=>T("DeleteUserWorkflow.DeleteSelfTitle"); ///"You can not delete an account you logged in as." public static string DeleteUserWorkflow_DeleteSelfErrorMessage=>T("DeleteUserWorkflow.DeleteSelfErrorMessage"); ///"Select Function" public static string Website_Function_SelectDialog_Title=>T("Website.Function.SelectDialog.Title"); ///"Select Widget" public static string Website_Widget_SelectDialog_Title=>T("Website.Widget.SelectDialog.Title"); ///"Select Page or File" public static string Website_ContentLink_SelectDialog_Title=>T("Website.ContentLink.SelectDialog.Title"); ///"Select Page" public static string Website_Page_SelectDialog_Title=>T("Website.Page.SelectDialog.Title"); ///"Select Frontend File" public static string Website_FrontendFile_SelectDialog_Title=>T("Website.FrontendFile.SelectDialog.Title"); ///"Select Media" public static string Website_Media_SelectDialog_Title=>T("Website.Media.SelectDialog.Title"); ///"Select Image" public static string Website_Image_SelectDialog_Title=>T("Website.Image.SelectDialog.Title"); ///"Select Folder" public static string Website_Folder_SelectDialog_Title=>T("Website.Folder.SelectDialog.Title"); ///"Draft" public static string PublishingStatus_draft=>T("PublishingStatus.draft"); ///"Awaiting Approval" public static string PublishingStatus_awaitingApproval=>T("PublishingStatus.awaitingApproval"); ///"Awaiting Publication" public static string PublishingStatus_awaitingPublication=>T("PublishingStatus.awaitingPublication"); ///"Published" public static string PublishingStatus_published=>T("PublishingStatus.published"); ///"General settings" public static string Website_Forms_Administrative_EditUserStep1_LabelFieldGroup=>T("Website.Forms.Administrative.EditUserStep1.LabelFieldGroup"); ///"User name" public static string Website_Forms_Administrative_EditUserStep1_UserNameLabel=>T("Website.Forms.Administrative.EditUserStep1.UserNameLabel"); ///"User names can not be changed. This is a 'read only' field." public static string Website_Forms_Administrative_EditUserStep1_UserNameHelp=>T("Website.Forms.Administrative.EditUserStep1.UserNameHelp"); ///"Password" public static string Website_Forms_Administrative_EditUserStep1_PasswordLabel=>T("Website.Forms.Administrative.EditUserStep1.PasswordLabel"); ///"The password has to be more than 6 characters long." public static string Website_Forms_Administrative_EditUserStep1_PasswordHelp=>T("Website.Forms.Administrative.EditUserStep1.PasswordHelp"); ///"Name" public static string Website_Forms_Administrative_EditUserStep1_NameLabel=>T("Website.Forms.Administrative.EditUserStep1.NameLabel"); ///"The full name of the person using this account." public static string Website_Forms_Administrative_EditUserStep1_NameHelp=>T("Website.Forms.Administrative.EditUserStep1.NameHelp"); ///"Email" public static string Website_Forms_Administrative_EditUserStep1_EmailLabel=>T("Website.Forms.Administrative.EditUserStep1.EmailLabel"); ///"The e-mail address of the user (optional)." public static string Website_Forms_Administrative_EditUserStep1_EmailHelp=>T("Website.Forms.Administrative.EditUserStep1.EmailHelp"); ///"Folder" public static string Website_Forms_Administrative_EditUserStep1_GroupLabel=>T("Website.Forms.Administrative.EditUserStep1.GroupLabel"); ///"If you enter a folder name that does not already exist a new folder will be created." public static string Website_Forms_Administrative_EditUserStep1_GroupHelp=>T("Website.Forms.Administrative.EditUserStep1.GroupHelp"); ///"C1 Console Localization" public static string Website_Forms_Administrative_EditUserStep1_LabelLocalizationFieldGroup=>T("Website.Forms.Administrative.EditUserStep1.LabelLocalizationFieldGroup"); ///"Display Preferences" public static string Website_Forms_Administrative_EditUserStep1_CultureLabel=>T("Website.Forms.Administrative.EditUserStep1.CultureLabel"); ///"Display for time, date, and number formats within the console" public static string Website_Forms_Administrative_EditUserStep1_CultureHelp=>T("Website.Forms.Administrative.EditUserStep1.CultureHelp"); ///"Console Language Preferences" public static string Website_Forms_Administrative_EditUserStep1_C1ConsoleLanguageLabel=>T("Website.Forms.Administrative.EditUserStep1.C1ConsoleLanguageLabel"); ///"Language displayed within your console for labels, help texts, dialogs, etc. The available options are limited to language packages installed. See Composite.Localization packages for more language options." public static string Website_Forms_Administrative_EditUserStep1_C1ConsoleLanguageHelp=>T("Website.Forms.Administrative.EditUserStep1.C1ConsoleLanguageHelp"); ///"Perspectives" public static string Website_Forms_Administrative_EditUserStep1_ActivePerspectiveFieldLabel=>T("Website.Forms.Administrative.EditUserStep1.ActivePerspectiveFieldLabel"); ///"Visible perspectives" public static string Website_Forms_Administrative_EditUserStep1_ActivePerspectiveMultiSelectLabel=>T("Website.Forms.Administrative.EditUserStep1.ActivePerspectiveMultiSelectLabel"); ///"Select which perspectives should be visible when the user starts the C1 Console." public static string Website_Forms_Administrative_EditUserStep1_ActivePerspectiveMultiSelectHelp=>T("Website.Forms.Administrative.EditUserStep1.ActivePerspectiveMultiSelectHelp"); ///"Global permissions" public static string Website_Forms_Administrative_EditUserStep1_GlobalPermissionsFieldLabel=>T("Website.Forms.Administrative.EditUserStep1.GlobalPermissionsFieldLabel"); ///"Global permissions" public static string Website_Forms_Administrative_EditUserStep1_GlobalPermissionsMultiSelectLabel=>T("Website.Forms.Administrative.EditUserStep1.GlobalPermissionsMultiSelectLabel"); ///"The Administrate permission grants the user access to manage user permissions and execute other administrative tasks. The Configure permission grants access to super user tasks." public static string Website_Forms_Administrative_EditUserStep1_GlobalPermissionsMultiSelectHelp=>T("Website.Forms.Administrative.EditUserStep1.GlobalPermissionsMultiSelectHelp"); ///"The removal of your own administrative permission has been ignored. You still have administrative privileges." public static string Website_Forms_Administrative_EditUserStep1_GlobalPermissions_IgnoredOwnAdministrativeRemoval=>T("Website.Forms.Administrative.EditUserStep1.GlobalPermissions.IgnoredOwnAdministrativeRemoval"); ///"Data language access" public static string Website_Forms_Administrative_EditUserStep1_ActiveLocalesFieldLabel=>T("Website.Forms.Administrative.EditUserStep1.ActiveLocalesFieldLabel"); ///"Data Languages" public static string Website_Forms_Administrative_EditUserStep1_ActiveLocalesMultiSelectLabel=>T("Website.Forms.Administrative.EditUserStep1.ActiveLocalesMultiSelectLabel"); ///"User has access to manage data in the selected languages." public static string Website_Forms_Administrative_EditUserStep1_ActiveLocalesMultiSelectHelp=>T("Website.Forms.Administrative.EditUserStep1.ActiveLocalesMultiSelectHelp"); ///"Active content language" public static string Website_Forms_Administrative_EditUserStep1_ActiveLocaleLabel=>T("Website.Forms.Administrative.EditUserStep1.ActiveLocaleLabel"); ///"The content language this user will edit." public static string Website_Forms_Administrative_EditUserStep1_ActiveLocaleHelp=>T("Website.Forms.Administrative.EditUserStep1.ActiveLocaleHelp"); ///"The selected language is not checked in the data language section." public static string Website_Forms_Administrative_EditUserStep1_ActiveLocaleNotChecked=>T("Website.Forms.Administrative.EditUserStep1.ActiveLocaleNotChecked"); ///"You must select at least one active language." public static string Website_Forms_Administrative_EditUserStep1_NoActiveLocaleSelected=>T("Website.Forms.Administrative.EditUserStep1.NoActiveLocaleSelected"); ///"General" public static string Website_Forms_Administrative_EditUserStep1_GenerelTabLabel=>T("Website.Forms.Administrative.EditUserStep1.GenerelTabLabel"); ///"Permissions" public static string Website_Forms_Administrative_EditUserStep1_PermissionsTabLabel=>T("Website.Forms.Administrative.EditUserStep1.PermissionsTabLabel"); ///"Perspectives" public static string Website_Forms_Administrative_EditUserStep1_PerspectivesTabLabel=>T("Website.Forms.Administrative.EditUserStep1.PerspectivesTabLabel"); ///"User Groups" public static string Website_Forms_Administrative_EditUserStep1_UserGroupsFieldLabel=>T("Website.Forms.Administrative.EditUserStep1.UserGroupsFieldLabel"); ///"Select the user groups that the selected user should be a member of." public static string Website_Forms_Administrative_EditUserStep1_UserGroupsMultiSelectHelp=>T("Website.Forms.Administrative.EditUserStep1.UserGroupsMultiSelectHelp"); ///"Is Locked" public static string Website_Forms_Administrative_EditUserStep1_IsLockedLabel=>T("Website.Forms.Administrative.EditUserStep1.IsLockedLabel"); ///"User can not log in" public static string Website_Forms_Administrative_EditUserStep1_IsLockedItemLabel=>T("Website.Forms.Administrative.EditUserStep1.IsLockedItemLabel"); ///"When checked the user will be forbidden from logging in." public static string Website_Forms_Administrative_EditUserStep1_IsLockedHelp=>T("Website.Forms.Administrative.EditUserStep1.IsLockedHelp"); ///"Error" public static string EditUserWorkflow_EditErrorTitle=>T("EditUserWorkflow.EditErrorTitle"); ///"You can not delete your own access rights to 'System' perspective." public static string EditUserWorkflow_EditOwnAccessToSystemPerspective=>T("EditUserWorkflow.EditOwnAccessToSystemPerspective"); ///"You can not lock your own account." public static string EditUserWorkflow_LockingOwnUserAccount=>T("EditUserWorkflow.LockingOwnUserAccount"); ///"Users" public static string UserElementProvider_RootLabel=>T("UserElementProvider.RootLabel"); ///"Users" public static string UserElementProvider_RootToolTip=>T("UserElementProvider.RootToolTip"); ///"Add User" public static string UserElementProvider_AddUserLabel=>T("UserElementProvider.AddUserLabel"); ///"Add new user" public static string UserElementProvider_AddUserToolTip=>T("UserElementProvider.AddUserToolTip"); ///"Edit User" public static string UserElementProvider_EditUserLabel=>T("UserElementProvider.EditUserLabel"); ///"Edit selected user" public static string UserElementProvider_EditUserToolTip=>T("UserElementProvider.EditUserToolTip"); ///"Delete User" public static string UserElementProvider_DeleteUserLabel=>T("UserElementProvider.DeleteUserLabel"); ///"Delete the selected user" public static string UserElementProvider_DeleteUserToolTip=>T("UserElementProvider.DeleteUserToolTip"); ///"Warning" public static string UserElementProvider_ChangeOtherActiveLocaleTitle=>T("UserElementProvider.ChangeOtherActiveLocaleTitle"); ///"You have change the active language for a user that is currently logged on. The users console will be reloaded and data might be lost." public static string UserElementProvider_ChangeOtherActiveLocaleMessage=>T("UserElementProvider.ChangeOtherActiveLocaleMessage"); ///"Cleanup Required" public static string UserElementProvider_ChangeOtherActiveLocaleDialogTitle=>T("UserElementProvider.ChangeOtherActiveLocaleDialogTitle"); ///"This requires a stage cleanup. Active editors will be saved and closed." public static string UserElementProvider_ChangeOtherActiveLocaleDialogText=>T("UserElementProvider.ChangeOtherActiveLocaleDialogText"); ///"A user with the same name already exists" public static string AddNewUserWorkflow_UsernameDuplicateError=>T("AddNewUserWorkflow.UsernameDuplicateError"); ///"Add New User" public static string Website_Forms_Administrative_AddNewUserStep1_LabelFieldGroup=>T("Website.Forms.Administrative.AddNewUserStep1.LabelFieldGroup"); ///"User name" public static string Website_Forms_Administrative_AddNewUserStep1_UserNameLabel=>T("Website.Forms.Administrative.AddNewUserStep1.UserNameLabel"); ///"When you have created a new user the username cannot be changed." public static string Website_Forms_Administrative_AddNewUserStep1_UserNameHelp=>T("Website.Forms.Administrative.AddNewUserStep1.UserNameHelp"); ///"Password" public static string Website_Forms_Administrative_AddNewUserStep1_PasswordLabel=>T("Website.Forms.Administrative.AddNewUserStep1.PasswordLabel"); ///"The password has to be more than 6 characters long." public static string Website_Forms_Administrative_AddNewUserStep1_PasswordHelp=>T("Website.Forms.Administrative.AddNewUserStep1.PasswordHelp"); ///"Name" public static string Website_Forms_Administrative_AddNewUserStep1_NameLabel=>T("Website.Forms.Administrative.AddNewUserStep1.NameLabel"); ///"The full name of the person using this account." public static string Website_Forms_Administrative_AddNewUserStep1_NameHelp=>T("Website.Forms.Administrative.AddNewUserStep1.NameHelp"); ///"Email address" public static string Website_Forms_Administrative_AddNewUserStep1_EmailLabel=>T("Website.Forms.Administrative.AddNewUserStep1.EmailLabel"); ///"The e-mail address of the user (optional)." public static string Website_Forms_Administrative_AddNewUserStep1_EmailHelp=>T("Website.Forms.Administrative.AddNewUserStep1.EmailHelp"); ///"Folder" public static string Website_Forms_Administrative_AddNewUserStep1_GroupLabel=>T("Website.Forms.Administrative.AddNewUserStep1.GroupLabel"); ///"If you enter a folder name that does not already exist a new folder will be created." public static string Website_Forms_Administrative_AddNewUserStep1_GroupHelp=>T("Website.Forms.Administrative.AddNewUserStep1.GroupHelp"); ///"Display Preferences" public static string Website_Forms_Administrative_AddNewUserStep1_CultureLabel=>T("Website.Forms.Administrative.AddNewUserStep1.CultureLabel"); ///"Display for time, date, and number formats within the console" public static string Website_Forms_Administrative_AddNewUserStep1_CultureHelp=>T("Website.Forms.Administrative.AddNewUserStep1.CultureHelp"); ///"Console Language Preferences" public static string Website_Forms_Administrative_AddNewUserStep1_C1ConsoleLanguageLabel=>T("Website.Forms.Administrative.AddNewUserStep1.C1ConsoleLanguageLabel"); ///"Language displayed within your console for labels, help texts, dialogs, etc. The available options are limited to language packages installed. See Composite.Localization packages for more language options." public static string Website_Forms_Administrative_AddNewUserStep1_C1ConsoleLanguageHelp=>T("Website.Forms.Administrative.AddNewUserStep1.C1ConsoleLanguageHelp"); ///"A language is required" public static string UserElementProvider_MissingActiveLanguageTitle=>T("UserElementProvider.MissingActiveLanguageTitle"); ///"To create a user a language is required, but no languages have been added yet. You can add one under the System perspective." public static string UserElementProvider_MissingActiveLanguageMessage=>T("UserElementProvider.MissingActiveLanguageMessage"); ///"User with the same login already exist" public static string UserElementProvider_UserLoginIsAlreadyUsed=>T("UserElementProvider.UserLoginIsAlreadyUsed"); ///"Add Datafolder" public static string AssociatedDataElementProviderHelper_AddDataFolderTypeLabel=>T("AssociatedDataElementProviderHelper.AddDataFolderTypeLabel"); ///"Add Datafolder" public static string AssociatedDataElementProviderHelper_AddDataFolderTypeToolTip=>T("AssociatedDataElementProviderHelper.AddDataFolderTypeToolTip"); ///"Add Data" public static string AssociatedDataElementProviderHelper_AddAssociatedDataLabel=>T("AssociatedDataElementProviderHelper.AddAssociatedDataLabel"); ///"Add data" public static string AssociatedDataElementProviderHelper_AddAssociatedDataToolTip=>T("AssociatedDataElementProviderHelper.AddAssociatedDataToolTip"); ///"Edit Data" public static string AssociatedDataElementProviderHelper_EditAssociatedDataLabel=>T("AssociatedDataElementProviderHelper.EditAssociatedDataLabel"); ///"Edit data" public static string AssociatedDataElementProviderHelper_EditAssociatedDataToolTip=>T("AssociatedDataElementProviderHelper.EditAssociatedDataToolTip"); ///"Delete Data" public static string AssociatedDataElementProviderHelper_DeleteAssociatedDataLabel=>T("AssociatedDataElementProviderHelper.DeleteAssociatedDataLabel"); ///"Delete data" public static string AssociatedDataElementProviderHelper_DeleteAssociatedDataToolTip=>T("AssociatedDataElementProviderHelper.DeleteAssociatedDataToolTip"); ///"Duplicate Data" public static string AssociatedDataElementProviderHelper_DuplicateAssociatedDataLabel=>T("AssociatedDataElementProviderHelper.DuplicateAssociatedDataLabel"); ///"Duplicate data" public static string AssociatedDataElementProviderHelper_DuplicateAssociatedDataToolTip=>T("AssociatedDataElementProviderHelper.DuplicateAssociatedDataToolTip"); ///"Localize" public static string AssociatedDataElementProviderHelper_LocalizeData=>T("AssociatedDataElementProviderHelper.LocalizeData"); ///"Localize data" public static string AssociatedDataElementProviderHelper_LocalizeDataToolTip=>T("AssociatedDataElementProviderHelper.LocalizeDataToolTip"); ///"Not yet approved or published" public static string AssociatedDataElementProviderHelper_DisabledData=>T("AssociatedDataElementProviderHelper.DisabledData"); ///"Add Datafolder" public static string AssociatedDataElementProviderHelper_AddDataFolderExSelectType_FieldLabel=>T("AssociatedDataElementProviderHelper.AddDataFolderExSelectType.FieldLabel"); ///"Datafolder type" public static string AssociatedDataElementProviderHelper_AddDataFolderExSelectType_SelectorLabel=>T("AssociatedDataElementProviderHelper.AddDataFolderExSelectType.SelectorLabel"); ///"Create new datatype or use an existing datatype (if present)." public static string AssociatedDataElementProviderHelper_AddDataFolderExSelectType_SelectorHelp=>T("AssociatedDataElementProviderHelper.AddDataFolderExSelectType.SelectorHelp"); ///"Settings" public static string AssociatedDataElementProviderHelper_AddDataFolderExCreateNewType_LabelNewType=>T("AssociatedDataElementProviderHelper.AddDataFolderExCreateNewType.LabelNewType"); ///"Type name" public static string AssociatedDataElementProviderHelper_AddDataFolderExCreateNewType_LabelTypeName=>T("AssociatedDataElementProviderHelper.AddDataFolderExCreateNewType.LabelTypeName"); ///"The technical name of the data type (ex. Product). This is used to identify this type in code and should not be changed once used externally." public static string AssociatedDataElementProviderHelper_AddDataFolderExCreateNewType_HelpTypeName=>T("AssociatedDataElementProviderHelper.AddDataFolderExCreateNewType.HelpTypeName"); ///"Type namespace" public static string AssociatedDataElementProviderHelper_AddDataFolderExCreateNewType_LabelTypeNamespace=>T("AssociatedDataElementProviderHelper.AddDataFolderExCreateNewType.LabelTypeNamespace"); ///"The namespace (module / category name) of the type. This is used to identify this type in code and should not be changed." public static string AssociatedDataElementProviderHelper_AddDataFolderExCreateNewType_HelpTypeNamespace=>T("AssociatedDataElementProviderHelper.AddDataFolderExCreateNewType.HelpTypeNamespace"); ///"Title" public static string AssociatedDataElementProviderHelper_AddDataFolderExCreateNewType_LabelTypeTitle=>T("AssociatedDataElementProviderHelper.AddDataFolderExCreateNewType.LabelTypeTitle"); ///"Use this entry to specify a user friendly name. You can change this field as you like." public static string AssociatedDataElementProviderHelper_AddDataFolderExCreateNewType_HelpTypeTitle=>T("AssociatedDataElementProviderHelper.AddDataFolderExCreateNewType.HelpTypeTitle"); ///"Fields" public static string AssociatedDataElementProviderHelper_AddDataFolderExCreateNewType_LabelFields=>T("AssociatedDataElementProviderHelper.AddDataFolderExCreateNewType.LabelFields"); ///"Services" public static string AssociatedDataElementProviderHelper_AddDataFolderExCreateNewType_ServicesLabel=>T("AssociatedDataElementProviderHelper.AddDataFolderExCreateNewType.ServicesLabel"); ///"Has publishing" public static string AssociatedDataElementProviderHelper_AddDataFolderExCreateNewType_HasPublishing=>T("AssociatedDataElementProviderHelper.AddDataFolderExCreateNewType.HasPublishing"); ///"Has localization" public static string AssociatedDataElementProviderHelper_AddDataFolderExCreateNewType_HasLocalization=>T("AssociatedDataElementProviderHelper.AddDataFolderExCreateNewType.HasLocalization"); ///"No page datafolders exists" public static string AssociatedDataElementProviderHelper_AddDataFolderExWorkflow_NoTypesTitle=>T("AssociatedDataElementProviderHelper.AddDataFolderExWorkflow.NoTypesTitle"); ///"No page datafolders have been created yet. You can create a page datafolder in the 'Data' perspective." public static string AssociatedDataElementProviderHelper_AddDataFolderExWorkflow_NoTypesMessage=>T("AssociatedDataElementProviderHelper.AddDataFolderExWorkflow.NoTypesMessage"); ///"No Unused Page Datafolders Exist" public static string AssociatedDataElementProviderHelper_AddDataFolderExWorkflow_NoUnusedTypesTitle=>T("AssociatedDataElementProviderHelper.AddDataFolderExWorkflow.NoUnusedTypesTitle"); ///"All available page datafolders have been added already. To create a new page datafolder go to the 'Data' perspective." public static string AssociatedDataElementProviderHelper_AddDataFolderExWorkflow_NoUnusedTypesMessage=>T("AssociatedDataElementProviderHelper.AddDataFolderExWorkflow.NoUnusedTypesMessage"); ///"Error" public static string AssociatedDataElementProviderHelper_AddDataFolderExCreateNewType_ErrorTitle=>T("AssociatedDataElementProviderHelper.AddDataFolderExCreateNewType.ErrorTitle"); ///"Select existing data folder type to add" public static string AssociatedDataElementProviderHelper_AddDataFolderSelectType_FieldLabel=>T("AssociatedDataElementProviderHelper.AddDataFolderSelectType.FieldLabel"); ///"Existing data folder types" public static string AssociatedDataElementProviderHelper_AddDataFolderSelectType_SelectorLabel=>T("AssociatedDataElementProviderHelper.AddDataFolderSelectType.SelectorLabel"); ///"Select existing data folder type to add" public static string AssociatedDataElementProviderHelper_AddDataFolderSelectType_SelectorHelp=>T("AssociatedDataElementProviderHelper.AddDataFolderSelectType.SelectorHelp"); ///"Remove Metadata Field" public static string AssociatedDataElementProviderHelper_RemoveMetaDataTypeLabel=>T("AssociatedDataElementProviderHelper.RemoveMetaDataTypeLabel"); ///"Remove metadata field" public static string AssociatedDataElementProviderHelper_RemoveMetaDataTypeToolTip=>T("AssociatedDataElementProviderHelper.RemoveMetaDataTypeToolTip"); ///"Remove Datafolder from Page" public static string AssociatedDataElementProviderHelper_DeleteDataFolderWorkflow_LabelFieldGroup=>T("AssociatedDataElementProviderHelper.DeleteDataFolderWorkflow.LabelFieldGroup"); ///"Data cleanup" public static string AssociatedDataElementProviderHelper_DeleteDataFolderWorkflow_FieldGroupLabel=>T("AssociatedDataElementProviderHelper.DeleteDataFolderWorkflow.FieldGroupLabel"); ///"Delete data" public static string AssociatedDataElementProviderHelper_DeleteDataFolderWorkflow_DeleteFolderDataLabel=>T("AssociatedDataElementProviderHelper.DeleteDataFolderWorkflow.DeleteFolderDataLabel"); ///"Yes, delete folder data" public static string AssociatedDataElementProviderHelper_DeleteDataFolderWorkflow_DeleteFolderDataCheckBoxLabel=>T("AssociatedDataElementProviderHelper.DeleteDataFolderWorkflow.DeleteFolderDataCheckBoxLabel"); ///"If you want data in this folder to stay in the database, you should uncheck this option." public static string AssociatedDataElementProviderHelper_DeleteDataFolderWorkflow_DeleteFolderDataHelp=>T("AssociatedDataElementProviderHelper.DeleteDataFolderWorkflow.DeleteFolderDataHelp"); ///"Add Metadata Field" public static string AssociatedDataElementProviderHelper_AddMetaDataSelectType_LayoutLabel=>T("AssociatedDataElementProviderHelper.AddMetaDataSelectType.LayoutLabel"); ///"Add Metadata Field" public static string AssociatedDataElementProviderHelper_AddMetaDataTypeLabel=>T("AssociatedDataElementProviderHelper.AddMetaDataTypeLabel"); ///"Add metadata field" public static string AssociatedDataElementProviderHelper_AddMetaDataTypeToolTip=>T("AssociatedDataElementProviderHelper.AddMetaDataTypeToolTip"); ///"Select existing metadata type to add" public static string AssociatedDataElementProviderHelper_AddMetaDataSelectType_FieldLabel=>T("AssociatedDataElementProviderHelper.AddMetaDataSelectType.FieldLabel"); ///"Existing metadata types" public static string AssociatedDataElementProviderHelper_AddMetaDataSelectType_SelectorLabel=>T("AssociatedDataElementProviderHelper.AddMetaDataSelectType.SelectorLabel"); ///"Select existing metadata type to add" public static string AssociatedDataElementProviderHelper_AddMetaDataSelectType_SelectorHelp=>T("AssociatedDataElementProviderHelper.AddMetaDataSelectType.SelectorHelp"); ///"No page metadata types exists" public static string AssociatedDataElementProviderHelper_AddMetaDataWorkflow_NoTypesTitle=>T("AssociatedDataElementProviderHelper.AddMetaDataWorkflow.NoTypesTitle"); ///"No page metatypes have been created yet. You can create a Page metatype in the 'Data' perspective." public static string AssociatedDataElementProviderHelper_AddMetaDataWorkflow_NoTypesMessage=>T("AssociatedDataElementProviderHelper.AddMetaDataWorkflow.NoTypesMessage"); ///"Metadata field group naming" public static string AssociatedDataElementProviderHelper_AddMetaDataCreateFieldGroup_NamingFieldLabel=>T("AssociatedDataElementProviderHelper.AddMetaDataCreateFieldGroup.NamingFieldLabel"); ///"Name" public static string AssociatedDataElementProviderHelper_AddMetaDataCreateFieldGroup_FieldGroupNameLabel=>T("AssociatedDataElementProviderHelper.AddMetaDataCreateFieldGroup.FieldGroupNameLabel"); ///"Enter a unique name identifying this metadata field group" public static string AssociatedDataElementProviderHelper_AddMetaDataCreateFieldGroup_FieldGroupNameHelp=>T("AssociatedDataElementProviderHelper.AddMetaDataCreateFieldGroup.FieldGroupNameHelp"); ///"Label" public static string AssociatedDataElementProviderHelper_AddMetaDataCreateFieldGroup_FieldGroupLabelLabel=>T("AssociatedDataElementProviderHelper.AddMetaDataCreateFieldGroup.FieldGroupLabelLabel"); ///"Enter a user friendly label for this metadata field group" public static string AssociatedDataElementProviderHelper_AddMetaDataCreateFieldGroup_FieldGroupLabelHelp=>T("AssociatedDataElementProviderHelper.AddMetaDataCreateFieldGroup.FieldGroupLabelHelp"); ///"Metadata field group visibility" public static string AssociatedDataElementProviderHelper_AddMetaDataCreateFieldGroup_VisabilityFieldLabel=>T("AssociatedDataElementProviderHelper.AddMetaDataCreateFieldGroup.VisabilityFieldLabel"); ///"Tab" public static string AssociatedDataElementProviderHelper_AddMetaDataCreateFieldGroup_ContainerSelectorLabel=>T("AssociatedDataElementProviderHelper.AddMetaDataCreateFieldGroup.ContainerSelectorLabel"); ///"Select the tab for which this metadata should exists" public static string AssociatedDataElementProviderHelper_AddMetaDataCreateFieldGroup_ContainerSelectorHelp=>T("AssociatedDataElementProviderHelper.AddMetaDataCreateFieldGroup.ContainerSelectorHelp"); ///"Start display from" public static string AssociatedDataElementProviderHelper_AddMetaDataCreateFieldGroup_StartDisplaySelectorLabel=>T("AssociatedDataElementProviderHelper.AddMetaDataCreateFieldGroup.StartDisplaySelectorLabel"); ///"Start display from" public static string AssociatedDataElementProviderHelper_AddMetaDataCreateFieldGroup_StartDisplaySelectorHelp=>T("AssociatedDataElementProviderHelper.AddMetaDataCreateFieldGroup.StartDisplaySelectorHelp"); ///"Inherit display" public static string AssociatedDataElementProviderHelper_AddMetaDataCreateFieldGroup_InheritDisplaySelectorLabel=>T("AssociatedDataElementProviderHelper.AddMetaDataCreateFieldGroup.InheritDisplaySelectorLabel"); ///"Inherit display" public static string AssociatedDataElementProviderHelper_AddMetaDataCreateFieldGroup_InheritDisplaySelectorHelp=>T("AssociatedDataElementProviderHelper.AddMetaDataCreateFieldGroup.InheritDisplaySelectorHelp"); ///"The metadata field group has no items in scope" public static string AssociatedDataElementProviderHelper_NoItems_Title=>T("AssociatedDataElementProviderHelper.NoItems.Title"); ///"There are currently no items within the specified display range. Press Previous to change the display range or Finish to create the metadata field group." public static string AssociatedDataElementProviderHelper_NoItems_Description=>T("AssociatedDataElementProviderHelper.NoItems.Description"); ///"This item" public static string AssociatedDataElementProviderHelper_AddMetaDataWorkflow_StartDisplayOption0=>T("AssociatedDataElementProviderHelper.AddMetaDataWorkflow.StartDisplayOption0"); ///"Children" public static string AssociatedDataElementProviderHelper_AddMetaDataWorkflow_StartDisplayOption1=>T("AssociatedDataElementProviderHelper.AddMetaDataWorkflow.StartDisplayOption1"); ///"2nd generation descendants" public static string AssociatedDataElementProviderHelper_AddMetaDataWorkflow_StartDisplayOption2=>T("AssociatedDataElementProviderHelper.AddMetaDataWorkflow.StartDisplayOption2"); ///"3rd generation descendants" public static string AssociatedDataElementProviderHelper_AddMetaDataWorkflow_StartDisplayOption3=>T("AssociatedDataElementProviderHelper.AddMetaDataWorkflow.StartDisplayOption3"); ///"4th generation descendants" public static string AssociatedDataElementProviderHelper_AddMetaDataWorkflow_StartDisplayOption4=>T("AssociatedDataElementProviderHelper.AddMetaDataWorkflow.StartDisplayOption4"); ///"5th generation descendants" public static string AssociatedDataElementProviderHelper_AddMetaDataWorkflow_StartDisplayOption5=>T("AssociatedDataElementProviderHelper.AddMetaDataWorkflow.StartDisplayOption5"); ///"Do not inherit" public static string AssociatedDataElementProviderHelper_AddMetaDataWorkflow_InheritDisplayOption0=>T("AssociatedDataElementProviderHelper.AddMetaDataWorkflow.InheritDisplayOption0"); ///"Inherit 1 generation" public static string AssociatedDataElementProviderHelper_AddMetaDataWorkflow_InheritDisplayOption1=>T("AssociatedDataElementProviderHelper.AddMetaDataWorkflow.InheritDisplayOption1"); ///"Inherit 2 generations" public static string AssociatedDataElementProviderHelper_AddMetaDataWorkflow_InheritDisplayOption2=>T("AssociatedDataElementProviderHelper.AddMetaDataWorkflow.InheritDisplayOption2"); ///"Inherit 3 generations" public static string AssociatedDataElementProviderHelper_AddMetaDataWorkflow_InheritDisplayOption3=>T("AssociatedDataElementProviderHelper.AddMetaDataWorkflow.InheritDisplayOption3"); ///"Always inherit" public static string AssociatedDataElementProviderHelper_AddMetaDataWorkflow_InheritDisplayOption4=>T("AssociatedDataElementProviderHelper.AddMetaDataWorkflow.InheritDisplayOption4"); ///"The field group name is in use" public static string AssociatedDataElementProviderHelper_AddMetaDataWorkflow_FieldGroupNameNotValid=>T("AssociatedDataElementProviderHelper.AddMetaDataWorkflow.FieldGroupNameNotValid"); ///"Remove Metadata Field Group" public static string AssociatedDataElementProviderHelper_DeleteMetaDataSelectType_LayoutLabel=>T("AssociatedDataElementProviderHelper.DeleteMetaDataSelectType.LayoutLabel"); ///"Select a metadata field group to remove" public static string AssociatedDataElementProviderHelper_DeleteMetaDataSelectFieldGroupName_FieldLabel=>T("AssociatedDataElementProviderHelper.DeleteMetaDataSelectFieldGroupName.FieldLabel"); ///"Field group" public static string AssociatedDataElementProviderHelper_DeleteMetaDataSelectFieldGroupName_SelectorLabel=>T("AssociatedDataElementProviderHelper.DeleteMetaDataSelectFieldGroupName.SelectorLabel"); ///"Select a metadata field group to remove" public static string AssociatedDataElementProviderHelper_DeleteMetaDataSelectFieldGroupName_SelectorHelp=>T("AssociatedDataElementProviderHelper.DeleteMetaDataSelectFieldGroupName.SelectorHelp"); ///"Edit Metadata Field" public static string AssociatedDataElementProviderHelper_EditMetaDataTypeLabel=>T("AssociatedDataElementProviderHelper.EditMetaDataTypeLabel"); ///"Edit metadata field" public static string AssociatedDataElementProviderHelper_EditMetaDataTypeToolTip=>T("AssociatedDataElementProviderHelper.EditMetaDataTypeToolTip"); ///"Edit Page Metadata Field" public static string AssociatedDataElementProviderHelper_EditMetaDataWorkflow_Layout_Label=>T("AssociatedDataElementProviderHelper.EditMetaDataWorkflow.Layout.Label"); ///"Page metadata field settings" public static string AssociatedDataElementProviderHelper_EditMetaDataWorkflow_FieldGroup_Label=>T("AssociatedDataElementProviderHelper.EditMetaDataWorkflow.FieldGroup.Label"); ///"Label" public static string AssociatedDataElementProviderHelper_EditMetaDataWorkflow_LabelTextBox_Label=>T("AssociatedDataElementProviderHelper.EditMetaDataWorkflow.LabelTextBox.Label"); ///"The label of the metadata field. Used when editing pages" public static string AssociatedDataElementProviderHelper_EditMetaDataWorkflow_LabelTextBox_Help=>T("AssociatedDataElementProviderHelper.EditMetaDataWorkflow.LabelTextBox.Help"); ///"Tab" public static string AssociatedDataElementProviderHelper_EditMetaDataWorkflow_MetaDataContainerSelector_Label=>T("AssociatedDataElementProviderHelper.EditMetaDataWorkflow.MetaDataContainerSelector.Label"); ///"Select the tab for which this metadata should exists" public static string AssociatedDataElementProviderHelper_EditMetaDataWorkflow_MetaDataContainerSelector_Help=>T("AssociatedDataElementProviderHelper.EditMetaDataWorkflow.MetaDataContainerSelector.Help"); ///"Start display from" public static string AssociatedDataElementProviderHelper_EditMetaDataWorkflow_StartDisplaySelectorLabel=>T("AssociatedDataElementProviderHelper.EditMetaDataWorkflow.StartDisplaySelectorLabel"); ///"Start display from" public static string AssociatedDataElementProviderHelper_EditMetaDataWorkflow_StartDisplaySelectorHelp=>T("AssociatedDataElementProviderHelper.EditMetaDataWorkflow.StartDisplaySelectorHelp"); ///"Inherit display" public static string AssociatedDataElementProviderHelper_EditMetaDataWorkflow_InheritDisplaySelectorLabel=>T("AssociatedDataElementProviderHelper.EditMetaDataWorkflow.InheritDisplaySelectorLabel"); ///"Inherit display" public static string AssociatedDataElementProviderHelper_EditMetaDataWorkflow_InheritDisplaySelectorHelp=>T("AssociatedDataElementProviderHelper.EditMetaDataWorkflow.InheritDisplaySelectorHelp"); ///"Metadata field" public static string AssociatedDataElementProviderHelper_EditMetaDataWorkflow_MetaDataDefinitionSelector_Label=>T("AssociatedDataElementProviderHelper.EditMetaDataWorkflow.MetaDataDefinitionSelector.Label"); ///"Select the metadata field to edit" public static string AssociatedDataElementProviderHelper_EditMetaDataWorkflow_MetaDataDefinitionSelector_Help=>T("AssociatedDataElementProviderHelper.EditMetaDataWorkflow.MetaDataDefinitionSelector.Help"); ///"No Metadata Fields to Edit" public static string AssociatedDataElementProviderHelper_EditMetaDataWorkflow_NoMetaDataDefinitionsExists_Title=>T("AssociatedDataElementProviderHelper.EditMetaDataWorkflow.NoMetaDataDefinitionsExists.Title"); ///"There is no metadata fields defined on this item to edit" public static string AssociatedDataElementProviderHelper_EditMetaDataWorkflow_NoMetaDataDefinitionsExists_Message=>T("AssociatedDataElementProviderHelper.EditMetaDataWorkflow.NoMetaDataDefinitionsExists.Message"); ///"The metadata type is used another place with same name but different label" public static string AssociatedDataElementProviderHelper_EditMetaDataWorkflow_MetaDataFieldNameAlreadyUsed=>T("AssociatedDataElementProviderHelper.EditMetaDataWorkflow.MetaDataFieldNameAlreadyUsed"); ///"There exists one or more definitions with the same name, container change is not allowed" public static string AssociatedDataElementProviderHelper_EditMetaDataWorkflow_MetaDataContainerChangeNotAllowed=>T("AssociatedDataElementProviderHelper.EditMetaDataWorkflow.MetaDataContainerChangeNotAllowed"); ///"Press finish to save" public static string AssociatedDataElementProviderHelper_EditMetaDataWorkflow_NoDefaultValuesNeeded_Title=>T("AssociatedDataElementProviderHelper.EditMetaDataWorkflow.NoDefaultValuesNeeded.Title"); ///"All required information has been gathered. Press Finish to update the metadata field" public static string AssociatedDataElementProviderHelper_EditMetaDataWorkflow_NoDefaultValuesNeeded_Description=>T("AssociatedDataElementProviderHelper.EditMetaDataWorkflow.NoDefaultValuesNeeded.Description"); ///"No Metadata Fields to Remove" public static string AssociatedDataElementProviderHelper_DeleteMetaDataWorkflow_NoDefinedTypesExists_Title=>T("AssociatedDataElementProviderHelper.DeleteMetaDataWorkflow.NoDefinedTypesExists.Title"); ///"There is no metadata fields defined on this item to remove" public static string AssociatedDataElementProviderHelper_DeleteMetaDataWorkflow_NoDefinedTypesExists_Message=>T("AssociatedDataElementProviderHelper.DeleteMetaDataWorkflow.NoDefinedTypesExists.Message"); ///"Cascade delete error" public static string DeleteAssociatedDataWorkflow_CascadeDeleteErrorTitle=>T("DeleteAssociatedDataWorkflow.CascadeDeleteErrorTitle"); ///"The type is referenced by another type that does not allow cascade deletes. This operation is halted" public static string DeleteAssociatedDataWorkflow_CascadeDeleteErrorMessage=>T("DeleteAssociatedDataWorkflow.CascadeDeleteErrorMessage"); ///"Settings" public static string Website_Forms_Administrative_CreateNewAssociatedTypeStep1_LabelNewType=>T("Website.Forms.Administrative.CreateNewAssociatedTypeStep1.LabelNewType"); ///"Type name" public static string Website_Forms_Administrative_CreateNewAssociatedTypeStep1_LabelTypeName=>T("Website.Forms.Administrative.CreateNewAssociatedTypeStep1.LabelTypeName"); ///"The name of the new type that you are creating (ex. product)" public static string Website_Forms_Administrative_CreateNewAssociatedTypeStep1_HelpTypeName=>T("Website.Forms.Administrative.CreateNewAssociatedTypeStep1.HelpTypeName"); ///"Type namespace" public static string Website_Forms_Administrative_CreateNewAssociatedTypeStep1_LabelTypeNamespace=>T("Website.Forms.Administrative.CreateNewAssociatedTypeStep1.LabelTypeNamespace"); ///"The name of the module, category or namespace that you are creating" public static string Website_Forms_Administrative_CreateNewAssociatedTypeStep1_HelpTypeNamespace=>T("Website.Forms.Administrative.CreateNewAssociatedTypeStep1.HelpTypeNamespace"); ///"Title" public static string Website_Forms_Administrative_CreateNewAssociatedTypeStep1_LabelTypeTitle=>T("Website.Forms.Administrative.CreateNewAssociatedTypeStep1.LabelTypeTitle"); ///"Use this entry to specify a user friendly name" public static string Website_Forms_Administrative_CreateNewAssociatedTypeStep1_HelpTypeTitle=>T("Website.Forms.Administrative.CreateNewAssociatedTypeStep1.HelpTypeTitle"); ///"Fields" public static string Website_Forms_Administrative_CreateNewAssociatedTypeStep1_LabelFields=>T("Website.Forms.Administrative.CreateNewAssociatedTypeStep1.LabelFields"); ///"Services" public static string Website_Forms_Administrative_CreateNewAssociatedTypeStep1_ServicesLabel=>T("Website.Forms.Administrative.CreateNewAssociatedTypeStep1.ServicesLabel"); ///"Has versioning" public static string Website_Forms_Administrative_CreateNewAssociatedTypeStep1_HasVersioning=>T("Website.Forms.Administrative.CreateNewAssociatedTypeStep1.HasVersioning"); ///"Has publishing" public static string Website_Forms_Administrative_CreateNewAssociatedTypeStep1_HasPublishing=>T("Website.Forms.Administrative.CreateNewAssociatedTypeStep1.HasPublishing"); ///"Delete Data?" public static string Website_Forms_Administrative_DeleteAssociatedTypeDataStep1_FieldGroupLabel=>T("Website.Forms.Administrative.DeleteAssociatedTypeDataStep1.FieldGroupLabel"); ///"Delete data?" public static string Website_Forms_Administrative_DeleteAssociatedTypeDataStep1_Text=>T("Website.Forms.Administrative.DeleteAssociatedTypeDataStep1.Text"); ///"Add page data" public static string Website_Forms_Administrative_AddAssociatedDataWorkflow_FieldGroupLabel=>T("Website.Forms.Administrative.AddAssociatedDataWorkflow.FieldGroupLabel"); ///"Select a datatype to add" public static string Website_Forms_Administrative_AddAssociatedDataWorkflow_TypeSelectorLabel=>T("Website.Forms.Administrative.AddAssociatedDataWorkflow.TypeSelectorLabel"); ///"Select one of the existing types to add data to" public static string Website_Forms_Administrative_AddAssociatedDataWorkflow_TypeSelectorHelp=>T("Website.Forms.Administrative.AddAssociatedDataWorkflow.TypeSelectorHelp"); ///"Add page datatype" public static string Website_Forms_Administrative_AddAssociatedTypeWorkflow_FieldGroupLabel=>T("Website.Forms.Administrative.AddAssociatedTypeWorkflow.FieldGroupLabel"); ///"Select type to add" public static string Website_Forms_Administrative_AddAssociatedTypeAddExisting_TypeSelectorLabel=>T("Website.Forms.Administrative.AddAssociatedTypeAddExisting.TypeSelectorLabel"); ///"Select one of the existing types in the system" public static string Website_Forms_Administrative_AddAssociatedTypeAddExisting_TypeSelectorHelp=>T("Website.Forms.Administrative.AddAssociatedTypeAddExisting.TypeSelectorHelp"); ///"Select a foreign key" public static string Website_Forms_Administrative_AddAssociatedTypeAddExistingSelectForeignKey_KeySelectorLabel=>T("Website.Forms.Administrative.AddAssociatedTypeAddExistingSelectForeignKey.KeySelectorLabel"); ///"Select one of the fields from the type to use as foreign key" public static string Website_Forms_Administrative_AddAssociatedTypeAddExistingSelectForeignKey_KeySelectorHelp=>T("Website.Forms.Administrative.AddAssociatedTypeAddExistingSelectForeignKey.KeySelectorHelp"); ///"Add a" public static string Website_Forms_Administrative_AddAssociatedTypeAddingTypeSelection_KeySelectorLabel=>T("Website.Forms.Administrative.AddAssociatedTypeAddingTypeSelection.KeySelectorLabel"); ///"Creating a new type or using an existing type" public static string Website_Forms_Administrative_AddAssociatedTypeAddingTypeSelection_KeySelectorHelp=>T("Website.Forms.Administrative.AddAssociatedTypeAddingTypeSelection.KeySelectorHelp"); ///"Select type:" public static string Website_Forms_Administrative_AddAssociatedTypeAssociationTypeSelection_KeySelectorLabel=>T("Website.Forms.Administrative.AddAssociatedTypeAssociationTypeSelection.KeySelectorLabel"); ///"Regular data is a new type that are created under a page. Metadata is a new field that are created on a page" public static string Website_Forms_Administrative_AddAssociatedTypeAssociationTypeSelection_KeySelectorHelp=>T("Website.Forms.Administrative.AddAssociatedTypeAssociationTypeSelection.KeySelectorHelp"); ///"Rule name" public static string Website_Forms_Administrative_AddAssociatedTypeCompositionScopeSelection_ScopeRuleNameLabel=>T("Website.Forms.Administrative.AddAssociatedTypeCompositionScopeSelection.ScopeRuleNameLabel"); ///"Rule name are saved with the metadata and are a part of the metadata key. The name must be unique." public static string Website_Forms_Administrative_AddAssociatedTypeCompositionScopeSelection_ScopeRuleNameHelp=>T("Website.Forms.Administrative.AddAssociatedTypeCompositionScopeSelection.ScopeRuleNameHelp"); ///"Rule label" public static string Website_Forms_Administrative_AddAssociatedTypeCompositionScopeSelection_ScopeRuleLabelLabel=>T("Website.Forms.Administrative.AddAssociatedTypeCompositionScopeSelection.ScopeRuleLabelLabel"); ///"Rule label is used as a user friendly name for the instance. Can be localized" public static string Website_Forms_Administrative_AddAssociatedTypeCompositionScopeSelection_ScopeRuleHelpHelp=>T("Website.Forms.Administrative.AddAssociatedTypeCompositionScopeSelection.ScopeRuleHelpHelp"); ///"Select composition container" public static string Website_Forms_Administrative_AddAssociatedTypeCompositionScopeSelection_ContainerKeySelectorLabel=>T("Website.Forms.Administrative.AddAssociatedTypeCompositionScopeSelection.ContainerKeySelectorLabel"); ///"Select container for the new rule." public static string Website_Forms_Administrative_AddAssociatedTypeCompositionScopeSelection_ContainerKeySelectorHelp=>T("Website.Forms.Administrative.AddAssociatedTypeCompositionScopeSelection.ContainerKeySelectorHelp"); ///"Select composition scope" public static string Website_Forms_Administrative_AddAssociatedTypeCompositionScopeSelection_ScopeKeySelectorLabel=>T("Website.Forms.Administrative.AddAssociatedTypeCompositionScopeSelection.ScopeKeySelectorLabel"); ///"Select the scope for the new composition" public static string Website_Forms_Administrative_AddAssociatedTypeCompositionScopeSelection_ScopeKeySelectorHelp=>T("Website.Forms.Administrative.AddAssociatedTypeCompositionScopeSelection.ScopeKeySelectorHelp"); ///"Levels" public static string Website_Forms_Administrative_AddAssociatedTypeLevelsScopeSelection_LevelsLabel=>T("Website.Forms.Administrative.AddAssociatedTypeLevelsScopeSelection.LevelsLabel"); ///"The depth of sub pages in which the composition will be visible" public static string Website_Forms_Administrative_AddAssociatedTypeLevelsScopeSelection_LevelsHelp=>T("Website.Forms.Administrative.AddAssociatedTypeLevelsScopeSelection.LevelsHelp"); ///"Confirm new datatype:" public static string Website_Forms_Administrative_AddAssociatedTypeFinalInfo_AssociationTypeLabel=>T("Website.Forms.Administrative.AddAssociatedTypeFinalInfo.AssociationTypeLabel"); ///"Metadata is a new field that are created on a page" public static string Website_Forms_Administrative_AddAssociatedTypeFinalInfo_AssociationTypeHelp=>T("Website.Forms.Administrative.AddAssociatedTypeFinalInfo.AssociationTypeHelp"); ///"Composition scope rule name" public static string Website_Forms_Administrative_AddAssociatedTypeFinalInfo_CompositionScopeRuleNameLabel=>T("Website.Forms.Administrative.AddAssociatedTypeFinalInfo.CompositionScopeRuleNameLabel"); ///"Rule name are saved with the metadata and are a part of the metadata key. The name must be unique." public static string Website_Forms_Administrative_AddAssociatedTypeFinalInfo_CompositionScopeRuleNameHelp=>T("Website.Forms.Administrative.AddAssociatedTypeFinalInfo.CompositionScopeRuleNameHelp"); ///"Composition scope rule label" public static string Website_Forms_Administrative_AddAssociatedTypeFinalInfo_CompositionScopeRuleLabelLabel=>T("Website.Forms.Administrative.AddAssociatedTypeFinalInfo.CompositionScopeRuleLabelLabel"); ///"Rule label is used as a user friendly name for the instance. Can be localized" public static string Website_Forms_Administrative_AddAssociatedTypeFinalInfo_CompositionScopeRuleHelpHelp=>T("Website.Forms.Administrative.AddAssociatedTypeFinalInfo.CompositionScopeRuleHelpHelp"); ///"Composition scope" public static string Website_Forms_Administrative_AddAssociatedTypeFinalInfo_CompositionScopeLabel=>T("Website.Forms.Administrative.AddAssociatedTypeFinalInfo.CompositionScopeLabel"); ///"This is the scope in which the new composition will be visible when editing pages" public static string Website_Forms_Administrative_AddAssociatedTypeFinalInfo_CompositionScopeHelp=>T("Website.Forms.Administrative.AddAssociatedTypeFinalInfo.CompositionScopeHelp"); ///"Adding type" public static string Website_Forms_Administrative_AddAssociatedTypeFinalInfo_AddingTypeLabel=>T("Website.Forms.Administrative.AddAssociatedTypeFinalInfo.AddingTypeLabel"); ///"Create a new type or use an existing type" public static string Website_Forms_Administrative_AddAssociatedTypeFinalInfo_AddingTypeHelp=>T("Website.Forms.Administrative.AddAssociatedTypeFinalInfo.AddingTypeHelp"); ///"Existing type name" public static string Website_Forms_Administrative_AddAssociatedTypeFinalInfo_ExistingTypeNameLabel=>T("Website.Forms.Administrative.AddAssociatedTypeFinalInfo.ExistingTypeNameLabel"); ///"The name of the selected existing type in the system to use" public static string Website_Forms_Administrative_AddAssociatedTypeFinalInfo_ExistingTypeNameHelp=>T("Website.Forms.Administrative.AddAssociatedTypeFinalInfo.ExistingTypeNameHelp"); ///"Foreign key field name" public static string Website_Forms_Administrative_AddAssociatedTypeFinalInfo_ForeignKeyFieldNameLabel=>T("Website.Forms.Administrative.AddAssociatedTypeFinalInfo.ForeignKeyFieldNameLabel"); ///"The name of the field of the existing type to use as a foreign key " public static string Website_Forms_Administrative_AddAssociatedTypeFinalInfo_ForeignKeyFieldNameHelp=>T("Website.Forms.Administrative.AddAssociatedTypeFinalInfo.ForeignKeyFieldNameHelp"); ///"Remove Datafolder" public static string AssociatedDataElementProviderHelper_RemoveAssociatedTypeLabel=>T("AssociatedDataElementProviderHelper.RemoveAssociatedTypeLabel"); ///"Remove datafolder" public static string AssociatedDataElementProviderHelper_RemoveAssociatedTypeToolTip=>T("AssociatedDataElementProviderHelper.RemoveAssociatedTypeToolTip"); ///"Remove page datatype" public static string Website_Forms_Administrative_RemoveAssociatedType_FieldGroupLabel=>T("Website.Forms.Administrative.RemoveAssociatedType.FieldGroupLabel"); ///"Remove page datatype" public static string Website_Forms_Administrative_RemoveAssociatedTypeFinalInfo_AssociationTypeLabel=>T("Website.Forms.Administrative.RemoveAssociatedTypeFinalInfo.AssociationTypeLabel"); ///"Composition scope rule name" public static string Website_Forms_Administrative_RemoveAssociatedTypeFinalInfo_CompositionScopeRuleNameLabel=>T("Website.Forms.Administrative.RemoveAssociatedTypeFinalInfo.CompositionScopeRuleNameLabel"); ///"Select a rule" public static string Website_Forms_Administrative_RemoveAssociatedTypeSelectRuleName_KeySelectorLabel=>T("Website.Forms.Administrative.RemoveAssociatedTypeSelectRuleName.KeySelectorLabel"); ///"The name of the rule to remove" public static string Website_Forms_Administrative_RemoveAssociatedTypeSelectRuleName_KeySelectorHelp=>T("Website.Forms.Administrative.RemoveAssociatedTypeSelectRuleName.KeySelectorHelp"); ///"Select page datatype" public static string Website_Forms_Administrative_RemoveAssociatedTypeSelectAssociationType_KeySelectorLabel=>T("Website.Forms.Administrative.RemoveAssociatedTypeSelectAssociationType.KeySelectorLabel"); ///"" public static string Website_Forms_Administrative_RemoveAssociatedTypeSelectAssociationType_KeySelectorHelp=>T("Website.Forms.Administrative.RemoveAssociatedTypeSelectAssociationType.KeySelectorHelp"); ///"Select datatype" public static string Website_Forms_Administrative_RemoveAssociatedTypeSelectType_TypeSelectorLabel=>T("Website.Forms.Administrative.RemoveAssociatedTypeSelectType.TypeSelectorLabel"); ///"Select one of the existing types" public static string Website_Forms_Administrative_RemoveAssociatedTypeSelectType_TypeSelectorHelp=>T("Website.Forms.Administrative.RemoveAssociatedTypeSelectType.TypeSelectorHelp"); ///"Virtual root" public static string VirtualElementProviderElementProvider_ID01=>T("VirtualElementProviderElementProvider.ID01"); ///"Users and Permissions" public static string VirtualElementProviderElementProvider_PermissionsPerspective=>T("VirtualElementProviderElementProvider.PermissionsPerspective"); ///"Users" public static string VirtualElementProviderElementProvider_UserPerspective=>T("VirtualElementProviderElementProvider.UserPerspective"); ///"Developer Apps" public static string VirtualElementProviderElementProvider_DeveloperApplicationPerspective=>T("VirtualElementProviderElementProvider.DeveloperApplicationPerspective"); ///"User Groups" public static string VirtualElementProviderElementProvider_UserGroupPerspective=>T("VirtualElementProviderElementProvider.UserGroupPerspective"); ///"System" public static string VirtualElementProviderElementProvider_SystemPerspective=>T("VirtualElementProviderElementProvider.SystemPerspective"); ///"Content" public static string VirtualElementProviderElementProvider_ContentPerspective=>T("VirtualElementProviderElementProvider.ContentPerspective"); ///"Data" public static string VirtualElementProviderElementProvider_DatasPerspective=>T("VirtualElementProviderElementProvider.DatasPerspective"); ///"Layout" public static string VirtualElementProviderElementProvider_DesignPerspective=>T("VirtualElementProviderElementProvider.DesignPerspective"); ///"Functions" public static string VirtualElementProviderElementProvider_FunctionsPerspective=>T("VirtualElementProviderElementProvider.FunctionsPerspective"); ///"All Media Files" public static string VirtualElementProviderElementProvider_MediaFilePerspective=>T("VirtualElementProviderElementProvider.MediaFilePerspective"); ///"Media" public static string VirtualElementProviderElementProvider_MediaPerspective=>T("VirtualElementProviderElementProvider.MediaPerspective"); ///"All Functions" public static string VirtualElementProviderElementProvider_ReadOnlyFunctionPerspective=>T("VirtualElementProviderElementProvider.ReadOnlyFunctionPerspective"); ///"All Widget Functions" public static string VirtualElementProviderElementProvider_ReadOnlyWidgetFunctionPerspective=>T("VirtualElementProviderElementProvider.ReadOnlyWidgetFunctionPerspective"); ///"SQL Functions" public static string VirtualElementProviderElementProvider_SqlFunctionPerspective=>T("VirtualElementProviderElementProvider.SqlFunctionPerspective"); ///"Xslt Based Functions" public static string VirtualElementProviderElementProvider_XsltBasedFunctionPerspective=>T("VirtualElementProviderElementProvider.XsltBasedFunctionPerspective"); ///"Broadcast Message" public static string VirtualElementProviderElementProvider_RootActions_SendMessageLabel=>T("VirtualElementProviderElementProvider.RootActions.SendMessageLabel"); ///"Send a message to all running consoles" public static string VirtualElementProviderElementProvider_RootActions_SendMessageTooltip=>T("VirtualElementProviderElementProvider.RootActions.SendMessageTooltip"); ///"Time Zone Settings" public static string VirtualElementProviderElementProvider_RootActions_SetTimezoneLabel=>T("VirtualElementProviderElementProvider.RootActions.SetTimezoneLabel"); ///"Time zone to be displayed for all users within the console" public static string VirtualElementProviderElementProvider_RootActions_SetTimezoneTooltip=>T("VirtualElementProviderElementProvider.RootActions.SetTimezoneTooltip"); ///"Global Settings" public static string VirtualElementProviderElementProvider_RootActions_GlobalSetting=>T("VirtualElementProviderElementProvider.RootActions.GlobalSetting"); ///"Rebuild search index" public static string VirtualElementProviderElementProvider_RootActions_RebuildSearchIndexLabel=>T("VirtualElementProviderElementProvider.RootActions.RebuildSearchIndexLabel"); ///"Initiate search index rebuilding" public static string VirtualElementProviderElementProvider_RootActions_RebuildSearchIndexTooltip=>T("VirtualElementProviderElementProvider.RootActions.RebuildSearchIndexTooltip"); ///"Restart server" public static string VirtualElementProviderElementProvider_RootActions_RestartApplicationLabel=>T("VirtualElementProviderElementProvider.RootActions.RestartApplicationLabel"); ///"Restart the server" public static string VirtualElementProviderElementProvider_RootActions_RestartApplicationTooltip=>T("VirtualElementProviderElementProvider.RootActions.RestartApplicationTooltip"); ///"Broadcast Message to All {applicationname} Consoles" public static string SendMessageToConsolesWorkflow_Layout_Label=>T("SendMessageToConsolesWorkflow.Layout.Label"); ///"Title" public static string SendMessageToConsolesWorkflow_TitleTextBox_Label=>T("SendMessageToConsolesWorkflow.TitleTextBox.Label"); ///"Dialog title of broadcast message" public static string SendMessageToConsolesWorkflow_TitleTextBox_Help=>T("SendMessageToConsolesWorkflow.TitleTextBox.Help"); ///"Message" public static string SendMessageToConsolesWorkflow_MessageTextArea_Label=>T("SendMessageToConsolesWorkflow.MessageTextArea.Label"); ///"The message to broadcast" public static string SendMessageToConsolesWorkflow_MessageTextArea_Help=>T("SendMessageToConsolesWorkflow.MessageTextArea.Help"); ///"Time Zone Updated" public static string SendMessageToConsolesWorkflow_SuccessMessage_TimezoneChangedTitle=>T("SendMessageToConsolesWorkflow.SuccessMessage.TimezoneChangedTitle"); ///"Time zone has been successfully updated" public static string SendMessageToConsolesWorkflow_SuccessMessage_TimezoneChangedMessage=>T("SendMessageToConsolesWorkflow.SuccessMessage.TimezoneChangedMessage"); ///"Set Time Zone Display" public static string SetTimezoneWorkflow_Layout_Label=>T("SetTimezoneWorkflow.Layout.Label"); ///"Select Time Zone" public static string SetTimezoneWorkflow_TitleTextBox_Label=>T("SetTimezoneWorkflow.TitleTextBox.Label"); ///"Time zone to be displayed for all users within the console. The console will restart once time zone updated. Any unsaved changes will be lost." public static string SetTimezoneWorkflow_TitleTextBox_Help=>T("SetTimezoneWorkflow.TitleTextBox.Help"); ///"Time zone update requires a console restart. Any unsaved changes will be lost." public static string SetTimezoneWorkflow_WarningText_Text=>T("SetTimezoneWorkflow.WarningText.Text"); ///"Login" public static string LoginWebRequestHandler_Login=>T("LoginWebRequestHandler.Login"); ///"Login to {0}" public static string LoginWebRequestHandler_Header_Template=>T("LoginWebRequestHandler.Header"); ///"Login to {0}" public static string LoginWebRequestHandler_Header(object parameter0)=>string.Format(T("LoginWebRequestHandler.Header"), parameter0); ///"Incorrect user name or password" public static string LoginWebRequestHandler_LoginFailed=>T("LoginWebRequestHandler.LoginFailed"); ///"Password" public static string LoginWebRequestHandler_Password=>T("LoginWebRequestHandler.Password"); ///"Username" public static string LoginWebRequestHandler_Username=>T("LoginWebRequestHandler.Username"); ///"Log in as another user." public static string LoginWebRequestHandler_LogInAsOtherUser=>T("LoginWebRequestHandler.LogInAsOtherUser"); ///"Wrong username or password." public static string LoginWebRequestHandler_WrongUserNameOrPassword=>T("LoginWebRequestHandler.WrongUserNameOrPassword"); ///"The supplied Windows login, {0}\{1} is not registered in the user database. You must use a different login." public static string LoginWebRequestHandler_UserNameNotRegistered_Template=>T("LoginWebRequestHandler.UserNameNotRegistered"); ///"The supplied Windows login, {0}\{1} is not registered in the user database. You must use a different login." public static string LoginWebRequestHandler_UserNameNotRegistered(object parameter0,object parameter1)=>string.Format(T("LoginWebRequestHandler.UserNameNotRegistered"), parameter0,parameter1); ///"The type {0} is not an interface." public static string DataInterfaceValidator_TypeNotAnInterface_Template=>T("DataInterfaceValidator.TypeNotAnInterface"); ///"The type {0} is not an interface." public static string DataInterfaceValidator_TypeNotAnInterface(object parameter0)=>string.Format(T("DataInterfaceValidator.TypeNotAnInterface"), parameter0); ///"The interface type {0} does not implement the interface {1}." public static string DataInterfaceValidator_TypeDoesNotImplementInterface_Template=>T("DataInterfaceValidator.TypeDoesNotImplementInterface"); ///"The interface type {0} does not implement the interface {1}." public static string DataInterfaceValidator_TypeDoesNotImplementInterface(object parameter0,object parameter1)=>string.Format(T("DataInterfaceValidator.TypeDoesNotImplementInterface"), parameter0,parameter1); ///"The property {0} on the interface type {1} is not a accepted type." public static string DataInterfaceValidator_NotAcceptedType_Template=>T("DataInterfaceValidator.NotAcceptedType"); ///"The property {0} on the interface type {1} is not a accepted type." public static string DataInterfaceValidator_NotAcceptedType(object parameter0,object parameter1)=>string.Format(T("DataInterfaceValidator.NotAcceptedType"), parameter0,parameter1); ///"The interface {0} is not a valid IData interface." public static string DataInterfaceValidator_NotValidIDataInterface_Template=>T("DataInterfaceValidator.NotValidIDataInterface"); ///"The interface {0} is not a valid IData interface." public static string DataInterfaceValidator_NotValidIDataInterface(object parameter0)=>string.Format(T("DataInterfaceValidator.NotValidIDataInterface"), parameter0); ///"Cascade delete error" public static string DeleteMediaFileWorkflow_CascadeDeleteErrorTitle=>T("DeleteMediaFileWorkflow.CascadeDeleteErrorTitle"); ///"The type is referenced by another type that does not allow cascade deletes. This operation is halted" public static string DeleteMediaFileWorkflow_CascadeDeleteErrorMessage=>T("DeleteMediaFileWorkflow.CascadeDeleteErrorMessage"); ///"Cascade delete error" public static string DeleteMediaFolderWorkflow_CascadeDeleteErrorTitle=>T("DeleteMediaFolderWorkflow.CascadeDeleteErrorTitle"); ///"The type is referenced by another type that does not allow cascade deletes. This operation is halted" public static string DeleteMediaFolderWorkflow_CascadeDeleteErrorMessage=>T("DeleteMediaFolderWorkflow.CascadeDeleteErrorMessage"); ///"Add folders and files to the media archive" public static string MediaFileProviderElementProvider_RootToolTip=>T("MediaFileProviderElementProvider.RootToolTip"); ///"Add Folder" public static string MediaFileProviderElementProvider_AddMediaFolder=>T("MediaFileProviderElementProvider.AddMediaFolder"); ///"Add new media folder" public static string MediaFileProviderElementProvider_AddMediaFolderToolTip=>T("MediaFileProviderElementProvider.AddMediaFolderToolTip"); ///"Upload File" public static string MediaFileProviderElementProvider_AddMediaFile=>T("MediaFileProviderElementProvider.AddMediaFile"); ///"Add new media file" public static string MediaFileProviderElementProvider_AddMediaFileToolTip=>T("MediaFileProviderElementProvider.AddMediaFileToolTip"); ///"Delete File" public static string MediaFileProviderElementProvider_DeleteMediaFile=>T("MediaFileProviderElementProvider.DeleteMediaFile"); ///"Delete the selected media file" public static string MediaFileProviderElementProvider_DeleteMediaFileToolTip=>T("MediaFileProviderElementProvider.DeleteMediaFileToolTip"); ///"Delete Folder" public static string MediaFileProviderElementProvider_DeleteMediaFolder=>T("MediaFileProviderElementProvider.DeleteMediaFolder"); ///"Delete the media folder and all items under it." public static string MediaFileProviderElementProvider_DeleteMediaFolderToolTip=>T("MediaFileProviderElementProvider.DeleteMediaFolderToolTip"); ///"Download" public static string MediaFileProviderElementProvider_Download=>T("MediaFileProviderElementProvider.Download"); ///"Download file" public static string MediaFileProviderElementProvider_DownloadToolTip=>T("MediaFileProviderElementProvider.DownloadToolTip"); ///"File Properties" public static string MediaFileProviderElementProvider_EditMediaFile=>T("MediaFileProviderElementProvider.EditMediaFile"); ///"Rename the selected media file" public static string MediaFileProviderElementProvider_EditMediaFileToolTip=>T("MediaFileProviderElementProvider.EditMediaFileToolTip"); ///"Edit text" public static string MediaFileProviderElementProvider_EditMediaFileTextContent=>T("MediaFileProviderElementProvider.EditMediaFileTextContent"); ///"Edit text content" public static string MediaFileProviderElementProvider_EditMediaFileTextContentToolTip=>T("MediaFileProviderElementProvider.EditMediaFileTextContentToolTip"); ///"Image Editor" public static string MediaFileProviderElementProvider_EditImage=>T("MediaFileProviderElementProvider.EditImage"); ///"Open the selected media file in the image editor" public static string MediaFileProviderElementProvider_EditImageToolTip=>T("MediaFileProviderElementProvider.EditImageToolTip"); ///"Folder Properties" public static string MediaFileProviderElementProvider_EditMediaFolder=>T("MediaFileProviderElementProvider.EditMediaFolder"); ///"Edit media folder properties" public static string MediaFileProviderElementProvider_EditMediaFolderToolTip=>T("MediaFileProviderElementProvider.EditMediaFolderToolTip"); ///"Replace File" public static string MediaFileProviderElementProvider_ChangeMediaFile=>T("MediaFileProviderElementProvider.ChangeMediaFile"); ///"Replace the selected with another media file" public static string MediaFileProviderElementProvider_ChangeMediaFileToolTip=>T("MediaFileProviderElementProvider.ChangeMediaFileToolTip"); ///"Upload Multiple" public static string MediaFileProviderElementProvider_UploadZipFile=>T("MediaFileProviderElementProvider.UploadZipFile"); ///"Upload Zip file" public static string MediaFileProviderElementProvider_UploadZipFileToolTip=>T("MediaFileProviderElementProvider.UploadZipFileToolTip"); ///"Media Item" public static string MediaFileProviderElementProvider_MediaFileItemToolTip=>T("MediaFileProviderElementProvider.MediaFileItemToolTip"); ///"Organize folders and files" public static string MediaFileProviderElementProvider_OrganizedFilesAndFoldersToolTip=>T("MediaFileProviderElementProvider.OrganizedFilesAndFoldersToolTip"); ///"Error" public static string MediaFileProviderElementProvider_ErrorMessageTitle=>T("MediaFileProviderElementProvider.ErrorMessageTitle"); ///"File '{0}' already exists in folder '{1}'" public static string MediaFileProviderElementProvider_FileAlreadyExistsMessage_Template=>T("MediaFileProviderElementProvider.FileAlreadyExistsMessage"); ///"File '{0}' already exists in folder '{1}'" public static string MediaFileProviderElementProvider_FileAlreadyExistsMessage(object parameter0,object parameter1)=>string.Format(T("MediaFileProviderElementProvider.FileAlreadyExistsMessage"), parameter0,parameter1); ///"Failure" public static string UploadNewMediaFileWorkflow_UploadFailure=>T("UploadNewMediaFileWorkflow.UploadFailure"); ///"The uploaded file must be of the same type as the original. The file you uploaded is of a different type." public static string UploadNewMediaFileWorkflow_UploadFailureMessage=>T("UploadNewMediaFileWorkflow.UploadFailureMessage"); ///"Show Graph" public static string RelationshipGraphActionExecutor_ShowGraph=>T("RelationshipGraphActionExecutor.ShowGraph"); ///"Show relationship graph" public static string RelationshipGraphActionExecutor_ShowGraphToolTip=>T("RelationshipGraphActionExecutor.ShowGraphToolTip"); ///"Show Oriented Graph" public static string RelationshipGraphActionExecutor_ShowOrientedGraph=>T("RelationshipGraphActionExecutor.ShowOrientedGraph"); ///"Show Oriented Relationship graph" public static string RelationshipGraphActionExecutor_ShowOrientedGraphToolTip=>T("RelationshipGraphActionExecutor.ShowOrientedGraphToolTip"); ///"Show Element Information" public static string ShowElementInformationActionExecutor_ShowElementInformation_Label=>T("ShowElementInformationActionExecutor.ShowElementInformation.Label"); ///"Show Element Information" public static string ShowElementInformationActionExecutor_ShowElementInformation_ToolTip=>T("ShowElementInformationActionExecutor.ShowElementInformation.ToolTip"); ///"Search elements" public static string RelationshipGraphActionExecutor_Search=>T("RelationshipGraphActionExecutor.Search"); ///"Search for elements" public static string RelationshipGraphActionExecutor_SearchToolTip=>T("RelationshipGraphActionExecutor.SearchToolTip"); ///"Search elements" public static string RelationshipGraphActionExecutor_SearchElements=>T("RelationshipGraphActionExecutor.SearchElements"); ///"Search for elements" public static string RelationshipGraphActionExecutor_SearchElementsToolTip=>T("RelationshipGraphActionExecutor.SearchElementsToolTip"); ///"Version No." public static string Website_General_LabelVersionNumber=>T("Website.General.LabelVersionNumber"); ///"Restart?" public static string Website_Application_DialogReload_Title=>T("Website.Application.DialogReload.Title"); ///"Restart {applicationname}? All unsaved changes will be lost." public static string Website_Application_DialogReload_Text=>T("Website.Application.DialogReload.Text"); ///"Save Resource?" public static string WebSite_Application_DialogSaveResource_Title=>T("WebSite.Application.DialogSaveResource.Title"); ///""${resourcename}" has been modified. Save changes?" public static string WebSite_Application_DialogSaveResource_Text=>T("WebSite.Application.DialogSaveResource.Text"); ///"Save Resources?" public static string Website_Dialogs_SaveAll_LabelSaveResources=>T("Website.Dialogs.SaveAll.LabelSaveResources"); ///"Unsaved resources" public static string Website_Dialogs_SaveAll_LabelUnsavedResources=>T("Website.Dialogs.SaveAll.LabelUnsavedResources"); ///"Yes" public static string Website_Dialogs_LabelYes=>T("Website.Dialogs.LabelYes"); ///"No" public static string Website_Dialogs_LabelNo=>T("Website.Dialogs.LabelNo"); ///"OK" public static string Website_Dialogs_LabelAccept=>T("Website.Dialogs.LabelAccept"); ///"Cancel" public static string Website_Dialogs_LabelCancel=>T("Website.Dialogs.LabelCancel"); ///"More Info" public static string Website_Dialogs_LabelDisclosure=>T("Website.Dialogs.LabelDisclosure"); ///"About {applicationname}" public static string Website_Dialogs_About_Title=>T("Website.Dialogs.About.Title"); ///"Credits" public static string Website_Dialogs_About_LabelCredits=>T("Website.Dialogs.About.LabelCredits"); ///"Back" public static string Website_Dialogs_About_LabelBack=>T("Website.Dialogs.About.LabelBack"); ///"Credits" public static string Website_Dialogs_About_LabelCredits2=>T("Website.Dialogs.About.LabelCredits2"); ///"No access" public static string Website_Dialogs_NoAccessTitle=>T("Website.Dialogs.NoAccessTitle"); ///"You have not been granted access rights to the system. Please contact your administrator." public static string Website_Dialogs_NoAccessText=>T("Website.Dialogs.NoAccessText"); ///"Unit" public static string Website_Dialogs_ImageEditor_ScaleImage_Unit=>T("Website.Dialogs.ImageEditor.ScaleImage.Unit"); ///"Width" public static string Website_Dialogs_ImageEditor_ScaleImage_Width=>T("Website.Dialogs.ImageEditor.ScaleImage.Width"); ///"Height" public static string Website_Dialogs_ImageEditor_ScaleImage_Height=>T("Website.Dialogs.ImageEditor.ScaleImage.Height"); ///"Scale Image" public static string Website_Dialogs_ImageEditor_ScaleImage_LabelScaleImage=>T("Website.Dialogs.ImageEditor.ScaleImage.LabelScaleImage"); ///"Dimensions" public static string Website_Dialogs_ImageEditor_ScaleImage_LabelDimensions=>T("Website.Dialogs.ImageEditor.ScaleImage.LabelDimensions"); ///"Image Size" public static string Website_Dialogs_ImageEditor_ScaleImage_LabelImageSize=>T("Website.Dialogs.ImageEditor.ScaleImage.LabelImageSize"); ///"Fixed Ratio" public static string Website_Dialogs_ImageEditor_ScaleImage_LabelFixedRatio=>T("Website.Dialogs.ImageEditor.ScaleImage.LabelFixedRatio"); ///"Free Resize" public static string Website_Dialogs_ImageEditor_ScaleImage_LabelFreeResize=>T("Website.Dialogs.ImageEditor.ScaleImage.LabelFreeResize"); ///"Pixels" public static string Website_Dialogs_ImageEditor_ScaleImage_LabelPixels=>T("Website.Dialogs.ImageEditor.ScaleImage.LabelPixels"); ///"Percent" public static string Website_Dialogs_ImageEditor_ScaleImage_LabelPercent=>T("Website.Dialogs.ImageEditor.ScaleImage.LabelPercent"); ///"Login screen" public static string Website_Dialogs_Options_LoginScreen=>T("Website.Dialogs.Options.LoginScreen"); ///"Options" public static string Website_Dialogs_Options_LabelOptions=>T("Website.Dialogs.Options.LabelOptions"); ///"General" public static string Website_Dialogs_Options_LabelGeneral=>T("Website.Dialogs.Options.LabelGeneral"); ///"Advanced" public static string Website_Dialogs_Options_LabelAdvanced=>T("Website.Dialogs.Options.LabelAdvanced"); ///"Login Preferences" public static string Website_Dialogs_Options_LabelLoginPreferences=>T("Website.Dialogs.Options.LabelLoginPreferences"); ///"Fake login screen" public static string Website_Dialogs_Options_LabelFakeLoginScreen=>T("Website.Dialogs.Options.LabelFakeLoginScreen"); ///"No login screen" public static string Website_Dialogs_Options_LabelNoLoginScreen=>T("Website.Dialogs.Options.LabelNoLoginScreen"); ///"Error in web service method " public static string Website_Dialogs_WebServices_Error=>T("Website.Dialogs.WebServices.Error"); ///"Web Service Error" public static string Website_Dialogs_WebServices_LabelWebServiceError=>T("Website.Dialogs.WebServices.LabelWebServiceError"); ///"Insert Where?" public static string Website_Dialogs_SystemTree_DetailedPaste_Title=>T("Website.Dialogs.SystemTree.DetailedPaste.Title"); ///"Position" public static string Website_Dialogs_SystemTree_DetailedPaste_LabelPosition=>T("Website.Dialogs.SystemTree.DetailedPaste.LabelPosition"); ///"Insert before" public static string Website_Dialogs_SystemTree_DetailedPaste_LabelInsertBefore=>T("Website.Dialogs.SystemTree.DetailedPaste.LabelInsertBefore"); ///"Insert after" public static string Website_Dialogs_SystemTree_DetailedPaste_LabelInsertAfter=>T("Website.Dialogs.SystemTree.DetailedPaste.LabelInsertAfter"); ///"Basic view" public static string Website_Dialogs_EditFunction_BasicView=>T("Website.Dialogs.EditFunction.BasicView"); ///"Advanced view" public static string Website_Dialogs_EditFunction_AdvancedView=>T("Website.Dialogs.EditFunction.AdvancedView"); ///"This function has no parameters" public static string Website_Dialogs_EditFunction_BasicView_NoParameters=>T("Website.Dialogs.EditFunction.BasicView.NoParameters"); ///"Edit image" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_LabelTitle=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.LabelTitle"); ///"File" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_LabelFile=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.LabelFile"); ///"Save" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_LabelSave=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.LabelSave"); ///"Save As..." public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_LabelSaveAs=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.LabelSaveAs"); ///"Revert" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_LabelRevert=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.LabelRevert"); ///"View" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_LabelView=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.LabelView"); ///"Zoom" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_LabelZoom=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.LabelZoom"); ///"Zoom In" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_LabelZoomIn=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.LabelZoomIn"); ///"Zoom Out" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_LabelZoomOut=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.LabelZoomOut"); ///"800%" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_Label800=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.Label800"); ///"400%" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_Label400=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.Label400"); ///"200%" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_Label200=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.Label200"); ///"100%" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_Label100=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.Label100"); ///"50%" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_Label50=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.Label50"); ///"25%" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_Label25=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.Label25"); ///"12%" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_Label12=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.Label12"); ///"Image" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_LabelImage=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.LabelImage"); ///"Transform" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_LabelTransform=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.LabelTransform"); ///"Flip Horizontally" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_LabelFlipHorizontal=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.LabelFlipHorizontal"); ///"Flip Vertically" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_LabelFlipVertical=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.LabelFlipVertical"); ///"Rotate 90 Degrees CW" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_LabelRotate90CW=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.LabelRotate90CW"); ///"Rotate 90 Degrees CCW" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_LabelRotate90CCW=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.LabelRotate90CCW"); ///"Rotate 180 Degrees" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_LabelRotate180=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.LabelRotate180"); ///"Scale Image..." public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_LabelScale=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.LabelScale"); ///"Crop Image" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_LabelCrop=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.LabelCrop"); ///"Select" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_ToolBox_ToolTipSelect=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.ToolBox.ToolTipSelect"); ///"Zoom" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_ToolBox_ToolTipZoom=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.ToolBox.ToolTipZoom"); ///"Save" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_ToolBar_LabelSave=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.ToolBar.LabelSave"); ///"Scale image" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_ToolBar_LabelScale=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.ToolBar.LabelScale"); ///"Crop image" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_ToolBar_LabelCrop=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.ToolBar.LabelCrop"); ///"Undo" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_ToolBar_LabelUndo=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.ToolBar.LabelUndo"); ///"Redo" public static string Website_Content_Views_Editors_ImageEditor_ImageEditor_ToolBar_LabelRedo=>T("Website.Content.Views.Editors.ImageEditor.ImageEditor.ToolBar.LabelRedo"); ///"Permissions" public static string Website_Content_Views_Editors_PermissionEditor_LabelTitle=>T("Website.Content.Views.Editors.PermissionEditor.LabelTitle"); ///"Users" public static string Website_Content_Views_Editors_PermissionEditor_LabelTabUsers=>T("Website.Content.Views.Editors.PermissionEditor.LabelTabUsers"); ///"User Groups" public static string Website_Content_Views_Editors_PermissionEditor_LabelTabUserGroups=>T("Website.Content.Views.Editors.PermissionEditor.LabelTabUserGroups"); ///"Save" public static string Website_Content_Views_Editors_PermissionEditor_LabelButtonSave=>T("Website.Content.Views.Editors.PermissionEditor.LabelButtonSave"); ///"Go back one page" public static string Website_Content_Views_Help_ToolTipBack=>T("Website.Content.Views.Help.ToolTipBack"); ///"Go forward one page" public static string Website_Content_Views_Help_ToolTipForward=>T("Website.Content.Views.Help.ToolTipForward"); ///"Refresh page" public static string Website_Content_Views_Help_ToolTipRefresh=>T("Website.Content.Views.Help.ToolTipRefresh"); ///"Contents" public static string Website_Content_Views_Help_LabelContents=>T("Website.Content.Views.Help.LabelContents"); ///"Help contents" public static string Website_Content_Views_Help_ToolTipContents=>T("Website.Content.Views.Help.ToolTipContents"); ///"Collapse All" public static string Website_Content_Views_SystemView_ToolTipCollapseAll=>T("Website.Content.Views.SystemView.ToolTipCollapseAll"); ///"Link with Editor" public static string Website_Content_Views_SystemView_ToolTipLinkWithEditor=>T("Website.Content.Views.SystemView.ToolTipLinkWithEditor"); ///"New Search..." public static string Website_Content_Views_Search_Search_LabelNewSearch=>T("Website.Content.Views.Search.Search.LabelNewSearch"); ///"Formatted" public static string Website_Content_Views_ViewSource_LabelFormatted=>T("Website.Content.Views.ViewSource.LabelFormatted"); ///"Raw" public static string Website_Content_Views_ViewSource_LabelRaw=>T("Website.Content.Views.ViewSource.LabelRaw"); ///"Server Log" public static string ServerLog_Element_Label=>T("ServerLog.Element.Label"); ///"The server log contain security and system health related messages." public static string ServerLog_Element_Tooltip=>T("ServerLog.Element.Tooltip"); ///"View Server Log" public static string ServerLog_Element_View_Label=>T("ServerLog.Element.View.Label"); ///"View recent server events" public static string ServerLog_Element_View_Tooltip=>T("ServerLog.Element.View.Tooltip"); ///"Server Log" public static string ServerLog_LabelTitle=>T("ServerLog.LabelTitle"); ///"Delete old" public static string ServerLog_LabelButtonDeleteOld=>T("ServerLog.LabelButtonDeleteOld"); ///"Refresh" public static string ServerLog_LabelButtonRefresh=>T("ServerLog.LabelButtonRefresh"); ///"No log data available..." public static string ServerLog_EmptyLabel=>T("ServerLog.EmptyLabel"); ///"Only the {0} most recent log entries are shown. Open the log for more entries." public static string ServerLog_LogEntriesRemovedBrowserViewLabel_Template=>T("ServerLog.LogEntriesRemovedBrowserViewLabel"); ///"Only the {0} most recent log entries are shown. Open the log for more entries." public static string ServerLog_LogEntriesRemovedBrowserViewLabel(object parameter0)=>string.Format(T("ServerLog.LogEntriesRemovedBrowserViewLabel"), parameter0); ///"Only the {0} most recent log entries are shown. {1} entries exists for the current search. Either narrow the search or use the log viewer tool from http://docs.composite.net/Configuration/Logging for full log access." public static string ServerLog_LogEntriesRemovedLabel_Template=>T("ServerLog.LogEntriesRemovedLabel"); ///"Only the {0} most recent log entries are shown. {1} entries exists for the current search. Either narrow the search or use the log viewer tool from http://docs.composite.net/Configuration/Logging for full log access." public static string ServerLog_LogEntriesRemovedLabel(object parameter0,object parameter1)=>string.Format(T("ServerLog.LogEntriesRemovedLabel"), parameter0,parameter1); ///"Date" public static string ServerLog_LogEntry_DateLabel=>T("ServerLog.LogEntry.DateLabel"); ///"Message" public static string ServerLog_LogEntry_MessageLabel=>T("ServerLog.LogEntry.MessageLabel"); ///"Title" public static string ServerLog_LogEntry_TitleLabel=>T("ServerLog.LogEntry.TitleLabel"); ///"EventType" public static string ServerLog_LogEntry_EventTypeLabel=>T("ServerLog.LogEntry.EventTypeLabel"); ///"Verbose" public static string ServerLog_Severity_Verbose=>T("ServerLog.Severity.Verbose"); ///"Information" public static string ServerLog_Severity_Information=>T("ServerLog.Severity.Information"); ///"Warning" public static string ServerLog_Severity_Warning=>T("ServerLog.Severity.Warning"); ///"Error" public static string ServerLog_Severity_Error=>T("ServerLog.Severity.Error"); ///"Critical" public static string ServerLog_Severity_Critical=>T("ServerLog.Severity.Critical"); ///"Refresh" public static string FunctionDocumentation_LabelButtonRefresh=>T("FunctionDocumentation.LabelButtonRefresh"); ///"Print" public static string FunctionDocumentation_LabelButtonPrint=>T("FunctionDocumentation.LabelButtonPrint"); ///"Execution Ended" public static string Website_FlowUICompleted_ExecutionEndedTitle=>T("Website.FlowUICompleted.ExecutionEndedTitle"); ///"The action executed in this window has ended." public static string Website_FlowUICompleted_ExecutionEndedMessage=>T("Website.FlowUICompleted.ExecutionEndedMessage"); ///"Server Error" public static string Website_ServerError_ServerErrorTitle=>T("Website.ServerError.ServerErrorTitle"); ///"An unfortunate error has occurred." public static string Website_ServerError_ServerErrorMessage=>T("Website.ServerError.ServerErrorMessage"); ///"Details" public static string Website_ServerError_ServerErrorDetails=>T("Website.ServerError.ServerErrorDetails"); ///"License Violation" public static string Website_LicenseViolation_LicenseViolationTitle=>T("Website.LicenseViolation.LicenseViolationTitle"); ///"The requested action is in violates with your current license." public static string Website_LicenseViolation_LicenseViolationMessage=>T("Website.LicenseViolation.LicenseViolationMessage"); ///"Flash options" public static string Website_Templates_WysiwygEditorPlugins_MediaFlashOptions_LabelFlashOptions=>T("Website.Templates.WysiwygEditorPlugins.MediaFlashOptions.LabelFlashOptions"); ///"High" public static string Website_Templates_WysiwygEditorPlugins_MediaFlashOptions_LabelHigh=>T("Website.Templates.WysiwygEditorPlugins.MediaFlashOptions.LabelHigh"); ///"Low" public static string Website_Templates_WysiwygEditorPlugins_MediaFlashOptions_LabelLow=>T("Website.Templates.WysiwygEditorPlugins.MediaFlashOptions.LabelLow"); ///"Autohigh" public static string Website_Templates_WysiwygEditorPlugins_MediaFlashOptions_LabelAutohigh=>T("Website.Templates.WysiwygEditorPlugins.MediaFlashOptions.LabelAutohigh"); ///"Autolow" public static string Website_Templates_WysiwygEditorPlugins_MediaFlashOptions_LabelAutolow=>T("Website.Templates.WysiwygEditorPlugins.MediaFlashOptions.LabelAutolow"); ///"Best" public static string Website_Templates_WysiwygEditorPlugins_MediaFlashOptions_LabelBest=>T("Website.Templates.WysiwygEditorPlugins.MediaFlashOptions.LabelBest"); ///"Window" public static string Website_Templates_WysiwygEditorPlugins_MediaFlashOptions_LabelWindow=>T("Website.Templates.WysiwygEditorPlugins.MediaFlashOptions.LabelWindow"); ///"Opaque" public static string Website_Templates_WysiwygEditorPlugins_MediaFlashOptions_LabelOpaque=>T("Website.Templates.WysiwygEditorPlugins.MediaFlashOptions.LabelOpaque"); ///"Transparent" public static string Website_Templates_WysiwygEditorPlugins_MediaFlashOptions_LabelTransparent=>T("Website.Templates.WysiwygEditorPlugins.MediaFlashOptions.LabelTransparent"); ///"Showall" public static string Website_Templates_WysiwygEditorPlugins_MediaFlashOptions_LabelShowall=>T("Website.Templates.WysiwygEditorPlugins.MediaFlashOptions.LabelShowall"); ///"Noborder" public static string Website_Templates_WysiwygEditorPlugins_MediaFlashOptions_LabelNoborder=>T("Website.Templates.WysiwygEditorPlugins.MediaFlashOptions.LabelNoborder"); ///"Exactfit" public static string Website_Templates_WysiwygEditorPlugins_MediaFlashOptions_LabelExactfit=>T("Website.Templates.WysiwygEditorPlugins.MediaFlashOptions.LabelExactfit"); ///"Auto play" public static string Website_Templates_WysiwygEditorPlugins_MediaFlashOptions_LabelAutoPlay=>T("Website.Templates.WysiwygEditorPlugins.MediaFlashOptions.LabelAutoPlay"); ///"Loop" public static string Website_Templates_WysiwygEditorPlugins_MediaFlashOptions_LabelLoop=>T("Website.Templates.WysiwygEditorPlugins.MediaFlashOptions.LabelLoop"); ///"Show menu" public static string Website_Templates_WysiwygEditorPlugins_MediaFlashOptions_LabelShowMenu=>T("Website.Templates.WysiwygEditorPlugins.MediaFlashOptions.LabelShowMenu"); ///"SWLiveConnect" public static string Website_Templates_WysiwygEditorPlugins_MediaFlashOptions_LabelSWLiveConnect=>T("Website.Templates.WysiwygEditorPlugins.MediaFlashOptions.LabelSWLiveConnect"); ///"Quicktime options" public static string Website_Templates_WysiwygEditorPlugins_MediaQuickTimeOptions_LabelQuickTimeOptions=>T("Website.Templates.WysiwygEditorPlugins.MediaQuickTimeOptions.LabelQuickTimeOptions"); ///"Loop" public static string Website_Templates_WysiwygEditorPlugins_MediaQuickTimeOptions_LabelLoop=>T("Website.Templates.WysiwygEditorPlugins.MediaQuickTimeOptions.LabelLoop"); ///"Cache" public static string Website_Templates_WysiwygEditorPlugins_MediaQuickTimeOptions_LabelCache=>T("Website.Templates.WysiwygEditorPlugins.MediaQuickTimeOptions.LabelCache"); ///"No correction" public static string Website_Templates_WysiwygEditorPlugins_MediaQuickTimeOptions_LabelNoCorrection=>T("Website.Templates.WysiwygEditorPlugins.MediaQuickTimeOptions.LabelNoCorrection"); ///"Kiosk mode" public static string Website_Templates_WysiwygEditorPlugins_MediaQuickTimeOptions_LabelKioskMode=>T("Website.Templates.WysiwygEditorPlugins.MediaQuickTimeOptions.LabelKioskMode"); ///"Play every frame" public static string Website_Templates_WysiwygEditorPlugins_MediaQuickTimeOptions_LabelPlayEveryFrame=>T("Website.Templates.WysiwygEditorPlugins.MediaQuickTimeOptions.LabelPlayEveryFrame"); ///"Auto play" public static string Website_Templates_WysiwygEditorPlugins_MediaQuickTimeOptions_LabelAutoPlay=>T("Website.Templates.WysiwygEditorPlugins.MediaQuickTimeOptions.LabelAutoPlay"); ///"Controller" public static string Website_Templates_WysiwygEditorPlugins_MediaQuickTimeOptions_LabelController=>T("Website.Templates.WysiwygEditorPlugins.MediaQuickTimeOptions.LabelController"); ///"Enable Javascript" public static string Website_Templates_WysiwygEditorPlugins_MediaQuickTimeOptions_LabelEnableJavaScript=>T("Website.Templates.WysiwygEditorPlugins.MediaQuickTimeOptions.LabelEnableJavaScript"); ///"AutoHREF" public static string Website_Templates_WysiwygEditorPlugins_MediaQuickTimeOptions_LabelAutoHRef=>T("Website.Templates.WysiwygEditorPlugins.MediaQuickTimeOptions.LabelAutoHRef"); ///"Target cache" public static string Website_Templates_WysiwygEditorPlugins_MediaQuickTimeOptions_LabelTargetCache=>T("Website.Templates.WysiwygEditorPlugins.MediaQuickTimeOptions.LabelTargetCache"); ///"Shockwave options" public static string Website_Templates_WysiwygEditorPlugins_MediaShockWaveOptions_LabelShockWaveOptions=>T("Website.Templates.WysiwygEditorPlugins.MediaShockWaveOptions.LabelShockWaveOptions"); ///"High" public static string Website_Templates_WysiwygEditorPlugins_MediaShockWaveOptions_LabelHigh=>T("Website.Templates.WysiwygEditorPlugins.MediaShockWaveOptions.LabelHigh"); ///"Low" public static string Website_Templates_WysiwygEditorPlugins_MediaShockWaveOptions_LabelLow=>T("Website.Templates.WysiwygEditorPlugins.MediaShockWaveOptions.LabelLow"); ///"Autohigh" public static string Website_Templates_WysiwygEditorPlugins_MediaShockWaveOptions_LabelAutoHigh=>T("Website.Templates.WysiwygEditorPlugins.MediaShockWaveOptions.LabelAutoHigh"); ///"Autolow" public static string Website_Templates_WysiwygEditorPlugins_MediaShockWaveOptions_LabelAutoLow=>T("Website.Templates.WysiwygEditorPlugins.MediaShockWaveOptions.LabelAutoLow"); ///"Best" public static string Website_Templates_WysiwygEditorPlugins_MediaShockWaveOptions_LabelBest=>T("Website.Templates.WysiwygEditorPlugins.MediaShockWaveOptions.LabelBest"); ///"Window" public static string Website_Templates_WysiwygEditorPlugins_MediaShockWaveOptions_LabelWindow=>T("Website.Templates.WysiwygEditorPlugins.MediaShockWaveOptions.LabelWindow"); ///"Opaque" public static string Website_Templates_WysiwygEditorPlugins_MediaShockWaveOptions_LabelOpaque=>T("Website.Templates.WysiwygEditorPlugins.MediaShockWaveOptions.LabelOpaque"); ///"Transparent" public static string Website_Templates_WysiwygEditorPlugins_MediaShockWaveOptions_LabelTransparent=>T("Website.Templates.WysiwygEditorPlugins.MediaShockWaveOptions.LabelTransparent"); ///"Showall" public static string Website_Templates_WysiwygEditorPlugins_MediaShockWaveOptions_LabelShowAll=>T("Website.Templates.WysiwygEditorPlugins.MediaShockWaveOptions.LabelShowAll"); ///"Noborder" public static string Website_Templates_WysiwygEditorPlugins_MediaShockWaveOptions_LabelNoBorder=>T("Website.Templates.WysiwygEditorPlugins.MediaShockWaveOptions.LabelNoBorder"); ///"Exactfit" public static string Website_Templates_WysiwygEditorPlugins_MediaShockWaveOptions_LabelExactFit=>T("Website.Templates.WysiwygEditorPlugins.MediaShockWaveOptions.LabelExactFit"); ///"Auto play" public static string Website_Templates_WysiwygEditorPlugins_MediaShockWaveOptions_LabelAutoPlay=>T("Website.Templates.WysiwygEditorPlugins.MediaShockWaveOptions.LabelAutoPlay"); ///"Loop" public static string Website_Templates_WysiwygEditorPlugins_MediaShockWaveOptions_LabelLoop=>T("Website.Templates.WysiwygEditorPlugins.MediaShockWaveOptions.LabelLoop"); ///"Show menu" public static string Website_Templates_WysiwygEditorPlugins_MediaShockWaveOptions_LabelShowMenu=>T("Website.Templates.WysiwygEditorPlugins.MediaShockWaveOptions.LabelShowMenu"); ///"SWLiveConnect" public static string Website_Templates_WysiwygEditorPlugins_MediaShockWaveOptions_LabelSWLiveConnect=>T("Website.Templates.WysiwygEditorPlugins.MediaShockWaveOptions.LabelSWLiveConnect"); ///"Quicktime options" public static string Website_Templates_WysiwygEditorPlugins_MediaWinMediaOptions_LabelQuickTimeOptions=>T("Website.Templates.WysiwygEditorPlugins.MediaWinMediaOptions.LabelQuickTimeOptions"); ///"Auto Start" public static string Website_Templates_WysiwygEditorPlugins_MediaWinMediaOptions_LabelAutoStart=>T("Website.Templates.WysiwygEditorPlugins.MediaWinMediaOptions.LabelAutoStart"); ///"Show menu" public static string Website_Templates_WysiwygEditorPlugins_MediaWinMediaOptions_LabelShowMenu=>T("Website.Templates.WysiwygEditorPlugins.MediaWinMediaOptions.LabelShowMenu"); ///"Invoke URLs" public static string Website_Templates_WysiwygEditorPlugins_MediaWinMediaOptions_LabelInvokeURLs=>T("Website.Templates.WysiwygEditorPlugins.MediaWinMediaOptions.LabelInvokeURLs"); ///"Stretch to fit" public static string Website_Templates_WysiwygEditorPlugins_MediaWinMediaOptions_LabelStretchToFit=>T("Website.Templates.WysiwygEditorPlugins.MediaWinMediaOptions.LabelStretchToFit"); ///"Enabled" public static string Website_Templates_WysiwygEditorPlugins_MediaWinMediaOptions_LabelEnabled=>T("Website.Templates.WysiwygEditorPlugins.MediaWinMediaOptions.LabelEnabled"); ///"Fullscreen" public static string Website_Templates_WysiwygEditorPlugins_MediaWinMediaOptions_LabelFullScreen=>T("Website.Templates.WysiwygEditorPlugins.MediaWinMediaOptions.LabelFullScreen"); ///"Mute" public static string Website_Templates_WysiwygEditorPlugins_MediaWinMediaOptions_LabelMute=>T("Website.Templates.WysiwygEditorPlugins.MediaWinMediaOptions.LabelMute"); ///"Windowless video" public static string Website_Templates_WysiwygEditorPlugins_MediaWinMediaOptions_LabelWindowLessVideo=>T("Website.Templates.WysiwygEditorPlugins.MediaWinMediaOptions.LabelWindowLessVideo"); ///"Save" public static string Website_App_LabelSave=>T("Website.App.LabelSave"); ///"Save and Publish" public static string Website_App_LabelSaveAndPublish=>T("Website.App.LabelSaveAndPublish"); ///"Close Tab" public static string Website_App_LabelCloseTab=>T("Website.App.LabelCloseTab"); ///"Close Others" public static string Website_App_LabelCloseOthers=>T("Website.App.LabelCloseOthers"); ///"Refresh View" public static string Website_App_LabelRefreshView=>T("Website.App.LabelRefreshView"); ///"Make Dirty" public static string Website_App_LabelMakeDirty=>T("Website.App.LabelMakeDirty"); ///"View Source" public static string Website_App_LabelViewSource=>T("Website.App.LabelViewSource"); ///"View Generated" public static string Website_App_LabelViewGenerated=>T("Website.App.LabelViewGenerated"); ///"View Serialized" public static string Website_App_LabelViewSerialized=>T("Website.App.LabelViewSerialized"); ///"Close" public static string Website_App_LabelClose=>T("Website.App.LabelClose"); ///"File" public static string Website_App_LabelFile=>T("Website.App.LabelFile"); ///"Close" public static string Website_App_LabelFileClose=>T("Website.App.LabelFileClose"); ///"Close All" public static string Website_App_LabelFileCloseAll=>T("Website.App.LabelFileCloseAll"); ///"Save All..." public static string Website_App_LabelFileSaveAll=>T("Website.App.LabelFileSaveAll"); ///"Sign out" public static string Website_App_LabelFileExit=>T("Website.App.LabelFileExit"); ///"View" public static string Website_App_LabelView=>T("Website.App.LabelView"); ///"Composite Start" public static string Website_App_LabelViewCompositeStart=>T("Website.App.LabelViewCompositeStart"); ///"System Log" public static string Website_App_LabelSystemLog=>T("Website.App.LabelSystemLog"); ///"Developer Panel" public static string Website_App_LabelDeveloperPanel=>T("Website.App.LabelDeveloperPanel"); ///"Tools" public static string Website_App_LabelTools=>T("Website.App.LabelTools"); ///"Help" public static string Website_App_LabelHelp=>T("Website.App.LabelHelp"); ///"Settings" public static string Website_App_LabelSettings=>T("Website.App.LabelSettings"); ///"Help Contents" public static string Website_App_LabelHelpContents=>T("Website.App.LabelHelpContents"); ///"Provide Feedback..." public static string Website_App_LabelFeedback=>T("Website.App.LabelFeedback"); ///"About {applicationname}" public static string Website_App_LabelAbout=>T("Website.App.LabelAbout"); ///"Cut" public static string Website_App_LabelCut=>T("Website.App.LabelCut"); ///"Copy" public static string Website_App_LabelCopy=>T("Website.App.LabelCopy"); ///"Paste" public static string Website_App_LabelPaste=>T("Website.App.LabelPaste"); ///"Refresh" public static string Website_App_LabelRefresh=>T("Website.App.LabelRefresh"); ///"Only first {0} elements are shown in the tree." public static string Website_App_LimitedElementsShown_Template=>T("Website.App.LimitedElementsShown"); ///"Only first {0} elements are shown in the tree." public static string Website_App_LimitedElementsShown(object parameter0)=>string.Format(T("Website.App.LimitedElementsShown"), parameter0); ///"Loading..." public static string Website_App_LabelLoading=>T("Website.App.LabelLoading"); ///"Loaded" public static string Website_App_LabelLoaded=>T("Website.App.LabelLoaded"); ///"Saved" public static string Website_App_LabelSaved=>T("Website.App.LabelSaved"); ///"Minimize" public static string Website_App_ToolTipMinimize=>T("Website.App.ToolTipMinimize"); ///"Maximize" public static string Website_App_ToolTipMaximize=>T("Website.App.ToolTipMaximize"); ///"Restore" public static string Website_App_ToolTipUnMaximize=>T("Website.App.ToolTipUnMaximize"); ///"Restore" public static string Website_App_ToolTipUnMinimize=>T("Website.App.ToolTipUnMinimize"); ///"Close" public static string Website_App_ToolTipClose=>T("Website.App.ToolTipClose"); ///"Opening {0}..." public static string Website_App_StatusBar_Opening_Template=>T("Website.App.StatusBar.Opening"); ///"Opening {0}..." public static string Website_App_StatusBar_Opening(object parameter0)=>string.Format(T("Website.App.StatusBar.Opening"), parameter0); ///"Refreshing {0}..." public static string Website_App_StatusBar_Refreshing_Template=>T("Website.App.StatusBar.Refreshing"); ///"Refreshing {0}..." public static string Website_App_StatusBar_Refreshing(object parameter0)=>string.Format(T("Website.App.StatusBar.Refreshing"), parameter0); ///"Loading {0}..." public static string Website_App_StatusBar_Loading_Template=>T("Website.App.StatusBar.Loading"); ///"Loading {0}..." public static string Website_App_StatusBar_Loading(object parameter0)=>string.Format(T("Website.App.StatusBar.Loading"), parameter0); ///"Error" public static string Website_App_StatusBar_Error=>T("Website.App.StatusBar.Error"); ///"Warning" public static string Website_App_StatusBar_Warn=>T("Website.App.StatusBar.Warn"); ///"Working..." public static string Website_App_StatusBar_Busy=>T("Website.App.StatusBar.Busy"); ///"Ready!" public static string Website_App_StatusBar_Ready=>T("Website.App.StatusBar.Ready"); ///"Error in" public static string Website_App_StatusBar_ErrorInField=>T("Website.App.StatusBar.ErrorInField"); ///"Add New Media File" public static string Website_Forms_Administrative_AddNewMediaFile_Layout_Label=>T("Website.Forms.Administrative.AddNewMediaFile.Layout.Label"); ///"Filename" public static string Website_Forms_Administrative_AddNewMediaFile_FileUpload_Label=>T("Website.Forms.Administrative.AddNewMediaFile.FileUpload.Label"); ///"Select the file to upload" public static string Website_Forms_Administrative_AddNewMediaFile_FileUpload_Help=>T("Website.Forms.Administrative.AddNewMediaFile.FileUpload.Help"); ///"Allow overwrite" public static string Website_Forms_Administrative_AddNewMediaFile_OverwriteCheckBox_Label=>T("Website.Forms.Administrative.AddNewMediaFile.OverwriteCheckBox.Label"); ///"Replace existing file" public static string Website_Forms_Administrative_AddNewMediaFile_OverwriteCheckBox_Help=>T("Website.Forms.Administrative.AddNewMediaFile.OverwriteCheckBox.Help"); ///"Filename" public static string Website_Forms_Administrative_AddNewMediaFile_FilenameTextBox_Label=>T("Website.Forms.Administrative.AddNewMediaFile.FilenameTextBox.Label"); ///"The name of the file in the media library" public static string Website_Forms_Administrative_AddNewMediaFile_FilenameTextBox_Help=>T("Website.Forms.Administrative.AddNewMediaFile.FilenameTextBox.Help"); ///"Title" public static string Website_Forms_Administrative_AddNewMediaFile_TitleTextBox_Label=>T("Website.Forms.Administrative.AddNewMediaFile.TitleTextBox.Label"); ///"Use this field for an image title" public static string Website_Forms_Administrative_AddNewMediaFile_TitleTextBox_Help=>T("Website.Forms.Administrative.AddNewMediaFile.TitleTextBox.Help"); ///"Description" public static string Website_Forms_Administrative_AddNewMediaFile_DescriptionTextBox_Label=>T("Website.Forms.Administrative.AddNewMediaFile.DescriptionTextBox.Label"); ///"Use this field for a short description of the image" public static string Website_Forms_Administrative_AddNewMediaFile_DescriptionTextBox_Help=>T("Website.Forms.Administrative.AddNewMediaFile.DescriptionTextBox.Help"); ///"Please select a file to upload" public static string Website_Forms_Administrative_AddNewMediaFile_MissingUploadedFile_Message=>T("Website.Forms.Administrative.AddNewMediaFile.MissingUploadedFile.Message"); ///"A file with the same name exists. Check allow overwrite or change the filename" public static string Website_Forms_Administrative_AddNewMediaFile_FileExists_Message=>T("Website.Forms.Administrative.AddNewMediaFile.FileExists.Message"); ///"The total length of the filename (folder and filename) is too long" public static string Website_Forms_Administrative_AddNewMediaFile_TotalFilenameToLong_Message=>T("Website.Forms.Administrative.AddNewMediaFile.TotalFilenameToLong.Message"); ///"Add tags to your media item seperated by a comma (,)" public static string Website_Forms_Administrative_AddNewMediaFile_TagsTextBox_Help=>T("Website.Forms.Administrative.AddNewMediaFile.TagsTextBox.Help"); ///"Tags" public static string Website_Forms_Administrative_AddNewMediaFile_TagsTextBox_Label=>T("Website.Forms.Administrative.AddNewMediaFile.TagsTextBox.Label"); ///"Add New Media Folder" public static string Website_Forms_Administrative_AddNewMediaFolder_Label_AddNewMediaFolder=>T("Website.Forms.Administrative.AddNewMediaFolder.Label.AddNewMediaFolder"); ///"Folder Name" public static string Website_Forms_Administrative_AddNewMediaFolder_LabelFolderName=>T("Website.Forms.Administrative.AddNewMediaFolder.LabelFolderName"); ///"" public static string Website_Forms_Administrative_AddNewMediaFolder_HelpFolderName=>T("Website.Forms.Administrative.AddNewMediaFolder.HelpFolderName"); ///"Title" public static string Website_Forms_Administrative_AddNewMediaFolder_LabelTitle=>T("Website.Forms.Administrative.AddNewMediaFolder.LabelTitle"); ///"" public static string Website_Forms_Administrative_AddNewMediaFolder_HelpTitle=>T("Website.Forms.Administrative.AddNewMediaFolder.HelpTitle"); ///"Description" public static string Website_Forms_Administrative_AddNewMediaFolder_LabelDescription=>T("Website.Forms.Administrative.AddNewMediaFolder.LabelDescription"); ///"" public static string Website_Forms_Administrative_AddNewMediaFolder_HelpDescription=>T("Website.Forms.Administrative.AddNewMediaFolder.HelpDescription"); ///"The folder already exists" public static string Website_Forms_Administrative_AddNewMediaFolder_FolderNameAlreadyUsed=>T("Website.Forms.Administrative.AddNewMediaFolder.FolderNameAlreadyUsed"); ///"The total length of the folder name is too long" public static string Website_Forms_Administrative_AddNewMediaFolder_FolderNameTooLong=>T("Website.Forms.Administrative.AddNewMediaFolder.FolderNameTooLong"); ///"The folder name can not only be '/' or '\'" public static string Website_Forms_Administrative_AddNewMediaFolder_FolderNotOnlySlash=>T("Website.Forms.Administrative.AddNewMediaFolder.FolderNotOnlySlash"); ///"Upload Multiple Files via a Zip File" public static string Website_Forms_Administrative_AddZipMediaFile_LabelDialog=>T("Website.Forms.Administrative.AddZipMediaFile.LabelDialog"); ///"Zip file" public static string Website_Forms_Administrative_AddZipMediaFile_LabelFile=>T("Website.Forms.Administrative.AddZipMediaFile.LabelFile"); ///"Create a Zip file (right click local folder and select Send to -> Compressed folder) and select it using the Browse button" public static string Website_Forms_Administrative_AddZipMediaFile_HelpFile=>T("Website.Forms.Administrative.AddZipMediaFile.HelpFile"); ///"Create folders" public static string Website_Forms_Administrative_AddZipMediaFile_LabelRecreateStructure=>T("Website.Forms.Administrative.AddZipMediaFile.LabelRecreateStructure"); ///"Selecting this option will copy the exact folder structure from your Zip file" public static string Website_Forms_Administrative_AddZipMediaFile_HelpRecreateStructure=>T("Website.Forms.Administrative.AddZipMediaFile.HelpRecreateStructure"); ///"Extract folders from Zip file" public static string Website_Forms_Administrative_AddZipMediaFile_LabelRecreateStructureCheckBox=>T("Website.Forms.Administrative.AddZipMediaFile.LabelRecreateStructureCheckBox"); ///"Overwrite existing" public static string Website_Forms_Administrative_AddZipMediaFile_LabelOverwriteExsisting=>T("Website.Forms.Administrative.AddZipMediaFile.LabelOverwriteExsisting"); ///"Selecting this option will overwrite existing files in the media archive with matching file names" public static string Website_Forms_Administrative_AddZipMediaFile_HelpOverwriteExsisting=>T("Website.Forms.Administrative.AddZipMediaFile.HelpOverwriteExsisting"); ///"Error" public static string Website_Forms_Administrative_AddZipMediaFile_Error_Title=>T("Website.Forms.Administrative.AddZipMediaFile.Error.Title"); ///"Overwrite existing files" public static string Website_Forms_Administrative_AddZipMediaFile_LabelOverwriteExsistingCheckBox=>T("Website.Forms.Administrative.AddZipMediaFile.LabelOverwriteExsistingCheckBox"); ///"Please select a file to upload" public static string Website_Forms_Administrative_AddZipMediaFile_MissingUploadedFile_Message=>T("Website.Forms.Administrative.AddZipMediaFile.MissingUploadedFile.Message"); ///"Please use the normal upload command to upload .docx files" public static string Website_Forms_Administrative_AddZipMediaFile_CannotUploadDocxFile=>T("Website.Forms.Administrative.AddZipMediaFile.CannotUploadDocxFile"); ///"The selected file was not a correct zip file" public static string Website_Forms_Administrative_AddZipMediaFile_WrongUploadedFile_Message=>T("Website.Forms.Administrative.AddZipMediaFile.WrongUploadedFile.Message"); ///"Function search" public static string Website_Forms_Administrative_AllFunctionsElementProviderSearchForm_LabelFunctionSearch=>T("Website.Forms.Administrative.AllFunctionsElementProviderSearchForm.LabelFunctionSearch"); ///"Keyword" public static string Website_Forms_Administrative_AllFunctionsElementProviderSearchForm_LabelKeyword=>T("Website.Forms.Administrative.AllFunctionsElementProviderSearchForm.LabelKeyword"); ///"Write a keyword to search for." public static string Website_Forms_Administrative_AllFunctionsElementProviderSearchForm_LabelKeywordHelp=>T("Website.Forms.Administrative.AllFunctionsElementProviderSearchForm.LabelKeywordHelp"); ///"Return type" public static string Website_Forms_Administrative_AllFunctionsElementProviderSearchForm_LabelReturnType=>T("Website.Forms.Administrative.AllFunctionsElementProviderSearchForm.LabelReturnType"); ///"Select a return type to search for." public static string Website_Forms_Administrative_AllFunctionsElementProviderSearchForm_LabelReturnTypeHelp=>T("Website.Forms.Administrative.AllFunctionsElementProviderSearchForm.LabelReturnTypeHelp"); ///"Delete This File?" public static string Website_Forms_Administrative_DeleteMediaFile_LabelFieldGroup=>T("Website.Forms.Administrative.DeleteMediaFile.LabelFieldGroup"); ///"Delete this file?" public static string Website_Forms_Administrative_DeleteMediaFile_Text=>T("Website.Forms.Administrative.DeleteMediaFile.Text"); ///"Deleting a file" public static string Website_Forms_Administrative_DeleteMediaFile_DeleteDataConfirmationHeader=>T("Website.Forms.Administrative.DeleteMediaFile.DeleteDataConfirmationHeader"); ///"There is some referenced data that will also be deleted, do you want to continue?" public static string Website_Forms_Administrative_DeleteMediaFile_DeleteDataConfirmationText=>T("Website.Forms.Administrative.DeleteMediaFile.DeleteDataConfirmationText"); ///"Delete This Folder?" public static string Website_Forms_Administrative_DeleteMediaFolder_LabelFieldGroup=>T("Website.Forms.Administrative.DeleteMediaFolder.LabelFieldGroup"); ///"Delete this folder?" public static string Website_Forms_Administrative_DeleteMediaFolder_Text=>T("Website.Forms.Administrative.DeleteMediaFolder.Text"); ///"This folder contains one or more files or subfolders. Deleting this folder will also delete all sub files and folders. Delete this folder?" public static string Website_Forms_Administrative_DeleteMediaFolder_HasChildringText=>T("Website.Forms.Administrative.DeleteMediaFolder.HasChildringText"); ///"Media Properties" public static string Website_Forms_Administrative_EditMediaFile_LabelFieldGroup=>T("Website.Forms.Administrative.EditMediaFile.LabelFieldGroup"); ///"Title" public static string Website_Forms_Administrative_EditMediaFile_LabelTitle=>T("Website.Forms.Administrative.EditMediaFile.LabelTitle"); ///"A human friendly short text describing the content of the media file" public static string Website_Forms_Administrative_EditMediaFile_HelpTitle=>T("Website.Forms.Administrative.EditMediaFile.HelpTitle"); ///"File Name" public static string Website_Forms_Administrative_EditMediaFile_LabelFileName=>T("Website.Forms.Administrative.EditMediaFile.LabelFileName"); ///"The file name to use when the media file is downloaded." public static string Website_Forms_Administrative_EditMediaFile_HelpFileName=>T("Website.Forms.Administrative.EditMediaFile.HelpFileName"); ///"Description" public static string Website_Forms_Administrative_EditMediaFile_LabelDescription=>T("Website.Forms.Administrative.EditMediaFile.LabelDescription"); ///"A description of the media file content" public static string Website_Forms_Administrative_EditMediaFile_HelpDescription=>T("Website.Forms.Administrative.EditMediaFile.HelpDescription"); ///"Tags" public static string Website_Forms_Administrative_EditMediaFile_LabelTags=>T("Website.Forms.Administrative.EditMediaFile.LabelTags"); ///"Provide tags for the media file content (Delimited by commas (,))" public static string Website_Forms_Administrative_EditMediaFile_HelpTags=>T("Website.Forms.Administrative.EditMediaFile.HelpTags"); ///"URL" public static string Website_Forms_Administrative_EditMediaFile_LabelMediaURL=>T("Website.Forms.Administrative.EditMediaFile.LabelMediaURL"); ///"This is the URL for your media File" public static string Website_Forms_Administrative_EditMediaFile_HelpMediaURL=>T("Website.Forms.Administrative.EditMediaFile.HelpMediaURL"); ///"The total length of the filename (folder and filename) is too long" public static string Website_Forms_Administrative_EditMediaFile_TotalFilenameToLong_Message=>T("Website.Forms.Administrative.EditMediaFile.TotalFilenameToLong.Message"); ///"A file with the same name already exists in this folder." public static string Website_Forms_Administrative_EditMediaFile_FileExists_Message=>T("Website.Forms.Administrative.EditMediaFile.FileExists.Message"); ///"Folder Properties" public static string Website_Forms_Administrative_EditMediaFolder_LabelFieldGroup=>T("Website.Forms.Administrative.EditMediaFolder.LabelFieldGroup"); ///"Folder Name" public static string Website_Forms_Administrative_EditMediaFolder_LabelFolderName=>T("Website.Forms.Administrative.EditMediaFolder.LabelFolderName"); ///"" public static string Website_Forms_Administrative_EditMediaFolder_HelpFolderName=>T("Website.Forms.Administrative.EditMediaFolder.HelpFolderName"); ///"Title" public static string Website_Forms_Administrative_EditMediaFolder_LabelTitle=>T("Website.Forms.Administrative.EditMediaFolder.LabelTitle"); ///"Use this field for a folder title" public static string Website_Forms_Administrative_EditMediaFolder_HelpTitle=>T("Website.Forms.Administrative.EditMediaFolder.HelpTitle"); ///"Description" public static string Website_Forms_Administrative_EditMediaFolder_LabelDescription=>T("Website.Forms.Administrative.EditMediaFolder.LabelDescription"); ///"" public static string Website_Forms_Administrative_EditMediaFolder_HelpDescription=>T("Website.Forms.Administrative.EditMediaFolder.HelpDescription"); ///"The folder contains a file where the total length of the filename and the new folder name is too long" public static string Website_Forms_Administrative_EditMediaFolder_TotalFilenameToLong_Message=>T("Website.Forms.Administrative.EditMediaFolder.TotalFilenameToLong.Message"); ///"Saved, but not published" public static string Website_Forms_Administrative_EditPage_PublishDatePreventPublishTitle=>T("Website.Forms.Administrative.EditPage.PublishDatePreventPublishTitle"); ///"Your page has been saved, but not published since you have a future publish date set on the 'Settings' tab." public static string Website_Forms_Administrative_EditPage_PublishDatePreventPublish=>T("Website.Forms.Administrative.EditPage.PublishDatePreventPublish"); ///"Search" public static string Website_Forms_Administrative_ElementKeywordSearch_LabelFieldGroup=>T("Website.Forms.Administrative.ElementKeywordSearch.LabelFieldGroup"); ///"Keyword" public static string Website_Forms_Administrative_ElementKeywordSearch_LabelKeyword=>T("Website.Forms.Administrative.ElementKeywordSearch.LabelKeyword"); ///"Write a keyword to search for." public static string Website_Forms_Administrative_ElementKeywordSearch_LabelSearchKeyword=>T("Website.Forms.Administrative.ElementKeywordSearch.LabelSearchKeyword"); ///"Upload New Media File" public static string Website_Forms_Administrative_UploadMediaFile_LabelFieldGroup=>T("Website.Forms.Administrative.UploadMediaFile.LabelFieldGroup"); ///"File name:" public static string Website_Forms_Administrative_UploadMediaFile_LabelFile=>T("Website.Forms.Administrative.UploadMediaFile.LabelFile"); ///"" public static string Website_Forms_Administrative_UploadMediaFile_HelpFile=>T("Website.Forms.Administrative.UploadMediaFile.HelpFile"); ///"File missing or empty" public static string Website_Forms_Administrative_UploadMediaFile_EmptyFileErrorTitle=>T("Website.Forms.Administrative.UploadMediaFile.EmptyFileErrorTitle"); ///"No file data was received. Please use the browse button and ensure that the selected file is not empty." public static string Website_Forms_Administrative_UploadMediaFile_EmptyFileErrorMessage=>T("Website.Forms.Administrative.UploadMediaFile.EmptyFileErrorMessage"); ///"Upload New Media File to Existing File" public static string Website_Forms_Administrative_UploadNewMediaFile_LabelFieldGroup=>T("Website.Forms.Administrative.UploadNewMediaFile.LabelFieldGroup"); ///"File name:" public static string Website_Forms_Administrative_UploadNewMediaFile_LabelFile=>T("Website.Forms.Administrative.UploadNewMediaFile.LabelFile"); ///"" public static string Website_Forms_Administrative_UploadNewMediaFile_HelpFile=>T("Website.Forms.Administrative.UploadNewMediaFile.HelpFile"); ///"Save" public static string Website_Forms_Administrative_AdministrativeTemplates_Document_LabelSave=>T("Website.Forms.Administrative.AdministrativeTemplates.Document.LabelSave"); ///"Save As..." public static string Website_Forms_Administrative_AdministrativeTemplates_Document_LabelSaveAs=>T("Website.Forms.Administrative.AdministrativeTemplates.Document.LabelSaveAs"); ///"Previous" public static string Website_Forms_Administrative_AdministrativeTemplates_Wizard_LabelPrevious=>T("Website.Forms.Administrative.AdministrativeTemplates.Wizard.LabelPrevious"); ///"Next" public static string Website_Forms_Administrative_AdministrativeTemplates_Wizard_LabelNext=>T("Website.Forms.Administrative.AdministrativeTemplates.Wizard.LabelNext"); ///"Finish" public static string Website_Forms_Administrative_AdministrativeTemplates_Wizard_LabelFinish=>T("Website.Forms.Administrative.AdministrativeTemplates.Wizard.LabelFinish"); ///"Cancel" public static string Website_Forms_Administrative_AdministrativeTemplates_Wizard_LabelCancel=>T("Website.Forms.Administrative.AdministrativeTemplates.Wizard.LabelCancel"); ///"OK" public static string Website_Forms_Administrative_AdministrativeTemplates_DataDialog_LabelOk=>T("Website.Forms.Administrative.AdministrativeTemplates.DataDialog.LabelOk"); ///"Cancel" public static string Website_Forms_Administrative_AdministrativeTemplates_DataDialog_LabelCancel=>T("Website.Forms.Administrative.AdministrativeTemplates.DataDialog.LabelCancel"); ///"OK" public static string Website_Forms_Administrative_AdministrativeTemplates_ConfirmDialog_LabelOk=>T("Website.Forms.Administrative.AdministrativeTemplates.ConfirmDialog.LabelOk"); ///"Cancel" public static string Website_Forms_Administrative_AdministrativeTemplates_ConfirmDialog_LabelCancel=>T("Website.Forms.Administrative.AdministrativeTemplates.ConfirmDialog.LabelCancel"); ///"Input" public static string Website_Misc_SourceCodeViewer_LabelInput=>T("Website.Misc.SourceCodeViewer.LabelInput"); ///"Output" public static string Website_Misc_SourceCodeViewer_LabelOutput=>T("Website.Misc.SourceCodeViewer.LabelOutput"); ///"Not allowed." public static string Website_Misc_Trees_DialogTitle_PasteNotAllowed=>T("Website.Misc.Trees.DialogTitle.PasteNotAllowed"); ///"Paste not allowed in this context." public static string Website_Misc_Trees_DialogText_PasteNotAllowed=>T("Website.Misc.Trees.DialogText.PasteNotAllowed"); ///"Not allowed" public static string Website_Misc_Trees_DialogTitle_PasteTypeNotAllowed=>T("Website.Misc.Trees.DialogTitle.PasteTypeNotAllowed"); ///"Folder won't accept document type." public static string Website_Misc_Trees_DialogText_PasteTypeNotAllowed=>T("Website.Misc.Trees.DialogText.PasteTypeNotAllowed"); ///"Edit Selections" public static string Website_Misc_MultiSelector_LabelEditSelections=>T("Website.Misc.MultiSelector.LabelEditSelections"); ///"More" public static string Website_Misc_Toolbar_LabelShowMoreActions=>T("Website.Misc.Toolbar.LabelShowMoreActions"); ///"Version information" public static string GenericVersionProcessController_Version=>T("GenericVersionProcessController.Version"); ///"Show version information" public static string GenericVersionProcessController_VersionToolTip=>T("GenericVersionProcessController.VersionToolTip"); ///"Select a value" public static string AspNetUiControl_Selector_SelectValueLabel=>T("AspNetUiControl.Selector.SelectValueLabel"); ///"< broken reference >..." public static string AspNetUiControl_Selector_BrokenReference=>T("AspNetUiControl.Selector.BrokenReference"); ///"(no selection)" public static string AspNetUiControl_Selector_NoSelection=>T("AspNetUiControl.Selector.NoSelection"); ///"No matches for '{0}'" public static string AspNetUiControl_Selector_NoMatchesFor_Template=>T("AspNetUiControl.Selector.NoMatchesFor"); ///"No matches for '{0}'" public static string AspNetUiControl_Selector_NoMatchesFor(object parameter0)=>string.Format(T("AspNetUiControl.Selector.NoMatchesFor"), parameter0); ///"This field contains a broken reference" public static string Validation_BrokenReference=>T("Validation.BrokenReference"); ///"This field is required." public static string Validation_RequiredField=>T("Validation.RequiredField"); ///"Only {0} digit(s) after decimal point allowed" public static string Validation_Decimal_SymbolsAfterPointAllowed_Template=>T("Validation.Decimal.SymbolsAfterPointAllowed"); ///"Only {0} digit(s) after decimal point allowed" public static string Validation_Decimal_SymbolsAfterPointAllowed(object parameter0)=>string.Format(T("Validation.Decimal.SymbolsAfterPointAllowed"), parameter0); ///"Only {0} digit(s) before decimal point allowed" public static string Validation_Decimal_SymbolsBeforePointAllowed_Template=>T("Validation.Decimal.SymbolsBeforePointAllowed"); ///"Only {0} digit(s) before decimal point allowed" public static string Validation_Decimal_SymbolsBeforePointAllowed(object parameter0)=>string.Format(T("Validation.Decimal.SymbolsBeforePointAllowed"), parameter0); ///"Invalid date string: '{0}'. Use the format '{1}'." public static string Validation_DateTime_InvalidDateFormat_Template=>T("Validation.DateTime.InvalidDateFormat"); ///"Invalid date string: '{0}'. Use the format '{1}'." public static string Validation_DateTime_InvalidDateFormat(object parameter0,object parameter1)=>string.Format(T("Validation.DateTime.InvalidDateFormat"), parameter0,parameter1); ///"The specified value is either too big or too small. The acceptable range is from -2,147,483,648 to 2,147,483,647" public static string Validation_Int32_Overflow=>T("Validation.Int32.Overflow"); ///"Required" public static string Validation_Required=>T("Validation.Required"); ///"Numbers only" public static string Validation_InvalidField_Number=>T("Validation.InvalidField.Number"); ///"Integers only" public static string Validation_InvalidField_Integer=>T("Validation.InvalidField.Integer"); ///"Invalid identifier" public static string Validation_InvalidField_ProgrammingIdentifier=>T("Validation.InvalidField.ProgrammingIdentifier"); ///"Invalid namespace" public static string Validation_InvalidField_ProgrammingNamespace=>T("Validation.InvalidField.ProgrammingNamespace"); ///"Invalid URL" public static string Validation_InvalidField_Url=>T("Validation.InvalidField.Url"); ///"Invalid notation" public static string Validation_InvalidField_Currency=>T("Validation.InvalidField.Currency"); ///"Invalid e-mail" public static string Validation_InvalidField_Email=>T("Validation.InvalidField.Email"); ///"Invalid GUID" public static string Validation_InvalidField_Guid=>T("Validation.InvalidField.Guid"); ///"{0} characters minimum" public static string Validation_StringLength_Min_Template=>T("Validation.StringLength.Min"); ///"{0} characters minimum" public static string Validation_StringLength_Min(object parameter0)=>string.Format(T("Validation.StringLength.Min"), parameter0); ///"{0} characters maximum" public static string Validation_StringLength_Max_Template=>T("Validation.StringLength.Max"); ///"{0} characters maximum" public static string Validation_StringLength_Max(object parameter0)=>string.Format(T("Validation.StringLength.Max"), parameter0); ///"Page Browser" public static string Browser_Label=>T("Browser.Label"); ///"Browse unpublished pages" public static string Browser_ToolTip=>T("Browser.ToolTip"); ///"Copy{count} of {0}" public static string Duplication_Text_Template=>T("Duplication.Text"); ///"Copy{count} of {0}" public static string Duplication_Text(object parameter0)=>string.Format(T("Duplication.Text"), parameter0); ///"Original" public static string DefaultVersionName=>T("DefaultVersionName"); ///"{0} selected" public static string Selector_Count_Template=>T("Selector.Count"); ///"{0} selected" public static string Selector_Count(object parameter0)=>string.Format(T("Selector.Count"), parameter0); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Management", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_NameValidation { ///"Name can not be an empty string" public static string EmptyName=>T("EmptyName"); ///"Namespace can not be an empty string" public static string EmptyNamespace=>T("EmptyNamespace"); ///"Namespace can not contain the same name part multiple times" public static string DuplicateElementNamespace=>T("DuplicateElementNamespace"); ///"The name '{0}' is not a valid identifier" public static string InvalidIdentifier_Template=>T("InvalidIdentifier"); ///"The name '{0}' is not a valid identifier" public static string InvalidIdentifier(object parameter0)=>string.Format(T("InvalidIdentifier"), parameter0); ///"The name '{0}' is not a valid identifier. Identifiers may not start with digits." public static string InvalidIdentifierDigit_Template=>T("InvalidIdentifierDigit"); ///"The name '{0}' is not a valid identifier. Identifiers may not start with digits." public static string InvalidIdentifierDigit(object parameter0)=>string.Format(T("InvalidIdentifierDigit"), parameter0); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.NameValidation", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Permissions { ///"Read" public static string ReadLabel=>T("ReadLabel"); ///"Edit" public static string EditLabel=>T("EditLabel"); ///"Add" public static string AddLabel=>T("AddLabel"); ///"Delete" public static string DeleteLabel=>T("DeleteLabel"); ///"Approve" public static string ApproveLabel=>T("ApproveLabel"); ///"Publish" public static string PublishLabel=>T("PublishLabel"); ///"Configure" public static string ConfigureLabel=>T("ConfigureLabel"); ///"Administrate" public static string AdministrateLabel=>T("AdministrateLabel"); ///"ClearPermissions" public static string ClearPermissionsLabel=>T("ClearPermissionsLabel"); ///"This operation would remove your administrative permissions from this entity. You can not remove your own administrative permissions." public static string AdminLockoutMessage=>T("AdminLockoutMessage"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Permissions", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_AllFunctionsElementProvider { ///"All Functions" public static string Plugins_AllFunctionsElementProvider_FunctionRootFolderLabel=>T("Plugins.AllFunctionsElementProvider.FunctionRootFolderLabel"); ///"All functions" public static string Plugins_AllFunctionsElementProvider_FunctionRootFolderToolTip=>T("Plugins.AllFunctionsElementProvider.FunctionRootFolderToolTip"); ///"All Widget Functions" public static string Plugins_AllFunctionsElementProvider_WidgetFunctionRootFolderLabel=>T("Plugins.AllFunctionsElementProvider.WidgetFunctionRootFolderLabel"); ///"All widget functions" public static string Plugins_AllFunctionsElementProvider_WidgetFunctionRootFolderToolTip=>T("Plugins.AllFunctionsElementProvider.WidgetFunctionRootFolderToolTip"); ///"Generate Documentation" public static string AllFunctionsElementProvider_GenerateDocumentation=>T("AllFunctionsElementProvider.GenerateDocumentation"); ///"Generate documentation for all functions below this folder" public static string AllFunctionsElementProvider_GenerateDocumentationTooltip=>T("AllFunctionsElementProvider.GenerateDocumentationTooltip"); ///"Information" public static string AllFunctionsElementProvider_ViewFunctionInformation=>T("AllFunctionsElementProvider.ViewFunctionInformation"); ///"View function information" public static string AllFunctionsElementProvider_ViewFunctionInformationTooltip=>T("AllFunctionsElementProvider.ViewFunctionInformationTooltip"); ///"Test: {0}" public static string FunctionTesterWorkflow_Layout_Label_Template=>T("FunctionTesterWorkflow.Layout.Label"); ///"Test: {0}" public static string FunctionTesterWorkflow_Layout_Label(object parameter0)=>string.Format(T("FunctionTesterWorkflow.Layout.Label"), parameter0); ///"Functions" public static string FunctionTesterWorkflow_FunctionCalls_Label=>T("FunctionTesterWorkflow.FunctionCalls.Label"); ///"Results" public static string FunctionTesterWorkflow_Preview_Label=>T("FunctionTesterWorkflow.Preview.Label"); ///"Runtime" public static string FunctionTesterWorkflow_Runtime_FieldGroup_Label=>T("FunctionTesterWorkflow.Runtime.FieldGroup.Label"); ///"Settings" public static string FunctionTesterWorkflow_DebugFieldGroup_Label=>T("FunctionTesterWorkflow.DebugFieldGroup.Label"); ///"Page" public static string FunctionTesterWorkflow_DebugPage_Label=>T("FunctionTesterWorkflow.DebugPage.Label"); ///"When executing the function, this page is used as current page" public static string FunctionTesterWorkflow_DebugPage_Help=>T("FunctionTesterWorkflow.DebugPage.Help"); ///"Data scope" public static string FunctionTesterWorkflow_DebugPageDataScope_Label=>T("FunctionTesterWorkflow.DebugPageDataScope.Label"); ///"When executing the function, this is used as current data scope" public static string FunctionTesterWorkflow_DebugPageDataScope_Help=>T("FunctionTesterWorkflow.DebugPageDataScope.Help"); ///"Language" public static string FunctionTesterWorkflow_DebugActiveLocale_Label=>T("FunctionTesterWorkflow.DebugActiveLocale.Label"); ///"When executing the function, this is used as the current language" public static string FunctionTesterWorkflow_DebugActiveLocale_Help=>T("FunctionTesterWorkflow.DebugActiveLocale.Help"); ///"Administrative" public static string FunctionTesterWorkflow_AdminitrativeScope_Label=>T("FunctionTesterWorkflow.AdminitrativeScope.Label"); ///"Public" public static string FunctionTesterWorkflow_PublicScope_Label=>T("FunctionTesterWorkflow.PublicScope.Label"); ///"Test Function" public static string AllFunctionsElementProvider_FunctionTester_Label=>T("AllFunctionsElementProvider.FunctionTester.Label"); ///"Test function" public static string AllFunctionsElementProvider_FunctionTester_ToolTip=>T("AllFunctionsElementProvider.FunctionTester.ToolTip"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.AllFunctionsElementProvider", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_Components { ///"E-Commerce" public static string Tags_Ecommerce=>T("Tags.Ecommerce"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.Components", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_GeneratedDataTypesElementProvider { ///"Global Datatypes" public static string GlobalDataFolderLabel=>T("GlobalDataFolderLabel"); ///"Global datatypes" public static string GlobalDataFolderToolTip=>T("GlobalDataFolderToolTip"); ///"Website Items" public static string GlobalDataFolderLabel_OnlyGlobalData=>T("GlobalDataFolderLabel_OnlyGlobalData"); ///"Website Items (Data)" public static string GlobalDataFolderToolTip_OnlyGlobalData=>T("GlobalDataFolderToolTip_OnlyGlobalData"); ///"Page Datafolders" public static string PageDataFolderDataFolderLabel=>T("PageDataFolderDataFolderLabel"); ///"Page datafolders" public static string PageDataFolderDataFolderToolTip=>T("PageDataFolderDataFolderToolTip"); ///"Page Metatypes" public static string PageMetaDataFolderLabel=>T("PageMetaDataFolderLabel"); ///"Page metatypes" public static string PageMetaDataFolderToolTip=>T("PageMetaDataFolderToolTip"); ///"Add Datatype" public static string Add=>T("Add"); ///"Add new global datatype" public static string AddToolTip=>T("AddToolTip"); ///"List Unpublished Content" public static string ViewUnpublishedItems=>T("ViewUnpublishedItems"); ///"Get an overview of data that haven't been published yet" public static string ViewUnpublishedItemsToolTip=>T("ViewUnpublishedItemsToolTip"); ///"Unpublished data" public static string ViewUnpublishedItems_document_title=>T("ViewUnpublishedItems-document-title"); ///"The list below display data items which are currently being edited or are ready to be approved / published." public static string ViewUnpublishedItems_document_description=>T("ViewUnpublishedItems-document-description"); ///"No unpublished data." public static string ViewUnpublishedItems_document_empty_label=>T("ViewUnpublishedItems-document-empty-label"); ///"Add Datafolder" public static string AddDataFolder=>T("AddDataFolder"); ///"Add new datafolder" public static string AddDataFolderToolTip=>T("AddDataFolderToolTip"); ///"Add Metatype" public static string AddMetaDataLabel=>T("AddMetaDataLabel"); ///"Add metatype" public static string AddMetaDataToolTip=>T("AddMetaDataToolTip"); ///"Edit Datatype" public static string Edit=>T("Edit"); ///"Edit selected datatype" public static string EditToolTip=>T("EditToolTip"); ///"Edit" public static string EditDataFolderTypeLabel=>T("EditDataFolderTypeLabel"); ///"Edit selected datafolder" public static string EditDataFolderTypeToolTip=>T("EditDataFolderTypeToolTip"); ///"Edit" public static string EditMetaDataTypeLabel=>T("EditMetaDataTypeLabel"); ///"Edit selected metadata" public static string EditMetaDataTypeToolTip=>T("EditMetaDataTypeToolTip"); ///"Delete Datatype" public static string Delete=>T("Delete"); ///"Delete selected datatype" public static string DeleteToolTip=>T("DeleteToolTip"); ///"Delete" public static string DeleteDataFolderTypeLabel=>T("DeleteDataFolderTypeLabel"); ///"Delete selected datafolder" public static string DeleteDataFolderTypeToolTip=>T("DeleteDataFolderTypeToolTip"); ///"Delete" public static string DeleteMetaDataTypeLabel=>T("DeleteMetaDataTypeLabel"); ///"Delete selected metadata" public static string DeleteMetaDataTypeToolTip=>T("DeleteMetaDataTypeToolTip"); ///"Edit Form Markup" public static string EditFormMarkup=>T("EditFormMarkup"); ///"Modify the layout of the data form using markup" public static string EditFormMarkupToolTip=>T("EditFormMarkupToolTip"); ///"Enable Localization" public static string EnableLocalization=>T("EnableLocalization"); ///"Enable localization" public static string EnableLocalizationToolTip=>T("EnableLocalizationToolTip"); ///"Disable Localization" public static string DisableLocalization=>T("DisableLocalization"); ///"Disable localization" public static string DisableLocalizationToolTip=>T("DisableLocalizationToolTip"); ///"Not yet approved or published" public static string DisabledData=>T("DisabledData"); ///"(undefined [{0}])" public static string UndefinedLabelTemplate_Template=>T("UndefinedLabelTemplate"); ///"(undefined [{0}])" public static string UndefinedLabelTemplate(object parameter0)=>string.Format(T("UndefinedLabelTemplate"), parameter0); ///"(undefined)" public static string UndefinedDataLavelTemplate=>T("UndefinedDataLavelTemplate"); ///"Show in Content perspective" public static string ShowInContent=>T("ShowInContent"); ///"Show in Content perspective" public static string ShowInContentToolTip=>T("ShowInContentToolTip"); ///"Add Data" public static string AddData=>T("AddData"); ///"Add new data" public static string AddDataToolTip=>T("AddDataToolTip"); ///"Edit Data" public static string EditData=>T("EditData"); ///"Edit selected data" public static string EditDataToolTip=>T("EditDataToolTip"); ///"Delete Data" public static string DeleteData=>T("DeleteData"); ///"Delete selected data" public static string DeleteDataToolTip=>T("DeleteDataToolTip"); ///"Duplicate Data" public static string DuplicateData=>T("DuplicateData"); ///"Duplicate selected data" public static string DuplicateDataToolTip=>T("DuplicateDataToolTip"); ///"Translate Data" public static string LocalizeData=>T("LocalizeData"); ///"Translate selected data" public static string LocalizeDataToolTip=>T("LocalizeDataToolTip"); ///"Publication settings" public static string PublicationSettings_FieldGroupLabel=>T("PublicationSettings.FieldGroupLabel"); ///"Status" public static string PublicationStatus_Label=>T("PublicationStatus.Label"); ///"Send the data to another publication status." public static string PublicationStatus_Help=>T("PublicationStatus.Help"); ///"Publish date" public static string PublishDate_Label=>T("PublishDate.Label"); ///"Specify at which date and time you want the data to be published automatically." public static string PublishDate_Help=>T("PublishDate.Help"); ///"Date Created" public static string DateCreated_Label=>T("DateCreated.Label"); ///"Date Modified" public static string DateModified_Label=>T("DateModified.Label"); ///"Author" public static string CreatedBy_Label=>T("CreatedBy.Label"); ///"Author" public static string ChangedBy_Label=>T("ChangedBy.Label"); ///"Unpublish date" public static string UnpublishDate_Label=>T("UnpublishDate.Label"); ///"Specify at which date and time you want the data to be unpublished automatically." public static string UnpublishDate_Help=>T("UnpublishDate.Help"); ///"New Datatype" public static string AddNewInterfaceTypeStep1_DocumentTitle=>T("AddNewInterfaceTypeStep1.DocumentTitle"); ///"New Page Metatype" public static string AddNewCompositionTypeWorkflow_DocumentTitle=>T("AddNewCompositionTypeWorkflow.DocumentTitle"); ///"New Page Datafolder" public static string AddNewAggregationTypeWorkflow_DocumentTitle=>T("AddNewAggregationTypeWorkflow.DocumentTitle"); ///"Settings" public static string EditorCommon_SettingsTab=>T("EditorCommon.SettingsTab"); ///"Type title" public static string EditorCommon_LabelTitleGroup=>T("EditorCommon.LabelTitleGroup"); ///"Programmatic naming and services" public static string EditorCommon_LabelProgrammaticNamingAndServices=>T("EditorCommon.LabelProgrammaticNamingAndServices"); ///"Programmatic naming" public static string EditorCommon_LabelProgrammaticNaming=>T("EditorCommon.LabelProgrammaticNaming"); ///"Type name" public static string EditorCommon_LabelTypeName=>T("EditorCommon.LabelTypeName"); ///"The technical name of the data type (ex. Product). This is used to identify this type in code and should not be changed once used externally." public static string EditorCommon_HelpTypeName=>T("EditorCommon.HelpTypeName"); ///"Type namespace" public static string EditorCommon_LabelTypeNamespace=>T("EditorCommon.LabelTypeNamespace"); ///"The namespace (module / category name) of the type. This is used to identify this type in code and should not be changed once used externally." public static string EditorCommon_HelpTypeNamespace=>T("EditorCommon.HelpTypeNamespace"); ///"Title" public static string EditorCommon_LabelTitle=>T("EditorCommon.LabelTitle"); ///"Use this entry to specify a user friendly name. This name is used in most UI." public static string EditorCommon_HelpTitle=>T("EditorCommon.HelpTitle"); ///"Fields" public static string EditorCommon_LabelFields=>T("EditorCommon.LabelFields"); ///"Key field type" public static string EditorCommon_KeyFieldTypeLabel=>T("EditorCommon.KeyFieldTypeLabel"); ///"The type of the primary key. Use the default 'Guid' type for optimal performance and 'RandomString' for shorter data urls." public static string EditorCommon_KeyFieldTypeHelp=>T("EditorCommon.KeyFieldTypeHelp"); ///"Guid" public static string EditorCommon_KeyFieldType_Guid=>T("EditorCommon.KeyFieldType.Guid"); ///"Random String, 4 characters long" public static string EditorCommon_KeyFieldType_RandomString4=>T("EditorCommon.KeyFieldType.RandomString4"); ///"Random String, 8 characters long" public static string EditorCommon_KeyFieldType_RandomString8=>T("EditorCommon.KeyFieldType.RandomString8"); ///"Services" public static string EditorCommon_ServicesLabel=>T("EditorCommon.ServicesLabel"); ///"Short URL name" public static string EditorCommon_InternalUrlPrefixLabel=>T("EditorCommon.InternalUrlPrefixLabel"); ///"When specified, allows data items of the current type to be referenced in content. The internal links will have format '~/{ShortURLName}({id})', f.e. '~/product(aIkH34F)" public static string EditorCommon_InternalUrlPrefixHelp=>T("EditorCommon.InternalUrlPrefixHelp"); ///"Has caching" public static string EditorCommon_HasCaching=>T("EditorCommon.HasCaching"); ///"Is searchable" public static string EditorCommon_IsSearchable=>T("EditorCommon.IsSearchable"); ///"Has publishing" public static string EditorCommon_HasPublishing=>T("EditorCommon.HasPublishing"); ///"Is localizable data" public static string EditorCommon_HasLocalization=>T("EditorCommon.HasLocalization"); ///"Delete Data?" public static string DeleteGeneratedDataStep1_LabelFieldGroup=>T("DeleteGeneratedDataStep1.LabelFieldGroup"); ///"Delete data?" public static string DeleteGeneratedDataStep1_Text=>T("DeleteGeneratedDataStep1.Text"); ///"There is some referenced data that will also be deleted, do you want to continue?" public static string DeleteDataConfirmationText=>T("DeleteDataConfirmationText"); ///"Delete Datatype" public static string DeleteGeneratedInterfaceStep1_LabelFieldGroup=>T("DeleteGeneratedInterfaceStep1.LabelFieldGroup"); ///"Delete the datatype" public static string DeleteGeneratedInterfaceStep1_Text=>T("DeleteGeneratedInterfaceStep1.Text"); ///"Cascade delete error" public static string CascadeDeleteErrorTitle=>T("CascadeDeleteErrorTitle"); ///"The type is referenced by another type that does not allow cascade deletes. This operation is halted" public static string CascadeDeleteErrorMessage=>T("CascadeDeleteErrorMessage"); ///"Delete Datatype" public static string DeleteAggregationTypeWorkflow_LabelFieldGroup=>T("DeleteAggregationTypeWorkflow.LabelFieldGroup"); ///"Delete the datatype" public static string DeleteAggregationTypeWorkflow_Text=>T("DeleteAggregationTypeWorkflow.Text"); ///"Error" public static string DeleteAggregationTypeWorkflow_ErrorTitle=>T("DeleteAggregationTypeWorkflow.ErrorTitle"); ///"Cannot delete type '{0}' since it is used by a page type." public static string DeleteAggregationTypeWorkflow_IsUsedByPageType_Template=>T("DeleteAggregationTypeWorkflow.IsUsedByPageType"); ///"Cannot delete type '{0}' since it is used by a page type." public static string DeleteAggregationTypeWorkflow_IsUsedByPageType(object parameter0)=>string.Format(T("DeleteAggregationTypeWorkflow.IsUsedByPageType"), parameter0); ///"Delete Datatype" public static string DeleteCompositionTypeWorkflow_LabelFieldGroup=>T("DeleteCompositionTypeWorkflow.LabelFieldGroup"); ///"Delete the datatype" public static string DeleteCompositionTypeWorkflow_Text=>T("DeleteCompositionTypeWorkflow.Text"); ///"Error" public static string DeleteCompositionTypeWorkflow_ErrorTitle=>T("DeleteCompositionTypeWorkflow.ErrorTitle"); ///"Cannot delete type '{0}' since there're types that referenced to it." public static string DeleteCompositionTypeWorkflow_TypeIsReferenced_Template=>T("DeleteCompositionTypeWorkflow.TypeIsReferenced"); ///"Cannot delete type '{0}' since there're types that referenced to it." public static string DeleteCompositionTypeWorkflow_TypeIsReferenced(object parameter0)=>string.Format(T("DeleteCompositionTypeWorkflow.TypeIsReferenced"), parameter0); ///"Cannot delete type '{0}' since it is used by a page type." public static string DeleteCompositionTypeWorkflow_IsUsedByPageType_Template=>T("DeleteCompositionTypeWorkflow.IsUsedByPageType"); ///"Cannot delete type '{0}' since it is used by a page type." public static string DeleteCompositionTypeWorkflow_IsUsedByPageType(object parameter0)=>string.Format(T("DeleteCompositionTypeWorkflow.IsUsedByPageType"), parameter0); ///"To Xml" public static string ToXmlLabel=>T("ToXmlLabel"); ///"To Xml" public static string ToXmlToolTip=>T("ToXmlToolTip"); ///"Enable Localization" public static string EnableTypeLocalizationWorkflow_Dialog_Label=>T("EnableTypeLocalizationWorkflow.Dialog.Label"); ///"Enable localization" public static string EnableTypeLocalizationWorkflow_Step1_FieldGroup_Label=>T("EnableTypeLocalizationWorkflow.Step1.FieldGroup.Label"); ///"Move existing data to ..." public static string EnableTypeLocalizationWorkflow_Step1_CultureSelector_Label=>T("EnableTypeLocalizationWorkflow.Step1.CultureSelector.Label"); ///"When you enable 'localization' on a data type, all data must belong to a language. Select the language existing data should now be moved to." public static string EnableTypeLocalizationWorkflow_Step1_CultureSelector_Help=>T("EnableTypeLocalizationWorkflow.Step1.CultureSelector.Help"); ///"Confirmation" public static string EnableTypeLocalizationWorkflow_Step2_Title=>T("EnableTypeLocalizationWorkflow.Step2.Title"); ///"Data type will be localized and data copied to selected locale. Click Finish to continue." public static string EnableTypeLocalizationWorkflow_Step2_Description=>T("EnableTypeLocalizationWorkflow.Step2.Description"); ///"Warning" public static string EnableTypeLocalizationWorkflow_Step3_Title=>T("EnableTypeLocalizationWorkflow.Step3.Title"); ///"There's some datatypes which have references to the type. While localizing the data will be copied to all languages in order to prevent appearing of broken references." public static string EnableTypeLocalizationWorkflow_Step3_Description=>T("EnableTypeLocalizationWorkflow.Step3.Description"); ///"Missing active locales" public static string EnableTypeLocalizationWorkflow_Abort_Title=>T("EnableTypeLocalizationWorkflow.Abort.Title"); ///"There are no added active locales. Add at least one before localization this datatype." public static string EnableTypeLocalizationWorkflow_Abort_Description=>T("EnableTypeLocalizationWorkflow.Abort.Description"); ///"Disable Localization" public static string DisableTypeLocalizationWorkflow_Dialog_Label=>T("DisableTypeLocalizationWorkflow.Dialog.Label"); ///"Disable localization" public static string DisableTypeLocalizationWorkflow_Step1_FieldGroup_Label=>T("DisableTypeLocalizationWorkflow.Step1.FieldGroup.Label"); ///"Keep data from ..." public static string DisableTypeLocalizationWorkflow_Step1_CultureSelector_Label=>T("DisableTypeLocalizationWorkflow.Step1.CultureSelector.Label"); ///"When localization is disabled on a datatype only one translation can be kept. Data from other languages will be lost." public static string DisableTypeLocalizationWorkflow_Step1_CultureSelector_Help=>T("DisableTypeLocalizationWorkflow.Step1.CultureSelector.Help"); ///"Confirmation" public static string DisableTypeLocalizationWorkflow_Step2_Title=>T("DisableTypeLocalizationWorkflow.Step2.Title"); ///"All data from other locales than the one selected will be lost. Click Finish to continue." public static string DisableTypeLocalizationWorkflow_Step2_Description=>T("DisableTypeLocalizationWorkflow.Step2.Description"); ///"Failed to translate data" public static string LocalizeDataWorkflow_ShowError_LayoutLabel=>T("LocalizeDataWorkflow.ShowError.LayoutLabel"); ///"Translation errors" public static string LocalizeDataWorkflow_ShowError_InfoTableCaption=>T("LocalizeDataWorkflow.ShowError.InfoTableCaption"); ///"This data has already been translated. The translated version belongs to a different group." public static string LocalizeDataWorkflow_ShowError_AlreadyTranslated=>T("LocalizeDataWorkflow.ShowError.AlreadyTranslated"); ///"The following fields has a reference to a data type. You should translate these data items before you can translate this data item" public static string LocalizeDataWorkflow_ShowError_Description=>T("LocalizeDataWorkflow.ShowError.Description"); ///"The field '{0}' is referencing data of type '{1}' with the label '{2}'" public static string LocalizeDataWorkflow_ShowError_FieldErrorFormat_Template=>T("LocalizeDataWorkflow.ShowError.FieldErrorFormat"); ///"The field '{0}' is referencing data of type '{1}' with the label '{2}'" public static string LocalizeDataWorkflow_ShowError_FieldErrorFormat(object parameter0,object parameter1,object parameter2)=>string.Format(T("LocalizeDataWorkflow.ShowError.FieldErrorFormat"), parameter0,parameter1,parameter2); ///"Error" public static string AddNewInterfaceTypeStep1_ErrorTitle=>T("AddNewInterfaceTypeStep1.ErrorTitle"); ///"Error" public static string EditInterfaceTypeStep1_ErrorTitle=>T("EditInterfaceTypeStep1.ErrorTitle"); ///"Error" public static string AddNewCompositionTypeWorkflow_ErrorTitle=>T("AddNewCompositionTypeWorkflow.ErrorTitle"); ///"Error" public static string EditCompositionTypeWorkflow_ErrorTitle=>T("EditCompositionTypeWorkflow.ErrorTitle"); ///"XML Result" public static string DataTypeDescriptorToXmlLabel=>T("DataTypeDescriptorToXmlLabel"); ///"This type has custom form markup" public static string FormMarkupInfo_Dialog_Label=>T("FormMarkupInfo.Dialog.Label"); ///"Your field changes will not affect the form for editing data. Do '{0}' to change the form or delete the file '{1}'." public static string FormMarkupInfo_Message_Template=>T("FormMarkupInfo.Message"); ///"Your field changes will not affect the form for editing data. Do '{0}' to change the form or delete the file '{1}'." public static string FormMarkupInfo_Message(object parameter0,object parameter1)=>string.Format(T("FormMarkupInfo.Message"), parameter0,parameter1); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.GeneratedDataTypesElementProvider", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_GenericPublishProcessController { ///"Send to Draft" public static string SendToDraft=>T("SendToDraft"); ///"" public static string SendToDraftToolTip=>T("SendToDraftToolTip"); ///"Publish" public static string Publish=>T("Publish"); ///"Publish to site" public static string PublishToolTip=>T("PublishToolTip"); ///"Unpublish" public static string Unpublish=>T("Unpublish"); ///"Set to draft status and remove the published version" public static string UnpublishToolTip=>T("UnpublishToolTip"); ///"Send for Approval" public static string SendForApproval=>T("SendForApproval"); ///"Send for approval" public static string SendForApprovalToolTip=>T("SendForApprovalToolTip"); ///"Send for Publication" public static string SendForPublication=>T("SendForPublication"); ///"Send for publication" public static string SendForPublicationToolTip=>T("SendForPublicationToolTip"); ///"Undo Changes" public static string UndoPublishedChanges=>T("UndoPublishedChanges"); ///"Undo unpublished changes" public static string UndoPublishedChangesToolTip=>T("UndoPublishedChangesToolTip"); ///"Action Not Possible" public static string ValidationErrorTitle=>T("ValidationErrorTitle"); ///"The data did not validate with the following errors:" public static string ValidationErrorMessage=>T("ValidationErrorMessage"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_LocalizationElementProvider { ///"Languages" public static string ElementProvider_RootFolderLabel=>T("ElementProvider.RootFolderLabel"); ///"Explore and manage installed languages" public static string ElementProvider_RootFolderToolTip=>T("ElementProvider.RootFolderToolTip"); ///"Default" public static string ElementProvider_DefaultLabel=>T("ElementProvider.DefaultLabel"); ///"No Languages Available" public static string AddSystemLocaleWorkflow_NoMoreLocalesTitle=>T("AddSystemLocaleWorkflow.NoMoreLocalesTitle"); ///"You have installed all possible languages." public static string AddSystemLocaleWorkflow_NoMoreLocalesMessage=>T("AddSystemLocaleWorkflow.NoMoreLocalesMessage"); ///"Add Language" public static string AddSystemLocaleWorkflow_AddElementActionLabel=>T("AddSystemLocaleWorkflow.AddElementActionLabel"); ///"Add new language" public static string AddSystemLocaleWorkflow_AddElementActionToolTip=>T("AddSystemLocaleWorkflow.AddElementActionToolTip"); ///"Add Language" public static string AddSystemLocaleWorkflow_Dialog_Label=>T("AddSystemLocaleWorkflow.Dialog.Label"); ///"Languages" public static string AddSystemLocaleWorkflow_CultureSelector_Label=>T("AddSystemLocaleWorkflow.CultureSelector.Label"); ///"The list of available, uninstalled languages. Language packages may be installed for additional options." public static string AddSystemLocaleWorkflow_CultureSelector_Help=>T("AddSystemLocaleWorkflow.CultureSelector.Help"); ///"URL mapping name" public static string AddSystemLocaleWorkflow_UrlMappingName_Label=>T("AddSystemLocaleWorkflow.UrlMappingName.Label"); ///"This string will be inserted into the URL of pages published in a given language. The website "default" language may leave this entry blank." public static string AddSystemLocaleWorkflow_UrlMappingName_Help=>T("AddSystemLocaleWorkflow.UrlMappingName.Help"); ///"User access" public static string AddSystemLocaleWorkflow_AllUsersAccess_Label=>T("AddSystemLocaleWorkflow.AllUsersAccess.Label"); ///"Give access to all users" public static string AddSystemLocaleWorkflow_AllUsersAccess_ItemLabel=>T("AddSystemLocaleWorkflow.AllUsersAccess.ItemLabel"); ///"If checked, the language will be made available to all registered users for viewing and editing" public static string AddSystemLocaleWorkflow_AllUsersAccess_Help=>T("AddSystemLocaleWorkflow.AllUsersAccess.Help"); ///"URL mapping name is already in use" public static string AddSystemLocaleWorkflow_UrlMappingName_InUseMessage=>T("AddSystemLocaleWorkflow.UrlMappingName.InUseMessage"); ///"Edit Language" public static string EditSystemLocaleWorkflow_EditElementActionLabel=>T("EditSystemLocaleWorkflow.EditElementActionLabel"); ///"Edit language" public static string EditSystemLocaleWorkflow_EditElementActionToolTip=>T("EditSystemLocaleWorkflow.EditElementActionToolTip"); ///"Edit Language" public static string EditSystemLocaleWorkflow_Dialog_Label=>T("EditSystemLocaleWorkflow.Dialog.Label"); ///"Language properties" public static string EditSystemLocaleWorkflow_FieldGroup_Label=>T("EditSystemLocaleWorkflow.FieldGroup.Label"); ///"URL mapping name" public static string EditSystemLocaleWorkflow_UrlMappingName_Label=>T("EditSystemLocaleWorkflow.UrlMappingName.Label"); ///"URL mapping name" public static string EditSystemLocaleWorkflow_UrlMappingName_Help=>T("EditSystemLocaleWorkflow.UrlMappingName.Help"); ///"URL mapping name is already in use" public static string EditSystemLocaleWorkflow_UrlMappingName_InUseMessage=>T("EditSystemLocaleWorkflow.UrlMappingName.InUseMessage"); ///"Set as Default" public static string DefineDefaultActiveLocaleWorkflow_ElementActionLabel=>T("DefineDefaultActiveLocaleWorkflow.ElementActionLabel"); ///"Set as default language" public static string DefineDefaultActiveLocaleWorkflow_ElementActionToolTip=>T("DefineDefaultActiveLocaleWorkflow.ElementActionToolTip"); ///"Remove Language" public static string RemoveSystemLocaleWorkflow_RemoveElementActionLabel=>T("RemoveSystemLocaleWorkflow.RemoveElementActionLabel"); ///"Remove language" public static string RemoveSystemLocaleWorkflow_RemoveElementActionToolTip=>T("RemoveSystemLocaleWorkflow.RemoveElementActionToolTip"); ///"Remove Language?" public static string RemoveSystemLocaleWorkflow_Dialog_Label=>T("RemoveSystemLocaleWorkflow.Dialog.Label"); ///"Cannot Remove Last Language" public static string RemoveSystemLocaleWorkflow_Abort_Title=>T("RemoveSystemLocaleWorkflow.Abort.Title"); ///"You are about to remove a language that is the only language for one or more users. Please add other languages to these users and try again." public static string RemoveSystemLocaleWorkflow_Abort_Description=>T("RemoveSystemLocaleWorkflow.Abort.Description"); ///"Remove this language?" public static string RemoveSystemLocaleWorkflow_Confirm_Description=>T("RemoveSystemLocaleWorkflow.Confirm.Description"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_MasterPagePageTemplate { ///"Add New Master Page" public static string AddNewMasterPagePageTemplateWorkflow_LabelDialog=>T("AddNewMasterPagePageTemplateWorkflow.LabelDialog"); ///"Edit Master Page" public static string EditMasterPageAction_Label=>T("EditMasterPageAction.Label"); ///"Edit source code of the master page" public static string EditMasterPageAction_ToolTip=>T("EditMasterPageAction.ToolTip"); ///"Delete" public static string DeleteMasterPageAction_Label=>T("DeleteMasterPageAction.Label"); ///"Delete page template" public static string DeleteMasterPageAction_ToolTip=>T("DeleteMasterPageAction.ToolTip"); ///"Validation error" public static string EditTemplate_Validation_DialogTitle=>T("EditTemplate.Validation.DialogTitle"); ///"Compilation failed: {0}" public static string EditTemplate_Validation_CompilationFailed_Template=>T("EditTemplate.Validation.CompilationFailed"); ///"Compilation failed: {0}" public static string EditTemplate_Validation_CompilationFailed(object parameter0)=>string.Format(T("EditTemplate.Validation.CompilationFailed"), parameter0); ///"Page template class does not inherit '{0}'" public static string EditTemplate_Validation_IncorrectBaseClass_Template=>T("EditTemplate.Validation.IncorrectBaseClass"); ///"Page template class does not inherit '{0}'" public static string EditTemplate_Validation_IncorrectBaseClass(object parameter0)=>string.Format(T("EditTemplate.Validation.IncorrectBaseClass"), parameter0); ///"Failed to evaluate page template property '{0}'. Exception: {1}" public static string EditTemplate_Validation_PropertyError_Template=>T("EditTemplate.Validation.PropertyError"); ///"Failed to evaluate page template property '{0}'. Exception: {1}" public static string EditTemplate_Validation_PropertyError(object parameter0,object parameter1)=>string.Format(T("EditTemplate.Validation.PropertyError"), parameter0,parameter1); ///"It is not allowed to change the template ID through the current workflow. The original template ID is '{0}'" public static string EditTemplate_Validation_TemplateIdChanged_Template=>T("EditTemplate.Validation.TemplateIdChanged"); ///"It is not allowed to change the template ID through the current workflow. The original template ID is '{0}'" public static string EditTemplate_Validation_TemplateIdChanged(object parameter0)=>string.Format(T("EditTemplate.Validation.TemplateIdChanged"), parameter0); ///"Add New Master Page Template" public static string AddNewMasterPagePageTemplate_LabelDialog=>T("AddNewMasterPagePageTemplate.LabelDialog"); ///"Template Title" public static string AddNewMasterPagePageTemplate_LabelTemplateTitle=>T("AddNewMasterPagePageTemplate.LabelTemplateTitle"); ///"The title identifies this template in lists. Consider selecting a short but meaningful name." public static string AddNewMasterPagePageTemplate_LabelTemplateTitleHelp=>T("AddNewMasterPagePageTemplate.LabelTemplateTitleHelp"); ///"Copy from" public static string AddNewMasterPagePageTemplate_LabelCopyFrom=>T("AddNewMasterPagePageTemplate.LabelCopyFrom"); ///"You can copy the markup from another Layout Template by selecting it in this list." public static string AddNewMasterPagePageTemplate_LabelCopyFromHelp=>T("AddNewMasterPagePageTemplate.LabelCopyFromHelp"); ///"(New template)" public static string AddNewMasterPagePageTemplate_LabelCopyFromEmptyOption=>T("AddNewMasterPagePageTemplate.LabelCopyFromEmptyOption"); ///"Title already used" public static string AddNewMasterPagePageTemplateWorkflow_TitleInUseTitle=>T("AddNewMasterPagePageTemplateWorkflow.TitleInUseTitle"); ///"The title is too long (used as part of a filename)." public static string AddNewMasterPagePageTemplateWorkflow_TitleTooLong=>T("AddNewMasterPagePageTemplateWorkflow.TitleTooLong"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.MasterPagePageTemplate", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_MethodBasedFunctionProviderElementProvider { ///"C# Functions" public static string RootFolderLabel=>T("RootFolderLabel"); ///"Method functions" public static string RootFolderToolTip=>T("RootFolderToolTip"); ///"Delete This Function" public static string DeleteFunction_LabelFieldGroup=>T("DeleteFunction.LabelFieldGroup"); ///"Delete this function" public static string DeleteFunction_Text=>T("DeleteFunction.Text"); ///"Add External C# function" public static string Add=>T("Add"); ///"Add an external C# method based function." public static string AddToolTip=>T("AddToolTip"); ///"Add Inline C# function" public static string Create=>T("Create"); ///"Add an inline C# method based function." public static string CreateToolTip=>T("CreateToolTip"); ///"Edit" public static string Edit=>T("Edit"); ///"Edit Function." public static string EditToolTip=>T("EditToolTip"); ///"Delete" public static string Delete=>T("Delete"); ///"Delete Function." public static string DeleteToolTip=>T("DeleteToolTip"); ///"Type" public static string AddNewMethodBasedFunctionStep1_LabelType=>T("AddNewMethodBasedFunctionStep1.LabelType"); ///"The type that contains the method in question" public static string AddNewMethodBasedFunctionStep1_LabelTypeHelp=>T("AddNewMethodBasedFunctionStep1.LabelTypeHelp"); ///"Method name" public static string AddNewMethodBasedFunctionStep2_LabelMethodName=>T("AddNewMethodBasedFunctionStep2.LabelMethodName"); ///"" public static string AddNewMethodBasedFunctionStep2_HelpMethodName=>T("AddNewMethodBasedFunctionStep2.HelpMethodName"); ///"Method Name" public static string AddNewMethodBasedFunctionStep3_LabelMethodName=>T("AddNewMethodBasedFunctionStep3.LabelMethodName"); ///"" public static string AddNewMethodBasedFunctionStep3_HelpMethodName=>T("AddNewMethodBasedFunctionStep3.HelpMethodName"); ///"Namespace Name" public static string AddNewMethodBasedFunctionStep3_LabelNamespaceName=>T("AddNewMethodBasedFunctionStep3.LabelNamespaceName"); ///"" public static string AddNewMethodBasedFunctionStep3_HelpNamespaceName=>T("AddNewMethodBasedFunctionStep3.HelpNamespaceName"); ///"Error" public static string AddNewMethodBasedFunctionStep3_LabelError=>T("AddNewMethodBasedFunctionStep3.LabelError"); ///"Cascade delete error" public static string CascadeDeleteErrorTitle=>T("CascadeDeleteErrorTitle"); ///"The type is referenced by another type that does not allow cascade deletes. This operation is halted" public static string CascadeDeleteErrorMessage=>T("CascadeDeleteErrorMessage"); ///"Could not find type" public static string AddFunction_CouldNotFindType=>T("AddFunction.CouldNotFindType"); ///"The type does not contain any valid method" public static string AddFunction_TypeHasNoValidMethod=>T("AddFunction.TypeHasNoValidMethod"); ///"The type is marked as either abstract or static. Calling methods on abstract or static types is not supported." public static string AddFunction_TypeIsAbstractOrStatic=>T("AddFunction.TypeIsAbstractOrStatic"); ///"The type must not have overloads" public static string AddFunction_TypeMustNotHaveOverloads=>T("AddFunction.TypeMustNotHaveOverloads"); ///"Method name must be non-empty" public static string AddFunction_MethodNameIsEmpty=>T("AddFunction.MethodNameIsEmpty"); ///"Namespace must be like A.B.C - not start and end with ." public static string AddFunction_InvalidNamespace=>T("AddFunction.InvalidNamespace"); ///"The function name '{0}' is already used" public static string AddFunction_NameAlreadyUsed_Template=>T("AddFunction.NameAlreadyUsed"); ///"The function name '{0}' is already used" public static string AddFunction_NameAlreadyUsed(object parameter0)=>string.Format(T("AddFunction.NameAlreadyUsed"), parameter0); ///"Edit Method Based Query" public static string EditMethodBasedFunction_LabelFieldGroup=>T("EditMethodBasedFunction.LabelFieldGroup"); ///"Method Name" public static string EditMethodBasedFunction_LabelMethodName=>T("EditMethodBasedFunction.LabelMethodName"); ///"The name that the function should be know under." public static string EditMethodBasedFunction_LabelMethodNameHelp=>T("EditMethodBasedFunction.LabelMethodNameHelp"); ///"Namespace Name" public static string EditMethodBasedFunction_LabelNamespaceName=>T("EditMethodBasedFunction.LabelNamespaceName"); ///"The namespace to place the method under." public static string EditMethodBasedFunction_LabelNamespaceNameHelp=>T("EditMethodBasedFunction.LabelNamespaceNameHelp"); ///"Type" public static string EditMethodBasedFunction_LabelType=>T("EditMethodBasedFunction.LabelType"); ///"The type that contains the method in question." public static string EditMethodBasedFunction_LabelTypeHelp=>T("EditMethodBasedFunction.LabelTypeHelp"); ///"Method" public static string EditMethodBasedFunction_LabelMethod=>T("EditMethodBasedFunction.LabelMethod"); ///"The method to invoke on the type." public static string EditMethodBasedFunction_LabelMethodHelp=>T("EditMethodBasedFunction.LabelMethodHelp"); ///"Error" public static string EditMethodBasedFunction_LabelError=>T("EditMethodBasedFunction.LabelError"); ///"Method name must be non-empty" public static string EditFunction_MethodNameEmpty=>T("EditFunction.MethodNameEmpty"); ///"Namespace must not start and end with . - example A.B.C" public static string EditFunction_InvalidNamespace=>T("EditFunction.InvalidNamespace"); ///"Could not find type" public static string EditFunction_TypeNotFound=>T("EditFunction.TypeNotFound"); ///"The type does not contain the method" public static string EditFunction_MethodNotInType=>T("EditFunction.MethodNotInType"); ///"The type does not contain any valid method" public static string EditFunction_NoValidMethod=>T("EditFunction.NoValidMethod"); ///"The type must not have overloads" public static string EditFunction_MethodOverloadsNotAllowed=>T("EditFunction.MethodOverloadsNotAllowed"); ///"Settings" public static string AddInlineFunctionWorkflow_FieldGroup_Label=>T("AddInlineFunctionWorkflow.FieldGroup.Label"); ///"Name" public static string AddInlineFunctionWorkflow_MethodName_Label=>T("AddInlineFunctionWorkflow.MethodName.Label"); ///"The name of the method you want to create" public static string AddInlineFunctionWorkflow_MethodName_Help=>T("AddInlineFunctionWorkflow.MethodName.Help"); ///"Namespace" public static string AddInlineFunctionWorkflow_MethodNamespace_Label=>T("AddInlineFunctionWorkflow.MethodNamespace.Label"); ///"The namespace of the method you want to create" public static string AddInlineFunctionWorkflow_MethodNamespace_Help=>T("AddInlineFunctionWorkflow.MethodNamespace.Help"); ///"Description" public static string AddInlineFunctionWorkflow_MethodDescription_Label=>T("AddInlineFunctionWorkflow.MethodDescription.Label"); ///"A short description of the function" public static string AddInlineFunctionWorkflow_MethodDescription_Help=>T("AddInlineFunctionWorkflow.MethodDescription.Help"); ///"Template" public static string AddInlineFunctionWorkflow_InlineFunctionMethodTemplate_Label=>T("AddInlineFunctionWorkflow.InlineFunctionMethodTemplate.Label"); ///"Select the template that you want to use for the new method." public static string AddInlineFunctionWorkflow_InlineFunctionMethodTemplate_Help=>T("AddInlineFunctionWorkflow.InlineFunctionMethodTemplate.Help"); ///"Settings" public static string EditInlineFunctionWorkflow_FieldGroup_Label=>T("EditInlineFunctionWorkflow.FieldGroup.Label"); ///"Name" public static string EditInlineFunctionWorkflow_MethodName_Label=>T("EditInlineFunctionWorkflow.MethodName.Label"); ///"The name of the method you want to create" public static string EditInlineFunctionWorkflow_MethodName_Help=>T("EditInlineFunctionWorkflow.MethodName.Help"); ///"Namespace" public static string EditInlineFunctionWorkflow_MethodNamespace_Label=>T("EditInlineFunctionWorkflow.MethodNamespace.Label"); ///"The namespace of the method you want to create" public static string EditInlineFunctionWorkflow_MethodNamespace_Help=>T("EditInlineFunctionWorkflow.MethodNamespace.Help"); ///"Description" public static string EditInlineFunctionWorkflow_MethodDescription_Label=>T("EditInlineFunctionWorkflow.MethodDescription.Label"); ///"A short description of the function" public static string EditInlineFunctionWorkflow_MethodDescription_Help=>T("EditInlineFunctionWorkflow.MethodDescription.Help"); ///"Debug" public static string EditInlineFunctionWorkflow_DebugFieldGroup_Label=>T("EditInlineFunctionWorkflow.DebugFieldGroup.Label"); ///"Page" public static string EditInlineFunctionWorkflow_DebugPage_Label=>T("EditInlineFunctionWorkflow.DebugPage.Label"); ///"When debugging, this page is used as current page" public static string EditInlineFunctionWorkflow_DebugPage_Help=>T("EditInlineFunctionWorkflow.DebugPage.Help"); ///"Data scope" public static string EditInlineFunctionWorkflow_DebugPageDataScope_Label=>T("EditInlineFunctionWorkflow.DebugPageDataScope.Label"); ///"When debugging, this is used as current data scope" public static string EditInlineFunctionWorkflow_DebugPageDataScope_Help=>T("EditInlineFunctionWorkflow.DebugPageDataScope.Help"); ///"Language" public static string EditInlineFunctionWorkflow_DebugActiveLocale_Label=>T("EditInlineFunctionWorkflow.DebugActiveLocale.Label"); ///"When debugging, this is used as the current language" public static string EditInlineFunctionWorkflow_DebugActiveLocale_Help=>T("EditInlineFunctionWorkflow.DebugActiveLocale.Help"); ///"Source" public static string EditInlineFunctionWorkflow_Code_Label=>T("EditInlineFunctionWorkflow.Code.Label"); ///"Assembly References" public static string EditInlineFunctionWorkflow_AssembliesFieldGroup_Label=>T("EditInlineFunctionWorkflow.AssembliesFieldGroup.Label"); ///"Preview" public static string EditInlineFunctionWorkflow_Preview_Label=>T("EditInlineFunctionWorkflow.Preview.Label"); ///"Input Parameters" public static string EditInlineFunctionWorkflow_ParameterFieldGroup_Label=>T("EditInlineFunctionWorkflow.ParameterFieldGroup.Label"); ///"Administrative" public static string EditInlineFunctionWorkflow_AdminitrativeScope_Label=>T("EditInlineFunctionWorkflow.AdminitrativeScope.Label"); ///"Public" public static string EditInlineFunctionWorkflow_PublicScope_Label=>T("EditInlineFunctionWorkflow.PublicScope.Label"); ///"Empty method" public static string InlineFunctionMethodTemplate_Clean=>T("InlineFunctionMethodTemplate.Clean"); ///"Method with parameters" public static string InlineFunctionMethodTemplate_WithParameters=>T("InlineFunctionMethodTemplate.WithParameters"); ///"Method using data connection" public static string InlineFunctionMethodTemplate_DataConnection=>T("InlineFunctionMethodTemplate.DataConnection"); ///"A public static class named {0} is missing from the code. This class should contain the function method." public static string CSharpInlineFunction_OnMissingContainerType_Template=>T("CSharpInlineFunction.OnMissingContainerType"); ///"A public static class named {0} is missing from the code. This class should contain the function method." public static string CSharpInlineFunction_OnMissingContainerType(object parameter0)=>string.Format(T("CSharpInlineFunction.OnMissingContainerType"), parameter0); ///"The namespace in the code '{0}' does not match the given function namespace '{1}'." public static string CSharpInlineFunction_OnNamespaceMismatch_Template=>T("CSharpInlineFunction.OnNamespaceMismatch"); ///"The namespace in the code '{0}' does not match the given function namespace '{1}'." public static string CSharpInlineFunction_OnNamespaceMismatch(object parameter0,object parameter1)=>string.Format(T("CSharpInlineFunction.OnNamespaceMismatch"), parameter0,parameter1); ///"The given function name '{0}' was not found or not public static in the class '{1}'." public static string CSharpInlineFunction_OnMissionMethod_Template=>T("CSharpInlineFunction.OnMissionMethod"); ///"The given function name '{0}' was not found or not public static in the class '{1}'." public static string CSharpInlineFunction_OnMissionMethod(object parameter0,object parameter1)=>string.Format(T("CSharpInlineFunction.OnMissionMethod"), parameter0,parameter1); ///"The parameter '{0}' has not been added to 'Input Parameters' - to call your function you need to add the parameter and give it either a test or default value." public static string CSharpInlineFunction_MissingParameterDefinition_Template=>T("CSharpInlineFunction.MissingParameterDefinition"); ///"The parameter '{0}' has not been added to 'Input Parameters' - to call your function you need to add the parameter and give it either a test or default value." public static string CSharpInlineFunction_MissingParameterDefinition(object parameter0)=>string.Format(T("CSharpInlineFunction.MissingParameterDefinition"), parameter0); ///"The parameter '{0}' is expecting test value of type '{1}', got value of type '{2}'." public static string CSharpInlineFunction_WrongParameterTestValueType_Template=>T("CSharpInlineFunction.WrongParameterTestValueType"); ///"The parameter '{0}' is expecting test value of type '{1}', got value of type '{2}'." public static string CSharpInlineFunction_WrongParameterTestValueType(object parameter0,object parameter1,object parameter2)=>string.Format(T("CSharpInlineFunction.WrongParameterTestValueType"), parameter0,parameter1,parameter2); ///"The parameter '{0}' defined on 'Input Parameters' must have a test or default value before your function can be evaluated." public static string CSharpInlineFunction_MissingParameterTestOrDefaultValue_Template=>T("CSharpInlineFunction.MissingParameterTestOrDefaultValue"); ///"The parameter '{0}' defined on 'Input Parameters' must have a test or default value before your function can be evaluated." public static string CSharpInlineFunction_MissingParameterTestOrDefaultValue(object parameter0)=>string.Format(T("CSharpInlineFunction.MissingParameterTestOrDefaultValue"), parameter0); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_PackageElementProvider { ///"Packages" public static string RootFolderLabel=>T("RootFolderLabel"); ///"Explore and manage installed packages" public static string RootFolderToolTip=>T("RootFolderToolTip"); ///"Available Packages" public static string AvailablePackagesFolderLabel=>T("AvailablePackagesFolderLabel"); ///"Available packages" public static string AvailablePackagesFolderToolTip=>T("AvailablePackagesFolderToolTip"); ///"Installed Packages" public static string InstalledPackageFolderLabel=>T("InstalledPackageFolderLabel"); ///"Installed packages" public static string InstalledPackageFolderToolTip=>T("InstalledPackageFolderToolTip"); ///"Local Packages" public static string LocalPackagesFolderLabel=>T("LocalPackagesFolderLabel"); ///"Local packages" public static string LocalPackagesFolderToolTip=>T("LocalPackagesFolderToolTip"); ///"Package Sources" public static string PackageSourcesFolderLabel=>T("PackageSourcesFolderLabel"); ///"Package sources" public static string PackageSourcesFolderToolTip=>T("PackageSourcesFolderToolTip"); ///"Package Info" public static string ViewAvailableInformationLabel=>T("ViewAvailableInformationLabel"); ///"View package information" public static string ViewAvailableInformationToolTip=>T("ViewAvailableInformationToolTip"); ///"Install" public static string InstallLabel=>T("InstallLabel"); ///"Install this C1 Package on your system" public static string InstallToolTip=>T("InstallToolTip"); ///"Package Info" public static string ViewInstalledInformationLabel=>T("ViewInstalledInformationLabel"); ///"View package information" public static string ViewInstalledInformationToolTip=>T("ViewInstalledInformationToolTip"); ///"Install Local Package..." public static string InstallLocalPackageLabel=>T("InstallLocalPackageLabel"); ///"Install package from local file system" public static string InstallLocalPackageToolTip=>T("InstallLocalPackageToolTip"); ///"Add Package Source" public static string AddPackageSourceLabel=>T("AddPackageSourceLabel"); ///"Add package source" public static string AddPackageSourceToolTip=>T("AddPackageSourceToolTip"); ///"Delete Package Source" public static string DeletePackageSourceLabel=>T("DeletePackageSourceLabel"); ///"Delete package source" public static string DeletePackageSourceToolTip=>T("DeletePackageSourceToolTip"); ///"Clear Cache" public static string ClearServerCacheLabel=>T("ClearServerCacheLabel"); ///"Clear cache to get the newest packages" public static string ClearServerCacheToolTip=>T("ClearServerCacheToolTip"); ///"Package Info" public static string ViewAvailableInformation_FieldGroupLabel=>T("ViewAvailableInformation.FieldGroupLabel"); ///"Name" public static string ViewAvailableInformation_NameTextLabel=>T("ViewAvailableInformation.NameTextLabel"); ///"Description" public static string ViewAvailableInformation_DescriptionTextLabel=>T("ViewAvailableInformation.DescriptionTextLabel"); ///"Author" public static string ViewAvailableInformation_AuthorTextLabel=>T("ViewAvailableInformation.AuthorTextLabel"); ///"Free Trial Info" public static string ViewAvailableInformation_TrialInfoFieldGroupLabel=>T("ViewAvailableInformation.TrialInfoFieldGroupLabel"); ///"Trial information" public static string ViewAvailableInformation_TrialInformationLabel=>T("ViewAvailableInformation.TrialInformationLabel"); ///"This is a commercial package, available for free in the trial period. When the trial period has expired functionality may be degraded, unless you choose to purchase a license." public static string ViewAvailableInformation_TrialInformationText=>T("ViewAvailableInformation.TrialInformationText"); ///"Free trial period (days)" public static string ViewAvailableInformation_TrialDaysLabel=>T("ViewAvailableInformation.TrialDaysLabel"); ///"License Information" public static string ViewAvailableInformation_LicenseInformationGroupLabel=>T("ViewAvailableInformation.LicenseInformationGroupLabel"); ///"Subscription Name" public static string ViewAvailableInformation_SubscriptionNameLabel=>T("ViewAvailableInformation.SubscriptionNameLabel"); ///"License Expiration Date" public static string ViewAvailableInformation_LicenseExpirationDateLabel=>T("ViewAvailableInformation.LicenseExpirationDateLabel"); ///"Installation Info" public static string ViewAvailableInformation_InstallationInfoFieldGroupLabel=>T("ViewAvailableInformation.InstallationInfoFieldGroupLabel"); ///"Version" public static string ViewAvailableInformation_VersionTextLabel=>T("ViewAvailableInformation.VersionTextLabel"); ///"Technical Description" public static string ViewAvailableInformation_TechicalDescriptionTextLabel=>T("ViewAvailableInformation.TechicalDescriptionTextLabel"); ///"Source" public static string ViewAvailableInformation_PackageSourceTextLabel=>T("ViewAvailableInformation.PackageSourceTextLabel"); ///"Price" public static string ViewAvailableInformation_PriceTextLabel=>T("ViewAvailableInformation.PriceTextLabel"); ///"Subscriptions that include this package" public static string ViewAvailableInformation_SubscriptionListLabel=>T("ViewAvailableInformation.SubscriptionListLabel"); ///"Install" public static string ViewAvailableInformation_Toolbar_InstallLabel=>T("ViewAvailableInformation.Toolbar.InstallLabel"); ///"Read more" public static string ViewAvailableInformation_Toolbar_ReadMoreLabel=>T("ViewAvailableInformation.Toolbar.ReadMoreLabel"); ///"Already Installed" public static string ViewAvailableInformation_ShowError_MessageTitle=>T("ViewAvailableInformation.ShowError.MessageTitle"); ///"The package is already installed, cannot install the selected package." public static string ViewAvailableInformation_ShowError_MessageMessage=>T("ViewAvailableInformation.ShowError.MessageMessage"); ///"Package server did not respond" public static string ViewAvailableInformation_ShowServerError_MessageTitle=>T("ViewAvailableInformation.ShowServerError.MessageTitle"); ///"The package server did not respond, try again or contact the system administrator" public static string ViewAvailableInformation_ShowServerError_MessageMessage=>T("ViewAvailableInformation.ShowServerError.MessageMessage"); ///"Package Info" public static string ViewInstalledInformation_FieldGroupLabel=>T("ViewInstalledInformation.FieldGroupLabel"); ///"Name" public static string ViewInstalledInformation_NameTextLabel=>T("ViewInstalledInformation.NameTextLabel"); ///"Installation date" public static string ViewInstalledInformation_DateTextLabel=>T("ViewInstalledInformation.DateTextLabel"); ///"Installed by" public static string ViewInstalledInformation_UserTextLabel=>T("ViewInstalledInformation.UserTextLabel"); ///"Author" public static string ViewInstalledInformation_AuthorTextLabel=>T("ViewInstalledInformation.AuthorTextLabel"); ///"Version" public static string ViewInstalledInformation_VersionTextLabel=>T("ViewInstalledInformation.VersionTextLabel"); ///"Trial info" public static string ViewInstalledInformation_TrialInfoFieldGroupLabel=>T("ViewInstalledInformation.TrialInfoFieldGroupLabel"); ///"Trial information" public static string ViewInstalledInformation_TrialInformationLabel=>T("ViewInstalledInformation.TrialInformationLabel"); ///"This is a commercial package, available for free in the trial period. When the trial period has expired functionality may be degraded, unless you choose to purchase a license." public static string ViewInstalledInformation_TrialInformationText=>T("ViewInstalledInformation.TrialInformationText"); ///"Trial expiration date" public static string ViewInstalledInformation_TrialExpireLabel=>T("ViewInstalledInformation.TrialExpireLabel"); ///"License Information" public static string ViewInstalledInformation_LicenseInformationGroupLabel=>T("ViewInstalledInformation.LicenseInformationGroupLabel"); ///"Subscription Name" public static string ViewInstalledInformation_SubscriptionNameLabel=>T("ViewInstalledInformation.SubscriptionNameLabel"); ///"License Expiration Date" public static string ViewInstalledInformation_LicenseExpirationDateLabel=>T("ViewInstalledInformation.LicenseExpirationDateLabel"); ///"Uninstall" public static string ViewInstalledInformation_Toolbar_UninstallLabel=>T("ViewInstalledInformation.Toolbar.UninstallLabel"); ///"Purchase this!" public static string ViewInstalledInformation_Toolbar_PurchaseLabel=>T("ViewInstalledInformation.Toolbar.PurchaseLabel"); ///"Already Uninstalled" public static string ViewInstalledInformation_ShowError_MessageTitle=>T("ViewInstalledInformation.ShowError.MessageTitle"); ///"The package is already uninstalled, cannot uninstall the selected package." public static string ViewInstalledInformation_ShowError_MessageMessage=>T("ViewInstalledInformation.ShowError.MessageMessage"); ///"Install Package" public static string InstallRemotePackage_Step1_LayoutLabel=>T("InstallRemotePackage.Step1.LayoutLabel"); ///"This is a trial/payment package" public static string InstallRemotePackage_Step1_HeadingTitle=>T("InstallRemotePackage.Step1.HeadingTitle"); ///"This package is subject to payment - please examine the EULA on the next screen for details about trial period and payment terms." public static string InstallRemotePackage_Step1_HeadingDescription=>T("InstallRemotePackage.Step1.HeadingDescription"); ///"Install Package" public static string InstallRemotePackage_Step2_LayoutLabel=>T("InstallRemotePackage.Step2.LayoutLabel"); ///"License agreement" public static string InstallRemotePackage_Step2_HeadingTitle=>T("InstallRemotePackage.Step2.HeadingTitle"); ///"If you accept the terms of the agreement, click the check box below. You must accept the agreement to install." public static string InstallRemotePackage_Step2_HeadingDescription=>T("InstallRemotePackage.Step2.HeadingDescription"); ///"I accept the license agreement" public static string InstallRemotePackage_Step2_IAcceptItemLabel=>T("InstallRemotePackage.Step2.IAcceptItemLabel"); ///"You must accept the terms of the license agreement before you can proceed." public static string InstallRemotePackage_Step2_AcceptMissing=>T("InstallRemotePackage.Step2.AcceptMissing"); ///"Install Package" public static string InstallRemotePackage_Step3_LayoutLabel=>T("InstallRemotePackage.Step3.LayoutLabel"); ///"Download and validate package" public static string InstallRemotePackage_Step3_HeadingTitle=>T("InstallRemotePackage.Step3.HeadingTitle"); ///"The package will be downloaded and validated. Please note that this may take several minutes. Click Next to continue." public static string InstallRemotePackage_Step3_HeadingDescription=>T("InstallRemotePackage.Step3.HeadingDescription"); ///"Install Local Package" public static string InstallRemotePackage_Step4_LayoutLabel=>T("InstallRemotePackage.Step4.LayoutLabel"); ///"Ready to install" public static string InstallRemotePackage_Step4_HeadingTitle=>T("InstallRemotePackage.Step4.HeadingTitle"); ///"Ready to install the package. Please note that the installation may take several minutes. Click Next to continue." public static string InstallRemotePackage_Step4_HeadingDescription=>T("InstallRemotePackage.Step4.HeadingDescription"); ///"Ready to install" public static string InstallRemotePackage_Step4_NonUninstallableHeadingTitle=>T("InstallRemotePackage.Step4.NonUninstallableHeadingTitle"); ///"Ready to install the package. Please note that the installation may take several minutes. Also note that this package can not be uninstalled. Click Next to continue." public static string InstallRemotePackage_Step4_NonUninstallableHeadingDescription=>T("InstallRemotePackage.Step4.NonUninstallableHeadingDescription"); ///"Package Installed" public static string InstallRemotePackage_Step5_LayoutLabel=>T("InstallRemotePackage.Step5.LayoutLabel"); ///"Package installed successfully" public static string InstallRemotePackage_Step5_HeadingTitle=>T("InstallRemotePackage.Step5.HeadingTitle"); ///"Package installed successfully." public static string InstallRemotePackage_Step5_HeadingDescription=>T("InstallRemotePackage.Step5.HeadingDescription"); ///"Package installation failed" public static string InstallRemotePackage_ShowError_LayoutLabel=>T("InstallRemotePackage.ShowError.LayoutLabel"); ///"Package Installation Failed" public static string InstallRemotePackage_ShowError_InfoTableCaption=>T("InstallRemotePackage.ShowError.InfoTableCaption"); ///"Message" public static string InstallRemotePackage_ShowError_MessageTitle=>T("InstallRemotePackage.ShowError.MessageTitle"); ///"The package Did Not Validate" public static string InstallRemotePackage_ShowWarning_LayoutLabel=>T("InstallRemotePackage.ShowWarning.LayoutLabel"); ///"The package did not validate" public static string InstallRemotePackage_ShowWarning_InfoTableCaption=>T("InstallRemotePackage.ShowWarning.InfoTableCaption"); ///"Install Local Package" public static string InstallLocalPackage_Step1_LayoutLabel=>T("InstallLocalPackage.Step1.LayoutLabel"); ///"Package file" public static string InstallLocalPackage_Step1_FileUploadLabel=>T("InstallLocalPackage.Step1.FileUploadLabel"); ///"Browse to and select the local package file" public static string InstallLocalPackage_Step1_FileUploadHelp=>T("InstallLocalPackage.Step1.FileUploadHelp"); ///"Install Local Package" public static string InstallLocalPackage_Step2_LayoutLabel=>T("InstallLocalPackage.Step2.LayoutLabel"); ///"Ready to install" public static string InstallLocalPackage_Step2_HeadingTitle=>T("InstallLocalPackage.Step2.HeadingTitle"); ///"Ready to install the package. Please note that the installation may take several minutes. Click Next to continue." public static string InstallLocalPackage_Step2_HeadingDescription=>T("InstallLocalPackage.Step2.HeadingDescription"); ///"Package Installed" public static string InstallLocalPackage_Step3_LayoutLabel=>T("InstallLocalPackage.Step3.LayoutLabel"); ///"Package installed successfully" public static string InstallLocalPackage_Step3_HeadingTitle=>T("InstallLocalPackage.Step3.HeadingTitle"); ///"Package installed successfully." public static string InstallLocalPackage_Step3_HeadingDescription=>T("InstallLocalPackage.Step3.HeadingDescription"); ///"Package Installation Failed" public static string InstallLocalPackage_ShowError_LayoutLabel=>T("InstallLocalPackage.ShowError.LayoutLabel"); ///"Package installation failed" public static string InstallLocalPackage_ShowError_InfoTableCaption=>T("InstallLocalPackage.ShowError.InfoTableCaption"); ///"Message" public static string InstallLocalPackage_ShowError_MessageTitle=>T("InstallLocalPackage.ShowError.MessageTitle"); ///"The package Did Not Validate" public static string InstallLocalPackage_ShowWarning_LayoutLabel=>T("InstallLocalPackage.ShowWarning.LayoutLabel"); ///"The package did not validate" public static string InstallLocalPackage_ShowWarning_InfoTableCaption=>T("InstallLocalPackage.ShowWarning.InfoTableCaption"); ///"Uninstall Package" public static string UninstallRemotePackage_Step1_LayoutLabel=>T("UninstallRemotePackage.Step1.LayoutLabel"); ///"Ready to check uninstallation process" public static string UninstallRemotePackage_Step1_HeadingTitle=>T("UninstallRemotePackage.Step1.HeadingTitle"); ///"Ready to check the uninstall process of the package. Click Next to continue." public static string UninstallRemotePackage_Step1_HeadingDescription=>T("UninstallRemotePackage.Step1.HeadingDescription"); ///"Uninstall Package" public static string UninstallRemotePackage_Step2_LayoutLabel=>T("UninstallRemotePackage.Step2.LayoutLabel"); ///"Ready to uninstall" public static string UninstallRemotePackage_Step2_HeadingTitle=>T("UninstallRemotePackage.Step2.HeadingTitle"); ///"Ready to uninstall the package. Please note that the installation may take several minutes. Click Next to continue." public static string UninstallRemotePackage_Step2_HeadingDescription=>T("UninstallRemotePackage.Step2.HeadingDescription"); ///"Package Uninstalled" public static string UninstallRemotePackage_Step3_LayoutLabel=>T("UninstallRemotePackage.Step3.LayoutLabel"); ///"Package uninstalled successfully" public static string UninstallRemotePackage_Step3_HeadingTitle=>T("UninstallRemotePackage.Step3.HeadingTitle"); ///"Package uninstalled successfully." public static string UninstallRemotePackage_Step3_HeadingDescription=>T("UninstallRemotePackage.Step3.HeadingDescription"); ///"Package Uninstallation Failed" public static string UninstallRemotePackage_ShowError_LayoutLabel=>T("UninstallRemotePackage.ShowError.LayoutLabel"); ///"Package uninstallation failed" public static string UninstallRemotePackage_ShowError_InfoTableCaption=>T("UninstallRemotePackage.ShowError.InfoTableCaption"); ///"Message" public static string UninstallRemotePackage_ShowError_MessageTitle=>T("UninstallRemotePackage.ShowError.MessageTitle"); ///"Uninstall Package" public static string UninstallRemotePackage_ShowUnregistre_LayoutLabel=>T("UninstallRemotePackage.ShowUnregistre.LayoutLabel"); ///"Registration of uninstallation failed" public static string UninstallRemotePackage_ShowUnregistre_HeadingTitle=>T("UninstallRemotePackage.ShowUnregistre.HeadingTitle"); ///"The registration of uninstallation failed. Contact the package vendor for manual unregistration." public static string UninstallRemotePackage_ShowUnregistre_HeadingDescription=>T("UninstallRemotePackage.ShowUnregistre.HeadingDescription"); ///"Uninstall Local Package" public static string UninstallLocalPackage_Step1_LayoutLabel=>T("UninstallLocalPackage.Step1.LayoutLabel"); ///"Ready to check uninstallation process" public static string UninstallLocalPackage_Step1_HeadingTitle=>T("UninstallLocalPackage.Step1.HeadingTitle"); ///"Ready to check the uninstall process of the package. Click Next to continue." public static string UninstallLocalPackage_Step1_HeadingDescription=>T("UninstallLocalPackage.Step1.HeadingDescription"); ///"Uninstall Local Package" public static string UninstallLocalPackage_Step2_LayoutLabel=>T("UninstallLocalPackage.Step2.LayoutLabel"); ///"Ready to uninstall" public static string UninstallLocalPackage_Step2_HeadingTitle=>T("UninstallLocalPackage.Step2.HeadingTitle"); ///"Ready to uninstall the package. Please note that the installation may take several minutes. Click Next to continue." public static string UninstallLocalPackage_Step2_HeadingDescription=>T("UninstallLocalPackage.Step2.HeadingDescription"); ///"Package Uninstalled" public static string UninstallLocalPackage_Step3_LayoutLabel=>T("UninstallLocalPackage.Step3.LayoutLabel"); ///"Package uninstalled successfully" public static string UninstallLocalPackage_Step3_HeadingTitle=>T("UninstallLocalPackage.Step3.HeadingTitle"); ///"Package uninstalled successfully." public static string UninstallLocalPackage_Step3_HeadingDescription=>T("UninstallLocalPackage.Step3.HeadingDescription"); ///"Package Uninstallation Failed" public static string UninstallLocalPackage_ShowError_LayoutLabel=>T("UninstallLocalPackage.ShowError.LayoutLabel"); ///"Package uninstallation failed" public static string UninstallLocalPackage_ShowError_InfoTableCaption=>T("UninstallLocalPackage.ShowError.InfoTableCaption"); ///"Message" public static string UninstallLocalPackage_ShowError_MessageTitle=>T("UninstallLocalPackage.ShowError.MessageTitle"); ///"New Package Source" public static string AddPackageSource_Step1_LayoutLabel=>T("AddPackageSource.Step1.LayoutLabel"); ///"Package source data" public static string AddPackageSource_Step1_FieldGroupLabel=>T("AddPackageSource.Step1.FieldGroupLabel"); ///"Package web service URL" public static string AddPackageSource_Step1_UrlLabel=>T("AddPackageSource.Step1.UrlLabel"); ///"Packages can be hosted on remote servers. The package web service URL will be validated in the next step." public static string AddPackageSource_Step1_UrlHelp=>T("AddPackageSource.Step1.UrlHelp"); ///"The entered text was not a valid URL" public static string AddPackageSource_Step1_UrlNotValid=>T("AddPackageSource.Step1.UrlNotValid"); ///"The server is not a C1 CMS package server" public static string AddPackageSource_Step1_UrlNonPackageServer=>T("AddPackageSource.Step1.UrlNonPackageServer"); ///"Add Package Server Source" public static string AddPackageSource_Step2_LayoutLabel=>T("AddPackageSource.Step2.LayoutLabel"); ///"Server URL is valid" public static string AddPackageSource_Step2_HeadingTitle=>T("AddPackageSource.Step2.HeadingTitle"); ///"Note that the HTTP protocol is used on this connection. This implies that all information will be send unencrypted. Click Finish to add the source." public static string AddPackageSource_Step2_HeadingNoHttpsDescription=>T("AddPackageSource.Step2.HeadingNoHttpsDescription"); ///"Click Finish to add the source." public static string AddPackageSource_Step2_HeadingWithHttpsDescription=>T("AddPackageSource.Step2.HeadingWithHttpsDescription"); ///"Delete Confirmation" public static string DeletePackageSource_Step1_LayoutLabel=>T("DeletePackageSource.Step1.LayoutLabel"); ///"Delete the selected server source" public static string DeletePackageSource_Step1_Text=>T("DeletePackageSource.Step1.Text"); ///"Trial Period Has Expired" public static string ConfirmLicense_ExpiredTitle=>T("ConfirmLicense.ExpiredTitle"); ///"The trial period of the package has expired. You need to obtain a valid license." public static string ConfirmLicense_ExpiredMessage=>T("ConfirmLicense.ExpiredMessage"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_PageElementProvider { ///"Add New Page" public static string AddNewPageStep1_DialogLabel=>T("AddNewPageStep1.DialogLabel"); ///"Add New {0}" public static string AddNewPageStep1_DialogLabelFormat_Template=>T("AddNewPageStep1.DialogLabelFormat"); ///"Add New {0}" public static string AddNewPageStep1_DialogLabelFormat(object parameter0)=>string.Format(T("AddNewPageStep1.DialogLabelFormat"), parameter0); ///"General settings" public static string GeneralSettings_FieldGroupLabel=>T("GeneralSettings.FieldGroupLabel"); ///"Publication settings" public static string PublicationSettings_FieldGroupLabel=>T("PublicationSettings.FieldGroupLabel"); ///"Advanced settings" public static string AdvancedSettings_FieldGroupLabel=>T("AdvancedSettings.FieldGroupLabel"); ///"Page title" public static string AddNewPageStep1_LabelTitle=>T("AddNewPageStep1.LabelTitle"); ///"The entry specified in this field is shown in the browser window title bar. The field is used by search engines and sitemaps" public static string AddNewPageStep1_LabelTitleHelp=>T("AddNewPageStep1.LabelTitleHelp"); ///"Description" public static string AddNewPageStep1_LabelAbstract=>T("AddNewPageStep1.LabelAbstract"); ///"Use this field for at short description of the page" public static string AddNewPageStep1_LabelAbstractHelp=>T("AddNewPageStep1.LabelAbstractHelp"); ///"Page type" public static string AddNewPageStep1_LabelTemplate=>T("AddNewPageStep1.LabelTemplate"); ///"The page type selection influences the behavior and features of your page, like 'a normal page' or 'a blog'. The options available depend on features installed." public static string AddNewPageStep1_HelpTemplate=>T("AddNewPageStep1.HelpTemplate"); ///"Position" public static string AddNewPageStep1_LabelPosition=>T("AddNewPageStep1.LabelPosition"); ///"Select where in the content tree you want the page to be placed." public static string AddNewPageStep1_HelpPosition=>T("AddNewPageStep1.HelpPosition"); ///"Insert at the top" public static string AddNewPageStep1_LabelAddToTop=>T("AddNewPageStep1.LabelAddToTop"); ///"Insert at the bottom" public static string AddNewPageStep1_LabelAddToBottom=>T("AddNewPageStep1.LabelAddToBottom"); ///"Insert alphabetically" public static string AddNewPageStep1_LabelAddAlphabetic=>T("AddNewPageStep1.LabelAddAlphabetic"); ///"Select position..." public static string AddNewPageStep1_LabelAddBelowOtherPage=>T("AddNewPageStep1.LabelAddBelowOtherPage"); ///"URL title" public static string AddNewPageStep2_LabelUrlTitle=>T("AddNewPageStep2.LabelUrlTitle"); ///"The entry specified in this field is shown in the browser address bar. The field is used by search engines" public static string AddNewPageStep2_HelpUrlTitle=>T("AddNewPageStep2.HelpUrlTitle"); ///"Menu title" public static string AddNewPageStep2_LabelMenuTitle=>T("AddNewPageStep2.LabelMenuTitle"); ///"The entry specified in this field can be used in the navigation on the website" public static string AddNewPageStep2_HelpMenuTitle=>T("AddNewPageStep2.HelpMenuTitle"); ///"Select detailed page position" public static string AddNewPageStep2_LabelPositionSelectorPanel=>T("AddNewPageStep2.LabelPositionSelectorPanel"); ///"Position below" public static string AddNewPageStep2_LabelPositionSelector=>T("AddNewPageStep2.LabelPositionSelector"); ///"" public static string AddNewPageStep2_HelpPositionSelector=>T("AddNewPageStep2.HelpPositionSelector"); ///"The specified title is too long. Make it shorter and try again" public static string AddNewPageStep1_TitleTooLong=>T("AddNewPageStep1.TitleTooLong"); ///"The specified menu title is too long. Make it shorter and try again" public static string AddNewPageStep1_MenuTitleTooLong=>T("AddNewPageStep1.MenuTitleTooLong"); ///"Settings" public static string EditPage_LabelPaneSettings=>T("EditPage.LabelPaneSettings"); ///"Status" public static string EditPage_LabelPublicationState=>T("EditPage.LabelPublicationState"); ///"Send the page to another status" public static string EditPage_HelpPublicationState=>T("EditPage.HelpPublicationState"); ///"Page title" public static string EditPage_LabelPageTitle=>T("EditPage.LabelPageTitle"); ///"The entry specified in this field is shown in the browser window title bar. The field is used by search engines and sitemaps" public static string EditPage_LabelPageTitleHelp=>T("EditPage.LabelPageTitleHelp"); ///"Menu title" public static string EditPage_LabelMenuTitle=>T("EditPage.LabelMenuTitle"); ///"The entry specified in this field can be used in the navigation on the website" public static string EditPage_HelpMenuTitle=>T("EditPage.HelpMenuTitle"); ///"URL title" public static string EditPage_LabelUrlTitle=>T("EditPage.LabelUrlTitle"); ///"URL title was rewritten" public static string EditPage_UrlTitleFormattedTitle=>T("EditPage.UrlTitleFormattedTitle"); ///"According to the current URL replacement rules, URL title was changed to '{0}'" public static string EditPage_UrlTitleFormattedMessage_Template=>T("EditPage.UrlTitleFormattedMessage"); ///"According to the current URL replacement rules, URL title was changed to '{0}'" public static string EditPage_UrlTitleFormattedMessage(object parameter0)=>string.Format(T("EditPage.UrlTitleFormattedMessage"), parameter0); ///"The entry specified in this field is shown in the browser address bar as a part of the URL address. The field is used by search engines" public static string EditPage_HelpUrlTitle=>T("EditPage.HelpUrlTitle"); ///"Friendly URL" public static string EditPage_LabelFriendlyUrl=>T("EditPage.LabelFriendlyUrl"); ///"The entry specified in this field is a shorter version of the actual page URL and redirects to it, when entered in the browser address bar. Note that some servers may have to be configured to support this feature." public static string EditPage_HelpFriendlyUrl=>T("EditPage.HelpFriendlyUrl"); ///"Description" public static string EditPage_LabelAbstract=>T("EditPage.LabelAbstract"); ///"Use this field for a short description of the page" public static string EditPage_LabelAbstractHelp=>T("EditPage.LabelAbstractHelp"); ///"Content" public static string EditPage_LabelContent=>T("EditPage.LabelContent"); ///"Preview" public static string EditPage_LabelPreview=>T("EditPage.LabelPreview"); ///"Page type" public static string EditPage_PageTypeSelectorLabel=>T("EditPage.PageTypeSelectorLabel"); ///"The page type selection defines the role of the page, like 'a normal page' or 'a blog'. The options available depend on features installed." public static string EditPage_PageTypeSelectorHelp=>T("EditPage.PageTypeSelectorHelp"); ///"{0} characters maximum" public static string EditPage_MaxLength_Template=>T("EditPage.MaxLength"); ///"{0} characters maximum" public static string EditPage_MaxLength(object parameter0)=>string.Format(T("EditPage.MaxLength"), parameter0); ///"Delete page?" public static string DeletePage_LabelFieldGroup=>T("DeletePage.LabelFieldGroup"); ///"Delete page and all subpages" public static string DeletePageStep1_Title=>T("DeletePageStep1.Title"); ///"All subpages will also be deleted. Continue?" public static string DeletePageStep1_Description=>T("DeletePageStep1.Description"); ///"Delete page '{0}'?" public static string DeletePageStep2_Text_Template=>T("DeletePageStep2.Text"); ///"Delete page '{0}'?" public static string DeletePageStep2_Text(object parameter0)=>string.Format(T("DeletePageStep2.Text"), parameter0); ///"Another page is using the specified URL title. URL titles must be unique among pages with the same parent." public static string UrlTitleNotUniqueError=>T("UrlTitleNotUniqueError"); ///"The specified URL title contains invalid characters. Since this field is used to build the web address for the page, certain special characters (like question mark, slash and dot) are not allowed. You can use letters, digits and dash." public static string UrlTitleNotValidError=>T("UrlTitleNotValidError"); ///"The specified URL title is too long. Make it shorter and try again" public static string UrlTitleTooLong=>T("UrlTitleTooLong"); ///"Another page is using the specified Friendly URL. Friendly URL's must be unique." public static string FriendlyUrlNotUniqueError=>T("FriendlyUrlNotUniqueError"); ///"The title can not be empty." public static string TitleMissingError=>T("TitleMissingError"); ///"Page not saved" public static string PageSaveValidationFailedTitle=>T("PageSaveValidationFailedTitle"); ///"The page did not validate and has not been saved. Please examine field messages." public static string PageSaveValidationFailedMessage=>T("PageSaveValidationFailedMessage"); ///"Websites" public static string PageElementProvider_RootLabel=>T("PageElementProvider.RootLabel"); ///"Websites" public static string PageElementProvider_RootLabelToolTip=>T("PageElementProvider.RootLabelToolTip"); ///"Add Website" public static string PageElementProvider_AddPageAtRoot=>T("PageElementProvider.AddPageAtRoot"); ///"Add {0}" public static string PageElementProvider_AddPageAtRootFormat_Template=>T("PageElementProvider.AddPageAtRootFormat"); ///"Add {0}" public static string PageElementProvider_AddPageAtRootFormat(object parameter0)=>string.Format(T("PageElementProvider.AddPageAtRootFormat"), parameter0); ///"Add new homepage" public static string PageElementProvider_AddPageAtRootToolTip=>T("PageElementProvider.AddPageAtRootToolTip"); ///"List Unpublished Content" public static string PageElementProvider_ViewUnpublishedItems=>T("PageElementProvider.ViewUnpublishedItems"); ///"Get an overview of pages and other content that haven't been published yet." public static string PageElementProvider_ViewUnpublishedItemsToolTip=>T("PageElementProvider.ViewUnpublishedItemsToolTip"); ///"Unpublished Content" public static string PageElementProvider_ViewUnpublishedItems_document_title=>T("PageElementProvider.ViewUnpublishedItems-document-title"); ///"The list below displays pages and other content which are currently in draft or are ready to be approved / published." public static string PageElementProvider_ViewUnpublishedItems_document_description=>T("PageElementProvider.ViewUnpublishedItems-document-description"); ///"Edit Page" public static string PageElementProvider_EditPage=>T("PageElementProvider.EditPage"); ///"Edit selected page" public static string PageElementProvider_EditPageToolTip=>T("PageElementProvider.EditPageToolTip"); ///"Delete" public static string PageElementProvider_Delete=>T("PageElementProvider.Delete"); ///"Delete the selected page" public static string PageElementProvider_DeleteToolTip=>T("PageElementProvider.DeleteToolTip"); ///"Duplicate Page" public static string PageElementProvider_Duplicate=>T("PageElementProvider.Duplicate"); ///"Duplicate the selected page" public static string PageElementProvider_DuplicateToolTip=>T("PageElementProvider.DuplicateToolTip"); ///"Translate Page" public static string PageElementProvider_LocalizePage=>T("PageElementProvider.LocalizePage"); ///"Translate selected page" public static string PageElementProvider_LocalizePageToolTip=>T("PageElementProvider.LocalizePageToolTip"); ///"Undo Translation" public static string PageElementProvider_UnLocalizePage => T("PageElementProvider.UnLocalizePage"); ///"Delete Translation for Selected Page" public static string PageElementProvider_UnLocalizePageToolTip => T("PageElementProvider.UnLocalizePageToolTip"); ///"Add page" public static string PageElementProvider_AddSubPage=>T("PageElementProvider.AddSubPage"); ///"Add {0}" public static string PageElementProvider_AddSubPageFormat_Template=>T("PageElementProvider.AddSubPageFormat"); ///"Add {0}" public static string PageElementProvider_AddSubPageFormat(object parameter0)=>string.Format(T("PageElementProvider.AddSubPageFormat"), parameter0); ///"Add new page below the selected" public static string PageElementProvider_AddSubPageToolTip=>T("PageElementProvider.AddSubPageToolTip"); ///"Show page local orderings" public static string PageElementProvider_DisplayLocalOrderingLabel=>T("PageElementProvider.DisplayLocalOrderingLabel"); ///"Show page local orderings" public static string PageElementProvider_DisplayLocalOrderingToolTip=>T("PageElementProvider.DisplayLocalOrderingToolTip"); ///"Not yet approved or published" public static string PageElementProvider_DisabledPage=>T("PageElementProvider.DisabledPage"); ///"Website Template required" public static string PageElementProvider_MissingTemplateTitle=>T("PageElementProvider.MissingTemplateTitle"); ///"You should create a 'Page Template' first. Go to the 'Layout' perspective and create one." public static string PageElementProvider_MissingTemplateMessage=>T("PageElementProvider.MissingTemplateMessage"); ///"Language required" public static string PageElementProvider_MissingActiveLanguageTitle=>T("PageElementProvider.MissingActiveLanguageTitle"); ///"To add a page, you should firstly add at least one language. It can be done in the 'System' perspective." public static string PageElementProvider_MissingActiveLanguageMessage=>T("PageElementProvider.MissingActiveLanguageMessage"); ///"No page type available" public static string PageElementProvider_NoPageTypesAvailableTitle=>T("PageElementProvider.NoPageTypesAvailableTitle"); ///"You should create a 'Page Type' first. Go to the 'Layout' perspective and create one." public static string PageElementProvider_NoPageTypesAvailableMessage=>T("PageElementProvider.NoPageTypesAvailableMessage"); ///"Page type required" public static string PageElementProvider_MissingPageTypeTitle=>T("PageElementProvider.MissingPageTypeTitle"); ///"To create a homepage, a page type without the "only subpages" restriction is required, but none have been added yet. You can add one under the Layout perspective." public static string PageElementProvider_MissingPageTypeHomepageMessage=>T("PageElementProvider.MissingPageTypeHomepageMessage"); ///"To create a subpage, a page type without the the only homepages restriction is required, but none have been added yet. You can add one under the Layout perspective." public static string PageElementProvider_MissingPageTypeSubpageMessage=>T("PageElementProvider.MissingPageTypeSubpageMessage"); ///"Unable to add a page!" public static string PageElementProvider_RuleDontAllowPageAddTitle=>T("PageElementProvider.RuleDontAllowPageAddTitle"); ///"The rules that define availability for Page Types prohibit adding a page here." public static string PageElementProvider_RuleDontAllowPageAddMessage=>T("PageElementProvider.RuleDontAllowPageAddMessage"); ///"Manage host name" public static string ManageHostNames_Add_DialogLabel=>T("ManageHostNames.Add.DialogLabel"); ///"Add host name association to page" public static string ManageHostNames_Add_HeadingTitle=>T("ManageHostNames.Add.HeadingTitle"); ///"You can associate a host name (or a domain name) to a page by specifying it in the field below. Please note that the DNS settings for the specified host name must also be configured, which is done outside this system." public static string ManageHostNames_Add_HeadingDescription=>T("ManageHostNames.Add.HeadingDescription"); ///"Host name association to page" public static string ManageHostNames_Add_FieldGroupLabel=>T("ManageHostNames.Add.FieldGroupLabel"); ///"Host name" public static string ManageHostNames_Add_HostNameTextBoxLabel=>T("ManageHostNames.Add.HostNameTextBoxLabel"); ///"Specify the host name (like 'www.composite.net' or 'composite.net') you want to associate with this page" public static string ManageHostNames_Add_HostNametextBoxHelp=>T("ManageHostNames.Add.HostNametextBoxHelp"); ///"The syntax of the host name is not valid" public static string ManageHostNames_Add_InvalidHostNameSyntaxError=>T("ManageHostNames.Add.InvalidHostNameSyntaxError"); ///"This host name is already associated to a page. You must remove the existing association first." public static string ManageHostNames_Add_HostNameNotUniqueError=>T("ManageHostNames.Add.HostNameNotUniqueError"); ///"Manage host name" public static string ManageHostNames_Remove_DialogLabel=>T("ManageHostNames.Remove.DialogLabel"); ///"Remove host name association from page" public static string ManageHostNames_Remove_FieldGroupLabel=>T("ManageHostNames.Remove.FieldGroupLabel"); ///"Host names to remove" public static string ManageHostNames_Remove_MultiSelectorLabel=>T("ManageHostNames.Remove.MultiSelectorLabel"); ///"The host names you select will no longer be associated with the page" public static string ManageHostNames_Remove_MultiSelectorHelp=>T("ManageHostNames.Remove.MultiSelectorHelp"); ///"Please confirm deletion of all sub pages" public static string DeletePageWorkflow_MissingConfirmErrorMessage=>T("DeletePageWorkflow.MissingConfirmErrorMessage"); ///"Cascade delete error" public static string DeletePageWorkflow_CascadeDeleteErrorTitle=>T("DeletePageWorkflow.CascadeDeleteErrorTitle"); ///"The page is referenced by another type that does not allow cascade deletes. This operation is halted" public static string DeletePageWorkflow_CascadeDeleteErrorMessage=>T("DeletePageWorkflow.CascadeDeleteErrorMessage"); ///"Can not delete page" public static string DeletePageWorkflow_HasCompositionsTitle=>T("DeletePageWorkflow.HasCompositionsTitle"); ///"This page has one or more page folders or metadata fields defined on it. Delete these first." public static string DeletePageWorkflow_HasCompositionsMessage=>T("DeletePageWorkflow.HasCompositionsMessage"); ///"Delete page versions" public static string DeletePageWorkflow_ConfirmAllVersionsDeletion_DialogLabel=>T("DeletePageWorkflow.ConfirmAllVersionsDeletion.DialogLabel"); ///"This page contains multiple versions" public static string DeletePageWorkflow_ConfirmAllVersionsDeletion_Text=>T("DeletePageWorkflow.ConfirmAllVersionsDeletion.Text"); ///"Delete all versions" public static string DeletePageWorkflow_ConfirmAllVersionsDeletion_DeleteAllVersions=>T("DeletePageWorkflow.ConfirmAllVersionsDeletion.DeleteAllVersions"); ///"Delete only current version" public static string DeletePageWorkflow_ConfirmAllVersionsDeletion_DeleteCurrentVersion=>T("DeletePageWorkflow.ConfirmAllVersionsDeletion.DeleteCurrentVersion"); ///"Title" public static string ViewUnpublishedItems_PageTitleLabel=>T("ViewUnpublishedItems.PageTitleLabel"); ///"Version" public static string ViewUnpublishedItems_VersionLabel=>T("ViewUnpublishedItems.VersionLabel"); ///"Status" public static string ViewUnpublishedItems_StatusLabel=>T("ViewUnpublishedItems.StatusLabel"); ///"Author" public static string ViewUnpublishedItems_LabelChangedBy=>T("ViewUnpublishedItems.LabelChangedBy"); ///"Publish Date" public static string ViewUnpublishedItems_PublishDateLabel=>T("ViewUnpublishedItems.PublishDateLabel"); ///"Date and time the page has been scheduled to publish automatically. To edit, see the Publication Schedule in Edit Page mode." public static string ViewUnpublishedItems_PublishDateHelp=>T("ViewUnpublishedItems.PublishDateHelp"); ///"Unpublish Date" public static string ViewUnpublishedItems_UnpublishDateLabel=>T("ViewUnpublishedItems.UnpublishDateLabel"); ///"Date and time the page has been scheduled to unpublish automatically. To edit, see the Publication Schedule in Edit Page mode." public static string ViewUnpublishedItems_UnpublishDateHelp=>T("ViewUnpublishedItems.UnpublishDateHelp"); ///"Date Created" public static string ViewUnpublishedItems_DateCreatedLabel=>T("ViewUnpublishedItems.DateCreatedLabel"); ///"Date Modified" public static string ViewUnpublishedItems_DateModifiedLabel=>T("ViewUnpublishedItems.DateModifiedLabel"); ///"Publish Pages" public static string ViewUnpublishedItems_PublishConfirmTitle=>T("ViewUnpublishedItems.PublishConfirmTitle"); ///"You are about to publish these pages. Continue?" public static string ViewUnpublishedItems_PublishConfirmText=>T("ViewUnpublishedItems.PublishConfirmText"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_PageTemplateElementProvider { ///"Page Templates" public static string PageTemplateElementProvider_RootLabel=>T("PageTemplateElementProvider.RootLabel"); ///"You can find the sites XHTML templates here" public static string PageTemplateElementProvider_RootLabelToolTip=>T("PageTemplateElementProvider.RootLabelToolTip"); ///"Add Template" public static string PageTemplateElementProvider_AddTemplate=>T("PageTemplateElementProvider.AddTemplate"); ///"Add new template" public static string PageTemplateElementProvider_AddTemplateToolTip=>T("PageTemplateElementProvider.AddTemplateToolTip"); ///"Delete" public static string PageTemplateElementProvider_DeleteTemplate=>T("PageTemplateElementProvider.DeleteTemplate"); ///"Delete this item" public static string PageTemplateElementProvider_DeleteTemplateToolTip=>T("PageTemplateElementProvider.DeleteTemplateToolTip"); ///"Shared Code" public static string PageTemplateElementProvider_SharedCodeFolder_Title=>T("PageTemplateElementProvider.SharedCodeFolder.Title"); ///"Files used by layout files" public static string PageTemplateElementProvider_SharedCodeFolder_ToolTip=>T("PageTemplateElementProvider.SharedCodeFolder.ToolTip"); ///"Edit" public static string EditSharedCodeFile_Label=>T("EditSharedCodeFile.Label"); ///"Edit the file" public static string EditSharedCodeFile_ToolTip=>T("EditSharedCodeFile.ToolTip"); ///"Edit XML Template" public static string PageTemplateElementProvider_EditXmlTemplate=>T("PageTemplateElementProvider.EditXmlTemplate"); ///"Edit the selected XML template" public static string PageTemplateElementProvider_EditXmlTemplateToolTip=>T("PageTemplateElementProvider.EditXmlTemplateToolTip"); ///"Add New XML Page Template" public static string AddNewXmlPageTemplate_LabelDialog=>T("AddNewXmlPageTemplate.LabelDialog"); ///"Template Title" public static string AddNewXmlPageTemplate_LabelTemplateTitle=>T("AddNewXmlPageTemplate.LabelTemplateTitle"); ///"The title identifies this template in lists. Consider selecting a short but meaningful name." public static string AddNewXmlPageTemplate_LabelTemplateTitleHelp=>T("AddNewXmlPageTemplate.LabelTemplateTitleHelp"); ///"Copy from" public static string AddNewXmlPageTemplate_LabelCopyFrom=>T("AddNewXmlPageTemplate.LabelCopyFrom"); ///"You can copy the markup from another XML Page Template by selecting it in this list." public static string AddNewXmlPageTemplate_LabelCopyFromHelp=>T("AddNewXmlPageTemplate.LabelCopyFromHelp"); ///"(New template)" public static string AddNewXmlPageTemplate_LabelCopyFromEmptyOption=>T("AddNewXmlPageTemplate.LabelCopyFromEmptyOption"); ///"Title already used" public static string AddNewXmlPageTemplateWorkflow_TitleInUseTitle=>T("AddNewXmlPageTemplateWorkflow.TitleInUseTitle"); ///"The title is too long (used as part of the XML filename)." public static string AddNewXmlPageTemplateWorkflow_TitleTooLong=>T("AddNewXmlPageTemplateWorkflow.TitleTooLong"); ///"Markup Code" public static string EditXmlPageTemplate_LabelMarkUpCode=>T("EditXmlPageTemplate.LabelMarkUpCode"); ///"Template Info" public static string EditXmlPageTemplate_LabelTemplateIdentification=>T("EditXmlPageTemplate.LabelTemplateIdentification"); ///"Template Title" public static string EditXmlPageTemplate_LabelTemplateTitle=>T("EditXmlPageTemplate.LabelTemplateTitle"); ///"The title identifies this template in lists. Consider selecting a short but meaningful name." public static string EditXmlPageTemplate_LabelTemplateTitleHelp=>T("EditXmlPageTemplate.LabelTemplateTitleHelp"); ///"Unable to Save Template" public static string EditXmlPageTemplateWorkflow_InvalidXmlTitle=>T("EditXmlPageTemplateWorkflow.InvalidXmlTitle"); ///"The page template markup did not validate. {0}" public static string EditXmlPageTemplateWorkflow_InvalidXmlMessage_Template=>T("EditXmlPageTemplateWorkflow.InvalidXmlMessage"); ///"The page template markup did not validate. {0}" public static string EditXmlPageTemplateWorkflow_InvalidXmlMessage(object parameter0)=>string.Format(T("EditXmlPageTemplateWorkflow.InvalidXmlMessage"), parameter0); ///"Cannot rename a template - the file with the name '{0}' already exists." public static string EditXmlPageTemplateWorkflow_CannotRenameFileExists_Template=>T("EditXmlPageTemplateWorkflow.CannotRenameFileExists"); ///"Cannot rename a template - the file with the name '{0}' already exists." public static string EditXmlPageTemplateWorkflow_CannotRenameFileExists(object parameter0)=>string.Format(T("EditXmlPageTemplateWorkflow.CannotRenameFileExists"), parameter0); ///"Title already used" public static string EditXmlPageTemplateWorkflow_TitleInUseTitle=>T("EditXmlPageTemplateWorkflow.TitleInUseTitle"); ///"Delete This Page Template?" public static string DeletePageTemplateStep1_LabelFieldGroup=>T("DeletePageTemplateStep1.LabelFieldGroup"); ///"Delete page template?" public static string DeletePageTemplateStep1_Text=>T("DeletePageTemplateStep1.Text"); ///"Cascade Delete Error" public static string DeletePageTemplateWorkflow_CascadeDeleteErrorTitle=>T("DeletePageTemplateWorkflow.CascadeDeleteErrorTitle"); ///"The type is referenced by another type that does not allow cascade deletes. This operation is halted." public static string DeletePageTemplateWorkflow_CascadeDeleteErrorMessage=>T("DeletePageTemplateWorkflow.CascadeDeleteErrorMessage"); ///"There are {0} page[s] referencing this template: {1}" public static string DeletePageTemplateWorkflow_PageReference_Template=>T("DeletePageTemplateWorkflow.PageReference"); ///"There are {0} page[s] referencing this template: {1}" public static string DeletePageTemplateWorkflow_PageReference(object parameter0,object parameter1)=>string.Format(T("DeletePageTemplateWorkflow.PageReference"), parameter0,parameter1); ///"There are {0} page type[s] referencing this template: {1}" public static string DeletePageTemplateWorkflow_PageTypeReference_Template=>T("DeletePageTemplateWorkflow.PageTypeReference"); ///"There are {0} page type[s] referencing this template: {1}" public static string DeletePageTemplateWorkflow_PageTypeReference(object parameter0,object parameter1)=>string.Format(T("DeletePageTemplateWorkflow.PageTypeReference"), parameter0,parameter1); ///"Add New Page Template" public static string AddNewPageTemplate_LabelDialog=>T("AddNewPageTemplate.LabelDialog"); ///"Choose one of the possible types of page templates" public static string AddNewPageTemplate_TemplateTypeHelp=>T("AddNewPageTemplate.TemplateTypeHelp"); ///"Template type" public static string AddNewPageTemplate_TemplateTypeLabel=>T("AddNewPageTemplate.TemplateTypeLabel"); ///"Razor" public static string AddNewPageTemplate_TemplateType_Razor=>T("AddNewPageTemplate.TemplateType.Razor"); ///"Master Page" public static string AddNewPageTemplate_TemplateType_MasterPage=>T("AddNewPageTemplate.TemplateType.MasterPage"); ///"XML" public static string AddNewPageTemplate_TemplateType_XML=>T("AddNewPageTemplate.TemplateType.XML"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateElementProvider", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_PageTemplateFeatureElementProvider { ///"Page Template Features" public static string ElementProvider_RootLabel=>T("ElementProvider.RootLabel"); ///"Here you can find features - snippets of HTML and functionality - included in the website templates." public static string ElementProvider_RootToolTip=>T("ElementProvider.RootToolTip"); ///"Add Template Feature" public static string ElementProvider_AddTemplateFeature=>T("ElementProvider.AddTemplateFeature"); ///"Add a new page template feature" public static string ElementProvider_AddTemplateFeatureToolTip=>T("ElementProvider.AddTemplateFeatureToolTip"); ///"Delete Template Feature" public static string ElementProvider_DeleteTemplateFeature=>T("ElementProvider.DeleteTemplateFeature"); ///"Delete this template feature" public static string ElementProvider_DeleteTemplateFeatureToolTip=>T("ElementProvider.DeleteTemplateFeatureToolTip"); ///"Edit Template Feature" public static string ElementProvider_EditTemplateFeature=>T("ElementProvider.EditTemplateFeature"); ///"Edit the selected template feature" public static string ElementProvider_EditTemplateFeatureToolTip=>T("ElementProvider.EditTemplateFeatureToolTip"); ///"Use Visual Editor" public static string ElementProvider_EditVisually=>T("ElementProvider.EditVisually"); ///"When enabled the visual editor will be used to manage this feature" public static string ElementProvider_EditVisuallyToolTip=>T("ElementProvider.EditVisuallyToolTip"); ///"Add New Page Template Feature" public static string AddWorkflow_LabelDialog=>T("AddWorkflow.LabelDialog"); ///"Feature name" public static string AddWorkflow_LabelTemplateFeatureName=>T("AddWorkflow.LabelTemplateFeatureName"); ///"The name is used to identify this feature when included in templates" public static string AddWorkflow_LabelTemplateFeatureNameHelp=>T("AddWorkflow.LabelTemplateFeatureNameHelp"); ///"Editor type" public static string AddWorkflow_LabelTemplateFeatureEditorType=>T("AddWorkflow.LabelTemplateFeatureEditorType"); ///"Choose which type of editor to use when maintaining this feature. You can always switch the editor type in the tree later." public static string AddWorkflow_LabelTemplateFeatureEditorTypeHelp=>T("AddWorkflow.LabelTemplateFeatureEditorTypeHelp"); ///"Visual Editor" public static string AddWorkflow_LabelTemplateFeatureEditorType_html=>T("AddWorkflow.LabelTemplateFeatureEditorType.html"); ///"Markup Editor" public static string AddWorkflow_LabelTemplateFeatureEditorType_xml=>T("AddWorkflow.LabelTemplateFeatureEditorType.xml"); ///"The name is already used by another feature" public static string AddWorkflow_NameInUse=>T("AddWorkflow.NameInUse"); ///"The title is too long (max 50 characters)" public static string AddWorkflow_NameTooLong=>T("AddWorkflow.NameTooLong"); ///"The name must be usable in a file name - you have invalid characters you need to remove" public static string AddWorkflow_NameNotValidInFilename=>T("AddWorkflow.NameNotValidInFilename"); ///"Delete This Page Template Feature?" public static string DeleteWorkflow_Title=>T("DeleteWorkflow.Title"); ///"If this feature is in use by page templates, this action could lead to errors." public static string DeleteWorkflow_Text=>T("DeleteWorkflow.Text"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_PageTypeElementProvider { ///"Page Types" public static string PageType_Tree_Root_Label=>T("PageType.Tree.Root.Label"); ///"Placeholder Content" public static string PageType_Tree_DefaultContentElement_Label=>T("PageType.Tree.DefaultContentElement.Label"); ///"Metadata Fields" public static string PageType_Tree_MetaDataFieldsElement_Label=>T("PageType.Tree.MetaDataFieldsElement.Label"); ///"Add Page Type" public static string PageType_Tree_AddNewPageType_Label=>T("PageType.Tree.AddNewPageType.Label"); ///"Add new page type" public static string PageType_Tree_AddNewPageType_ToolTip=>T("PageType.Tree.AddNewPageType.ToolTip"); ///"Edit Page Type" public static string PageType_Tree_EditPageType_Label=>T("PageType.Tree.EditPageType.Label"); ///"Edit selected page type" public static string PageType_Tree_EditPageType_ToolTip=>T("PageType.Tree.EditPageType.ToolTip"); ///"Delete Page Type" public static string PageType_Tree_DeletePageType_Label=>T("PageType.Tree.DeletePageType.Label"); ///"Delete selected page type" public static string PageType_Tree_DeletePageType_ToolTip=>T("PageType.Tree.DeletePageType.ToolTip"); ///"Add Default Content" public static string PageType_Tree_AddDefaultPageContent_Label=>T("PageType.Tree.AddDefaultPageContent.Label"); ///"Add placeholder default content" public static string PageType_Tree_AddDefaultPageContent_ToolTip=>T("PageType.Tree.AddDefaultPageContent.ToolTip"); ///"Edit Default Content" public static string PageType_Tree_EditDefaultPageContent_Label=>T("PageType.Tree.EditDefaultPageContent.Label"); ///"Edit placeholder default content" public static string PageType_Tree_EditDefaultPageContent_ToolTip=>T("PageType.Tree.EditDefaultPageContent.ToolTip"); ///"Delete Default Content" public static string PageType_Tree_DeleteDefaultPageContent_Label=>T("PageType.Tree.DeleteDefaultPageContent.Label"); ///"Delete default content" public static string PageType_Tree_DeleteDefaultPageContent_ToolTip=>T("PageType.Tree.DeleteDefaultPageContent.ToolTip"); ///"Add Metadata Field" public static string PageType_Tree_AddMetaDataField_Label=>T("PageType.Tree.AddMetaDataField.Label"); ///"Add new Metadata field" public static string PageType_Tree_AddMetaDataField_ToolTip=>T("PageType.Tree.AddMetaDataField.ToolTip"); ///"Edit Metadata Field" public static string PageType_Tree_EditMetaDataField_Label=>T("PageType.Tree.EditMetaDataField.Label"); ///"Edit selected Metadata field" public static string PageType_Tree_EditMetaDataField_ToolTip=>T("PageType.Tree.EditMetaDataField.ToolTip"); ///"Delete Metadata Field" public static string PageType_Tree_DeleteMetaDataField_Label=>T("PageType.Tree.DeleteMetaDataField.Label"); ///"Delete selected Metadata field" public static string PageType_Tree_DeleteMetaDataField_ToolTip=>T("PageType.Tree.DeleteMetaDataField.ToolTip"); ///"Add New Page Type" public static string PageType_AddNewPageTypeWorkflow_Layout_Label=>T("PageType.AddNewPageTypeWorkflow.Layout.Label"); ///"New page type settings" public static string PageType_AddNewPageTypeWorkflow_FieldGroup_Label=>T("PageType.AddNewPageTypeWorkflow.FieldGroup.Label"); ///"Name" public static string PageType_AddNewPageTypeWorkflow_NameTextBox_Label=>T("PageType.AddNewPageTypeWorkflow.NameTextBox.Label"); ///"The name of the new page type" public static string PageType_AddNewPageTypeWorkflow_NameTextBox_Help=>T("PageType.AddNewPageTypeWorkflow.NameTextBox.Help"); ///"Description" public static string PageType_AddNewPageTypeWorkflow_DescriptionTextArea_Label=>T("PageType.AddNewPageTypeWorkflow.DescriptionTextArea.Label"); ///"The description of the new page type" public static string PageType_AddNewPageTypeWorkflow_DescriptionTextArea_Help=>T("PageType.AddNewPageTypeWorkflow.DescriptionTextArea.Help"); ///"Settings" public static string PageType_EditPageTypeWorkflow_SettingsPlaceHolder_Label=>T("PageType.EditPageTypeWorkflow.SettingsPlaceHolder.Label"); ///"Page type settings" public static string PageType_EditPageTypeWorkflow_SettingsFieldGroup_Label=>T("PageType.EditPageTypeWorkflow.SettingsFieldGroup.Label"); ///"Name" public static string PageType_EditPageTypeWorkflow_NameTextBox_Label=>T("PageType.EditPageTypeWorkflow.NameTextBox.Label"); ///"The name of the page type" public static string PageType_EditPageTypeWorkflow_NameTextBox_Help=>T("PageType.EditPageTypeWorkflow.NameTextBox.Help"); ///"Description" public static string PageType_EditPageTypeWorkflow_DescriptionTextArea_Label=>T("PageType.EditPageTypeWorkflow.DescriptionTextArea.Label"); ///"The description of the page type" public static string PageType_EditPageTypeWorkflow_DescriptionTextArea_Help=>T("PageType.EditPageTypeWorkflow.DescriptionTextArea.Help"); ///"Available" public static string PageType_EditPageTypeWorkflow_AvailableCheckBox_Label=>T("PageType.EditPageTypeWorkflow.AvailableCheckBox.Label"); ///"Unchecking this will make this page non-selectable on any page" public static string PageType_EditPageTypeWorkflow_AvailableCheckBox_Help=>T("PageType.EditPageTypeWorkflow.AvailableCheckBox.Help"); ///"Preset menu title" public static string PageType_EditPageTypeWorkflow_PresetMenuTitleCheckBox_Label=>T("PageType.EditPageTypeWorkflow.PresetMenuTitleCheckBox.Label"); ///"If this is checked a default value for the menu title on pages is preset" public static string PageType_EditPageTypeWorkflow_PresetMenuTitleCheckBox_Help=>T("PageType.EditPageTypeWorkflow.PresetMenuTitleCheckBox.Help"); ///"Default child page type" public static string PageType_EditPageTypeWorkflow_DefaultChildPageTypeKeySelector_Label=>T("PageType.EditPageTypeWorkflow.DefaultChildPageTypeKeySelector.Label"); ///"Select a page type to be the default page type for child pages created with this page type" public static string PageType_EditPageTypeWorkflow_DefaultChildPageTypeKeySelector_Help=>T("PageType.EditPageTypeWorkflow.DefaultChildPageTypeKeySelector.Help"); ///"[None]" public static string PageType_EditPageTypeWorkflow_DefaultChildPageTypeKeySelector_NoneSelectedLabel=>T("PageType.EditPageTypeWorkflow.DefaultChildPageTypeKeySelector.NoneSelectedLabel"); ///"Layout" public static string PageType_EditPageTypeWorkflow_PageTemplatePlaceHolder_Label=>T("PageType.EditPageTypeWorkflow.PageTemplatePlaceHolder.Label"); ///"Layout" public static string PageType_EditPageTypeWorkflow_PageTemplateRestrictionFieldGroup_Label=>T("PageType.EditPageTypeWorkflow.PageTemplateRestrictionFieldGroup.Label"); ///"Layout restrictions" public static string PageType_EditPageTypeWorkflow_PageTemplateRestrictionMultiKeySelector_Label=>T("PageType.EditPageTypeWorkflow.PageTemplateRestrictionMultiKeySelector.Label"); ///"Select layouts to be only available when editing pages of this page type. If none is selected (default), all will be available." public static string PageType_EditPageTypeWorkflow_PageTemplateRestrictionMultiKeySelector_Help=>T("PageType.EditPageTypeWorkflow.PageTemplateRestrictionMultiKeySelector.Help"); ///"Default layout" public static string PageType_EditPageTypeWorkflow_DefaultPageTemplateKeySelector_Label=>T("PageType.EditPageTypeWorkflow.DefaultPageTemplateKeySelector.Label"); ///"Select a layout to be the default layout for pages created with this page type" public static string PageType_EditPageTypeWorkflow_DefaultPageTemplateKeySelector_Help=>T("PageType.EditPageTypeWorkflow.DefaultPageTemplateKeySelector.Help"); ///"[None]" public static string PageType_EditPageTypeWorkflow_DefaultPageTemplateKeySelector_NoneSelectedLabel=>T("PageType.EditPageTypeWorkflow.DefaultPageTemplateKeySelector.NoneSelectedLabel"); ///"Availability" public static string PageType_EditPageTypeWorkflow_AvailabilityPlaceHolder_Label=>T("PageType.EditPageTypeWorkflow.AvailabilityPlaceHolder.Label"); ///"Availability" public static string PageType_EditPageTypeWorkflow_AvailabilityFieldGroup_Label=>T("PageType.EditPageTypeWorkflow.AvailabilityFieldGroup.Label"); ///"Homepage relation" public static string PageType_EditPageTypeWorkflow_HomepageRelationKeySelector_Label=>T("PageType.EditPageTypeWorkflow.HomepageRelationKeySelector.Label"); ///"Homepage relation" public static string PageType_EditPageTypeWorkflow_HomepageRelationKeySelector_Help=>T("PageType.EditPageTypeWorkflow.HomepageRelationKeySelector.Help"); ///"No restrictions" public static string PageType_EditPageTypeWorkflow_HomepageRelationKeySelector_NoRestrictionLabel=>T("PageType.EditPageTypeWorkflow.HomepageRelationKeySelector.NoRestrictionLabel"); ///"Only sub pages" public static string PageType_EditPageTypeWorkflow_HomepageRelationKeySelector_OnlySubPagesLabel=>T("PageType.EditPageTypeWorkflow.HomepageRelationKeySelector.OnlySubPagesLabel"); ///"Only home pages" public static string PageType_EditPageTypeWorkflow_HomepageRelationKeySelector_OnlyHomePagesLabel=>T("PageType.EditPageTypeWorkflow.HomepageRelationKeySelector.OnlyHomePagesLabel"); ///"Page type parent restriction" public static string PageType_EditPageTypeWorkflow_PageTypeChildRestrictionMultiKeySelector_Label=>T("PageType.EditPageTypeWorkflow.PageTypeChildRestrictionMultiKeySelector.Label"); ///"Only allow this page type as for child pages with the selected page types" public static string PageType_EditPageTypeWorkflow_PageTypeChildRestrictionMultiKeySelector_Help=>T("PageType.EditPageTypeWorkflow.PageTypeChildRestrictionMultiKeySelector.Help"); ///"DataFolders / Applications" public static string PageType_EditPageTypeWorkflow_DataFolderApplicationPlaceHolder_Label=>T("PageType.EditPageTypeWorkflow.DataFolderApplicationPlaceHolder.Label"); ///"Data folders" public static string PageType_EditPageTypeWorkflow_DataFolderFieldGroup_Label=>T("PageType.EditPageTypeWorkflow.DataFolderFieldGroup.Label"); ///"Data folders" public static string PageType_EditPageTypeWorkflow_DataFolderMultiKeySelector_Label=>T("PageType.EditPageTypeWorkflow.DataFolderMultiKeySelector.Label"); ///"Select the data folders that should automatically be added to pages using this page type" public static string PageType_EditPageTypeWorkflow_DataFolderMultiKeySelector_Help=>T("PageType.EditPageTypeWorkflow.DataFolderMultiKeySelector.Help"); ///"Applications" public static string PageType_EditPageTypeWorkflow_ApplicationFieldGroup_Label=>T("PageType.EditPageTypeWorkflow.ApplicationFieldGroup.Label"); ///"Applications" public static string PageType_EditPageTypeWorkflow_ApplicationMultiKeySelector_Label=>T("PageType.EditPageTypeWorkflow.ApplicationMultiKeySelector.Label"); ///"Select the applications that should automatically be added to pages using this page type" public static string PageType_EditPageTypeWorkflow_ApplicationMultiKeySelector_Help=>T("PageType.EditPageTypeWorkflow.ApplicationMultiKeySelector.Help"); ///"The default layout is not one of the selected restricted layouts" public static string PageType_EditPageTypeWorkflow_ValidationError_DefaultTemplateNotInRestrictions=>T("PageType.EditPageTypeWorkflow.ValidationError.DefaultTemplateNotInRestrictions"); ///"Page type parent restrictions are not allowed with home pages only" public static string PageType_EditPageTypeWorkflow_ValidationError_HomepageRelationConflictsWithParentRestrictions=>T("PageType.EditPageTypeWorkflow.ValidationError.HomepageRelationConflictsWithParentRestrictions"); ///"Delete This Page Type?" public static string PageType_DeletePageTypeWorkflow_Confirm_Layout_Label=>T("PageType.DeletePageTypeWorkflow.Confirm.Layout.Label"); ///"Delete the page type {0}?" public static string PageType_DeletePageTypeWorkflow_Confirm_Layout_Messeage_Template=>T("PageType.DeletePageTypeWorkflow.Confirm.Layout.Messeage"); ///"Delete the page type {0}?" public static string PageType_DeletePageTypeWorkflow_Confirm_Layout_Messeage(object parameter0)=>string.Format(T("PageType.DeletePageTypeWorkflow.Confirm.Layout.Messeage"), parameter0); ///"Page Type in Use" public static string PageType_DeletePageTypeWorkflow_PagesRefering_Layout_Label=>T("PageType.DeletePageTypeWorkflow.PagesRefering.Layout.Label"); ///"The page type {0} is in use and it is not possible to delete it" public static string PageType_DeletePageTypeWorkflow_PagesRefering_Layout_Message_Template=>T("PageType.DeletePageTypeWorkflow.PagesRefering.Layout.Message"); ///"The page type {0} is in use and it is not possible to delete it" public static string PageType_DeletePageTypeWorkflow_PagesRefering_Layout_Message(object parameter0)=>string.Format(T("PageType.DeletePageTypeWorkflow.PagesRefering.Layout.Message"), parameter0); ///"Add Default Content" public static string PageType_AddPageTypeDefaultPageContentWorkflow_Layout_Label=>T("PageType.AddPageTypeDefaultPageContentWorkflow.Layout.Label"); ///"Placeholder ID" public static string PageType_AddPageTypeDefaultPageContentWorkflow_PlaceHolderIdTextBox_Label=>T("PageType.AddPageTypeDefaultPageContentWorkflow.PlaceHolderIdTextBox.Label"); ///"The ID of the placeholder. You can write a non-existing ID and create the placeholder afterwards (by editing Page Template markup)." public static string PageType_AddPageTypeDefaultPageContentWorkflow_PlaceHolderIdTextBox_Help=>T("PageType.AddPageTypeDefaultPageContentWorkflow.PlaceHolderIdTextBox.Help"); ///"No templates with {0}" public static string PageType_AddPageTypeDefaultPageContentWorkflow_NonExistingPlaceholderId_Title_Template=>T("PageType.AddPageTypeDefaultPageContentWorkflow.NonExistingPlaceholderId.Title"); ///"No templates with {0}" public static string PageType_AddPageTypeDefaultPageContentWorkflow_NonExistingPlaceholderId_Title(object parameter0)=>string.Format(T("PageType.AddPageTypeDefaultPageContentWorkflow.NonExistingPlaceholderId.Title"), parameter0); ///"Please note that the Placeholder ID you specified '{0}', is currently not in any Layout Template." public static string PageType_AddPageTypeDefaultPageContentWorkflow_NonExistingPlaceholderId_Message_Template=>T("PageType.AddPageTypeDefaultPageContentWorkflow.NonExistingPlaceholderId.Message"); ///"Please note that the Placeholder ID you specified '{0}', is currently not in any Layout Template." public static string PageType_AddPageTypeDefaultPageContentWorkflow_NonExistingPlaceholderId_Message(object parameter0)=>string.Format(T("PageType.AddPageTypeDefaultPageContentWorkflow.NonExistingPlaceholderId.Message"), parameter0); ///"Edit default content" public static string PageType_EditPageTypeDefaultPageContentWorkflow_Layout_Label=>T("PageType.EditPageTypeDefaultPageContentWorkflow.Layout.Label"); ///"Settings" public static string PageType_EditPageTypeDefaultPageContentWorkflow_SettingsPlaceHolder_Label=>T("PageType.EditPageTypeDefaultPageContentWorkflow.SettingsPlaceHolder.Label"); ///"Placeholder Settings" public static string PageType_EditPageTypeDefaultPageContentWorkflow_SettingsFieldGroup_Label=>T("PageType.EditPageTypeDefaultPageContentWorkflow.SettingsFieldGroup.Label"); ///"Placeholder ID" public static string PageType_EditPageTypeDefaultPageContentWorkflow_PlaceHolderIdTextBox_Label=>T("PageType.EditPageTypeDefaultPageContentWorkflow.PlaceHolderIdTextBox.Label"); ///"The ID of the placeholder. You can write a non-existing ID and create the placeholder afterwards (edit Page Template markup)." public static string PageType_EditPageTypeDefaultPageContentWorkflow_PlaceHolderIdTextBox_Help=>T("PageType.EditPageTypeDefaultPageContentWorkflow.PlaceHolderIdTextBox.Help"); ///"Container Classes" public static string PageType_EditPageTypeDefaultPageContentWorkflow_PlaceHolderContainerClassesTextBox_Label=>T("PageType.EditPageTypeDefaultPageContentWorkflow.PlaceHolderContainerClassesTextBox.Label"); ///"Extra 'Container Classes' to add to this placeholder when user is editing this type of page. Container classes let you style the editor and control which components can be added." public static string PageType_EditPageTypeDefaultPageContentWorkflow_PlaceHolderContainerClassesTextBox_Help=>T("PageType.EditPageTypeDefaultPageContentWorkflow.PlaceHolderContainerClassesTextBox.Help"); ///"Content" public static string PageType_EditPageTypeDefaultPageContentWorkflow_ContentXhtmlEditor_Label=>T("PageType.EditPageTypeDefaultPageContentWorkflow.ContentXhtmlEditor.Label"); ///"Add Metadata Field" public static string PageType_AddPageTypeMetaDataFieldWorkflow_Layout_Label=>T("PageType.AddPageTypeMetaDataFieldWorkflow.Layout.Label"); ///"" public static string PageType_AddPageTypeMetaDataFieldWorkflow_FieldGroup_Label=>T("PageType.AddPageTypeMetaDataFieldWorkflow.FieldGroup.Label"); ///"Programmatic name" public static string PageType_AddPageTypeMetaDataFieldWorkflow_NameTextBox_Label=>T("PageType.AddPageTypeMetaDataFieldWorkflow.NameTextBox.Label"); ///"The unique name of the Metadata field. This can not be changed later!" public static string PageType_AddPageTypeMetaDataFieldWorkflow_NameTextBox_Help=>T("PageType.AddPageTypeMetaDataFieldWorkflow.NameTextBox.Help"); ///"Show with label" public static string PageType_AddPageTypeMetaDataFieldWorkflow_LabelTextBox_Label=>T("PageType.AddPageTypeMetaDataFieldWorkflow.LabelTextBox.Label"); ///"The label of the Metadata field. Used for UI." public static string PageType_AddPageTypeMetaDataFieldWorkflow_LabelTextBox_Help=>T("PageType.AddPageTypeMetaDataFieldWorkflow.LabelTextBox.Help"); ///"Metadata type" public static string PageType_AddPageTypeMetaDataFieldWorkflow_MetaDataTypeKeySelector_Label=>T("PageType.AddPageTypeMetaDataFieldWorkflow.MetaDataTypeKeySelector.Label"); ///"The Metadata type" public static string PageType_AddPageTypeMetaDataFieldWorkflow_MetaDataTypeKeySelector_Help=>T("PageType.AddPageTypeMetaDataFieldWorkflow.MetaDataTypeKeySelector.Help"); ///"Display on tab" public static string PageType_AddPageTypeMetaDataFieldWorkflow_MetaDataContainerKeySelector_Label=>T("PageType.AddPageTypeMetaDataFieldWorkflow.MetaDataContainerKeySelector.Label"); ///"Select the tab to display the Metadata when editing a page." public static string PageType_AddPageTypeMetaDataFieldWorkflow_MetaDataContainerKeySelector_Help=>T("PageType.AddPageTypeMetaDataFieldWorkflow.MetaDataContainerKeySelector.Help"); ///"Add Metadata default values" public static string PageType_AddPageTypeMetaDataFieldWorkflow_AddingDefaultMetaData_Title=>T("PageType.AddPageTypeMetaDataFieldWorkflow.AddingDefaultMetaData.Title"); ///"The field name with another type is already used." public static string PageType_AddPageTypeMetaDataFieldWorkflow_ValidationError_MetaDataFieldNameAlreadyUsed=>T("PageType.AddPageTypeMetaDataFieldWorkflow.ValidationError.MetaDataFieldNameAlreadyUsed"); ///"Delete This Metadata Field?" public static string PageType_DeletePageTypeMetaDataFieldWorkflow_Confirm_Layout_Label=>T("PageType.DeletePageTypeMetaDataFieldWorkflow.Confirm.Layout.Label"); ///"Delete the Metadata field {0}? Warning: all its existing Metadata items will also be deleted" public static string PageType_DeletePageTypeMetaDataFieldWorkflow_Confirm_Layout_Message_Template=>T("PageType.DeletePageTypeMetaDataFieldWorkflow.Confirm.Layout.Message"); ///"Delete the Metadata field {0}? Warning: all its existing Metadata items will also be deleted" public static string PageType_DeletePageTypeMetaDataFieldWorkflow_Confirm_Layout_Message(object parameter0)=>string.Format(T("PageType.DeletePageTypeMetaDataFieldWorkflow.Confirm.Layout.Message"), parameter0); ///"Edit Metadata Field" public static string PageType_EditPageTypeMetaDataFieldWorkflow_Layout_Label=>T("PageType.EditPageTypeMetaDataFieldWorkflow.Layout.Label"); ///"Metadata field settings" public static string PageType_EditPageTypeMetaDataFieldWorkflow_FieldGroup_Label=>T("PageType.EditPageTypeMetaDataFieldWorkflow.FieldGroup.Label"); ///"Label" public static string PageType_EditPageTypeMetaDataFieldWorkflow_LabelTextBox_Label=>T("PageType.EditPageTypeMetaDataFieldWorkflow.LabelTextBox.Label"); ///"The label of the Metadata field. Used for UI" public static string PageType_EditPageTypeMetaDataFieldWorkflow_LabelTextBox_Help=>T("PageType.EditPageTypeMetaDataFieldWorkflow.LabelTextBox.Help"); ///"Tab" public static string PageType_EditPageTypeMetaDataFieldWorkflow_MetaDataContainerKeySelector_Label=>T("PageType.EditPageTypeMetaDataFieldWorkflow.MetaDataContainerKeySelector.Label"); ///"Select the tab to put the Metadata when editing a page" public static string PageType_EditPageTypeMetaDataFieldWorkflow_MetaDataContainerKeySelector_Help=>T("PageType.EditPageTypeMetaDataFieldWorkflow.MetaDataContainerKeySelector.Help"); ///"Metatype" public static string PageType_EditPageTypeMetaDataFieldWorkflow_MetaTypeName_Label=>T("PageType.EditPageTypeMetaDataFieldWorkflow.MetaTypeName.Label"); ///"The name of the metatype." public static string PageType_EditPageTypeMetaDataFieldWorkflow_MetaTypeName_Help=>T("PageType.EditPageTypeMetaDataFieldWorkflow.MetaTypeName.Help"); ///"The Metadata type is used another place with same name but different label" public static string PageType_EditPageTypeMetaDataFieldWorkflow_ValidationError_MetaDataFieldNameAlreadyUsed=>T("PageType.EditPageTypeMetaDataFieldWorkflow.ValidationError.MetaDataFieldNameAlreadyUsed"); ///"There exists one or more definitions with the same name, container change is not allowed" public static string PageType_EditPageTypeMetaDataFieldWorkflow_ValidationError_MetaDataContainerChangeNotAllowed=>T("PageType.EditPageTypeMetaDataFieldWorkflow.ValidationError.MetaDataContainerChangeNotAllowed"); ///"Metadata type has been deleted" public static string PageType_EditPageTypeMetaDataFieldWorkflow_ValidationError_MetaDataTypeNotExisting_Title=>T("PageType.EditPageTypeMetaDataFieldWorkflow.ValidationError.MetaDataTypeNotExisting.Title"); ///"The Metadata type has been deleted from the system and can no longer be added to any page types" public static string PageType_EditPageTypeMetaDataFieldWorkflow_ValidationError_MetaDataTypeNotExisting_Message=>T("PageType.EditPageTypeMetaDataFieldWorkflow.ValidationError.MetaDataTypeNotExisting.Message"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.PageTypeElementProvider", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_RazorFunction { ///"Razor Functions" public static string RootElement_Label=>T("RootElement.Label"); ///"Razor functions" public static string RootElement_ToolTip=>T("RootElement.ToolTip"); ///"Add Razor Function" public static string AddNewRazorFunction_Label=>T("AddNewRazorFunction.Label"); ///"Add a new Razor function" public static string AddNewRazorFunction_ToolTip=>T("AddNewRazorFunction.ToolTip"); ///"Edit" public static string EditRazorFunction_Label=>T("EditRazorFunction.Label"); ///"Edit Razor Function" public static string EditRazorFunction_ToolTip=>T("EditRazorFunction.ToolTip"); ///"Delete" public static string DeleteRazorFunction_Label=>T("DeleteRazorFunction.Label"); ///"Delete this Razor function" public static string DeleteRazorFunction_ToolTip=>T("DeleteRazorFunction.ToolTip"); ///"Add Razor Function" public static string AddNewRazorFunction_LabelDialog=>T("AddNewRazorFunction.LabelDialog"); ///"Name" public static string AddNewRazorFunction_LabelName=>T("AddNewRazorFunction.LabelName"); ///"" public static string AddNewRazorFunction_HelpName=>T("AddNewRazorFunction.HelpName"); ///"Namespace" public static string AddNewRazorFunction_LabelNamespace=>T("AddNewRazorFunction.LabelNamespace"); ///"" public static string AddNewRazorFunction_HelpNamespace=>T("AddNewRazorFunction.HelpNamespace"); ///"Copy from" public static string AddNewRazorFunction_LabelCopyFrom=>T("AddNewRazorFunction.LabelCopyFrom"); ///"You can copy the code from another Razor function by selecting it in this list." public static string AddNewRazorFunction_LabelCopyFromHelp=>T("AddNewRazorFunction.LabelCopyFromHelp"); ///"(New Razor function)" public static string AddNewRazorFunction_LabelCopyFromEmptyOption=>T("AddNewRazorFunction.LabelCopyFromEmptyOption"); ///"A C1 function with the same name already exists." public static string AddNewRazorFunctionWorkflow_DuplicateName=>T("AddNewRazorFunctionWorkflow.DuplicateName"); ///"The function name is empty" public static string AddNewRazorFunctionWorkflow_EmptyName=>T("AddNewRazorFunctionWorkflow.EmptyName"); ///"The function namespace is empty" public static string AddNewRazorFunctionWorkflow_NamespaceEmpty=>T("AddNewRazorFunctionWorkflow.NamespaceEmpty"); ///"The namespace must be like A.B.C - not starting or ending with a period (.)" public static string AddNewRazorFunctionWorkflow_InvalidNamespace=>T("AddNewRazorFunctionWorkflow.InvalidNamespace"); ///"The total length of the name and the namespace is too long (used to name the .cshtml file)." public static string AddNewRazorFunctionWorkflow_TotalNameTooLang=>T("AddNewRazorFunctionWorkflow.TotalNameTooLang"); ///"Validation Error" public static string EditRazorFunctionWorkflow_Validation_DialogTitle=>T("EditRazorFunctionWorkflow.Validation.DialogTitle"); ///"Compilation failed: {0}" public static string EditRazorFunctionWorkflow_Validation_CompilationFailed_Template=>T("EditRazorFunctionWorkflow.Validation.CompilationFailed"); ///"Compilation failed: {0}" public static string EditRazorFunctionWorkflow_Validation_CompilationFailed(object parameter0)=>string.Format(T("EditRazorFunctionWorkflow.Validation.CompilationFailed"), parameter0); ///"Razor function should inherit '{0}'" public static string EditRazorFunctionWorkflow_Validation_IncorrectBaseClass_Template=>T("EditRazorFunctionWorkflow.Validation.IncorrectBaseClass"); ///"Razor function should inherit '{0}'" public static string EditRazorFunctionWorkflow_Validation_IncorrectBaseClass(object parameter0)=>string.Format(T("EditRazorFunctionWorkflow.Validation.IncorrectBaseClass"), parameter0); ///"Delete Razor Function?" public static string DeleteRazorFunctionWorkflow_ConfirmDeleteTitle=>T("DeleteRazorFunctionWorkflow.ConfirmDeleteTitle"); ///"Delete the selected Razor function?" public static string DeleteRazorFunctionWorkflow_ConfirmDeleteMessage=>T("DeleteRazorFunctionWorkflow.ConfirmDeleteMessage"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.RazorFunction", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_RazorPageTemplate { ///"Edit Razor File" public static string EditRazorFileAction_Label=>T("EditRazorFileAction.Label"); ///"Edit the cshtml file" public static string EditRazorFileAction_ToolTip=>T("EditRazorFileAction.ToolTip"); ///"Edit Razor Template" public static string EditRazorTemplateAction_Label=>T("EditRazorTemplateAction.Label"); ///"Edit the cshtml file behind the template" public static string EditRazorTemplateAction_ToolTip=>T("EditRazorTemplateAction.ToolTip"); ///"Delete" public static string DeleteRazorPageTemplateAction_Label=>T("DeleteRazorPageTemplateAction.Label"); ///"Delete page template" public static string DeleteRazorPageTemplateAction_ToolTip=>T("DeleteRazorPageTemplateAction.ToolTip"); ///"Add New Razor Template" public static string AddNewRazorPageTemplate_LabelDialog=>T("AddNewRazorPageTemplate.LabelDialog"); ///"Template Title" public static string AddNewRazorPageTemplate_LabelTemplateTitle=>T("AddNewRazorPageTemplate.LabelTemplateTitle"); ///"The title identifies this template in lists. Consider selecting a short but meaningful name." public static string AddNewRazorPageTemplate_LabelTemplateTitleHelp=>T("AddNewRazorPageTemplate.LabelTemplateTitleHelp"); ///"Copy from" public static string AddNewRazorPageTemplate_LabelCopyFrom=>T("AddNewRazorPageTemplate.LabelCopyFrom"); ///"You can copy the markup from another Layout Template by selecting it in this list." public static string AddNewRazorPageTemplate_LabelCopyFromHelp=>T("AddNewRazorPageTemplate.LabelCopyFromHelp"); ///"(New template)" public static string AddNewRazorPageTemplate_LabelCopyFromEmptyOption=>T("AddNewRazorPageTemplate.LabelCopyFromEmptyOption"); ///"Title already used" public static string AddNewRazorPageTemplateWorkflow_TitleInUseTitle=>T("AddNewRazorPageTemplateWorkflow.TitleInUseTitle"); ///"The title is too long (used as part of the .cshtml filename)." public static string AddNewRazorPageTemplateWorkflow_TitleTooLong=>T("AddNewRazorPageTemplateWorkflow.TitleTooLong"); ///"Validation error" public static string EditTemplate_Validation_DialogTitle=>T("EditTemplate.Validation.DialogTitle"); ///"Compilation failed: {0}" public static string EditTemplate_Validation_CompilationFailed_Template=>T("EditTemplate.Validation.CompilationFailed"); ///"Compilation failed: {0}" public static string EditTemplate_Validation_CompilationFailed(object parameter0)=>string.Format(T("EditTemplate.Validation.CompilationFailed"), parameter0); ///"Page template class does not inherit '{0}'" public static string EditTemplate_Validation_IncorrectBaseClass_Template=>T("EditTemplate.Validation.IncorrectBaseClass"); ///"Page template class does not inherit '{0}'" public static string EditTemplate_Validation_IncorrectBaseClass(object parameter0)=>string.Format(T("EditTemplate.Validation.IncorrectBaseClass"), parameter0); ///"Failed to evaluate page template property '{0}'. Excepton: {1}" public static string EditTemplate_Validation_PropertyError_Template=>T("EditTemplate.Validation.PropertyError"); ///"Failed to evaluate page template property '{0}'. Excepton: {1}" public static string EditTemplate_Validation_PropertyError(object parameter0,object parameter1)=>string.Format(T("EditTemplate.Validation.PropertyError"), parameter0,parameter1); ///"It is not allowed to change template id through current workflow. Original template id is '{0}'" public static string EditTemplate_Validation_TemplateIdChanged_Template=>T("EditTemplate.Validation.TemplateIdChanged"); ///"It is not allowed to change template id through current workflow. Original template id is '{0}'" public static string EditTemplate_Validation_TemplateIdChanged(object parameter0)=>string.Format(T("EditTemplate.Validation.TemplateIdChanged"), parameter0); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.RazorPageTemplate", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_SqlFunction { ///"SQL Functions" public static string SqlFunctionElementProvider_RootLabel=>T("SqlFunctionElementProvider.RootLabel"); ///"Add Connections and then queries to connections" public static string SqlFunctionElementProvider_RootLabelToolTip=>T("SqlFunctionElementProvider.RootLabelToolTip"); ///"Add SQL Connection" public static string SqlFunctionElementProvider_AddConnection=>T("SqlFunctionElementProvider.AddConnection"); ///"Add new SQL connection" public static string SqlFunctionElementProvider_AddConnectionToolTip=>T("SqlFunctionElementProvider.AddConnectionToolTip"); ///"Edit" public static string SqlFunctionElementProvider_EditConnection=>T("SqlFunctionElementProvider.EditConnection"); ///"Edit SQL connection" public static string SqlFunctionElementProvider_EditConnectionToolTip=>T("SqlFunctionElementProvider.EditConnectionToolTip"); ///"Delete" public static string SqlFunctionElementProvider_DeleteConnection=>T("SqlFunctionElementProvider.DeleteConnection"); ///"Delete SQL connection" public static string SqlFunctionElementProvider_DeleteConnectionToolTip=>T("SqlFunctionElementProvider.DeleteConnectionToolTip"); ///"Add New SQL Query" public static string SqlFunctionElementProvider_AddQuery=>T("SqlFunctionElementProvider.AddQuery"); ///"Add a new SQL XML Provider" public static string SqlFunctionElementProvider_AddQueryToolTip=>T("SqlFunctionElementProvider.AddQueryToolTip"); ///"Edit" public static string SqlFunctionElementProvider_EditQuery=>T("SqlFunctionElementProvider.EditQuery"); ///"Edit SQL Query" public static string SqlFunctionElementProvider_EditQueryToolTip=>T("SqlFunctionElementProvider.EditQueryToolTip"); ///"Delete" public static string SqlFunctionElementProvider_DeleteQuery=>T("SqlFunctionElementProvider.DeleteQuery"); ///"Delete SQL Query" public static string SqlFunctionElementProvider_DeleteQueryToolTip=>T("SqlFunctionElementProvider.DeleteQueryToolTip"); ///"Add New SQL Query" public static string AddNewSqlFunction_LabelDialog=>T("AddNewSqlFunction.LabelDialog"); ///"Function naming" public static string AddNewSqlFunction_LabelNamingPanel=>T("AddNewSqlFunction.LabelNamingPanel"); ///"Name" public static string AddNewSqlFunction_LabelName=>T("AddNewSqlFunction.LabelName"); ///"" public static string AddNewSqlFunction_HelpName=>T("AddNewSqlFunction.HelpName"); ///"Namespace" public static string AddNewSqlFunction_LabelNamespace=>T("AddNewSqlFunction.LabelNamespace"); ///"" public static string AddNewSqlFunction_HelpNamespace=>T("AddNewSqlFunction.HelpNamespace"); ///"SQL command text" public static string AddNewSqlFunction_LabelQueryCOmmand=>T("AddNewSqlFunction.LabelQueryCOmmand"); ///"" public static string AddNewSqlFunction_HelpQueryCOmmand=>T("AddNewSqlFunction.HelpQueryCOmmand"); ///"Is a Stored Procedure" public static string AddEditSqlFunction_LabelIsStoredProcedure=>T("AddEditSqlFunction.LabelIsStoredProcedure"); ///"Yes, the command is a procedure" public static string AddEditSqlFunction_LabelIsStoredProcedureCheckBox=>T("AddEditSqlFunction.LabelIsStoredProcedureCheckBox"); ///"Returns result as XML" public static string AddEditSqlFunction_LabelReturnsXml=>T("AddEditSqlFunction.LabelReturnsXml"); ///"Yes, the command returns XML" public static string AddEditSqlFunction_LabelReturnsXmlCheckBox=>T("AddEditSqlFunction.LabelReturnsXmlCheckBox"); ///"Is a query" public static string AddEditSqlFunction_LabelIsQuery=>T("AddEditSqlFunction.LabelIsQuery"); ///"Yes, the command returns data" public static string AddEditSqlFunction_LabelIsQueryCheckBox=>T("AddEditSqlFunction.LabelIsQueryCheckBox"); ///"SQL Command behaviour" public static string AddEditSqlFunction_LabelCommandBehaviour=>T("AddEditSqlFunction.LabelCommandBehaviour"); ///"SQL Command" public static string AddEditSqlFunction_LabelSqlEditor=>T("AddEditSqlFunction.LabelSqlEditor"); ///"Add New SQL Connection" public static string AddNewSqlFunctionConnection_LabelDialog=>T("AddNewSqlFunctionConnection.LabelDialog"); ///"Name" public static string AddNewSqlFunctionConnection_LabelName=>T("AddNewSqlFunctionConnection.LabelName"); ///"" public static string AddNewSqlFunctionConnection_HelpName=>T("AddNewSqlFunctionConnection.HelpName"); ///"Connection String" public static string AddNewSqlFunctionConnection_LabelConnectionString=>T("AddNewSqlFunctionConnection.LabelConnectionString"); ///"" public static string AddNewSqlFunctionConnection_HelpConnectionString=>T("AddNewSqlFunctionConnection.HelpConnectionString"); ///"MS SQL Server" public static string AddNewSqlFunctionConnection_LabelIsMSSQL=>T("AddNewSqlFunctionConnection.LabelIsMSSQL"); ///"Database is a MS SQL Server" public static string AddNewSqlFunctionConnection_LabelIsMSSQLCheckBox=>T("AddNewSqlFunctionConnection.LabelIsMSSQLCheckBox"); ///"SQL Connection settings" public static string EditSqlFunctionConnection_LabelFieldGroup=>T("EditSqlFunctionConnection.LabelFieldGroup"); ///"Input Parameters" public static string EditSqlFunction_LabelInputParameters=>T("EditSqlFunction.LabelInputParameters"); ///"Settings" public static string EditSqlFunction_LabelSettings=>T("EditSqlFunction.LabelSettings"); ///"Function name and description" public static string EditSqlFunction_LabelNamingAndDescription=>T("EditSqlFunction.LabelNamingAndDescription"); ///"Name" public static string EditSqlFunction_LabelName=>T("EditSqlFunction.LabelName"); ///"" public static string EditSqlFunction_HelpName=>T("EditSqlFunction.HelpName"); ///"Namespace" public static string EditSqlFunction_LabelNamespace=>T("EditSqlFunction.LabelNamespace"); ///"" public static string EditSqlFunction_HelpNamespace=>T("EditSqlFunction.HelpNamespace"); ///"Description" public static string EditSqlFunction_LabelDescription=>T("EditSqlFunction.LabelDescription"); ///"" public static string EditSqlFunction_HelpDescription=>T("EditSqlFunction.HelpDescription"); ///"Preview" public static string EditSqlFunction_LabelPreview=>T("EditSqlFunction.LabelPreview"); ///"Name" public static string EditSqlFunctionConnection_LabelName=>T("EditSqlFunctionConnection.LabelName"); ///"" public static string EditSqlFunctionConnection_HelpName=>T("EditSqlFunctionConnection.HelpName"); ///"Connection String" public static string EditSqlFunctionConnection_LabelConnectionString=>T("EditSqlFunctionConnection.LabelConnectionString"); ///"" public static string EditSqlFunctionConnection_HelpConnectionString=>T("EditSqlFunctionConnection.HelpConnectionString"); ///"MS SQL Server" public static string EditSqlFunctionConnection_LabelIsMSSQL=>T("EditSqlFunctionConnection.LabelIsMSSQL"); ///"Database is a MS SQL Server" public static string EditSqlFunctionConnection_LabelIsMSSQLCheckBox=>T("EditSqlFunctionConnection.LabelIsMSSQLCheckBox"); ///"Delete This SQL Connection?" public static string DeleteSqlConnection_LabelFieldGroup=>T("DeleteSqlConnection.LabelFieldGroup"); ///"Delete this SQL connection?" public static string DeleteSqlConnection_Text=>T("DeleteSqlConnection.Text"); ///"Delete This SQL Function?" public static string DeleteSqlFunction_LabelFieldGroup=>T("DeleteSqlFunction.LabelFieldGroup"); ///"Delete this SQL function?" public static string DeleteSqlFunction_Text=>T("DeleteSqlFunction.Text"); ///"Cascade Delete Error" public static string CascadeDeleteErrorTitle=>T("CascadeDeleteErrorTitle"); ///"The type is referenced by another type that does not allow cascade deletes. This operation is halted" public static string CascadeDeleteErrorMessage=>T("CascadeDeleteErrorMessage"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_StandardFunctions { ///"Loads an ASP.NET User Control" public static string Composite_AspNet_LoadUserControl_description=>T("Composite.AspNet.LoadUserControl.description"); ///"The path to the User Controls .ascx file, like “~/Controls/MyControl.ascx”" public static string Composite_AspNet_LoadUserControl_param_Path_help=>T("Composite.AspNet.LoadUserControl.param.Path.help"); ///"Path" public static string Composite_AspNet_LoadUserControl_param_Path_label=>T("Composite.AspNet.LoadUserControl.param.Path.label"); ///"Lets you specify constant boolean value" public static string Composite_Constant_Boolean_description=>T("Composite.Constant.Boolean.description"); ///"" public static string Composite_Constant_Boolean_param_Constant_help=>T("Composite.Constant.Boolean.param.Constant.help"); ///"Value" public static string Composite_Constant_Boolean_param_Constant_label=>T("Composite.Constant.Boolean.param.Constant.label"); ///"Lets you specify constant date and time value" public static string Composite_Constant_DateTime_description=>T("Composite.Constant.DateTime.description"); ///"" public static string Composite_Constant_DateTime_param_Constant_help=>T("Composite.Constant.DateTime.param.Constant.help"); ///"Value" public static string Composite_Constant_DateTime_param_Constant_label=>T("Composite.Constant.DateTime.param.Constant.label"); ///"Lets you specify constant decimal value" public static string Composite_Constant_Decimal_description=>T("Composite.Constant.Decimal.description"); ///"" public static string Composite_Constant_Decimal_param_Constant_help=>T("Composite.Constant.Decimal.param.Constant.help"); ///"Value" public static string Composite_Constant_Decimal_param_Constant_label=>T("Composite.Constant.Decimal.param.Constant.label"); ///"Lets you specify constant Guid value" public static string Composite_Constant_Guid_description=>T("Composite.Constant.Guid.description"); ///"" public static string Composite_Constant_Guid_param_Constant_help=>T("Composite.Constant.Guid.param.Constant.help"); ///"Value" public static string Composite_Constant_Guid_param_Constant_label=>T("Composite.Constant.Guid.param.Constant.label"); ///"Lets you specify constant integer value" public static string Composite_Constant_Integer_description=>T("Composite.Constant.Integer.description"); ///"" public static string Composite_Constant_Integer_param_Constant_help=>T("Composite.Constant.Integer.param.Constant.help"); ///"Value" public static string Composite_Constant_Integer_param_Constant_label=>T("Composite.Constant.Integer.param.Constant.label"); ///"Lets you specify constant string value" public static string Composite_Constant_String_description=>T("Composite.Constant.String.description"); ///"" public static string Composite_Constant_String_param_Constant_help=>T("Composite.Constant.String.param.Constant.help"); ///"Value" public static string Composite_Constant_String_param_Constant_label=>T("Composite.Constant.String.param.Constant.label"); ///"Lets you visually specify a Xhtml document constant" public static string Composite_Constant_XhtmlDocument_description=>T("Composite.Constant.XhtmlDocument.description"); ///"" public static string Composite_Constant_XhtmlDocument_param_Constant_help=>T("Composite.Constant.XhtmlDocument.param.Constant.help"); ///"Value" public static string Composite_Constant_XhtmlDocument_param_Constant_label=>T("Composite.Constant.XhtmlDocument.param.Constant.label"); ///"Adds a new instance of the given type." public static string Composite_IDataGenerated_AddDataInstance_description=>T("Composite.IDataGenerated.AddDataInstance.description"); ///"Updates instance(s) with the given values." public static string Composite_IDataGenerated_UpdateDataInstance_description=>T("Composite.IDataGenerated.UpdateDataInstance.description"); ///"" public static string Composite_IDataGenerated_UpdateDataInstance_param_Filter_help=>T("Composite.IDataGenerated.UpdateDataInstance.param.Filter.help"); ///"Filter" public static string Composite_IDataGenerated_UpdateDataInstance_param_Filter_label=>T("Composite.IDataGenerated.UpdateDataInstance.param.Filter.label"); ///"Deletes instance(s) with the given filter." public static string Composite_IDataGenerated_DeleteDataInstance_description=>T("Composite.IDataGenerated.DeleteDataInstance.description"); ///"" public static string Composite_IDataGenerated_DeleteDataInstance_param_Filter_help=>T("Composite.IDataGenerated.DeleteDataInstance.param.Filter.help"); ///"Filter" public static string Composite_IDataGenerated_DeleteDataInstance_param_Filter_label=>T("Composite.IDataGenerated.DeleteDataInstance.param.Filter.label"); ///"Creates a DataReference based on a key value." public static string Composite_IDataGenerated_GetDataReference_description=>T("Composite.IDataGenerated.GetDataReference.description"); ///"The key value of the data to reference." public static string Composite_IDataGenerated_GetDataReference_param_KeyValue_help=>T("Composite.IDataGenerated.GetDataReference.param.KeyValue.help"); ///"Key value" public static string Composite_IDataGenerated_GetDataReference_param_KeyValue_label=>T("Composite.IDataGenerated.GetDataReference.param.KeyValue.label"); ///"Creates a NullableDataReference based on a key value. The default value is 'null', no reference." public static string Composite_IDataGenerated_GetNullableDataReference_description=>T("Composite.IDataGenerated.GetNullableDataReference.description"); ///"The key value of the data to reference." public static string Composite_IDataGenerated_GetNullableDataReference_param_KeyValue_help=>T("Composite.IDataGenerated.GetNullableDataReference.param.KeyValue.help"); ///"Key value" public static string Composite_IDataGenerated_GetNullableDataReference_param_KeyValue_label=>T("Composite.IDataGenerated.GetNullableDataReference.param.KeyValue.label"); ///"Converts a DataReference into a single element filter. This filter will select a maximum of one item." public static string Composite_IDataGenerated_Filter_DataReferenceFilter_description=>T("Composite.IDataGenerated.Filter.DataReferenceFilter.description"); ///"The Data Reference to use when selecting data." public static string Composite_IDataGenerated_Filter_DataReferenceFilter_param_DataReference_help=>T("Composite.IDataGenerated.Filter.DataReferenceFilter.param.DataReference.help"); ///"Data Reference" public static string Composite_IDataGenerated_Filter_DataReferenceFilter_param_DataReference_label=>T("Composite.IDataGenerated.Filter.DataReferenceFilter.param.DataReference.label"); ///"Lets you select data based on its reference to the currently rendered page." public static string Composite_IDataGenerated_Filter_ActivePageReferenceFilter_description=>T("Composite.IDataGenerated.Filter.ActivePageReferenceFilter.description"); ///"Select what relation the current page must have with the data you wish to retrieve." public static string Composite_IDataGenerated_Filter_ActivePageReferenceFilter_param_SitemapScope_help=>T("Composite.IDataGenerated.Filter.ActivePageReferenceFilter.param.SitemapScope.help"); ///"Page scope" public static string Composite_IDataGenerated_Filter_ActivePageReferenceFilter_param_SitemapScope_label=>T("Composite.IDataGenerated.Filter.ActivePageReferenceFilter.param.SitemapScope.label"); ///"Defines an “and” or “or” query, combining two other filters." public static string Composite_IDataGenerated_Filter_CompoundFilter_description=>T("Composite.IDataGenerated.Filter.CompoundFilter.description"); ///"And / or filter" public static string Composite_IDataGenerated_Filter_CompoundFilter_param_IsAndQuery_label=>T("Composite.IDataGenerated.Filter.CompoundFilter.param.IsAndQuery.label"); ///"If you select “And” both filters are applied to the data. Selecting “Or” will give you the data that matches just one of the filters." public static string Composite_IDataGenerated_Filter_CompoundFilter_param_IsAndQuery_help=>T("Composite.IDataGenerated.Filter.CompoundFilter.param.IsAndQuery.help"); ///"One of the two filters (the one to evaluate first)" public static string Composite_IDataGenerated_Filter_CompoundFilter_param_Left_help=>T("Composite.IDataGenerated.Filter.CompoundFilter.param.Left.help"); ///"Left filter" public static string Composite_IDataGenerated_Filter_CompoundFilter_param_Left_label=>T("Composite.IDataGenerated.Filter.CompoundFilter.param.Left.label"); ///"One of the two filters (the one to evaluate last)" public static string Composite_IDataGenerated_Filter_CompoundFilter_param_Right_help=>T("Composite.IDataGenerated.Filter.CompoundFilter.param.Right.help"); ///"Right filter" public static string Composite_IDataGenerated_Filter_CompoundFilter_param_Right_label=>T("Composite.IDataGenerated.Filter.CompoundFilter.param.Right.label"); ///"Lets you specify a filter on data by specifying requirements for the individual fields. If you set requirements on multiple fields, they are all enforced (and query)." public static string Composite_IDataGenerated_Filter_FieldPredicatesFilter_description=>T("Composite.IDataGenerated.Filter.FieldPredicatesFilter.description"); ///"Retrieves an XML representation of the data. " public static string Composite_IDataGenerated_GetXml_description=>T("Composite.IDataGenerated.GetXml.description"); ///"Element name" public static string Composite_IDataGenerated_GetXml_param_ElementName_label=>T("Composite.IDataGenerated.GetXml.param.ElementName.label"); ///"Element namespace" public static string Composite_IDataGenerated_GetXml_param_ElementNamespace_label=>T("Composite.IDataGenerated.GetXml.param.ElementNamespace.label"); ///"" public static string Composite_IDataGenerated_GetXml_param_Filter_help=>T("Composite.IDataGenerated.GetXml.param.Filter.help"); ///"Filter" public static string Composite_IDataGenerated_GetXml_param_Filter_label=>T("Composite.IDataGenerated.GetXml.param.Filter.label"); ///"When selected the data XML will be preceded by a <PagingInfo /> element detailing number of pages, items and more." public static string Composite_IDataGenerated_GetXml_param_IncludePagingInfo_help=>T("Composite.IDataGenerated.GetXml.param.IncludePagingInfo.help"); ///"Include paging info" public static string Composite_IDataGenerated_GetXml_param_IncludePagingInfo_label=>T("Composite.IDataGenerated.GetXml.param.IncludePagingInfo.label"); ///"The field to order data by" public static string Composite_IDataGenerated_GetXml_param_OrderByField_help=>T("Composite.IDataGenerated.GetXml.param.OrderByField.help"); ///"Order by" public static string Composite_IDataGenerated_GetXml_param_OrderByField_label=>T("Composite.IDataGenerated.GetXml.param.OrderByField.label"); ///"When set to true results are delivered in ascending order, otherwise descending order is used. Default is ascending order." public static string Composite_IDataGenerated_GetXml_param_OrderAscending_help=>T("Composite.IDataGenerated.GetXml.param.OrderAscending.help"); ///"Order ascending" public static string Composite_IDataGenerated_GetXml_param_OrderAscending_label=>T("Composite.IDataGenerated.GetXml.param.OrderAscending.label"); ///"If the number of data elements exceed the page size you can use paging to move to the other pages. See the Page size parameter." public static string Composite_IDataGenerated_GetXml_param_PageNumber_help=>T("Composite.IDataGenerated.GetXml.param.PageNumber.help"); ///"Page number" public static string Composite_IDataGenerated_GetXml_param_PageNumber_label=>T("Composite.IDataGenerated.GetXml.param.PageNumber.label"); ///"The number of items to display on one page – the maximum number of elements to return. " public static string Composite_IDataGenerated_GetXml_param_PageSize_help=>T("Composite.IDataGenerated.GetXml.param.PageSize.help"); ///"Page size" public static string Composite_IDataGenerated_GetXml_param_PageSize_label=>T("Composite.IDataGenerated.GetXml.param.PageSize.label"); ///"The data fields to output in the XML. Fewer fields can yield faster renderings." public static string Composite_IDataGenerated_GetXml_param_PropertyNames_help=>T("Composite.IDataGenerated.GetXml.param.PropertyNames.help"); ///"Selected fields" public static string Composite_IDataGenerated_GetXml_param_PropertyNames_label=>T("Composite.IDataGenerated.GetXml.param.PropertyNames.label"); ///"If you include reference data in the 'Selected properties' setting, you can use this option to control how the referenced data is included. 'Inline' is easy to use, but may bloat the size of the XML document." public static string Composite_IDataGenerated_GetXml_param_ShowReferencesInline_help=>T("Composite.IDataGenerated.GetXml.param.ShowReferencesInline.help"); ///"Show reference data inline" public static string Composite_IDataGenerated_GetXml_param_ShowReferencesInline_label=>T("Composite.IDataGenerated.GetXml.param.ShowReferencesInline.label"); ///"When true data can be ordered randomly. Specify the number of random results you require by setting the 'Page size'. If a filter is specified, this is applied before the random selection. If you specify an 'Order by' value, you should specify a low 'Page size' or the randomization will become void." public static string Composite_IDataGenerated_GetXml_param_Randomized_help=>T("Composite.IDataGenerated.GetXml.param.Randomized.help"); ///"Randomized" public static string Composite_IDataGenerated_GetXml_param_Randomized_label=>T("Composite.IDataGenerated.GetXml.param.Randomized.label"); ///"Determines if result XML has to be cached, and what priority those cache records should have" public static string Composite_IDataGenerated_GetXml_param_CachePriority_help=>T("Composite.IDataGenerated.GetXml.param.CachePriority.help"); ///"Cache Priority" public static string Composite_IDataGenerated_GetXml_param_CachePriority_label=>T("Composite.IDataGenerated.GetXml.param.CachePriority.label"); ///"Fetches the ID of the current page or a page relative to the current page." public static string Composite_Pages_GetPageId_description=>T("Composite.Pages.GetPageId.description"); ///"What page to get id from. The default is from the current page." public static string Composite_Pages_GetPageId_param_SitemapScope_help=>T("Composite.Pages.GetPageId.param.SitemapScope.help"); ///"Page association" public static string Composite_Pages_GetPageId_param_SitemapScope_label=>T("Composite.Pages.GetPageId.param.SitemapScope.label"); ///"Quick and raw sitemap xhtml." public static string Composite_Pages_QuickSitemap_description=>T("Composite.Pages.QuickSitemap.description"); ///"Returns a hierarchical XML structure of pages. When executed as part of a page rendering XML elements representing the current and ancestor pages will be appended the attributes isopen=”true” and iscurrent=”true”" public static string Composite_Pages_SitemapXml_description=>T("Composite.Pages.SitemapXml.description"); ///"Source page" public static string Composite_Pages_SitemapXml_param_SourcePage_label=>T("Composite.Pages.SitemapXml.param.SourcePage.label"); ///"By default the source page is the page currently being rendered. Specify a value if you want to get sitemap information relative to another page. The source page controls how page elements are annotated with 'isopen' and 'iscurrent' and is the starting point when calculating the page scope." public static string Composite_Pages_SitemapXml_param_SourcePage_help=>T("Composite.Pages.SitemapXml.param.SourcePage.help"); ///"Page scope" public static string Composite_Pages_SitemapXml_param_SitemapScope_label=>T("Composite.Pages.SitemapXml.param.SitemapScope.label"); ///"The scope of pages to extract from the sitemap. The default is 'all pages'. You can use this parameter to extract the structure you need to complete your task." public static string Composite_Pages_SitemapXml_param_SitemapScope_help=>T("Composite.Pages.SitemapXml.param.SitemapScope.help"); ///"Gets information about current page in all the languages." public static string Composite_Pages_GetForeignPageInfo_description=>T("Composite.Pages.GetForeignPageInfo.description"); ///"Defines a 'cache zone' around a function call or markup (typically containing function calls). This function can be used to enhance page rendering performance by caching sections of a web page. The 'Object Cache Id' value should be unique to the content being cached." public static string Composite_Utils_Caching_PageObjectCache_description=>T("Composite.Utils.Caching.PageObjectCache.description"); ///"Object to cache" public static string Composite_Utils_Caching_PageObjectCache_param_ObjectToCache_label=>T("Composite.Utils.Caching.PageObjectCache.param.ObjectToCache.label"); ///"What you want to cache - this can be a single function call or a section of markup containing one or more function calls." public static string Composite_Utils_Caching_PageObjectCache_param_ObjectToCache_help=>T("Composite.Utils.Caching.PageObjectCache.param.ObjectToCache.help"); ///"Unique cache id" public static string Composite_Utils_Caching_PageObjectCache_param_ObjectCacheId_label=>T("Composite.Utils.Caching.PageObjectCache.param.ObjectCacheId.label"); ///"Specify an ID unique to the content being cached. This value is used - in conjunction with the Page scope - to define a unique cache key." public static string Composite_Utils_Caching_PageObjectCache_param_ObjectCacheId_help=>T("Composite.Utils.Caching.PageObjectCache.param.ObjectCacheId.help"); ///"Page scope" public static string Composite_Utils_Caching_PageObjectCache_param_SitemapScope_label=>T("Composite.Utils.Caching.PageObjectCache.param.SitemapScope.label"); ///"The page scope the cached data should be shared on. By default the page scope is 'this website', but you can change it to page specific caching and more." public static string Composite_Utils_Caching_PageObjectCache_param_SitemapScope_help=>T("Composite.Utils.Caching.PageObjectCache.param.SitemapScope.help"); ///"Cache duration (seconds)" public static string Composite_Utils_Caching_PageObjectCache_param_SecondsToCache_label=>T("Composite.Utils.Caching.PageObjectCache.param.SecondsToCache.label"); ///"The number of seconds the cached object should be reused. Default is 1 minute (60 seconds)." public static string Composite_Utils_Caching_PageObjectCache_param_SecondsToCache_help=>T("Composite.Utils.Caching.PageObjectCache.param.SecondsToCache.help"); ///"Language specific" public static string Composite_Utils_Caching_PageObjectCache_param_LanguageSpecific_label=>T("Composite.Utils.Caching.PageObjectCache.param.LanguageSpecific.label"); ///"Choose if the cached object should be uniquely cached per website language or commonly shared among languages." public static string Composite_Utils_Caching_PageObjectCache_param_LanguageSpecific_help=>T("Composite.Utils.Caching.PageObjectCache.param.LanguageSpecific.help"); ///"AreEqual" public static string Composite_Utils_Compare_AreEqual_description=>T("Composite.Utils.Compare.AreEqual.description"); ///"Compares two objects for equality. Returns true if the two objects are equal." public static string Composite_Utils_Compare_AreEqual_param_ValueA_help=>T("Composite.Utils.Compare.AreEqual.param.ValueA.help"); ///"Value A to compare." public static string Composite_Utils_Compare_AreEqual_param_ValueA_label=>T("Composite.Utils.Compare.AreEqual.param.ValueA.label"); ///"" public static string Composite_Utils_Compare_AreEqual_param_ValueB_help=>T("Composite.Utils.Compare.AreEqual.param.ValueB.help"); ///"Value B to compare." public static string Composite_Utils_Compare_AreEqual_param_ValueB_label=>T("Composite.Utils.Compare.AreEqual.param.ValueB.label"); ///"" public static string Composite_Utils_Compare_IsLessThan_description=>T("Composite.Utils.Compare.IsLessThan.description"); ///"" public static string Composite_Utils_Compare_IsLessThan_param_ValueA_help=>T("Composite.Utils.Compare.IsLessThan.param.ValueA.help"); ///"Value A to compare." public static string Composite_Utils_Compare_IsLessThan_param_ValueA_label=>T("Composite.Utils.Compare.IsLessThan.param.ValueA.label"); ///"" public static string Composite_Utils_Compare_IsLessThan_param_ValueB_help=>T("Composite.Utils.Compare.IsLessThan.param.ValueB.help"); ///"Value B to compare." public static string Composite_Utils_Compare_IsLessThan_param_ValueB_label=>T("Composite.Utils.Compare.IsLessThan.param.ValueB.label"); ///"Reads a string from the application configuration file (web.config or app.config)" public static string Composite_Utils_Configuration_AppSettingsValue_description=>T("Composite.Utils.Configuration.AppSettingsValue.description"); ///"" public static string Composite_Utils_Configuration_AppSettingsValue_param_KeyName_help=>T("Composite.Utils.Configuration.AppSettingsValue.param.KeyName.help"); ///"Key Name" public static string Composite_Utils_Configuration_AppSettingsValue_param_KeyName_label=>T("Composite.Utils.Configuration.AppSettingsValue.param.KeyName.label"); ///"Add a number of days to the current date and get the resulting date." public static string Composite_Utils_Date_AddDays_description=>T("Composite.Utils.Date.AddDays.description"); ///"Specify a negative or positive number of days to add to the current date." public static string Composite_Utils_Date_AddDays_param_DaysToAdd_help=>T("Composite.Utils.Date.AddDays.param.DaysToAdd.help"); ///"Days to add" public static string Composite_Utils_Date_AddDays_param_DaysToAdd_label=>T("Composite.Utils.Date.AddDays.param.DaysToAdd.label"); ///"The current date and time" public static string Composite_Utils_Date_Now_description=>T("Composite.Utils.Date.Now.description"); ///"Returns an input parameter from executing function context. Use this in developing to copy an input value to a new function call." public static string Composite_Utils_GetInputParameter_description=>T("Composite.Utils.GetInputParameter.description"); ///"Specify the name of the input parameter which value you wish to use here." public static string Composite_Utils_GetInputParameter_param_InputParameterName_help=>T("Composite.Utils.GetInputParameter.param.InputParameterName.help"); ///"Parameter name" public static string Composite_Utils_GetInputParameter_param_InputParameterName_label=>T("Composite.Utils.GetInputParameter.param.InputParameterName.label"); ///"Parses a string into an object. The type of object depends on the receiver. Using this function to deliver a value to a DateTime parameter, will make the system parse the string as a DateTime etc." public static string Composite_Utils_ParseStringToObject_description=>T("Composite.Utils.ParseStringToObject.description"); ///"Specify the string to parse. Note that the string must be formatted in a way that can be converted into the type of object that is expected." public static string Composite_Utils_ParseStringToObject_param_StringToParse_help=>T("Composite.Utils.ParseStringToObject.param.StringToParse.help"); ///"String to parse" public static string Composite_Utils_ParseStringToObject_param_StringToParse_label=>T("Composite.Utils.ParseStringToObject.param.StringToParse.label"); ///"Returns a new random Guid." public static string Composite_Utils_Guid_NewGuid_description=>T("Composite.Utils.Guid.NewGuid.description"); ///"A list of all cultures" public static string Composite_Utils_Globalization_AllCultures_description=>T("Composite.Utils.Globalization.AllCultures.description"); ///"The culture for the current user / request." public static string Composite_Utils_Globalization_CurrentCulture_description=>T("Composite.Utils.Globalization.CurrentCulture.description"); ///"Returns the sum from a list of integers" public static string Composite_Utils_Integer_Sum_description=>T("Composite.Utils.Integer.Sum.description"); ///"" public static string Composite_Utils_Integer_Sum_param_Ints_help=>T("Composite.Utils.Integer.Sum.param.Ints.help"); ///"Integer list" public static string Composite_Utils_Integer_Sum_param_Ints_label=>T("Composite.Utils.Integer.Sum.param.Ints.label"); ///"Check if a boolean is true or false. " public static string Composite_Utils_Predicates_BoolEquals_description=>T("Composite.Utils.Predicates.BoolEquals.description"); ///"" public static string Composite_Utils_Predicates_BoolEquals_param_Value_help=>T("Composite.Utils.Predicates.BoolEquals.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_BoolEquals_param_Value_label=>T("Composite.Utils.Predicates.BoolEquals.param.Value.label"); ///"Check if a date equals a certain value" public static string Composite_Utils_Predicates_DateTimeEquals_description=>T("Composite.Utils.Predicates.DateTimeEquals.description"); ///"" public static string Composite_Utils_Predicates_DateTimeEquals_param_Value_help=>T("Composite.Utils.Predicates.DateTimeEquals.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_DateTimeEquals_param_Value_label=>T("Composite.Utils.Predicates.DateTimeEquals.param.Value.label"); ///"Check if a date is greater than a certain value" public static string Composite_Utils_Predicates_DateTimeGreaterThan_description=>T("Composite.Utils.Predicates.DateTimeGreaterThan.description"); ///"" public static string Composite_Utils_Predicates_DateTimeGreaterThan_param_Value_help=>T("Composite.Utils.Predicates.DateTimeGreaterThan.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_DateTimeGreaterThan_param_Value_label=>T("Composite.Utils.Predicates.DateTimeGreaterThan.param.Value.label"); ///"Check if a date is less than a certain value" public static string Composite_Utils_Predicates_DateTimeLessThan_description=>T("Composite.Utils.Predicates.DateTimeLessThan.description"); ///"" public static string Composite_Utils_Predicates_DateTimeLessThan_param_Value_help=>T("Composite.Utils.Predicates.DateTimeLessThan.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_DateTimeLessThan_param_Value_label=>T("Composite.Utils.Predicates.DateTimeLessThan.param.Value.label"); ///"Check is a decimal has a certain value" public static string Composite_Utils_Predicates_DecimalEquals_description=>T("Composite.Utils.Predicates.DecimalEquals.description"); ///"" public static string Composite_Utils_Predicates_DecimalEquals_param_Value_help=>T("Composite.Utils.Predicates.DecimalEquals.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_DecimalEquals_param_Value_label=>T("Composite.Utils.Predicates.DecimalEquals.param.Value.label"); ///"Check if a decimal is greater than a certain value" public static string Composite_Utils_Predicates_DecimalGreaterThan_description=>T("Composite.Utils.Predicates.DecimalGreaterThan.description"); ///"" public static string Composite_Utils_Predicates_DecimalGreaterThan_param_Value_help=>T("Composite.Utils.Predicates.DecimalGreaterThan.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_DecimalGreaterThan_param_Value_label=>T("Composite.Utils.Predicates.DecimalGreaterThan.param.Value.label"); ///"Check if a decimal is less than a certain value" public static string Composite_Utils_Predicates_DecimalLessThan_description=>T("Composite.Utils.Predicates.DecimalLessThan.description"); ///"" public static string Composite_Utils_Predicates_DecimalLessThan_param_Value_help=>T("Composite.Utils.Predicates.DecimalLessThan.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_DecimalLessThan_param_Value_label=>T("Composite.Utils.Predicates.DecimalLessThan.param.Value.label"); ///"Check if a Guid equals a certain value" public static string Composite_Utils_Predicates_GuidEquals_description=>T("Composite.Utils.Predicates.GuidEquals.description"); ///"" public static string Composite_Utils_Predicates_GuidEquals_param_Value_help=>T("Composite.Utils.Predicates.GuidEquals.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_GuidEquals_param_Value_label=>T("Composite.Utils.Predicates.GuidEquals.param.Value.label"); ///"Check if a Guid exists in a comma separated string list" public static string Composite_Utils_Predicates_GuidInCommaSeparatedList_description=>T("Composite.Utils.Predicates.GuidInCommaSeparatedList.description"); ///"List of Guid" public static string Composite_Utils_Predicates_GuidInCommaSeparatedList_param_CommaSeparatedGuids_label=>T("Composite.Utils.Predicates.GuidInCommaSeparatedList.param.CommaSeparatedGuids.label"); ///"A string containing zero or more Guids separated by commas" public static string Composite_Utils_Predicates_GuidInCommaSeparatedList_param_CommaSeparatedGuids_help=>T("Composite.Utils.Predicates.GuidInCommaSeparatedList.param.CommaSeparatedGuids.help"); ///"Check if a string field matches one of the terms in a comma separated string list" public static string Composite_Utils_Predicates_StringInCommaSeparatedList_description=>T("Composite.Utils.Predicates.StringInCommaSeparatedList.description"); ///"Search terms" public static string Composite_Utils_Predicates_StringInCommaSeparatedList_param_CommaSeparatedSearchTerms_label=>T("Composite.Utils.Predicates.StringInCommaSeparatedList.param.CommaSeparatedSearchTerms.label"); ///"A string containing search terms separated by commas, like 'c1,cms,linq'" public static string Composite_Utils_Predicates_StringInCommaSeparatedList_param_CommaSeparatedSearchTerms_help=>T("Composite.Utils.Predicates.StringInCommaSeparatedList.param.CommaSeparatedSearchTerms.help"); ///"Ignore case" public static string Composite_Utils_Predicates_StringInCommaSeparatedList_param_IgnoreCase_label=>T("Composite.Utils.Predicates.StringInCommaSeparatedList.param.IgnoreCase.label"); ///"When 'false', casing of the words must match exactly. Default is 'true', case insensitive search" public static string Composite_Utils_Predicates_StringInCommaSeparatedList_param_IgnoreCase_help=>T("Composite.Utils.Predicates.StringInCommaSeparatedList.param.IgnoreCase.help"); ///"Check if a string field matches one of the strings in the supplied list" public static string Composite_Utils_Predicates_StringInList_description=>T("Composite.Utils.Predicates.StringInList.description"); ///"Search terms" public static string Composite_Utils_Predicates_StringInList_param_SearchTerms_label=>T("Composite.Utils.Predicates.StringInList.param.SearchTerms.label"); ///"A list of strings to match up against the searched string field." public static string Composite_Utils_Predicates_StringInList_param_SearchTerms_help=>T("Composite.Utils.Predicates.StringInList.param.SearchTerms.help"); ///"Ignore case" public static string Composite_Utils_Predicates_StringInList_param_IgnoreCase_label=>T("Composite.Utils.Predicates.StringInList.param.IgnoreCase.label"); ///"When 'false', casing of the words must match exactly. Default is 'true', case insensitive search" public static string Composite_Utils_Predicates_StringInList_param_IgnoreCase_help=>T("Composite.Utils.Predicates.StringInList.param.IgnoreCase.help"); ///"Check if an integer equals a certain value" public static string Composite_Utils_Predicates_IntegerEquals_description=>T("Composite.Utils.Predicates.IntegerEquals.description"); ///"" public static string Composite_Utils_Predicates_IntegerEquals_param_Value_help=>T("Composite.Utils.Predicates.IntegerEquals.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_IntegerEquals_param_Value_label=>T("Composite.Utils.Predicates.IntegerEquals.param.Value.label"); ///"Check if an integer is greater than a certain value" public static string Composite_Utils_Predicates_IntegerGreaterThan_description=>T("Composite.Utils.Predicates.IntegerGreaterThan.description"); ///"" public static string Composite_Utils_Predicates_IntegerGreaterThan_param_Value_help=>T("Composite.Utils.Predicates.IntegerGreaterThan.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_IntegerGreaterThan_param_Value_label=>T("Composite.Utils.Predicates.IntegerGreaterThan.param.Value.label"); ///"Check if an integer is less than a certain value" public static string Composite_Utils_Predicates_IntegerLessThan_description=>T("Composite.Utils.Predicates.IntegerLessThan.description"); ///"" public static string Composite_Utils_Predicates_IntegerLessThan_param_Value_help=>T("Composite.Utils.Predicates.IntegerLessThan.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_IntegerLessThan_param_Value_label=>T("Composite.Utils.Predicates.IntegerLessThan.param.Value.label"); ///"Check if a string contains a certain value" public static string Composite_Utils_Predicates_StringContains_description=>T("Composite.Utils.Predicates.StringContains.description"); ///"" public static string Composite_Utils_Predicates_StringContains_param_Value_help=>T("Composite.Utils.Predicates.StringContains.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_StringContains_param_Value_label=>T("Composite.Utils.Predicates.StringContains.param.Value.label"); ///"Check if a string ends with a certain value" public static string Composite_Utils_Predicates_StringEndsWith_description=>T("Composite.Utils.Predicates.StringEndsWith.description"); ///"" public static string Composite_Utils_Predicates_StringEndsWith_param_Value_help=>T("Composite.Utils.Predicates.StringEndsWith.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_StringEndsWith_param_Value_label=>T("Composite.Utils.Predicates.StringEndsWith.param.Value.label"); ///"Check if a string equals a certain value" public static string Composite_Utils_Predicates_StringEquals_description=>T("Composite.Utils.Predicates.StringEquals.description"); ///"" public static string Composite_Utils_Predicates_StringEquals_param_Value_help=>T("Composite.Utils.Predicates.StringEquals.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_StringEquals_param_Value_label=>T("Composite.Utils.Predicates.StringEquals.param.Value.label"); ///"Check if a string starts with a certain value" public static string Composite_Utils_Predicates_StringStartsWith_description=>T("Composite.Utils.Predicates.StringStartsWith.description"); ///"" public static string Composite_Utils_Predicates_StringStartsWith_param_Value_help=>T("Composite.Utils.Predicates.StringStartsWith.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_StringStartsWith_param_Value_label=>T("Composite.Utils.Predicates.StringStartsWith.param.Value.label"); ///"Check if a Guid equals a certain value" public static string Composite_Utils_Predicates_NullableGuidEquals_description=>T("Composite.Utils.Predicates.NullableGuidEquals.description"); ///"" public static string Composite_Utils_Predicates_NullableGuidEquals_param_Value_help=>T("Composite.Utils.Predicates.NullableGuidEquals.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_NullableGuidEquals_param_Value_label=>T("Composite.Utils.Predicates.NullableGuidEquals.param.Value.label"); ///"Check if a nullable Guid has no value" public static string Composite_Utils_Predicates_NullableGuidNoValue_description=>T("Composite.Utils.Predicates.NullableGuidNoValue.description"); ///"Check if an integer equals a certain value" public static string Composite_Utils_Predicates_NullableIntegerEquals_description=>T("Composite.Utils.Predicates.NullableIntegerEquals.description"); ///"" public static string Composite_Utils_Predicates_NullableIntegerEquals_param_Value_help=>T("Composite.Utils.Predicates.NullableIntegerEquals.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_NullableIntegerEquals_param_Value_label=>T("Composite.Utils.Predicates.NullableIntegerEquals.param.Value.label"); ///"Check if an nullable integer has no value" public static string Composite_Utils_Predicates_NullableIntegerNoValue_description=>T("Composite.Utils.Predicates.NullableIntegerNoValue.description"); ///"Check if a string has no value" public static string Composite_Utils_Predicates_StringNoValue_description=>T("Composite.Utils.Predicates.StringNoValue.description"); ///"Check if a boolean is true or false. " public static string Composite_Utils_Predicates_NullableBoolEquals_description=>T("Composite.Utils.Predicates.NullableBoolEquals.description"); ///"" public static string Composite_Utils_Predicates_NullableBoolEquals_param_Value_help=>T("Composite.Utils.Predicates.NullableBoolEquals.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_NullableBoolEquals_param_Value_label=>T("Composite.Utils.Predicates.NullableBoolEquals.param.Value.label"); ///"Check if a nullable boolean has no value" public static string Composite_Utils_Predicates_NullableBoolNoValue_description=>T("Composite.Utils.Predicates.NullableBoolNoValue.description"); ///"Check if a date equals a certain value" public static string Composite_Utils_Predicates_NullableDateTimeEquals_description=>T("Composite.Utils.Predicates.NullableDateTimeEquals.description"); ///"" public static string Composite_Utils_Predicates_NullableDateTimeEquals_param_Value_help=>T("Composite.Utils.Predicates.NullableDateTimeEquals.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_NullableDateTimeEquals_param_Value_label=>T("Composite.Utils.Predicates.NullableDateTimeEquals.param.Value.label"); ///"Check if a date is greater than a certain value" public static string Composite_Utils_Predicates_NullableDateTimeGreaterThan_description=>T("Composite.Utils.Predicates.NullableDateTimeGreaterThan.description"); ///"" public static string Composite_Utils_Predicates_NullableDateTimeGreaterThan_param_Value_help=>T("Composite.Utils.Predicates.NullableDateTimeGreaterThan.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_NullableDateTimeGreaterThan_param_Value_label=>T("Composite.Utils.Predicates.NullableDateTimeGreaterThan.param.Value.label"); ///"Check if a date is less than a certain value" public static string Composite_Utils_Predicates_NullableDateTimeLessThan_description=>T("Composite.Utils.Predicates.NullableDateTimeLessThan.description"); ///"" public static string Composite_Utils_Predicates_NullableDateTimeLessThan_param_Value_help=>T("Composite.Utils.Predicates.NullableDateTimeLessThan.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_NullableDateTimeLessThan_param_Value_label=>T("Composite.Utils.Predicates.NullableDateTimeLessThan.param.Value.label"); ///"Check if a nullable date has no value" public static string Composite_Utils_Predicates_NullableDateTimeNoValue_description=>T("Composite.Utils.Predicates.NullableDateTimeNoValue.description"); ///"Check is a decimal has a certain value" public static string Composite_Utils_Predicates_NullableDecimalEquals_description=>T("Composite.Utils.Predicates.NullableDecimalEquals.description"); ///"" public static string Composite_Utils_Predicates_NullableDecimalEquals_param_Value_help=>T("Composite.Utils.Predicates.NullableDecimalEquals.param.Value.help"); ///"The value to compare with" public static string Composite_Utils_Predicates_NullableDecimalEquals_param_Value_label=>T("Composite.Utils.Predicates.NullableDecimalEquals.param.Value.label"); ///"Check is a nullable decimal has no value" public static string Composite_Utils_Predicates_NullableDecimalNoValue_description=>T("Composite.Utils.Predicates.NullableDecimalNoValue.description"); ///"Joins a list of strings to a single string" public static string Composite_Utils_String_Join_description=>T("Composite.Utils.String.Join.description"); ///"The separator to insert between strings." public static string Composite_Utils_String_Join_param_Separator_help=>T("Composite.Utils.String.Join.param.Separator.help"); ///"Separator" public static string Composite_Utils_String_Join_param_Separator_label=>T("Composite.Utils.String.Join.param.Separator.label"); ///"The list of strings to join" public static string Composite_Utils_String_Join_param_Strings_help=>T("Composite.Utils.String.Join.param.Strings.help"); ///"Strings to join" public static string Composite_Utils_String_Join_param_Strings_label=>T("Composite.Utils.String.Join.param.Strings.label"); ///"Joins two strings to a simple string" public static string Composite_Utils_String_JoinTwo_description=>T("Composite.Utils.String.JoinTwo.description"); ///"The string to put first" public static string Composite_Utils_String_JoinTwo_param_StringA_help=>T("Composite.Utils.String.JoinTwo.param.StringA.help"); ///"String A" public static string Composite_Utils_String_JoinTwo_param_StringA_label=>T("Composite.Utils.String.JoinTwo.param.StringA.label"); ///"The string to put last" public static string Composite_Utils_String_JoinTwo_param_StringB_help=>T("Composite.Utils.String.JoinTwo.param.StringB.help"); ///"String B" public static string Composite_Utils_String_JoinTwo_param_StringB_label=>T("Composite.Utils.String.JoinTwo.param.StringB.label"); ///"A string to insert in between String A and String B. Default is no separator" public static string Composite_Utils_String_JoinTwo_param_Separator_help=>T("Composite.Utils.String.JoinTwo.param.Separator.help"); ///"Separator" public static string Composite_Utils_String_JoinTwo_param_Separator_label=>T("Composite.Utils.String.JoinTwo.param.Separator.label"); ///"Splits a string into a list of string." public static string Composite_Utils_String_Split_description=>T("Composite.Utils.String.Split.description"); ///"The separator to use when splitting the string. Default is comma (",")" public static string Composite_Utils_String_Split_param_Separator_help=>T("Composite.Utils.String.Split.param.Separator.help"); ///"Separator" public static string Composite_Utils_String_Split_param_Separator_label=>T("Composite.Utils.String.Split.param.Separator.label"); ///"The string you wish to split into a list." public static string Composite_Utils_String_Split_param_String_help=>T("Composite.Utils.String.Split.param.String.help"); ///"String to split" public static string Composite_Utils_String_Split_param_String_label=>T("Composite.Utils.String.Split.param.String.label"); ///"" public static string Composite_Utils_Validation_DateTimeNotNullValidation_description=>T("Composite.Utils.Validation.DateTimeNotNullValidation.description"); ///"" public static string Composite_Utils_Validation_DecimalNotNullValidation_description=>T("Composite.Utils.Validation.DecimalNotNullValidation.description"); ///"Validates the precision of digits (the number of decimals the user has specified)" public static string Composite_Utils_Validation_DecimalPrecisionValidation_description=>T("Composite.Utils.Validation.DecimalPrecisionValidation.description"); ///"The maximum number of digits to allow on the decimal" public static string Composite_Utils_Validation_DecimalPrecisionValidation_param_MaxDigits_help=>T("Composite.Utils.Validation.DecimalPrecisionValidation.param.MaxDigits.help"); ///"Max number of decimal digits" public static string Composite_Utils_Validation_DecimalPrecisionValidation_param_MaxDigits_label=>T("Composite.Utils.Validation.DecimalPrecisionValidation.param.MaxDigits.label"); ///"" public static string Composite_Utils_Validation_GuidNotNullValidation_description=>T("Composite.Utils.Validation.GuidNotNullValidation.description"); ///"" public static string Composite_Utils_Validation_Int32NotNullValidation_description=>T("Composite.Utils.Validation.Int32NotNullValidation.description"); ///"Validates than an integer is within a certain range." public static string Composite_Utils_Validation_IntegerRangeValidation_description=>T("Composite.Utils.Validation.IntegerRangeValidation.description"); ///"The maximum number allowed in this field." public static string Composite_Utils_Validation_IntegerRangeValidation_param_max_help=>T("Composite.Utils.Validation.IntegerRangeValidation.param.max.help"); ///"Maximum number" public static string Composite_Utils_Validation_IntegerRangeValidation_param_max_label=>T("Composite.Utils.Validation.IntegerRangeValidation.param.max.label"); ///"The minimum number allowed in this field." public static string Composite_Utils_Validation_IntegerRangeValidation_param_min_help=>T("Composite.Utils.Validation.IntegerRangeValidation.param.min.help"); ///"Minimum number" public static string Composite_Utils_Validation_IntegerRangeValidation_param_min_label=>T("Composite.Utils.Validation.IntegerRangeValidation.param.min.label"); ///"Validates that a string conforms to the specified regular expression" public static string Composite_Utils_Validation_RegularExpressionValidation_description=>T("Composite.Utils.Validation.RegularExpressionValidation.description"); ///"The regular expression pattern to use" public static string Composite_Utils_Validation_RegularExpressionValidation_param_pattern_help=>T("Composite.Utils.Validation.RegularExpressionValidation.param.pattern.help"); ///"RegEx pattern" public static string Composite_Utils_Validation_RegularExpressionValidation_param_pattern_label=>T("Composite.Utils.Validation.RegularExpressionValidation.param.pattern.label"); ///"Validates that the length of a string is within the specified range" public static string Composite_Utils_Validation_StringLengthValidation_description=>T("Composite.Utils.Validation.StringLengthValidation.description"); ///"" public static string Composite_Utils_Validation_StringLengthValidation_param_max_help=>T("Composite.Utils.Validation.StringLengthValidation.param.max.help"); ///"Maximum length" public static string Composite_Utils_Validation_StringLengthValidation_param_max_label=>T("Composite.Utils.Validation.StringLengthValidation.param.max.label"); ///"" public static string Composite_Utils_Validation_StringLengthValidation_param_min_help=>T("Composite.Utils.Validation.StringLengthValidation.param.min.help"); ///"Minimum length" public static string Composite_Utils_Validation_StringLengthValidation_param_min_label=>T("Composite.Utils.Validation.StringLengthValidation.param.min.label"); ///"" public static string Composite_Utils_Validation_StringNotNullValidation_description=>T("Composite.Utils.Validation.StringNotNullValidation.description"); ///"" public static string Composite_Web_Client_BrowserPlatform_description=>T("Composite.Web.Client.BrowserPlatform.description"); ///"" public static string Composite_Web_Client_BrowserString_description=>T("Composite.Web.Client.BrowserString.description"); ///"" public static string Composite_Web_Client_BrowserType_description=>T("Composite.Web.Client.BrowserType.description"); ///"" public static string Composite_Web_Client_BrowserVersion_description=>T("Composite.Web.Client.BrowserVersion.description"); ///"" public static string Composite_Web_Client_EcmaScriptVersion_description=>T("Composite.Web.Client.EcmaScriptVersion.description"); ///"True if the current request is identified as coming from a crawler (search engine)." public static string Composite_Web_Client_IsCrawler_description=>T("Composite.Web.Client.IsCrawler.description"); ///"True if the current request is identified as coming from a mobile device." public static string Composite_Web_Client_IsMobileDevice_description=>T("Composite.Web.Client.IsMobileDevice.description"); ///"Common HTML meta tags you probably want in your html head" public static string Composite_Web_Html_Template_CommonMetaTags_description=>T("Composite.Web.Html.Template.CommonMetaTags.description"); ///"Content-Type" public static string Composite_Web_Html_Template_CommonMetaTags_param_ContentType_label=>T("Composite.Web.Html.Template.CommonMetaTags.param.ContentType.label"); ///"By default this is 'text/html; charset=utf-8'. If you serve something else you should overwrite this." public static string Composite_Web_Html_Template_CommonMetaTags_param_ContentType_help=>T("Composite.Web.Html.Template.CommonMetaTags.param.ContentType.help"); ///"Designer" public static string Composite_Web_Html_Template_CommonMetaTags_param_Designer_label=>T("Composite.Web.Html.Template.CommonMetaTags.param.Designer.label"); ///"Who designed this website? Show it in the 'Designer' meta tag. Default is not to emit the meta tag." public static string Composite_Web_Html_Template_CommonMetaTags_param_Designer_help=>T("Composite.Web.Html.Template.CommonMetaTags.param.Designer.help"); ///"Show generator" public static string Composite_Web_Html_Template_CommonMetaTags_param_ShowGenerator_label=>T("Composite.Web.Html.Template.CommonMetaTags.param.ShowGenerator.label"); ///"Show the world you support C1 CMS Foundation - free open source!" public static string Composite_Web_Html_Template_CommonMetaTags_param_ShowGenerator_help=>T("Composite.Web.Html.Template.CommonMetaTags.param.ShowGenerator.help"); ///"Appends a lang='(language code)' attribute the the parent element, reflecting the language of the current page. You can put this just below the <html /> tag." public static string Composite_Web_Html_Template_LangAttribute_description=>T("Composite.Web.Html.Template.LangAttribute.description"); ///"Includes a named Page Template Feature at this location. Page Template Features can contain HTML and functional snippets and are managed on the Layout perspective." public static string Composite_Web_Html_Template_PageTemplateFeature_description=>T("Composite.Web.Html.Template.PageTemplateFeature.description"); ///"Feature name" public static string Composite_Web_Html_Template_PageTemplateFeature_param_FeatureName_label=>T("Composite.Web.Html.Template.PageTemplateFeature.param.FeatureName.label"); ///"The name of the Page Template Feature you wish to include." public static string Composite_Web_Html_Template_PageTemplateFeature_param_FeatureName_help=>T("Composite.Web.Html.Template.PageTemplateFeature.param.FeatureName.help"); ///"Emits the 'definitive title' of the current page; the same value that ends up in the page title tag. This title may originate from the page being rendered or from a C1 Function/ASP.NET control which changed the title to match specific data being featured on the page." public static string Composite_Web_Html_Template_HtmlTitleValue_description=>T("Composite.Web.Html.Template.HtmlTitleValue.description"); ///"Prefix to be removed" public static string Composite_Web_Html_Template_HtmlTitleValue_param_PrefixToRemove_label=>T("Composite.Web.Html.Template.HtmlTitleValue.param.PrefixToRemove.label"); ///"If the HTML title has a prefix value you wish to get rid of, specify the prefix here. If the prefix is not found in the title, this value is ignored." public static string Composite_Web_Html_Template_HtmlTitleValue_param_PrefixToRemove_help=>T("Composite.Web.Html.Template.HtmlTitleValue.param.PrefixToRemove.help"); ///"Postfix to be removed" public static string Composite_Web_Html_Template_HtmlTitleValue_param_PostfixToRemove_label=>T("Composite.Web.Html.Template.HtmlTitleValue.param.PostfixToRemove.label"); ///"If the HTML title has a postfix value you wish to get rid of, specify the postfix here. If the postfix is not found in the title, this value is ignored." public static string Composite_Web_Html_Template_HtmlTitleValue_param_PostfixToRemove_help=>T("Composite.Web.Html.Template.HtmlTitleValue.param.PostfixToRemove.help"); ///"Emits the 'definitive description' of the current page; the same value that ends up in the page meta description tag. This value may originate from the page being rendered or from a C1 Function/ASP.NET control which changed the description to match specific data being featured on the page." public static string Composite_Web_Html_Template_MetaDescriptionValue_description=>T("Composite.Web.Html.Template.MetaDescriptionValue.description"); ///"Element to wrap description" public static string Composite_Web_Html_Template_MetaDescriptionValue_param_Element_label=>T("Composite.Web.Html.Template.MetaDescriptionValue.param.Element.label"); ///"To have the description wrapped in an element (like <p class="description" />) specify it here. The element with only be emitted when a description text exist." public static string Composite_Web_Html_Template_MetaDescriptionValue_param_Element_help=>T("Composite.Web.Html.Template.MetaDescriptionValue.param.Element.help"); ///"Gets a value from the current users cookie collection." public static string Composite_Web_Request_CookieValue_description=>T("Composite.Web.Request.CookieValue.description"); ///"" public static string Composite_Web_Request_CookieValue_param_CookieName_help=>T("Composite.Web.Request.CookieValue.param.CookieName.help"); ///"Cookie name" public static string Composite_Web_Request_CookieValue_param_CookieName_label=>T("Composite.Web.Request.CookieValue.param.CookieName.label"); ///"If the user does not have this cookie, use this field to specify what value to default to." public static string Composite_Web_Request_CookieValue_param_FallbackValue_help=>T("Composite.Web.Request.CookieValue.param.FallbackValue.help"); ///"Fallback value" public static string Composite_Web_Request_CookieValue_param_FallbackValue_label=>T("Composite.Web.Request.CookieValue.param.FallbackValue.label"); ///"Gets a boolean value from a form post (HTTP POST)" public static string Composite_Web_Request_FormPostBoolValue_description=>T("Composite.Web.Request.FormPostBoolValue.description"); ///"" public static string Composite_Web_Request_FormPostBoolValue_param_FallbackValue_help=>T("Composite.Web.Request.FormPostBoolValue.param.FallbackValue.help"); ///"Fallback value" public static string Composite_Web_Request_FormPostBoolValue_param_FallbackValue_label=>T("Composite.Web.Request.FormPostBoolValue.param.FallbackValue.label"); ///"" public static string Composite_Web_Request_FormPostBoolValue_param_ParameterName_help=>T("Composite.Web.Request.FormPostBoolValue.param.ParameterName.help"); ///"Parameter name" public static string Composite_Web_Request_FormPostBoolValue_param_ParameterName_label=>T("Composite.Web.Request.FormPostBoolValue.param.ParameterName.label"); ///"Gets a decimal value from a form post (HTTP POST)" public static string Composite_Web_Request_FormPostDecimalValue_description=>T("Composite.Web.Request.FormPostDecimalValue.description"); ///"" public static string Composite_Web_Request_FormPostDecimalValue_param_FallbackValue_help=>T("Composite.Web.Request.FormPostDecimalValue.param.FallbackValue.help"); ///"Fallback value" public static string Composite_Web_Request_FormPostDecimalValue_param_FallbackValue_label=>T("Composite.Web.Request.FormPostDecimalValue.param.FallbackValue.label"); ///"" public static string Composite_Web_Request_FormPostDecimalValue_param_ParameterName_help=>T("Composite.Web.Request.FormPostDecimalValue.param.ParameterName.help"); ///"Parameter name" public static string Composite_Web_Request_FormPostDecimalValue_param_ParameterName_label=>T("Composite.Web.Request.FormPostDecimalValue.param.ParameterName.label"); ///"Gets a Guid value from a form post (HTTP POST)" public static string Composite_Web_Request_FormPostGuidValue_description=>T("Composite.Web.Request.FormPostGuidValue.description"); ///"" public static string Composite_Web_Request_FormPostGuidValue_param_FallbackValue_help=>T("Composite.Web.Request.FormPostGuidValue.param.FallbackValue.help"); ///"Fallback value" public static string Composite_Web_Request_FormPostGuidValue_param_FallbackValue_label=>T("Composite.Web.Request.FormPostGuidValue.param.FallbackValue.label"); ///"" public static string Composite_Web_Request_FormPostGuidValue_param_ParameterName_help=>T("Composite.Web.Request.FormPostGuidValue.param.ParameterName.help"); ///"Parameter name" public static string Composite_Web_Request_FormPostGuidValue_param_ParameterName_label=>T("Composite.Web.Request.FormPostGuidValue.param.ParameterName.label"); ///"Gets an integer value from a form post (HTTP POST)" public static string Composite_Web_Request_FormPostIntegerValue_description=>T("Composite.Web.Request.FormPostIntegerValue.description"); ///"" public static string Composite_Web_Request_FormPostIntegerValue_param_FallbackValue_help=>T("Composite.Web.Request.FormPostIntegerValue.param.FallbackValue.help"); ///"Fallback value" public static string Composite_Web_Request_FormPostIntegerValue_param_FallbackValue_label=>T("Composite.Web.Request.FormPostIntegerValue.param.FallbackValue.label"); ///"" public static string Composite_Web_Request_FormPostIntegerValue_param_ParameterName_help=>T("Composite.Web.Request.FormPostIntegerValue.param.ParameterName.help"); ///"Parameter name" public static string Composite_Web_Request_FormPostIntegerValue_param_ParameterName_label=>T("Composite.Web.Request.FormPostIntegerValue.param.ParameterName.label"); ///"Gets a string value from a form post (HTTP POST)" public static string Composite_Web_Request_FormPostValue_description=>T("Composite.Web.Request.FormPostValue.description"); ///"" public static string Composite_Web_Request_FormPostValue_param_FallbackValue_help=>T("Composite.Web.Request.FormPostValue.param.FallbackValue.help"); ///"Fallback value" public static string Composite_Web_Request_FormPostValue_param_FallbackValue_label=>T("Composite.Web.Request.FormPostValue.param.FallbackValue.label"); ///"" public static string Composite_Web_Request_FormPostValue_param_ParameterName_help=>T("Composite.Web.Request.FormPostValue.param.ParameterName.help"); ///"Parameter name" public static string Composite_Web_Request_FormPostValue_param_ParameterName_label=>T("Composite.Web.Request.FormPostValue.param.ParameterName.label"); ///"Gets a date and time value from a form post (HTTP POST). The incoming date string is expected to be XML formatted (like “2003-09-26T13:30:00”)" public static string Composite_Web_Request_FormPostXmlFormattedDateTimeValue_description=>T("Composite.Web.Request.FormPostXmlFormattedDateTimeValue.description"); ///"The value to use if the post did not contain the specified parameter name." public static string Composite_Web_Request_FormPostXmlFormattedDateTimeValue_param_FallbackValue_help=>T("Composite.Web.Request.FormPostXmlFormattedDateTimeValue.param.FallbackValue.help"); ///"Fallback value" public static string Composite_Web_Request_FormPostXmlFormattedDateTimeValue_param_FallbackValue_label=>T("Composite.Web.Request.FormPostXmlFormattedDateTimeValue.param.FallbackValue.label"); ///"" public static string Composite_Web_Request_FormPostXmlFormattedDateTimeValue_param_ParameterName_help=>T("Composite.Web.Request.FormPostXmlFormattedDateTimeValue.param.ParameterName.help"); ///"Parameter name" public static string Composite_Web_Request_FormPostXmlFormattedDateTimeValue_param_ParameterName_label=>T("Composite.Web.Request.FormPostXmlFormattedDateTimeValue.param.ParameterName.label"); ///"Gets a boolean value from a Url parameter (HTTP GET)" public static string Composite_Web_Request_QueryStringBoolValue_description=>T("Composite.Web.Request.QueryStringBoolValue.description"); ///"" public static string Composite_Web_Request_QueryStringBoolValue_param_FallbackValue_help=>T("Composite.Web.Request.QueryStringBoolValue.param.FallbackValue.help"); ///"Fallback value" public static string Composite_Web_Request_QueryStringBoolValue_param_FallbackValue_label=>T("Composite.Web.Request.QueryStringBoolValue.param.FallbackValue.label"); ///"" public static string Composite_Web_Request_QueryStringBoolValue_param_ParameterName_help=>T("Composite.Web.Request.QueryStringBoolValue.param.ParameterName.help"); ///"Parameter name" public static string Composite_Web_Request_QueryStringBoolValue_param_ParameterName_label=>T("Composite.Web.Request.QueryStringBoolValue.param.ParameterName.label"); ///"Gets a decimal value from a Url parameter (HTTP GET)" public static string Composite_Web_Request_QueryStringDecimalValue_description=>T("Composite.Web.Request.QueryStringDecimalValue.description"); ///"" public static string Composite_Web_Request_QueryStringDecimalValue_param_FallbackValue_help=>T("Composite.Web.Request.QueryStringDecimalValue.param.FallbackValue.help"); ///"Fallback value" public static string Composite_Web_Request_QueryStringDecimalValue_param_FallbackValue_label=>T("Composite.Web.Request.QueryStringDecimalValue.param.FallbackValue.label"); ///"" public static string Composite_Web_Request_QueryStringDecimalValue_param_ParameterName_help=>T("Composite.Web.Request.QueryStringDecimalValue.param.ParameterName.help"); ///"Parameter name" public static string Composite_Web_Request_QueryStringDecimalValue_param_ParameterName_label=>T("Composite.Web.Request.QueryStringDecimalValue.param.ParameterName.label"); ///"Gets a Guid value from a Url parameter (HTTP GET)" public static string Composite_Web_Request_QueryStringGuidValue_description=>T("Composite.Web.Request.QueryStringGuidValue.description"); ///"" public static string Composite_Web_Request_QueryStringGuidValue_param_FallbackValue_help=>T("Composite.Web.Request.QueryStringGuidValue.param.FallbackValue.help"); ///"Fallback value" public static string Composite_Web_Request_QueryStringGuidValue_param_FallbackValue_label=>T("Composite.Web.Request.QueryStringGuidValue.param.FallbackValue.label"); ///"" public static string Composite_Web_Request_QueryStringGuidValue_param_ParameterName_help=>T("Composite.Web.Request.QueryStringGuidValue.param.ParameterName.help"); ///"Parameter name" public static string Composite_Web_Request_QueryStringGuidValue_param_ParameterName_label=>T("Composite.Web.Request.QueryStringGuidValue.param.ParameterName.label"); ///"Gets an integer value from a Url parameter (HTTP GET)" public static string Composite_Web_Request_QueryStringIntegerValue_description=>T("Composite.Web.Request.QueryStringIntegerValue.description"); ///"" public static string Composite_Web_Request_QueryStringIntegerValue_param_FallbackValue_help=>T("Composite.Web.Request.QueryStringIntegerValue.param.FallbackValue.help"); ///"Fallback value" public static string Composite_Web_Request_QueryStringIntegerValue_param_FallbackValue_label=>T("Composite.Web.Request.QueryStringIntegerValue.param.FallbackValue.label"); ///"" public static string Composite_Web_Request_QueryStringIntegerValue_param_ParameterName_help=>T("Composite.Web.Request.QueryStringIntegerValue.param.ParameterName.help"); ///"Parameter name" public static string Composite_Web_Request_QueryStringIntegerValue_param_ParameterName_label=>T("Composite.Web.Request.QueryStringIntegerValue.param.ParameterName.label"); ///"Gets a string value from a Url parameter (HTTP GET)" public static string Composite_Web_Request_QueryStringValue_description=>T("Composite.Web.Request.QueryStringValue.description"); ///"" public static string Composite_Web_Request_QueryStringValue_param_FallbackValue_help=>T("Composite.Web.Request.QueryStringValue.param.FallbackValue.help"); ///"Fallback value" public static string Composite_Web_Request_QueryStringValue_param_FallbackValue_label=>T("Composite.Web.Request.QueryStringValue.param.FallbackValue.label"); ///"" public static string Composite_Web_Request_QueryStringValue_param_ParameterName_help=>T("Composite.Web.Request.QueryStringValue.param.ParameterName.help"); ///"Parameter name" public static string Composite_Web_Request_QueryStringValue_param_ParameterName_label=>T("Composite.Web.Request.QueryStringValue.param.ParameterName.label"); ///"Gets a date and time value from a Url parameter (HTTP GET). The incoming date string is expected to be XML formatted (like “2003-09-26T13:30:00”)" public static string Composite_Web_Request_QueryStringXmlFormattedDateTimeValue_description=>T("Composite.Web.Request.QueryStringXmlFormattedDateTimeValue.description"); ///"The value to use if the Url did not contain the specified parameter name." public static string Composite_Web_Request_QueryStringXmlFormattedDateTimeValue_param_FallbackValue_help=>T("Composite.Web.Request.QueryStringXmlFormattedDateTimeValue.param.FallbackValue.help"); ///"Fallback value" public static string Composite_Web_Request_QueryStringXmlFormattedDateTimeValue_param_FallbackValue_label=>T("Composite.Web.Request.QueryStringXmlFormattedDateTimeValue.param.FallbackValue.label"); ///"" public static string Composite_Web_Request_QueryStringXmlFormattedDateTimeValue_param_ParameterName_help=>T("Composite.Web.Request.QueryStringXmlFormattedDateTimeValue.param.ParameterName.help"); ///"Parameter name" public static string Composite_Web_Request_QueryStringXmlFormattedDateTimeValue_param_ParameterName_label=>T("Composite.Web.Request.QueryStringXmlFormattedDateTimeValue.param.ParameterName.label"); ///"Returns additional information passed in a URL along with the page link." public static string Composite_Web_Request_PathInfo_description=>T("Composite.Web.Request.PathInfo.description"); ///"The segment of the path info to retrieve, using the format '/(0)/(1)/(2)/...'. Specify -1 to get the entire string." public static string Composite_Web_Request_PathInfo_param_Segment_help=>T("Composite.Web.Request.PathInfo.param.Segment.help"); ///"Segment" public static string Composite_Web_Request_PathInfo_param_Segment_label=>T("Composite.Web.Request.PathInfo.param.Segment.label"); ///"When true, any path info string will be accepted. Default is true." public static string Composite_Web_Request_PathInfo_param_AutoApprove_help=>T("Composite.Web.Request.PathInfo.param.AutoApprove.help"); ///"AutoApprove" public static string Composite_Web_Request_PathInfo_param_AutoApprove_label=>T("Composite.Web.Request.PathInfo.param.AutoApprove.label"); ///"" public static string Composite_Web_Request_PathInfo_param_FallbackValue_help=>T("Composite.Web.Request.PathInfo.param.FallbackValue.help"); ///"Fallback value" public static string Composite_Web_Request_PathInfo_param_FallbackValue_label=>T("Composite.Web.Request.PathInfo.param.FallbackValue.label"); ///"Extracts an integer value from a PathInfo segment." public static string Composite_Web_Request_PathInfoInt_description=>T("Composite.Web.Request.PathInfoInt.description"); ///"The segment of the path info to retrieve, using the format '/(0)/(1)/(2)/...'." public static string Composite_Web_Request_PathInfoInt_param_Segment_help=>T("Composite.Web.Request.PathInfoInt.param.Segment.help"); ///"Segment" public static string Composite_Web_Request_PathInfoInt_param_Segment_label=>T("Composite.Web.Request.PathInfoInt.param.Segment.label"); ///"When true, any path info string will be accepted. Default is true." public static string Composite_Web_Request_PathInfoInt_param_AutoApprove_help=>T("Composite.Web.Request.PathInfoInt.param.AutoApprove.help"); ///"AutoApprove" public static string Composite_Web_Request_PathInfoInt_param_AutoApprove_label=>T("Composite.Web.Request.PathInfoInt.param.AutoApprove.label"); ///"" public static string Composite_Web_Request_PathInfoInt_param_FallbackValue_help=>T("Composite.Web.Request.PathInfoInt.param.FallbackValue.help"); ///"Fallback value" public static string Composite_Web_Request_PathInfoInt_param_FallbackValue_label=>T("Composite.Web.Request.PathInfoInt.param.FallbackValue.label"); ///"Extracts a GUID from a PathInfo segment." public static string Composite_Web_Request_PathInfoGuid_description=>T("Composite.Web.Request.PathInfoGuid.description"); ///"The segment of the path info to retrieve, using the format '/(0)/(1)/(2)/...'. " public static string Composite_Web_Request_PathInfoGuid_param_Segment_help=>T("Composite.Web.Request.PathInfoGuid.param.Segment.help"); ///"Segment" public static string Composite_Web_Request_PathInfoGuid_param_Segment_label=>T("Composite.Web.Request.PathInfoGuid.param.Segment.label"); ///"When true, accept any path info string will be accepted. Default is true." public static string Composite_Web_Request_PathInfoGuid_param_AutoApprove_help=>T("Composite.Web.Request.PathInfoGuid.param.AutoApprove.help"); ///"AutoApprove" public static string Composite_Web_Request_PathInfoGuid_param_AutoApprove_label=>T("Composite.Web.Request.PathInfoGuid.param.AutoApprove.label"); ///"" public static string Composite_Web_Request_PathInfoGuid_param_FallbackValue_help=>T("Composite.Web.Request.PathInfoGuid.param.FallbackValue.help"); ///"Fallback value" public static string Composite_Web_Request_PathInfoGuid_param_FallbackValue_label=>T("Composite.Web.Request.PathInfoGuid.param.FallbackValue.label"); ///"Notifies the system of PathInfo being used, so that the request is not redirected to the 'Page not found' page." public static string Composite_Web_Request_RegisterPathInfoUsage_description=>T("Composite.Web.Request.RegisterPathInfoUsage.description"); ///"Retrieves a variable from the current users session as a string." public static string Composite_Web_Request_SessionVariable_description=>T("Composite.Web.Request.SessionVariable.description"); ///"The value to use if the session variable was not found" public static string Composite_Web_Request_SessionVariable_param_FallbackValue_help=>T("Composite.Web.Request.SessionVariable.param.FallbackValue.help"); ///"Fallback value" public static string Composite_Web_Request_SessionVariable_param_FallbackValue_label=>T("Composite.Web.Request.SessionVariable.param.FallbackValue.label"); ///"" public static string Composite_Web_Request_SessionVariable_param_VariableName_help=>T("Composite.Web.Request.SessionVariable.param.VariableName.help"); ///"Variable name" public static string Composite_Web_Request_SessionVariable_param_VariableName_label=>T("Composite.Web.Request.SessionVariable.param.VariableName.label"); ///"Redirects the website visitor to another URL. URL redirects are suppressed when this function executes inside the C1 console." public static string Composite_Web_Response_Redirect_description=>T("Composite.Web.Response.Redirect.description"); ///"The URL the user should be redirected to, either absolute (http://contoso.com/default.aspx) or relative (/Login.aspx))." public static string Composite_Web_Response_Redirect_param_Url_help=>T("Composite.Web.Response.Redirect.param.Url.help"); ///"URL" public static string Composite_Web_Response_Redirect_param_Url_label=>T("Composite.Web.Response.Redirect.param.Url.label"); ///"Sets a cookie value for the current user" public static string Composite_Web_Response_SetCookieValue_description=>T("Composite.Web.Response.SetCookieValue.description"); ///"The name of the cookie to set / overwrite" public static string Composite_Web_Response_SetCookieValue_param_CookieName_help=>T("Composite.Web.Response.SetCookieValue.param.CookieName.help"); ///"Cookie name" public static string Composite_Web_Response_SetCookieValue_param_CookieName_label=>T("Composite.Web.Response.SetCookieValue.param.CookieName.label"); ///"The value to store in the cookie" public static string Composite_Web_Response_SetCookieValue_param_Value_help=>T("Composite.Web.Response.SetCookieValue.param.Value.help"); ///"Cookie value" public static string Composite_Web_Response_SetCookieValue_param_Value_label=>T("Composite.Web.Response.SetCookieValue.param.Value.label"); ///"When the cookie should expire (stop to exist). The default value is 'session', when the user closes the browser." public static string Composite_Web_Response_SetCookieValue_param_Expires_help=>T("Composite.Web.Response.SetCookieValue.param.Expires.help"); ///"Expiration" public static string Composite_Web_Response_SetCookieValue_param_Expires_label=>T("Composite.Web.Response.SetCookieValue.param.Expires.label"); ///"Sets the maximum number of seconds the current page should be publicly cached on the server. To ensure that the page response is not cached set the "Maximum seconds" to "0". If multiple sources set the server cache duration, the smallest number is used. Note that the file "~/Renderers/Page.aspx" contains a default value for cache duration – you can edit this file to change the default." public static string Composite_Web_Response_SetServerPageCacheDuration_description=>T("Composite.Web.Response.SetServerPageCacheDuration.description"); ///"The maximum number of seconds the page currently being rendered should be publicly cached. A high value yield good performance, a low value make changes show up faster. A value of '0' ensure that all visitors get a unique response." public static string Composite_Web_Response_SetServerPageCacheDuration_param_MaxSeconds_help=>T("Composite.Web.Response.SetServerPageCacheDuration.param.MaxSeconds.help"); ///"Maximum seconds" public static string Composite_Web_Response_SetServerPageCacheDuration_param_MaxSeconds_label=>T("Composite.Web.Response.SetServerPageCacheDuration.param.MaxSeconds.label"); ///"Sets a session variable for the current user" public static string Composite_Web_Response_SetSessionVariable_description=>T("Composite.Web.Response.SetSessionVariable.description"); ///"" public static string Composite_Web_Response_SetSessionVariable_param_Value_help=>T("Composite.Web.Response.SetSessionVariable.param.Value.help"); ///"Value" public static string Composite_Web_Response_SetSessionVariable_param_Value_label=>T("Composite.Web.Response.SetSessionVariable.param.Value.label"); ///"The name of the session variable to set." public static string Composite_Web_Response_SetSessionVariable_param_VariableName_help=>T("Composite.Web.Response.SetSessionVariable.param.VariableName.help"); ///"Variable name" public static string Composite_Web_Response_SetSessionVariable_param_VariableName_label=>T("Composite.Web.Response.SetSessionVariable.param.VariableName.label"); ///"Gets the web application virtual path. Typically this is '' - the empty string, when running in the website root, but if {applicationname} is running in a sub folder this can be '/MySubfolder'. You can use this value to prefix URL's so they will work no matter is {applicationname} is running is a subfolder or not. Sample XSLT usage: <img src="{/in:inputs/in:result[@name='ApplicationPath']}/images/myImage.png" />" public static string Composite_Web_Server_ApplicationPath_description=>T("Composite.Web.Server.ApplicationPath.description"); ///"Gets an IIS application variable" public static string Composite_Web_Server_ApplicationVariable_description=>T("Composite.Web.Server.ApplicationVariable.description"); ///"Value to use if the application variable was not located" public static string Composite_Web_Server_ApplicationVariable_param_FallbackValue_help=>T("Composite.Web.Server.ApplicationVariable.param.FallbackValue.help"); ///"Fallback value" public static string Composite_Web_Server_ApplicationVariable_param_FallbackValue_label=>T("Composite.Web.Server.ApplicationVariable.param.FallbackValue.label"); ///"" public static string Composite_Web_Server_ApplicationVariable_param_VariableName_help=>T("Composite.Web.Server.ApplicationVariable.param.VariableName.help"); ///"Variable name" public static string Composite_Web_Server_ApplicationVariable_param_VariableName_label=>T("Composite.Web.Server.ApplicationVariable.param.VariableName.label"); ///"Gets the value of an IIS Server variable" public static string Composite_Web_Server_ServerVariable_description=>T("Composite.Web.Server.ServerVariable.description"); ///"The IIS Server variable to get." public static string Composite_Web_Server_ServerVariable_param_VariableName_help=>T("Composite.Web.Server.ServerVariable.param.VariableName.help"); ///"Variable name" public static string Composite_Web_Server_ServerVariable_param_VariableName_label=>T("Composite.Web.Server.ServerVariable.param.VariableName.label"); ///"Loads a local XML file given a relative path" public static string Composite_Xml_LoadFile_description=>T("Composite.Xml.LoadFile.description"); ///"The relative path of the XML file to load" public static string Composite_Xml_LoadFile_param_RelativePath_help=>T("Composite.Xml.LoadFile.param.RelativePath.help"); ///"Relative path" public static string Composite_Xml_LoadFile_param_RelativePath_label=>T("Composite.Xml.LoadFile.param.RelativePath.label"); ///"Loads a local XHTML file given a relative path" public static string Composite_Xml_LoadXhtmlFile_description=>T("Composite.Xml.LoadXhtmlFile.description"); ///"The relative path of the XHTML file to load" public static string Composite_Xml_LoadXhtmlFile_param_RelativePath_help=>T("Composite.Xml.LoadXhtmlFile.param.RelativePath.help"); ///"Relative path" public static string Composite_Xml_LoadXhtmlFile_param_RelativePath_label=>T("Composite.Xml.LoadXhtmlFile.param.RelativePath.label"); ///"Loads a remote XML file given a Url" public static string Composite_Xml_LoadUrl_description=>T("Composite.Xml.LoadUrl.description"); ///"" public static string Composite_Xml_LoadUrl_param_Url_help=>T("Composite.Xml.LoadUrl.param.Url.help"); ///"Url" public static string Composite_Xml_LoadUrl_param_Url_label=>T("Composite.Xml.LoadUrl.param.Url.label"); ///"Time period in seconds for which the result should is cached. Default is 0 (no caching)." public static string Composite_Xml_LoadUrl_param_CacheTime_help=>T("Composite.Xml.LoadUrl.param.CacheTime.help"); ///"Seconds to cache" public static string Composite_Xml_LoadUrl_param_CacheTime_label=>T("Composite.Xml.LoadUrl.param.CacheTime.label"); ///"Provides localized date formatting functions for XSLT use. " public static string Composite_Xslt_Extensions_DateFormatting_description=>T("Composite.Xslt.Extensions.DateFormatting.description"); ///"Provides globalization functions for XSLT use." public static string Composite_Xslt_Extensions_Globalization_description=>T("Composite.Xslt.Extensions.Globalization.description"); ///"Provides functions that parse encoded XML documents or XHTML fragments into nodes. Use this extension when you have XML or XHTML as a string and need to copy it to the output or do transformations on it." public static string Composite_Xslt_Extensions_MarkupParser_description=>T("Composite.Xslt.Extensions.MarkupParser.description"); ///"Sends an e-mail. Remember to configure SMTP server connection in the web.config file." public static string Composite_Mail_SendMail_description=>T("Composite.Mail.SendMail.description"); ///"From" public static string Composite_Mail_SendMail_param_From_label=>T("Composite.Mail.SendMail.param.From.label"); ///"Sender's address." public static string Composite_Mail_SendMail_param_From_help=>T("Composite.Mail.SendMail.param.From.help"); ///"To" public static string Composite_Mail_SendMail_param_To_label=>T("Composite.Mail.SendMail.param.To.label"); ///"Recipient. A list of comma separated email addresses." public static string Composite_Mail_SendMail_param_To_help=>T("Composite.Mail.SendMail.param.To.help"); ///"Subject" public static string Composite_Mail_SendMail_param_Subject_label=>T("Composite.Mail.SendMail.param.Subject.label"); ///"Email subject." public static string Composite_Mail_SendMail_param_Subject_help=>T("Composite.Mail.SendMail.param.Subject.help"); ///"Body" public static string Composite_Mail_SendMail_param_Body_label=>T("Composite.Mail.SendMail.param.Body.label"); ///"Email body." public static string Composite_Mail_SendMail_param_Body_help=>T("Composite.Mail.SendMail.param.Body.help"); ///"IsHtml" public static string Composite_Mail_SendMail_param_IsHtml_label=>T("Composite.Mail.SendMail.param.IsHtml.label"); ///"Defines whether email to be sent is an HTML email or a text email." public static string Composite_Mail_SendMail_param_IsHtml_help=>T("Composite.Mail.SendMail.param.IsHtml.help"); ///"CC" public static string Composite_Mail_SendMail_param_CC_label=>T("Composite.Mail.SendMail.param.CC.label"); ///"Carbon Copy. A list of comma separated email addresses that are secondary recipients of a message." public static string Composite_Mail_SendMail_param_CC_help=>T("Composite.Mail.SendMail.param.CC.help"); ///"ReplyTo" public static string Composite_Mail_SendMail_param_ReplyTo_label=>T("Composite.Mail.SendMail.param.ReplyTo.label"); ///"Address that should be used to reply to the message." public static string Composite_Mail_SendMail_param_ReplyTo_help=>T("Composite.Mail.SendMail.param.ReplyTo.help"); ///"BCC" public static string Composite_Mail_SendMail_param_BCC_label=>T("Composite.Mail.SendMail.param.BCC.label"); ///"Blind Carbon Copy. A list of recipients which will receive a mail but their individual email addresses will be concealed from the complete list of recipients." public static string Composite_Mail_SendMail_param_BCC_help=>T("Composite.Mail.SendMail.param.BCC.help"); ///"Attachment" public static string Composite_Mail_SendMail_param_Attachment_label=>T("Composite.Mail.SendMail.param.Attachment.label"); ///"List of attached files. \n Format it the following [{name}=]{filepath}[,{mime-type] [ | .... ]. \n File path can be either relative or absolute path f.e. "C:\someimage.jpg" or "/coolpicture.jpg" \n If file path starts with "Composite/", it will be recognized as a path to Composite media, f.e. 'Composite/MediaArchive:someImage.gif' \n \n Examples: \n /attachment.jpg \n image.jpg=/attachment.jpg \n image.jpg=/attachment.jpg,image/jpg \n image1.jpg=/attachment1.jpg,image/jpg|image2.jpg=/attachment2.jpg,image/jpg" public static string Composite_Mail_SendMail_param_Attachment_help=>T("Composite.Mail.SendMail.param.Attachment.help"); ///"AttachmentFromMedia" public static string Composite_Mail_SendMail_param_AttachmentFromMedia_label=>T("Composite.Mail.SendMail.param.AttachmentFromMedia.label"); ///"A file from media library to be attached." public static string Composite_Mail_SendMail_param_AttachmentFromMedia_help=>T("Composite.Mail.SendMail.param.AttachmentFromMedia.help"); ///"Filters images by it's folder path" public static string Composite_Data_Types_IImageFile_MediaFolderFilter_description=>T("Composite.Data.Types.IImageFile.MediaFolderFilter.description"); ///"Media Folder" public static string Composite_Data_Types_IImageFile_MediaFolderFilter_param_MediaFolder_label=>T("Composite.Data.Types.IImageFile.MediaFolderFilter.param.MediaFolder.label"); ///"A reference to a media folder" public static string Composite_Data_Types_IImageFile_MediaFolderFilter_param_MediaFolder_help=>T("Composite.Data.Types.IImageFile.MediaFolderFilter.param.MediaFolder.help"); ///"Include Subfolders" public static string Composite_Data_Types_IImageFile_MediaFolderFilter_param_IncludeSubfolders_label=>T("Composite.Data.Types.IImageFile.MediaFolderFilter.param.IncludeSubfolders.label"); ///"Determines whether images from subfolders should be included." public static string Composite_Data_Types_IImageFile_MediaFolderFilter_param_IncludeSubfolders_help=>T("Composite.Data.Types.IImageFile.MediaFolderFilter.param.IncludeSubfolders.help"); ///"Filters images by it's folder path" public static string Composite_Data_Types_IMediaFile_MediaFolderFilter_description=>T("Composite.Data.Types.IMediaFile.MediaFolderFilter.description"); ///"Media Folder" public static string Composite_Data_Types_IMediaFile_MediaFolderFilter_param_MediaFolder_label=>T("Composite.Data.Types.IMediaFile.MediaFolderFilter.param.MediaFolder.label"); ///"A reference to a media folder" public static string Composite_Data_Types_IMediaFile_MediaFolderFilter_param_MediaFolder_help=>T("Composite.Data.Types.IMediaFile.MediaFolderFilter.param.MediaFolder.help"); ///"Include Subfolders" public static string Composite_Data_Types_IMediaFile_MediaFolderFilter_param_IncludeSubfolders_label=>T("Composite.Data.Types.IMediaFile.MediaFolderFilter.param.IncludeSubfolders.label"); ///"Determines whether media files from subfolders should be included." public static string Composite_Data_Types_IMediaFile_MediaFolderFilter_param_IncludeSubfolders_help=>T("Composite.Data.Types.IMediaFile.MediaFolderFilter.param.IncludeSubfolders.help"); ///"Converts an enumerable of XElements to a Dictionary using named attributes for keys and values." public static string Composite_Utils_Dictionary_XElementsToDictionary_description=>T("Composite.Utils.Dictionary.XElementsToDictionary.description"); ///"XElements" public static string Composite_Utils_Dictionary_XElementsToDictionary_param_XElements_label=>T("Composite.Utils.Dictionary.XElementsToDictionary.param.XElements.label"); ///"An enumerable of XElements that will be used to create a dictionary from." public static string Composite_Utils_Dictionary_XElementsToDictionary_param_XElements_help=>T("Composite.Utils.Dictionary.XElementsToDictionary.param.XElements.help"); ///"Key Attribute Name" public static string Composite_Utils_Dictionary_XElementsToDictionary_param_KeyAttributeName_label=>T("Composite.Utils.Dictionary.XElementsToDictionary.param.KeyAttributeName.label"); ///"The name of the attribute on each XElement which value will be used for keys in the dictionary." public static string Composite_Utils_Dictionary_XElementsToDictionary_param_KeyAttributeName_help=>T("Composite.Utils.Dictionary.XElementsToDictionary.param.KeyAttributeName.help"); ///"Value Attribute Name" public static string Composite_Utils_Dictionary_XElementsToDictionary_param_ValueAttributeName_label=>T("Composite.Utils.Dictionary.XElementsToDictionary.param.ValueAttributeName.label"); ///"The name of the attribute on each XElement which value will be used for values in the dictionary." public static string Composite_Utils_Dictionary_XElementsToDictionary_param_ValueAttributeName_help=>T("Composite.Utils.Dictionary.XElementsToDictionary.param.ValueAttributeName.help"); ///"Converts an enumerable of objects to a Dictionary using named property names for keys and values." public static string Composite_Utils_Dictionary_EnumerableToDictionary_description=>T("Composite.Utils.Dictionary.EnumerableToDictionary.description"); ///"Objects" public static string Composite_Utils_Dictionary_EnumerableToDictionary_param_Elements_label=>T("Composite.Utils.Dictionary.EnumerableToDictionary.param.Elements.label"); ///"An enumerable of objects that will be used to create a dictionary from." public static string Composite_Utils_Dictionary_EnumerableToDictionary_param_Elements_help=>T("Composite.Utils.Dictionary.EnumerableToDictionary.param.Elements.help"); ///"Key Property Name" public static string Composite_Utils_Dictionary_EnumerableToDictionary_param_KeyPropertyName_label=>T("Composite.Utils.Dictionary.EnumerableToDictionary.param.KeyPropertyName.label"); ///"The name of the property on each object which value will be used for keys in the dictionary." public static string Composite_Utils_Dictionary_EnumerableToDictionary_param_KeyPropertyName_help=>T("Composite.Utils.Dictionary.EnumerableToDictionary.param.KeyPropertyName.help"); ///"Value Property Name" public static string Composite_Utils_Dictionary_EnumerableToDictionary_param_ValuePropertyName_label=>T("Composite.Utils.Dictionary.EnumerableToDictionary.param.ValuePropertyName.label"); ///"The name of the property on each object which value will be used for values in the dictionary." public static string Composite_Utils_Dictionary_EnumerableToDictionary_param_ValuePropertyName_help=>T("Composite.Utils.Dictionary.EnumerableToDictionary.param.ValuePropertyName.help"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.StandardFunctions", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_TimezoneAbbreviations { ///"Etc/GMT+12" public static string TimezoneAbbreviations_Dateline_Standard_Time=>T("TimezoneAbbreviations.Dateline Standard Time"); ///"Etc/GMT+11" public static string TimezoneAbbreviations_UTC_11=>T("TimezoneAbbreviations.UTC-11"); ///"UTC-10" public static string TimezoneAbbreviations_Aleutian_Standard_Time=>T("TimezoneAbbreviations.Aleutian Standard Time"); ///"HST" public static string TimezoneAbbreviations_Hawaiian_Standard_Time=>T("TimezoneAbbreviations.Hawaiian Standard Time"); ///"MART" public static string TimezoneAbbreviations_Marquesas_Standard_Time=>T("TimezoneAbbreviations.Marquesas Standard Time"); ///"AKST" public static string TimezoneAbbreviations_Alaskan_Standard_Time=>T("TimezoneAbbreviations.Alaskan Standard Time"); ///"UTC-09" public static string TimezoneAbbreviations_UTC_09=>T("TimezoneAbbreviations.UTC-09"); ///"PST" public static string TimezoneAbbreviations_Pacific_Standard_Time_Mexico=>T("TimezoneAbbreviations.Pacific Standard Time (Mexico)"); ///"UTC-08" public static string TimezoneAbbreviations_UTC_08=>T("TimezoneAbbreviations.UTC-08"); ///"PST" public static string TimezoneAbbreviations_Pacific_Standard_Time=>T("TimezoneAbbreviations.Pacific Standard Time"); ///"MST" public static string TimezoneAbbreviations_US_Mountain_Standard_Time=>T("TimezoneAbbreviations.US Mountain Standard Time"); ///"MST" public static string TimezoneAbbreviations_Mountain_Standard_Time_Mexico=>T("TimezoneAbbreviations.Mountain Standard Time (Mexico)"); ///"MST" public static string TimezoneAbbreviations_Mountain_Standard_Time=>T("TimezoneAbbreviations.Mountain Standard Time"); ///"CST" public static string TimezoneAbbreviations_Central_America_Standard_Time=>T("TimezoneAbbreviations.Central America Standard Time"); ///"CST" public static string TimezoneAbbreviations_Central_Standard_Time=>T("TimezoneAbbreviations.Central Standard Time"); ///"EASST" public static string TimezoneAbbreviations_Easter_Island_Standard_Time=>T("TimezoneAbbreviations.Easter Island Standard Time"); ///"CST" public static string TimezoneAbbreviations_Central_Standard_Time_Mexico=>T("TimezoneAbbreviations.Central Standard Time (Mexico)"); ///"CST" public static string TimezoneAbbreviations_Canada_Central_Standard_Time=>T("TimezoneAbbreviations.Canada Central Standard Time"); ///"SAPST" public static string TimezoneAbbreviations_SA_Pacific_Standard_Time=>T("TimezoneAbbreviations.SA Pacific Standard Time"); ///"EST" public static string TimezoneAbbreviations_Eastern_Standard_Time_Mexico=>T("TimezoneAbbreviations.Eastern Standard Time (Mexico)"); ///"EST" public static string TimezoneAbbreviations_Eastern_Standard_Time=>T("TimezoneAbbreviations.Eastern Standard Time"); ///"EST" public static string TimezoneAbbreviations_Haiti_Standard_Time=>T("TimezoneAbbreviations.Haiti Standard Time"); ///"UTC-05" public static string TimezoneAbbreviations_Cuba_Standard_Time=>T("TimezoneAbbreviations.Cuba Standard Time"); ///"EST" public static string TimezoneAbbreviations_US_Eastern_Standard_Time=>T("TimezoneAbbreviations.US Eastern Standard Time"); ///"VET" public static string TimezoneAbbreviations_Venezuela_Standard_Time=>T("TimezoneAbbreviations.Venezuela Standard Time"); ///"PYST" public static string TimezoneAbbreviations_Paraguay_Standard_Time=>T("TimezoneAbbreviations.Paraguay Standard Time"); ///"AST" public static string TimezoneAbbreviations_Atlantic_Standard_Time=>T("TimezoneAbbreviations.Atlantic Standard Time"); ///"AMST" public static string TimezoneAbbreviations_Central_Brazilian_Standard_Time=>T("TimezoneAbbreviations.Central Brazilian Standard Time"); ///"SAWST" public static string TimezoneAbbreviations_SA_Western_Standard_Time=>T("TimezoneAbbreviations.SA Western Standard Time"); ///"CLST" public static string TimezoneAbbreviations_Pacific_SA_Standard_Time=>T("TimezoneAbbreviations.Pacific SA Standard Time"); ///"UTC-04" public static string TimezoneAbbreviations_Turks_And_Caicos_Standard_Time=>T("TimezoneAbbreviations.Turks And Caicos Standard Time"); ///"NST" public static string TimezoneAbbreviations_Newfoundland_Standard_Time=>T("TimezoneAbbreviations.Newfoundland Standard Time"); ///"UTC-03" public static string TimezoneAbbreviations_Tocantins_Standard_Time=>T("TimezoneAbbreviations.Tocantins Standard Time"); ///"BRST" public static string TimezoneAbbreviations_E__South_America_Standard_Time=>T("TimezoneAbbreviations.E. South America Standard Time"); ///"GFT" public static string TimezoneAbbreviations_SA_Eastern_Standard_Time=>T("TimezoneAbbreviations.SA Eastern Standard Time"); ///"ART" public static string TimezoneAbbreviations_Argentina_Standard_Time=>T("TimezoneAbbreviations.Argentina Standard Time"); ///"WGT" public static string TimezoneAbbreviations_Greenland_Standard_Time=>T("TimezoneAbbreviations.Greenland Standard Time"); ///"UYT" public static string TimezoneAbbreviations_Montevideo_Standard_Time=>T("TimezoneAbbreviations.Montevideo Standard Time"); ///"UTC-03" public static string TimezoneAbbreviations_Saint_Pierre_Standard_Time=>T("TimezoneAbbreviations.Saint Pierre Standard Time"); ///"BRT" public static string TimezoneAbbreviations_Bahia_Standard_Time=>T("TimezoneAbbreviations.Bahia Standard Time"); ///"Etc/GMT+2" public static string TimezoneAbbreviations_UTC_02=>T("TimezoneAbbreviations.UTC-02"); ///"AST" public static string TimezoneAbbreviations_Mid_Atlantic_Standard_Time=>T("TimezoneAbbreviations.Mid-Atlantic Standard Time"); ///"AZOT" public static string TimezoneAbbreviations_Azores_Standard_Time=>T("TimezoneAbbreviations.Azores Standard Time"); ///"CVT" public static string TimezoneAbbreviations_Cape_Verde_Standard_Time=>T("TimezoneAbbreviations.Cape Verde Standard Time"); ///"WET" public static string TimezoneAbbreviations_Morocco_Standard_Time=>T("TimezoneAbbreviations.Morocco Standard Time"); ///"Etc/GMT" public static string TimezoneAbbreviations_UTC=>T("TimezoneAbbreviations.UTC"); ///"GMT" public static string TimezoneAbbreviations_GMT_Standard_Time=>T("TimezoneAbbreviations.GMT Standard Time"); ///"GMT" public static string TimezoneAbbreviations_Greenwich_Standard_Time=>T("TimezoneAbbreviations.Greenwich Standard Time"); ///"CET" public static string TimezoneAbbreviations_W__Europe_Standard_Time=>T("TimezoneAbbreviations.W. Europe Standard Time"); ///"CET" public static string TimezoneAbbreviations_Central_Europe_Standard_Time=>T("TimezoneAbbreviations.Central Europe Standard Time"); ///"CET" public static string TimezoneAbbreviations_Romance_Standard_Time=>T("TimezoneAbbreviations.Romance Standard Time"); ///"CET" public static string TimezoneAbbreviations_Central_European_Standard_Time=>T("TimezoneAbbreviations.Central European Standard Time"); ///"WAT" public static string TimezoneAbbreviations_W__Central_Africa_Standard_Time=>T("TimezoneAbbreviations.W. Central Africa Standard Time"); ///"WAST" public static string TimezoneAbbreviations_Namibia_Standard_Time=>T("TimezoneAbbreviations.Namibia Standard Time"); ///"EET" public static string TimezoneAbbreviations_Jordan_Standard_Time=>T("TimezoneAbbreviations.Jordan Standard Time"); ///"EET" public static string TimezoneAbbreviations_GTB_Standard_Time=>T("TimezoneAbbreviations.GTB Standard Time"); ///"EET" public static string TimezoneAbbreviations_Middle_East_Standard_Time=>T("TimezoneAbbreviations.Middle East Standard Time"); ///"EET" public static string TimezoneAbbreviations_Egypt_Standard_Time=>T("TimezoneAbbreviations.Egypt Standard Time"); ///"EET" public static string TimezoneAbbreviations_Syria_Standard_Time=>T("TimezoneAbbreviations.Syria Standard Time"); ///"EET" public static string TimezoneAbbreviations_E__Europe_Standard_Time=>T("TimezoneAbbreviations.E. Europe Standard Time"); ///"UTC+02" public static string TimezoneAbbreviations_West_Bank_Standard_Time=>T("TimezoneAbbreviations.West Bank Standard Time"); ///"SAST" public static string TimezoneAbbreviations_South_Africa_Standard_Time=>T("TimezoneAbbreviations.South Africa Standard Time"); ///"EET" public static string TimezoneAbbreviations_FLE_Standard_Time=>T("TimezoneAbbreviations.FLE Standard Time"); ///"EET" public static string TimezoneAbbreviations_Turkey_Standard_Time=>T("TimezoneAbbreviations.Turkey Standard Time"); ///"IST" public static string TimezoneAbbreviations_Israel_Standard_Time=>T("TimezoneAbbreviations.Israel Standard Time"); ///"EET" public static string TimezoneAbbreviations_Kaliningrad_Standard_Time=>T("TimezoneAbbreviations.Kaliningrad Standard Time"); ///"EET" public static string TimezoneAbbreviations_Libya_Standard_Time=>T("TimezoneAbbreviations.Libya Standard Time"); ///"AST" public static string TimezoneAbbreviations_Arabic_Standard_Time=>T("TimezoneAbbreviations.Arabic Standard Time"); ///"AST" public static string TimezoneAbbreviations_Arab_Standard_Time=>T("TimezoneAbbreviations.Arab Standard Time"); ///"MSK" public static string TimezoneAbbreviations_Belarus_Standard_Time=>T("TimezoneAbbreviations.Belarus Standard Time"); ///"MSK" public static string TimezoneAbbreviations_Russian_Standard_Time=>T("TimezoneAbbreviations.Russian Standard Time"); ///"EAT" public static string TimezoneAbbreviations_E__Africa_Standard_Time=>T("TimezoneAbbreviations.E. Africa Standard Time"); ///"MSK" public static string TimezoneAbbreviations_Astrakhan_Standard_Time=>T("TimezoneAbbreviations.Astrakhan Standard Time"); ///"IRST" public static string TimezoneAbbreviations_Iran_Standard_Time=>T("TimezoneAbbreviations.Iran Standard Time"); ///"GST" public static string TimezoneAbbreviations_Arabian_Standard_Time=>T("TimezoneAbbreviations.Arabian Standard Time"); ///"AZT" public static string TimezoneAbbreviations_Azerbaijan_Standard_Time=>T("TimezoneAbbreviations.Azerbaijan Standard Time"); ///"SAMT" public static string TimezoneAbbreviations_Russia_Time_Zone_3=>T("TimezoneAbbreviations.Russia Time Zone 3"); ///"MUT" public static string TimezoneAbbreviations_Mauritius_Standard_Time=>T("TimezoneAbbreviations.Mauritius Standard Time"); ///"GET" public static string TimezoneAbbreviations_Georgian_Standard_Time=>T("TimezoneAbbreviations.Georgian Standard Time"); ///"AMT" public static string TimezoneAbbreviations_Caucasus_Standard_Time=>T("TimezoneAbbreviations.Caucasus Standard Time"); ///"AFT" public static string TimezoneAbbreviations_Afghanistan_Standard_Time=>T("TimezoneAbbreviations.Afghanistan Standard Time"); ///"UZT" public static string TimezoneAbbreviations_West_Asia_Standard_Time=>T("TimezoneAbbreviations.West Asia Standard Time"); ///"YEKT" public static string TimezoneAbbreviations_Ekaterinburg_Standard_Time=>T("TimezoneAbbreviations.Ekaterinburg Standard Time"); ///"PKT" public static string TimezoneAbbreviations_Pakistan_Standard_Time=>T("TimezoneAbbreviations.Pakistan Standard Time"); ///"IST" public static string TimezoneAbbreviations_India_Standard_Time=>T("TimezoneAbbreviations.India Standard Time"); ///"IST" public static string TimezoneAbbreviations_Sri_Lanka_Standard_Time=>T("TimezoneAbbreviations.Sri Lanka Standard Time"); ///"NPT" public static string TimezoneAbbreviations_Nepal_Standard_Time=>T("TimezoneAbbreviations.Nepal Standard Time"); ///"ALMT" public static string TimezoneAbbreviations_Central_Asia_Standard_Time=>T("TimezoneAbbreviations.Central Asia Standard Time"); ///"BDT" public static string TimezoneAbbreviations_Bangladesh_Standard_Time=>T("TimezoneAbbreviations.Bangladesh Standard Time"); ///"NOVT" public static string TimezoneAbbreviations_N__Central_Asia_Standard_Time=>T("TimezoneAbbreviations.N. Central Asia Standard Time"); ///"MSK+3" public static string TimezoneAbbreviations_Altai_Standard_Time=>T("TimezoneAbbreviations.Altai Standard Time"); ///"MMT" public static string TimezoneAbbreviations_Myanmar_Standard_Time=>T("TimezoneAbbreviations.Myanmar Standard Time"); ///"ICT" public static string TimezoneAbbreviations_SE_Asia_Standard_Time=>T("TimezoneAbbreviations.SE Asia Standard Time"); ///"UTC+07" public static string TimezoneAbbreviations_W__Mongolia_Standard_Time=>T("TimezoneAbbreviations.W. Mongolia Standard Time"); ///"KRAT" public static string TimezoneAbbreviations_North_Asia_Standard_Time=>T("TimezoneAbbreviations.North Asia Standard Time"); ///"UTC+07" public static string TimezoneAbbreviations_Tomsk_Standard_Time=>T("TimezoneAbbreviations.Tomsk Standard Time"); ///"CST" public static string TimezoneAbbreviations_China_Standard_Time=>T("TimezoneAbbreviations.China Standard Time"); ///"IRKT" public static string TimezoneAbbreviations_North_Asia_East_Standard_Time=>T("TimezoneAbbreviations.North Asia East Standard Time"); ///"SGT" public static string TimezoneAbbreviations_Singapore_Standard_Time=>T("TimezoneAbbreviations.Singapore Standard Time"); ///"AWST" public static string TimezoneAbbreviations_W__Australia_Standard_Time=>T("TimezoneAbbreviations.W. Australia Standard Time"); ///"CST" public static string TimezoneAbbreviations_Taipei_Standard_Time=>T("TimezoneAbbreviations.Taipei Standard Time"); ///"ULAT" public static string TimezoneAbbreviations_Ulaanbaatar_Standard_Time=>T("TimezoneAbbreviations.Ulaanbaatar Standard Time"); ///"KST" public static string TimezoneAbbreviations_North_Korea_Standard_Time=>T("TimezoneAbbreviations.North Korea Standard Time"); ///"UTC+09" public static string TimezoneAbbreviations_Transbaikal_Standard_Time=>T("TimezoneAbbreviations.Transbaikal Standard Time"); ///"JST" public static string TimezoneAbbreviations_Tokyo_Standard_Time=>T("TimezoneAbbreviations.Tokyo Standard Time"); ///"KST" public static string TimezoneAbbreviations_Korea_Standard_Time=>T("TimezoneAbbreviations.Korea Standard Time"); ///"YAKT" public static string TimezoneAbbreviations_Yakutsk_Standard_Time=>T("TimezoneAbbreviations.Yakutsk Standard Time"); ///"ACDT" public static string TimezoneAbbreviations_Cen__Australia_Standard_Time=>T("TimezoneAbbreviations.Cen. Australia Standard Time"); ///"ACST" public static string TimezoneAbbreviations_AUS_Central_Standard_Time=>T("TimezoneAbbreviations.AUS Central Standard Time"); ///"AEST" public static string TimezoneAbbreviations_E__Australia_Standard_Time=>T("TimezoneAbbreviations.E. Australia Standard Time"); ///"AEDT" public static string TimezoneAbbreviations_AUS_Eastern_Standard_Time=>T("TimezoneAbbreviations.AUS Eastern Standard Time"); ///"PGT" public static string TimezoneAbbreviations_West_Pacific_Standard_Time=>T("TimezoneAbbreviations.West Pacific Standard Time"); ///"AEDT" public static string TimezoneAbbreviations_Tasmania_Standard_Time=>T("TimezoneAbbreviations.Tasmania Standard Time"); ///"MAGT" public static string TimezoneAbbreviations_Magadan_Standard_Time=>T("TimezoneAbbreviations.Magadan Standard Time"); ///"VLAT" public static string TimezoneAbbreviations_Vladivostok_Standard_Time=>T("TimezoneAbbreviations.Vladivostok Standard Time"); ///"SRET" public static string TimezoneAbbreviations_Russia_Time_Zone_10=>T("TimezoneAbbreviations.Russia Time Zone 10"); ///"UTC+11" public static string TimezoneAbbreviations_Norfolk_Standard_Time=>T("TimezoneAbbreviations.Norfolk Standard Time"); ///"UTC+11" public static string TimezoneAbbreviations_Sakhalin_Standard_Time=>T("TimezoneAbbreviations.Sakhalin Standard Time"); ///"SBT" public static string TimezoneAbbreviations_Central_Pacific_Standard_Time=>T("TimezoneAbbreviations.Central Pacific Standard Time"); ///"PETT" public static string TimezoneAbbreviations_Russia_Time_Zone_11=>T("TimezoneAbbreviations.Russia Time Zone 11"); ///"NZDT" public static string TimezoneAbbreviations_New_Zealand_Standard_Time=>T("TimezoneAbbreviations.New Zealand Standard Time"); ///"Etc/GMT-12" public static string TimezoneAbbreviations_UTC12=>T("TimezoneAbbreviations.UTC+12"); ///"FJST" public static string TimezoneAbbreviations_Fiji_Standard_Time=>T("TimezoneAbbreviations.Fiji Standard Time"); ///"PETT" public static string TimezoneAbbreviations_Kamchatka_Standard_Time=>T("TimezoneAbbreviations.Kamchatka Standard Time"); ///"CHAST" public static string TimezoneAbbreviations_Chatham_Islands_Standard_Time=>T("TimezoneAbbreviations.Chatham Islands Standard Time"); ///"TOT" public static string TimezoneAbbreviations_Tonga_Standard_Time=>T("TimezoneAbbreviations.Tonga Standard Time"); ///"WSDT" public static string TimezoneAbbreviations_Samoa_Standard_Time=>T("TimezoneAbbreviations.Samoa Standard Time"); ///"LINT" public static string TimezoneAbbreviations_Line_Islands_Standard_Time=>T("TimezoneAbbreviations.Line Islands Standard Time"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.TimezoneAbbreviations", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_TimezoneDisplayNames { ///"(UTC-12:00) International Date Line West" public static string TimezoneDisplayName_Dateline_Standard_Time=>T("TimezoneDisplayName.Dateline Standard Time"); ///"(UTC-11:00) Coordinated Universal Time-11" public static string TimezoneDisplayName_UTC_11=>T("TimezoneDisplayName.UTC-11"); ///"(UTC-10:00) Aleutian Islands" public static string TimezoneDisplayName_Aleutian_Standard_Time=>T("TimezoneDisplayName.Aleutian Standard Time"); ///"(UTC-10:00) Hawaii" public static string TimezoneDisplayName_Hawaiian_Standard_Time=>T("TimezoneDisplayName.Hawaiian Standard Time"); ///"(UTC-09:30) Marquesas Islands" public static string TimezoneDisplayName_Marquesas_Standard_Time=>T("TimezoneDisplayName.Marquesas Standard Time"); ///"(UTC-09:00) Alaska" public static string TimezoneDisplayName_Alaskan_Standard_Time=>T("TimezoneDisplayName.Alaskan Standard Time"); ///"(UTC-09:00) Coordinated Universal Time-09" public static string TimezoneDisplayName_UTC_09=>T("TimezoneDisplayName.UTC-09"); ///"(UTC-08:00) Baja California" public static string TimezoneDisplayName_Pacific_Standard_Time_Mexico=>T("TimezoneDisplayName.Pacific Standard Time (Mexico)"); ///"(UTC-08:00) Coordinated Universal Time-08" public static string TimezoneDisplayName_UTC_08=>T("TimezoneDisplayName.UTC-08"); ///"(UTC-08:00) Pacific Time (US & Canada)" public static string TimezoneDisplayName_Pacific_Standard_Time=>T("TimezoneDisplayName.Pacific Standard Time"); ///"(UTC-07:00) Arizona" public static string TimezoneDisplayName_US_Mountain_Standard_Time=>T("TimezoneDisplayName.US Mountain Standard Time"); ///"(UTC-07:00) Chihuahua, La Paz, Mazatlan" public static string TimezoneDisplayName_Mountain_Standard_Time_Mexico=>T("TimezoneDisplayName.Mountain Standard Time (Mexico)"); ///"(UTC-07:00) Mountain Time (US & Canada)" public static string TimezoneDisplayName_Mountain_Standard_Time=>T("TimezoneDisplayName.Mountain Standard Time"); ///"(UTC-06:00) Central America" public static string TimezoneDisplayName_Central_America_Standard_Time=>T("TimezoneDisplayName.Central America Standard Time"); ///"(UTC-06:00) Central Time (US & Canada)" public static string TimezoneDisplayName_Central_Standard_Time=>T("TimezoneDisplayName.Central Standard Time"); ///"(UTC-06:00) Easter Island" public static string TimezoneDisplayName_Easter_Island_Standard_Time=>T("TimezoneDisplayName.Easter Island Standard Time"); ///"(UTC-06:00) Guadalajara, Mexico City, Monterrey" public static string TimezoneDisplayName_Central_Standard_Time_Mexico=>T("TimezoneDisplayName.Central Standard Time (Mexico)"); ///"(UTC-06:00) Saskatchewan" public static string TimezoneDisplayName_Canada_Central_Standard_Time=>T("TimezoneDisplayName.Canada Central Standard Time"); ///"(UTC-05:00) Bogota, Lima, Quito, Rio Branco" public static string TimezoneDisplayName_SA_Pacific_Standard_Time=>T("TimezoneDisplayName.SA Pacific Standard Time"); ///"(UTC-05:00) Chetumal" public static string TimezoneDisplayName_Eastern_Standard_Time_Mexico=>T("TimezoneDisplayName.Eastern Standard Time (Mexico)"); ///"(UTC-05:00) Eastern Time (US & Canada)" public static string TimezoneDisplayName_Eastern_Standard_Time=>T("TimezoneDisplayName.Eastern Standard Time"); ///"(UTC-05:00) Haiti" public static string TimezoneDisplayName_Haiti_Standard_Time=>T("TimezoneDisplayName.Haiti Standard Time"); ///"(UTC-05:00) Havana" public static string TimezoneDisplayName_Cuba_Standard_Time=>T("TimezoneDisplayName.Cuba Standard Time"); ///"(UTC-05:00) Indiana (East)" public static string TimezoneDisplayName_US_Eastern_Standard_Time=>T("TimezoneDisplayName.US Eastern Standard Time"); ///"(UTC-04:00) Asuncion" public static string TimezoneDisplayName_Paraguay_Standard_Time=>T("TimezoneDisplayName.Paraguay Standard Time"); ///"(UTC-04:00) Atlantic Time (Canada)" public static string TimezoneDisplayName_Atlantic_Standard_Time=>T("TimezoneDisplayName.Atlantic Standard Time"); ///"(UTC-04:00) Caracas" public static string TimezoneDisplayName_Venezuela_Standard_Time=>T("TimezoneDisplayName.Venezuela Standard Time"); ///"(UTC-04:00) Cuiaba" public static string TimezoneDisplayName_Central_Brazilian_Standard_Time=>T("TimezoneDisplayName.Central Brazilian Standard Time"); ///"(UTC-04:00) Georgetown, La Paz, Manaus, San Juan" public static string TimezoneDisplayName_SA_Western_Standard_Time=>T("TimezoneDisplayName.SA Western Standard Time"); ///"(UTC-04:00) Santiago" public static string TimezoneDisplayName_Pacific_SA_Standard_Time=>T("TimezoneDisplayName.Pacific SA Standard Time"); ///"(UTC-04:00) Turks and Caicos" public static string TimezoneDisplayName_Turks_And_Caicos_Standard_Time=>T("TimezoneDisplayName.Turks And Caicos Standard Time"); ///"(UTC-03:30) Newfoundland" public static string TimezoneDisplayName_Newfoundland_Standard_Time=>T("TimezoneDisplayName.Newfoundland Standard Time"); ///"(UTC-03:00) Araguaina" public static string TimezoneDisplayName_Tocantins_Standard_Time=>T("TimezoneDisplayName.Tocantins Standard Time"); ///"(UTC-03:00) Brasilia" public static string TimezoneDisplayName_E__South_America_Standard_Time=>T("TimezoneDisplayName.E. South America Standard Time"); ///"(UTC-03:00) Cayenne, Fortaleza" public static string TimezoneDisplayName_SA_Eastern_Standard_Time=>T("TimezoneDisplayName.SA Eastern Standard Time"); ///"(UTC-03:00) City of Buenos Aires" public static string TimezoneDisplayName_Argentina_Standard_Time=>T("TimezoneDisplayName.Argentina Standard Time"); ///"(UTC-03:00) Greenland" public static string TimezoneDisplayName_Greenland_Standard_Time=>T("TimezoneDisplayName.Greenland Standard Time"); ///"(UTC-03:00) Montevideo" public static string TimezoneDisplayName_Montevideo_Standard_Time=>T("TimezoneDisplayName.Montevideo Standard Time"); ///"(UTC-03:00) Saint Pierre and Miquelon" public static string TimezoneDisplayName_Saint_Pierre_Standard_Time=>T("TimezoneDisplayName.Saint Pierre Standard Time"); ///"(UTC-03:00) Salvador" public static string TimezoneDisplayName_Bahia_Standard_Time=>T("TimezoneDisplayName.Bahia Standard Time"); ///"(UTC-02:00) Coordinated Universal Time-02" public static string TimezoneDisplayName_UTC_02=>T("TimezoneDisplayName.UTC-02"); ///"(UTC-02:00) Mid-Atlantic - Old" public static string TimezoneDisplayName_Mid_Atlantic_Standard_Time=>T("TimezoneDisplayName.Mid-Atlantic Standard Time"); ///"(UTC-01:00) Azores" public static string TimezoneDisplayName_Azores_Standard_Time=>T("TimezoneDisplayName.Azores Standard Time"); ///"(UTC-01:00) Cabo Verde Is." public static string TimezoneDisplayName_Cape_Verde_Standard_Time=>T("TimezoneDisplayName.Cape Verde Standard Time"); ///"(UTC) Coordinated Universal Time" public static string TimezoneDisplayName_UTC=>T("TimezoneDisplayName.UTC"); ///"(UTC+00:00) Casablanca" public static string TimezoneDisplayName_Morocco_Standard_Time=>T("TimezoneDisplayName.Morocco Standard Time"); ///"(UTC+00:00) Dublin, Edinburgh, Lisbon, London" public static string TimezoneDisplayName_GMT_Standard_Time=>T("TimezoneDisplayName.GMT Standard Time"); ///"(UTC+00:00) Monrovia, Reykjavik" public static string TimezoneDisplayName_Greenwich_Standard_Time=>T("TimezoneDisplayName.Greenwich Standard Time"); ///"(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna" public static string TimezoneDisplayName_W__Europe_Standard_Time=>T("TimezoneDisplayName.W. Europe Standard Time"); ///"(UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague" public static string TimezoneDisplayName_Central_Europe_Standard_Time=>T("TimezoneDisplayName.Central Europe Standard Time"); ///"(UTC+01:00) Brussels, Copenhagen, Madrid, Paris" public static string TimezoneDisplayName_Romance_Standard_Time=>T("TimezoneDisplayName.Romance Standard Time"); ///"(UTC+01:00) Sarajevo, Skopje, Warsaw, Zagreb" public static string TimezoneDisplayName_Central_European_Standard_Time=>T("TimezoneDisplayName.Central European Standard Time"); ///"(UTC+01:00) West Central Africa" public static string TimezoneDisplayName_W__Central_Africa_Standard_Time=>T("TimezoneDisplayName.W. Central Africa Standard Time"); ///"(UTC+01:00) Windhoek" public static string TimezoneDisplayName_Namibia_Standard_Time=>T("TimezoneDisplayName.Namibia Standard Time"); ///"(UTC+02:00) Amman" public static string TimezoneDisplayName_Jordan_Standard_Time=>T("TimezoneDisplayName.Jordan Standard Time"); ///"(UTC+02:00) Athens, Bucharest" public static string TimezoneDisplayName_GTB_Standard_Time=>T("TimezoneDisplayName.GTB Standard Time"); ///"(UTC+02:00) Beirut" public static string TimezoneDisplayName_Middle_East_Standard_Time=>T("TimezoneDisplayName.Middle East Standard Time"); ///"(UTC+02:00) Cairo" public static string TimezoneDisplayName_Egypt_Standard_Time=>T("TimezoneDisplayName.Egypt Standard Time"); ///"(UTC+02:00) Chisinau" public static string TimezoneDisplayName_E__Europe_Standard_Time=>T("TimezoneDisplayName.E. Europe Standard Time"); ///"(UTC+02:00) Damascus" public static string TimezoneDisplayName_Syria_Standard_Time=>T("TimezoneDisplayName.Syria Standard Time"); ///"(UTC+02:00) Gaza, Hebron" public static string TimezoneDisplayName_West_Bank_Standard_Time=>T("TimezoneDisplayName.West Bank Standard Time"); ///"(UTC+02:00) Harare, Pretoria" public static string TimezoneDisplayName_South_Africa_Standard_Time=>T("TimezoneDisplayName.South Africa Standard Time"); ///"(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius" public static string TimezoneDisplayName_FLE_Standard_Time=>T("TimezoneDisplayName.FLE Standard Time"); ///"(UTC+02:00) Istanbul" public static string TimezoneDisplayName_Turkey_Standard_Time=>T("TimezoneDisplayName.Turkey Standard Time"); ///"(UTC+02:00) Jerusalem" public static string TimezoneDisplayName_Israel_Standard_Time=>T("TimezoneDisplayName.Israel Standard Time"); ///"(UTC+02:00) Kaliningrad" public static string TimezoneDisplayName_Kaliningrad_Standard_Time=>T("TimezoneDisplayName.Kaliningrad Standard Time"); ///"(UTC+02:00) Tripoli" public static string TimezoneDisplayName_Libya_Standard_Time=>T("TimezoneDisplayName.Libya Standard Time"); ///"(UTC+03:00) Baghdad" public static string TimezoneDisplayName_Arabic_Standard_Time=>T("TimezoneDisplayName.Arabic Standard Time"); ///"(UTC+03:00) Kuwait, Riyadh" public static string TimezoneDisplayName_Arab_Standard_Time=>T("TimezoneDisplayName.Arab Standard Time"); ///"(UTC+03:00) Minsk" public static string TimezoneDisplayName_Belarus_Standard_Time=>T("TimezoneDisplayName.Belarus Standard Time"); ///"(UTC+03:00) Moscow, St. Petersburg, Volgograd" public static string TimezoneDisplayName_Russian_Standard_Time=>T("TimezoneDisplayName.Russian Standard Time"); ///"(UTC+03:00) Nairobi" public static string TimezoneDisplayName_E__Africa_Standard_Time=>T("TimezoneDisplayName.E. Africa Standard Time"); ///"(UTC+03:30) Tehran" public static string TimezoneDisplayName_Iran_Standard_Time=>T("TimezoneDisplayName.Iran Standard Time"); ///"(UTC+04:00) Abu Dhabi, Muscat" public static string TimezoneDisplayName_Arabian_Standard_Time=>T("TimezoneDisplayName.Arabian Standard Time"); ///"(UTC+04:00) Astrakhan, Ulyanovsk" public static string TimezoneDisplayName_Astrakhan_Standard_Time=>T("TimezoneDisplayName.Astrakhan Standard Time"); ///"(UTC+04:00) Baku" public static string TimezoneDisplayName_Azerbaijan_Standard_Time=>T("TimezoneDisplayName.Azerbaijan Standard Time"); ///"(UTC+04:00) Izhevsk, Samara" public static string TimezoneDisplayName_Russia_Time_Zone_3=>T("TimezoneDisplayName.Russia Time Zone 3"); ///"(UTC+04:00) Port Louis" public static string TimezoneDisplayName_Mauritius_Standard_Time=>T("TimezoneDisplayName.Mauritius Standard Time"); ///"(UTC+04:00) Tbilisi" public static string TimezoneDisplayName_Georgian_Standard_Time=>T("TimezoneDisplayName.Georgian Standard Time"); ///"(UTC+04:00) Yerevan" public static string TimezoneDisplayName_Caucasus_Standard_Time=>T("TimezoneDisplayName.Caucasus Standard Time"); ///"(UTC+04:30) Kabul" public static string TimezoneDisplayName_Afghanistan_Standard_Time=>T("TimezoneDisplayName.Afghanistan Standard Time"); ///"(UTC+05:00) Ashgabat, Tashkent" public static string TimezoneDisplayName_West_Asia_Standard_Time=>T("TimezoneDisplayName.West Asia Standard Time"); ///"(UTC+05:00) Ekaterinburg" public static string TimezoneDisplayName_Ekaterinburg_Standard_Time=>T("TimezoneDisplayName.Ekaterinburg Standard Time"); ///"(UTC+05:00) Islamabad, Karachi" public static string TimezoneDisplayName_Pakistan_Standard_Time=>T("TimezoneDisplayName.Pakistan Standard Time"); ///"(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi" public static string TimezoneDisplayName_India_Standard_Time=>T("TimezoneDisplayName.India Standard Time"); ///"(UTC+05:30) Sri Jayawardenepura" public static string TimezoneDisplayName_Sri_Lanka_Standard_Time=>T("TimezoneDisplayName.Sri Lanka Standard Time"); ///"(UTC+05:45) Kathmandu" public static string TimezoneDisplayName_Nepal_Standard_Time=>T("TimezoneDisplayName.Nepal Standard Time"); ///"(UTC+06:00) Astana" public static string TimezoneDisplayName_Central_Asia_Standard_Time=>T("TimezoneDisplayName.Central Asia Standard Time"); ///"(UTC+06:00) Dhaka" public static string TimezoneDisplayName_Bangladesh_Standard_Time=>T("TimezoneDisplayName.Bangladesh Standard Time"); ///"(UTC+06:00) Novosibirsk" public static string TimezoneDisplayName_N__Central_Asia_Standard_Time=>T("TimezoneDisplayName.N. Central Asia Standard Time"); ///"(UTC+06:30) Yangon (Rangoon)" public static string TimezoneDisplayName_Myanmar_Standard_Time=>T("TimezoneDisplayName.Myanmar Standard Time"); ///"(UTC+07:00) Bangkok, Hanoi, Jakarta" public static string TimezoneDisplayName_SE_Asia_Standard_Time=>T("TimezoneDisplayName.SE Asia Standard Time"); ///"(UTC+07:00) Barnaul, Gorno-Altaysk" public static string TimezoneDisplayName_Altai_Standard_Time=>T("TimezoneDisplayName.Altai Standard Time"); ///"(UTC+07:00) Hovd" public static string TimezoneDisplayName_W__Mongolia_Standard_Time=>T("TimezoneDisplayName.W. Mongolia Standard Time"); ///"(UTC+07:00) Krasnoyarsk" public static string TimezoneDisplayName_North_Asia_Standard_Time=>T("TimezoneDisplayName.North Asia Standard Time"); ///"(UTC+07:00) Tomsk" public static string TimezoneDisplayName_Tomsk_Standard_Time=>T("TimezoneDisplayName.Tomsk Standard Time"); ///"(UTC+08:00) Beijing, Chongqing, Hong Kong, Urumqi" public static string TimezoneDisplayName_China_Standard_Time=>T("TimezoneDisplayName.China Standard Time"); ///"(UTC+08:00) Irkutsk" public static string TimezoneDisplayName_North_Asia_East_Standard_Time=>T("TimezoneDisplayName.North Asia East Standard Time"); ///"(UTC+08:00) Kuala Lumpur, Singapore" public static string TimezoneDisplayName_Singapore_Standard_Time=>T("TimezoneDisplayName.Singapore Standard Time"); ///"(UTC+08:00) Perth" public static string TimezoneDisplayName_W__Australia_Standard_Time=>T("TimezoneDisplayName.W. Australia Standard Time"); ///"(UTC+08:00) Taipei" public static string TimezoneDisplayName_Taipei_Standard_Time=>T("TimezoneDisplayName.Taipei Standard Time"); ///"(UTC+08:00) Ulaanbaatar" public static string TimezoneDisplayName_Ulaanbaatar_Standard_Time=>T("TimezoneDisplayName.Ulaanbaatar Standard Time"); ///"(UTC+08:30) Pyongyang" public static string TimezoneDisplayName_North_Korea_Standard_Time=>T("TimezoneDisplayName.North Korea Standard Time"); ///"(UTC+08:45) Eucla" public static string TimezoneDisplayName_Aus_Central_W__Standard_Time=>T("TimezoneDisplayName.Aus Central W. Standard Time"); ///"(UTC+09:00) Chita" public static string TimezoneDisplayName_Transbaikal_Standard_Time=>T("TimezoneDisplayName.Transbaikal Standard Time"); ///"(UTC+09:00) Osaka, Sapporo, Tokyo" public static string TimezoneDisplayName_Tokyo_Standard_Time=>T("TimezoneDisplayName.Tokyo Standard Time"); ///"(UTC+09:00) Seoul" public static string TimezoneDisplayName_Korea_Standard_Time=>T("TimezoneDisplayName.Korea Standard Time"); ///"(UTC+09:00) Yakutsk" public static string TimezoneDisplayName_Yakutsk_Standard_Time=>T("TimezoneDisplayName.Yakutsk Standard Time"); ///"(UTC+09:30) Adelaide" public static string TimezoneDisplayName_Cen__Australia_Standard_Time=>T("TimezoneDisplayName.Cen. Australia Standard Time"); ///"(UTC+09:30) Darwin" public static string TimezoneDisplayName_AUS_Central_Standard_Time=>T("TimezoneDisplayName.AUS Central Standard Time"); ///"(UTC+10:00) Brisbane" public static string TimezoneDisplayName_E__Australia_Standard_Time=>T("TimezoneDisplayName.E. Australia Standard Time"); ///"(UTC+10:00) Canberra, Melbourne, Sydney" public static string TimezoneDisplayName_AUS_Eastern_Standard_Time=>T("TimezoneDisplayName.AUS Eastern Standard Time"); ///"(UTC+10:00) Guam, Port Moresby" public static string TimezoneDisplayName_West_Pacific_Standard_Time=>T("TimezoneDisplayName.West Pacific Standard Time"); ///"(UTC+10:00) Hobart" public static string TimezoneDisplayName_Tasmania_Standard_Time=>T("TimezoneDisplayName.Tasmania Standard Time"); ///"(UTC+10:00) Vladivostok" public static string TimezoneDisplayName_Vladivostok_Standard_Time=>T("TimezoneDisplayName.Vladivostok Standard Time"); ///"(UTC+10:30) Lord Howe Island" public static string TimezoneDisplayName_Lord_Howe_Standard_Time=>T("TimezoneDisplayName.Lord Howe Standard Time"); ///"(UTC+11:00) Bougainville Island" public static string TimezoneDisplayName_Bougainville_Standard_Time=>T("TimezoneDisplayName.Bougainville Standard Time"); ///"(UTC+11:00) Chokurdakh" public static string TimezoneDisplayName_Russia_Time_Zone_10=>T("TimezoneDisplayName.Russia Time Zone 10"); ///"(UTC+11:00) Magadan" public static string TimezoneDisplayName_Magadan_Standard_Time=>T("TimezoneDisplayName.Magadan Standard Time"); ///"(UTC+11:00) Norfolk Island" public static string TimezoneDisplayName_Norfolk_Standard_Time=>T("TimezoneDisplayName.Norfolk Standard Time"); ///"(UTC+11:00) Sakhalin" public static string TimezoneDisplayName_Sakhalin_Standard_Time=>T("TimezoneDisplayName.Sakhalin Standard Time"); ///"(UTC+11:00) Solomon Is., New Caledonia" public static string TimezoneDisplayName_Central_Pacific_Standard_Time=>T("TimezoneDisplayName.Central Pacific Standard Time"); ///"(UTC+12:00) Anadyr, Petropavlovsk-Kamchatsky" public static string TimezoneDisplayName_Russia_Time_Zone_11=>T("TimezoneDisplayName.Russia Time Zone 11"); ///"(UTC+12:00) Auckland, Wellington" public static string TimezoneDisplayName_New_Zealand_Standard_Time=>T("TimezoneDisplayName.New Zealand Standard Time"); ///"(UTC+12:00) Coordinated Universal Time+12" public static string TimezoneDisplayName_UTC12=>T("TimezoneDisplayName.UTC+12"); ///"(UTC+12:00) Fiji" public static string TimezoneDisplayName_Fiji_Standard_Time=>T("TimezoneDisplayName.Fiji Standard Time"); ///"(UTC+12:00) Petropavlovsk-Kamchatsky - Old" public static string TimezoneDisplayName_Kamchatka_Standard_Time=>T("TimezoneDisplayName.Kamchatka Standard Time"); ///"(UTC+12:45) Chatham Islands" public static string TimezoneDisplayName_Chatham_Islands_Standard_Time=>T("TimezoneDisplayName.Chatham Islands Standard Time"); ///"(UTC+13:00) Nuku'alofa" public static string TimezoneDisplayName_Tonga_Standard_Time=>T("TimezoneDisplayName.Tonga Standard Time"); ///"(UTC+13:00) Samoa" public static string TimezoneDisplayName_Samoa_Standard_Time=>T("TimezoneDisplayName.Samoa Standard Time"); ///"(UTC+14:00) Kiritimati Island" public static string TimezoneDisplayName_Line_Islands_Standard_Time=>T("TimezoneDisplayName.Line Islands Standard Time"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.TimezoneDisplayNames", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_UserControlFunction { ///"User Control Functions" public static string RootElement_Label=>T("RootElement.Label"); ///"Functions based on .ascx controls" public static string RootElement_ToolTip=>T("RootElement.ToolTip"); ///"Add User Control Function" public static string AddNewUserControlFunction_Label=>T("AddNewUserControlFunction.Label"); ///"Add a new User Control function" public static string AddNewUserControlFunction_ToolTip=>T("AddNewUserControlFunction.ToolTip"); ///"Edit" public static string EditUserControlFunction_Label=>T("EditUserControlFunction.Label"); ///"Edit the User Control Function" public static string EditUserControlFunction_ToolTip=>T("EditUserControlFunction.ToolTip"); ///"Delete" public static string DeleteUserControlFunction_Label=>T("DeleteUserControlFunction.Label"); ///"Delete the User Control function" public static string DeleteUserControlFunction_ToolTip=>T("DeleteUserControlFunction.ToolTip"); ///"Add User Control Function" public static string AddNewUserControlFunction_LabelDialog=>T("AddNewUserControlFunction.LabelDialog"); ///"Name" public static string AddNewUserControlFunction_LabelName=>T("AddNewUserControlFunction.LabelName"); ///"" public static string AddNewUserControlFunction_HelpName=>T("AddNewUserControlFunction.HelpName"); ///"Namespace" public static string AddNewUserControlFunction_LabelNamespace=>T("AddNewUserControlFunction.LabelNamespace"); ///"" public static string AddNewUserControlFunction_HelpNamespace=>T("AddNewUserControlFunction.HelpNamespace"); ///"Copy from" public static string AddNewUserControlFunction_LabelCopyFrom=>T("AddNewUserControlFunction.LabelCopyFrom"); ///"You can copy the code from another User Control function by selecting it in this list." public static string AddNewUserControlFunction_LabelCopyFromHelp=>T("AddNewUserControlFunction.LabelCopyFromHelp"); ///"(New User Control function)" public static string AddNewUserControlFunction_LabelCopyFromEmptyOption=>T("AddNewUserControlFunction.LabelCopyFromEmptyOption"); ///"A C1 function with the same name already exists." public static string AddNewUserControlFunctionWorkflow_DuplicateName=>T("AddNewUserControlFunctionWorkflow.DuplicateName"); ///"Function name is empty" public static string AddNewUserControlFunctionWorkflow_EmptyName=>T("AddNewUserControlFunctionWorkflow.EmptyName"); ///"Function namespace is empty" public static string AddNewUserControlFunctionWorkflow_NamespaceEmpty=>T("AddNewUserControlFunctionWorkflow.NamespaceEmpty"); ///"Namespace must be like A.B.C - not start and end with ." public static string AddNewUserControlFunctionWorkflow_InvalidNamespace=>T("AddNewUserControlFunctionWorkflow.InvalidNamespace"); ///"The total length of the name and the namespace is too long (used to name the ASCX file)." public static string AddNewUserControlFunctionWorkflow_TotalNameTooLang=>T("AddNewUserControlFunctionWorkflow.TotalNameTooLang"); ///"Validation Error" public static string EditUserControlFunctionWorkflow_Validation_DialogTitle=>T("EditUserControlFunctionWorkflow.Validation.DialogTitle"); ///"Compilation failed: {0}" public static string EditUserControlFunctionWorkflow_Validation_CompilationFailed_Template=>T("EditUserControlFunctionWorkflow.Validation.CompilationFailed"); ///"Compilation failed: {0}" public static string EditUserControlFunctionWorkflow_Validation_CompilationFailed(object parameter0)=>string.Format(T("EditUserControlFunctionWorkflow.Validation.CompilationFailed"), parameter0); ///"The User Control function should inherit '{0}'" public static string EditUserControlFunctionWorkflow_Validation_IncorrectBaseClass_Template=>T("EditUserControlFunctionWorkflow.Validation.IncorrectBaseClass"); ///"The User Control function should inherit '{0}'" public static string EditUserControlFunctionWorkflow_Validation_IncorrectBaseClass(object parameter0)=>string.Format(T("EditUserControlFunctionWorkflow.Validation.IncorrectBaseClass"), parameter0); ///"Delete User Control Function?" public static string DeleteUserControlFunctionWorkflow_ConfirmDeleteTitle=>T("DeleteUserControlFunctionWorkflow.ConfirmDeleteTitle"); ///"Delete the selected User Control?" public static string DeleteUserControlFunctionWorkflow_ConfirmDeleteMessage=>T("DeleteUserControlFunctionWorkflow.ConfirmDeleteMessage"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.UserControlFunction", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_UserGroupElementProvider { ///"User Groups" public static string UserGroupElementProvider_RootLabel=>T("UserGroupElementProvider.RootLabel"); ///"User Groups" public static string UserGroupElementProvider_RootToolTip=>T("UserGroupElementProvider.RootToolTip"); ///"Add User Group" public static string UserGroupElementProvider_AddNewUserGroupLabel=>T("UserGroupElementProvider.AddNewUserGroupLabel"); ///"Add new User Group" public static string UserGroupElementProvider_AddNewUserGroupToolTip=>T("UserGroupElementProvider.AddNewUserGroupToolTip"); ///"Edit User Group" public static string UserGroupElementProvider_EditUserGroupLabel=>T("UserGroupElementProvider.EditUserGroupLabel"); ///"Edit User Group" public static string UserGroupElementProvider_EditUserGroupToolTip=>T("UserGroupElementProvider.EditUserGroupToolTip"); ///"Delete User Group" public static string UserGroupElementProvider_DeleteUserGroupLabel=>T("UserGroupElementProvider.DeleteUserGroupLabel"); ///"Delete User Group" public static string UserGroupElementProvider_DeleteUserGroupToolTip=>T("UserGroupElementProvider.DeleteUserGroupToolTip"); ///"Add User Group" public static string AddNewUserGroup_AddNewUserGroupStep1_LabelFieldGroup=>T("AddNewUserGroup.AddNewUserGroupStep1.LabelFieldGroup"); ///"User group name" public static string AddNewUserGroup_AddNewUserGroupStep1_UserGroupNameLabel=>T("AddNewUserGroup.AddNewUserGroupStep1.UserGroupNameLabel"); ///"The name of the new user group" public static string AddNewUserGroup_AddNewUserGroupStep1_UserGroupNameHelp=>T("AddNewUserGroup.AddNewUserGroupStep1.UserGroupNameHelp"); ///"A user group with the same name already exists" public static string AddNewUserGroup_AddNewUserGroupStep1_UserGroupNameAlreadyExists=>T("AddNewUserGroup.AddNewUserGroupStep1.UserGroupNameAlreadyExists"); ///"Edit User Group" public static string EditUserGroup_EditUserGroupStep1_LabelFieldGroup=>T("EditUserGroup.EditUserGroupStep1.LabelFieldGroup"); ///"User group name" public static string EditUserGroup_EditUserGroupStep1_UserGroupNameLabel=>T("EditUserGroup.EditUserGroupStep1.UserGroupNameLabel"); ///"The name of the user group" public static string EditUserGroup_EditUserGroupStep1_UserGroupNameHelp=>T("EditUserGroup.EditUserGroupStep1.UserGroupNameHelp"); ///"A user group with the same name already exists" public static string EditUserGroup_EditUserGroupStep1_UserGroupNameAlreadyExists=>T("EditUserGroup.EditUserGroupStep1.UserGroupNameAlreadyExists"); ///"Perspectives" public static string EditUserGroup_EditUserGroupStep1_ActivePerspectiveFieldLabel=>T("EditUserGroup.EditUserGroupStep1.ActivePerspectiveFieldLabel"); ///"Perspectives" public static string EditUserGroup_EditUserGroupStep1_ActivePerspectiveMultiSelectLabel=>T("EditUserGroup.EditUserGroupStep1.ActivePerspectiveMultiSelectLabel"); ///"Select which perspectives the users of this group gets access to view" public static string EditUserGroup_EditUserGroupStep1_ActivePerspectiveMultiSelectHelp=>T("EditUserGroup.EditUserGroupStep1.ActivePerspectiveMultiSelectHelp"); ///"Global permissions" public static string EditUserGroup_EditUserGroupStep1_GlobalPermissionsFieldLabel=>T("EditUserGroup.EditUserGroupStep1.GlobalPermissionsFieldLabel"); ///"Global permissions" public static string EditUserGroup_EditUserGroupStep1_GlobalPermissionsMultiSelectLabel=>T("EditUserGroup.EditUserGroupStep1.GlobalPermissionsMultiSelectLabel"); ///"Global permissions that users in this group should have. The Administrate permission grants the user group access to manage user group permissions and execute other administrative tasks. The Configure permission grants access to super user tasks." public static string EditUserGroup_EditUserGroupStep1_GlobalPermissionsMultiSelectHelp=>T("EditUserGroup.EditUserGroupStep1.GlobalPermissionsMultiSelectHelp"); ///"Data Language Access" public static string EditUserGroup_EditUserGroupStep1_ActiveLocalesFieldLabel=>T("EditUserGroup.EditUserGroupStep1.ActiveLocalesFieldLabel"); ///"Data Languages" public static string EditUserGroup_EditUserGroupStep1_ActiveLocalesMultiSelectLabel=>T("EditUserGroup.EditUserGroupStep1.ActiveLocalesMultiSelectLabel"); ///"Users in this group has access to manage data in the selected languages." public static string EditUserGroup_EditUserGroupStep1_ActiveLocalesMultiSelectHelp=>T("EditUserGroup.EditUserGroupStep1.ActiveLocalesMultiSelectHelp"); ///"User Group Has Users" public static string DeleteUserGroup_DeleteUserGroupInitialStep_UserGroupHasUsersTitle=>T("DeleteUserGroup.DeleteUserGroupInitialStep.UserGroupHasUsersTitle"); ///"You cannot delete a user group that has users." public static string DeleteUserGroup_DeleteUserGroupInitialStep_UserGroupHasUsersMessage=>T("DeleteUserGroup.DeleteUserGroupInitialStep.UserGroupHasUsersMessage"); ///"Delete User Group" public static string DeleteUserGroup_DeleteUserGroupStep1_LabelFieldGroup=>T("DeleteUserGroup.DeleteUserGroupStep1.LabelFieldGroup"); ///"Delete the selected user group?" public static string DeleteUserGroup_DeleteUserGroupStep1_Text=>T("DeleteUserGroup.DeleteUserGroupStep1.Text"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.UserGroupElementProvider", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_VisualFunction { ///"Delete Visual Function?" public static string DeleteStep1_FieldGroupLabel=>T("DeleteStep1.FieldGroupLabel"); ///"Are you sure you wish to delete the selected function?" public static string DeleteStep1_Text=>T("DeleteStep1.Text"); ///"Add Visual Function" public static string AddNew_DialogLabel=>T("AddNew.DialogLabel"); ///"No Datatypes to Visualize" public static string AddNew_NoTypesExistsErrorTitle=>T("AddNew.NoTypesExistsErrorTitle"); ///"No datatypes have been created yet. You must first create a datatype to visualize before you can create a visualization." public static string AddNew_NoTypesExistsErrorMessage=>T("AddNew.NoTypesExistsErrorMessage"); ///"No Data to Visualize and Preview" public static string AddNew_NoDataExistsErrorTitle=>T("AddNew.NoDataExistsErrorTitle"); ///"Data must exist before you can create a rendering. Add some data to this type and try again." public static string AddNew_NoDataExistsErrorMessage=>T("AddNew.NoDataExistsErrorMessage"); ///"No Templates" public static string AddNew_NoPageTemplatesExistsErrorTitle=>T("AddNew.NoPageTemplatesExistsErrorTitle"); ///"At least one template must exist before you can create a rendering. Create one template and try again." public static string AddNew_NoPageTemplatesExistsErrorMessage=>T("AddNew.NoPageTemplatesExistsErrorMessage"); ///"A Language Is Required" public static string AddNew_MissingActiveLanguageTitle=>T("AddNew.MissingActiveLanguageTitle"); ///"To create a visual function a language is required, but no languages have been added yet. You can add one under the System perspective." public static string AddNew_MissingActiveLanguageMessage=>T("AddNew.MissingActiveLanguageMessage"); ///"Datatype" public static string AddNewStep1_TypeSelectorLabel=>T("AddNewStep1.TypeSelectorLabel"); ///"" public static string AddNewStep1_TypeSelectorHelp=>T("AddNewStep1.TypeSelectorHelp"); ///"Function name" public static string AddNewStep2_FuncitonNameLabel=>T("AddNewStep2.FuncitonNameLabel"); ///"" public static string AddNewStep2_FuncitonNameHelp=>T("AddNewStep2.FuncitonNameHelp"); ///"Function namespace" public static string AddNewStep2_FuncitonNamespaceLabel=>T("AddNewStep2.FuncitonNamespaceLabel"); ///"" public static string AddNewStep2_FuncitonNamespaceHelp=>T("AddNewStep2.FuncitonNamespaceHelp"); ///"Visual Function Settings" public static string Edit_PlaceHolderLabel=>T("Edit.PlaceHolderLabel"); ///"Visual function" public static string Edit_HeadingTitel=>T("Edit.HeadingTitel"); ///"Visual function settings" public static string Edit_FieldGroupLabel=>T("Edit.FieldGroupLabel"); ///"Function name" public static string Edit_FunctionNameLabel=>T("Edit.FunctionNameLabel"); ///"The name of the function. Names must be unique with a namespace." public static string Edit_FunctionNameHelp=>T("Edit.FunctionNameHelp"); ///"Function namespace" public static string Edit_FunctionNamespaceLabel=>T("Edit.FunctionNamespaceLabel"); ///"The 'package' this function belongs to." public static string Edit_FunctionNamespaceHelp=>T("Edit.FunctionNamespaceHelp"); ///"Description" public static string Edit_FunctionDescriptionLabel=>T("Edit.FunctionDescriptionLabel"); ///"A description of the function that can help people understand what it does." public static string Edit_FunctionDescriptionHelp=>T("Edit.FunctionDescriptionHelp"); ///"Item list length" public static string Edit_ItemListLenghtLabel=>T("Edit.ItemListLenghtLabel"); ///"The maximum number of items to show." public static string Edit_ItemListLenghtHelp=>T("Edit.ItemListLenghtHelp"); ///"Item sorting" public static string Edit_ItemSortingLabel=>T("Edit.ItemSortingLabel"); ///"Select which field to use when sorting the list. Use '(random)' to pick randomly from the list." public static string Edit_ItemSortingHelp=>T("Edit.ItemSortingHelp"); ///"List sort order" public static string Edit_ListSortingLabel=>T("Edit.ListSortingLabel"); ///"Ascending" public static string Edit_ListSortingTrueLabel=>T("Edit.ListSortingTrueLabel"); ///"Descending" public static string Edit_ListSortingFalseLabel=>T("Edit.ListSortingFalseLabel"); ///"Select the sorted order. Ascending order is alphabetically, chronological. This field is ignored when '(random)' sorting is active." public static string Edit_ListSortingHelp=>T("Edit.ListSortingHelp"); ///"Preview template" public static string Edit_PreviewTemplateLabel=>T("Edit.PreviewTemplateLabel"); ///"This information is only used when previewing the function." public static string Edit_PreviewTemplateHelp=>T("Edit.PreviewTemplateHelp"); ///"Visual Layout" public static string Edit_WYSIWYGLayoutLabel=>T("Edit.WYSIWYGLayoutLabel"); ///"Preview" public static string Edit_LabelPreview=>T("Edit.LabelPreview"); ///"No templates" public static string Edit_NoPageTemplatesExistsErrorTitle=>T("Edit.NoPageTemplatesExistsErrorTitle"); ///"At least one template must exist before you can edit a rendering. Create one template and try again." public static string Edit_NoPageTemplatesExistsErrorMessage=>T("Edit.NoPageTemplatesExistsErrorMessage"); ///"A language is required" public static string Edit_MissingActiveLanguageTitle=>T("Edit.MissingActiveLanguageTitle"); ///"To edit a visual function a language is required, but no languages have been added yet. You can add one under the System perspective." public static string Edit_MissingActiveLanguageMessage=>T("Edit.MissingActiveLanguageMessage"); ///"Select a visual function" public static string Select_FieldGroupLabel=>T("Select.FieldGroupLabel"); ///"Select a function" public static string Select_FunctionFunctionsLabel=>T("Select.FunctionFunctionsLabel"); ///"Select a visual function to edit or delete" public static string Select_FunctionFunctionsHelp=>T("Select.FunctionFunctionsHelp"); ///"Another function with this name exists. Names must be unique." public static string AddVisualFunctionWorkflow_FunctionNameValidatoinErrorMessage=>T("AddVisualFunctionWorkflow.FunctionNameValidatoinErrorMessage"); ///"Another function with this name exists. Names must be unique." public static string EditVisualFunctionWorkflow_FunctionNameValidatoinErrorMessage=>T("EditVisualFunctionWorkflow.FunctionNameValidatoinErrorMessage"); ///"Visual Functions" public static string VisualFunctionElementProvider_RootFolderLabel=>T("VisualFunctionElementProvider.RootFolderLabel"); ///"Visual functions" public static string VisualFunctionElementProvider_RootFolderToolTip=>T("VisualFunctionElementProvider.RootFolderToolTip"); ///"Add Visual Function" public static string VisualFunctionElementProvider_AddNewLabel=>T("VisualFunctionElementProvider.AddNewLabel"); ///"Add new visual function" public static string VisualFunctionElementProvider_AddNewToolTip=>T("VisualFunctionElementProvider.AddNewToolTip"); ///"Edit Visual Function" public static string VisualFunctionElementProvider_EditLabel=>T("VisualFunctionElementProvider.EditLabel"); ///"Edit visual function" public static string VisualFunctionElementProvider_EditToolTip=>T("VisualFunctionElementProvider.EditToolTip"); ///"Delete Visual Function" public static string VisualFunctionElementProvider_DeleteLabel=>T("VisualFunctionElementProvider.DeleteLabel"); ///"Delete visual function" public static string VisualFunctionElementProvider_DeleteToolTip=>T("VisualFunctionElementProvider.DeleteToolTip"); ///"Another function with this name exists. Names must be unique." public static string VisualFunctionElementProvider_FunctionNameNotUniqueError=>T("VisualFunctionElementProvider.FunctionNameNotUniqueError"); ///"New visual function" public static string VisualFunctionElementProviderHelper_AddNewLabel=>T("VisualFunctionElementProviderHelper.AddNewLabel"); ///"New visual function" public static string VisualFunctionElementProviderHelper_AddNewToolTip=>T("VisualFunctionElementProviderHelper.AddNewToolTip"); ///"Edit visual function" public static string VisualFunctionElementProviderHelper_EditLabel=>T("VisualFunctionElementProviderHelper.EditLabel"); ///"Edit visual function" public static string VisualFunctionElementProviderHelper_EditToolTip=>T("VisualFunctionElementProviderHelper.EditToolTip"); ///"Delete visual function" public static string VisualFunctionElementProviderHelper_DeleteLabel=>T("VisualFunctionElementProviderHelper.DeleteLabel"); ///"Delete visual function" public static string VisualFunctionElementProviderHelper_DeleteToolTip=>T("VisualFunctionElementProviderHelper.DeleteToolTip"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_WebsiteFileElementProvider { ///"/" public static string WebsiteFilesRootElement_Label=>T("WebsiteFilesRootElement.Label"); ///"/" public static string LayoutResourcesRootElement_Label=>T("LayoutResourcesRootElement.Label"); ///"Layout" public static string LayoutResourcesKeyNameLabel=>T("LayoutResourcesKeyNameLabel"); ///"Delete File?" public static string DeleteFile_LabelFieldGroup=>T("DeleteFile.LabelFieldGroup"); ///"Delete file?" public static string DeleteFile_Text=>T("DeleteFile.Text"); ///"Delete Folder?" public static string DeleteFolder_LabelFieldGroup=>T("DeleteFolder.LabelFieldGroup"); ///"Delete folder?" public static string DeleteFolder_Text=>T("DeleteFolder.Text"); ///"Add New Folder" public static string AddNewFolder_LabelFieldGroup=>T("AddNewFolder.LabelFieldGroup"); ///"Folder name" public static string AddNewFolder_Text=>T("AddNewFolder.Text"); ///"Enter the name of the new folder" public static string AddNewFolder_Help=>T("AddNewFolder.Help"); ///"A folder with the same name already exists" public static string AddNewFolder_Error_FolderExist=>T("AddNewFolder.Error.FolderExist"); ///"Add New File" public static string AddNewFile_LabelFieldGroup=>T("AddNewFile.LabelFieldGroup"); ///"File name" public static string AddNewFile_Text=>T("AddNewFile.Text"); ///"Enter the name of the new file" public static string AddNewFile_Help=>T("AddNewFile.Help"); ///"A file with the same name already exists" public static string AddNewFile_Error_FileExist=>T("AddNewFile.Error.FileExist"); ///"Upload File" public static string UploadNewWebsiteFile_LabelFieldGroup=>T("UploadNewWebsiteFile.LabelFieldGroup"); ///"Select file" public static string UploadNewWebsiteFile_LabelFile=>T("UploadNewWebsiteFile.LabelFile"); ///"Select file to upload" public static string UploadNewWebsiteFile_HelpFile=>T("UploadNewWebsiteFile.HelpFile"); ///"Overwrite existing file" public static string UploadNewWebsiteFile_ConfirmOverwriteTitle=>T("UploadNewWebsiteFile.ConfirmOverwriteTitle"); ///"A file with the same name already exists, overwrite?" public static string UploadNewWebsiteFile_ConfirmOverwriteDescription=>T("UploadNewWebsiteFile.ConfirmOverwriteDescription"); ///"Wrong File Type" public static string UploadFile_Error_WrongTypeTitle=>T("UploadFile.Error.WrongTypeTitle"); ///"Wrong file type" public static string UploadFile_Error_WrongTypeMessage=>T("UploadFile.Error.WrongTypeMessage"); ///"Upload and Extract Zip" public static string UploadAndExtractZipFileTitle=>T("UploadAndExtractZipFileTitle"); ///"Upload multiple files and folders by providing a Zip file" public static string UploadAndExtractZipFileToolTip=>T("UploadAndExtractZipFileToolTip"); ///"Upload and Extract Zip File" public static string UploadAndExtractZipFile_DialogLabel=>T("UploadAndExtractZipFile.DialogLabel"); ///"Zip file" public static string UploadAndExtractZipFile_FileLabel=>T("UploadAndExtractZipFile.FileLabel"); ///"The file/folder structure of the zip file you select will be extracted and copied to the website" public static string UploadAndExtractZipFile_FileHelp=>T("UploadAndExtractZipFile.FileHelp"); ///"Overwrite existing" public static string UploadAndExtractZipFile_OverwriteExistingLabel=>T("UploadAndExtractZipFile.OverwriteExistingLabel"); ///"If you select this option, existing files will be overwritten" public static string UploadAndExtractZipFile_OverwriteExistingHelp=>T("UploadAndExtractZipFile.OverwriteExistingHelp"); ///"Overwrite existing files" public static string UploadAndExtractZipFile_OverwriteExistingItemLabel=>T("UploadAndExtractZipFile.OverwriteExistingItemLabel"); ///"File '{0}' exists both in the zip and on the website. Choose to overwrite files to complete this action" public static string UploadAndExtractZipFile_FileExistsError_Template=>T("UploadAndExtractZipFile.FileExistsError"); ///"File '{0}' exists both in the zip and on the website. Choose to overwrite files to complete this action" public static string UploadAndExtractZipFile_FileExistsError(object parameter0)=>string.Format(T("UploadAndExtractZipFile.FileExistsError"), parameter0); ///"No file was uploaded" public static string UploadAndExtractZipFile_FileNotUploaded=>T("UploadAndExtractZipFile.FileNotUploaded"); ///"The uploaded file is not a valid Zip archive" public static string UploadAndExtractZipFile_NotZip=>T("UploadAndExtractZipFile.NotZip"); ///"Zip upload could not be completed" public static string UploadAndExtractZipFile_ErrorDialogLabel=>T("UploadAndExtractZipFile.ErrorDialogLabel"); ///"Upload failed unexpectedly. Please see log for details" public static string UploadAndExtractZipFile_UnexpectedError=>T("UploadAndExtractZipFile.UnexpectedError"); ///"Existing file '{0}' is marked as read only. No files were uploaded" public static string UploadAndExtractZipFile_ExistingFileReadOnly_Template=>T("UploadAndExtractZipFile.ExistingFileReadOnly"); ///"Existing file '{0}' is marked as read only. No files were uploaded" public static string UploadAndExtractZipFile_ExistingFileReadOnly(object parameter0)=>string.Format(T("UploadAndExtractZipFile.ExistingFileReadOnly"), parameter0); ///"New Folder" public static string AddWebsiteFolderTitle=>T("AddWebsiteFolderTitle"); ///"Add new folder" public static string AddWebsiteFolderToolTip=>T("AddWebsiteFolderToolTip"); ///"New File" public static string AddWebsiteFileTitle=>T("AddWebsiteFileTitle"); ///"Create new file" public static string AddWebsiteFileToolTip=>T("AddWebsiteFileToolTip"); ///"Delete File" public static string DeleteWebsiteFileTitle=>T("DeleteWebsiteFileTitle"); ///"Delete file" public static string DeleteWebsiteFileToolTip=>T("DeleteWebsiteFileToolTip"); ///"Download" public static string DownloadFileTitle=>T("DownloadFileTitle"); ///"Download file" public static string DownloadFileToolTip=>T("DownloadFileToolTip"); ///"Delete Folder" public static string DeleteWebsiteFolderTitle=>T("DeleteWebsiteFolderTitle"); ///"Delete folder" public static string DeleteWebsiteFolderToolTip=>T("DeleteWebsiteFolderToolTip"); ///"Edit File" public static string EditWebsiteFileTitle=>T("EditWebsiteFileTitle"); ///"Edit file" public static string EditWebsiteFileToolTip=>T("EditWebsiteFileToolTip"); ///"Upload File" public static string UploadWebsiteFileTitle=>T("UploadWebsiteFileTitle"); ///"Upload file" public static string UploadWebsiteFileToolTip=>T("UploadWebsiteFileToolTip"); ///"Show in "{0}"" public static string AddFolderToWhiteListTitle_Template=>T("AddFolderToWhiteListTitle"); ///"Show in "{0}"" public static string AddFolderToWhiteListTitle(object parameter0)=>string.Format(T("AddFolderToWhiteListTitle"), parameter0); ///"Control if this folder should be visible in "{0}"" public static string AddFolderToWhiteListToolTip_Template=>T("AddFolderToWhiteListToolTip"); ///"Control if this folder should be visible in "{0}"" public static string AddFolderToWhiteListToolTip(object parameter0)=>string.Format(T("AddFolderToWhiteListToolTip"), parameter0); ///"Show in "{0}"" public static string RemoveFolderFromWhiteListTitle_Template=>T("RemoveFolderFromWhiteListTitle"); ///"Show in "{0}"" public static string RemoveFolderFromWhiteListTitle(object parameter0)=>string.Format(T("RemoveFolderFromWhiteListTitle"), parameter0); ///"Control if this folder should be visible in "{0}"" public static string RemoveFolderFromWhiteListToolTip_Template=>T("RemoveFolderFromWhiteListToolTip"); ///"Control if this folder should be visible in "{0}"" public static string RemoveFolderFromWhiteListToolTip(object parameter0)=>string.Format(T("RemoveFolderFromWhiteListToolTip"), parameter0); ///"Error" public static string DeleteWebsiteFileWorkflow_DeleteErrorTitle=>T("DeleteWebsiteFileWorkflow.DeleteErrorTitle"); ///"Could not delete the file" public static string DeleteWebsiteFileWorkflow_DeleteErrorMessage=>T("DeleteWebsiteFileWorkflow.DeleteErrorMessage"); ///"Error" public static string DeleteWebsiteFolderWorkflow_DeleteErrorTitle=>T("DeleteWebsiteFolderWorkflow.DeleteErrorTitle"); ///"Could not delete the folder" public static string DeleteWebsiteFolderWorkflow_DeleteErrorMessage=>T("DeleteWebsiteFolderWorkflow.DeleteErrorMessage"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Plugins_XsltBasedFunction { ///"XSLT Functions" public static string Plugins_XsltBasedFunctionProviderElementProvider_RootFolderLabel=>T("Plugins.XsltBasedFunctionProviderElementProvider.RootFolderLabel"); ///"XSLT functions" public static string Plugins_XsltBasedFunctionProviderElementProvider_RootFolderToolTip=>T("Plugins.XsltBasedFunctionProviderElementProvider.RootFolderToolTip"); ///"An XSLT function with the same name already exists." public static string AddNewXsltFunctionWorkflow_DuplicateName=>T("AddNewXsltFunctionWorkflow.DuplicateName"); ///"Method name must be non-empty" public static string AddNewXsltFunctionWorkflow_MethodEmpty=>T("AddNewXsltFunctionWorkflow.MethodEmpty"); ///"Namespace must be non-empty" public static string AddNewXsltFunctionWorkflow_NamespaceEmpty=>T("AddNewXsltFunctionWorkflow.NamespaceEmpty"); ///"Namespace must be like A.B.C - not start and end with ." public static string AddNewXsltFunctionWorkflow_InvalidNamespace=>T("AddNewXsltFunctionWorkflow.InvalidNamespace"); ///"A language is required" public static string AddNewXsltFunctionWorkflow_MissingActiveLanguageTitle=>T("AddNewXsltFunctionWorkflow.MissingActiveLanguageTitle"); ///"To create a XSLT function a language is required, but no languages have been added yet. You can add one under the System perspective." public static string AddNewXsltFunctionWorkflow_MissingActiveLanguageMessage=>T("AddNewXsltFunctionWorkflow.MissingActiveLanguageMessage"); ///"A page is required" public static string AddNewXsltFunctionWorkflow_MissingPageTitle=>T("AddNewXsltFunctionWorkflow.MissingPageTitle"); ///"To create a XSLT function at least one page has to be added." public static string AddNewXsltFunctionWorkflow_MissingPageMessage=>T("AddNewXsltFunctionWorkflow.MissingPageMessage"); ///"The total length of the name and the namespace is too long (used to name the XSL file)." public static string AddNewXsltFunctionWorkflow_TotalNameTooLang=>T("AddNewXsltFunctionWorkflow.TotalNameTooLang"); ///"Delete XSLT Function?" public static string DeleteXsltFunctionWorkflow_ConfirmDeleteTitle=>T("DeleteXsltFunctionWorkflow.ConfirmDeleteTitle"); ///"Delete the selected XSLT?" public static string DeleteXsltFunctionWorkflow_ConfirmDeleteMessage=>T("DeleteXsltFunctionWorkflow.ConfirmDeleteMessage"); ///"Cascade Delete Error" public static string DeleteXsltFunctionWorkflow_CascadeDeleteErrorTitle=>T("DeleteXsltFunctionWorkflow.CascadeDeleteErrorTitle"); ///"The type is referenced by another type that does not allow cascade deletes. This operation is halted" public static string DeleteXsltFunctionWorkflow_CascadeDeleteErrorMessage=>T("DeleteXsltFunctionWorkflow.CascadeDeleteErrorMessage"); ///"An XSLT function with the same name already exists." public static string EditXsltFunctionWorkflow_DuplicateName=>T("EditXsltFunctionWorkflow.DuplicateName"); ///"The method name must be non-empty" public static string EditXsltFunctionWorkflow_EmptyMethodName=>T("EditXsltFunctionWorkflow.EmptyMethodName"); ///"The namespace must be non-empty" public static string EditXsltFunctionWorkflow_NamespaceEmpty=>T("EditXsltFunctionWorkflow.NamespaceEmpty"); ///"The namespace must be like A.B.C - not start and end with '.' (period)" public static string EditXsltFunctionWorkflow_InvalidNamespace=>T("EditXsltFunctionWorkflow.InvalidNamespace"); ///"XslFilePath must start with \ or /" public static string EditXsltFunctionWorkflow_InvalidFileName=>T("EditXsltFunctionWorkflow.InvalidFileName"); ///"Invalid function name" public static string EditXsltFunctionWorkflow_InvalidName=>T("EditXsltFunctionWorkflow.InvalidName"); ///"Cannot rename the function, file '{0}' already exists." public static string EditXsltFunctionWorkflow_CannotRenameFileExists_Template=>T("EditXsltFunctionWorkflow.CannotRenameFileExists"); ///"Cannot rename the function, file '{0}' already exists." public static string EditXsltFunctionWorkflow_CannotRenameFileExists(object parameter0)=>string.Format(T("EditXsltFunctionWorkflow.CannotRenameFileExists"), parameter0); ///"The total length of the name and the namespace is too long (used to name the XSL file)." public static string EditXsltFunctionWorkflow_TotalNameTooLang=>T("EditXsltFunctionWorkflow.TotalNameTooLang"); ///"Duplicate local function names" public static string EditXsltFunctionWorkflow_SameLocalFunctionNameClashTitle=>T("EditXsltFunctionWorkflow.SameLocalFunctionNameClashTitle"); ///"Two or more function calls has the same local name. Change the names so that all are different." public static string EditXsltFunctionWorkflow_SameLocalFunctionNameClashMessage=>T("EditXsltFunctionWorkflow.SameLocalFunctionNameClashMessage"); ///"Add XSLT Function" public static string XsltBasedFunctionProviderElementProvider_Add=>T("XsltBasedFunctionProviderElementProvider.Add"); ///"Add new XSLT function" public static string XsltBasedFunctionProviderElementProvider_AddToolTip=>T("XsltBasedFunctionProviderElementProvider.AddToolTip"); ///"Edit" public static string XsltBasedFunctionProviderElementProvider_Edit=>T("XsltBasedFunctionProviderElementProvider.Edit"); ///"Edit XSLT function" public static string XsltBasedFunctionProviderElementProvider_EditToolTip=>T("XsltBasedFunctionProviderElementProvider.EditToolTip"); ///"Delete" public static string XsltBasedFunctionProviderElementProvider_Delete=>T("XsltBasedFunctionProviderElementProvider.Delete"); ///"Delete XSLT function" public static string XsltBasedFunctionProviderElementProvider_DeleteToolTip=>T("XsltBasedFunctionProviderElementProvider.DeleteToolTip"); ///"Add New XSLT Function" public static string AddNewXsltFunctionStep1_LabelDialog=>T("AddNewXsltFunctionStep1.LabelDialog"); ///"Name" public static string AddNewXsltFunctionStep1_LabelName=>T("AddNewXsltFunctionStep1.LabelName"); ///"" public static string AddNewXsltFunctionStep1_HelpName=>T("AddNewXsltFunctionStep1.HelpName"); ///"Namespace" public static string AddNewXsltFunctionStep1_LabelNamespace=>T("AddNewXsltFunctionStep1.LabelNamespace"); ///"" public static string AddNewXsltFunctionStep1_HelpNamespace=>T("AddNewXsltFunctionStep1.HelpNamespace"); ///"Output type" public static string AddNewXsltFunctionStep1_LabelOutputType=>T("AddNewXsltFunctionStep1.LabelOutputType"); ///"Copy from" public static string AddNewXsltFunctionStep1_LabelCopyFrom=>T("AddNewXsltFunctionStep1.LabelCopyFrom"); ///"(New XSLT function)" public static string AddNewXsltFunctionStep1_LabelCopyFromEmptyOption=>T("AddNewXsltFunctionStep1.LabelCopyFromEmptyOption"); ///"Settings" public static string EditXsltFunction_LabelSettings=>T("EditXsltFunction.LabelSettings"); ///"Name" public static string EditXsltFunction_LabelName=>T("EditXsltFunction.LabelName"); ///"" public static string EditXsltFunction_HelpName=>T("EditXsltFunction.HelpName"); ///"Namespace" public static string EditXsltFunction_LabelNamespace=>T("EditXsltFunction.LabelNamespace"); ///"" public static string EditXsltFunction_HelpNamespace=>T("EditXsltFunction.HelpNamespace"); ///"Description" public static string EditXsltFunction_LabelDescription=>T("EditXsltFunction.LabelDescription"); ///"" public static string EditXsltFunction_HelpDescription=>T("EditXsltFunction.HelpDescription"); ///"Debug" public static string EditXsltFunction_LabelDebug=>T("EditXsltFunction.LabelDebug"); ///"Page" public static string EditXsltFunction_LabelPage=>T("EditXsltFunction.LabelPage"); ///"When debugging, this page is used as context for the rendering." public static string EditXsltFunction_HelpPage=>T("EditXsltFunction.HelpPage"); ///"Administrative" public static string EditXsltFunction_LabelAdminitrativeScope=>T("EditXsltFunction.LabelAdminitrativeScope"); ///"Public" public static string EditXsltFunction_LabelPublicScope=>T("EditXsltFunction.LabelPublicScope"); ///"Data scope" public static string EditXsltFunction_LabelPageDataScope=>T("EditXsltFunction.LabelPageDataScope"); ///"Choose public or development version as context for the rendering." public static string EditXsltFunction_HelpPageDataScope=>T("EditXsltFunction.HelpPageDataScope"); ///"Language" public static string EditXsltFunction_LabelActiveLocales=>T("EditXsltFunction.LabelActiveLocales"); ///"Select language to be used while debugging the function." public static string EditXsltFunction_HelpActiveLocales=>T("EditXsltFunction.HelpActiveLocales"); ///"Output type" public static string EditXsltFunction_OutputType=>T("EditXsltFunction.OutputType"); ///"Input Parameters" public static string EditXsltFunction_LabelInputParameters=>T("EditXsltFunction.LabelInputParameters"); ///"Function Calls" public static string EditXsltFunction_LabelFunctionCalls=>T("EditXsltFunction.LabelFunctionCalls"); ///"Template" public static string EditXsltFunction_LabelTemplate=>T("EditXsltFunction.LabelTemplate"); ///"Preview" public static string EditXsltFunction_LabelPreview=>T("EditXsltFunction.LabelPreview"); ///"A Language Is Required" public static string EditXsltFunctionWorkflow_MissingActiveLanguageTitle=>T("EditXsltFunctionWorkflow.MissingActiveLanguageTitle"); ///"To edit a XSLT function a language is required, but no languages have been added yet. You can add one under the System perspective." public static string EditXsltFunctionWorkflow_MissingActiveLanguageMessage=>T("EditXsltFunctionWorkflow.MissingActiveLanguageMessage"); ///"A Page Is Required" public static string EditXsltFunctionWorkflow_MissingPageTitle=>T("EditXsltFunctionWorkflow.MissingPageTitle"); ///"To edit a XSLT function at least one page has to be added." public static string EditXsltFunctionWorkflow_MissingPageMessage=>T("EditXsltFunctionWorkflow.MissingPageMessage"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Plugins.XsltBasedFunction", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Search { ///"Search" public static string SearchPerspective_Label=>T("SearchPerspective.Label"); ///"Search here..." public static string SearchPage_SearchHerePlaceholder=>T("SearchPage.SearchHerePlaceholder"); ///"No results found for '{0}'" public static string SearchPage_NoResultFound_Template=>T("SearchPage.NoResultFound"); ///"No results found for '{0}'" public static string SearchPage_NoResultFound(object parameter0)=>string.Format(T("SearchPage.NoResultFound"), parameter0); ///"1 result found for '{0}'" public static string SearchPage_SingleResultFound_Template=>T("SearchPage.SingleResultFound"); ///"1 result found for '{0}'" public static string SearchPage_SingleResultFound(object parameter0)=>string.Format(T("SearchPage.SingleResultFound"), parameter0); ///"{1} results for '{0}'" public static string SearchPage_MultipleResultsFound_Template=>T("SearchPage.MultipleResultsFound"); ///"{1} results for '{0}'" public static string SearchPage_MultipleResultsFound(object parameter0,object parameter1)=>string.Format(T("SearchPage.MultipleResultsFound"), parameter0,parameter1); ///"Page" public static string DataType_Page=>T("DataType.Page"); ///"Media File" public static string DataType_MediaFile=>T("DataType.MediaFile"); ///"Page Type" public static string FieldNames_PageTypeId=>T("FieldNames.PageTypeId"); ///"Label" public static string FieldNames_Label=>T("FieldNames.Label"); ///"Description" public static string FieldNames_Description=>T("FieldNames.Description"); ///"Data Type" public static string FieldNames_DataType=>T("FieldNames.DataType"); ///"Last Updated" public static string FieldNames_LastUpdated=>T("FieldNames.LastUpdated"); ///"Updated By" public static string FieldNames_UpdatedBy=>T("FieldNames.UpdatedBy"); ///"Publication Status" public static string FieldNames_PublicationStatus=>T("FieldNames.PublicationStatus"); ///"Media Type" public static string FieldNames_MimeType=>T("FieldNames.MimeType"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Search", key); /// public static class Untranslated { ///"Search" public const string SearchPerspective_Label="${Composite.Search,SearchPerspective.Label}"; ///"Search here..." public const string SearchPage_SearchHerePlaceholder="${Composite.Search,SearchPage.SearchHerePlaceholder}"; ///"No results found for '{0}'" public const string SearchPage_NoResultFound="${Composite.Search,SearchPage.NoResultFound}"; ///"1 result found for '{0}'" public const string SearchPage_SingleResultFound="${Composite.Search,SearchPage.SingleResultFound}"; ///"{1} results for '{0}'" public const string SearchPage_MultipleResultsFound="${Composite.Search,SearchPage.MultipleResultsFound}"; ///"Page" public const string DataType_Page="${Composite.Search,DataType.Page}"; ///"Media File" public const string DataType_MediaFile="${Composite.Search,DataType.MediaFile}"; ///"Page Type" public const string FieldNames_PageTypeId="${Composite.Search,FieldNames.PageTypeId}"; ///"Label" public const string FieldNames_Label="${Composite.Search,FieldNames.Label}"; ///"Description" public const string FieldNames_Description="${Composite.Search,FieldNames.Description}"; ///"Data Type" public const string FieldNames_DataType="${Composite.Search,FieldNames.DataType}"; ///"Last Updated" public const string FieldNames_LastUpdated="${Composite.Search,FieldNames.LastUpdated}"; ///"Updated By" public const string FieldNames_UpdatedBy="${Composite.Search,FieldNames.UpdatedBy}"; ///"Publication Status" public const string FieldNames_PublicationStatus="${Composite.Search,FieldNames.PublicationStatus}"; ///"Media Type" public const string FieldNames_MimeType="${Composite.Search,FieldNames.MimeType}"; }} /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Web_FormControl_FunctionCallsDesigner { ///"Function Properties" public static string DialogTitle=>T("DialogTitle"); ///"Function result local name" public static string FunctionLocalNameGroupLabel=>T("FunctionLocalNameGroupLabel"); ///"Local name" public static string FunctionLocalNameLabel=>T("FunctionLocalNameLabel"); ///"If you include a function multiple times this field can help you distinguish the individual results by their local name. " public static string FunctionLocalNameHelp=>T("FunctionLocalNameHelp"); ///"Parameter Value" public static string ParameterValueLabel=>T("ParameterValueLabel"); ///"Select Function" public static string AddNewFunctionDialogLabel=>T("AddNewFunctionDialogLabel"); ///"Select Function" public static string SetNewFunctionDialogLabel=>T("SetNewFunctionDialogLabel"); ///"Value for parameter '{0}'" public static string ComplexFunctionCallDialogLabel_Template=>T("ComplexFunctionCallDialogLabel"); ///"Value for parameter '{0}'" public static string ComplexFunctionCallDialogLabel(object parameter0)=>string.Format(T("ComplexFunctionCallDialogLabel"), parameter0); ///"Parameter Type" public static string ParameterTypeLabel=>T("ParameterTypeLabel"); ///"Parameter Name" public static string ParameterNameLabel=>T("ParameterNameLabel"); ///"Return type" public static string ReturnTypeLabel=>T("ReturnTypeLabel"); ///"Validation failed" public static string ValidationFailedAlertTitle=>T("ValidationFailedAlertTitle"); ///"Function '{0}' does not exist." public static string FunctionNotFound_Template=>T("FunctionNotFound"); ///"Function '{0}' does not exist." public static string FunctionNotFound(object parameter0)=>string.Format(T("FunctionNotFound"), parameter0); ///"Required parameter '{0}' has not been defined." public static string RequiredParameterNotDefined_Template=>T("RequiredParameterNotDefined"); ///"Required parameter '{0}' has not been defined." public static string RequiredParameterNotDefined(object parameter0)=>string.Format(T("RequiredParameterNotDefined"), parameter0); ///"Incorrect type cast. Parameter name: '{0}', function name: '{1}'." public static string IncorrectTypeCast_Template=>T("IncorrectTypeCast"); ///"Incorrect type cast. Parameter name: '{0}', function name: '{1}'." public static string IncorrectTypeCast(object parameter0,object parameter1)=>string.Format(T("IncorrectTypeCast"), parameter0,parameter1); ///"Default" public static string ParameterTypeDefaultLabel=>T("ParameterTypeDefaultLabel"); ///"Constant" public static string ParameterTypeConstantLabel=>T("ParameterTypeConstantLabel"); ///"Input Parameter" public static string ParameterTypeInputParameterLabel=>T("ParameterTypeInputParameterLabel"); ///"Function" public static string ParameterTypeFunctionLabel=>T("ParameterTypeFunctionLabel"); ///"Add New" public static string AddNewButtonLabel=>T("AddNewButtonLabel"); ///"Delete" public static string DeleteButtonLabel=>T("DeleteButtonLabel"); ///"Set New" public static string SetNewButtonLabel=>T("SetNewButtonLabel"); ///"Source" public static string ToolBar_LabelSource=>T("ToolBar.LabelSource"); ///"Design" public static string ToolBar_LabelDesign=>T("ToolBar.LabelDesign"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Web.FormControl.FunctionCallsDesigner", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Web_FormControl_FunctionParameterDesigner { ///"Add New" public static string AddNewButtonLabel=>T("AddNewButtonLabel"); ///"Delete" public static string DeleteButtonLabel=>T("DeleteButtonLabel"); ///"List of input parameters" public static string TreeRootNodeLabel=>T("TreeRootNodeLabel"); ///"Parameter naming and help" public static string ParameterNamingGroupLabel=>T("ParameterNamingGroupLabel"); ///"Parameter name" public static string Name=>T("Name"); ///"The name of the parameter. The name is used by the system to identify this parameter. Names must be unique and may not contain spaces and other special characters. Use names like 'Title', 'StartDate', 'LargeImage' etc." public static string NameHelp=>T("NameHelp"); ///"Label" public static string Label=>T("Label"); ///"The text that users should see when specifying a value for this parameter. This is the 'human name' for the parameter." public static string LabelHelp=>T("LabelHelp"); ///"Help" public static string Help=>T("Help"); ///"Write a short text that tells the user what to do with the parameter." public static string HelpHelp=>T("HelpHelp"); ///"Parameter type and values" public static string ParameterTypeValueGroupLabel=>T("ParameterTypeValueGroupLabel"); ///"Parameter type" public static string Type=>T("Type"); ///"The type of this parameter." public static string TypeHelp=>T("TypeHelp"); ///"Default value" public static string DefaultValue=>T("DefaultValue"); ///"You can specify a default value for this parameter. If a parameter has a default value, users are not required to specify it when calling the function." public static string DefaultValueHelp=>T("DefaultValueHelp"); ///"Specify default value" public static string DefaultValueSpecify=>T("DefaultValueSpecify"); ///"Edit default value" public static string DefaultValueEdit=>T("DefaultValueEdit"); ///"Parameter Default Value" public static string DefaultValueDialogLabel=>T("DefaultValueDialogLabel"); ///"Test value" public static string TestValue=>T("TestValue"); ///"When previewing you can test with different input parameter values using this field. If this is left blank, the default value will be used for previews." public static string TestValueHelp=>T("TestValueHelp"); ///"Specify test value" public static string TestValueSpecify=>T("TestValueSpecify"); ///"Edit test value" public static string TestValueEdit=>T("TestValueEdit"); ///"Parameter Test Value" public static string TestValueDialogLabel=>T("TestValueDialogLabel"); ///"Parameter presentation" public static string ParameterPresentationGroupLabel=>T("ParameterPresentationGroupLabel"); ///"Widget" public static string Widget=>T("Widget"); ///"You can select which type of input widget (like a textbox) to use when specifying a value for this parameter. Widgets are only available for simple types." public static string WidgetHelp=>T("WidgetHelp"); ///"(no widget specified)" public static string NoWidgetSpecifiedLabel=>T("NoWidgetSpecifiedLabel"); ///"Parameter Widget" public static string WidgetDialogLabel=>T("WidgetDialogLabel"); ///"Position" public static string Position=>T("Position"); ///"Last" public static string PositionLast=>T("PositionLast"); ///"The position of the parameter. This controls the order of the parameters." public static string PositionHelp=>T("PositionHelp"); ///"Remember to specify a widget..." public static string SpecifyWidgetTip=>T("SpecifyWidgetTip"); ///"The specified name is not valid." public static string FieldNameSyntaxInvalid=>T("FieldNameSyntaxInvalid"); ///"Can not save... Another parameter has the same name. Please change the name." public static string CannotSave=>T("CannotSave"); ///"Invalid name. Parameter names can not contain spaces. You can write a readable name in the Label field below." public static string SpaceInNameError=>T("SpaceInNameError"); ///"Parameter names can not be empty. Please specify a name." public static string NameEmptyError=>T("NameEmptyError"); ///"Another parameter uses this name. Parameter names must be unique." public static string NameAlreadyInUseError=>T("NameAlreadyInUseError"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Web.FormControl.FunctionParameterDesigner", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Web_FormControl_TypeFieldDesigner { ///"Basic" public static string BasicTabLabel=>T("BasicTabLabel"); ///"Advanced" public static string AdvancedTabLabel=>T("AdvancedTabLabel"); ///"Add New" public static string AddNewButtonLabel=>T("AddNewButtonLabel"); ///"Delete" public static string DeleteButtonLabel=>T("DeleteButtonLabel"); ///"Datatype Fields" public static string LabelDataTypeFields=>T("LabelDataTypeFields"); ///"Key field properties" public static string KeyFieldDetailsGroupLabel=>T("KeyFieldDetailsGroupLabel"); ///"Key field type" public static string KeyFieldType=>T("KeyFieldType"); ///"The data type of the key field. Guid fields feature optimal performance, string key fields are usefull when the id values have to be exposed in urls." public static string KeyFieldTypeHelp=>T("KeyFieldTypeHelp"); ///"Field properties" public static string FieldDetailsGroupLabel=>T("FieldDetailsGroupLabel"); ///"Name" public static string Name=>T("Name"); ///"The name of the field is used by the system to identify this field. Names must be unique and can not contain spaces and other special characters. Use names like 'Title', 'StartDate', 'LargeImage' etc." public static string NameHelp=>T("NameHelp"); ///"Label" public static string Label=>T("Label"); ///"Label text are showed to users when adding a new item based on the datatype." public static string LabelHelp=>T("LabelHelp"); ///"Help" public static string Help=>T("Help"); ///"Use this entry for a short help text to the user." public static string HelpHelp=>T("HelpHelp"); ///"Field type and requirements" public static string FieldTypeGroupLabel=>T("FieldTypeGroupLabel"); ///"Field type" public static string FieldType=>T("FieldType"); ///"Select a data type for the field. The type determine which kind of data the field can hold." public static string FieldTypeHelp=>T("FieldTypeHelp"); ///"String" public static string System_String=>T("System.String"); ///"Integer" public static string System_Int32=>T("System.Int32"); ///"Decimal number" public static string System_Decimal=>T("System.Decimal"); ///"Date" public static string System_DateTime=>T("System.DateTime"); ///"Boolean" public static string System_Boolean=>T("System.Boolean"); ///"Unique Identifier (GUID)" public static string System_Guid=>T("System.Guid"); ///"Data reference" public static string Reference=>T("Reference"); ///"Use this field to further configure your selected type." public static string TypeDetailsHelp=>T("TypeDetailsHelp"); ///"Optional" public static string Optional=>T("Optional"); ///"Optional fields may be left blank." public static string OptionalHelp=>T("OptionalHelp"); ///"No" public static string OptionalFalseLabel=>T("OptionalFalseLabel"); ///"Yes" public static string OptionalTrueLabel=>T("OptionalTrueLabel"); ///"Validation rules" public static string ValidationRules=>T("ValidationRules"); ///"You can specify strict rules on the data that is entered in this field, i.e. "must be at least 5 characters long", "must be a valid e-mail address", "must be a date in the past" etc." public static string ValidationRulesHelp=>T("ValidationRulesHelp"); ///"Add validation rules..." public static string ValidationRulesAdd=>T("ValidationRulesAdd"); ///"Edit validation rules" public static string ValidationRulesEdit=>T("ValidationRulesEdit"); ///"Field Validation Rules Configuration" public static string ValidationRulesDialogLabel=>T("ValidationRulesDialogLabel"); ///"Field validation" public static string FieldValidationGroupLabel=>T("FieldValidationGroupLabel"); ///"Form field presentation" public static string FieldPresentationGroupLabel=>T("FieldPresentationGroupLabel"); ///"Structural presentation" public static string FieldStructureGroupLabel=>T("FieldStructureGroupLabel"); ///"Widget type" public static string Widget=>T("Widget"); ///"You can select which type of input widget (like a textbox) to use when editing this field." public static string WidgetHelp=>T("WidgetHelp"); ///"Field Widget Configuration" public static string WidgetDialogLabel=>T("WidgetDialogLabel"); ///"Position" public static string Position=>T("Position"); ///"Last" public static string PositionLast=>T("PositionLast"); ///"The position of the field. This controls the order of the fields." public static string PositionHelp=>T("PositionHelp"); ///"Tree grouping" public static string GroupByPriority=>T("GroupByPriority"); ///"(no grouping)..." public static string GroupByPriorityNone=>T("GroupByPriorityNone"); ///"Group by this field" public static string GroupByPriorityFirst=>T("GroupByPriorityFirst"); ///"Group as {0}. priority" public static string GroupByPriorityN_Template=>T("GroupByPriorityN"); ///"Group as {0}. priority" public static string GroupByPriorityN(object parameter0)=>string.Format(T("GroupByPriorityN"), parameter0); ///"You can specify that a field should be used to group data - this can improve readability when viewing long lists. Use priority when multiple fields are used for grouping." public static string GroupByPriorityHelp=>T("GroupByPriorityHelp"); ///"Tree ordering" public static string TreeOrdering=>T("TreeOrdering"); ///"(no ordering)..." public static string TreeOrderingNone=>T("TreeOrderingNone"); ///"Order ascending (A-Z)" public static string TreeOrderingFirstAscending=>T("TreeOrderingFirstAscending"); ///"Order descending (Z-A)" public static string TreeOrderingFirstDescending=>T("TreeOrderingFirstDescending"); ///"Order {0}. ascending" public static string TreeOrderingNAscending_Template=>T("TreeOrderingNAscending"); ///"Order {0}. ascending" public static string TreeOrderingNAscending(object parameter0)=>string.Format(T("TreeOrderingNAscending"), parameter0); ///"Order {0}. descending" public static string TreeOrderingNDescending_Template=>T("TreeOrderingNDescending"); ///"Order {0}. descending" public static string TreeOrderingNDescending(object parameter0)=>string.Format(T("TreeOrderingNDescending"), parameter0); ///"You can specify that a field should be used to order data in the tree view - this can improve readability when a field is used to position elements on the website." public static string TreeOrderingHelp=>T("TreeOrderingHelp"); ///"Is title field" public static string IsTitleField=>T("IsTitleField"); ///"Check this if you wish this field to be used as the title field. Title fields are used when listing data, like in the tree to the left." public static string IsTitleFieldHelp=>T("IsTitleFieldHelp"); ///"Use this as title field in lists" public static string IsTitleFieldLabel=>T("IsTitleFieldLabel"); ///"Field default value" public static string DefaultValueGroupLabel=>T("DefaultValueGroupLabel"); ///"Default value" public static string DefaultValue=>T("DefaultValue"); ///"You can define a default value for this field." public static string DefaultValueHelp=>T("DefaultValueHelp"); ///"Field default value configuration" public static string DefaultValueDialogLabel=>T("DefaultValueDialogLabel"); ///"Data url" public static string DataUrlGroupLabel=>T("DataUrlGroupLabel"); ///"Field appears in data url" public static string AppearsInUrlLabel=>T("AppearsInUrlLabel"); ///"Use in data urls" public static string AppearsInUrlItemLabel=>T("AppearsInUrlItemLabel"); ///"When checked the field will appear in data urls" public static string AppearsInUrlHelp=>T("AppearsInUrlHelp"); ///"Order" public static string DataUrlOrderLabel=>T("DataUrlOrderLabel"); ///"Order in which the field appear in data url route" public static string DataUrlOrderHelp=>T("DataUrlOrderHelp"); ///"Format" public static string DataUrlDateFormatLabel=>T("DataUrlDateFormatLabel"); ///"Chose in what format the date field will appear in url" public static string DataUrlDateFormatHelp=>T("DataUrlDateFormatHelp"); ///"Year" public static string DataUrlDateFormat_Year=>T("DataUrlDateFormat_Year"); ///"Month" public static string DataUrlDateFormat_Month=>T("DataUrlDateFormat_Month"); ///"Day" public static string DataUrlDateFormat_Day=>T("DataUrlDateFormat_Day"); ///"String maximum length" public static string StringMaximumLength=>T("StringMaximumLength"); ///"16 character maximum" public static string _16CharMax=>T("16CharMax"); ///"32 character maximum" public static string _32CharMax=>T("32CharMax"); ///"64 character maximum" public static string _64CharMax=>T("64CharMax"); ///"128 character maximum" public static string _128CharMax=>T("128CharMax"); ///"256 character maximum" public static string _256CharMax=>T("256CharMax"); ///"512 character maximum" public static string _512CharMax=>T("512CharMax"); ///"1024 character maximum" public static string _1024CharMax=>T("1024CharMax"); ///"Unlimited length" public static string Unlimited=>T("Unlimited"); ///"Search" public static string SearchGroupLabel=>T("SearchGroupLabel"); ///"Text Search" public static string Search_TextSearch=>T("Search.TextSearch"); ///"Index text content" public static string Search_IndexText_Label=>T("Search.IndexText.Label"); ///"When checked, the text content of the field will be searchable." public static string Search_IndexText_Help=>T("Search.IndexText.Help"); ///"Search Results" public static string Search_SearchResults=>T("Search.SearchResults"); ///"Enable field preview" public static string Search_FieldPreview_Label=>T("Search.FieldPreview.Label"); ///"When checked, the field will appear in the search results table as a column." public static string Search_FieldPreview_Help=>T("Search.FieldPreview.Help"); ///"Faceted Search" public static string Search_FacetedSearch=>T("Search.FacetedSearch"); ///"Enable faceted search" public static string Search_Facet_Label=>T("Search.Facet.Label"); ///"When checked, the field will appear in search results as a facet." public static string Search_Facet_Help=>T("Search.Facet.Help"); ///"Decimal number format" public static string DecimalNumberFormat=>T("DecimalNumberFormat"); ///"1 decimal place" public static string _1DecimalPlace=>T("1DecimalPlace"); ///"{0} decimal places" public static string nDecimalPlaces_Template=>T("nDecimalPlaces"); ///"{0} decimal places" public static string nDecimalPlaces(object parameter0)=>string.Format(T("nDecimalPlaces"), parameter0); ///"Reference Type" public static string ReferenceType=>T("ReferenceType"); ///"The specified name is not valid." public static string FieldNameSyntaxInvalid=>T("FieldNameSyntaxInvalid"); ///"Can not save... Another Field has the same name. Please change the name." public static string CannotSave=>T("CannotSave"); ///"Invalid name. Data field names can not contain spaces. You can write a readable name in the Label field below." public static string SpaceInNameError=>T("SpaceInNameError"); ///"Data field names can not be empty. Please specify a name." public static string NameEmptyError=>T("NameEmptyError"); ///"Another field uses this name. Data field names must be unique." public static string NameAlreadyInUseError=>T("NameAlreadyInUseError"); ///"The selected type can not be optional." public static string NotAnOptionalTypeError=>T("NotAnOptionalTypeError"); ///"Remember to specify a widget..." public static string NoWidgetSelected=>T("NoWidgetSelected"); ///"(no widget specified)" public static string NoWidgetSelectedLabel=>T("NoWidgetSelectedLabel"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Web.FormControl.TypeFieldDesigner", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Web_PageBrowser { ///"Page source" public static string Menu_ViewSource=>T("Menu.ViewSource"); ///"View mode" public static string Menu_ViewMode=>T("Menu.ViewMode"); ///"Back" public static string ContextMenu_Back=>T("ContextMenu.Back"); ///"Forward" public static string ContextMenu_Forward=>T("ContextMenu.Forward"); ///"Refresh" public static string ContextMenu_Refresh=>T("ContextMenu.Refresh"); ///"View Page Source" public static string ContextMenu_ViewSource=>T("ContextMenu.ViewSource"); ///"Go back one page" public static string ToolBarButton_Back_ToolTip=>T("ToolBarButton.Back.ToolTip"); ///"Go forward one page" public static string ToolBarButton_Forward_ToolTip=>T("ToolBarButton.Forward.ToolTip"); ///"Refresh page" public static string ToolBarButton_Refresh_ToolTip=>T("ToolBarButton.Refresh.ToolTip"); ///"Show Tree" public static string ToolBarButton_TreeView_ToolTip=>T("ToolBarButton.TreeView.ToolTip"); ///"Go to the address in the location bar" public static string ToolBarButton_Go_ToolTip=>T("ToolBarButton.Go.ToolTip"); ///"Go to the Start page" public static string ToolBarButton_Home_ToolTip=>T("ToolBarButton.Home.ToolTip"); ///"Access denied" public static string AddressBar_Invalid_DialogTitle_External=>T("AddressBar.Invalid.DialogTitle.External"); ///"External URL cannot loaded." public static string AddressBar_Invalid_DialogText_External=>T("AddressBar.Invalid.DialogText.External"); ///"Bad URL" public static string AddressBar_Invalid_DialogTitle_BadRequest=>T("AddressBar.Invalid.DialogTitle.BadRequest"); ///"The URL is invalid and cannot be loaded." public static string AddressBar_Invalid_DialogText_BadRequest=>T("AddressBar.Invalid.DialogText.BadRequest"); ///"Not authorized" public static string AddressBar_Invalid_DialogTitle_Unauthorized=>T("AddressBar.Invalid.DialogTitle.Unauthorized"); ///"You are not authorized to view the page on specified URL." public static string AddressBar_Invalid_DialogText_Unauthorized=>T("AddressBar.Invalid.DialogText.Unauthorized"); ///"Page not found" public static string AddressBar_Invalid_DialogTitle_NotFound=>T("AddressBar.Invalid.DialogTitle.NotFound"); ///"Page not found on the specified URL." public static string AddressBar_Invalid_DialogText_NotFound=>T("AddressBar.Invalid.DialogText.NotFound"); ///"Server error" public static string AddressBar_Invalid_DialogTitle_InternalError=>T("AddressBar.Invalid.DialogTitle.InternalError"); ///"The server has reported an error on the specified URL. The page cannot be loaded." public static string AddressBar_Invalid_DialogText_InternalError=>T("AddressBar.Invalid.DialogText.InternalError"); ///"Page not loaded" public static string AddressBar_Invalid_DialogTitle_Default=>T("AddressBar.Invalid.DialogTitle.Default"); ///"An error prevents the URL from being loaded." public static string AddressBar_Invalid_DialogText_Default=>T("AddressBar.Invalid.DialogText.Default"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Web.PageBrowser", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Web_SEOAssistant { ///"SEO Assistant" public static string SEOAssistant=>T("SEOAssistant"); ///"Search engine optimization" public static string SEOAssistant_ToolTip=>T("SEOAssistant.ToolTip"); ///"Generate a page preview to compute the SEO indication." public static string IntroText=>T("IntroText"); ///"Result" public static string TabResult=>T("TabResult"); ///"Keywords" public static string TabKeywords=>T("TabKeywords"); ///"Keywords found in page preview:" public static string ResultHeading=>T("ResultHeading"); ///"No keywords configured." public static string NoKeywordsWarning=>T("NoKeywordsWarning"); ///"In title" public static string isInTitle=>T("isInTitle"); ///"In URL" public static string isInURL=>T("isInURL"); ///"In menu title" public static string isInMenuTitle=>T("isInMenuTitle"); ///"In description" public static string isInDescription=>T("isInDescription"); ///"In heading" public static string isInHeading=>T("isInHeading"); ///"In content" public static string isInContent=>T("isInContent"); ///"No keywords found in page preview" public static string NoKeywords=>T("NoKeywords"); ///"Failed to analyze the keywords because the markup is not valid" public static string IncorrectHtml=>T("IncorrectHtml"); ///"Add SEO word ..." public static string AddKeywordInputPlaceholder=>T("AddKeywordInputPlaceholder"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Web.SEOAssistant", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Web_SourceEditor { ///"Retrieved on SourceEditorBinding startup to make sure strings are loaded :)" public static string Preload_Key=>T("Preload.Key"); ///"Invalid XHTML" public static string Invalid_HTML_DialogTitle=>T("Invalid.HTML.DialogTitle"); ///"The root <html> tag is missing." public static string Invalid_HTML_MissingHtml=>T("Invalid.HTML.MissingHtml"); ///"The <head> tag is missing." public static string Invalid_HTML_MissingHead=>T("Invalid.HTML.MissingHead"); ///"The <body> tag is missing." public static string Invalid_HTML_MissingBody=>T("Invalid.HTML.MissingBody"); ///"The <head> tag must precede <body>." public static string Invalid_HTML_HeadBodyIndex=>T("Invalid.HTML.HeadBodyIndex"); ///"The root namespace is wrong." public static string Invalid_HTML_NamespaceURI=>T("Invalid.HTML.NamespaceURI"); ///"Only one <body> tag allowed." public static string Invalid_HTML_MultipleBody=>T("Invalid.HTML.MultipleBody"); ///"Only one <head> tag allowed." public static string Invalid_HTML_MultipleHead=>T("Invalid.HTML.MultipleHead"); ///"The root <html> tag can only have <head> and <body> tags as children." public static string Invalid_HTML_NotAllowedHtmlChild=>T("Invalid.HTML.NotAllowedHtmlChild"); ///"Source format aborted" public static string Format_XML_ErrorDialog_Title=>T("Format.XML.ErrorDialog.Title"); ///"XML source formatting requires a well-formed document structure." public static string Format_XML_ErrorDialog_Text=>T("Format.XML.ErrorDialog.Text"); ///"Plain Edit" public static string Switch_PlainEdit_Label=>T("Switch.PlainEdit.Label"); ///"No syntax highlight, faster performance" public static string Switch_PlainEdit_ToolTip=>T("Switch.PlainEdit.ToolTip"); ///"Colored Edit" public static string Switch_ColoredEdit_Label=>T("Switch.ColoredEdit.Label"); ///"Syntax highlight, slower performance" public static string Switch_ColoredEdit_ToolTip=>T("Switch.ColoredEdit.ToolTip"); ///"Insert" public static string Toolbar_Insert_Label=>T("Toolbar.Insert.Label"); ///"Format" public static string Toolbar_Format_Label=>T("Toolbar.Format.Label"); ///"Format XML source" public static string Toolbar_Format_ToolTip=>T("Toolbar.Format.ToolTip"); ///"Toggle word wrap" public static string Toolbar_ToggleWordWrap_Label=>T("Toolbar.ToggleWordWrap.Label"); ///"Find and replace" public static string Toolbar_FindAndReplace_Label=>T("Toolbar.FindAndReplace.Label"); ///"Page URL" public static string Insert_PageURL_Label=>T("Insert.PageURL.Label"); ///"Image URL" public static string Insert_ImageURL_Label=>T("Insert.ImageURL.Label"); ///"Media URL" public static string Insert_MediaURL_Label=>T("Insert.MediaURL.Label"); ///"Frontend URL" public static string Insert_FrontendURL_Label=>T("Insert.FrontendURL.Label"); ///"Function Markup" public static string Insert_FunctionMarkup_Label=>T("Insert.FunctionMarkup.Label"); ///"Translate To {0}" public static string ResxEditor_TranslateTo_Label_Template=>T("ResxEditor.TranslateTo.Label"); ///"Translate To {0}" public static string ResxEditor_TranslateTo_Label(object parameter0)=>string.Format(T("ResxEditor.TranslateTo.Label"), parameter0); ///"Translate To {0}" public static string ResxEditor_TranslateTo_Tooltip_Template=>T("ResxEditor.TranslateTo.Tooltip"); ///"Translate To {0}" public static string ResxEditor_TranslateTo_Tooltip(object parameter0)=>string.Format(T("ResxEditor.TranslateTo.Tooltip"), parameter0); ///"Label" public static string ResxEditor_Label=>T("ResxEditor.Label"); ///"Original Text" public static string ResxEditor_OriginalText=>T("ResxEditor.OriginalText"); ///"Translated Text" public static string ResxEditor_TranslatedText=>T("ResxEditor.TranslatedText"); ///"Save" public static string ResxEditor_Save=>T("ResxEditor.Save"); ///"Find and replace" public static string FindAndReplace_LabelTitle=>T("FindAndReplace.LabelTitle"); ///"Find" public static string FindAndReplace_LabelFind=>T("FindAndReplace.LabelFind"); ///"Replace with" public static string FindAndReplace_LabelReplaceWith=>T("FindAndReplace.LabelReplaceWith"); ///"Match case" public static string FindAndReplace_LabelMatchCase=>T("FindAndReplace.LabelMatchCase"); ///"Whole words" public static string FindAndReplace_LabelWholeWords=>T("FindAndReplace.LabelWholeWords"); ///"Find Next" public static string FindAndReplace_ButtonFind=>T("FindAndReplace.ButtonFind"); ///"Replace" public static string FindAndReplace_ButtonReplace=>T("FindAndReplace.ButtonReplace"); ///"Replace all" public static string FindAndReplace_ButtonReplaceAll=>T("FindAndReplace.ButtonReplaceAll"); ///"Find and Replace" public static string FindAndReplace_LaunchButton_Label=>T("FindAndReplace.LaunchButton.Label"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Web.SourceEditor", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Composite_Web_VisualEditor { ///"Retrieved on VisualEditorBinding startup to make sure strings are loaded :)" public static string Preload_Key=>T("Preload.Key"); ///"Strong text" public static string ToolBar_ToolTipStrong=>T("ToolBar.ToolTipStrong"); ///"Emphasize text" public static string ToolBar_ToolTipEmphasize=>T("ToolBar.ToolTipEmphasize"); ///"Underline text" public static string ToolBar_ToolTipUnderline=>T("ToolBar.ToolTipUnderline"); ///"Strike text" public static string ToolBar_ToolTipStrike=>T("ToolBar.ToolTipStrike"); ///"Align left" public static string ToolBar_ToolTipAlignLeft=>T("ToolBar.ToolTipAlignLeft"); ///"Align right" public static string ToolBar_ToolTipAlignRight=>T("ToolBar.ToolTipAlignRight"); ///"Justify left" public static string ToolBar_ToolTipJustifyLeft=>T("ToolBar.ToolTipJustifyLeft"); ///"Justify right" public static string ToolBar_ToolTipJustifyRight=>T("ToolBar.ToolTipJustifyRight"); ///"Justify center" public static string ToolBar_ToolTipJustifyCenter=>T("ToolBar.ToolTipJustifyCenter"); ///"Justify full" public static string ToolBar_ToolTipJustifyFull=>T("ToolBar.ToolTipJustifyFull"); ///"Unordered list" public static string ToolBar_ToolTipUnorderedList=>T("ToolBar.ToolTipUnorderedList"); ///"Ordered list" public static string ToolBar_ToolTipOrderedList=>T("ToolBar.ToolTipOrderedList"); ///"Link" public static string ToolBar_ToolTipLink=>T("ToolBar.ToolTipLink"); ///"Delete link" public static string ToolBar_ToolTipDeleteLink=>T("ToolBar.ToolTipDeleteLink"); ///"Cleanup messy code" public static string ToolBar_ToolTipCleanup=>T("ToolBar.ToolTipCleanup"); ///"Undo" public static string ToolBar_ToolTipUndo=>T("ToolBar.ToolTipUndo"); ///"Redo" public static string ToolBar_ToolTipRedo=>T("ToolBar.ToolTipRedo"); ///"Source" public static string ToolBar_LabelSource=>T("ToolBar.LabelSource"); ///"Visual" public static string ToolBar_LabelWysiwyg=>T("ToolBar.LabelWysiwyg"); ///"Paragraph" public static string FormatSelector_LabelParagraph=>T("FormatSelector.LabelParagraph"); ///"Address" public static string FormatSelector_LabelAddress=>T("FormatSelector.LabelAddress"); ///"Blockquote" public static string FormatSelector_LabelBlockQuote=>T("FormatSelector.LabelBlockQuote"); ///"Division" public static string FormatSelector_LabelDivision=>T("FormatSelector.LabelDivision"); ///"Heading 1" public static string FormatSelector_LabelHeading1=>T("FormatSelector.LabelHeading1"); ///"Heading 2" public static string FormatSelector_LabelHeading2=>T("FormatSelector.LabelHeading2"); ///"Heading 3" public static string FormatSelector_LabelHeading3=>T("FormatSelector.LabelHeading3"); ///"Heading 4" public static string FormatSelector_LabelHeading4=>T("FormatSelector.LabelHeading4"); ///"Heading 5" public static string FormatSelector_LabelHeading5=>T("FormatSelector.LabelHeading5"); ///"Heading 6" public static string FormatSelector_LabelHeading6=>T("FormatSelector.LabelHeading6"); ///"(None)" public static string ClassSelector_LabelNone=>T("ClassSelector.LabelNone"); ///"Insert" public static string ContextMenu_LabelInsert=>T("ContextMenu.LabelInsert"); ///"Paste" public static string ContextMenu_LabelPaste=>T("ContextMenu.LabelPaste"); ///"Link" public static string ContextMenu_LabelLink=>T("ContextMenu.LabelLink"); ///"Unlink" public static string ContextMenu_LabelUnLink=>T("ContextMenu.LabelUnLink"); ///"Link Properties" public static string ContextMenu_LabelLinkProperties=>T("ContextMenu.LabelLinkProperties"); ///"Table…" public static string ContextMenu_LabelTable=>T("ContextMenu.LabelTable"); ///"Manage Table" public static string ContextMenu_LabelTableManage=>T("ContextMenu.LabelTableManage"); ///"Image…" public static string ContextMenu_LabelImage=>T("ContextMenu.LabelImage"); ///"As Simple Text…" public static string ContextMenu_LabelAsText=>T("ContextMenu.LabelAsText"); ///"Field" public static string ContextMenu_LabelField=>T("ContextMenu.LabelField"); ///"Delete Field" public static string ContextMenu_LabelFieldDelete=>T("ContextMenu.LabelFieldDelete"); ///"Function…" public static string ContextMenu_LabelRendering=>T("ContextMenu.LabelRendering"); ///"Character…" public static string ContextMenu_LabelCharacter=>T("ContextMenu.LabelCharacter"); ///"Image Properties…" public static string ContextMenu_LabelImageProperties=>T("ContextMenu.LabelImageProperties"); ///"Function Properties…" public static string ContextMenu_LabelRenderingProperties=>T("ContextMenu.LabelRenderingProperties"); ///"Cut Row" public static string ContextMenu_LabelCutRow=>T("ContextMenu.LabelCutRow"); ///"Copy Row" public static string ContextMenu_LabelCopyRow=>T("ContextMenu.LabelCopyRow"); ///"Paste Row" public static string ContextMenu_LabelPasteRow=>T("ContextMenu.LabelPasteRow"); ///"Before" public static string ContextMenu_LabelBefore=>T("ContextMenu.LabelBefore"); ///"After" public static string ContextMenu_LabelAfter=>T("ContextMenu.LabelAfter"); ///"Table Properties" public static string ContextMenu_LabelTableProperties=>T("ContextMenu.LabelTableProperties"); ///"Cell Properties" public static string ContextMenu_LabelCellProperties=>T("ContextMenu.LabelCellProperties"); ///"Row Properties" public static string ContextMenu_LabelRowProperties=>T("ContextMenu.LabelRowProperties"); ///"Insert Row" public static string ContextMenu_LabelInsertRow=>T("ContextMenu.LabelInsertRow"); ///"Delete Row" public static string ContextMenu_LabelDeleteRow=>T("ContextMenu.LabelDeleteRow"); ///"Insert Column" public static string ContextMenu_LabelInsertcolumn=>T("ContextMenu.LabelInsertcolumn"); ///"Delete Column" public static string ContextMenu_LabelDeleteColumn=>T("ContextMenu.LabelDeleteColumn"); ///"Merge Table Cells" public static string ContextMenu_LabelMergeTableCells=>T("ContextMenu.LabelMergeTableCells"); ///"Split Merged Cells" public static string ContextMenu_LabelSplitMergedCells=>T("ContextMenu.LabelSplitMergedCells"); ///"Delete Table" public static string ContextMenu_LabelDeleteTable=>T("ContextMenu.LabelDeleteTable"); ///"Align Image" public static string ContextMenu_LabelAlignImage=>T("ContextMenu.LabelAlignImage"); ///"Right" public static string ContextMenu_LabelAlignImageRight=>T("ContextMenu.LabelAlignImageRight"); ///"Left" public static string ContextMenu_LabelAlignImageLeft=>T("ContextMenu.LabelAlignImageLeft"); ///"None" public static string ContextMenu_LabelAlignImageNone=>T("ContextMenu.LabelAlignImageNone"); ///"Source code error" public static string ContentError_DialogTitle=>T("ContentError.DialogTitle"); ///"Error in source code:" public static string ContentError_DialogText=>T("ContentError.DialogText"); ///"No placeholders in template." public static string TemplateTree_NoTemplateWarning=>T("TemplateTree.NoTemplateWarning"); ///"Basic" public static string LabelTabBasic=>T("LabelTabBasic"); ///"Advanced" public static string LabelTabAdvanced=>T("LabelTabAdvanced"); ///"Class" public static string LabelClass=>T("LabelClass"); ///"The class attribute specifies a CSS classname for an element." public static string HelpClass=>T("HelpClass"); ///"ID" public static string LabelId=>T("LabelId"); ///"The id attribute can be used by JavaScript or CSS to make changes to an element." public static string HelpId=>T("HelpId"); ///"Clipboard disabled" public static string MozSecurityNote_LabelSecurityStuff=>T("MozSecurityNote.LabelSecurityStuff"); ///"For security reasons, access to the clipboard was blocked by your browser. Please use standard keyboard shortcuts. For a technical description of, how to configure your browser for use with {applicationname}, press the "More Info" button." public static string MozSecurityNote_TextSecurityStuff=>T("MozSecurityNote.TextSecurityStuff"); ///"Insert Link" public static string Link_LabelInsertLink=>T("Link.LabelInsertLink"); ///"Link Properties" public static string Link_LabelLinkProperties=>T("Link.LabelLinkProperties"); ///"URL" public static string Link_LinkDestination=>T("Link.LinkDestination"); ///"Role" public static string Link_LinkRole=>T("Link.LinkRole"); ///"Title" public static string Link_TitleText=>T("Link.TitleText"); ///"Target" public static string Link_LinkTarget=>T("Link.LinkTarget"); ///"Open in new window" public static string Link_LinkTarget_LabelCheckBox=>T("Link.LinkTarget.LabelCheckBox"); ///"The title text is rendered as a tooltip when the mouse hovers over the link. This can be used to let your customers know where the link is going without disturbing the flow of your text." public static string Link_TitleTextToolTip=>T("Link.TitleTextToolTip"); ///"Link properties" public static string Link_LabelLink=>T("Link.LabelLink"); ///"Cell type" public static string Tables_Cell_CellType=>T("Tables.Cell.CellType"); ///"Cell width" public static string Tables_Cell_LabelWidth=>T("Tables.Cell.LabelWidth"); ///"Horizontal alignment" public static string Tables_Cell_HorizontalAlignment=>T("Tables.Cell.HorizontalAlignment"); ///"Vertical alignment" public static string Tables_Cell_VerticalAlignment=>T("Tables.Cell.VerticalAlignment"); ///"Apply changes to" public static string Tables_Cell_ApplyTo=>T("Tables.Cell.ApplyTo"); ///"Cell Properties" public static string Tables_Cell_LabelCellProperties=>T("Tables.Cell.LabelCellProperties"); ///"Layout" public static string Tables_Cell_LabelLayout=>T("Tables.Cell.LabelLayout"); ///"Data Cell" public static string Tables_Cell_LabelDataCell=>T("Tables.Cell.LabelDataCell"); ///"Header Cell" public static string Tables_Cell_LabelHeaderCell=>T("Tables.Cell.LabelHeaderCell"); ///"Left" public static string Tables_Cell_LabelLeft=>T("Tables.Cell.LabelLeft"); ///"Right" public static string Tables_Cell_LabelRight=>T("Tables.Cell.LabelRight"); ///"Top" public static string Tables_Cell_LabelTop=>T("Tables.Cell.LabelTop"); ///"Center" public static string Tables_Cell_LabelCenter=>T("Tables.Cell.LabelCenter"); ///"Bottom" public static string Tables_Cell_LabelBottom=>T("Tables.Cell.LabelBottom"); ///"Scope" public static string Tables_Cell_LabelScope=>T("Tables.Cell.LabelScope"); ///"Current cell" public static string Tables_Cell_LabelCurrentCell=>T("Tables.Cell.LabelCurrentCell"); ///"All cells in row" public static string Tables_Cell_LabelAllRowCells=>T("Tables.Cell.LabelAllRowCells"); ///"All cells in table" public static string Tables_Cell_LabelAllTableCells=>T("Tables.Cell.LabelAllTableCells"); ///"Columns" public static string Tables_Merge_Columns=>T("Tables.Merge.Columns"); ///"Rows" public static string Tables_Merge_Rows=>T("Tables.Merge.Rows"); ///"Merge Table Cells" public static string Tables_Merge_LabelMergeCells=>T("Tables.Merge.LabelMergeCells"); ///"Row in table part" public static string Tables_Row_Rows=>T("Tables.Row.Rows"); ///"Horizontal Alignment" public static string Tables_Row_HorizontalAlignment=>T("Tables.Row.HorizontalAlignment"); ///"Vertical Alignment" public static string Tables_Row_VerticalAlignment=>T("Tables.Row.VerticalAlignment"); ///"Apply changes to" public static string Tables_Row_ApplyTo=>T("Tables.Row.ApplyTo"); ///"Row Properties" public static string Tables_Row_LabelRowProperties=>T("Tables.Row.LabelRowProperties"); ///"Layout" public static string Tables_Row_LabelLayout=>T("Tables.Row.LabelLayout"); ///"Table Head" public static string Tables_Row_LabelTableHead=>T("Tables.Row.LabelTableHead"); ///"Table Body" public static string Tables_Row_LabelTableBody=>T("Tables.Row.LabelTableBody"); ///"Table Foot" public static string Tables_Row_LabelTableFoot=>T("Tables.Row.LabelTableFoot"); ///"Left" public static string Tables_Row_LabelLeft=>T("Tables.Row.LabelLeft"); ///"Center" public static string Tables_Row_LabelCenter=>T("Tables.Row.LabelCenter"); ///"Right" public static string Tables_Row_LabelRight=>T("Tables.Row.LabelRight"); ///"Top" public static string Tables_Row_LabelTop=>T("Tables.Row.LabelTop"); ///"Bottom" public static string Tables_Row_LabelBottom=>T("Tables.Row.LabelBottom"); ///"Scope" public static string Tables_Row_LabelScope=>T("Tables.Row.LabelScope"); ///"Current row" public static string Tables_Row_LabelCurrentRow=>T("Tables.Row.LabelCurrentRow"); ///"Odd rows in table" public static string Tables_Row_LabelOddRows=>T("Tables.Row.LabelOddRows"); ///"Even rows in table" public static string Tables_Row_LabelEvenRows=>T("Tables.Row.LabelEvenRows"); ///"All rows in table" public static string Tables_Row_LabelAllRows=>T("Tables.Row.LabelAllRows"); ///"Insert Table" public static string Tables_Table_TitleInsert=>T("Tables.Table.TitleInsert"); ///"Table Properties" public static string Tables_Table_TitleUpdate=>T("Tables.Table.TitleUpdate"); ///"Columns" public static string Tables_Table_Columns=>T("Tables.Table.Columns"); ///"Rows" public static string Tables_Table_Rows=>T("Tables.Table.Rows"); ///"Summary" public static string Tables_Table_Summary=>T("Tables.Table.Summary"); ///"The summary explains the table content and structure so that people using non-visual browsers (such as blind people) may better understand it. This is especially important for tables without captions." public static string Tables_Table_SummaryHelp=>T("Tables.Table.SummaryHelp"); ///"Table layout" public static string Tables_Table_LabelLayout=>T("Tables.Table.LabelLayout"); ///"Table description" public static string Tables_Table_LabelMeta=>T("Tables.Table.LabelMeta"); ///"Source" public static string Image_Source=>T("Image.Source"); ///"Alternate text" public static string Image_AlternativeText=>T("Image.AlternativeText"); ///"The alternate text is displayed as visible text in browsers where images cannot be rendered normally. This may be the case for mobile phone browsers and special browsers for the visually impaired. The alt attribute should clearly describe the content of the image." public static string Image_AlternativeTextToolTip=>T("Image.AlternativeTextToolTip"); ///"Title text" public static string Image_TitleText=>T("Image.TitleText"); ///"The title text is rendered as a tooltip when the mouse hovers over the image. An image that might be confusing for the viewer can be instantly clarified by a title." public static string Image_TitleTextToolTip=>T("Image.TitleTextToolTip"); ///"Image properties" public static string Image_LabelImage=>T("Image.LabelImage"); ///"Insert Image" public static string Image_LabelInsertImage=>T("Image.LabelInsertImage"); ///"Image Properties" public static string Image_LabelImageProperties=>T("Image.LabelImageProperties"); ///"Maximum Width" public static string Image_MaxWidth=>T("Image.MaxWidth"); ///"If the width of the image is bigger that the specified value, it will be downsized to the specified value." public static string Image_MaxWidthToolTip=>T("Image.MaxWidthToolTip"); ///"Maximum Height" public static string Image_MaxHeight=>T("Image.MaxHeight"); ///"If the height of the image is bigger that the specified value, it will be downsized to the specified value." public static string Image_MaxHeightToolTip=>T("Image.MaxHeightToolTip"); ///"Select Character" public static string CharMap_LabelSelectSpecialChar=>T("CharMap.LabelSelectSpecialChar"); ///"General" public static string CharMap_LabelGeneral=>T("CharMap.LabelGeneral"); ///"Alphabetical" public static string CharMap_LabelAlphabetical=>T("CharMap.LabelAlphabetical"); ///"Math & Symbols" public static string CharMap_LabelMathSymbols=>T("CharMap.LabelMathSymbols"); ///"Common" public static string CharMap_LabelCommon=>T("CharMap.LabelCommon"); ///"Quotation" public static string CharMap_LabelQuotation=>T("CharMap.LabelQuotation"); ///"Currency" public static string CharMap_LabelCurrency=>T("CharMap.LabelCurrency"); ///"Latin" public static string CharMap_LabelLatin=>T("CharMap.LabelLatin"); ///"Greek" public static string CharMap_LabelGreek=>T("CharMap.LabelGreek"); ///"Math and Logic" public static string CharMap_LabelMathAndLogic=>T("CharMap.LabelMathAndLogic"); ///"Symbols" public static string CharMap_LabelSymbols=>T("CharMap.LabelSymbols"); ///"Arrows" public static string CharMap_LabelArrows=>T("CharMap.LabelArrows"); ///"Paste as Text" public static string TextPaste_Label=>T("TextPaste.Label"); ///"Paste content here. Then press OK." public static string TextPaste_PasteHereContent=>T("TextPaste.PasteHereContent"); ///"How to spell check ..." public static string SpellCheck_InfoLabel=>T("SpellCheck.InfoLabel"); ///"How to spell check in the Visual Editor" public static string SpellCheck_InfoCaption=>T("SpellCheck.InfoCaption"); ///"To get suggestions for a misspelled word, press your SHIFT key down when you invoke the context menu." public static string SpellCheck_InfoText=>T("SpellCheck.InfoText"); ///"Find and Replace" public static string SearchAndReplace_LaunchButton_Label=>T("SearchAndReplace.LaunchButton.Label"); ///"Find and replace" public static string SearchAndReplace_LabelTitle=>T("SearchAndReplace.LabelTitle"); ///"Find" public static string SearchAndReplace_LabelFind=>T("SearchAndReplace.LabelFind"); ///"Replace with" public static string SearchAndReplace_LabelReplaceWith=>T("SearchAndReplace.LabelReplaceWith"); ///"Match case" public static string SearchAndReplace_LabelMatchCase=>T("SearchAndReplace.LabelMatchCase"); ///"Whole words" public static string SearchAndReplace_LabelWholeWords=>T("SearchAndReplace.LabelWholeWords"); ///"Find Next" public static string SearchAndReplace_ButtonFind=>T("SearchAndReplace.ButtonFind"); ///"Replace" public static string SearchAndReplace_ButtonReplace=>T("SearchAndReplace.ButtonReplace"); ///"Replace all" public static string SearchAndReplace_ButtonReplaceAll=>T("SearchAndReplace.ButtonReplaceAll"); ///"nothing was found" public static string SearchAndReplace_NothingFoundMessage=>T("SearchAndReplace.NothingFoundMessage"); ///"item(s) found" public static string SearchAndReplace_ItemsWereFoundMessage=>T("SearchAndReplace.ItemsWereFoundMessage"); ///"Edit" public static string Function_Edit=>T("Function.Edit"); ///"Edit {0}" public static string LaunchButton_Label_Template=>T("LaunchButton.Label"); ///"Edit {0}" public static string LaunchButton_Label(object parameter0)=>string.Format(T("LaunchButton.Label"), parameter0); ///"Components" public static string Components_LaunchButton_Label=>T("Components.LaunchButton.Label"); ///"Component..." public static string ContextMenu_LabelComponent=>T("ContextMenu.LabelComponent"); ///"Select a component" public static string Components_Window_Headline=>T("Components.Window.Headline"); ///"No selectable components" public static string Components_Window_NoItems=>T("Components.Window.NoItems"); ///"Filter..." public static string Components_Window_DialogFilterPlaceholder=>T("Components.Window.DialogFilterPlaceholder"); ///"OK" public static string Components_Window_Ok=>T("Components.Window.Ok"); ///"Cancel" public static string Components_Window_Cancel=>T("Components.Window.Cancel"); private static string T(string key) => StringResourceSystemFacade.GetString("Composite.Web.VisualEditor", key); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Orckestra_Tools_UrlConfiguration { ///"URL Configuration" public static string Tree_ConfigurationElementLabel=>T("Tree.ConfigurationElementLabel"); ///"This section allows configuring shorter and friendlier urls" public static string Tree_ConfigurationElementToolTip=>T("Tree.ConfigurationElementToolTip"); ///"Edit URL Configuration" public static string Tree_ConfigurationElementEditLabel=>T("Tree.ConfigurationElementEditLabel"); ///"Edit URL Configuration" public static string Tree_ConfigurationElementEditToolTip=>T("Tree.ConfigurationElementEditToolTip"); ///"Hostnames" public static string Tree_HostnamesFolderLabel=>T("Tree.HostnamesFolderLabel"); ///"Here you can map a hostname to a site" public static string Tree_HostnamesFolderToolTip=>T("Tree.HostnamesFolderToolTip"); ///"Add Hostname" public static string Tree_AddHostnameLabel=>T("Tree.AddHostnameLabel"); ///"Add a new hostname mapping" public static string Tree_AddHostnameToolTip=>T("Tree.AddHostnameToolTip"); ///"Edit Hostname" public static string Tree_EditHostnameLabel=>T("Tree.EditHostnameLabel"); ///"Edit this hostname mapping" public static string Tree_EditHostnameToolTip=>T("Tree.EditHostnameToolTip"); ///"Delete Hostname" public static string Tree_DeleteHostnameLabel=>T("Tree.DeleteHostnameLabel"); ///"Delete this hostname mapping" public static string Tree_DeleteHostnameToolTip=>T("Tree.DeleteHostnameToolTip"); ///"UrlConfiguration" public static string Tree_UrlConfigurationLabel=>T("Tree.UrlConfigurationLabel"); ///"URL Configuration" public static string UrlConfiguration_Title=>T("UrlConfiguration.Title"); ///"Page URL Suffix" public static string UrlConfiguration_PageUrlSuffix_Label=>T("UrlConfiguration.PageUrlSuffix.Label"); ///"A string that will be appended to all page urls. F.e. '.aspx' or '.html', leaving this field empty will produce extensionless urls" public static string UrlConfiguration_PageUrlSuffix_Help=>T("UrlConfiguration.PageUrlSuffix.Help"); ///"New Hostname" public static string HostnameBinding_AddNewHostnameTitle=>T("HostnameBinding.AddNewHostnameTitle"); ///"Hostname" public static string HostnameBinding_Hostname_Label=>T("HostnameBinding.Hostname.Label"); ///"Hostname to which current url building rules will be applied" public static string HostnameBinding_Hostname_Help=>T("HostnameBinding.Hostname.Help"); ///"Page" public static string HostnameBinding_Page_Label=>T("HostnameBinding.Page.Label"); ///"Root page that will be the default page for the current hostname" public static string HostnameBinding_Page_Help=>T("HostnameBinding.Page.Help"); ///"URL" public static string HostnameBinding_IncludeHomepageUrlTitle_Label=>T("HostnameBinding.IncludeHomepageUrlTitle.Label"); ///"Include homepage URL Title" public static string HostnameBinding_IncludeHomepageUrlTitle_ItemLabel=>T("HostnameBinding.IncludeHomepageUrlTitle.ItemLabel"); ///"Determines whether root page's title should be a part of url. Not having it checked produces shorter urls" public static string HostnameBinding_IncludeHomepageUrlTitle_Help=>T("HostnameBinding.IncludeHomepageUrlTitle.Help"); ///"Include language URL mapping" public static string HostnameBinding_IncludeLanguageUrlMapping_ItemLabel=>T("HostnameBinding.IncludeLanguageUrlMapping.ItemLabel"); ///"Determines whether language code should be a part of a url" public static string HostnameBinding_IncludeLanguageUrlMapping_Help=>T("HostnameBinding.IncludeLanguageUrlMapping.Help"); ///"Enforce HTTPS" public static string HostnameBinding_EnforceHttps_ItemLabel=>T("HostnameBinding.EnforceHttps.ItemLabel"); ///"When checked, all the HTTP requests will be redirected to HTTPS links" public static string HostnameBinding_EnforceHttps_Help=>T("HostnameBinding.EnforceHttps.Help"); ///"Custom 404 Page" public static string HostnameBinding_Custom404Page_Label=>T("HostnameBinding.Custom404Page.Label"); ///"Url to which request will be redirected in the case there's a request to non-existent c1 page" public static string HostnameBinding_Custom404Page_Help=>T("HostnameBinding.Custom404Page.Help"); ///"Alias hostnames" public static string HostnameBinding_Aliases_Label=>T("HostnameBinding.Aliases.Label"); ///"Hostnames from which all requests will be redirected to the current hostname" public static string HostnameBinding_Aliases_Help=>T("HostnameBinding.Aliases.Help"); ///"Alias Redirect" public static string HostnameBinding_UsePermanentRedirect_Label=>T("HostnameBinding.UsePermanentRedirect.Label"); ///"Use permanent redirect (HTTP 301)" public static string HostnameBinding_UsePermanentRedirect_ItemLabel=>T("HostnameBinding.UsePermanentRedirect.ItemLabel"); ///"When redirecting from an alias to the common hostname, a permanent redirect will tell visitors (browsers and search engines) that this redirect should be considered permanent and may be cached. Checking this box has a positive effect on SEO, provided the alias rule do not change in the near future" public static string HostnameBinding_UsePermanentRedirect_Help=>T("HostnameBinding.UsePermanentRedirect.Help"); private static string T(string key) => StringResourceSystemFacade.GetString("Orckestra.Tools.UrlConfiguration", key); } } } ================================================ FILE: Composite/Core/ResourceSystem/LocalizationFiles.tt ================================================ <#@ template debug="false" hostspecific="true" language="C#" #> <#@ output extension=".cs" #> <#@ assembly name="System.Configuration" #> <#@ assembly name="System.Core" #> <#@ assembly name="System.Xml" #> <#@ assembly name="System.Xml.Linq" #> <#@ import namespace="System.IO" #> <#@ import namespace="System.Globalization" #> <#@ import namespace="System.Configuration" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Text" #> <#@ import namespace="System.Xml.Linq" #> <# var pathToCurrentFolder = Host.ResolvePath(@""); var pathToSolutionFolder = pathToCurrentFolder.Substring(0, pathToCurrentFolder.Length - @"Composite\Core\ResourceSystem".Length); var pathToLocalizationFiles = pathToSolutionFolder + @"WebSite\Composite\localization"; #> using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Composite.Core.ResourceSystem { /// /// Class generated from localization files /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class LocalizationFiles { <#= GenerateCode(pathToLocalizationFiles) #> } } <#+ public static string GenerateCode(string folder) { var propertyDefinitions = new StringBuilder(); var classDefinitions = new StringBuilder(); string[] files = Directory.GetFiles(folder, @"*.en-us.xml"); foreach(string filePath in files) { string friendlyFileName = filePath.Substring(folder.Length + 1, filePath.Length - folder.Length - ".en-us.xml".Length - 1); string fileIdentifier = friendlyFileName.Replace(".", "_"); string className = fileIdentifier; if(className == "MimeTypes") continue; /* propertyDefinitions.Append(@" /// public static %classname% %propertyname% { get { return new %classname%(); } }" .Replace("%classname%", className) .Replace("%propertyname%", fileIdentifier)); */ classDefinitions.Append(@" /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class %classname% { " .Replace("%classname%", className)); GenerateLocalizationProperties(filePath, friendlyFileName, classDefinitions, className.Contains("Search")); classDefinitions.Append("} \r\n"); } return propertyDefinitions.ToString() + classDefinitions.ToString(); } private static void GenerateLocalizationProperties(string filePath, string friendlyFileName, StringBuilder output, bool generateConstants) { XDocument xdoc = XDocument.Load(filePath); var constants = new StringBuilder(); foreach(var element in xdoc.Root.Elements()) { var keyAttr = element.Attribute("key"); if(keyAttr == null) { throw new InvalidOperationException("Missing 'key' attribute. File: " + filePath); } var valueAttr = element.Attribute("value"); if(valueAttr == null) { throw new InvalidOperationException("Missing 'value' attribute. File: " + filePath); } string key = keyAttr.Value; string value = valueAttr.Value; string propertyName = key.Replace(".", "_").Replace("-", "_").Replace(" ", "_").Replace("(", "").Replace(")", "").Replace("+", ""); if (char.IsDigit(propertyName[0])) propertyName = "_" + propertyName; int parametersCount = 0; while(value.Contains("{" + parametersCount + "}")) { parametersCount++; } var xmlComment = "///"%comment%" \r\n" .Replace("%comment%", XmlEncode(value).Replace("\r\n", "\r\n ///")); output.Append(xmlComment); output.Append("public static string %property%=>T(\"%key%\");\r\n" .Replace("%comment%", XmlEncode(value).Replace("\r\n", "\r\n ///")) .Replace("%key%", key) .Replace("%property%", propertyName + (parametersCount > 0 ? "_Template" : "") )); if(parametersCount > 0) { string[] parametersDefinitions = new string[parametersCount]; string[] parametersReferences = new string[parametersCount]; for(int i=0; istring.Format(T(\"%key%\"), %parametersRef%);\r\n" .Replace("%key%", key) .Replace("%property%", propertyName) .Replace("%parametersDef%", parametersDefinitionsStr) .Replace("%parametersRef%", parametersReferencesStr)); } constants.AppendLine("///"%comment%"\r\npublic const string %property%=\"${%fileName%,%key%}\";" .Replace("%comment%", XmlEncode(value).Replace("\r\n", "\r\n ///")) .Replace("%property%", propertyName) .Replace("%fileName%", friendlyFileName) .Replace("%key%", key)); } output.Append( @"private static string T(string key) => StringResourceSystemFacade.GetString(""" + friendlyFileName + @""", key); "); if(generateConstants) { output.Append( @"/// public static class Untranslated { " + constants + @" }"); } } private static string XmlEncode(string text) { return text.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\"", """).Replace("'", "'"); } #> ================================================ FILE: Composite/Core/ResourceSystem/Plugins/ResourceProvider/ILocalizationProvider.cs ================================================ using System.Collections.Generic; using System.Globalization; using Composite.Core.Collections.Generic; namespace Composite.Core.ResourceSystem.Plugins.ResourceProvider { internal interface ILocalizationProvider : IResourceProvider { IEnumerable GetSections(); string GetString(string section, string stringId, CultureInfo cultureInfo); /// /// A dictionary of stringId -> stringValue /// /// ReadOnlyDictionary GetAllStrings(string section, CultureInfo cultureInfo); IEnumerable GetSupportedCultures(); } } ================================================ FILE: Composite/Core/ResourceSystem/Plugins/ResourceProvider/IResourceProvider.cs ================================================ using Composite.Core.ResourceSystem.Plugins.ResourceProvider.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.ResourceSystem.Plugins.ResourceProvider { [CustomFactory(typeof(ResourceProviderCustomFactory))] [ConfigurationNameMapper(typeof(ResourceProviderDefaultNameRetriever))] internal interface IResourceProvider { } } ================================================ FILE: Composite/Core/ResourceSystem/Plugins/ResourceProvider/IStringResourceProvider.cs ================================================ using System.Collections.Generic; using System.Globalization; namespace Composite.Core.ResourceSystem.Plugins.ResourceProvider { internal interface IStringResourceProvider : IResourceProvider { string GetStringValue(string stringId, CultureInfo cultureInfo); /// /// A dictionary of stringId -> stringValue /// /// IDictionary GetAllStrings(CultureInfo cultureInfo); IEnumerable GetSupportedCultures(); } } ================================================ FILE: Composite/Core/ResourceSystem/Plugins/ResourceProvider/NonConfigurableResourceProvider.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Core.ResourceSystem.Plugins.ResourceProvider { [Assembler(typeof(NonConfigurableResourceProviderAssembler))] internal class NonConfigurableResourceProvider : ResourceProviderData { } internal sealed class NonConfigurableResourceProviderAssembler : IAssembler { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IResourceProvider Assemble(IBuilderContext context, ResourceProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IResourceProvider)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/Core/ResourceSystem/Plugins/ResourceProvider/ResourceProviderData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.ResourceSystem.Plugins.ResourceProvider { [Assembler(typeof(NonConfigurableResourceProviderAssembler))] [ConfigurationElementType(typeof(NonConfigurableResourceProvider))] internal class ResourceProviderData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/Core/ResourceSystem/Plugins/ResourceProvider/Runtime/ResourceProviderCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.ResourceSystem.Plugins.ResourceProvider.Runtime { internal sealed class ResourceProviderCustomFactory : AssemblerBasedCustomFactory { protected override ResourceProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { ResourceProviderSettings settings = configurationSource.GetSection(ResourceProviderSettings.SectionName) as ResourceProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", ResourceProviderSettings.SectionName)); } return settings.ResourceProviderPlugins.Get(name); } } } ================================================ FILE: Composite/Core/ResourceSystem/Plugins/ResourceProvider/Runtime/ResourceProviderDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.ResourceSystem.Plugins.ResourceProvider.Runtime { internal sealed class ResourceProviderDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/Core/ResourceSystem/Plugins/ResourceProvider/Runtime/ResourceProviderFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.ResourceSystem.Plugins.ResourceProvider.Runtime { internal sealed class ResourceProviderFactory : NameTypeFactoryBase { public ResourceProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/Core/ResourceSystem/Plugins/ResourceProvider/Runtime/ResourceProviderSettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.ResourceSystem.Plugins.ResourceProvider.Runtime { internal sealed class ResourceProviderSettings : SerializableConfigurationSection { public const string SectionName = "Composite.Core.ResourceSystem.Plugins.ResourceProviderConfiguration"; private const string _resourceProviderPluginsProperty = "ResourceProviderPlugins"; [ConfigurationProperty(_resourceProviderPluginsProperty)] public NameTypeManagerTypeConfigurationElementCollection ResourceProviderPlugins { get { return (NameTypeManagerTypeConfigurationElementCollection)base[_resourceProviderPluginsProperty]; } } } } ================================================ FILE: Composite/Core/ResourceSystem/ResourceHandle.cs ================================================ using System; using Composite.Core.ResourceSystem.Icons; namespace Composite.Core.ResourceSystem { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class ResourceHandle { /// public static ResourceHandle Build(string resourceNamespace, string resourceName) { return new ResourceHandle(resourceNamespace, resourceName); } /// public static ResourceHandle BuildIconFromDefaultProvider(string resourceName) { return new ResourceHandle(BuildInIconProviderName.ProviderName, resourceName); } /// /// DO NOT USE! For serializing only! /// public ResourceHandle() { } /// public ResourceHandle(string resourceNamespace, string resourceName) { this.ResourceName = resourceName; this.ResourceNamespace = resourceNamespace; } /// public string ResourceNamespace { get; set; } /// public string ResourceName{ get; set; } } } ================================================ FILE: Composite/Core/ResourceSystem/StringResourceSystemFacade.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Composite.Core.Extensions; using Composite.Data.Caching; using Composite.Core.ResourceSystem.Foundation.PluginFacades; using Composite.Core.Types; namespace Composite.Core.ResourceSystem { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class StringResourceSystemFacade { private static readonly string LogTitle = typeof (StringResourceSystemFacade).Name; private static Regex _regex = new Regex(@"\$\{(?.+?)\}", RegexOptions.Compiled); private static readonly int ResourceCacheSize = 5000; private static readonly Cache> _resourceCache = new Cache>("Resource strings", ResourceCacheSize); private static readonly string Error_SectionNotDefined = "*** SECTION NOT FOUND ***"; private static readonly string Error_StringNotDefined = "*** STRING NOT FOUND ***"; /// public static void Initialize() { } /// public static string GetString(string providerName, string stringName) { return GetString(providerName, stringName, true); } /// public static string GetString(string section, string stringName, bool throwOnError) { Verify.ArgumentNotNullOrEmpty(section, "section"); Verify.ArgumentNotNullOrEmpty(stringName, "stringName"); var culture = Thread.CurrentThread.CurrentUICulture; string cacheKey = culture.Name + section + stringName; ExtendedNullable cachedValue = _resourceCache.Get(cacheKey); if (cachedValue != null) { return cachedValue.Value; } if (throwOnError) { Verify.ArgumentCondition(!section.Contains(','), "section", "providerName may not contain ',' symbol"); Verify.ArgumentCondition(!stringName.Contains(','), "stringName", "stringName may not contain ',' symbol"); } string result = ResourceProviderPluginFacade.GetStringValue(section, stringName, culture); if(result != null) { _resourceCache.Add(cacheKey, new ExtendedNullable {Value = result}); return result; } if (!throwOnError) { return null; } if (!ResourceProviderPluginFacade.LocalizationSectionDefined(section)) { Log.LogVerbose(LogTitle, "Localization section not defined '{0}:{1}'".FormatWith(section, stringName)); return Error_SectionNotDefined; } Log.LogVerbose(LogTitle, "Localization string not defined '{0}:{1}'".FormatWith(section, stringName)); return Error_StringNotDefined; } /// /// Returns a list of all defined localization sections /// /// public static IEnumerable GetLocalizationSectionNames() { return ResourceProviderPluginFacade.GetLocalizationSectionNames(); } /// public static bool TryGetString(string providerName, string stringName, out string resultString) { resultString = GetString(providerName, stringName, false); return resultString != null && (resultString != Error_SectionNotDefined) && (resultString != Error_StringNotDefined); } /// public static List GetLocalization(string providerName) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); Verify.ArgumentCondition(!providerName.Contains(','), "providerName", "providerName may not contain ','"); if (providerName == "XmlStringResourceProvider") { providerName = "Composite.Management"; } IDictionary translations = ResourceProviderPluginFacade.GetAllStrings(providerName); if(translations == null) { Log.LogVerbose(LogTitle, "Missing localization section: '{0}'".FormatWith(providerName)); return new List(); } List result = new List(); foreach (KeyValuePair pair in translations) { result.Add(new KeyValuePair(pair.Key, pair.Value)); } return result; } /// public static IEnumerable GetSupportedCultures() { return ResourceProviderPluginFacade.GetSupportedStringCultures(); } /// public static CultureInfo GetDefaultStringCulture() { return CultureInfo.CreateSpecificCulture("en-US"); } /// /// Returns a (localized) list of cultures, where the value is "(region) / (language)", where (language) is the language /// application users will get, if they select the specified culture. /// /// A list of (culture name, region/language label) [Obsolete("Go call GetSupportedCulturesList()", true)] public static List GetApplicationRegionAndLanguageList() { throw new NotImplementedException(); } /// /// Returns a localized label for a culture. Fall back to system display name. /// /// culture to get a localized label for /// Label for the culture public static string GetCultureTitle(CultureInfo culture) { string localizedLanguageTitle; if (TryGetString("Composite.Cultures", culture.Name, out localizedLanguageTitle)) { return localizedLanguageTitle; } return culture.DisplayName; } /// /// Returns a (localized) list of all cultures /// /// A dictionary of (culture name, region/language label) public static Dictionary GetAllCultures() { var cultureInfos = CultureInfo.GetCultures(CultureTypes.SpecificCultures); Dictionary cultures = cultureInfos.ToDictionary(f => f.Name, GetCultureTitle); return cultures.OrderBy(f => f.Value).ToDictionary(f => f.Key, f => f.Value); } /// /// Returns a (localized) list of cultures supported by the C1 Console /// /// A list of (culture name, region/language label) public static List GetSupportedCulturesList() { List supportedCultures = StringResourceSystemFacade.GetSupportedCultures().ToList(); CultureInfo defaultCulture = StringResourceSystemFacade.GetDefaultStringCulture(); List translatedOptions = new List(); List culturesLocalizedList = StringResourceSystemFacade.GetLocalization("Composite.Cultures"); string defaultCultureDisplayName = culturesLocalizedList.Where(f => f.Key == defaultCulture.Name).Select(f => f.Value).FirstOrDefault(); if (defaultCultureDisplayName == null) defaultCultureDisplayName = defaultCulture.EnglishName; foreach (CultureInfo culture in supportedCultures) { string cultureDisplayName = culturesLocalizedList.Where(f => f.Key == culture.Name).Select(f => f.Value).FirstOrDefault(); if (cultureDisplayName == null) cultureDisplayName = culture.EnglishName; translatedOptions.Add(new KeyValuePair(culture.Name, cultureDisplayName)); } translatedOptions = translatedOptions.OrderBy(f => f.Value).ToList(); return translatedOptions; } /// /// Parses the for any localization strings /// if there is any matches and these have a value, then the string is replaced /// the result string is returned. /// /// /// public static string ParseString(string stringToParse) { if (stringToParse == null) return null; MatchCollection matchCollection = _regex.Matches(stringToParse); string currentString = stringToParse; foreach (Match match in matchCollection) { string compositeName = match.Groups["id"].Value; if (string.IsNullOrWhiteSpace(compositeName)) continue; int idx = compositeName.LastIndexOf(','); if (idx == -1) continue; string resourceStoreName = compositeName.Remove(idx); string stringName = compositeName.Remove(0, idx + 1).TrimStart(' '); string replacement = GetString(resourceStoreName, stringName); currentString = currentString.Replace(match.Value, replacement); } return currentString; } /// public static IEnumerable SplitParseableStrings(string stringToSplit, char separator) { if (string.IsNullOrEmpty(stringToSplit)) { yield break; } bool isInIgnoreSeparatorMode = false; StringBuilder sb = new StringBuilder(); foreach( char c in stringToSplit) { if (isInIgnoreSeparatorMode == false && c == separator) { yield return sb.ToString(); sb = new StringBuilder(); } else { if (c == '}') { isInIgnoreSeparatorMode = false; } if (c == '$') { isInIgnoreSeparatorMode = true; } sb.Append(c); } } yield return sb.ToString(); } } } ================================================ FILE: Composite/Core/Routing/AttributeBasedRoutingHelper.cs ================================================ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Core.Extensions; using Composite.Core.Types; using Composite.Data; namespace Composite.Core.Routing { internal class AttributeBasedRoutingHelper { internal class PropertyUrlMapping { public Attribute Attribute; public PropertyInfo Property; public IRelativeRouteToPredicateMapper Mapper; } internal interface IRelativeRouteResover : IRelativeRouteToPredicateMapper { /// IData TryGetData(Guid pageId, RelativeRoute routePart); } public static IRelativeRouteToPredicateMapper GetPredicateMapper(Type dataType) { Verify.ArgumentNotNull(dataType, "dataType"); Verify.ArgumentCondition(dataType.IsInterface && typeof(IData).IsAssignableFrom(dataType), "dataType", "The data type have to an interface, inheriting {0}".FormatWith(typeof(IData).FullName)); var mappings = dataType .GetAllProperties() .SelectMany(prop => prop .GetCustomAttributes().OfType() .Select(attr => new { Attribute = attr, attr.Order, Property = prop, Mapper = attr.BuildMapper(prop) })) .OrderBy(a => a.Order) .Select(a => new PropertyUrlMapping { Attribute = a.Attribute, Property = a.Property, Mapper = a.Mapper }) .ToArray(); if (!mappings.Any()) { return null; } foreach (var mapping in mappings) { Verify.IsNotNull(mapping.Mapper, "An attribute of type '{0}' returned a null mapper", mapping.Attribute.GetType().FullName); } var targetType = typeof (DataTypeRelativeRouteToPredicateMapper<>).MakeGenericType(dataType); var constructor = targetType.GetConstructor(new[] {typeof (PropertyUrlMapping[])}); return (IRelativeRouteToPredicateMapper) constructor.Invoke(new object[] { mappings }); } internal class DataTypeRelativeRouteToPredicateMapper : IRelativeRouteResover, IRelativeRouteToPredicateMapper where TDataType : class, IData { private readonly PropertyUrlMapping[] _mappings; private readonly PropertyUrlMapping _keyMapping; private readonly int _keyFieldUrlSegmentOffset; /// /// Invoked via reflection. /// /// public DataTypeRelativeRouteToPredicateMapper(PropertyUrlMapping[] mappings) { _mappings = mappings; var keyProperties = typeof(TDataType).GetKeyProperties(); if (keyProperties.Count == 1) { var keyProperty = keyProperties[0]; var keyValueProviderType = typeof(IRelativeRouteValueProvider<>).MakeGenericType(keyProperty.PropertyType); int pathSegmentsToIgnore = 0; for (int i = 0; i < _mappings.Length; i++) { var propertyMapping = _mappings[i]; if (propertyMapping.Property == keyProperty && keyValueProviderType.IsInstanceOfType(propertyMapping.Mapper)) { _keyMapping = propertyMapping; _keyFieldUrlSegmentOffset = pathSegmentsToIgnore; } pathSegmentsToIgnore += propertyMapping.Mapper.PathSegmentsCount; } } } public int PathSegmentsCount { get { return _mappings.Sum(m => m.Mapper.PathSegmentsCount); } } public Expression> GetPredicate(Guid pageId, RelativeRoute route) { int segmentsProcessed = 0; var segments = route.PathSegments; var parameterExpression = Expression.Parameter(typeof(TDataType), "t"); Expression filterExpression = null; foreach (var mapping in _mappings) { string[] segmentsArgument = null; if (mapping.Mapper.PathSegmentsCount > 0) { segmentsArgument = segments.Skip(segmentsProcessed).Take(mapping.Mapper.PathSegmentsCount).ToArray(); segmentsProcessed += mapping.Mapper.PathSegmentsCount; } var relativeRoute = new RelativeRoute { PathSegments = segmentsArgument, QueryString = route.QueryString }; var fieldFilter = GetFieldFilter(mapping.Mapper, mapping.Property.PropertyType, pageId, relativeRoute); if (fieldFilter == null) { return null; } var propertyExpression = Expression.Property(parameterExpression, mapping.Property); var filterFragmentExpression = Expression.Invoke(fieldFilter, propertyExpression); filterExpression = filterExpression == null ? (Expression)filterFragmentExpression : Expression.AndAlso(filterExpression, filterFragmentExpression); } if (filterExpression == null) { return null; } if (typeof (IPageRelatedData).IsAssignableFrom(typeof (TDataType))) { var pageIdProperty = typeof (IPageRelatedData).GetProperty("PageId"); var propertyExpr = Expression.Property(parameterExpression, pageIdProperty); var pageIdMatchExpr = Expression.Equal(propertyExpr, Expression.Constant(pageId)); filterExpression = Expression.AndAlso(pageIdMatchExpr, filterExpression); } return Expression.Lambda>(filterExpression, parameterExpression); } public RelativeRoute GetRoute(TDataType dataItem, bool searchSignificant) { Verify.ArgumentNotNull(dataItem, "dataItem"); var resultSegments = new List(); NameValueCollection resultQueryString = null; foreach (var mapping in _mappings) { object filedValue = mapping.Property.GetValue(dataItem); if (filedValue == null) { return null; } bool fieldSearchSignificant = searchSignificant && (_keyMapping == null || mapping == _keyMapping); var relativeRoute = InvokeMapper(mapping.Mapper, mapping.Property.PropertyType, filedValue, fieldSearchSignificant); if (relativeRoute == null) { return null; } resultSegments.AddRange(relativeRoute.PathSegments); if (relativeRoute.QueryString != null && relativeRoute.QueryString.HasKeys()) { if (resultQueryString == null) { resultQueryString = new NameValueCollection(relativeRoute.QueryString); } else { resultQueryString.Add(relativeRoute.QueryString); } } } return new RelativeRoute { PathSegments = resultSegments.ToArray(), QueryString = resultQueryString }; } private RelativeRoute InvokeMapper( IRelativeRouteToPredicateMapper mapper, Type fieldType, object fieldValue, bool searchSignificant) { var @interface = typeof(IRelativeRouteToPredicateMapper<>).MakeGenericType(fieldType); return @interface.GetMethod("GetRoute").Invoke(mapper, new[] { fieldValue, searchSignificant }) as RelativeRoute; } private Expression GetFieldFilter( IRelativeRouteToPredicateMapper mapper, Type propertyType, Guid pageId, RelativeRoute relativeRoute) { var @interface = typeof(IRelativeRouteToPredicateMapper<>).MakeGenericType(propertyType); return @interface.GetMethod("GetPredicate").Invoke(mapper, new object[] { pageId, relativeRoute }) as Expression; } public IData TryGetData(Guid pageId, RelativeRoute routePart) { if (routePart.PathSegments.Length != PathSegmentsCount) { return null; } // Searching by key, if key value is provided by mappers if (_keyMapping != null) { var keyRoutePart = new RelativeRoute { PathSegments = routePart.PathSegments.Skip(_keyFieldUrlSegmentOffset) .Take(_keyMapping.Mapper.PathSegmentsCount).ToArray(), QueryString = routePart.QueryString }; return TryDataByKeyProperty(_keyMapping, keyRoutePart); } // Searching by a fields predicate otherwise var predicate = GetPredicate(pageId, routePart); if (predicate == null) { return null; } var dataSet = DataFacade.GetData(predicate).Take(2).ToList(); if (dataSet.Count == 0) { return null; } if (dataSet.Count > 1) { throw new DataUrlCollisionException(typeof(TDataType), routePart); } return dataSet[0]; } private IData TryDataByKeyProperty(PropertyUrlMapping propertyMapping, RelativeRoute keyRoutePart) { var method = StaticReflection.GetGenericMethodInfo(() => TryDataByKeyProperty(null, null)); var genericMethod = method.MakeGenericMethod(propertyMapping.Property.PropertyType); return genericMethod.Invoke(this, new object[] {propertyMapping, keyRoutePart}) as TDataType; } private TDataType TryDataByKeyProperty(PropertyUrlMapping propertyMapping, RelativeRoute keyRoutePart) { var valueProvider = propertyMapping.Mapper as IRelativeRouteValueProvider; if (valueProvider == null) { return null; } TKeyType key; if (!valueProvider.TryGetValue(keyRoutePart, out key)) { return null; } return DataFacade.TryGetDataByUniqueKey(typeof (TDataType), key) as TDataType; } } } } ================================================ FILE: Composite/Core/Routing/DataReferenceRelativeRouteToPredicateMapper.cs ================================================ using System; using System.Linq; using System.Linq.Expressions; using Composite.Core.Linq; using Composite.Core.Types; using Composite.Data; namespace Composite.Core.Routing { internal class DataReferenceRelativeRouteToPredicateMapper : IRelativeRouteToPredicateMapper where TDataType: class, IData { private readonly IRelativeRouteToPredicateMapper _dataTypeMapper; public DataReferenceRelativeRouteToPredicateMapper(IRelativeRouteToPredicateMapper dataTypeMapper) { _dataTypeMapper = dataTypeMapper; } public int PathSegmentsCount { get { return _dataTypeMapper.PathSegmentsCount; } } public Expression> GetPredicate(Guid pageId, RelativeRoute relativeRoute) { var dataPredicate = _dataTypeMapper.GetPredicate(pageId, relativeRoute); if (dataPredicate == null) return null; var data = DataFacade.GetData(dataPredicate).Evaluate(); if (data.Count == 0) { return null; } if (data.Count > 1) { throw new DataUrlCollisionException(typeof(TDataType), relativeRoute); } var keyObject = data.First().GetUniqueKey(); var key = ValueTypeConverter.Convert(keyObject); var paramExpr = Expression.Parameter(typeof (TField)); var body = Expression.Equal(paramExpr, Expression.Constant(key)); return Expression.Lambda>(body, paramExpr); } public RelativeRoute GetRoute(TField fieldValue, bool fieldSearchSignificant) { var data = DataFacade.TryGetDataByUniqueKey((object)fieldValue); if (data == null) { return null; } return _dataTypeMapper.GetRoute(data, fieldSearchSignificant); } } } ================================================ FILE: Composite/Core/Routing/DataUrlCollisionException.cs ================================================ using System; namespace Composite.Core.Routing { internal class DataUrlCollisionException : Exception { public DataUrlCollisionException(Type dataType, RelativeRoute relativeRoute) : base($"There are multiple data items of type '{dataType}' matching the same relative route '{relativeRoute}'") { } } } ================================================ FILE: Composite/Core/Routing/DataUrls.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.C1Console.Events; using Composite.Core.Extensions; using Composite.Core.Types; using Composite.Data; using Composite.Data.Types; namespace Composite.Core.Routing { /// /// Building/parsing data urls, and registering objects. /// public static class DataUrls { private static readonly string LogTitle = typeof (DataUrls).FullName; private static readonly ConcurrentDictionary _globalDataUrlMappers = new ConcurrentDictionary(); private static readonly ConcurrentDictionary> _dynamicPageDataUrlMappers = new ConcurrentDictionary>(); private static readonly ConcurrentDictionary>> _staticPageDataUrlMappers = new ConcurrentDictionary>>(); static DataUrls() { GlobalEventSystemFacade.OnDesignChange += () => _dynamicPageDataUrlMappers.Clear(); Action clearCache = page => { ConcurrentDictionary temp; _dynamicPageDataUrlMappers.TryRemove(page.Id, out temp); }; DataEvents.OnDeleted += (sender, args) => clearCache((IPage) args.Data); DataEvents.OnAfterUpdate += (sender, args) => clearCache((IPage) args.Data); DataEvents.OnStoreChanged += (sender, args) => { if (!args.DataEventsFired) { _dynamicPageDataUrlMappers.Clear(); } }; } /// /// Gets the data item by page url data; returns null if no data url mappers found. /// /// /// public static IDataReference TryGetData(PageUrlData pageUrlData) { Verify.ArgumentNotNull(pageUrlData, "pageUrlData"); if (string.IsNullOrEmpty(pageUrlData.PathInfo) && !pageUrlData.HasQueryParameters) { return null; } foreach (var globalDataUrlMapper in _globalDataUrlMappers) { try { var data = globalDataUrlMapper.Value.GetData(pageUrlData); if (data != null) return data; } catch (Exception ex) { Log.LogError(LogTitle, ex); } } var page = pageUrlData.GetPage(); if (page == null) { return null; } foreach (var mapper in GetMappersForPage(page.Id)) { try { var data = mapper.GetData(pageUrlData); if (data != null) return data; } catch (Exception ex) { Log.LogError(LogTitle, ex); } } return null; } /// /// Gets page url data by data reference; returns null if no data url mappers found. /// /// The data reference. /// public static PageUrlData TryGetPageUrlData(IDataReference dataReference) { Verify.ArgumentNotNull(dataReference, "dataReference"); var interfaceType = dataReference.ReferencedType; IDataUrlMapper dataUrlMapper; if (_globalDataUrlMappers.TryGetValue(interfaceType, out dataUrlMapper)) { return dataUrlMapper.GetPageUrlData(dataReference); } if (typeof(IPageRelatedData).IsAssignableFrom(interfaceType)) { IData data = dataReference.Data; if (data == null) { return null; } Guid pageId = (data as IPageRelatedData).PageId; return TryGetPageUrlData(pageId, dataReference); } foreach (var pageId in GetPageReferences(dataReference)) { var pageUrlData = TryGetPageUrlData(pageId, dataReference); if (pageUrlData != null) { return pageUrlData; } } return null; } /// /// Indicates whether there's a registered that can build a url for a given data reference. /// /// The data reference. /// public static bool CanBuildUrlForData(IDataReference dataReference) { Verify.ArgumentNotNull(dataReference, "dataReference"); var interfaceType = dataReference.ReferencedType; if (_globalDataUrlMappers.ContainsKey(interfaceType)) { return true; } if (typeof(IPageRelatedData).IsAssignableFrom(interfaceType)) { IData data = dataReference.Data; Guid pageId = (data as IPageRelatedData).PageId; return CanBuildUrlForData(interfaceType, pageId); } return GetPageReferences(dataReference).Any(pageId => CanBuildUrlForData(interfaceType, pageId)); } private static bool CanBuildUrlForData(Type interfaceType, Guid pageId) { return GetMappersForPage(pageId, interfaceType).Any(); } private static IEnumerable GetPageReferences(IDataReference dataReference) { IData data = null; foreach (var propertyInfo in GetPageReferenceFields(dataReference.ReferencedType)) { data = data ?? dataReference.Data; if (data == null) { yield break; } Guid pageId = (Guid)propertyInfo.GetValue(data, null); if (pageId != Guid.Empty) { yield return pageId; } } } private static IEnumerable GetPageReferenceFields(Type referencedType) { var descriptor = DataMetaDataFacade.GetDataTypeDescriptor(referencedType.GetImmutableTypeId()); if (descriptor == null) { return Enumerable.Empty(); } return descriptor.Fields.Where(f => f.InstanceType == typeof(Guid) && f.ForeignKeyReferenceTypeName != null && TypeManager.TryGetType(f.ForeignKeyReferenceTypeName) == typeof(IPage)) .Select(f => referencedType.GetProperty(f.Name)); } private static PageUrlData TryGetPageUrlData(Guid pageId, IDataReference dataReference) { foreach (var mapper in GetMappersForPage(pageId, dataReference.ReferencedType)) { var pageUrlData = mapper.GetPageUrlData(dataReference); if (pageUrlData != null) return pageUrlData; } return null; } private static IEnumerable GetMappersForPage(Guid pageId, Type interfaceType = null) { if (pageId == Guid.Empty) yield break; var page = PageManager.GetPageById(pageId); if (page == null) yield break; var staticMappers = GetStaticMappers(page); foreach (var mapper in staticMappers) { if (interfaceType == null || mapper.Key.IsAssignableFrom(interfaceType)) { yield return mapper.Value; } } var mappers = GetDynamicMappers(page); foreach (var mapper in mappers) { if (interfaceType == null || mapper.Key.IsAssignableFrom(interfaceType)) { yield return mapper.Value; } } } private static IEnumerable> GetStaticMappers(IPage page) { ConcurrentBag> result; if (!_staticPageDataUrlMappers.TryGetValue(page.Id, out result)) { return Enumerable.Empty>(); } return result; } private static IEnumerable> GetDynamicMappers(IPage page) { ConcurrentDictionary mappers; PageRenderingHistory.RenderPageIfNotRendered(page); if (!_dynamicPageDataUrlMappers.TryGetValue(page.Id, out mappers)) { return Enumerable.Empty>(); } return mappers; } /// /// Registers a global data url mapper for the specified type. /// /// /// The data type. public static void RegisterGlobalDataUrlMapper(IDataUrlMapper dataUrlMapper) where T : class, IData { RegisterGlobalDataUrlMapper(typeof (T), dataUrlMapper); } /// /// Registers a global data url mapper for the specified type. /// /// The data type. /// The data url mapper. public static void RegisterGlobalDataUrlMapper(Type dataType, IDataUrlMapper dataUrlMapper) { Verify.ArgumentCondition(dataType.IsInterface && typeof(IData).IsAssignableFrom(dataType), "dataType", "The data type should be an interface inheriting Composite.Data.IData"); _globalDataUrlMappers[dataType] = dataUrlMapper; } /// /// Registers a data url mapper associated with a page. /// /// The page id. /// The data url mapper. /// The data type. public static void RegisterDynamicDataUrlMapper(Guid pageId, IDataUrlMapper dataUrlMapper) where T: class, IData { RegisterDynamicDataUrlMapper(pageId, typeof(T), dataUrlMapper); } /// /// Registers a data url mapper associated with a page. /// /// The page id. /// The data type. /// The data url mapper. public static void RegisterDynamicDataUrlMapper(Guid pageId, Type dataType, IDataUrlMapper dataUrlMapper) { Verify.ArgumentNotNull(dataType, "dataType"); Verify.ArgumentNotNull(dataUrlMapper, "dataUrlMapper"); Verify.ArgumentCondition(dataType.IsInterface && typeof(IData).IsAssignableFrom(dataType), "dataType", "The data type should be an interface inheriting Composite.Data.IData"); var handlerList = _dynamicPageDataUrlMappers.GetOrAdd(pageId, key => new ConcurrentDictionary()); handlerList[dataType] = dataUrlMapper; } /// /// Registers a data url mapper associated with a page. /// /// The page id. /// The data type. /// The data url mapper. public static void RegisterStaticDataUrlMapper(Guid pageId, Type dataType, IDataUrlMapper dataUrlMapper) { Verify.ArgumentNotNull(dataUrlMapper, "dataUrlMapper"); Verify.ArgumentCondition(dataType.IsInterface && typeof(IData).IsAssignableFrom(dataType), "dataType", "The data type should be an interface inheriting Composite.Data.IData"); var handlerList = _staticPageDataUrlMappers.GetOrAdd(pageId, key => new ConcurrentBag>()); if (handlerList.Count > 100) { // Preventing a memory leak here return; } handlerList.Add(new KeyValuePair(dataType, dataUrlMapper)); } } } ================================================ FILE: Composite/Core/Routing/DefaultRelativeRouteToPredicateMapper.cs ================================================ using System; using System.Linq; using System.Linq.Expressions; using Composite.Core.Routing.Foundation.PluginFacades; using Composite.Core.Types; using Composite.Core.WebClient; namespace Composite.Core.Routing { internal class DefaultRelativeRouteToPredicateMapper : IRelativeRouteToPredicateMapper, IRelativeRouteValueProvider { public int PathSegmentsCount => 1; public Expression> GetPredicate(Guid pageId, RelativeRoute routePart) { TValue fieldValue; if (!TryGetValue(routePart, out fieldValue)) { return null; } return field => field.Equals(fieldValue); } public RelativeRoute GetRoute(TValue fieldValue, bool searchSignificant) { if (!typeof(TValue).IsValueType && fieldValue == null) { return null; } string stringValue; if (IsGuidField) { stringValue = UrlUtils.CompressGuid((fieldValue as Guid?).Value); } else if (IsStringField) { stringValue = searchSignificant ? UrlUtils.EncodeUrlInvalidCharacters(fieldValue as string) : StringToUrlPart(fieldValue as string); } else { stringValue = ValueTypeConverter.Convert(fieldValue); } return new RelativeRoute {PathSegments = new[] {stringValue}}; } private static string StringToUrlPart(string partnerName) { return UrlFormattersPluginFacade.FormatUrl(partnerName, true); } public bool TryGetValue(RelativeRoute routePart, out TValue value) { var stringValue = routePart.PathSegments.Single(); if (string.IsNullOrEmpty(stringValue)) { value = default(TValue); return false; } if (IsGuidField) { Guid tempGuid; if (!UrlUtils.TryExpandGuid(stringValue, out tempGuid) && !Guid.TryParse(stringValue, out tempGuid)) { value = default(TValue); return false; } value = (TValue)(tempGuid as object); return true; } if (IsStringField) { value = (TValue) (UrlUtils.DecodeUrlInvalidCharacters(stringValue) as object); return true; } Exception exception; object valueObj = ValueTypeConverter.TryConvert(stringValue, typeof(TValue), out exception); bool success = valueObj != null; value = success ? (TValue) valueObj : default(TValue); return success; } private bool IsStringField => typeof(TValue) == typeof(string); private bool IsGuidField => typeof(TValue) == typeof(Guid); } } ================================================ FILE: Composite/Core/Routing/Foundation/PluginFacades/PageUrlProviderPluginFacade.cs ================================================ using Composite.C1Console.Events; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.Core.Routing.Plugins.PageUrlsProviders; using Composite.Core.Routing.Plugins.PageUrlsProviders.Runtime; using Composite.Core.Routing.Plugins.Runtime; namespace Composite.Core.Routing.Foundation.PluginFacades { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PageUrlProviderPluginFacade { private static readonly ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); static PageUrlProviderPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => _resourceLocker.ResetInitialization()); } /// public static IPageUrlProvider GetDefaultProvider() { var resources = _resourceLocker.Resources; string providerName = resources.DefaultPageUrlProviderName; var provider = resources.ProviderCache[providerName]; if (provider == null) { lock (resources.ProviderCache) { provider = resources.ProviderCache[providerName]; if (provider == null) { provider = resources.Factory.Create(providerName); Verify.IsNotNull(provider, "Failed to build page url provider '{0}'", providerName); resources.ProviderCache.Add(providerName, provider); } } } return provider; } private sealed class Resources { private string _defaultPageUrlProviderName; public PageUrlProviderFactory Factory { get; set; } public Hashtable ProviderCache { get; set; } public static void Initialize(Resources resources) { resources.Factory = new PageUrlProviderFactory(); resources.ProviderCache = new Hashtable(); } public string DefaultPageUrlProviderName { get { if (_defaultPageUrlProviderName == null) { string sectionName = UrlsConfiguration.SectionName; var routingConfiguration = ConfigurationServices.ConfigurationSource.GetSection(sectionName) as UrlsConfiguration; Verify.IsNotNull(routingConfiguration, "Missing configuration section '{0}'", sectionName); _defaultPageUrlProviderName = routingConfiguration.DefaultPageUrlProviderName; } return _defaultPageUrlProviderName; } } } } } ================================================ FILE: Composite/Core/Routing/Foundation/PluginFacades/UrlFormattersPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Composite.C1Console.Events; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.Core.Routing.Plugins.Runtime; using Composite.Core.Routing.Plugins.UrlFormatters; using Composite.Core.Routing.Plugins.UrlFormatters.Runtime; using Composite.Data.Types; using Composite.Data.Validation; using Composite.Data.Validation.ClientValidationRules; namespace Composite.Core.Routing.Foundation.PluginFacades { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class UrlFormattersPluginFacade { private static readonly string LogTitle = typeof(UrlFormattersPluginFacade).FullName; private static readonly ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); static UrlFormattersPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => _resourceLocker.ResetInitialization()); } /// public static string FormatUrl(string url, bool onlyMandatory) { IEnumerable> urlFormatters = _resourceLocker.Resources.UrlFormatters; foreach(var urlFormatter in urlFormatters) { if (!onlyMandatory || urlFormatter.Item2) { url = urlFormatter.Item1.FormatUrl(url); } } url = FilterInvalidCharacters(url); return url; } private static string FilterInvalidCharacters(string pageTitle) { var regexClientValidationRule = ClientValidationRuleFacade.GetClientValidationRules(typeof(IPage), "UrlTitle") .OfType().Single(); var generated = new StringBuilder(); var regex = new Regex(regexClientValidationRule.Expression); foreach (char c in pageTitle) { var matchString = new string(c, 1); if (regex.IsMatch(matchString)) { generated.Append(c); } } return generated.ToString(); } private sealed class Resources { public IEnumerable> UrlFormatters { get; private set; } public static void Initialize(Resources resources) { const string sectionName = UrlsConfiguration.SectionName; var routingConfiguration = ConfigurationServices.ConfigurationSource.GetSection(sectionName) as UrlsConfiguration; Verify.IsNotNull(routingConfiguration, "Config section '{0}' is missing", sectionName); var factory = new UrlFormatterFactory(); var formatters = new List>(); var urlFormattersConfigNode = routingConfiguration.UrlFormatters; if (urlFormattersConfigNode != null) { foreach (var urlFormatterData in urlFormattersConfigNode) { string name = urlFormatterData.Name; try { formatters.Add(new Tuple(factory.Create(name), urlFormatterData.Mandatory)); } catch(Exception ex) { Log.LogError(LogTitle, "Failed to load url formatter '{0}'", name); Log.LogError(LogTitle, ex); } } } resources.UrlFormatters = formatters; } } } } ================================================ FILE: Composite/Core/Routing/HostnameBindingsFacade.cs ================================================ using System; using System.Globalization; using System.Linq; using System.Web; using Composite.Core.Extensions; using Composite.Core.Routing.Pages; using Composite.Core.Threading; using Composite.Core.WebClient; using Composite.Data; using Composite.Data.Types; using Composite.Plugins.Routing.Pages; namespace Composite.Core.Routing { internal class HostnameBindingsFacade { static HostnameBindingsFacade() { DataEventSystemFacade.SubscribeToDataBeforeAdd(OnBeforeUpdatingHostnameConfiguration, true); DataEventSystemFacade.SubscribeToDataBeforeUpdate(OnBeforeUpdatingHostnameConfiguration, true); DataEventSystemFacade.SubscribeToDataBeforeAdd(OnBeforeUpdatingHostnameBinding, true); DataEventSystemFacade.SubscribeToDataBeforeUpdate(OnBeforeUpdatingHostnameBinding, true); } private static void OnBeforeUpdatingHostnameConfiguration(object sender, DataEventArgs dataeventargs) { var configurationNode = dataeventargs.Data as IUrlConfiguration; Verify.IsNotNull(configurationNode, "configurationNode is null"); // Trimming page url suffix configurationNode.PageUrlSuffix = (configurationNode.PageUrlSuffix ?? string.Empty).Trim(); } private static void OnBeforeUpdatingHostnameBinding(object sender, DataEventArgs dataeventargs) { var hostnameBinding = dataeventargs.Data as IHostnameBinding; Verify.IsNotNull(hostnameBinding, "hostnameBinding is null"); // Trimming and lowercasing hostname hostnameBinding.Hostname = (hostnameBinding.Hostname ?? string.Empty).Trim().ToLowerInvariant(); hostnameBinding.PageNotFoundUrl = (hostnameBinding.PageNotFoundUrl ?? string.Empty).Trim(); } public static void Initialize() { lock (typeof(HostnameBindingsFacade)) { using (ThreadDataManager.EnsureInitialize()) { if (DataFacade.GetData().Any()) { return; } var configurationData = DataFacade.BuildNew(); configurationData.Id = new Guid("c7bd886b-7208-4257-b641-df2571a4872b"); configurationData.PageUrlSuffix = string.Empty; DataFacade.AddNew(configurationData); } } } internal static IHostnameBinding GetBindingForCurrentRequest() { return GetHostnameBinding(HttpContext.Current); } private static IHostnameBinding GetHostnameBinding(HttpContext httpContext) { if(httpContext == null) return null; string host = httpContext.Request.Url.Host; // TODO: optimize? return DataFacade.GetData().AsEnumerable().FirstOrDefault(b => b.Hostname == host); } internal static IHostnameBinding GetAliasBinding(HttpContext httpContext) { if (httpContext == null) { return null; } string hostname = httpContext.Request.Url.Host.ToLowerInvariant(); foreach (var hostnameBinding in DataFacade.GetData(true).AsEnumerable()) { string[] aliases = hostnameBinding.Aliases.Split(new[] {"\r\n", "\n"}, StringSplitOptions.RemoveEmptyEntries); if (aliases.Any(a => a == hostname)) { return hostnameBinding; } } return null; } internal static bool IsPageNotFoundRequest() { var context = HttpContext.Current; if(context == null) { return false; } string customPageNotFoundUrl = GetCustomPageNotFoundUrl(context); if (customPageNotFoundUrl.IsNullOrEmpty()) { return false; } customPageNotFoundUrl = customPageNotFoundUrl.Trim(); if(!customPageNotFoundUrl.StartsWith("/") && !customPageNotFoundUrl.Contains("://")) { customPageNotFoundUrl = "/" + customPageNotFoundUrl; } var request = context.Request; return request.RawUrl == customPageNotFoundUrl || request.Url.PathAndQuery == customPageNotFoundUrl || request.Url.PathAndQuery.StartsWith(customPageNotFoundUrl + "?"); } internal static string GetCustomPageNotFoundUrl() => GetCustomPageNotFoundUrl(HttpContext.Current); private static string GetCustomPageNotFoundUrl(HttpContext httpContext) { if (httpContext == null) return null; var binding = GetHostnameBinding(httpContext); if(string.IsNullOrEmpty(binding?.PageNotFoundUrl)) { return null; } string url = binding.PageNotFoundUrl; var defaultCulture = DataLocalizationFacade.DefaultLocalizationCulture; CultureInfo localeFromRequest = C1PageRoute.PageUrlData?.LocalizationScope ?? DefaultPageUrlProvider.GetCultureInfo(httpContext.Request.FilePath, binding, out _) ?? defaultCulture; using (new DataConnection(localeFromRequest)) { url = InternalUrls.TryConvertInternalUrlToPublic(url) ?? url; } if (url.StartsWith("~/") && localeFromRequest.Name != defaultCulture.Name) { using (new DataConnection(defaultCulture)) { url = InternalUrls.TryConvertInternalUrlToPublic(url) ?? url; } } if (url.StartsWith("~/")) url = UrlUtils.ResolvePublicUrl(url); return url; } internal static bool ServeCustomPageNotFoundPage(HttpContext httpContext) { string rawUrl = httpContext.Request.RawUrl; string customPageNotFoundUrl = GetCustomPageNotFoundUrl(httpContext); if (string.IsNullOrEmpty(customPageNotFoundUrl)) { return false; } if (rawUrl == customPageNotFoundUrl || httpContext.Request.Url.PathAndQuery == customPageNotFoundUrl) { throw new HttpException(404, $"'Page not found' wasn't handled. Url: '{rawUrl}'"); } if (HttpRuntime.UsingIntegratedPipeline && customPageNotFoundUrl.StartsWith("/")) { httpContext.Server.TransferRequest(customPageNotFoundUrl); return true; } httpContext.Response.Redirect(customPageNotFoundUrl, true); throw new InvalidOperationException("This code should not be reachable"); } } } ================================================ FILE: Composite/Core/Routing/IDataUrlMapper.cs ================================================ using System; using Composite.Data; namespace Composite.Core.Routing { /// /// Provides a link between a data item and a url /// public interface IDataUrlMapper { /// /// Gets a data item by page url data /// /// /// IDataReference GetData(PageUrlData pageUrlData); /// /// Gets page url data by a a data item /// /// /// PageUrlData GetPageUrlData(IDataReference instance); } } ================================================ FILE: Composite/Core/Routing/IInternalUrlConverter.cs ================================================ using System.Collections.Generic; using Composite.Data; namespace Composite.Core.Routing { /// /// An interface for internal url transformation. /// public interface IInternalUrlConverter { /// /// Contains an enumeration of url prefixes for urls current convert is handling /// IEnumerable AcceptedUrlPrefixes { get; } /// /// Converts a url in an internal format (f.e. "~/page(guid)" or "~/media(guid)") to a public serveable url (f.e. "/page/subpage"). /// /// An internal url. /// The target url space. /// string ToPublicUrl(string internalUrl, UrlSpace urlSpace); /// /// Converts an internal url in an internal format (f.e. "~/page(guid)" or "~/media(guid)") to a data reference. /// /// An internal url. /// IDataReference ToDataReference(string internalUrl); } } ================================================ FILE: Composite/Core/Routing/IInternalUrlProvider.cs ================================================ using Composite.Data; namespace Composite.Core.Routing { /// /// Providers internal urls for data references. /// public interface IInternalUrlProvider { /// /// Builds an internal urls for the specified data reference. /// /// The data reference. /// string BuildInternalUrl(IDataReference reference); } } ================================================ FILE: Composite/Core/Routing/IMediaUrlProvider.cs ================================================ using System; using Composite.Core.WebClient.Media; namespace Composite.Core.Routing { /// /// An interface for providing media urls for a given media id. /// public interface IMediaUrlProvider { /// /// Gets a public media url /// /// The store id. /// The media id. /// string GetPublicMediaUrl(string storeId, Guid mediaId); } /// /// An interface for providing media urls for a given media id. /// public interface IResizableImageUrlProvider: IMediaUrlProvider { /// /// Gets a public media url, that takes the specified resizing options into account /// /// The store id. /// The media id. /// The image resizing options. /// string GetResizedImageUrl(string storeId, Guid mediaId, ResizingOptions resizingOptions); } } ================================================ FILE: Composite/Core/Routing/IRelativeRouteToPredicateMapper.cs ================================================ using System; using System.Collections.Specialized; using System.Linq; using System.Linq.Expressions; using System.Web; namespace Composite.Core.Routing { /// public class RelativeRoute { /// public string[] PathSegments { get; set; } /// public NameValueCollection QueryString { get; set; } /// public override string ToString() { string result = PathSegments != null ? string.Join("/", PathSegments) : string.Empty; if (result != string.Empty) { result = "/" + result; } if (QueryString != null && QueryString.Count > 0) { Func encode = HttpUtility.HtmlAttributeEncode; result += "?" + string.Join("&", QueryString.Cast().Select(key => $"{encode(key)}={encode(QueryString[key])}")); } return result; } } /// public interface IRelativeRouteToPredicateMapper { /// /// Returns the amount of path info segments, handled by current mapper. /// int PathSegmentsCount { get; } } /// public interface IRelativeRouteToPredicateMapper : IRelativeRouteToPredicateMapper { /// /// Gets a predicate for filtering data based on a url segment /// /// /// The relative route /// Expression> GetPredicate(Guid pageId, RelativeRoute routePart); /// /// /// /// /// When false, the generated relative route will not be used for database querying. /// RelativeRoute GetRoute(T fieldValue, bool searchSignificant); } /// public interface IRelativeRouteValueProvider : IRelativeRouteToPredicateMapper { /// /// /// /// /// /// bool TryGetValue(RelativeRoute routePart, out T value); } } ================================================ FILE: Composite/Core/Routing/InternalUrls.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Xml.Linq; using Composite.Core.Instrumentation; using Composite.Core.WebClient; using Composite.Data; using Composite.Data.DynamicTypes.Foundation; using Composite.Data.Foundation; using Composite.Plugins.Routing.InternalUrlConverters; using Composite.Plugins.Routing.InternalUrlProviders; namespace Composite.Core.Routing { /// /// Allows setting custom urls conversions. /// public static class InternalUrls { private static readonly List _converters = new List(); private static readonly ConcurrentDictionary _providers = new ConcurrentDictionary(); internal static void Initialize_PostDataTypes() { foreach (Type type in DataProviderRegistry.AllInterfaces) { string internalUrlPrefix = DynamicTypeReflectionFacade.GetInternalUrlPrefix(type); if(string.IsNullOrEmpty(internalUrlPrefix)) continue; Register(new DataInternalUrlConverter(internalUrlPrefix, type)); Register(type, new DataInternalUrlProvider(internalUrlPrefix, type)); } } /// /// Registers an internal url converter. /// /// public static void Register(IInternalUrlConverter urlConverter) { _converters.Add(urlConverter); } /// /// Register an internal url provider. /// /// /// public static void Register(Type dataType, IInternalUrlProvider urlProvider) { _providers[dataType] = urlProvider; } /// /// Converts internal urls to public ones in a given html fragment /// /// /// public static string ConvertInternalUrlsToPublic(string html) { Verify.ArgumentNotNull(html, "html"); return ConvertInternalUrlsToPublic(html, _converters); } /// /// Indicates whether internal urls can be generated for the specified data type. /// /// /// public static bool DataTypeSupported(Type dataType) { Verify.ArgumentNotNull(dataType, "dataType"); return _providers.ContainsKey(dataType); } /// /// Gets an internal url for the specified data reference. /// /// The data referenc. /// public static string TryBuildInternalUrl(IDataReference dataReference) { Verify.ArgumentNotNull(dataReference, "dataReference"); var type = dataReference.ReferencedType; IInternalUrlProvider internalUrlProvider; if (!_providers.TryGetValue(type, out internalUrlProvider)) { return null; } return internalUrlProvider.BuildInternalUrl(dataReference); } /// /// Tries to parse an internal url, returns a null if failed. /// /// The internal url. /// public static IDataReference TryParseInternalUrl(string internalUrl) { if (!internalUrl.StartsWith("~/")) return null; string urlWithoutTilde = internalUrl.Substring(2); foreach (var converter in _converters) { foreach (var prefix in converter.AcceptedUrlPrefixes.Reverse()) { if (urlWithoutTilde.StartsWith(prefix, StringComparison.Ordinal)) { return converter.ToDataReference(internalUrl); } } } return null; } /// /// Tries to convert an internal url to a public one, returns the original value if failed. /// /// The internal url. /// The url space. /// public static string TryConvertInternalUrlToPublic(string internalUrl, UrlSpace urlSpace = null) { if (!internalUrl.StartsWith("~/")) return internalUrl; string urlWithoutTilde = internalUrl.Substring(2); foreach (var converter in _converters) { foreach (var prefix in converter.AcceptedUrlPrefixes.Reverse()) { if (urlWithoutTilde.StartsWith(prefix, StringComparison.Ordinal)) { return converter.ToPublicUrl(internalUrl, urlSpace ?? new UrlSpace()) ?? internalUrl; } } } return internalUrl; } private static string ResolvePrefix(string urlPrefix) => UrlUtils.PublicRootPath + "/" + urlPrefix; private static Dictionary GetConvertersMap(Func mapPrefix) { var result = new Dictionary(); foreach (var converter in _converters) { foreach (var prefix in converter.AcceptedUrlPrefixes) { result[mapPrefix(prefix)] = converter; } } return result; } private static bool IsLinkAttribute(XName attrName) => attrName.LocalName == "src" || attrName.LocalName == "href" || attrName.LocalName == "srcset"; /// /// Converts internal urls to public ones in a given html fragment /// /// /// public static void ConvertInternalUrlsToPublic(XDocument document) { Verify.ArgumentNotNull(document, nameof(document)); var convertersMap = GetConvertersMap(ResolvePrefix); if (!convertersMap.Any()) return; var urlSpace = new UrlSpace(); var convertionCache = new Dictionary(); foreach (var element in document.Descendants()) { foreach (var attr in element.Attributes().Where(a => IsLinkAttribute(a.Name))) { string link = attr.Value; if (convertionCache.TryGetValue(link, out string cachedLink)) { attr.Value = cachedLink; continue; } foreach (var prefix in convertersMap.Keys) { if (link.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { var converter = convertersMap[prefix]; var newLink = converter.ToPublicUrl(link, urlSpace); if (newLink != null && newLink != link) { convertionCache[link] = newLink; attr.Value = newLink; break; } } } } } } /// /// Converts internal urls to public ones in a given html fragment /// /// /// /// internal static string ConvertInternalUrlsToPublic(string html, IEnumerable converters) { var convertersMap = GetConvertersMap(_ => _); if (!convertersMap.Any()) { return html; } // Urls, generated in UserControl-s may still have "~/" as a prefix foreach (var urlPrefix in convertersMap.Keys) { string rawUrlPrefix = "~/" + urlPrefix; string resolvedUrlPrefix = ResolvePrefix(urlPrefix); html = UrlUtils.ReplaceUrlPrefix(html, rawUrlPrefix, resolvedUrlPrefix); } StringBuilder result = null; var urlsToConvert = new List (); foreach (var pair in convertersMap) { string internalPrefix = ResolvePrefix(pair.Key); var converter = pair.Value; // Bracket encoding fix string prefixToSearch = internalPrefix; if (prefixToSearch.EndsWith("(", StringComparison.Ordinal)) { prefixToSearch = prefixToSearch.Substring(0, internalPrefix.Length - 1); } urlsToConvert.AddRange(UrlUtils.FindUrlsInHtml(html, prefixToSearch).Select(match => new UrlToConvert(match, internalPrefix, converter))); } // Sorting the offsets by descending, so we can replace urls in that order by not affecting offsets of not yet processed urls urlsToConvert.Sort((a, b) => -a.Match.Index.CompareTo(b.Match.Index)); int lastReplacementIndex = int.MaxValue; var urlSpace = new UrlSpace(); var measurements = new Dictionary(); var convertionCache = new Dictionary(); foreach (var urlToConvert in urlsToConvert) { UrlUtils.UrlMatch urlMatch = urlToConvert.Match; if(urlMatch.Index == lastReplacementIndex) continue; string internalUrlPrefix = urlToConvert.UrlPrefix; string internalUrl = urlMatch.Value; string publicUrl; if (!convertionCache.TryGetValue(internalUrl, out publicUrl)) { string decodedInternalUrl = internalUrl.Replace("%28", "(").Replace("%29", ")").Replace("&", "&"); if (!decodedInternalUrl.StartsWith(internalUrlPrefix)) { continue; } var converter = urlToConvert.Converter; MeasureConvertionPerformance(measurements, converter, () => { publicUrl = urlToConvert.Converter.ToPublicUrl(decodedInternalUrl, urlSpace); }); if (publicUrl == null) { convertionCache.Add(internalUrl, null); continue; } // Encoding xml attribute value publicUrl = publicUrl.Replace("&", "&"); convertionCache.Add(internalUrl, publicUrl); } else { if (internalUrl == null) continue; } if (result == null) { result = new StringBuilder(html); } result.Remove(urlMatch.Index, urlMatch.Value.Length); result.Insert(urlMatch.Index, publicUrl); lastReplacementIndex = urlMatch.Index; } foreach (var measurement in measurements.Values) { Profiler.AddSubMeasurement(measurement); } return result != null ? result.ToString() : html; } private static void MeasureConvertionPerformance(Dictionary measurements, IInternalUrlConverter converter, Action action) { string key = converter.GetType().FullName; var stopwatch = new Stopwatch(); long memoryBefore = GC.GetTotalMemory(false); stopwatch.Start(); action(); stopwatch.Stop(); long memoryTotal = GC.GetTotalMemory(false) - memoryBefore; long totalTime = (stopwatch.ElapsedTicks*1000000)/Stopwatch.Frequency; if (memoryTotal < 0) { memoryTotal = 0; } Measurement existingRecord; if (measurements.TryGetValue(key, out existingRecord)) { existingRecord.MemoryUsage += memoryTotal; existingRecord.TotalTime += totalTime; // NOTE: Loosing some of the precision here } else { measurements.Add(key, new Measurement(key) { MemoryUsage = memoryTotal, TotalTime = totalTime }); } } private class UrlToConvert : Tuple { public UrlToConvert(UrlUtils.UrlMatch match, string urlPrefix, IInternalUrlConverter converter) : base(match, urlPrefix, converter) { } public UrlUtils.UrlMatch Match { get { return Item1; } } public string UrlPrefix { get { return Item2; } } public IInternalUrlConverter Converter { get { return Item3; } } } } } ================================================ FILE: Composite/Core/Routing/MediaUrlData.cs ================================================ using System; using System.Collections.Specialized; using Composite.Data.Types; namespace Composite.Core.Routing { /// /// Information stored in a media url /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class MediaUrlData { /// /// Initializes a new instance of the class. /// public MediaUrlData() {} /// /// Initializes a new instance of the class. /// /// The media store. /// The media id. /// The query parameters. public MediaUrlData(string mediaStore, Guid mediaId, NameValueCollection queryParameters = null) { MediaStore = mediaStore; MediaId = mediaId; QueryParameters = queryParameters ?? new NameValueCollection(); } /// /// Initializes a new instance of the class. /// /// The media file. public MediaUrlData(IMediaFile mediaFile) { MediaStore = mediaFile.StoreId; MediaId = mediaFile.Id; QueryParameters = new NameValueCollection(); } /// /// Gets or sets the media id. /// /// /// The media id. /// public Guid MediaId { get; set; } /// /// Gets or sets the media store. /// /// /// The media store. /// public string MediaStore { get; set; } /// /// Gets or sets the query parameters. /// /// /// The query parameters. /// public NameValueCollection QueryParameters { get; set; } } } ================================================ FILE: Composite/Core/Routing/MediaUrls.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Specialized; using System.Web; using Composite.Core.Extensions; using Composite.Core.WebClient; using Composite.Core.WebClient.Media; using Composite.Data.Types; using Composite.Plugins.Routing.MediaUrlProviders; namespace Composite.Core.Routing { /// /// Responsible for parsing and building media urls /// public static class MediaUrls { internal static readonly string DefaultMediaStore = "MediaArchive"; private static readonly string MediaUrl_UnprocessedInternalPrefix = "~/media("; private static readonly string MediaUrl_InternalPrefix = UrlUtils.PublicRootPath + "/media("; internal static readonly string MediaUrl_PublicPrefix = UrlUtils.PublicRootPath + "/media/"; private static readonly string MediaUrl_UnprocessedRenderPrefix = "~/Renderers/ShowMedia.ashx"; private static readonly string MediaUrl_RenderPrefix = UrlUtils.PublicRootPath + "/Renderers/ShowMedia.ashx"; private static Lazy _defaultMediaUrlProvider = new Lazy(() => new DefaultMediaUrlProvider(null)); private static ConcurrentDictionary _mediaUrlProviders = new ConcurrentDictionary(); /// /// Parses the URL. /// /// The relative URL. /// public static MediaUrlData ParseUrl(string relativeUrl) { UrlKind urlKind; return ParseUrl(relativeUrl, out urlKind); } /// /// Parses the URL. /// /// The relative URL. /// Kind of the URL. /// public static MediaUrlData ParseUrl(string relativeUrl, out UrlKind urlKind) { relativeUrl = relativeUrl.Replace("%28", "(").Replace("%29", ")"); if(relativeUrl.StartsWith(MediaUrl_RenderPrefix, StringComparison.OrdinalIgnoreCase) || relativeUrl.StartsWith(MediaUrl_UnprocessedRenderPrefix, StringComparison.OrdinalIgnoreCase)) { return ParseRenderUrl(relativeUrl, out urlKind); } urlKind = UrlKind.Undefined; bool isInternalLink = relativeUrl.StartsWith(MediaUrl_InternalPrefix, StringComparison.Ordinal); bool isInternalUnprocessedLink = !isInternalLink && relativeUrl.StartsWith(MediaUrl_UnprocessedInternalPrefix, StringComparison.Ordinal); if (isInternalLink || isInternalUnprocessedLink) { string prefix = isInternalLink ? MediaUrl_InternalPrefix : MediaUrl_UnprocessedInternalPrefix; var result = ParseInternalUrl(relativeUrl, prefix); if(result != null) { urlKind = UrlKind.Internal; } return result; } int minimumLengthOfPublicMediaUrl = MediaUrl_PublicPrefix.Length + 22; /* 2 - length of a compressed guid */ if (relativeUrl.Length >= minimumLengthOfPublicMediaUrl && relativeUrl.StartsWith(MediaUrl_PublicPrefix)) { // Parsing urls like //media/{MediaId}* Guid mediaId; if (TryExtractMediaId(relativeUrl, MediaUrl_PublicPrefix.Length, out mediaId)) { NameValueCollection queryParams = new UrlBuilder(relativeUrl).GetQueryParameters(); urlKind = UrlKind.Public; return new MediaUrlData { MediaId = mediaId, MediaStore = DefaultMediaStore, QueryParameters = queryParams }; } // Parsing urls like //media//{MediaId}* int slashOffset = relativeUrl.IndexOf('/', MediaUrl_PublicPrefix.Length + 1); if (slashOffset > MediaUrl_PublicPrefix.Length + 1 && TryExtractMediaId(relativeUrl, slashOffset + 1, out mediaId)) { string mediaStore = relativeUrl.Substring(MediaUrl_PublicPrefix.Length, slashOffset - MediaUrl_PublicPrefix.Length); NameValueCollection queryParams = new UrlBuilder(relativeUrl).GetQueryParameters(); urlKind = UrlKind.Public; return new MediaUrlData { MediaId = mediaId, MediaStore = mediaStore, QueryParameters = queryParams }; } } return null; } private static bool TryExtractMediaId(string url, int offset, out Guid mediaId) { // Extracting a guid, which is kept in plain or compressed as base64 like form if((url.Length >= offset + 36 && Guid.TryParse(url.Substring(offset, 36), out mediaId)) /*|| (url.Length >= offset + 22 && UrlUtils.TryExpandGuid(url.Substring(offset, 22), out mediaId))*/) { return true; } mediaId = Guid.Empty; return false; } private static MediaUrlData ParseRenderUrl(string relativeUrl, out UrlKind urlKind) { try { var queryParameters = new UrlBuilder(relativeUrl).GetQueryParameters(); IMediaFile mediaFile = MediaUrlHelper.GetFileFromQueryString(queryParameters); Verify.IsNotNull(mediaFile, "failed to get file from a query string"); urlKind = UrlKind.Renderer; queryParameters.Remove("id"); queryParameters.Remove("i"); queryParameters.Remove("src"); queryParameters.Remove("store"); return new MediaUrlData { MediaId = mediaFile.Id, MediaStore = mediaFile.StoreId, QueryParameters = queryParameters }; } catch(Exception) { urlKind = UrlKind.Undefined; return null; } } private static MediaUrlData ParseInternalUrl(string relativeUrl, string urlPrefix) { int endBracketOffset = relativeUrl.IndexOf(")", StringComparison.Ordinal); if (endBracketOffset < 0) return null; string mediaStoreAndId = relativeUrl.Substring(urlPrefix.Length, endBracketOffset - urlPrefix.Length); string store = null; string mediaIdStr; int separatorIndex = mediaStoreAndId.LastIndexOf(":", StringComparison.Ordinal); if (separatorIndex > 0) { store = mediaStoreAndId.Substring(0, separatorIndex); mediaIdStr = mediaStoreAndId.Substring(separatorIndex + 1); } else { mediaIdStr = mediaStoreAndId; } Guid mediaId; if (!Guid.TryParse(mediaIdStr, out mediaId)) { return null; } NameValueCollection queryParams = new UrlBuilder(relativeUrl).GetQueryParameters(); return new MediaUrlData { MediaId = mediaId, MediaStore = store ?? DefaultMediaStore, QueryParameters = queryParams }; } /// /// Builds the URL. /// /// The media file. /// Kind of the URL. /// public static string BuildUrl(IMediaFile mediaFile, UrlKind urlKind = UrlKind.Public) { return BuildUrl(new MediaUrlData(mediaFile), urlKind); } /// /// Builds the URL. /// /// The media URL data. /// Kind of the URL. /// public static string BuildUrl(MediaUrlData mediaUrlData, UrlKind urlKind) { Verify.ArgumentNotNull(mediaUrlData, "mediaUrlData"); switch (urlKind) { case UrlKind.Internal: return BuildInternalUrl(mediaUrlData); case UrlKind.Renderer: return BuildRendererUrl(mediaUrlData); case UrlKind.Public: return BuildPublicUrl(mediaUrlData); } throw new NotSupportedException("Not supported url kind. urlKind == '{0}'".FormatWith(urlKind)); } private static string BuildInternalUrl(MediaUrlData mediaUrlData) { string storeId = mediaUrlData.MediaStore == DefaultMediaStore ? "" : mediaUrlData.MediaStore + ":"; var urlBuilder = new UrlBuilder("~/media(" + storeId + mediaUrlData.MediaId + ")"); if (mediaUrlData.QueryParameters != null) { urlBuilder.AddQueryParameters(mediaUrlData.QueryParameters); } return urlBuilder.ToString(); } private static string BuildRendererUrl(MediaUrlData mediaUrlData) { var queryParams = new NameValueCollection(mediaUrlData.QueryParameters) { {"id", mediaUrlData.MediaId.ToString()} }; if (mediaUrlData.MediaStore != null && mediaUrlData.MediaStore != DefaultMediaStore) { queryParams.Add("store", mediaUrlData.MediaStore); } var url = new UrlBuilder(UrlUtils.PublicRootPath + "/Renderers/ShowMedia.ashx"); url.AddQueryParameters(queryParams); return url; } private static string BuildPublicUrl(MediaUrlData mediaUrlData) { IMediaUrlProvider urlProvider; if (!_mediaUrlProviders.TryGetValue(mediaUrlData.MediaStore, out urlProvider)) { urlProvider = _defaultMediaUrlProvider.Value; } if (mediaUrlData.QueryParameters.Count > 0) { string mediaUrl; var resizingOptions = ResizingOptions.Parse(mediaUrlData.QueryParameters); var noneResizingOptions = mediaUrlData.QueryParameters; if (!resizingOptions.IsEmpty) { var imageResizableUrlProvider = urlProvider is IResizableImageUrlProvider ? urlProvider as IResizableImageUrlProvider : _defaultMediaUrlProvider.Value; mediaUrl = imageResizableUrlProvider.GetResizedImageUrl(mediaUrlData.MediaStore, mediaUrlData.MediaId, resizingOptions); foreach (var key in HttpUtility.ParseQueryString(resizingOptions.ToString()).AllKeys) { noneResizingOptions.Remove(key); } } else { mediaUrl = urlProvider.GetPublicMediaUrl(mediaUrlData.MediaStore, mediaUrlData.MediaId); } if (noneResizingOptions.Count > 0) { var urlBuilder = new UrlBuilder(mediaUrl); urlBuilder.AddQueryParameters(noneResizingOptions); return urlBuilder.ToString(); } return mediaUrl; } return urlProvider.GetPublicMediaUrl(mediaUrlData.MediaStore, mediaUrlData.MediaId); } /// /// Registers a media url provider /// /// The store id. /// The media url provider. public static void RegisterMediaUrlProvider(string storeId, IMediaUrlProvider mediaUrlProvider) { _mediaUrlProviders[storeId] = mediaUrlProvider; } } } ================================================ FILE: Composite/Core/Routing/PageNotFoundRoute.cs ================================================ using System; using System.Web; using System.Web.Routing; using Composite.Core.WebClient; namespace Composite.Core.Routing { internal class PageNotFoundRoute : Route { public PageNotFoundRoute() : base("{*url}", new PageNotFoundRouteHandler()) { } public override RouteData GetRouteData(HttpContextBase httpContext) { // Skipping the route is there's no associated "Page not found" url if(string.IsNullOrEmpty(HostnameBindingsFacade.GetCustomPageNotFoundUrl())) { return null; } // Skipping root request if(httpContext.Request.RawUrl.Length == UrlUtils.PublicRootPath.Length + 1) { return null; } return base.GetRouteData(httpContext); } } internal class PageNotFoundRouteHandler: IRouteHandler { public IHttpHandler GetHttpHandler(RequestContext requestContext) { var httpContext = HttpContext.Current; if (!HostnameBindingsFacade.ServeCustomPageNotFoundPage(httpContext)) { throw new InvalidOperationException("Failed to redirect to 'page not found' url"); } return EmptyHttpHandler.Instance; } private class EmptyHttpHandler : IHttpHandler { private EmptyHttpHandler() { } static EmptyHttpHandler() { Instance = new EmptyHttpHandler(); } public static EmptyHttpHandler Instance { get; private set; } public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext context) { throw new InvalidOperationException("This code should not be reachable"); } } } } ================================================ FILE: Composite/Core/Routing/PageUrlData.cs ================================================ using System; using System.Collections.Specialized; using System.Globalization; using Composite.Data; using Composite.Data.Types; namespace Composite.Core.Routing { /// /// Information stored in a C1 CMS page url /// public class PageUrlData { /// public PageUrlData() { } /// /// Initializes a new instance of the class. /// /// The page. public PageUrlData(IPage page) { Verify.ArgumentNotNull(page, "page"); PageId = page.Id; VersionId = page.VersionId; this.PublicationScope = page.DataSourceId.PublicationScope; this.LocalizationScope = page.DataSourceId.LocaleScope; } /// /// Initializes a new instance of the class. /// /// The page id. /// The publication scope. /// The localization scope. public PageUrlData(Guid pageId, PublicationScope publicationScope, CultureInfo localizationScope) { PageId = pageId; PublicationScope = publicationScope; LocalizationScope = localizationScope; } /// /// Gets or sets the page id. /// /// /// The page id. /// public Guid PageId { get; set; } /// /// Gets or sets the page version id. /// /// /// The page id. /// public Guid? VersionId { get; set; } /// /// Gets or sets the publication scope. /// /// /// The publication scope. /// public PublicationScope PublicationScope { get; set; } /// /// Gets or sets the localization scope. /// /// /// The localization scope. /// public CultureInfo LocalizationScope { get; set; } /// /// Gets or sets the path info. /// /// /// The path info. /// public virtual string PathInfo { get; set; } /// /// Gets or sets the query parameters. /// /// /// The query parameters. /// public virtual NameValueCollection QueryParameters { get; set; } internal bool HasQueryParameters { get { return QueryParameters != null && QueryParameters.HasKeys(); } } } } ================================================ FILE: Composite/Core/Routing/PageUrls.cs ================================================ using System.Web; using Composite.Core.Routing.Foundation.PluginFacades; using Composite.Core.Routing.Plugins.PageUrlsProviders; using Composite.Data.Types; namespace Composite.Core.Routing { /// /// Responsible for parsing and building page urls /// public static class PageUrls { private static IPageUrlProvider GetDefaultProvider() { return PageUrlProviderPluginFacade.GetDefaultProvider(); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static IPageUrlProvider UrlProvider { get { return GetDefaultProvider(); } } /// /// Parses the URL. /// /// The absolute URL. /// public static PageUrlData ParseUrl(string absoluteUrl) { UrlKind urlKind; return ParseUrl(absoluteUrl, out urlKind); } /// /// Parses the URL. /// /// The absolute URL. /// Kind of the URL. /// public static PageUrlData ParseUrl(string absoluteUrl, out UrlKind urlKind) { if (absoluteUrl.StartsWith("http") && absoluteUrl.Contains("://")) { return UrlProvider.ParseUrl(absoluteUrl, out urlKind); } var context = HttpContext.Current; string hostname = context != null ? context.Request.Url.Host : null; var urlSpace = new UrlSpace(hostname, absoluteUrl); return UrlProvider.ParseUrl(absoluteUrl, urlSpace, out urlKind); } /// /// Parses the URL. /// /// The relative URL. /// The URL space. /// Kind of the URL. /// public static PageUrlData ParseUrl(string relativeUrl, UrlSpace urlSpace, out UrlKind urlKind) { Verify.ArgumentNotNull(relativeUrl, "relativeUrl"); return UrlProvider.ParseUrl(relativeUrl, urlSpace, out urlKind); } /// /// Builds the URL. /// /// The page URL data. /// Kind of the URL. /// The URL space. /// public static string BuildUrl(PageUrlData pageUrlData, UrlKind urlKind = UrlKind.Public, UrlSpace urlSpace = null) { Verify.ArgumentNotNull(pageUrlData, "pageUrlData"); return UrlProvider.BuildUrl(pageUrlData, urlKind, urlSpace ?? new UrlSpace()); } /// /// Builds the URL. /// /// The page. /// Kind of the URL. /// The URL space. /// public static string BuildUrl(IPage page, UrlKind urlKind = UrlKind.Public, UrlSpace urlSpace = null) { Verify.ArgumentNotNull(page, "page"); return BuildUrl(new PageUrlData(page), urlKind, urlSpace ?? new UrlSpace()); } } } ================================================ FILE: Composite/Core/Routing/Pages/C1PageRoute.cs ================================================ using System; using System.Globalization; using System.Web; using System.Web.Routing; using Composite.Core.WebClient; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.WebClient.Renderings; using Composite.Core.WebClient.Renderings.Page; using Composite.Search.DocumentSources; namespace Composite.Core.Routing.Pages { /// /// Implements C1 page route for ASP.NET routing /// public class C1PageRoute : RouteBase { /// public static readonly string RouteData_PageUrl = "C1Page"; internal static readonly string HttpContextItem_C1PageUrl = "C1_PageUrl"; private static readonly string HttpContextItem_PathInfoHandled = "C1PageRoute_PathInfoHandled"; /// public static PageUrlData PageUrlData { get { var httpContext = HttpContext.Current; return httpContext != null ? httpContext.Items[HttpContextItem_C1PageUrl] as PageUrlData : null; } set { var httpContext = HttpContext.Current; Verify.IsNotNull(httpContext, "HttpContext is not available"); httpContext.Items[HttpContextItem_C1PageUrl] = value; } } /// /// Get the additional information that was passed in URL along with page url /// /// The PathInfo url part. public static string GetPathInfo() { return PageUrlData?.PathInfo; } /// /// This method has to be called to notify the system that PathInfo was used, and the request will not be redirected to "Page not found" page /// public static void RegisterPathInfoUsage() { var httpContext = HttpContext.Current; if(!httpContext.Items.Contains(HttpContextItem_PathInfoHandled)) { httpContext.Items.Add(HttpContextItem_PathInfoHandled, true); } } /// [Obsolete("User PathInfoUsed property instead")] public static bool PathInfoHasBeenUsed() { return PathInfoUsed; } /// /// Gets a value indicating whether path info part of C1 page url has been used. /// /// /// true if path info has been used; otherwise, false. /// public static bool PathInfoUsed { get { var httpContext = HttpContext.Current; return httpContext != null && httpContext.Items.Contains(HttpContextItem_PathInfoHandled); } } /// public override RouteData GetRouteData(HttpContextBase context) { if (!SystemSetupFacade.IsSystemFirstTimeInitialized) { return null; } string localPath = context.Request.Url.LocalPath; if (IsPagePreviewPath(localPath) && PagePreviewContext.TryGetPreviewKey(context.Request, out Guid previewKey)) { var page = PagePreviewContext.GetPage(previewKey); if (page == null) throw new InvalidOperationException("Not preview information found by key: " + previewKey); return new RouteData(this, new C1PageRouteHandler(new PageUrlData(page))); } if (UrlUtils.IsAdminConsoleRequest(localPath) || IsRenderersPath(localPath)) { return null; } var urlProvider = PageUrls.UrlProvider; string currentUrl = context.Request.Url.OriginalString; UrlKind urlKind; PageUrlData pageUrlData = urlProvider.ParseUrl(currentUrl, out urlKind); if (pageUrlData == null || urlKind == UrlKind.Renderer) { return null; } var urlSpace = new UrlSpace(context); // Redirecting friendly urls to public urls if (urlKind == UrlKind.Friendly || urlKind == UrlKind.Redirect || urlKind == UrlKind.Internal) { if(pageUrlData.PathInfo == "/") { pageUrlData.PathInfo = null; } string publicUrl = urlProvider.BuildUrl(pageUrlData, UrlKind.Public, urlSpace); if(publicUrl == null) { if (urlKind != UrlKind.Internal) { return null; } // Rendering internal url if public url is missing } else { return GetRedirectRoute(publicUrl); } } Verify.That(urlKind == UrlKind.Public || urlKind == UrlKind.Internal, "Unexpected url kind '{0}", urlKind); bool isPublicUrl = urlKind == UrlKind.Public; if (isPublicUrl) { // If url ends with a trailing slash - doing a redirect. F.e. http://localhost/a/ -> http://localhost/a if (pageUrlData.PathInfo == "/") { pageUrlData.PathInfo = null; return GetRedirectRoute(urlProvider.BuildUrl(pageUrlData, UrlKind.Public, urlSpace)); } // Checking casing in url, so the same page will not appear as a few pages by a crawler string correctUrl = urlProvider.BuildUrl(pageUrlData, UrlKind.Public, urlSpace); Verify.IsNotNull(correctUrl, "Failed to rebuild a public url from url '{0}'", currentUrl); string originalFilePath = new UrlBuilder(currentUrl).RelativeFilePath; string correctFilePath = new UrlBuilder(correctUrl).RelativeFilePath; string decodedOriginalPath = HttpUtility.UrlDecode(originalFilePath); string decodedCorrectFilePath = HttpUtility.UrlDecode(correctFilePath); if (!urlSpace.ForceRelativeUrls && (originalFilePath.Length != correctFilePath.Length && decodedOriginalPath != correctFilePath && decodedOriginalPath != decodedCorrectFilePath) || (string.Compare(originalFilePath, correctFilePath, false, CultureInfo.InvariantCulture) != 0 && string.Compare(originalFilePath, correctFilePath, true, CultureInfo.InvariantCulture) == 0) && decodedOriginalPath != decodedCorrectFilePath) { // redirect to a url with right casing return GetRedirectRoute(correctUrl); } } // GetRouteData may be executed multiple times if (!context.Items.Contains(HttpContextItem_C1PageUrl)) { PageUrlData = pageUrlData; } var data = new RouteData(this, new C1PageRouteHandler(pageUrlData)); data.Values.Add(RouteData_PageUrl, pageUrlData); return data; } /// public void Dispose() { } private static bool IsRenderersPath(string relativeUrl) { return relativeUrl.StartsWith(UrlUtils.RenderersRootPath + "/", true); } private static bool IsPagePreviewPath(string relativeUrl) { return relativeUrl.StartsWith($"{UrlUtils.RenderersRootPath}/PagePreview", true); } private RouteData GetRedirectRoute(string url) { return new RouteData(this, new SeoFriendlyRedirectRouteHandler(url)); } /// public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) { return null; } } } ================================================ FILE: Composite/Core/Routing/Pages/C1PageRouteHander.cs ================================================ using System; using System.Diagnostics.CodeAnalysis; using System.Collections.Concurrent; using System.Linq; using System.Web; using System.Web.Compilation; using System.Web.Configuration; using System.Web.Hosting; using System.Web.Routing; using System.Web.UI; using System.Xml.Linq; using Composite.AspNet; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.PageTemplates; namespace Composite.Core.Routing.Pages { /// /// A route handler for the "C1 page" route. /// public class C1PageRouteHandler : IRouteHandler { private const string PageHandlerPath = "Renderers/Page.aspx"; private const string PageHandlerVirtualPath = "~/" + PageHandlerPath; private readonly PageUrlData _pageUrlData; private static readonly Type _handlerType; [SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass")] static C1PageRouteHandler() { bool isIntegratedPipeline = HttpRuntime.UsingIntegratedPipeline; string sectionName = isIntegratedPipeline ? "system.webServer" : "system.web"; var config = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath).GetSection(sectionName); if (config != null) { string handlersSectionName = isIntegratedPipeline ? "handlers" : "httpHandlers"; var handlers = XElement.Parse(config.SectionInformation.GetRawXml()).Element(handlersSectionName); if(handlers == null) { return; } var handler = handlers .Elements("add") .Where(e => e.Attribute("path")?.Value.Equals(PageHandlerPath, StringComparison.OrdinalIgnoreCase) ?? false) .SingleOrDefaultOrException($"Multiple handlers for '{PageHandlerPath}' were found'"); if (handler != null) { var typeAttr = handler.Attribute("type"); Verify.IsNotNull(typeAttr, "'type' attribute is missing"); _handlerType = Type.GetType(typeAttr.Value); if(_handlerType == null) { Log.LogError(nameof(C1PageRouteHandler), $"Failed to load type '{typeAttr.Value}'"); } } } } /// /// Creates a new instance of . /// /// public C1PageRouteHandler(PageUrlData pageUrlData) { _pageUrlData = pageUrlData; } /// public IHttpHandler GetHttpHandler(RequestContext requestContext) { var context = requestContext.HttpContext; string localPath = context.Request.Url.LocalPath; string pathInfo = _pageUrlData.PathInfo; // Doing a url rewriting so ASP.NET will get correct FilePath/PathInfo properties if (!pathInfo.IsNullOrEmpty()) { string filePath = localPath.Substring(0, localPath.Length - pathInfo.Length); string queryString = context.Request.Url.Query; if (queryString.StartsWith("?")) { queryString = queryString.Substring(1); } context.RewritePath(filePath, pathInfo, queryString); } if (_handlerType == null && GlobalSettingsFacade.OmitAspNetWebFormsSupport) { var page = _pageUrlData.GetPage() ?? throw new HttpException(404, "Page not found - either this page has not been published yet or it has been deleted."); if (IsSlimPageRenderer(page.TemplateId)) { return new CmsPageHttpHandler(); } } // Disabling ASP.NET cache if there's a logged-in user if (Composite.C1Console.Security.UserValidationFacade.IsLoggedIn()) { context.Response.Cache.SetCacheability(HttpCacheability.NoCache); } if (_handlerType != null) { return (IHttpHandler)Activator.CreateInstance(_handlerType); } return (IHttpHandler)BuildManager.CreateInstanceFromVirtualPath(PageHandlerVirtualPath, typeof(Page)); } private static readonly ConcurrentDictionary _pageRendererTypCache = new ConcurrentDictionary(); private bool IsSlimPageRenderer(Guid pageTemplate) { return _pageRendererTypCache.GetOrAdd(pageTemplate, templateId => PageTemplateFacade.BuildPageRenderer(templateId) is ISlimPageRenderer); } } } ================================================ FILE: Composite/Core/Routing/Pages/SeoFriendlyRedirectHttpHandler.cs ================================================ using System.Web; namespace Composite.Core.Routing.Pages { internal class SeoFriendlyRedirectHttpHandler: IHttpHandler { private readonly string _redirectUrl; public SeoFriendlyRedirectHttpHandler(string redirectUrl) { _redirectUrl = redirectUrl; } public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext context) { context.Response.AddHeader("Location", _redirectUrl); context.Response.StatusCode = 301; // Http 301 - "Permanently moved" context.ApplicationInstance.CompleteRequest(); } } } ================================================ FILE: Composite/Core/Routing/Pages/SeoFriendlyRedirectRouteHandler.cs ================================================ using System.Web; using System.Web.Routing; namespace Composite.Core.Routing.Pages { /// /// A route handler that performs an HTTP redirect with response code 301 (Permanently moved). /// public class SeoFriendlyRedirectRouteHandler: IRouteHandler { private readonly string _redirectUrl; /// /// Creates a new instance of /// /// The URL to redirect to. public SeoFriendlyRedirectRouteHandler(string redirectUrl) { _redirectUrl = redirectUrl; } /// public IHttpHandler GetHttpHandler(RequestContext requestContext) { return new SeoFriendlyRedirectHttpHandler(_redirectUrl); } } } ================================================ FILE: Composite/Core/Routing/Plugins/PageUrlsProviders/IPageUrlBuilder.cs ================================================ using System; using Composite.Data.Types; namespace Composite.Core.Routing.Plugins.PageUrlsProviders { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete] public interface IPageUrlBuilder { /// /// Gets url information for a page /// /// A page /// Id of parent page, to be used for optimization purposes /// PageUrlSet BuildUrlSet(IPage page, Guid parentPageId); } } ================================================ FILE: Composite/Core/Routing/Plugins/PageUrlsProviders/IPageUrlProvider.cs ================================================ using System; using System.Globalization; using Composite.Core.Routing.Plugins.PageUrlsProviders.Runtime; using Composite.Data; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Routing.Plugins.PageUrlsProviders { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [CustomFactory(typeof(PageUrlProviderCustomFactory))] public interface IPageUrlProvider { /// /// Creates a new instance of PageUrlBuilder which will be used while building a C1 pages sitemap /// /// The publication scope. /// The localization scope. /// The URL space. Is used for providing different urls for f.e. different hostnames, etc. /// [Obsolete] IPageUrlBuilder CreateUrlBuilder(PublicationScope publicationScope, CultureInfo localizationScope, UrlSpace urlSpace); /// bool IsInternalUrl(string relativeUrl); /// PageUrlData ParseInternalUrl(string relativeUrl); /// PageUrlData ParseUrl(string relativeUrl, UrlSpace urlSpace, out UrlKind urlKind); /// PageUrlData ParseUrl(string absoluteUrl, out UrlKind urlKind); /// string BuildUrl(PageUrlData pageUrlData, UrlKind urlKind, UrlSpace urlSpace); } } ================================================ FILE: Composite/Core/Routing/Plugins/PageUrlsProviders/PageUrlSet.cs ================================================ namespace Composite.Core.Routing.Plugins.PageUrlsProviders { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class PageUrlSet { /// /// Url by which page will be accessable /// public string PublicUrl { get; set; } /// /// Friendly url, requesting this url will lead to a redirect to PublicUrl /// public string FriendlyUrl { get; set; } } } ================================================ FILE: Composite/Core/Routing/Plugins/PageUrlsProviders/Runtime/NonConfigurablePageUrlProvider.cs ================================================ using System; using Microsoft.Practices.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Routing.Plugins.PageUrlsProviders.Runtime { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Assembler(typeof(NonConfigurablePageUrlProviderAssembler))] public sealed class NonConfigurablePageUrlProvider : PageUrlProviderData { } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class NonConfigurablePageUrlProviderAssembler : IAssembler { /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IPageUrlProvider Assemble(IBuilderContext context, PageUrlProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IPageUrlProvider)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/Core/Routing/Plugins/PageUrlsProviders/Runtime/PageUrlProviderCustomFactory.cs ================================================ using System.Configuration; using Composite.Core.Extensions; using Composite.Core.Routing.Plugins.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Routing.Plugins.PageUrlsProviders.Runtime { internal sealed class PageUrlProviderCustomFactory : AssemblerBasedCustomFactory { protected override PageUrlProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { string section = UrlsConfiguration.SectionName; var settings = configurationSource.GetSection(section) as UrlsConfiguration; if (null == settings) { throw new ConfigurationErrorsException("The configuration section '{0}' was not found in the configuration".FormatWith(section)); } return settings.PageUrlProviders.Get(name); } } } ================================================ FILE: Composite/Core/Routing/Plugins/PageUrlsProviders/Runtime/PageUrlProviderData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Routing.Plugins.PageUrlsProviders.Runtime { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ConfigurationElementType(typeof(NonConfigurablePageUrlProvider))] public class PageUrlProviderData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/Core/Routing/Plugins/PageUrlsProviders/Runtime/PageUrlProviderFactory.cs ================================================ using Composite.Core.Configuration; using Composite.Core.Routing.Plugins.PageUrlsProviders; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Routing.Plugins.PageUrlsProviders.Runtime { internal sealed class PageUrlProviderFactory : NameTypeFactoryBase { public PageUrlProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/Core/Routing/Plugins/Runtime/UrlsConfiguration.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Composite.Core.Routing.Plugins.PageUrlsProviders.Runtime; using Composite.Core.Routing.Plugins.UrlFormatters.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Routing.Plugins.Runtime { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class UrlsConfiguration : SerializableConfigurationSection { /// public const string SectionName = "Composite.Core.Urls"; private const string _defaultPageUrlProviderNameProperty = "defaultPageUrlProviderName"; /// [ConfigurationProperty(_defaultPageUrlProviderNameProperty, IsRequired = true)] public string DefaultPageUrlProviderName { get { return (string)base[_defaultPageUrlProviderNameProperty]; } set { base[_defaultPageUrlProviderNameProperty] = value; } } private const string _pageUrlProvidersProperty = "PageUrlProviders"; /// [ConfigurationProperty(_pageUrlProvidersProperty)] public NameTypeManagerTypeConfigurationElementCollection PageUrlProviders { get { return (NameTypeManagerTypeConfigurationElementCollection)base[_pageUrlProvidersProperty]; } } private const string _urlFormattersProperty = "UrlFormatters"; /// [ConfigurationProperty(_urlFormattersProperty)] public NameTypeManagerTypeConfigurationElementCollection UrlFormatters { get { return (NameTypeManagerTypeConfigurationElementCollection)base[_urlFormattersProperty]; } } } } ================================================ FILE: Composite/Core/Routing/Plugins/UrlFormatters/IUrlFormatter.cs ================================================ using Composite.Core.Routing.Plugins.UrlFormatters.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Routing.Plugins.UrlFormatters { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [CustomFactory(typeof(UrlFormatterCustomFactory))] public interface IUrlFormatter { /// string FormatUrl(string url); } } ================================================ FILE: Composite/Core/Routing/Plugins/UrlFormatters/Runtime/NonConfigurableUrlFormatter.cs ================================================ using System; using Microsoft.Practices.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Routing.Plugins.UrlFormatters.Runtime { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Assembler(typeof(NonConfigurableUrlFormatterAssembler))] public sealed class NonConfigurableUrlFormatter : UrlFormatterData { } /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class NonConfigurableUrlFormatterAssembler : IAssembler { /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IUrlFormatter Assemble(IBuilderContext context, UrlFormatterData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IUrlFormatter)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/Core/Routing/Plugins/UrlFormatters/Runtime/UrlFormatterCustomFactory.cs ================================================ using System.Configuration; using Composite.Core.Extensions; using Composite.Core.Routing.Plugins.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Routing.Plugins.UrlFormatters.Runtime { internal sealed class UrlFormatterCustomFactory : AssemblerBasedCustomFactory { protected override UrlFormatterData GetConfiguration(string name, IConfigurationSource configurationSource) { string section = UrlsConfiguration.SectionName; var settings = configurationSource.GetSection(section) as UrlsConfiguration; if (null == settings) { throw new ConfigurationErrorsException("The configuration section '{0}' was not found in the configuration".FormatWith(section)); } return settings.UrlFormatters.Get(name); } } } ================================================ FILE: Composite/Core/Routing/Plugins/UrlFormatters/Runtime/UrlFormatterData.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Routing.Plugins.UrlFormatters.Runtime { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ConfigurationElementType(typeof(NonConfigurableUrlFormatter))] public class UrlFormatterData : NameTypeManagerTypeConfigurationElement { private const string MandatoryPropertyName = "mandatory"; /// [ConfigurationProperty(MandatoryPropertyName, IsRequired = true)] public bool Mandatory { get { return (bool)this[MandatoryPropertyName]; } set { this[MandatoryPropertyName] = value; } } } } ================================================ FILE: Composite/Core/Routing/Plugins/UrlFormatters/Runtime/UrlFormatterFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Routing.Plugins.UrlFormatters.Runtime { internal sealed class UrlFormatterFactory : NameTypeFactoryBase { public UrlFormatterFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/Core/Routing/Routes.cs ================================================ using System; using System.Web.Routing; using Composite.Core.Routing.Pages; using Composite.Core.WebClient; namespace Composite.Core.Routing { /// /// Allows adding custom routes with a priority in relation to defined by CompositeC1 routes. /// public static class Routes { /// [Obsolete("Use RegisterPageRoute() and Register404Route() instead", true)] public static void Register() { var routes = RouteTable.Routes; RegisterPageRoute(routes); Register404Route(routes); } /// /// Registers C1's page route. /// public static void RegisterPageRoute(RouteCollection routes) { routes.Ignore("Composite/{*pathInfo}"); routes.Ignore("{resource}.axd/{*pathInfo}"); AddFunctionBoxRoute(routes); AddSiteMapRoutes(routes); if (OnBeforePageRouteAdded != null) { OnBeforePageRouteAdded(routes); } routes.Add("c1 page route", new C1PageRoute()); if (OnAfterPageRouteAdded != null) { OnAfterPageRouteAdded(routes); } } /// /// Registers C1's 404 route that catches all requests. /// This method should be called only after all other routes are registered. /// public static void Register404Route(RouteCollection routes) { // Ignoring routes that shouldn't be caught by 404 handler routes.Ignore("Renderers/{*pathInfo}"); routes.Ignore("{*all_css_aspx}", new { all_css_aspx = @".*\.css.aspx(/.*)?" }); routes.Add("c1 404 route", new PageNotFoundRoute()); } private static void AddSiteMapRoutes(RouteCollection routes) { routes.Ignore("sitemap.xml"); routes.Ignore("{language}/sitemap.xml"); routes.Ignore("{language}/{urlTitle}/sitemap.xml"); } private static void AddFunctionBoxRoute(RouteCollection routes) { routes.Add("c1 function image", new FunctionBoxRoute()); routes.Add("c1 template preview", new TemplatePreviewRoute()); } /// /// Occurs before C1 page route is added. /// public static event RouteRegistration OnBeforePageRouteAdded; /// /// Occurs after C1 page route is added. /// public static event RouteRegistration OnAfterPageRouteAdded; /// /// Handles route registration /// /// The route collection. public delegate void RouteRegistration(RouteCollection routeCollection); } } ================================================ FILE: Composite/Core/Routing/UrlKind.cs ================================================ namespace Composite.Core.Routing { /// /// Url kind /// public enum UrlKind { /// Undefined = 0, /// /// A main, human friendly url by which a resource is accessed. F.e.: /// Page: "/Home/About" /// An image: "/media/6fb4c70b-12a6-4522-add6-1f40828c5452/Sample images/Colors of Inspiration.jpg" /// Public = 1, /// /// Url to an ASP.NET handler. F.e. link to a page: "/Renderers/Page.aspx?id=7446ceda-df90-49f0-a183-4e02ed6f6eec" /// Renderer url is expected to be handled without routing. /// Renderer = 2, /// /// The way links are kept in html content /// For pages /// Short: ~/page({Page id}) /// Full: ~/page({Page id})[ /c1mode(unpublished) ][ /{PathInfo} ][ ?{Query string} ] /// For media archive /// Short: ~/media({Media file Id}) /// Full: ~/media([{Media store}:]{Media file Id})[ ?{Query string} ] /// Internal = 5, /// /// Friendly url. A short url, by accessing which C1 will make a redirect to related "public" url /// Friendly = 3, /// /// Redirect url. As in the case of "friendly urls", is used for supporting obsolete urls /// Redirect = 4 } } ================================================ FILE: Composite/Core/Routing/UrlSpace.cs ================================================ using System.Web; using Composite.Plugins.Routing.Pages; namespace Composite.Core.Routing { /// /// Allows producing different urls for different hostnames, also to forcibly produce relative urls when needed /// (f.e. browsing in a console, where an iframe source has to point to the same hostname). /// public class UrlSpace { internal UrlSpace(string hostname) { Hostname = hostname; ForceRelativeUrls = false; } internal UrlSpace(string hostname, string relativeUrl) { Initialize(hostname, relativeUrl); } /// /// Initializes a new instance of the class. /// public UrlSpace() { var httpContext = System.Web.HttpContext.Current; if(httpContext != null) { InitializeThroughHttpContext(httpContext); } } /// /// Initializes a new instance of the class. /// /// The HTTP context. public UrlSpace(HttpContext httpContext) { Verify.ArgumentNotNull(httpContext, "httpContext"); InitializeThroughHttpContext(httpContext); } /// /// Initializes a new instance of the class. /// /// The HTTP context base. public UrlSpace(HttpContextBase httpContextBase) { Verify.ArgumentNotNull(httpContextBase, "httpContextBase"); var url = httpContextBase.Request.Url; Initialize(url.Host, url.LocalPath); } private void InitializeThroughHttpContext(HttpContext httpContext) { Initialize(httpContext.Request.Url.Host, httpContext.Request.Url.LocalPath); } private void Initialize(string hostname, string relativeUrl) { ForceRelativeUrls = HttpUtility.UrlDecode(relativeUrl).Contains(DefaultPageUrlProvider.UrlMarker_RelativeUrl); if (!ForceRelativeUrls) { Hostname = hostname; } } /// /// Gets or sets the hostname. /// /// /// The hostname. /// public string Hostname { get; set; } /// /// Disables hostname bindings, so all output urls will be relative. Is used in in-console preview. /// public bool ForceRelativeUrls { get; set; } } } ================================================ FILE: Composite/Core/Serialization/CodeGeneration/Foundation/ISerializer.cs ================================================ using System.Text; using System.Collections.Generic; namespace Composite.Core.Serialization.CodeGeneration.Foundation { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface ISerializer { /// object Deserialize(Dictionary objectState); } } ================================================ FILE: Composite/Core/Serialization/CodeGeneration/PropertySerializerManager.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Events; using Composite.Core.Collections.Generic; using Composite.Core.Serialization.CodeGeneration.Foundation; using Composite.Core.Types; namespace Composite.Core.Serialization.CodeGeneration { internal static class PropertySerializerManager { private static readonly ResourceLocker ResourceLocker = new ResourceLocker(new Resources(), Resources.Initialize, false); static PropertySerializerManager() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } /// /// Returns a property serializer for the given property type. /// If no serializer exists, one will be runtime code generated. /// /// /// public static ISerializer GetPropertySerializer(Type propertyClassType) { ISerializer serializer; if (!ResourceLocker.Resources.SerializersTypesCache.TryGetValue(propertyClassType, out serializer)) { using (ResourceLocker.Locker) { if (!ResourceLocker.Resources.SerializersTypesCache.TryGetValue(propertyClassType, out serializer)) { Type propertySerializerType = GetPropertySerializerType(propertyClassType); serializer = (ISerializer)Activator.CreateInstance(propertySerializerType); ResourceLocker.Resources.SerializersTypesCache.Add(propertySerializerType, serializer); } } } return serializer; } private static Type GetPropertySerializerType(Type propertyClassType) { string propertySerializerTypeName = PropertySerializerTypeCodeGenerator.CreateSerializerClassFullName(propertyClassType); Type propertySerializerType = TypeManager.TryGetType(propertySerializerTypeName); if (propertySerializerType == null) { propertySerializerType = CodeGeneratePropertySerializer(propertyClassType); } return propertySerializerType; } private static Type CodeGeneratePropertySerializer(Type propertyClassType) { CodeGenerationBuilder codeGenerationBuilder = new CodeGenerationBuilder("PropertySerializer: " + propertyClassType.FullName); PropertySerializerTypeCodeGenerator.AddPropertySerializerTypeCode(codeGenerationBuilder, propertyClassType); IEnumerable types = CodeGenerationManager.CompileRuntimeTempTypes(codeGenerationBuilder); return types.Single(); } private static void Flush() { ResourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private sealed class Resources { public Dictionary SerializersTypesCache; public static void Initialize(Resources resources) { resources.SerializersTypesCache = new Dictionary(); } } } } ================================================ FILE: Composite/Core/Serialization/CodeGeneration/PropertySerializerTypeCodeGenerator.cs ================================================ using System; using System.CodeDom; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text; using Composite.Core.Serialization.CodeGeneration.Foundation; using Composite.Core.Types; namespace Composite.Core.Serialization.CodeGeneration { /// /// This class creates the CodeDOM for a given property class /// internal static class PropertySerializerTypeCodeGenerator { private const string NamespaceName = "CompositeGenerated.PropertySerializers"; internal static void AddPropertySerializerTypeCode(CodeGenerationBuilder codeGenerationBuilder, Type propertyClassType) { codeGenerationBuilder.AddReference(propertyClassType.Assembly); codeGenerationBuilder.AddReference(typeof(EditorBrowsableAttribute).Assembly); codeGenerationBuilder.AddReference(typeof(StringConversionServices).Assembly); CodeTypeDeclaration codeTypeDeclaration = CreateCodeTypeDeclaration(propertyClassType); codeGenerationBuilder.AddType(NamespaceName, codeTypeDeclaration); } internal static void AddPropertySerializerTypeCode(CodeGenerationBuilder codeGenerationBuilder, string propertyClassTypeName, IList> properties) { codeGenerationBuilder.AddReference(typeof(EditorBrowsableAttribute).Assembly); codeGenerationBuilder.AddReference(typeof(StringConversionServices).Assembly); CodeTypeDeclaration codeTypeDeclaration = CreateCodeTypeDeclaration(propertyClassTypeName, properties); codeGenerationBuilder.AddType(NamespaceName, codeTypeDeclaration); } internal static string CreateSerializerClassFullName(Type propertyClassType) { return NamespaceName + "." + CreateSerializerClassName(propertyClassType.FullName); } internal static CodeTypeDeclaration CreateCodeTypeDeclaration(Type propertyClassType) { var properties = GetSerializeableProperties(propertyClassType).Select(p => new Tuple(p.Name, p.PropertyType)).ToList(); return CreateCodeTypeDeclaration(propertyClassType.FullName, properties); } internal static CodeTypeDeclaration CreateCodeTypeDeclaration(string propertyClassTypeName, IList> properties) { string className = CreateSerializerClassName(propertyClassTypeName); CodeTypeDeclaration declaration = new CodeTypeDeclaration(className); declaration.IsClass = true; declaration.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed; declaration.BaseTypes.Add(typeof(ISerializer)); declaration.CustomAttributes.Add( new CodeAttributeDeclaration( new CodeTypeReference(typeof(EditorBrowsableAttribute)), new CodeAttributeArgument( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(EditorBrowsableState)), EditorBrowsableState.Never.ToString() ) ) ) ); AddDeserializeMethod(declaration, propertyClassTypeName, properties); return declaration; } private static void AddDeserializeMethod(CodeTypeDeclaration declaration, string propertyClassTypeName, IList> properties) { CodeMemberMethod method = new CodeMemberMethod(); method.Name = "Deserialize"; method.ReturnType = new CodeTypeReference(typeof(object)); method.Attributes = MemberAttributes.Public | MemberAttributes.Final; method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Dictionary), "objectState")); method.Statements.Add(new CodeVariableDeclarationStatement( propertyClassTypeName, "propertyClass", new CodeObjectCreateExpression(propertyClassTypeName) )); foreach (var property in properties) { Type propertyType; string methodName; if (property.Item2.IsArray == false) { propertyType = property.Item2; methodName = "DeserializeValue"; } else { propertyType = property.Item2.GetElementType(); methodName = "DeserializeValueArray"; } method.Statements.Add(new CodeAssignStatement( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression("propertyClass"), property.Item1 ), new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeTypeReferenceExpression(typeof(StringConversionServices)), methodName, new CodeTypeReference[] { new CodeTypeReference(propertyType), } ), new CodeExpression[] { new CodeArrayIndexerExpression( new CodeVariableReferenceExpression("objectState"), new CodeExpression[] { new CodePrimitiveExpression( property.Item1 ) } ), new CodePropertyReferenceExpression( new CodeVariableReferenceExpression("propertyClass"), property.Item1 ) } ) )); } method.Statements.Add(new CodeMethodReturnStatement( new CodeVariableReferenceExpression("propertyClass") )); declaration.Members.Add(method); } private static List GetSerializeableProperties(Type type) { List serializeableProperties = new List(); PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { if (UseableForSerialization(property)) { serializeableProperties.Add(property); } else { throw new SerializationException(string.Format("Property {1} on type {0} has type {2} which is not serializeable.", type.FullName, property.Name, property.PropertyType)); } } return serializeableProperties; } private static bool UseableForSerialization(PropertyInfo property) { bool isUseable = property.CanRead && property.CanWrite; if (isUseable) { foreach (MethodInfo mi in property.GetAccessors(false)) { isUseable = isUseable && mi.IsPublic; } } isUseable = isUseable && TypeUseableForSerialization(property.PropertyType); return isUseable; } private static bool TypeUseableForSerialization(Type propertyType) { if (propertyType.IsSerializable == false) { return false; } if (propertyType.IsAbstract && propertyType != typeof(Type)) { return false; } if (propertyType.IsCOMObject || propertyType.IsGenericType || propertyType.IsInterface) { return false; } return true; } private static string CreateSerializerClassName(string propertyClassTypeFullName) { return string.Format("{0}CustomSerializer", propertyClassTypeFullName.Replace('.', '_').Replace('+', '_')); } } } ================================================ FILE: Composite/Core/Serialization/CompositeCollectionValueXmlSerializer.cs ================================================ using System; using System.Linq; using System.Reflection; using System.Xml.Linq; using Composite.Core.Types; namespace Composite.Core.Serialization { internal sealed class CompositeCollectionValueXmlSerializer : IValueXmlSerializer { public bool TrySerialize(Type objectToSerializeType, object objectToSerialize, IXmlSerializer xmlSerializer, out XElement serializedObject) { if (objectToSerializeType == null) throw new ArgumentNullException("objectToSerializeType"); if (xmlSerializer == null) throw new ArgumentNullException("xmlSerializer"); serializedObject = null; MethodInfo methodInfo; if (objectToSerializeType.IsGenericType) { Type genericType = objectToSerializeType.GetGenericTypeDefinition(); string methodName; if (genericType == typeof(Pair<,>)) { methodName = "SerializePair"; } else { return false; } methodInfo = typeof(CompositeCollectionValueXmlSerializer).GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static); methodInfo = methodInfo.MakeGenericMethod(objectToSerializeType.GetGenericArguments()); } else { string methodName; if (objectToSerializeType == typeof(KeyValuePair)) { methodName = "SerializeKeyValuePair"; } else { return false; } methodInfo = typeof(CompositeCollectionValueXmlSerializer).GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static); } XElement result = methodInfo.Invoke(null, new object[] { objectToSerialize, xmlSerializer }) as XElement; string serializedType = TypeManager.SerializeType(objectToSerializeType); result.Add(new XAttribute("type", serializedType)); serializedObject = result; return true; } public bool TryDeserialize(XElement serializedObject, IXmlSerializer xmlSerializer, out object deserializedObject) { if (serializedObject == null) throw new ArgumentNullException("serializedObject"); if (xmlSerializer == null) throw new ArgumentNullException("xmlSerializer"); deserializedObject = null; XAttribute typeAttribute = serializedObject.Attribute("type"); if (typeAttribute == null) return false; Type type = TypeManager.GetType(typeAttribute.Value); MethodInfo methodInfo; if (type.IsGenericType) { Type genericType = type.GetGenericTypeDefinition(); string methodName; if (genericType == typeof(Pair<,>)) { methodName = "DeserializePair"; } else { return false; } methodInfo = typeof(CompositeCollectionValueXmlSerializer).GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static); methodInfo = methodInfo.MakeGenericMethod(type.GetGenericArguments()); } else { string methodName; if (type == typeof(KeyValuePair)) { methodName = "DeserializeKeyValuePair"; } else { return false; } methodInfo = typeof(CompositeCollectionValueXmlSerializer).GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static); } try { object result = methodInfo.Invoke(null, new object[] { serializedObject, xmlSerializer }); if (result != null) { deserializedObject = result; return true; } else { return false; } } catch (Exception) { return false; } } private static XElement SerializePair(Pair pairToSerialize, IXmlSerializer xmlSerializer) { XElement result = new XElement("Pair"); XElement serializedKey = xmlSerializer.Serialize(typeof(TKey), pairToSerialize.First); XElement serializedValue = xmlSerializer.Serialize(typeof(TValue), pairToSerialize.Second); result.Add(new XElement("First", serializedKey)); result.Add(new XElement("Second", serializedValue)); return result; } private static Pair DeserializePair(XElement serializedObject, IXmlSerializer xmlSerializer) { if (serializedObject.Name.LocalName != "Pair") throw new InvalidOperationException(); XElement keyElement = serializedObject.Element("First"); if (keyElement == null) throw new InvalidOperationException(); object keyValue = xmlSerializer.Deserialize(keyElement.Elements().Single()); XElement valueElement = serializedObject.Element("Second"); if (valueElement == null) throw new InvalidOperationException(); object valueValue = xmlSerializer.Deserialize(valueElement.Elements().Single()); Pair result = new Pair((TKey)keyValue, (TValue)valueValue); return result; } private static XElement SerializeKeyValuePair(KeyValuePair KeyValuePairToSerialize, IXmlSerializer xmlSerializer) { XElement result = new XElement("KeyValuePair"); XElement serializedKey = xmlSerializer.Serialize(typeof(string), KeyValuePairToSerialize.Key); XElement serializedValue = xmlSerializer.Serialize(typeof(string), KeyValuePairToSerialize.Value); result.Add(new XElement("Key", serializedKey)); result.Add(new XElement("Value", serializedValue)); return result; } private static KeyValuePair DeserializeKeyValuePair(XElement serializedObject, IXmlSerializer xmlSerializer) { if (serializedObject.Name.LocalName != "KeyValuePair") throw new InvalidOperationException(); XElement keyElement = serializedObject.Element("Key"); if (keyElement == null) return null; object keyValue = xmlSerializer.Deserialize(keyElement.Elements().Single()); XElement valueElement = serializedObject.Element("Value"); if (valueElement == null) return null; object valueValue = xmlSerializer.Deserialize(valueElement.Elements().Single()); KeyValuePair result = new KeyValuePair((string)keyValue, (string)valueValue); return result; } } } ================================================ FILE: Composite/Core/Serialization/CompositeJsonSerializer.cs ================================================ using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Security; using Composite.C1Console.Security; using Composite.Core.Types; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Composite.Core.Serialization { /// /// Use this class to serialize and deserialize objects with json serializer /// public static class CompositeJsonSerializer { private const string ObjectKeyString = "meta:obj"; private const string TypeKeyString = "meta:type"; private const string HashKeyString = "meta:hash"; /// /// Check if string is serialized with JsonSerializer /// /// /// public static bool IsJsonSerialized(string str) { return str.StartsWith("{"); } /// /// Serialize with automatic type name handling /// /// Object to serialize /// serialized string public static string Serialize(object obj) { var serializedData = JsonConvert.SerializeObject(obj, new JsonSerializerSettings { TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple, TypeNameHandling = TypeNameHandling.Auto, Converters = { new JsonTypeConverter() }, Binder = CompositeSerializationBinder.Instance }); return serializedData; } /// /// Serialize with json object structure type name handling /// /// Object to serialize /// serialized string public static string SerializeObject(object obj) { var serializedData = JsonConvert.SerializeObject(obj, new JsonSerializerSettings { TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple, TypeNameHandling = TypeNameHandling.Objects, Formatting = Formatting.None, Converters = { new JsonTypeConverter() }, Binder = CompositeSerializationBinder.Instance }); return serializedData; } /// /// Serialize only the property names that is specified /// /// Object to serialize /// List of properties to be serialized /// serialized string public static string SerializePartial(object obj, IEnumerable propertyNames) { if (propertyNames == null) { return SerializeObject(obj); } var serializedData = JsonConvert.SerializeObject(obj, new JsonSerializerSettings { Converters = { new PartialJsonConvertor(propertyNames, obj.GetType()) } }); return serializedData; } /// /// Serialize with a wrapper containing the serialized object, its hash sign and its type /// /// Object to serialize /// To calculate the hash sign /// serialized string public static string Serialize(object obj, bool shouldSign) { var type = obj.GetType(); string serializedData; var methodInfo = type.GetMethod("Serialize"); if (methodInfo == null) { serializedData = Serialize(obj); } else { serializedData = (string)methodInfo.Invoke(obj, null); } var hash = shouldSign ? HashSigner.GetSignedHash(serializedData).GetHashCode() : 0; var serializedProperties = IsJsonSerialized(serializedData) ? serializedData.Substring(1, serializedData.Length - 2) : $@"""{ObjectKeyString}"":""{serializedData}"""; return "{" + serializedProperties + $@",""{TypeKeyString}"":""{GetSerializedTypeName(type)}""" + (shouldSign ? $@",""{HashKeyString}"":""{hash}""" : "") + "}"; } /// /// Deserialize string into object with specified type /// /// Serialized string /// Type of returned object /// The object public static T Deserialize(string str) { var obj = JsonConvert.DeserializeObject(str, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto, Binder = CompositeSerializationBinder.Instance, MaxDepth = 128 }); return obj; } /// /// Deserialize strings into object with specified type by merging them together /// /// Serialized string /// Type of returned object /// The object public static T Deserialize(params string[] strs) { var combinedObj = new JObject(); var mergeSettings = new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Union }; try { foreach (var s in strs) { combinedObj.Merge(JObject.Parse(s), mergeSettings); } } catch (Exception) { throw new ArgumentException("Cannot merge arguments into one"); } var obj = JsonConvert.DeserializeObject(combinedObj.ToString(), new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto, Binder = CompositeSerializationBinder.Instance, MaxDepth = 128 }); return obj; } /// /// Deserialize string into object /// /// Serialized string /// The object public static object Deserialize(string str) { var obj = JsonConvert.DeserializeObject(str, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, Binder = CompositeSerializationBinder.Instance, MaxDepth = 128 }); return obj; } /// /// Deserialize strings into object with specified type from a hash signed wrapper /// /// Serialized string /// Is signed /// Type of returned object /// The object public static T Deserialize(string str, bool isSigned) { var legacyStyleSerialized = str.StartsWith("{\"" + ObjectKeyString + "\":\""); string obj; var hash = 0; var typeName = str.GetValue(TypeKeyString); if (string.IsNullOrWhiteSpace(typeName)) { throw new SerializationException($"Failed to extract '{TypeKeyString}' property"); } var type = TypeManager.TryGetType(typeName); if (type == null) { throw new SerializationException($"Failed to resolve type '{typeName}'"); } if (isSigned) { if (!int.TryParse(str.GetValue(HashKeyString), out hash)) { throw new SerializationException($"Missing or invalid '{HashKeyString}' property"); } } if (legacyStyleSerialized) { obj = str.GetValue(ObjectKeyString); } else { obj = "{" + str.Substring(1, str.LastIndexOf(TypeKeyString, StringComparison.InvariantCulture) - 3) + "}"; } if (isSigned) { if (!HashSigner.ValidateSignedHash(obj, new HashValue(hash))) { throw new SecurityException($"Serialized {typeof(T).FullName} is tampered"); } } var methodInfo = type.GetMethod("Deserialize", BindingFlags.Public | BindingFlags.Static); if (methodInfo == null) { return Deserialize(obj); } if (!(typeof(T).IsAssignableFrom(methodInfo.ReturnType))) { Log.LogWarning("CompositeJsonSerializer", $"The action {typeName} is missing a public static Deserialize method taking a string as parameter and returning an {typeof(T)}"); throw new InvalidOperationException($"The token {typeName} is missing a public static Deserialize method taking a string as parameter and returning an {typeof(T)}"); } return (T)methodInfo.Invoke(null, new object[] { obj }); } private static string GetValue(this string str, string key) { var searchTerm = "\"" + key + "\":\""; var valueStartIndex = str.LastIndexOf(searchTerm, StringComparison.InvariantCulture) + searchTerm.Length; var valueLength = str.IndexOf("\"", valueStartIndex, StringComparison.InvariantCulture) - valueStartIndex; var value = str.Substring(valueStartIndex, valueLength); return value; } private static string GetSerializedTypeName(Type type) { return $"{type.FullName}, {type.Assembly.GetName().Name}"; } private class JsonTypeConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var type = (Type)value; writer.WriteValue(GetSerializedTypeName(type)); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override bool CanRead => false; public override bool CanConvert(Type objectType) { return typeof(Type).IsAssignableFrom(objectType); } } private class PartialJsonConvertor : JsonConverter { private readonly IEnumerable _propertyNames; private readonly Type _type; public PartialJsonConvertor(IEnumerable propertyNames, Type type) { _propertyNames = propertyNames; _type = type; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var o = new JObject(); o.AddFirst(new JProperty("$type", GetSerializedTypeName(_type))); var jsonSerializer = new JsonSerializer { TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple, TypeNameHandling = TypeNameHandling.Objects, Converters = { new JsonTypeConverter() } }; foreach (var property in _propertyNames) { o.Add(property, JToken.FromObject(GetPropValue(value, property), jsonSerializer)); } o.WriteTo(writer); } private static object GetPropValue(object src, string propName) { var prop = src.GetType().GetProperty(propName); if (prop == null) { throw new ArgumentException($"There is no {propName} in {src.GetType().FullName}"); } return prop.GetValue(src, null); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override bool CanConvert(Type objectType) { return true; } } } } ================================================ FILE: Composite/Core/Serialization/CompositeSerializationBinder.cs ================================================ using System; using System.Reflection; using System.Runtime.Serialization; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.Core.Types; using Composite.Data; using Newtonsoft.Json.Serialization; namespace Composite.Core.Serialization { /// /// Removes temporary assembly references when serializing references to generated classes. /// internal class CompositeSerializationBinder: DefaultSerializationBinder { private const string GeneratedTypesNamespacePrefix = "CompositeGenerated."; private const string GeneratedTypesAssemblyName = "Composite.Generated"; public static SerializationBinder Instance { get; } = new CompositeSerializationBinder(); public override void BindToName(Type serializedType, out string assemblyName, out string typeName) { typeName = serializedType.FullName; if (typeName.StartsWith(GeneratedTypesNamespacePrefix, StringComparison.OrdinalIgnoreCase) && Guid.TryParse(serializedType.Assembly.GetName().Name, out _)) { assemblyName = GeneratedTypesAssemblyName; } else { assemblyName = serializedType.Assembly.FullName; } } public override Type BindToType(string assemblyName, string typeName) { if (assemblyName == GeneratedTypesAssemblyName && typeName.StartsWith(GeneratedTypesNamespacePrefix, StringComparison.OrdinalIgnoreCase)) { var result = TypeManager.TryGetType($"{typeName}, {assemblyName}") ?? TypeManager.TryGetType(typeName); if (result != null) return result; } var type = base.BindToType(assemblyName, typeName); VerityTypeIsSupported(new AssemblyName(assemblyName), typeName, type); return type; } private void VerityTypeIsSupported(AssemblyName assemblyName, string typeFullName, Type type) { if (!TypeIsSupported(assemblyName, typeFullName, type)) { throw new NotSupportedException($"Not supported object type '{typeFullName}'"); } if (type.IsGenericType) { foreach (var typeArgument in type.GetGenericArguments()) { VerityTypeIsSupported(typeArgument.Assembly.GetName(), typeArgument.FullName, typeArgument); } } } private bool TypeIsSupported(AssemblyName assemblyName, string typeName, Type type) { if (assemblyName.Name == typeof(object).Assembly.GetName().Name /* "mscorlib" */) { var dotOffset = typeName.LastIndexOf(".", StringComparison.Ordinal); if (dotOffset > 0) { string @namespace = typeName.Substring(0, dotOffset); return @namespace == nameof(System) || @namespace.StartsWith("System.Collections"); } } return type != null && (type.IsEnum || typeof(EntityToken).IsAssignableFrom(type) || typeof(SearchToken).IsAssignableFrom(type) || typeof(IDataId).IsAssignableFrom(type) || type == typeof(DataSourceId) || type == typeof(DataScopeIdentifier)); } } } ================================================ FILE: Composite/Core/Serialization/ISerializerHandler.cs ================================================ namespace Composite.Core.Serialization { /// /// Handler to serialize and deserialize data for use in Workflows during ie. postbacks. /// public interface ISerializerHandler { /// /// Returns a string representation of an object /// /// /// string Serialize(object objectToSerialize); /// /// Returns the constructed object deserialized from the passed string /// /// /// object Deserialize(string serializedObject); } } ================================================ FILE: Composite/Core/Serialization/ISerializerHandlerFacade.cs ================================================  namespace Composite.Core.Serialization { internal interface ISerializerHandlerFacade { bool TrySerialize(object objectToSerialize, out string serializedObject, out string errorMessage); object Deserialize(string serializedObject); void OnFlush(); } } ================================================ FILE: Composite/Core/Serialization/IValueXmlSerializer.cs ================================================ using System; using System.Xml.Linq; namespace Composite.Core.Serialization { internal interface IValueXmlSerializer { bool TrySerialize(Type objectToSerializeType, object objectToSerialize, IXmlSerializer xmlSerializer, out XElement serializedObject); bool TryDeserialize(XElement serializedObject, IXmlSerializer xmlSerializer, out object deserializedObject); } } ================================================ FILE: Composite/Core/Serialization/IXmlSerializer.cs ================================================ using System; using System.Xml.Linq; namespace Composite.Core.Serialization { internal interface IXmlSerializer { XElement Serialize(Type objectToSerializeType, object objectToSerialize); object Deserialize(XElement serializedObject); } } ================================================ FILE: Composite/Core/Serialization/PrettyPrinter.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Data; using Composite.Core.Types; using Composite.Core.Linq; using Composite.Data.DynamicTypes; using System.Reflection; using System.Collections; using System.ComponentModel; namespace Composite.Core.Serialization { /// /// Used for printing a value to a string in a nice way. /// The result string will contain line feeds etc. /// It handles IData, Lists, Dictionaries, KeyValyePairs, Tupples etc. /// /// [EditorBrowsable(EditorBrowsableState.Never)] public static class PrettyPrinter { /// /// /// /// public static string Print(object result) { StringBuilder sb = new StringBuilder(); Print(result, sb, 0); return sb.ToString(); } private static void Print(object result, StringBuilder sb, int indentLevel, bool includeLineFeed = true) { if (result == null) { sb.AppendLine("(null)"); } else if ((result is IEnumerable) && (result.GetType() != typeof(string))) { IEnumerable enumerable = result as IEnumerable; List values = enumerable.ToListOfObjects(); sb.AppendLine(); int counter = 0; foreach (object value in values) { PrintIndent(sb, indentLevel); sb.Append("result[" + counter + "] : "); Print(value, sb, indentLevel + 1); counter++; } } else if (result is IData) { IData dataItem = result as IData; DataTypeDescriptor dataTypeDescriptor = Composite.Data.DynamicTypes.DynamicTypeManager.GetDataTypeDescriptor(dataItem.GetImmutableTypeId()); sb.AppendLine(dataItem.GetType().ToString()); PrintIndent(sb, indentLevel); sb.AppendLine("{"); foreach (DataFieldDescriptor dataFieldDescriptor in dataTypeDescriptor.Fields) { PropertyInfo propertyInfo = dataItem.GetType().GetPropertiesRecursively().Where(f => f.Name == dataFieldDescriptor.Name).First(); object value = propertyInfo.GetValue(dataItem, null); PrintIndent(sb, indentLevel + 1); sb.Append(dataFieldDescriptor.Name + " : "); if (value != null) sb.Append(value.ToString()); else sb.Append("(null)"); sb.AppendLine(", "); } PrintIndent(sb, indentLevel); sb.AppendLine("{"); } else if ((result.GetType().IsGenericType) && (result.GetType().GetGenericTypeDefinition() == typeof(KeyValuePair<,>))) { PropertyInfo keyPropertyInfo = result.GetType().GetProperty("Key"); PropertyInfo valuePropertyInfo = result.GetType().GetProperty("Value"); object keyValue = keyPropertyInfo.GetValue(result, null); object valueValue = valuePropertyInfo.GetValue(result, null); sb.Append("("); Print(keyValue, sb, indentLevel + 1, false); sb.Append(", "); Print(valueValue, sb, indentLevel + 1, false); sb.AppendLine(")"); } else if ((result.GetType().IsGenericType) && (result.GetType().GetGenericTypeDefinition() == typeof(Tuple<,>))) { PropertyInfo item1PropertyInfo = result.GetType().GetProperty("Item1"); PropertyInfo item2PropertyInfo = result.GetType().GetProperty("Item2"); object item1Value = item1PropertyInfo.GetValue(result, null); object item2Value = item2PropertyInfo.GetValue(result, null); sb.Append("("); Print(item1Value, sb, indentLevel + 1, false); sb.Append(", "); Print(item2Value, sb, indentLevel + 1, false); sb.AppendLine(")"); } else if ((result.GetType().IsGenericType) && (result.GetType().GetGenericTypeDefinition() == typeof(Tuple<,,>))) { PropertyInfo item1PropertyInfo = result.GetType().GetProperty("Item1"); PropertyInfo item2PropertyInfo = result.GetType().GetProperty("Item2"); PropertyInfo item3PropertyInfo = result.GetType().GetProperty("Item3"); object item1Value = item1PropertyInfo.GetValue(result, null); object item2Value = item2PropertyInfo.GetValue(result, null); object item3Value = item3PropertyInfo.GetValue(result, null); sb.Append("("); Print(item1Value, sb, indentLevel + 1, false); sb.Append(", "); Print(item2Value, sb, indentLevel + 1, false); sb.Append(", "); Print(item3Value, sb, indentLevel + 1, false); sb.AppendLine(")"); } else if ((result.GetType().IsGenericType) && (result.GetType().GetGenericTypeDefinition() == typeof(Tuple<,,,>))) { PropertyInfo item1PropertyInfo = result.GetType().GetProperty("Item1"); PropertyInfo item2PropertyInfo = result.GetType().GetProperty("Item2"); PropertyInfo item3PropertyInfo = result.GetType().GetProperty("Item3"); PropertyInfo item4PropertyInfo = result.GetType().GetProperty("Item4"); object item1Value = item1PropertyInfo.GetValue(result, null); object item2Value = item2PropertyInfo.GetValue(result, null); object item3Value = item3PropertyInfo.GetValue(result, null); object item4Value = item4PropertyInfo.GetValue(result, null); sb.Append("("); Print(item1Value, sb, indentLevel + 1, false); sb.Append(", "); Print(item2Value, sb, indentLevel + 1, false); sb.Append(", "); Print(item3Value, sb, indentLevel + 1, false); sb.Append(", "); Print(item4Value, sb, indentLevel + 1, false); sb.AppendLine(")"); } else if ((result.GetType().IsGenericType) && (result.GetType().GetGenericTypeDefinition() == typeof(Tuple<,,,,>))) { PropertyInfo item1PropertyInfo = result.GetType().GetProperty("Item1"); PropertyInfo item2PropertyInfo = result.GetType().GetProperty("Item2"); PropertyInfo item3PropertyInfo = result.GetType().GetProperty("Item3"); PropertyInfo item4PropertyInfo = result.GetType().GetProperty("Item4"); PropertyInfo item5PropertyInfo = result.GetType().GetProperty("Item5"); object item1Value = item1PropertyInfo.GetValue(result, null); object item2Value = item2PropertyInfo.GetValue(result, null); object item3Value = item3PropertyInfo.GetValue(result, null); object item4Value = item4PropertyInfo.GetValue(result, null); object item5Value = item5PropertyInfo.GetValue(result, null); sb.Append("("); Print(item1Value, sb, indentLevel + 1, false); sb.Append(", "); Print(item2Value, sb, indentLevel + 1, false); sb.Append(", "); Print(item3Value, sb, indentLevel + 1, false); sb.Append(", "); Print(item4Value, sb, indentLevel + 1, false); sb.Append(", "); Print(item5Value, sb, indentLevel + 1, false); sb.AppendLine(")"); } else { if (includeLineFeed) { sb.AppendLine(result.ToString()); } else { sb.Append(result.ToString()); } } } private static void PrintIndent(StringBuilder sb, int indentLevel) { for (int i = 0; i < indentLevel; i++) { sb.Append(" "); } } } } ================================================ FILE: Composite/Core/Serialization/PropertySerializerHandler.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using Composite.Core.Types; namespace Composite.Core.Serialization { class PropertySerializerHandler : ISerializerHandler { public string Serialize(object objectToSerialize) { if (objectToSerialize == null) throw new ArgumentNullException("objectToSerialize"); StringBuilder sb = new StringBuilder(); StringConversionServices.SerializeKeyValuePair(sb, "_Type_", TypeManager.SerializeType(objectToSerialize.GetType())); IEnumerable propertyInfos = from prop in objectToSerialize.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance) where prop.CanRead && prop.CanWrite select prop; foreach (PropertyInfo propertyInfo in propertyInfos) { MethodInfo methodInfo = (from mi in typeof(StringConversionServices).GetMethods(BindingFlags.Public | BindingFlags.Static) where mi.Name == "SerializeKeyValuePair" && mi.IsGenericMethodDefinition && mi.GetParameters().Length == 3 && mi.GetParameters()[2].ParameterType.IsGenericParameter select mi).SingleOrDefault(); methodInfo = methodInfo.MakeGenericMethod(new Type[] { propertyInfo.PropertyType }); object propertyValue = propertyInfo.GetValue(objectToSerialize, null); methodInfo.Invoke(null, new object[] { sb, propertyInfo.Name, propertyValue }); } return sb.ToString(); } public object Deserialize(string serializedObject) { Dictionary dic = StringConversionServices.ParseKeyValueCollection(serializedObject); if (dic.ContainsKey("_Type_") == false) throw new ArgumentException("serializedObject is of wrong format"); string typeString = StringConversionServices.DeserializeValueString(dic["_Type_"]); Type type = TypeManager.GetType(typeString); object obj = Activator.CreateInstance(type); IEnumerable propertyInfos = from prop in type.GetProperties(BindingFlags.Public | BindingFlags.Instance) where prop.CanRead && prop.CanWrite select prop; foreach (PropertyInfo propertyInfo in propertyInfos) { if (dic.ContainsKey(propertyInfo.Name) == false) throw new ArgumentException("serializedObject is of wrong format"); MethodInfo methodInfo = (from mi in typeof(StringConversionServices).GetMethods(BindingFlags.Public | BindingFlags.Static) where mi.Name == "DeserializeValue" && mi.IsGenericMethodDefinition && mi.GetParameters().Length == 2 && mi.GetParameters()[1].ParameterType.IsGenericParameter select mi).SingleOrDefault(); object defaultValue; if (propertyInfo.PropertyType == typeof(Guid)) defaultValue = default(Guid); else if (propertyInfo.PropertyType == typeof(string)) defaultValue = default(string); else if (propertyInfo.PropertyType == typeof(int)) defaultValue = default(int); else if (propertyInfo.PropertyType == typeof(DateTime)) defaultValue = default(DateTime); else if (propertyInfo.PropertyType == typeof(bool)) defaultValue = default(bool); else if (propertyInfo.PropertyType == typeof(decimal)) defaultValue = default(decimal); else if (propertyInfo.PropertyType == typeof(long)) defaultValue = default(long); else defaultValue = null; methodInfo = methodInfo.MakeGenericMethod(new Type[] { propertyInfo.PropertyType }); object propertyValue = methodInfo.Invoke(null, new object[] { dic[propertyInfo.Name], defaultValue }); propertyInfo.SetValue(obj, propertyValue, null); } return obj; } } } ================================================ FILE: Composite/Core/Serialization/SerializationFacade.cs ================================================ using System; using System.Collections.Generic; using Composite.Core.Collections.Generic; using Composite.C1Console.Events; using Composite.Core.Serialization.CodeGeneration; using Composite.Core.Serialization.CodeGeneration.Foundation; using Composite.Core.Types; namespace Composite.Core.Serialization { internal static class SerializationFacade { private static ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); static SerializationFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static object Deserialize(Type propertyClassType, string serializedProperties) { ISerializer serializer = GetSerializer(propertyClassType); Dictionary objectState = StringConversionServices.ParseKeyValueCollection(serializedProperties); return serializer.Deserialize(objectState); } public static T Deserialize(Type propertyClassType, string serializedProperties) { ISerializer serializer = GetSerializer(propertyClassType); Dictionary objectState = StringConversionServices.ParseKeyValueCollection(serializedProperties); return (T)serializer.Deserialize(objectState); } private static ISerializer GetSerializer(Type propertyClassType) { var reusourceLocker = _resourceLocker; var serializerCache = reusourceLocker.Resources.SerializerCache; ISerializer serializer; if (serializerCache.TryGetValue(propertyClassType, out serializer)) { return serializer; } using (reusourceLocker.Locker) { if (!serializerCache.TryGetValue(propertyClassType, out serializer)) { serializer = PropertySerializerManager.GetPropertySerializer(propertyClassType); serializerCache.Add(propertyClassType, serializer); } } return serializer; } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private sealed class Resources { public CompiledTypeCache SerializerCache { get; set; } public static void Initialize(Resources resources) { resources.SerializerCache = new CompiledTypeCache(); } } } } ================================================ FILE: Composite/Core/Serialization/SerializerHandlerAttribute.cs ================================================ using System; namespace Composite.Core.Serialization { /// /// Defines which is used to serialize and deserialize this class /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited = false)] public sealed class SerializerHandlerAttribute : Attribute { /// /// Defines which is used to serialize and deserialize this class /// /// public SerializerHandlerAttribute(Type serializerHandlerType) { this.SerializerHandlerType = serializerHandlerType; } /// /// The type which is used to serialize and deserialize the class the attribute is added to /// public Type SerializerHandlerType { get; private set; } } } ================================================ FILE: Composite/Core/Serialization/SerializerHandlerFacade.cs ================================================ using Composite.C1Console.Events; using System; namespace Composite.Core.Serialization { internal static class SerializerHandlerFacade { private static ISerializerHandlerFacade _implementation = new SerializerHandlerFacadeImpl(); internal static ISerializerHandlerFacade Implementation { get { return _implementation; } set { _implementation = value; } } static SerializerHandlerFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } // Overload public static string Serialize(object objectToSerialize) { string serializedObject; string errorMessage; if (TrySerialize(objectToSerialize, out serializedObject, out errorMessage) == false) { throw new InvalidOperationException(errorMessage); } return serializedObject; } public static bool TrySerialize(object objectToSerialize, out string serializedObject) { string errorMessage; return TrySerialize(objectToSerialize, out serializedObject, out errorMessage); } public static bool TrySerialize(object objectToSerialize, out string serializedObject, out string errorMessage) { return _implementation.TrySerialize(objectToSerialize, out serializedObject, out errorMessage); } public static object Deserialize(string serializedObject) { return _implementation.Deserialize(serializedObject); } private static void OnFlushEvent(FlushEventArgs args) { _implementation.OnFlush(); } } } ================================================ FILE: Composite/Core/Serialization/SerializerHandlerFacadeImpl.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Core.Types; namespace Composite.Core.Serialization { internal sealed class SerializerHandlerFacadeImpl : ISerializerHandlerFacade { private Dictionary _serializeHandlers = new Dictionary(); private readonly object _lock = new object(); public bool TrySerialize(object objectToSerialize, out string serializedObject, out string errorMessage) { if (objectToSerialize == null) throw new ArgumentNullException("objectToSerialize"); serializedObject = null; IEnumerable serializerHandlerAttributes = objectToSerialize.GetType().GetCustomAttributesRecursively(); if (serializerHandlerAttributes.Count() == 0) { errorMessage = string.Format("The type '{0}' has no '{1}' defined in its inherit tree", objectToSerialize.GetType(), typeof(SerializerHandlerAttribute)); return false; } SerializerHandlerAttribute serializerHandlerAttribute = serializerHandlerAttributes.First(); if (serializerHandlerAttribute.SerializerHandlerType == null) { errorMessage = string.Format("The type '{0}' has specified a null argument to the '{1}'", objectToSerialize.GetType(), typeof(SerializerHandlerAttribute)); return false; } if (typeof(ISerializerHandler).IsAssignableFrom(serializerHandlerAttribute.SerializerHandlerType) == false) { errorMessage = string.Format("The type '{0}' has specified a type that does not implement the '{1}' argument to the '{2}'", objectToSerialize.GetType(), typeof(ISerializerHandler), typeof(SerializerHandlerAttribute)); return false; } Type serializeHandlerType = serializerHandlerAttribute.SerializerHandlerType; ISerializerHandler serializerHandler; lock (_lock) { if (_serializeHandlers.TryGetValue(serializeHandlerType, out serializerHandler) == false) { serializerHandler = (ISerializerHandler)Activator.CreateInstance(serializeHandlerType); _serializeHandlers.Add(serializeHandlerType, serializerHandler); } } string serializedObj = serializerHandler.Serialize(objectToSerialize); StringBuilder sb = new StringBuilder(); StringConversionServices.SerializeKeyValuePair(sb, "SerializerHandlerType", TypeManager.SerializeType(serializerHandler.GetType())); StringConversionServices.SerializeKeyValuePair(sb, "SerializedObject", serializedObj); errorMessage = null; serializedObject = sb.ToString(); return true; } public object Deserialize(string serializedObject) { if (serializedObject == null) throw new ArgumentNullException("serializedObject"); Dictionary dic = StringConversionServices.ParseKeyValueCollection(serializedObject); if ((dic.ContainsKey("SerializerHandlerType") == false) || (dic.ContainsKey("SerializedObject") == false)) throw new InvalidOperationException("serializedObject is of wrong format"); string serilizerHandlerTypeString = StringConversionServices.DeserializeValueString(dic["SerializerHandlerType"]); Type serilizerHandlerType = TypeManager.GetType(serilizerHandlerTypeString); ISerializerHandler serializerHandler; lock (_lock) { if (_serializeHandlers.TryGetValue(serilizerHandlerType, out serializerHandler) == false) { serializerHandler = (ISerializerHandler)Activator.CreateInstance(serilizerHandlerType); _serializeHandlers.Add(serilizerHandlerType, serializerHandler); } } string serializedObjectString = StringConversionServices.DeserializeValueString(dic["SerializedObject"]); object resultObject = serializerHandler.Deserialize(serializedObjectString); return resultObject; } public void OnFlush() { _serializeHandlers = new Dictionary(); } } } ================================================ FILE: Composite/Core/Serialization/SerializerHandlerValueXmlSerializer.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using Composite.Data; namespace Composite.Core.Serialization { class SerializerHandlerValueXmlSerializer : IValueXmlSerializer { public bool TrySerialize(Type objectToSerializeType, object objectToSerialize, IXmlSerializer xmlSerializer, out XElement serializedObject) { if (objectToSerializeType == null) throw new ArgumentNullException("objectToSerializeType"); string serializedResult; bool result = SerializerHandlerFacade.TrySerialize(objectToSerialize, out serializedResult); if (result == false) { serializedObject = null; return false; } serializedObject = new XElement("SerializerHandler", new XAttribute("value", serializedResult)); return true; } public bool TryDeserialize(XElement serializedObject, IXmlSerializer xmlSerializer, out object deserializedObject) { if (serializedObject == null) throw new ArgumentNullException("serializedObject"); deserializedObject = null; if (serializedObject.Name.LocalName != "SerializerHandler") return false; XAttribute valueAttribute = serializedObject.Attribute("value"); if (valueAttribute == null) return false; try { deserializedObject = SerializerHandlerFacade.Deserialize(valueAttribute.Value); return true; } catch (DataSerilizationException) { throw; } catch (Exception) { return false; } } } } ================================================ FILE: Composite/Core/Serialization/StringConversionServices.cs ================================================ using System; using System.Linq; using System.Text; using System.ComponentModel; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Globalization; using System.Reflection; using System.Collections.Concurrent; namespace Composite.Core.Serialization { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class StringConversionServices { private const string _unencodedValueMarker = "'"; private const string _encodedValueMarker = "\\'"; private const string _unencodedEqualAndValueMarker = "=" + _unencodedValueMarker; private const string _keyValuePairRegExPattern = @"\s*(?[^=\s]*)\s*=\s*(?null|" + _unencodedValueMarker + @"(?[^" + _unencodedValueMarker + @"\\\r\n]*(\\.[^" + _unencodedValueMarker + @"\\\r\n]*)*)" + _unencodedValueMarker + @")\s*,*\s*"; private static Regex _keyValuePairRegEx = new Regex(_keyValuePairRegExPattern, RegexOptions.Compiled); private const string _listElementRegExPattern = @"\s*" + _unencodedValueMarker + @"(?[^" + _unencodedValueMarker + @"\\\r\n]*(\\.[^" + _unencodedValueMarker + @"\\\r\n]*)*)" + _unencodedValueMarker + @"\s*,*\s*"; private static Regex _listElementRegEx = new Regex(_listElementRegExPattern, RegexOptions.Compiled); private static readonly NumberFormatInfo _numberFormatInfo = CultureInfo.InvariantCulture.NumberFormat; // Caching private static readonly ConcurrentDictionary _serializeKeyValuePairMethodInfoCache = new ConcurrentDictionary(); private static readonly ConcurrentDictionary _deserializeValueMethodInfoCache = new ConcurrentDictionary(); #region DateTime /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, DateTime propertyValue) { builder.Append(propertyName); builder.Append(_unencodedEqualAndValueMarker); TypeConverter tc = TypeDescriptor.GetConverter(typeof(DateTime)); builder.Append(tc.ConvertToString(propertyValue)); builder.Append(_unencodedValueMarker); } /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, DateTime propertyValue) { SerializeKeyValuePair(builder, propertyName, propertyValue); } /// public static DateTime DeserializeValue(string stringRepresentation, DateTime deserializationTarget) { if (stringRepresentation == null) { return default(DateTime); } TypeConverter tc = TypeDescriptor.GetConverter(typeof(DateTime)); return (DateTime)tc.ConvertFromString(stringRepresentation); } /// public static DateTime DeserializeValueDateTime(string stringRepresentation) { return DeserializeValue(stringRepresentation, DateTime.Now); } #endregion #region int /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, int propertyValue) { builder.Append(propertyName); builder.Append(_unencodedEqualAndValueMarker); builder.Append(propertyValue.ToString()); builder.Append(_unencodedValueMarker); } /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, PT propertyValue, IEnumerable filterProperties) { if (filterProperties != null && !filterProperties.Contains(propertyName)) return; SerializeKeyValuePair(builder, propertyName, propertyValue); } /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, int propertyValue) { SerializeKeyValuePair(builder, propertyName, propertyValue); } /// public static int DeserializeValue(string stringRepresentation, int deserializationTarget) { if (stringRepresentation == null) { return default(int); } return Int32.Parse(stringRepresentation); } /// public static int DeserializeValueInt(string stringRepresentation) { return DeserializeValue(stringRepresentation, default(int)); } #endregion #region long /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, long propertyValue) { builder.Append(propertyName); builder.Append(_unencodedEqualAndValueMarker); builder.Append(propertyValue.ToString()); builder.Append(_unencodedValueMarker); } /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, long propertyValue) { SerializeKeyValuePair(builder, propertyName, propertyValue); } /// public static long DeserializeValue(string stringRepresentation, long deserializationTarget) { if (stringRepresentation == null) { return default(long); } return long.Parse(stringRepresentation); } /// public static long DeserializeValueLong(string stringRepresentation) { return DeserializeValue(stringRepresentation, default(long)); } #endregion #region decimal /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, decimal propertyValue) { builder.Append(propertyName); builder.Append(_unencodedEqualAndValueMarker); builder.Append(propertyValue.ToString(_numberFormatInfo)); builder.Append(_unencodedValueMarker); } /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, decimal propertyValue) { SerializeKeyValuePair(builder, propertyName, propertyValue); } /// public static decimal DeserializeValue(string stringRepresentation, decimal deserializationTarget) { if (stringRepresentation == null) { return default(decimal); } return decimal.Parse(stringRepresentation, _numberFormatInfo); } /// public static decimal DeserializeValueDecimal(string stringRepresentation) { return DeserializeValue(stringRepresentation, default(decimal)); } #endregion #region bool /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, bool propertyValue) { builder.Append(propertyName); builder.Append(_unencodedEqualAndValueMarker); builder.Append(propertyValue.ToString()); builder.Append(_unencodedValueMarker); } /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, bool propertyValue) { SerializeKeyValuePair(builder, propertyName, propertyValue); } /// public static bool DeserializeValue(string stringRepresentation, bool deserializationTarget) { if (stringRepresentation == null) { return default(bool); } return bool.Parse(stringRepresentation); } /// public static bool DeserializeValueBool(string stringRepresentation) { return DeserializeValue(stringRepresentation, default(bool)); } #endregion #region Guid /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, Guid propertyValue) { builder.Append(propertyName); builder.Append(_unencodedEqualAndValueMarker); builder.Append(propertyValue.ToString("D")); builder.Append(_unencodedValueMarker); } /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, Guid propertyValue) { SerializeKeyValuePair(builder, propertyName, propertyValue); } /// public static Guid DeserializeValue(string stringRepresentation, Guid deserializationTarget) { if (stringRepresentation == null) { return default(Guid); } return new Guid(stringRepresentation); } /// public static Guid DeserializeValueGuid(string stringRepresentation) { return DeserializeValue(stringRepresentation, Guid.Empty); } #endregion #region Type /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, Type propertyValue) { if (null == propertyValue) { builder.Append(propertyName); builder.Append("=null"); } else { builder.Append(propertyName); builder.Append(_unencodedEqualAndValueMarker); string typeString = String.Format("{0}, {1}", propertyValue.FullName, propertyValue.Assembly.FullName.Split(',')[0]); builder.Append(typeString); builder.Append(_unencodedValueMarker); } } /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, Type propertyValue) { SerializeKeyValuePair(builder, propertyName, propertyValue); } /// public static Type DeserializeValue(string stringRepresentation, Type deserializationTarget) { if (stringRepresentation == null) { return default(Type); } return Type.GetType(stringRepresentation); } /// public static Type DeserializeValueType(string stringRepresentation) { return DeserializeValue(stringRepresentation, default(Type)); } #endregion #region string /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, string propertyValue) { if (null == propertyValue) { builder.Append(propertyName); builder.Append("=null"); } else { builder.Append(propertyName); builder.Append(_unencodedEqualAndValueMarker); builder.Append(Escape(propertyValue)); builder.Append(_unencodedValueMarker); } } /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, string propertyValue) { SerializeKeyValuePair(builder, propertyName, propertyValue); } /// public static string DeserializeValue(string stringRepresentation, string deserializationTarget) { if (stringRepresentation == null) { return default(string); } return Unescape(stringRepresentation); } /// public static string DeserializeValueString(string stringRepresentation) { return DeserializeValue(stringRepresentation, ""); } #endregion #region Generic type /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, PT propertyValue) { if (null == propertyValue) { builder.Append(propertyName); builder.Append("=null"); } else { TypeConverter tc = TypeDescriptor.GetConverter(typeof(PT)); builder.Append(propertyName); builder.Append(_unencodedEqualAndValueMarker); builder.Append(Escape(tc.ConvertToString(propertyValue))); builder.Append(_unencodedValueMarker); } } /// public static PT DeserializeValue(string stringRepresentation, PT deserializationTarget) { if (stringRepresentation == null) { return default(PT); } TypeConverter tc = TypeDescriptor.GetConverter(typeof(PT)); return (PT)tc.ConvertFromString(Unescape(stringRepresentation)); } /// public static PT DeserializeValue(string stringRepresentation) where PT : class { return DeserializeValue(stringRepresentation, (PT)null); } #endregion #region array ([]) /// public static void SerializeKeyValueArrayPair(StringBuilder builder, string propertyName, PT[] propertyValue) { if (null != propertyValue) { TypeConverter tc = TypeDescriptor.GetConverter(typeof(PT)); Converter innerConverter = new Converter( delegate(PT target) { return Escape(tc.ConvertToString(target)); } ); string[] valuesAsStringArray = Array.ConvertAll(propertyValue as PT[], innerConverter); StringBuilder sb = new StringBuilder(); bool isFirst = true; foreach (string value in valuesAsStringArray) { if (isFirst) { isFirst = false; } { sb.Append(", "); } sb.Append(string.Format("{0}{1}{0}", _unencodedValueMarker, value)); } builder.Append(propertyName); builder.Append(_unencodedEqualAndValueMarker); builder.Append(Escape(sb.ToString())); builder.Append(_unencodedValueMarker); } else { // null value builder.Append(propertyName); builder.Append("=null"); } } /// public static void SerializeKeyValueArrayPair(StringBuilder builder, string propertyName, PT[] propertyValue,IEnumerable filterProperties) { if (filterProperties != null && !filterProperties.Contains(propertyName)) return; SerializeKeyValueArrayPair(builder, propertyName, propertyValue); } /// public static PT[] DeserializeValueArray(string stringRepresentation, PT[] deserializationTarget) { if (stringRepresentation != null) { string unescapedStringRepresentation = Unescape(stringRepresentation); string[] valuesAsStringArray = ParseElementList(unescapedStringRepresentation); TypeConverter tc = TypeDescriptor.GetConverter(typeof(PT)); Converter innerConverter = new Converter( delegate(string source) { return (PT)tc.ConvertFromString(Unescape(source)); } ); PT[] resultArray = Array.ConvertAll(valuesAsStringArray, innerConverter); return resultArray; } else { return null; } } /// public static PT[] DeserializeValueArray(string stringRepresentation) { return DeserializeValueArray(stringRepresentation, (PT[])null); } #endregion /// public static void SerializeKeyValuePair(StringBuilder builder, string propertyName, object propertyValue, Type propertyType) { Func factory = f => { MethodInfo method = (from mi in typeof(StringConversionServices).GetMethods(BindingFlags.Public | BindingFlags.Static) where mi.Name == "SerializeKeyValuePair" && mi.IsGenericMethodDefinition && mi.GetParameters().Length == 3 && mi.GetParameters()[2].ParameterType.IsGenericParameter select mi).SingleOrDefault(); method = method.MakeGenericMethod(new Type[] { f }); return method; }; MethodInfo methodInfo = _serializeKeyValuePairMethodInfoCache.GetOrAdd(propertyType, factory); methodInfo.Invoke(null, new object[] { builder, propertyName, propertyValue }); } /// public static object DeserializeValue(string stringRepresentation, Type propertyType) { Func factory = f => { MethodInfo method = (from mi in typeof(StringConversionServices).GetMethods(BindingFlags.Public | BindingFlags.Static) where mi.Name == "DeserializeValue" && mi.IsGenericMethodDefinition && mi.GetParameters().Length == 2 && mi.GetParameters()[1].ParameterType.IsGenericParameter select mi).SingleOrDefault(); method = method.MakeGenericMethod(new Type[] { f }); return method; }; object defaultValue; if (propertyType == typeof(Guid)) defaultValue = default(Guid); else if (propertyType == typeof(string)) defaultValue = default(string); else if (propertyType == typeof(int)) defaultValue = default(int); else if (propertyType == typeof(DateTime)) defaultValue = default(DateTime); else if (propertyType == typeof(bool)) defaultValue = default(bool); else if (propertyType == typeof(decimal)) defaultValue = default(decimal); else if (propertyType == typeof(long)) defaultValue = default(long); else defaultValue = null; MethodInfo methodInfo = _deserializeValueMethodInfoCache.GetOrAdd(propertyType, factory); object result = methodInfo.Invoke(null, new object[] { stringRepresentation, defaultValue }); return result; } /// public static Dictionary ParseKeyValueCollection(string keyValueCollectionString) { Dictionary parsed = new Dictionary(); MatchCollection matches = _keyValuePairRegEx.Matches(keyValueCollectionString); foreach (Match m in matches) { string key = m.Groups["Key"].Value; if (m.Groups["IsNull"].Value == "null") { parsed.Add(key, null); } else { string value = m.Groups["Value"].Value; parsed.Add(key, value); } } return parsed; } private static string[] ParseElementList(string elements) { MatchCollection matches = _listElementRegEx.Matches(elements); string[] result = new string[matches.Count]; int i = 0; foreach (Match m in matches) { result[i++] = m.Groups["Value"].Value; } return result; } private static string Escape(string sourceString) { return Regex.Escape(sourceString).Replace(_unencodedValueMarker, _encodedValueMarker); } private static string Unescape(string escapedStringRepresentation) { return Regex.Unescape(escapedStringRepresentation.Replace(_encodedValueMarker, _unencodedValueMarker)); } } } ================================================ FILE: Composite/Core/Serialization/SystemCollectionValueXmlSerializer.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Xml.Linq; using Composite.Core.Types; using Composite.Data; namespace Composite.Core.Serialization { internal sealed class SystemCollectionValueXmlSerializer : IValueXmlSerializer { public bool TrySerialize(Type objectToSerializeType, object objectToSerialize, IXmlSerializer xmlSerializer, out XElement serializedObject) { if (objectToSerializeType == null) throw new ArgumentNullException("objectToSerializeType"); if (xmlSerializer == null) throw new ArgumentNullException("xmlSerializer"); serializedObject = null; bool isArray = objectToSerializeType.IsArray; if (!objectToSerializeType.IsGenericType && !isArray) return false; if (isArray) { objectToSerializeType = objectToSerializeType.GetInterfaces() .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof (ICollection<>)); if (objectToSerializeType == null) { return false; } } Type genericType = objectToSerializeType.GetGenericTypeDefinition(); MethodInfo methodInfo; if (genericType == typeof(List<>) || genericType == typeof(ICollection<>)) { methodInfo = StaticReflection.GetGenericMethodInfo(o => SerializeCollection(null, null)); } else if (genericType == typeof(Dictionary<,>)) { methodInfo = StaticReflection.GetGenericMethodInfo(o => SerializeDictionary(null, null)); } else if (genericType == typeof(KeyValuePair<,>)) { methodInfo = StaticReflection.GetGenericMethodInfo(o => SerializeKeyValuePair(new KeyValuePair(), null)); } else { return false; } methodInfo = methodInfo.MakeGenericMethod(objectToSerializeType.GetGenericArguments()); XElement result = methodInfo.Invoke(null, new object[] { objectToSerialize, xmlSerializer }) as XElement; string serializedType = TypeManager.SerializeType(objectToSerializeType); result.Add(new XAttribute("type", serializedType)); serializedObject = result; return true; } public bool TryDeserialize(XElement serializedObject, IXmlSerializer xmlSerializer, out object deserializedObject) { if (serializedObject == null) throw new ArgumentNullException("serializedObject"); if (xmlSerializer == null) throw new ArgumentNullException("xmlSerializer"); deserializedObject = null; XAttribute typeAttribute = serializedObject.Attribute("type"); if (typeAttribute == null) return false; Type type = TypeManager.GetType(typeAttribute.Value); if (type.IsGenericType == false) return false; Type genericType = type.GetGenericTypeDefinition(); MethodInfo methodInfo; if (genericType == typeof(List<>)) { methodInfo = StaticReflection.GetGenericMethodInfo(o => DeserializeList(null, null)); } else if (genericType == typeof(Dictionary<,>)) { methodInfo = StaticReflection.GetGenericMethodInfo(o => DeserializeDictionary(null, null)); } else if (genericType == typeof(KeyValuePair<,>)) { methodInfo = StaticReflection.GetGenericMethodInfo(o => DeserializeKeyValuePair(null, null)); } else { return false; } methodInfo = methodInfo.MakeGenericMethod(type.GetGenericArguments()); try { object result = methodInfo.Invoke(null, new object[] { serializedObject, xmlSerializer }); if (result != null) { deserializedObject = result; return true; } return false; } catch (TargetInvocationException exception) { if (exception.InnerException is DataSerilizationException) { throw exception.InnerException; } return false; } catch (Exception) { return false; } } private static XElement SerializeCollection(ICollection listToSerialize, IXmlSerializer xmlSerializer) { XElement result = new XElement("List"); if (listToSerialize == null) return result; foreach (T itemValue in listToSerialize) { XElement serializedItemValue = xmlSerializer.Serialize(typeof(T), itemValue); result.Add(serializedItemValue); } return result; } private static List DeserializeList(XElement serializedObject, IXmlSerializer xmlSerializer) { if (serializedObject.Name.LocalName != "List") return null; List result = new List(); foreach (XElement childElement in serializedObject.Elements()) { object childValue = xmlSerializer.Deserialize(childElement); result.Add((T)childValue); } return result; } private static XElement SerializeDictionary(Dictionary dictionaryToSerialize, IXmlSerializer xmlSerializer) { XElement result = new XElement("Dictionary"); foreach (KeyValuePair kvp in dictionaryToSerialize) { XElement serializedKey = xmlSerializer.Serialize(typeof(TKey), kvp.Key); XElement serializedValue = xmlSerializer.Serialize(typeof(TValue), kvp.Value); result.Add(new XElement("KeyPair", new XElement("Key", serializedKey), new XElement("Value", serializedValue))); } return result; } private static Dictionary DeserializeDictionary(XElement serializedObject, IXmlSerializer xmlSerializer) { if (serializedObject.Name.LocalName != "Dictionary") return null; Dictionary result = new Dictionary(); foreach (XElement childElement in serializedObject.Elements("KeyPair")) { XElement keyElement = childElement.Element("Key"); if (keyElement == null) return null; object keyValue = xmlSerializer.Deserialize(keyElement.Elements().Single()); XElement valueElement = childElement.Element("Value"); if (valueElement == null) return null; object valueValue = xmlSerializer.Deserialize(valueElement.Elements().Single()); result.Add((TKey)keyValue, (TValue)valueValue); } return result; } private static XElement SerializeKeyValuePair(KeyValuePair KeyValuePairToSerialize, IXmlSerializer xmlSerializer) { XElement result = new XElement("KeyValuePair"); XElement serializedKey = xmlSerializer.Serialize(typeof(TKey), KeyValuePairToSerialize.Key); XElement serializedValue = xmlSerializer.Serialize(typeof(TValue), KeyValuePairToSerialize.Value); result.Add(new XElement("Key", serializedKey)); result.Add(new XElement("Value", serializedValue)); return result; } private static KeyValuePair DeserializeKeyValuePair(XElement serializedObject, IXmlSerializer xmlSerializer) { if (serializedObject.Name.LocalName != "KeyValuePair") throw new InvalidOperationException(); XElement keyElement = serializedObject.Element("Key"); if (keyElement == null) throw new InvalidOperationException(); object keyValue = xmlSerializer.Deserialize(keyElement.Elements().Single()); XElement valueElement = serializedObject.Element("Value"); if (valueElement == null) throw new InvalidOperationException(); object valueValue = xmlSerializer.Deserialize(valueElement.Elements().Single()); KeyValuePair result = new KeyValuePair((TKey)keyValue, (TValue)valueValue); return result; } } } ================================================ FILE: Composite/Core/Serialization/SystemPrimitivValueXmlSerializer.cs ================================================ using System; using System.Xml.Linq; using Composite.Core.Types; namespace Composite.Core.Serialization { internal sealed class SystemPrimitivValueXmlSerializer : IValueXmlSerializer { public bool TrySerialize(Type objectToSerializeType, object objectToSerialize, IXmlSerializer xmlSerializer, out XElement serializedObject) { if (objectToSerializeType == null) throw new ArgumentNullException("objectToSerializeType"); if ((objectToSerializeType != typeof(int)) && (objectToSerializeType != typeof(long)) && (objectToSerializeType != typeof(bool)) && (objectToSerializeType != typeof(string)) && (objectToSerializeType != typeof(double)) && (objectToSerializeType != typeof(decimal)) && (objectToSerializeType != typeof(Guid)) && (objectToSerializeType != typeof(DateTime))) { serializedObject = null; return false; } serializedObject = new XElement("Value"); string serializedType = TypeManager.SerializeType(objectToSerializeType); serializedObject.Add(new XAttribute("type", serializedType)); if (objectToSerialize != null) { serializedObject.Add(new XAttribute("value", objectToSerialize)); } return true; } public bool TryDeserialize(XElement serializedObject, IXmlSerializer xmlSerializer, out object deserializedObject) { if (serializedObject == null) throw new ArgumentNullException("serializedObject"); deserializedObject = null; if (serializedObject.Name.LocalName != "Value") return false; XAttribute typeAttribute = serializedObject.Attribute("type"); if (typeAttribute == null) return false; XAttribute valueAttribute = serializedObject.Attribute("value"); if (valueAttribute == null) return true; Type type = TypeManager.GetType(typeAttribute.Value); if (type == typeof(int)) deserializedObject = (int)valueAttribute; else if (type == typeof(long)) deserializedObject = (long)valueAttribute; else if (type == typeof(bool)) deserializedObject = (bool)valueAttribute; else if (type == typeof(string)) deserializedObject = (string)valueAttribute; else if (type == typeof(double)) deserializedObject = (double)valueAttribute; else if (type == typeof(decimal)) deserializedObject = (decimal)valueAttribute; else if (type == typeof(Guid)) deserializedObject = (Guid)valueAttribute; else if (type == typeof(DateTime)) deserializedObject = (DateTime)valueAttribute; else { return false; } return true; } } } ================================================ FILE: Composite/Core/Serialization/SystemSerializableValueXmlSerializer.cs ================================================ using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Xml.Linq; using Composite.Core.Types; namespace Composite.Core.Serialization { internal sealed class SystemSerializableValueXmlSerializer : IValueXmlSerializer { public bool TrySerialize(Type objectToSerializeType, object objectToSerialize, IXmlSerializer xmlSerializer, out XElement serializedObject) { if (objectToSerializeType == null) throw new ArgumentNullException("objectToSerializeType"); serializedObject = null; int attributeCount = objectToSerializeType.GetCustomAttributes(typeof(SerializableAttribute), false).Length; if (attributeCount > 0) { serializedObject = new XElement("Serializable"); if (objectToSerialize != null) { using (MemoryStream ms = new MemoryStream()) { BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(ms, objectToSerialize); ms.Seek(0, SeekOrigin.Begin); using (BinaryReader br = new BinaryReader(ms)) { byte[] bytes = br.ReadBytes((int)ms.Length); string result = Convert.ToBase64String(bytes); serializedObject.Add(new XAttribute("value", result)); } } } else { serializedObject.Add(new XAttribute("type", TypeManager.SerializeType(objectToSerializeType))); } return true; } else { return false; } } public bool TryDeserialize(XElement serializedObject, IXmlSerializer xmlSerializer, out object deserializedObject) { deserializedObject = null; if (serializedObject == null) throw new ArgumentNullException("serializedObject"); if (serializedObject.Name.LocalName != "Serializable") return false; XAttribute typeAttribute = serializedObject.Attribute("type"); XAttribute valueAttribute = serializedObject.Attribute("value"); if ((valueAttribute == null) && (typeAttribute != null)) { Type type = TypeManager.GetType(typeAttribute.Value); int attributeCount = type.GetCustomAttributes(typeof(SerializableAttribute), false).Length; if (attributeCount > 0) { return true; } else { return false; } } else if ((valueAttribute != null) && (typeAttribute == null)) { byte[] bytes = Convert.FromBase64String(valueAttribute.Value); using (MemoryStream ms = new MemoryStream(bytes)) { BinaryFormatter binaryFormatter = new BinaryFormatter(); deserializedObject = binaryFormatter.Deserialize(ms); return true; } } else { return false; } } } } ================================================ FILE: Composite/Core/Serialization/SystemTypesValueXmlSerializer.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Core.Types; using System.Xml.Linq; namespace Composite.Core.Serialization { internal sealed class SystemTypesValueXmlSerializer : IValueXmlSerializer { public bool TrySerialize(Type objectToSerializeType, object objectToSerialize, IXmlSerializer xmlSerializer, out XElement serializedObject) { if (objectToSerializeType == null) throw new ArgumentNullException("objectToSerializeType"); if ((objectToSerializeType == typeof(Type)) || (objectToSerializeType == typeof(Type).GetType())) { serializedObject = new XElement("Value"); string serializedType = TypeManager.SerializeType(typeof(Type)); serializedObject.Add(new XAttribute("type", serializedType)); if (objectToSerialize != null) { serializedObject.Add(new XAttribute("value", TypeManager.SerializeType((Type)objectToSerialize))); } return true; } else { serializedObject = null; return false; } } public bool TryDeserialize(XElement serializedObject, IXmlSerializer xmlSerializer, out object deserializedObject) { if (serializedObject == null) throw new ArgumentNullException("serializedObject"); deserializedObject = null; if (serializedObject.Name.LocalName != "Value") return false; XAttribute typeAttribute = serializedObject.Attribute("type"); if (typeAttribute == null) return false; XAttribute valueAttribute = serializedObject.Attribute("value"); if (valueAttribute == null) return true; Type type = TypeManager.GetType(typeAttribute.Value); if (type == typeof(Type)) { deserializedObject = TypeManager.GetType(valueAttribute.Value); return true; } else { return false; } } } } ================================================ FILE: Composite/Core/Serialization/XmlSerializer.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace Composite.Core.Serialization { internal sealed class XmlSerializer : IXmlSerializer { IEnumerable _valueXmlSerializers; public XmlSerializer(IEnumerable valueXmlSerializers) { if (valueXmlSerializers == null) throw new ArgumentNullException("valueXmlSerializers"); _valueXmlSerializers = valueXmlSerializers.ToList(); } public static IXmlSerializer CreateStandardSerializer() { return new XmlSerializer(new IValueXmlSerializer[] { new SystemPrimitivValueXmlSerializer(), new SystemCollectionValueXmlSerializer() }); } public XElement Serialize(Type objectToSerializeType, object objectToSerialize) { if (objectToSerializeType == typeof(object)) { if (objectToSerialize != null) { objectToSerializeType = objectToSerialize.GetType(); } else { return new XElement("Null"); } } XElement serializedObject; foreach (IValueXmlSerializer valueXmlSerializer in _valueXmlSerializers) { if (valueXmlSerializer.TrySerialize(objectToSerializeType, objectToSerialize, this, out serializedObject)) { return serializedObject; } } throw new InvalidOperationException(string.Format("Could not serialize object of type '{0}'", objectToSerializeType)); } public object Deserialize(XElement serializedObject) { if (serializedObject.Name.LocalName == "Null") { return null; } object deserializedObject; foreach (IValueXmlSerializer valueXmlSerializer in _valueXmlSerializers) { if (valueXmlSerializer.TryDeserialize(serializedObject, this, out deserializedObject)) { return deserializedObject; } } string serializedObjectStr = serializedObject.ToString(); // If necessary, cutting the size, since otherwise it may lead to megabyte long exception text if(serializedObjectStr.Length > 10000) { serializedObjectStr = serializedObjectStr.Substring(0, 10000); } throw new InvalidOperationException(string.Format("Could not deserialize '{0}'", serializedObjectStr)); } } } ================================================ FILE: Composite/Core/ServiceLocator.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Configuration; using Composite.Core.Configuration; using Composite.Core.Threading; using Microsoft.Extensions.DependencyInjection; namespace Composite.Core { /// /// A mechanism for retrieving a service objects; that is, an object that provides custom support to other objects. /// /// To register a service, see /// /// /// The underlying plumbing is from . /// public static class ServiceLocator { private const string HttpContextKey = "HttpApplication.ServiceScope"; private const string ThreadDataKey = "HttpApplication.ServiceScope"; private static IServiceCollection _serviceCollection = new ServiceCollection(); private static IServiceProvider _serviceProvider; private static ConcurrentDictionary _hasTypeLookup = new ConcurrentDictionary(); private static Func _serviceProviderBuilder = s => { var configurationSection = (CompilationSection)WebConfigurationManager.GetSection("system.web/compilation"); return s.BuildServiceProvider(validateScopes: configurationSection?.Debug ?? false); }; /// /// Get service of type T /// /// The type of service object to get /// A service object of type T or null if there is no such service public static T GetService() { return ServiceProvider.GetService(); } /// /// Get service of type T /// /// The type of service object to get /// There is no service of type T /// A service object of type T or null if there is no such service public static T GetRequiredService() { return ServiceProvider.GetRequiredService(); } /// /// Get services of type T /// /// The type of service objects to get /// An enumerable of service objects of type T public static IEnumerable GetServices() { return ServiceProvider.GetServices(); } /// /// Get service of the specified type /// /// The type of service object to get /// A service object of type serviceType or null if there is no such service public static object GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } /// /// Get service of the specified type /// /// The type of service object to get /// There is no service of type serviceType /// A service object of type serviceType public static object GetRequiredService(Type serviceType) { return ServiceProvider.GetRequiredService(serviceType); } /// /// Get services of the specified type /// /// The type of service objects to get /// An enumerable of service objects of type serviceType public static IEnumerable GetServices(Type serviceType) { return ServiceProvider.GetServices(serviceType); } /// /// Replaces the default services container by registering a builder for your own IServiceProvider. /// You must register this during the service configuration phase, see and the ConfigureServices method. /// /// A callback function that returns your custom IServiceProvider public static void SetServiceProvider(Func serviceProviderBuilder) { Verify.ArgumentNotNull(serviceProviderBuilder, nameof(serviceProviderBuilder)); Verify.IsNull(_serviceProvider, "ServiceProvider already created and cannot be replaced at this time. Your custom ServiceProvider must be set during application startup - see ApplicationStartupAttribute and ConfigureServices()."); _serviceProviderBuilder = serviceProviderBuilder; } /// /// Gets an application service provider /// public static IServiceProvider ServiceProvider { get { Verify.IsNotNull(_serviceProvider,"IServiceProvider not build - call out of expected sequence."); return RequestScopedServiceProvider ?? _serviceProvider; } } internal static bool HasService(Type serviceType) { Verify.ArgumentNotNull(serviceType, nameof(serviceType)); if (ServiceLocatorNotInitialized) { return false; } Verify.IsNotNull(_serviceProvider, "IServiceProvider not build - call out of expected sequence."); bool hasType; if (!_hasTypeLookup.TryGetValue(serviceType, out hasType)) { if (_serviceCollection.Any(sd => sd.ServiceType.IsAssignableFrom(serviceType) || (serviceType.IsGenericType && sd.ServiceType.IsAssignableFrom(serviceType.GetGenericTypeDefinition())))) { hasType = true; } else { try { hasType = ServiceProvider.GetService(serviceType) != null; } catch (Exception) { hasType = false; } } _hasTypeLookup.TryAdd(serviceType, hasType); } return hasType; } /// /// A service collection to be populated at startup /// internal static IServiceCollection ServiceCollection { get { Verify.IsNull(_serviceProvider, "ServiceCollection accessed after ServiceProvider build-up - call out of sequence."); return _serviceCollection; } } internal static void BuildServiceProvider() { _serviceProvider = _serviceProviderBuilder(_serviceCollection); } /// /// Creates a service scope associated with the current http context /// internal static void CreateRequestServicesScope(HttpContext context) { Verify.ArgumentNotNull(context, nameof(context)); Verify.IsNotNull(_serviceProvider, "ServiceProvider not initialized yet"); Verify.IsNull(context.Items[HttpContextKey], "Multiple calls to CreateRequestServicesScope unexpected"); var serviceScopeFactory = (IServiceScopeFactory)_serviceProvider.GetService(typeof(IServiceScopeFactory)); var serviceScope = serviceScopeFactory.CreateScope(); context.Items[HttpContextKey] = serviceScope; } /// /// Disposes a service scope associated with the current http context /// internal static void DisposeRequestServicesScope(HttpContext context) { Verify.ArgumentNotNull(context, nameof(context)); var scope = (IServiceScope)context.Items[HttpContextKey]; if (scope != null) { scope.Dispose(); context.Items.Remove(HttpContextKey); } } internal static IDisposable EnsureThreadDataServiceScope() { if (RequestScopedServiceProvider != null || ServiceLocatorNotInitialized) return EmptyDisposable.Instance; var current = ThreadDataManager.GetCurrentNotNull(); var serviceScopeFactory = (IServiceScopeFactory)_serviceProvider.GetService(typeof(IServiceScopeFactory)); var serviceScope = serviceScopeFactory.CreateScope(); current.SetValue(ThreadDataKey, serviceScope); return new ThreadDataServiceScopeDisposable(current); } /// /// Return a IServiceScope - if a scope has been initialized on the request (HttpContext) a scoped provider is returned. /// private static IServiceProvider RequestScopedServiceProvider { get { var context = HttpContext.Current; if (context != null) { var scope = (IServiceScope)context.Items[HttpContextKey]; return scope?.ServiceProvider; } var threadData = ThreadDataManager.Current; if (threadData != null) { var scope = (IServiceScope) threadData[ThreadDataKey]; return scope?.ServiceProvider; } return null; } } private class ThreadDataServiceScopeDisposable : IDisposable { private readonly ThreadDataManagerData _threadData; public ThreadDataServiceScopeDisposable(ThreadDataManagerData threadData) { _threadData = threadData; } public void Dispose() { var scope = (IServiceScope)_threadData[ThreadDataKey]; scope?.Dispose(); _threadData.SetValue(ThreadDataKey, null); } } private static bool ServiceLocatorNotInitialized => !SystemSetupFacade.IsSystemFirstTimeInitialized || SystemSetupFacade.SetupIsRunning; } } ================================================ FILE: Composite/Core/SmtpMailer.cs ================================================ using System.Net.Mail; using System.Threading.Tasks; namespace Composite.Core { internal class SmtpMailer : IMailer { public void Send(MailMessage message) { using (var client = new SmtpClient()) { client.Send(message); } } public async Task SendAsync(MailMessage message) { using (var client = new SmtpClient()) { await client.SendMailAsync(message); } } } } ================================================ FILE: Composite/Core/Sql/SqlConnectionManager.cs ================================================ using System.Data.SqlClient; using Composite.Core.Threading; namespace Composite.Core.Sql { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class SqlConnectionManager { /// public static SqlConnection GetConnection(string connectionString) { string threadDataKey = "SqlDataContext" + connectionString + "_SqlConnection"; var threadData = ThreadDataManager.GetCurrentNotNull(); SqlConnection connection; if (threadData.HasValue(threadDataKey)) { connection = threadData[threadDataKey] as SqlConnection; } else { connection = new SqlConnection(connectionString); connection.Open(); threadData.SetValue(threadDataKey, connection); threadData.OnDispose += connection.Close; } return connection; } } } ================================================ FILE: Composite/Core/Threading/ThreadCultureScope.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Globalization; using System.Threading; namespace Composite.Core.Threading { /// /// Will set the threads Culture and reset it to the original value when this is disposed of. /// /// using( var cultureScope = new ThreadCultureScope( new CultureInfo("da-DK") ) ) /// { /// // Code here will run in da-DK scope. /// // Culture in effect before the using statement will be reset when exiting the using. /// } /// /// public sealed class ThreadCultureScope : IDisposable { private CultureInfo _originalCulture = null; private CultureInfo _originalUiCulture = null; private CultureInfo _desiredCulture = null; private CultureInfo _desiredUiCulture = null; private bool _disposed = false; /// /// Constructs a new culture scope, setting the threads CurrentCulture and resetting when this is disposed. The CurrentUiCulture is not affected. /// /// Desired culture to be in effect public ThreadCultureScope(CultureInfo culture) { _originalCulture = Thread.CurrentThread.CurrentCulture; _desiredCulture = culture; Thread.CurrentThread.CurrentCulture = culture; } /// /// Constructs a new culture scope, setting the threads CurrentCulture and CurrentUiCulture and resetting when this is disposed. /// /// Desired culture to be in effect /// Desired UI culture to be in effect public ThreadCultureScope(CultureInfo culture, CultureInfo uiCulture) : this(culture) { _originalUiCulture = Thread.CurrentThread.CurrentUICulture; _desiredUiCulture = uiCulture; Thread.CurrentThread.CurrentUICulture = uiCulture; } /// /// The culture this class was constructed to use /// public CultureInfo Culture { get { return _desiredCulture; } } /// /// The UI culture this class was constructed to use or null if none were specified. /// public CultureInfo UiCulture { get { return _desiredUiCulture; } } /// /// Return thread culture settings to their original values. /// public void Dispose() { if (!_disposed) { if (_originalCulture!=null) Thread.CurrentThread.CurrentCulture = _originalCulture; if (_originalUiCulture != null) Thread.CurrentThread.CurrentUICulture = _originalUiCulture; _disposed = true; } #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~ThreadCultureScope() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } ================================================ FILE: Composite/Core/Threading/ThreadDataManager.cs ================================================ using System; using System.Web; using Composite.C1Console.Security.Foundation.PluginFacades; namespace Composite.Core.Threading { /// /// This class coordinates data connections and ensures that multiple requests to SQL Server will reuse the same sql connection, allowing transactions to run without the use of MSDTC /// public static class ThreadDataManager { private static readonly string LogTitle = typeof(ThreadDataManager).Name; private const string c_HttpContextItemsId = "ThreadDataManager"; [ThreadStatic] private static ThreadDataManagerData _threadDataManagerData; /// /// Gets object for the current thread /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static ThreadDataManagerData Current { get { var currentContext = _threadDataManagerData; if(currentContext != null) { return currentContext; } var httpContext = HttpContext.Current; if (httpContext != null) { var data = httpContext.Items[c_HttpContextItemsId] as ThreadDataManagerData; if (data == null) { InitializeThroughHttpContext(); data = httpContext.Items[c_HttpContextItemsId] as ThreadDataManagerData; Verify.That(data != null, "Failed to initialize data through http context"); } return data; } return null; } internal set { _threadDataManagerData = value; } } /// /// Gets the current thread data, in the case of not being initialized it'll throw an exception /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static ThreadDataManagerData GetCurrentNotNull() { ThreadDataManagerData current = Current; Verify.That(current != null, @"ThreadDataManager hasn't been initialized in the current thread. You probably have forgotten to use Composite.Core.Threading.ThreadDataManager.EnsureInitialize() call on a custom created thread. Example of usage: using(Composite.Core.Threading.ThreadDataManager.EnsureInitialize()) { // Code that works with C1 data layer goes here ..... }"); current.CheckNotDisposed(); return current; } /// /// Creates a new instance of object /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static ThreadDataManagerData CreateNew() { var current = Current; current?.CheckNotDisposed(); return new ThreadDataManagerData(current); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static IDisposable Initialize() { return new ThreadDataManagerScope(new ThreadDataManagerData(), true); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static IDisposable Initialize(ThreadDataManagerData parentThreadData) { parentThreadData?.CheckNotDisposed(); return new ThreadDataManagerScope(new ThreadDataManagerData(parentThreadData), true); } /// /// Returns an scope, checks that ThreadDataManager is initialized for the current thread, if not - does the initialization. /// Should be called in all non ASP.NET threads, that are using C1 data API. /// /// /// /// using (Composite.Core.Threading.ThreadDataManager.EnsureInitialize()) /// using (var conn = new DataConnection(PublicationScope.Published, new CultureInfo("en-US"))) /// { /// var pages = conn.Get<Composite.Data.Types.IPage>(); /// // ... /// } /// /// /// An scope public static IDisposable EnsureInitialize() { if (Current != null) return EmptyDisposable.Instance; return Initialize(); } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static void InitializeThroughHttpContext() { var httpContext = HttpContext.Current; Verify.IsNotNull(httpContext, "This can only be called from a thread started with a current http context"); if (httpContext.Items[c_HttpContextItemsId] == null) { if (_threadDataManagerData != null) { Log.LogCritical(LogTitle, "ThreadData has already been initialized in the current thread. It's been reset to NULL value, resource leaks are possible."); _threadDataManagerData = null; } var threadData = new ThreadDataManagerData(); httpContext.Items[c_HttpContextItemsId] = threadData; } } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Use the overload taking no parameters instead")] public static void InitializeThroughHttpContext(bool forceUserValidation) { InitializeThroughHttpContext(); if (forceUserValidation) { string username = LoginSessionStorePluginFacade.StoredUsername; } } /// /// To be used only in Global.asax /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static void FinalizeThroughHttpContext() { if(_threadDataManagerData != null) { _threadDataManagerData = null; Log.LogError(LogTitle, "Thread data hasn't been disposed after request execution. Resource leaks are possible."); } var httpContext = HttpContext.Current; // Checking if ThreadData was initialized though HttpContext var currentData = httpContext.Items[c_HttpContextItemsId] as IDisposable; if (currentData != null) { httpContext.Items[c_HttpContextItemsId] = null; try { currentData.Dispose(); } catch(Exception e) { Log.LogError(LogTitle, e); } } } private sealed class ThreadDataManagerScope : IDisposable { private bool _disposed; private readonly bool _disposeData; private readonly ThreadDataManagerData _threadData; private readonly ThreadDataManagerData _threadDataValueToBeRestored; public ThreadDataManagerScope(ThreadDataManagerData newCurrentData, bool disposeData) { Verify.ArgumentNotNull(newCurrentData, "newCurrentData"); newCurrentData.CheckNotDisposed(); _threadData = newCurrentData; // NOTE: We shouldn't take value from 'Current' property, since it may return it from HttpContext _threadDataValueToBeRestored = _threadDataManagerData; _threadDataManagerData = newCurrentData; _disposeData = disposeData; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Dispose(bool disposing) { if (disposing) { try { if (_disposed) throw new ObjectDisposedException(typeof(ThreadDataManagerData).FullName); _disposed = true; if (_disposeData) { try { _threadData.Dispose(); } catch (Exception e) { Log.LogError(LogTitle, e); } Verify.IsTrue(Current == _threadData, "ThreadDataManager.Current points to a different thread data object!!!"); } } finally { _threadDataManagerData = _threadDataValueToBeRestored; } } else { if (!_disposed && _disposeData) { try { _threadData.Dispose(); } catch (Exception) { // silent... } } } } #if LeakCheck private string stack = Environment.StackTrace; #endif ~ThreadDataManagerScope() { #if LeakCheck Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); #endif Dispose(false); } } } } ================================================ FILE: Composite/Core/Threading/ThreadDataManagerData.cs ================================================ using System.Threading; using Composite.Core.Collections.Generic; using System; namespace Composite.Core.Threading { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ThreadDataManagerData: IDisposable { /// public ThreadDataManagerData Parent { get; set; } private Hashtable Data { get; set; } private bool _disposed = false; /// public ThreadDataManagerData() : this(null) { } internal delegate void OnThreadDataDisposedDelegate(); /// public event ThreadStart OnDispose; /// public ThreadDataManagerData(ThreadDataManagerData parentThreadData) { this.Parent = parentThreadData; this.Data = new Hashtable(); } /// /// This method will find the first one that contains the key and return the value /// /// /// /// public bool TryGetParentValue(object key, out object value) { CheckNotDisposed(); ThreadDataManagerData current = this; while (current != null && !current.Data.ContainsKey(key)) { current = current.Parent; } if (current == null) { value = null; return false; } value = current.Data[key]; return true; } /// public void SetValue(object key, object value) { CheckNotDisposed(); this.Data[key] = value; } /// public object GetValue(object key) { CheckNotDisposed(); return Data[key]; } /// public bool HasValue(object key) { CheckNotDisposed(); return this.Data.ContainsKey(key); } /// public object this[object key] => GetValue(key); /// public void CheckNotDisposed() { if(_disposed) throw new ObjectDisposedException("TheadDataManagerData"); } #region IDisposable Members /// public void Dispose() { OnDispose?.Invoke(); _disposed = true; #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~ThreadDataManagerData() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif #endregion } } ================================================ FILE: Composite/Core/Threading/ThreadManager.cs ================================================ using System.Threading; namespace Composite.Core.Threading { internal static class ThreadManager { public static ParameterizedThreadStart CreateThreadStart(ThreadStart threadStart) { return delegate(object parameter) { StartThreadData startThreadData = (StartThreadData)parameter; using (ThreadDataManager.Initialize(startThreadData.Data)) { threadStart(); } }; } public static ParameterizedThreadStart CreateParameterizedThreadStart(ParameterizedThreadStart parameterizedThreadStart) { return delegate(object parameter) { StartThreadData startThreadData = (StartThreadData)parameter; using (ThreadDataManager.Initialize(startThreadData.Data)) { parameterizedThreadStart(startThreadData.Parameter); } }; } public static void StartThread(Thread thread) { ThreadDataManagerData data = ThreadDataManager.Current; StartThreadData startThreadData = new StartThreadData { Data = data, }; thread.Start(startThreadData); } public static void StartThread(Thread thread, object parameter) { ThreadDataManagerData data = ThreadDataManager.Current; StartThreadData startThreadData = new StartThreadData { Data = data, Parameter = parameter }; thread.Start(startThreadData); } private sealed class StartThreadData { public ThreadDataManagerData Data { get; set; } public object Parameter { get; set; } } } } ================================================ FILE: Composite/Core/Threading/TwoPhaseFileLock.cs ================================================ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Threading; namespace Composite.Core.Threading { /// /// Algorithm /// /// Initial: None of the files exists. Enter is allowed. Leave is an exception. /// - Write phase one file /// - Delete phase two file /// /// Enter: Wait until phase two file exists and phase one does not exist. Other AD/Thread has left. /// Exception: Only wait for max ms /// - Write phase one file (Preventing other Enter's) /// - Delete phase two file /// /// Leave: If phase one file exists (if not => I have timed out) /// - Write phase two file (Allowes other Enter's) /// - Delete phase one file /// /// internal class TwoPhaseFileLock { private string PhaseOneFilePath { get; set; } private string PhaseTwoFilePath { get; set; } public TwoPhaseFileLock(string id, string workDirectory) { Timeout = 45000; PhaseOneFilePath = Path.Combine(workDirectory, id + ".entered"); PhaseTwoFilePath = Path.Combine(workDirectory, id + ".left"); } /// /// Time out time in ms. Default is 10000 /// public int Timeout { get; set; } /// /// Acquires the lock. /// /// /// Returns true if the lock was obtained successfully. /// Returns false if the lock was acquried due to timeout. /// [SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public bool Acquire() { bool gotTheLock = false; if (IsFirstTime()) { gotTheLock = true; } else { gotTheLock = true; int startTime = Environment.TickCount; while (File.Exists(PhaseOneFilePath) && !File.Exists(PhaseTwoFilePath)) { Thread.Sleep(50); int timeElapsed = Environment.TickCount - startTime; if (timeElapsed >= Timeout) { gotTheLock = false; break; } } } Log.LogInformation("TwoPhaseFileLock", string.Format("AppDomain {0} acquiring the lock ({1})", AppDomain.CurrentDomain.Id, gotTheLock)); File.WriteAllText(PhaseOneFilePath, ""); SafeDelete(PhaseTwoFilePath); return gotTheLock; } /// /// Releases the lock. /// [SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void Release() { Log.LogInformation("TwoPhaseFileLock", string.Format("AppDomain {0} releasing the lock", AppDomain.CurrentDomain.Id)); if (IsFirstTime()) { throw new InvalidOperationException("Releasing the lock is not allowed before it has been acquired!"); } if (File.Exists(PhaseOneFilePath)) { File.WriteAllText(PhaseTwoFilePath, ""); SafeDelete(PhaseOneFilePath); } } [SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] private bool IsFirstTime() { return !File.Exists(PhaseOneFilePath) && !File.Exists(PhaseTwoFilePath); } [SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] private static void SafeDelete(string filePath) { try { if (File.Exists(filePath)) { File.Delete(filePath); } } catch (Exception) { // Ignore } } } } ================================================ FILE: Composite/Core/Types/AssemblyExtensionMethods.cs ================================================ using System; using System.Collections.Generic; using System.Reflection; namespace Composite.Core.Types { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class AssemblyExtensionMethods { /// public static IEnumerable GetTypes(this IEnumerable assemblies) { foreach (Assembly assembly in assemblies) { IEnumerable types = null; try { types = assembly.GetTypes(); } catch { // Ignore } if (types == null) continue; foreach (Type type in types) { yield return type; } } } } } ================================================ FILE: Composite/Core/Types/AssemblyFacade.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using Composite.Core.IO; using Composite.Core.Configuration; namespace Composite.Core.Types { /// /// /// [EditorBrowsable(EditorBrowsableState.Never)] public static class AssemblyFacade { private static readonly string LogTitle = typeof (AssemblyFacade).Name; private static readonly Type RuntimeModuleType = typeof(Module).Assembly.GetType("System.Reflection.RuntimeModule"); private static bool _compositeGeneratedErrorLogged; /// public static IEnumerable GetLoadedAssembliesFromBin() { string binDirectory = PathUtil.Resolve(GlobalSettingsFacade.BinDirectory).ToLowerInvariant().Replace('\\', '/'); List assemblies = new List(); foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (assembly.IsDynamic) continue; try { string codebase = assembly.CodeBase.ToLowerInvariant(); if (codebase.Contains(binDirectory)) { assemblies.Add(assembly); } } catch { // Ignore exceptions } } return assemblies; } /// /// Gets list of file pathes of .NET dll files from "~/Bin" folder, excluding Composite.Generated.dll. /// /// /// public static IEnumerable GetAssembliesFromBin() { return GetAssembliesFromBin(false); } /// /// Gets list of file pathes of .NET dll files from "~/Bin" folder. /// /// if set to true Composite.Generated.dll will also be included. /// /// public static IEnumerable GetAssembliesFromBin(bool includeCompositeGenerated) { var assembliesFromBin = new List(); foreach (string binFilePath in C1Directory.GetFiles(PathUtil.Resolve(GlobalSettingsFacade.BinDirectory), "*.dll")) { string assemblyFileName = Path.GetFileName(binFilePath); if (!includeCompositeGenerated) { if (assemblyFileName.IndexOf(CodeGenerationManager.CompositeGeneratedFileName, StringComparison.OrdinalIgnoreCase) >= 0) continue; } if (IsDotNetAssembly(binFilePath)) { assembliesFromBin.Add(binFilePath); } } return assembliesFromBin; } /// /// Gets the Composite.Generated assembly from the "~/Bin" folder /// /// public static Assembly GetGeneratedAssemblyFromBin() { foreach (string binFilePath in C1Directory.GetFiles(PathUtil.Resolve(GlobalSettingsFacade.BinDirectory), "*.dll")) { string assemblyFileName = Path.GetFileName(binFilePath); if (assemblyFileName.IndexOf(CodeGenerationManager.CompositeGeneratedFileName, StringComparison.OrdinalIgnoreCase) < 0) { continue; } try { return Assembly.LoadFrom(binFilePath); } catch(Exception ex) { if (!_compositeGeneratedErrorLogged) { Log.LogInformation(LogTitle, "Failed to load ~/Bin/Composite.Generated.dll "); Log.LogWarning(LogTitle, ex); _compositeGeneratedErrorLogged = true; } } } return null; } private static bool IsDotNetAssembly(string dllFilePath) { try { AssemblyName.GetAssemblyName(dllFilePath); } catch (BadImageFormatException) { return false; } catch (Exception) { } return true; } /// public static Assembly GetAppCodeAssembly() { return AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(IsAppCodeDll); } /// public static bool IsInMemoryAssembly(Assembly asm) { // Checking // (asm.ManifestModule as System.Reflection.RuntimeModule).GetFullyQualifiedName() == "" if (!RuntimeModuleType.IsInstanceOfType(asm.ManifestModule)) return false; var method = RuntimeModuleType.GetMethod("GetFullyQualifiedName", BindingFlags.NonPublic | BindingFlags.Instance); return (method.Invoke(asm.ManifestModule, new object[0]) as string) == ""; } /// public static bool IsAppCodeDll(Assembly assembly) { string fullName = assembly.FullName; return fullName != null && (fullName.StartsWith("App_Code.") || fullName.StartsWith("App_Code,")); } /// /// Gets assemblies from bin and app code assembly /// /// public static IEnumerable GetAllAssemblies() { List assemblies = GetLoadedAssembliesFromBin().ToList(); Assembly appCodeAssembly = GetAppCodeAssembly(); if (appCodeAssembly != null) { assemblies.Add(appCodeAssembly); } return assemblies; } internal static bool AssemblyPotentiallyUsesType(Assembly assembly, Type type) { Verify.ArgumentNotNull(assembly, nameof(assembly)); Verify.ArgumentNotNull(type, nameof(type)); var typeAssembly = type.Assembly; string typeAssemblyName = typeAssembly.GetName().Name; return assembly == typeAssembly || assembly.GetReferencedAssemblies().Any(r => r.Name == typeAssemblyName); } } } ================================================ FILE: Composite/Core/Types/AssemblyLocationExtensions.cs ================================================ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.IO; using System.Linq; namespace Composite.Core.Types { /// [EditorBrowsable(EditorBrowsableState.Never)] internal static class AssemblyLocationExtensions { /// /// Adds assembly locations to a string collection of the collection does not already has them. /// Note: Case insensitive /// /// /// /// public static void AddRangeIfNotContained(this StringCollection stringCollection, IEnumerable assemblyLocations) { foreach (string assemblyLocation in assemblyLocations) { AddIfNotContained(stringCollection, assemblyLocation); } } /// /// Adds a assembly location to a string collection of the collection does not already has it. /// Note: Case insensitive /// /// /// /// public static void AddIfNotContained(this StringCollection stringCollection, string assemblyLocation) { string assemblyFileName = Path.GetFileName(assemblyLocation); bool isContained = stringCollection. OfType(). Where(f => f.IndexOf(assemblyFileName, StringComparison.InvariantCultureIgnoreCase) >= 0). Any(); if (!isContained) { stringCollection.Add(assemblyLocation); } } } } ================================================ FILE: Composite/Core/Types/BuildinPlugins/BuildinTypeManagerTypeHandler/BuildinTypeManagerTypeHandler.cs ================================================ using System; using Composite.Plugins.Types.TypeManagerTypeHandler.DynamicBuildManagerTypeManagerTypeHandler; using Composite.Plugins.Types.TypeManagerTypeHandler.SystemTypeManagerTypeHandler; using Composite.Core.Types.Plugins.TypeManagerTypeHandler; namespace Composite.Core.Types.BuildinPlugins.BuildinTypeManagerTypeHandler { internal sealed class BuildinTypeManagerTypeHandler : ITypeManagerTypeHandler { public Type GetType(string fullName) { Type type; ITypeManagerTypeHandler handler; handler = new DynamicBuildManagerTypeManagerTypeHandler(); type = handler.GetType(fullName); if (type != null) return type; handler = new SystemTypeManagerTypeHandler(); type = handler.GetType(fullName); if (type != null) return type; return null; } public string SerializeType(Type type) { string serializedType; ITypeManagerTypeHandler handler; handler = new DynamicBuildManagerTypeManagerTypeHandler(); serializedType = handler.SerializeType(type); if (serializedType != null) return serializedType; handler = new SystemTypeManagerTypeHandler(); serializedType = handler.SerializeType(type); if (serializedType != null) return serializedType; return null; } public bool HasTypeWithName(string typeFullname) { ITypeManagerTypeHandler handler; handler = new DynamicBuildManagerTypeManagerTypeHandler(); if (handler.HasTypeWithName(typeFullname)) return true; handler = new SystemTypeManagerTypeHandler(); if (handler.HasTypeWithName(typeFullname)) return true; return false; } } } ================================================ FILE: Composite/Core/Types/CSharpCodeProviderFactory.cs ================================================ using System.CodeDom.Compiler; using Microsoft.CSharp; namespace Composite.Core.Types { internal class CSharpCodeProviderFactory { public static CSharpCodeProvider CreateCompiler() { return (CSharpCodeProvider)CodeDomProvider.CreateProvider("c#"); } } } ================================================ FILE: Composite/Core/Types/CodeCompatibilityChecker.cs ================================================ using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Text; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; namespace Composite.Core.Types { /// [EditorBrowsable(EditorBrowsableState.Never)] internal static class CodeCompatibilityChecker { /// /// This method will try to compile the given type to see if any changes done to the type /// will conflict with code in App_Code /// /// /// public static CompatibilityCheckResult CheckCompatibilityWithAppCodeFolder(DataTypeDescriptor dataTypeDescriptorToTest) { return CheckAgainstAppCode(dataTypeDescriptorToTest, true); } /// /// This method will check if any code in en App_Code folder depends on the given data interface. /// /// /// public static CompatibilityCheckResult CheckIfAppCodeDependsOnInterface(DataTypeDescriptor dataTypeDescriptorToTest) { return CheckAgainstAppCode(dataTypeDescriptorToTest, false); } /// /// This method checks to see if any change in the given data type descriptor will make code /// in App_Code fail and hence the site will fail. /// /// /// /// If true, the data type descriptor will be used instead of the original. /// If false, it will be excluded. /// /// [SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass", Justification = "File api is used for creating temporary files")] [SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass", Justification = "File api is used for creating temporary files")] [SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass", Justification = "File api is used for creating temporary files")] private static CompatibilityCheckResult CheckAgainstAppCode(DataTypeDescriptor dataTypeDescriptorToTest, bool includeDataTypeDescriptor) { var filesToCompile = GetAppCodeFiles().ToList(); if (filesToCompile.Count == 0) { return new CompatibilityCheckResult(); } var csCompiler = CSharpCodeProviderFactory.CreateCompiler(); var referencedAssemblies = new List(); var codeTypeDeclarations = new Dictionary>(); foreach (var dataTypeDescriptor in DataMetaDataFacade.GeneratedTypeDataTypeDescriptors) { if (!includeDataTypeDescriptor && dataTypeDescriptor.DataTypeId == dataTypeDescriptorToTest.DataTypeId) { continue; } var dataTypeDescriptorToUse = dataTypeDescriptor; if (includeDataTypeDescriptor && dataTypeDescriptor.DataTypeId == dataTypeDescriptorToTest.DataTypeId) { dataTypeDescriptorToUse = dataTypeDescriptorToTest; } referencedAssemblies.AddRange(InterfaceCodeGenerator.GetReferencedAssemblies(dataTypeDescriptorToUse)); var codeTypeDeclaration = InterfaceCodeGenerator.CreateCodeTypeDeclaration(dataTypeDescriptorToUse); if (!codeTypeDeclarations.TryGetValue(dataTypeDescriptorToUse.Namespace, out var declarations)) { declarations = new List(); codeTypeDeclarations.Add(dataTypeDescriptorToUse.Namespace, declarations); } declarations.Add(codeTypeDeclaration); var tempFilePath = GetTempFileName(dataTypeDescriptorToUse); filesToCompile.Add(tempFilePath); using (var file = File.Create(tempFilePath)) { using (var sw = new StreamWriter(file)) { var codeNamespace = new CodeNamespace(dataTypeDescriptorToUse.Namespace); codeNamespace.Types.Add(codeTypeDeclaration); csCompiler.GenerateCodeFromNamespace(codeNamespace, sw, new CodeGeneratorOptions()); } var sb = new StringBuilder(); using (var sw = new StringWriter(sb)) { csCompiler.GenerateCodeFromMember(codeTypeDeclaration, sw, new CodeGeneratorOptions()); } } } filesToCompile.Sort(); var compilerParameters = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = true }; compilerParameters.ReferencedAssemblies.AddRangeIfNotContained(referencedAssemblies.Select(f => f.Location).ToArray()); compilerParameters.ReferencedAssemblies.AddRangeIfNotContained(CodeGenerationManager.CompiledAssemblies.Select(f => f.Location).ToArray()); compilerParameters.AddLoadedAssemblies(false); compilerParameters.AddAssemblyLocationsFromBin(); compilerParameters.AddCommonAssemblies(); compilerParameters.RemoveGeneratedAssemblies(); var codeCompileUnit = new CodeCompileUnit(); foreach (var kvp in codeTypeDeclarations) { var codeNamespace = new CodeNamespace(kvp.Key); codeNamespace.Types.AddRange(kvp.Value.ToArray()); codeCompileUnit.Namespaces.Add(codeNamespace); } var compiler = CSharpCodeProviderFactory.CreateCompiler(); var compileResult = compiler.CompileAssemblyFromFile(compilerParameters, filesToCompile.ToArray()); if (!compileResult.Errors.HasErrors) { return new CompatibilityCheckResult(); } // Checking for a missing assembly error, if it is present, that means that App_Code check isn't applicable due to circular reference foreach (CompilerError error in compileResult.Errors) { if (error.ErrorNumber == "CS0012" && error.ErrorText.Contains("Composite.Generated")) { return new CompatibilityCheckResult(); } } return new CompatibilityCheckResult(compileResult); } private static string GetTempFileName(DataTypeDescriptor typeDescriptor) { var folderPath = PathUtil.Resolve(GlobalSettingsFacade.GeneratedAssembliesDirectory); var filePath = Path.Combine(folderPath, typeDescriptor.GetFullInterfaceName() + ".cs"); if (filePath.Length > 255) { filePath = Path.Combine(folderPath, typeDescriptor.DataTypeId + ".cs"); } return filePath; } [SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] private static IEnumerable GetAppCodeFiles() { var appCodeFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, GlobalSettingsFacade.AppCodeDirectory); if (!Directory.Exists(appCodeFolderPath)) { return new string[0]; } return Directory.GetFiles(appCodeFolderPath, "*.cs", SearchOption.AllDirectories); } } } ================================================ FILE: Composite/Core/Types/CodeGenerationBuilder.cs ================================================ using System; using System.CodeDom; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Composite.Core.Types { /// /// This class is used when compiling new types at run time in C1. /// It is used in two way. The first usage is for creating types that is located in temp assemblies. /// Normaly when temp assemblies has ben made a restart of C1 is done. And this leads into the second /// usage which is when the Composite.Generated.dll is compiled. This is done through the implementation /// and adding of the interface and . /// public class CodeGenerationBuilder { private readonly Dictionary _namespaces = new Dictionary(); private readonly List _assemblyLocations = new List(); internal string DebugLabel { get; private set; } /// /// Creates a new instance. /// /// This label will be used for logging when compiling the types. public CodeGenerationBuilder(string debugLabel = null) { DebugLabel = debugLabel ?? ""; } /// /// Adds a referenced assembly to be used in the compilation. /// /// The referenced assembly. public void AddReference(Assembly assembly) { AddReference(assembly.Location); } /// /// Adds a referenced assembly to be used in the compilation. /// /// The location of the referenced assembly. public void AddReference(string assemblyLocation) { if (!_assemblyLocations.Contains(assemblyLocation, StringComparer.InvariantCultureIgnoreCase)) { _assemblyLocations.Add(assemblyLocation); } } /// /// Adds a code namespace containing types to compile. /// /// Code namespace to add. public void AddNamespace(CodeNamespace codeNamespace) { CodeNamespace existingCodeNamespace; if (!_namespaces.TryGetValue(codeNamespace.Name, out existingCodeNamespace)) { _namespaces.Add(codeNamespace.Name, codeNamespace); } else { existingCodeNamespace.Types.AddRange(codeNamespace.Types); } } /// /// Adds a new type declaration to compile. If the type name already exists in /// the given namespace. The type is skipped! /// /// Namespace to add the type to. /// Type declaration to compile. public void AddType(string namespaceName, CodeTypeDeclaration codeTypeDeclaration) { AddTypes(namespaceName, new[] { codeTypeDeclaration }); } /// /// Adds new type declarations to compile. If a type name already exists in /// the given namespace. The type is skipped! /// /// /// public void AddTypes(string namespaceName, IEnumerable codeTypeDeclarations) { CodeNamespace codeNamespace; if (!_namespaces.TryGetValue(namespaceName, out codeNamespace)) { codeNamespace = new CodeNamespace(namespaceName); _namespaces.Add(namespaceName, codeNamespace); codeNamespace.Types.AddRange(codeTypeDeclarations.ToArray()); } else { foreach (CodeTypeDeclaration newCodeTypeDeclaration in codeTypeDeclarations) { bool alreadyExists = false; foreach (CodeTypeDeclaration exitingTypeDeclaration in codeNamespace.Types) { if (exitingTypeDeclaration.Name == newCodeTypeDeclaration.Name) { alreadyExists = true; break; } } if (!alreadyExists) { codeNamespace.Types.Add(newCodeTypeDeclaration); } } } } /// /// Added assembly locations /// public IEnumerable AssemblyLocations { get { return _assemblyLocations; } } /// /// Added namespaces /// public IEnumerable Namespaces { get { return _namespaces.Values; } } } } ================================================ FILE: Composite/Core/Types/CodeGenerationCommon.cs ================================================ using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.IO; namespace Composite.Core.Types { /// [EditorBrowsable(EditorBrowsableState.Never)] internal static class CodeGenerationCommon { /// /// Adds all assemblies from bin, except Composite.Generated.dll /// /// public static void AddAssemblyLocationsFromBin(this CompilerParameters compilerParameters) { AssemblyFacade.GetAssembliesFromBin().ForEach(compilerParameters.ReferencedAssemblies.AddIfNotContained); } /// /// Add assemblies that are loaded in the app domain. /// /// The compiler parameters. /// if set to true reference to App_Code will be included to results. public static void AddLoadedAssemblies(this CompilerParameters compilerParameters, bool includeAppCode) { var foundAssemblyLocations = new Dictionary(); IEnumerable assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(AssemblyHasLocation); if(!includeAppCode) { assemblies = assemblies.Where(asm => !asm.GetName().Name.StartsWith("App_Code")); } IEnumerable locations = assemblies.Select(a => a.Location); foreach (string location in locations) { string locationKey = Path.GetFileName(location).ToLowerInvariant(); if (!foundAssemblyLocations.ContainsKey(locationKey)) { foundAssemblyLocations.Add(locationKey, location); } else { string currentUsedLocation = foundAssemblyLocations[locationKey]; DateTime currentlyUsedLastWrite = C1File.GetLastWriteTime(currentUsedLocation); DateTime locationCandidateLastWrite = C1File.GetLastWriteTime(location); if (locationCandidateLastWrite > currentlyUsedLastWrite) { foundAssemblyLocations.Remove(locationKey); foundAssemblyLocations.Add(locationKey, location); } } } compilerParameters.ReferencedAssemblies.AddRangeIfNotContained(foundAssemblyLocations.Values); } /// /// Add common used assemblies /// /// public static void AddCommonAssemblies(this CompilerParameters compilerParameters) { var commonAssemblies = new List { typeof(System.Linq.Expressions.Expression).Assembly.Location, typeof(System.Xml.Linq.XElement).Assembly.Location, typeof(System.Xml.Serialization.IXmlSerializable).Assembly.Location, typeof(System.Data.Linq.Mapping.TableAttribute).Assembly.Location, typeof(System.ComponentModel.IContainer).Assembly.Location, typeof(System.Data.SqlClient.SqlCommand).Assembly.Location }; compilerParameters.ReferencedAssemblies.AddRangeIfNotContained(commonAssemblies); } /// /// Removes generated assemblies including Composite.Generated.dll /// /// public static void RemoveGeneratedAssemblies(this CompilerParameters compilerParameters) { List assembliesToRemove = compilerParameters.ReferencedAssemblies. OfType(). Where(f => f.IndexOf(CodeGenerationManager.CompositeGeneratedFileName, StringComparison.InvariantCultureIgnoreCase) >= 0 || f.StartsWith(PathUtil.Resolve(GlobalSettingsFacade.GeneratedAssembliesDirectory), StringComparison.InvariantCultureIgnoreCase)). Select(f => f). ToList(); assembliesToRemove.ForEach(compilerParameters.ReferencedAssemblies.Remove); } [DebuggerStepThrough] private static bool AssemblyHasLocation(Assembly assembly) { if (assembly.GetType().FullName == "System.Reflection.Emit.InternalAssemblyBuilder") { return false; } if (assembly.GlobalAssemblyCache) { return true; } try { return assembly.ManifestModule.Name != "" && assembly.ManifestModule.FullyQualifiedName != "" && assembly.ManifestModule.ScopeName != "RefEmit_InMemoryManifestModule" && !string.IsNullOrEmpty(assembly.Location); } catch (Exception) { return false; } } } } ================================================ FILE: Composite/Core/Types/CodeGenerationHelper.cs ================================================ using System; namespace Composite.Core.Types { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class CodeGenerationHelper { /// public static string GetTypeAlias(Type type) { return GetTypeAlias(type.FullName); } /// public static string GetTypeAlias(string typeFullName) { return typeFullName.Replace(".", "_"); } } } ================================================ FILE: Composite/Core/Types/CodeGenerationManager.cs ================================================ //#warning REMOVE THIS LINE!!! //#define OUTPUT_SOURCE_CODE_ON_ERROR using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using Composite.C1Console.Events; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.PackageSystem; using Composite.Data.Foundation.CodeGeneration; using Composite.Data.GeneratedTypes; namespace Composite.Core.Types { /// /// Handles all dynamic type compilations and the generation of Composite.Generated.dll /// public static class CodeGenerationManager { internal static readonly string LogTitle = typeof(CodeGenerationManager).Name; private const int NumberOfCompileRetries = 10; private static readonly object _lock = new object(); private static bool _compositeGeneratedCompiled = true; private static List _dynamicallyAddedCodeProviders = new List(); private static readonly List _compiledAssemblies = new List(); private static readonly Dictionary _compiledTypesByFullName = new Dictionary(); /// /// If set to true, /Bin/Composite.Generated.dll won't be overwritten on shutdown /// public static bool SuppressGeneration { get; set; } static CodeGenerationManager() { string assemblyTempPath = null; try { assemblyTempPath = PathUtil.Resolve(GlobalSettingsFacade.GeneratedAssembliesDirectory); } catch { // NOTE: We don't want this static constructor fail if GlobalSettingsFacade failed to load. } if (assemblyTempPath != null) { if (!C1Directory.Exists(assemblyTempPath)) { C1Directory.CreateDirectory(assemblyTempPath); } } GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); GlobalEventSystemFacade.SubscribeToShutDownEvent(args => ClearOldTempFiles()); } /// /// Validates that the current Composite.Generated.dll is not compiled after the given /// time. If it is compiled after the given time. Any attempts to recompile Composite.Generated.dll /// will be ignored. This is used to stop app domains from shutting each other down by recompiles. /// /// internal static void ValidateCompositeGenerate(DateTime time) { if (SuppressGeneration) { return; } var filePath = Path.Combine(PathUtil.BaseDirectory, "Bin", "Composite.Generated.dll"); if (!C1File.Exists(filePath)) { return; } var lastWrite = C1File.GetLastWriteTime(filePath); if (lastWrite <= time) { return; } _compositeGeneratedCompiled = true; Log.LogVerbose(LogTitle, $"Assembly in this application domain is newer than this application domain ({AppDomain.CurrentDomain.Id})"); } /// /// This method will recompile Composite.Generated.dll and drop it into bin. /// /// public static void GenerateCompositeGeneratedAssembly(bool forceGeneration = false) { if (SuppressGeneration) { return; } if (forceGeneration || !_compositeGeneratedCompiled) { lock (_lock) { if (forceGeneration || !_compositeGeneratedCompiled) { Log.LogVerbose(LogTitle, $"Compiling new assembly in this application domain ({AppDomain.CurrentDomain.Id})"); var t1 = Environment.TickCount; var builder = new CodeGenerationBuilder("Composite.Generated.dll"); PopulateBuilder(builder); var t2 = Environment.TickCount; Compile(builder); var t3 = Environment.TickCount; var numberOfTypes = builder.Namespaces.SelectMany(f => f.Types.OfType()).Count(); Log.LogVerbose(LogTitle, "Number of types build: " + numberOfTypes + "\nBuilding code dom: " + (t2 - t1) + "ms" + "\nCompiling code dom: " + (t3 - t2) + "ms" + "\nTotal compilation: " + (t3 - t1) + "ms"); _compositeGeneratedCompiled = true; return; } } } Log.LogVerbose(LogTitle, "New assembly already compiled by this application domain ({0})", AppDomain.CurrentDomain.Id); } /// /// This method will compile the type defined in /// and return the result types. These types exists in a temp assembly, that will be /// deleted when the app domain is terminated. /// /// /// /// public static IEnumerable CompileRuntimeTempTypes(CodeGenerationBuilder codeGenerationBuilder, bool verbose = true) { var t1 = Environment.TickCount; _compositeGeneratedCompiled = false; // When compiling a new type, Composite.Generated.dll should always be recompiled var compilerParameters = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = false, OutputAssembly = Path.Combine(TempAssemblyFolderPath, Guid.NewGuid() + ".dll") }; compilerParameters.ReferencedAssemblies.AddRangeIfNotContained(codeGenerationBuilder.AssemblyLocations.ToArray()); compilerParameters.ReferencedAssemblies.AddRangeIfNotContained(_compiledAssemblies.Select(f => f.Location).ToArray()); compilerParameters.AddAssemblyLocationsFromBin(); var codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.Namespaces.AddRange(codeGenerationBuilder.Namespaces.ToArray()); var compiler = CSharpCodeProviderFactory.CreateCompiler(); var compileResult = compiler.CompileAssemblyFromDom(compilerParameters, codeCompileUnit); if (!compileResult.Errors.HasErrors) { var resultAssembly = compileResult.CompiledAssembly; AddCompiledAssembly(resultAssembly); var resultTypes = resultAssembly.GetTypes(); var t2 = Environment.TickCount; Log.LogVerbose(LogTitle, $"Compile '{codeGenerationBuilder.DebugLabel}' in {t2 - t1}ms"); Log.LogVerbose(LogTitle, $"Types from : {compilerParameters.OutputAssembly}"); foreach (var resultType in resultTypes) { _compiledTypesByFullName[resultType.FullName] = resultType; } return resultTypes; } OutputSourceCodeOnError(compiler, codeCompileUnit); var failedAssemblyLoads = LoadAssembliesToMemory(compilerParameters.ReferencedAssemblies); var sb = new StringBuilder(); failedAssemblyLoads.ForEach(asm => sb.AppendFormat("Failed to load dll: '{0}' : {1}", asm.First, asm.Second).AppendLine()); sb.AppendLine("Failed building: " + codeGenerationBuilder.DebugLabel); foreach (CompilerError compilerError in compileResult.Errors) { if (compilerError.IsWarning) { continue; } var entry = "Compile error: " + compilerError.ErrorNumber + "(" + compilerError.Line + ")" + ": " + compilerError.ErrorText.Replace("{", "{{").Replace("}", "}}"); if (verbose) { Log.LogError(LogTitle, entry); } sb.AppendLine(entry); } throw new InvalidOperationException(sb.ToString()); } private static IEnumerable> LoadAssembliesToMemory(StringCollection assemblyLocations) { var failedAssemblyLoads = new List>(); foreach (var assemblyLocation in assemblyLocations) { if (PackageAssemblyHandler.TryGetAlreadyLoadedAssembly(assemblyLocation) != null) { continue; } try { var assembly = Assembly.LoadFrom(assemblyLocation); assembly.GetTypes(); // Accessing GetTypes() to iterate classes } catch (Exception ex) { var exceptionToLog = ex; var loadException = ex as ReflectionTypeLoadException; if (loadException?.LoaderExceptions != null && loadException.LoaderExceptions.Any()) { exceptionToLog = loadException.LoaderExceptions.First(); } failedAssemblyLoads.Add(new Pair(assemblyLocation, exceptionToLog)); } } return failedAssemblyLoads; } /// /// This method returns true if the given type is /// compiled at runetime. Otherwise false. /// /// /// public static bool IsCompiledAtRuntime(Type type) { return type.Assembly.Location.StartsWith(PathUtil.Resolve(GlobalSettingsFacade.GeneratedAssembliesDirectory), StringComparison.InvariantCultureIgnoreCase); } /// /// This method returns true if the types given by needs a recompile because /// they either is null or the type given by has changed and there for /// exists in a compiled at runtime assembly. /// /// A type that all the types given by depends on. /// All types in this enumerable should either be null or depend on the typoe given by /// Returns true if the types given by needs a recompile. public static bool IsRecompileNeeded(Type dependableType, IEnumerable dependingTypes) { foreach (var dependingType in dependingTypes) { if (dependingType == null) { return true; } if (IsCompiledAtRuntime(dependableType) && !IsCompiledAtRuntime(dependingType)) { return true; } } return false; } /// /// Use this method to add a implementation /// that will be used when (and only) generating the final Composite.Generated.dll. /// /// public static void AddAssemblyCodeProvider(ICodeProvider codeProvider) { _dynamicallyAddedCodeProviders.Add(codeProvider); } /// /// Gets the compiled types. /// /// public static Type GetCompiledType(string fullName) { return _compiledTypesByFullName.TryGetValue(fullName, out var type) ? type : null; } private static void Compile(CodeGenerationBuilder builder) { var compilerParameters = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = false, OutputAssembly = CompositeGeneratedAssemblyPath, TempFiles = new TempFileCollection(TempAssemblyFolderPath) }; compilerParameters.ReferencedAssemblies.AddRangeIfNotContained(builder.AssemblyLocations.ToArray()); compilerParameters.AddAssemblyLocationsFromBin(); var codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.Namespaces.AddRange(builder.Namespaces.ToArray()); for (var i = 0; i < NumberOfCompileRetries; i++) { var compiler = CSharpCodeProviderFactory.CreateCompiler(); CompilerResults compileResult = compiler.CompileAssemblyFromDom(compilerParameters, codeCompileUnit); if (!compileResult.Errors.HasErrors) { return; } if (i == NumberOfCompileRetries - 1) { OutputSourceCodeOnError(compiler, codeCompileUnit); var sb = new StringBuilder(); foreach (CompilerError compilerError in compileResult.Errors) { if (compilerError.IsWarning) { continue; } var entry = "Compile error: " + compilerError.ErrorNumber + "(" + compilerError.Line + ")" + ": " + compilerError.ErrorText.Replace("{", "{{").Replace("}", "}}"); Log.LogError(LogTitle, entry); sb.AppendLine(entry); } throw new InvalidOperationException(sb.ToString()); } } } /// /// Returns all currently temp compiled assemblies. /// internal static IEnumerable CompiledAssemblies => _compiledAssemblies; /// /// internal static string TempAssemblyFolderPath => PathUtil.Resolve(GlobalSettingsFacade.GeneratedAssembliesDirectory); /// /// internal static string BinFolder => RuntimeInformation.IsUnittest ? PathUtil.BaseDirectory : Path.Combine(PathUtil.BaseDirectory, "Bin"); /// /// internal static string CompositeGeneratedFileName => "Composite.Generated.dll"; /// /// internal static string CompositeGeneratedAssemblyPath => Path.Combine(BinFolder, "Composite.Generated.dll"); private static void PopulateBuilder(CodeGenerationBuilder builder) { foreach (var provider in CodeProviders) { provider.GetCodeToCompile(builder); } } private static IEnumerable CodeProviders { get { yield return new InterfaceCodeProvider(); yield return new EmptyDataClassCodeProvider(); yield return new DataWrapperClassCodeProvider(); foreach (var codeProvider in _dynamicallyAddedCodeProviders) { yield return codeProvider; } } } private static void AddCompiledAssembly(Assembly newAssembly) { var newType = newAssembly.GetTypes().First(); var assembliesToRemove = new List(); foreach (var assembly in _compiledAssemblies) { var type = assembly.GetTypes().SingleOrDefault(f => f.FullName == newType.FullName); if (type != null) { assembliesToRemove.Add(assembly); } } foreach (var assemblyToRemove in assembliesToRemove) { _compiledAssemblies.Remove(assemblyToRemove); } _compiledAssemblies.Add(newAssembly); } private static void Flush() { _dynamicallyAddedCodeProviders = new List(); } private static void ClearOldTempFiles() { var yesterday = DateTime.Now.AddDays(-1); var oldFiles = C1Directory.GetFiles(TempAssemblyFolderPath, "*.*").Where(filePath => C1File.GetCreationTime(filePath) < yesterday).ToArray(); foreach (var file in oldFiles) { try { C1File.Delete(file); } catch { // Silent } } } [Conditional("OUTPUT_SOURCE_CODE_ON_ERROR")] private static void OutputSourceCodeOnError(CodeDomProvider compiler, CodeCompileUnit codeCompileUnit) { using (var file = File.Create(Path.Combine(PathUtil.BaseDirectory, "output.cs"))) { using (var sw = new StreamWriter(file)) { compiler.GenerateCodeFromCompileUnit(codeCompileUnit, sw, new CodeGeneratorOptions()); } } } } } ================================================ FILE: Composite/Core/Types/CompatibilityCheckResult.cs ================================================ using System; using System.CodeDom.Compiler; using Composite.Core.Extensions; namespace Composite.Core.Types { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class CompatibilityCheckResult { internal CompatibilityCheckResult() { Successful = true; } internal CompatibilityCheckResult(CompilerResults compilerResults) { Successful = !compilerResults.Errors.HasErrors; CompilerResults = compilerResults; } /// public bool Successful { get; private set; } /// public CompilerResults CompilerResults { get; private set; } /// public string ErrorMessage { get { var compilationErrors = CompilerResults.Errors; if (compilationErrors.HasErrors) { for(int i=0; i where T : class, IData { public DataReferenceLabelPair(DataReference reference, string label) { this.Label = label; this.DataReference = reference; } public DataReferenceLabelPair(T data, string label) { this.Label = label; this.DataReference = new DataReference(data); } public string Label { get; private set; } public DataReference DataReference { get; private set; } } } ================================================ FILE: Composite/Core/Types/DynamicBuildManagerTypeCache.cs ================================================ using System; using System.Collections.Generic; using Composite.Core.Collections.Generic; namespace Composite.Core.Types { internal sealed class CompiledTypeCache { private readonly Hashtable _cache = new Hashtable(); public void RemoveOldVersion(Type key) { string cacheKey = GetCacheKey(key); CacheItem cacheItem; if (_cache.TryGetValue(cacheKey, out cacheItem)) { _cache.Remove(cacheKey); } } public void Add(Type key, TValue value) { string cacheKey = GetCacheKey(key); CacheItem cacheItem; if (_cache.TryGetValue(cacheKey, out cacheItem)) { if (cacheItem.Type == key) throw new ArgumentException("Adding an item with duplicate key"); _cache[cacheKey] = new CacheItem { Type = key, Value = value }; } else { _cache.Add(cacheKey, new CacheItem { Type = key, Value = value }); } } public bool ContainsKey(Type key) { CacheItem cacheItem; if (_cache.TryGetValue(GetCacheKey(key), out cacheItem) == false) return false; return true; } private static string GetCacheKey(Type key) { return TypeManager.SerializeType(key) + key.Assembly.FullName; } public bool TryGetValue(Type key, out TValue value) { CacheItem cacheItem; if (!_cache.TryGetValue(GetCacheKey(key), out cacheItem)) { value = default(TValue); return false; } value = cacheItem.Value; return true; } public IEnumerable Keys { get { foreach (CacheItem item in _cache.GetValues()) { yield return item.Type; } } } public TValue this[Type key] { get { CacheItem cacheItem; if (_cache.TryGetValue(GetCacheKey(key), out cacheItem) == false) { throw new ArgumentException("Key not found"); } return cacheItem.Value; } set { string cacheKey = GetCacheKey(key); CacheItem cacheItem; if (!_cache.TryGetValue(cacheKey, out cacheItem)) throw new ArgumentException("Key not found"); _cache[cacheKey] = new CacheItem { Type = key, Value = value }; } } private sealed class CacheItem { public Type Type { get; set; } public TValue Value { get; set; } } } } ================================================ FILE: Composite/Core/Types/ExtendedNullable.cs ================================================ namespace Composite.Core.Types { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ExtendedNullable { private T _value = default(T); private bool _hasValue = false; /// public static implicit operator ExtendedNullable(T value) { ExtendedNullable extendedNullable = new ExtendedNullable(); extendedNullable.Value = value; return extendedNullable; } /// public bool HasValue { get { return _hasValue; } } /// public T Value { get { return _value; } set { SetValue(value); } } private void SetValue(T value) { _value = value; _hasValue = true; } } } ================================================ FILE: Composite/Core/Types/Foundation/AssemblyFilenameCollection.cs ================================================ using System; using System.Collections.Generic; using System.IO; namespace Composite.Core.Types.Foundation { internal sealed class AssemblyFilenameCollection { private readonly Dictionary _assemblyFilenames = new Dictionary(); public bool ContainsAssemblyFilename(string assemblyFilename) { if (string.IsNullOrEmpty(assemblyFilename)) throw new ArgumentNullException("assemblyFilename"); string assemblyName = GetAssemblyName(assemblyFilename); return _assemblyFilenames.ContainsKey(assemblyName); } public bool ContainsAssemblyName(string assemblyName) { if (string.IsNullOrEmpty(assemblyName)) throw new ArgumentNullException("assemblyName"); return _assemblyFilenames.ContainsKey(assemblyName); } public void Add(string assemblyFilename) { if (string.IsNullOrEmpty(assemblyFilename)) throw new ArgumentNullException("assemblyFilename"); string assemblyName = GetAssemblyName(assemblyFilename); _assemblyFilenames[assemblyName] = assemblyFilename; } public string GetFilenameByAssemblyName(string assemblyName) { if (string.IsNullOrEmpty(assemblyName)) throw new ArgumentNullException("assemblyName"); string assemblyFilename; if (!_assemblyFilenames.TryGetValue(assemblyName, out assemblyFilename)) { throw new ArgumentException($"Does not contain the assembly name '{assemblyName}'"); } return assemblyFilename; } public static string GetAssemblyName(string assemblyFilename) { string filename = Path.GetFileName(assemblyFilename); string extension = Path.GetExtension(filename); filename = filename.Remove(filename.Length - extension.Length); return filename; } } } ================================================ FILE: Composite/Core/Types/Foundation/CompileUnitBaseTypeProber.cs ================================================ using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Composite.Core.Types.Foundation { // This code do NOT take generic base types into account. See http://msdn2.microsoft.com/en-us/library/system.codedom.codetypereference.basetype.aspx internal static class CompileUnitBaseTypeProber { /// /// Probes all class declarations, locates types with base types and return a map from found base types to all type declarations having this base type. /// /// The compile unit to probe /// The collection of assemblies all base types are expected to stem from. /// A dictionary of all found base types that map to a list of type declarations using this base type. public static Dictionary>> MapTypeDeclarationInheritance(this CodeCompileUnit compileUnit, IEnumerable allowedBaseTypeAssemblies) { Func typeResolver = f => allowedBaseTypeAssemblies.Select(g => g.GetType(f, false)).FirstOrDefault(g => g != null); return MapTypeDeclarationInheritance(compileUnit, typeResolver); } /// /// Probes all class declarations, locates types with base types and return a map from found base types to all type declarations having this base type. /// /// The compile unit to probe /// The parameters used for compilation. Used to locate relevant assemblies /// A dictionary of all found base types that map to a list of type declarations using this base type. public static Dictionary>> MapTypeDeclarationInheritance(this CodeCompileUnit compileUnit, CompilerParameters parms) { Func typeResolver = f => GetTypeFromReferencedAssemblies(parms, f); return MapTypeDeclarationInheritance(compileUnit, typeResolver); } /// /// Probes all class declarations, locates types with base types and return a map from found base types to all type declarations having this base type. /// /// The compile unit to probe /// A function that can map a type full name (without assembly information) to a Type /// A dictionary of all found base types that map to a list of type declarations using this base type. public static Dictionary>> MapTypeDeclarationInheritance(this CodeCompileUnit compileUnit, Func typeResolver) { var baseTypeToTypeDeclaration = new Dictionary>>(); foreach (CodeNamespace codeNamespace in compileUnit.Namespaces) { foreach (CodeTypeDeclaration codeTypeDeclaration in codeNamespace.Types) { foreach (CodeTypeReference baseTypeReference in codeTypeDeclaration.BaseTypes) { string baseTypeName = baseTypeReference.BaseType; Type baseType = typeResolver(baseTypeName); if (baseType == null) { // Base class be null since some generated classes are based on someother generated classes continue; } if (baseTypeToTypeDeclaration.ContainsKey(baseType) == false) baseTypeToTypeDeclaration.Add(baseType, new List>()); baseTypeToTypeDeclaration[baseType].Add(new KeyValuePair(codeNamespace, codeTypeDeclaration)); } } } return baseTypeToTypeDeclaration; } private static Type GetTypeFromReferencedAssemblies(CompilerParameters parms, string baseTypeName) { Assembly[] knownAssemblies = AppDomain.CurrentDomain.GetAssemblies(); Type baseType = Type.GetType(baseTypeName, false); if (baseType == null) { foreach (string referencedAssemblyFileName in parms.ReferencedAssemblies) { Assembly assembly = knownAssemblies .FirstOrDefault(f => f.CodeBase.EndsWith(referencedAssemblyFileName, StringComparison.OrdinalIgnoreCase)); if (assembly != null) { baseType = assembly.GetType(baseTypeName, false); if (baseType != null) break; } else { throw new InvalidOperationException(string.Format("Did not find a candidate for referenced assembly '{0}'", referencedAssemblyFileName)); } } } return baseType; } } } ================================================ FILE: Composite/Core/Types/Foundation/PluginFacades/ITypeManagerTypeHandlerPluginFacade.cs ================================================ using System; namespace Composite.Core.Types.Foundation.PluginFacades { internal interface ITypeManagerTypeHandlerPluginFacade { Type GetType(string providerName, string fullName); string SerializedType(string providerName, Type type); bool HasTypeWithName(string providerName, string typeFullname); void OnFlush(); } } ================================================ FILE: Composite/Core/Types/Foundation/PluginFacades/TypeManagerTypeHandlerPluginFacade.cs ================================================ using System; using Composite.C1Console.Events; namespace Composite.Core.Types.Foundation.PluginFacades { internal static class TypeManagerTypeHandlerPluginFacade { private static ITypeManagerTypeHandlerPluginFacade _implementation = new TypeManagerTypeHandlerPluginFacadeImpl(); internal static ITypeManagerTypeHandlerPluginFacade Implementation { get { return _implementation; } set { _implementation = value; } } static TypeManagerTypeHandlerPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static Type GetType(string providerName, string fullName) { return _implementation.GetType(providerName, fullName); } public static string SerializedType(string providerName, Type type) { return _implementation.SerializedType(providerName, type); } public static bool HasTypeWithName(string providerName, string typeFullname) { return _implementation.HasTypeWithName(providerName, typeFullname); } private static void OnFlushEvent(FlushEventArgs args) { _implementation.OnFlush(); } } } ================================================ FILE: Composite/Core/Types/Foundation/PluginFacades/TypeManagerTypeHandlerPluginFacadeImpl.cs ================================================ using System; using System.Collections.Concurrent; using Composite.Core.Types.Plugins.TypeManagerTypeHandler; using Composite.Core.Types.Plugins.TypeManagerTypeHandler.Runtime; namespace Composite.Core.Types.Foundation.PluginFacades { internal sealed class TypeManagerTypeHandlerPluginFacadeImpl : ITypeManagerTypeHandlerPluginFacade { private static readonly object _syncRoot = new object(); private static Resources _resources; public Type GetType(string providerName, string fullName) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); Verify.ArgumentNotNullOrEmpty(fullName, "fullName"); ITypeManagerTypeHandler typeManagerTypeHandler = GetTypeManagerTypeHandler(providerName); return typeManagerTypeHandler.GetType(fullName); } public string SerializedType(string providerName, Type type) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); Verify.ArgumentNotNull(type, "type"); ITypeManagerTypeHandler typeManagerTypeHandler = GetTypeManagerTypeHandler(providerName); return typeManagerTypeHandler.SerializeType(type); } public bool HasTypeWithName(string providerName, string typeFullname) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); Verify.ArgumentNotNullOrEmpty(typeFullname, "typeFullname"); ITypeManagerTypeHandler typeManagerTypeHandler = GetTypeManagerTypeHandler(providerName); return typeManagerTypeHandler.HasTypeWithName(typeFullname); } public void OnFlush() { _resources = null; } private static ITypeManagerTypeHandler GetTypeManagerTypeHandler(string providerName) { Resources resources = GetResources(); return resources.TypeHandlerCache.GetOrAdd(providerName, provider => { ITypeManagerTypeHandler typeHandler = resources.Factory.Create(provider); return typeHandler; }); } private static Resources GetResources() { Resources result = _resources; if(result == null) { lock(_syncRoot) { result = _resources; if(result == null) { result = BuildResources(); _resources = result; } } } return result; } private static Resources BuildResources() { return new Resources { Factory = new TypeManagerTypeHandlerFactory(), TypeHandlerCache = new ConcurrentDictionary() }; } private sealed class Resources { public TypeManagerTypeHandlerFactory Factory { get; set; } public ConcurrentDictionary TypeHandlerCache { get; set; } } } } ================================================ FILE: Composite/Core/Types/GenericComparer.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Reflection; namespace Composite.Core.Types { internal class GenericComparer : IComparer, IComparer { public static GenericComparer Build(Type type, string propertyName) { return new GenericComparer(type, propertyName, true); } public static GenericComparer Build(Type type, string propertyName, bool ascDesc) { return new GenericComparer(type, propertyName, ascDesc); } private MemberInfo _field; private bool _ascDesc; public GenericComparer(Type type, string propertyName, bool ascDesc) { this._field = type.GetPropertiesRecursively(f => f.Name == propertyName)[0]; this._ascDesc = ascDesc; } object GetValue(object obj) { if (_field is FieldInfo) return ((FieldInfo)_field).GetValue(obj); else return ((PropertyInfo)_field).GetValue(obj, new object[0]); } int IComparer.Compare(object obj1, object obj2) { IComparable comparer = (IComparable)GetValue(obj1); return comparer.CompareTo(GetValue(obj2)) * (_ascDesc ? 1 : -1); } public int Compare(T obj1, T obj2) { IComparable comparer = (IComparable)GetValue(obj1); object value = GetValue(obj2); if ((comparer == null) && (value == null)) return 0; if (comparer == null) return (_ascDesc ? 1 : -1); if (value == null) return (_ascDesc ? -1 : 1); return comparer.CompareTo(value) * (_ascDesc ? 1 : -1); } } } ================================================ FILE: Composite/Core/Types/ICodeProvider.cs ================================================ using System.ComponentModel; namespace Composite.Core.Types { /// /// Implementing this interface and regitre an instance with the method /// you can get code compiled when C1 shuts down or restarts. /// Use the to add code to compile. /// Compiling code when C1 is running see the method . /// /// [EditorBrowsable(EditorBrowsableState.Never)] public interface ICodeProvider { /// /// Add code namespaces and types and references you want to have compiled /// to the builder. /// /// void GetCodeToCompile(CodeGenerationBuilder builder); } } ================================================ FILE: Composite/Core/Types/ITypeManager.cs ================================================ using System; namespace Composite.Core.Types { internal interface ITypeManager { Type GetType(string fullName); Type TryGetType(string fullName); string SerializeType(Type type); string TrySerializeType(Type type); bool HasTypeWithName(string typeFullname); void OnFlush(); } } ================================================ FILE: Composite/Core/Types/KeyValuePair.cs ================================================ namespace Composite.Core.Types { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class KeyValuePair { private string _key = ""; private string _value = ""; /// public KeyValuePair() { } /// public KeyValuePair(string key, string value) { _key = key; _value = value; } /// public string Key { get { return _key; } set { _key = value; } } /// public string Value { get { return _value; } set { _value = value; } } } } ================================================ FILE: Composite/Core/Types/NameTypePair.cs ================================================ using System; namespace Composite.Core.Types { internal sealed class NameTypePair { private string _name; private Type _type; public NameTypePair(string name, Type type) { _name = name; _type = type; } public string Name { get { return _name; } } public Type Type { get { return _type; } } } } ================================================ FILE: Composite/Core/Types/Pair.cs ================================================ using System; namespace Composite.Core.Types { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class Pair { /// public Pair(TFirst firstValue, TSecond secondValue) { this.First = firstValue; this.Second = secondValue; } /// public TFirst First { get; set; } /// public TSecond Second { get; set; } /// public override bool Equals(object obj) { return Equals(obj as Pair); } /// public bool Equals(Pair pair) { if (pair == null) return false; return object.Equals(this.First, pair.First) && object.Equals(this.Second, pair.Second); } /// public override int GetHashCode() { return this.First.GetHashCode() ^ this.Second.GetHashCode(); } /// public override string ToString() { return string.Format("First: {0}, Second: {1}", this.First, this.Second); } } } ================================================ FILE: Composite/Core/Types/Plugins/TypeManagerTypeHandler/ITypeManagerTypeHandler.cs ================================================ using System; using Composite.Core.Types.Plugins.TypeManagerTypeHandler.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Types.Plugins.TypeManagerTypeHandler { [CustomFactory(typeof(TypeManagerTypeHandlerCustomFactory))] [ConfigurationNameMapper(typeof(TypeManagerTypeHandlerDefaultNameRetriever))] internal interface ITypeManagerTypeHandler { Type GetType(string serializedType); string SerializeType(Type type); /// /// /// /// Full name: namespace+name. X.Y.Z where X.Y is the namespace and Z is the type. /// bool HasTypeWithName(string typeFullname); } } ================================================ FILE: Composite/Core/Types/Plugins/TypeManagerTypeHandler/NonConfigurableTypeManagerTypeHandler.cs ================================================ using System; using Microsoft.Practices.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Types.Plugins.TypeManagerTypeHandler { [Assembler(typeof(NonConfigurableTypeManagerTypeHandlerAssembler))] internal sealed class NonConfigurableTypeManagerTypeHandler : TypeManagerTypeHandlerData { } internal sealed class NonConfigurableTypeManagerTypeHandlerAssembler : IAssembler { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public ITypeManagerTypeHandler Assemble(IBuilderContext context, TypeManagerTypeHandlerData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (ITypeManagerTypeHandler)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/Core/Types/Plugins/TypeManagerTypeHandler/Runtime/TypeManagerTypeHandlerCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Types.Plugins.TypeManagerTypeHandler.Runtime { internal sealed class TypeManagerTypeHandlerCustomFactory : AssemblerBasedCustomFactory { protected override TypeManagerTypeHandlerData GetConfiguration(string name, IConfigurationSource configurationSource) { TypeManagerTypeHandlerSettings settings = configurationSource.GetSection(TypeManagerTypeHandlerSettings.SectionName) as TypeManagerTypeHandlerSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", TypeManagerTypeHandlerSettings.SectionName)); } return settings.TypeManagerTypeHandlerPlugins.Get(name); } } } ================================================ FILE: Composite/Core/Types/Plugins/TypeManagerTypeHandler/Runtime/TypeManagerTypeHandlerDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Types.Plugins.TypeManagerTypeHandler.Runtime { internal sealed class TypeManagerTypeHandlerDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/Core/Types/Plugins/TypeManagerTypeHandler/Runtime/TypeManagerTypeHandlerFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.Types.Plugins.TypeManagerTypeHandler.Runtime { internal sealed class TypeManagerTypeHandlerFactory : NameTypeFactoryBase { public TypeManagerTypeHandlerFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/Core/Types/Plugins/TypeManagerTypeHandler/Runtime/TypeManagerTypeHandlerSettings.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Types.Plugins.TypeManagerTypeHandler.Runtime { internal sealed class TypeManagerTypeHandlerSettings : SerializableConfigurationSection { public const string SectionName = "Composite.Core.Types.Plugins.TypeManagerTypeHandler"; private const string _typeManagerTypeHandlerPluginsProperty = "TypeManagerTypeHandlerPlugins"; [ConfigurationProperty(_typeManagerTypeHandlerPluginsProperty, IsRequired = true)] public NameTypeConfigurationElementCollection TypeManagerTypeHandlerPlugins { get { return (NameTypeConfigurationElementCollection)base[_typeManagerTypeHandlerPluginsProperty]; } } } } ================================================ FILE: Composite/Core/Types/Plugins/TypeManagerTypeHandler/TypeManagerTypeHandlerData.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Types.Plugins.TypeManagerTypeHandler { internal class TypeManagerTypeHandlerData : NameTypeConfigurationElement { private const string _priorityPropertyName = "priority"; [ConfigurationProperty(_priorityPropertyName, IsRequired = true, IsKey = true)] public int Priority { get { return (int)base[_priorityPropertyName]; } set { base[_priorityPropertyName] = value; } } } } ================================================ FILE: Composite/Core/Types/PrimitiveTypes.cs ================================================ using System; using System.Linq; using System.Collections.Generic; namespace Composite.Core.Types { internal static class PrimitiveTypes { private static readonly Type[] _primitiveTypes = { typeof(DateTime), typeof(Boolean), typeof(Byte), typeof(Char), typeof(Double), typeof(Guid), typeof(Int16), typeof(Int32), typeof(Int64), typeof(SByte), typeof(Single), typeof(UInt16), typeof(UInt32), typeof(UInt64), typeof(string), typeof(Decimal) }; public static IEnumerable Types { get { return _primitiveTypes; } } public static bool IsPrimitiveType(this Type type) { return _primitiveTypes.Contains(type); } public static bool IsPrimitiveOrNullableType(this Type type) { if ((type.IsGenericType) && (type.GetGenericTypeDefinition() == typeof(Nullable<>))) { return IsPrimitiveType(type.GetGenericArguments()[0]); } else { return IsPrimitiveType(type); } } } } ================================================ FILE: Composite/Core/Types/StaticReflection.cs ================================================ using System; using System.Linq.Expressions; using System.Reflection; using Composite.Core.Extensions; namespace Composite.Core.Types { internal static class StaticReflection { public static MethodInfo GetGenericMethodInfo(Expression> expression) { Verify.ArgumentNotNull(expression, "expression"); return GetMethodInfo(expression.Body).GetGenericMethodDefinition(); } public static MethodInfo GetGenericMethodInfo(Expression> expression) { Verify.ArgumentNotNull(expression, "expression"); return GetMethodInfo(expression.Body).GetGenericMethodDefinition(); } public static MethodInfo GetMethodInfo(Expression> expression) { return GetMethodInfo(expression.Body as MethodCallExpression); } public static MethodInfo GetMethodInfo(Expression> expression) { return GetMethodInfo(expression.Body as MethodCallExpression); } public static MethodInfo GetMethodInfo(Expression expression) { Verify.ArgumentNotNull(expression, "expression"); if (expression is UnaryExpression && (expression as UnaryExpression).NodeType == ExpressionType.Convert) { expression = (expression as UnaryExpression).Operand; } Verify.ArgumentCondition(expression is MethodCallExpression, "expressionBody", "Expression body should be of type '{0}'".FormatWith(typeof(MethodCallExpression).Name)); return (expression as MethodCallExpression).Method; } } } ================================================ FILE: Composite/Core/Types/TypeExtensionMethods.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Composite.Data; using Composite.C1Console.Events; using Composite.Core.Collections.Generic; namespace Composite.Core.Types { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class TypeExtensionMethods { private static Hashtable> _propertyAttributeCache = new Hashtable>(); /// static TypeExtensionMethods() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } /// public static string GetVersionNeutralName(this Type type) { if (!type.IsGenericType) { return string.Format("{0},{1}", type.FullName, type.Assembly.FullName.Split(',')[0]); } Type[] genericArguments = type.GetGenericArguments(); StringBuilder sb = new StringBuilder(); bool firstTime = true; foreach (Type genericType in genericArguments) { string serializedType = GetVersionNeutralName(genericType); if (firstTime == false) { sb.Append(","); } else { firstTime = false; } sb.Append(string.Format("[{0}]", serializedType)); } string fullName = type.FullName.Remove(type.FullName.IndexOf('[')); return string.Format("{0}[{1}],{2}", fullName, sb, type.Assembly.FullName.Split(',')[0]); } /// public static List GetPropertiesRecursively(this Type type) { return GetPropertiesRecursively(type, null); } /// public static List GetPropertiesRecursively(this Type type, Func predicate) { predicate = predicate ?? (p => true); var properties = new List(); properties.AddRange(type.GetProperties().Where(predicate)); Type[] interfaceTypes = type.GetInterfaces(); foreach (Type interfaceType in interfaceTypes) { properties.AddRange(interfaceType.GetProperties().Where(predicate)); } // A compatibility fix, returning the same "PageId" property twice usually leads to an error if (typeof (IPageData).IsAssignableFrom(type)) { properties.RemoveAll(p => p.Name == nameof (IPageData.PageId) && p.DeclaringType == typeof (IPageData)); } return properties; } /// public static List GetInterfacesRecursively(this Type type) { var interfaces = new List(); GetInterfacesRecursively(type, null, interfaces); return interfaces; } /// public static List GetInterfacesRecursively(this Type type, Func predicate) { var interfaces = new List(); GetInterfacesRecursively(type, predicate, interfaces); return interfaces; } private static void GetInterfacesRecursively(this Type type, Func predicate, List interfaces) { foreach (Type interfaceType in type.GetInterfaces()) { if (predicate == null || predicate(interfaceType)) { if (!interfaces.Contains(interfaceType)) { interfaces.Add(interfaceType); } } GetInterfacesRecursively(interfaceType, predicate, interfaces); } } /// public static string SerializeValue(this Type sourceType, object valueToSerialize) { if (valueToSerialize == null) return null; if (sourceType == typeof(string)) return (string)valueToSerialize; if (sourceType == typeof(Guid)) return valueToSerialize.ToString(); if (sourceType == typeof(int)) return valueToSerialize.ToString(); throw new NotImplementedException(string.Format("Serialization of the the type {0} is not supported", sourceType.FullName)); } /// public static object DeserializeValue(this Type targetType, string serializedValue) { if (serializedValue == null) return null; if (targetType == typeof(string)) return serializedValue; if (targetType == typeof(Guid)) return new Guid(serializedValue); if (targetType == typeof(int)) return int.Parse(serializedValue); ; throw new NotImplementedException(string.Format("Deserializing values of the the type {0} is not supported", targetType.FullName)); } private static readonly Hashtable> _interfaceAttributeCache = new Hashtable>(); private static readonly object _lock = new object(); /// public static IEnumerable GetCustomInterfaceAttributes(this Type type) where T : Attribute { List attributeList; if (!_interfaceAttributeCache.TryGetValue(type, out attributeList)) { lock (_lock) { if (!_interfaceAttributeCache.TryGetValue(type, out attributeList)) { attributeList = new List(); GetCustomAttributesRecursively(type, attributeList, null, new List(), true); _interfaceAttributeCache.Add(type, attributeList); } } } return attributeList.OfType(); } private static readonly ConcurrentDictionary> _typeAttributeCache = new ConcurrentDictionary>(); /// public static IEnumerable GetCustomAttributesRecursively(this Type type) where T : Attribute { return GetCustomAttributesRecursively(type).OfType(); } /// public static IEnumerable GetCustomAttributesRecursively(this Type type, Type attributeType) { return GetCustomAttributesRecursively(type).Where(attr => attr.GetType() == attributeType); } private static IEnumerable GetCustomAttributesRecursively(this Type type) { return _typeAttributeCache.GetOrAdd(type, t => { var attributeList = new List(); GetCustomAttributesRecursively(t, attributeList, null, new List(), false); return attributeList; }); } /// public static IEnumerable GetCustomAttributesRecursively(this PropertyInfo propertyInfo) where T : Attribute { List attributeList; if (!_propertyAttributeCache.TryGetValue(propertyInfo, out attributeList)) { lock (_lock) { if (!_propertyAttributeCache.TryGetValue(propertyInfo, out attributeList)) { attributeList = new List(); GetCustomAttributesRecursively(propertyInfo.DeclaringType, attributeList, propertyInfo.Name, new List(), false); _propertyAttributeCache.Add(propertyInfo, attributeList); } } } return attributeList.OfType(); } private static void GetCustomAttributesRecursively(Type type, List foundAttributes, string propertyName, List typesChecked, bool examineInterfacesOnly) { if (typesChecked.Contains(type)) { return; } typesChecked.Add(type); IEnumerable attributes = null; if (propertyName == null) { if (!examineInterfacesOnly || type.IsInterface) { attributes = type.GetCustomAttributes(false).Cast(); } } else { PropertyInfo propertyInfo = type.GetProperty(propertyName); if (propertyInfo != null) { attributes = propertyInfo.GetCustomAttributes(true).Cast(); } } if (attributes != null) { foundAttributes.AddRange(attributes); } if (!examineInterfacesOnly && type.BaseType != null && type.BaseType != typeof(object)) { GetCustomAttributesRecursively(type.BaseType, foundAttributes, propertyName, typesChecked, examineInterfacesOnly); } Type[] interfaces = type.GetInterfaces(); foreach (Type interfaceType in interfaces) { GetCustomAttributesRecursively(interfaceType, foundAttributes, propertyName, typesChecked, examineInterfacesOnly); } } /// public static string GetShortLabel(this Type type) { if (type.IsGenericType) { string genericUglyName = type.Name; if (genericUglyName.IndexOf('`') > -1) { StringBuilder sb = new StringBuilder(genericUglyName.Substring(0, genericUglyName.IndexOf('`'))); sb.Append('<'); bool firstArg = true; foreach (Type genericArgument in type.GetGenericArguments()) { if (firstArg == false) sb.Append(','); sb.Append(genericArgument.GetShortLabel()); firstArg = false; } sb.Append('>'); return sb.ToString(); } return type.Name; } var titleAttributes = type.GetCustomInterfaceAttributes(); if (titleAttributes != null && titleAttributes.Any()) { return titleAttributes.First().Title; } return type.Name; } /// public static bool IsLazyGenericType(this Type type) { return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Lazy<>); } /// public static bool IsAssignableOrLazyFrom(this Type currentType, Type possibleSubType) { if (currentType.IsAssignableFrom(possibleSubType)) { return true; } if (possibleSubType.IsLazyGenericType()) { var lazyType = possibleSubType.GetGenericArguments().First(); return currentType.IsAssignableFrom(lazyType); } else { return false; } } private static void Flush() { _propertyAttributeCache = new Hashtable>(); } } } ================================================ FILE: Composite/Core/Types/TypeLocator.cs ================================================ using System; using System.Reflection; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Composite.Core.Configuration; namespace Composite.Core.Types { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] internal sealed class BaseTypeIncludesAttribute : Attribute { private Type _baseType; private TypeIncludes _includes; public BaseTypeIncludesAttribute(Type baseType) : this(baseType, TypeIncludes.ConcreteTypes) { } public BaseTypeIncludesAttribute(Type baseType, TypeIncludes includes) { _baseType = baseType; _includes = includes; } public Type BaseType { get { return _baseType; } } public TypeIncludes TypeIncludes { get { return _includes; } } } [Flags] internal enum TypeIncludes { /// /// Include interfaces in the result. /// InterfaceTypes = 0x01, /// /// Include concrete types in the result. /// ConcreteTypes = 0x02, /// /// Include primitives in the result. /// PrimitiveTypes = 0x04, } internal sealed class TypeLocator { public static IEnumerable FindTypes(TypeIncludes flags) { return FindTypes(flags, typeof(object)); } public static IEnumerable FindTypes(TypeIncludes flags, Type baseType) { if (baseType == null) throw new ArgumentNullException("baseType", "Must be set to a type"); Func predicate = BuildPredicate(flags); var foundTypes = from containedType in FindTypes(baseType) where predicate(containedType) select containedType; if (!(IsSet(flags, TypeIncludes.ConcreteTypes) && IsConcreteType(baseType))) { if(foundTypes.Contains(baseType)) { IList b = new List(); b.Add(baseType); foundTypes = foundTypes.Except(b.AsQueryable()); } } if (IsSet(flags, TypeIncludes.PrimitiveTypes)) { foundTypes = foundTypes.Concat(FindPrimitiveTypes()); } return foundTypes; } private static IEnumerable FindPrimitiveTypes() { return PrimitiveTypes.Types; } private static IEnumerable FindTypes(Type type) { IEnumerable assemblies = GetPropeableAssemblies(); var typesFound = from containedTypes in ( from assembly in assemblies select GetTypesFromAssembly( assembly ) ) from singleType in containedTypes where type.IsAssignableFrom(singleType) select singleType; return typesFound; } private static IEnumerable GetTypesFromAssembly(Assembly assembly) { try { return assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { if (ex.LoaderExceptions.Length > 0) { throw new InvalidOperationException("Failed to reflect the assembly " + assembly.FullName + ". The loader exception message is " + ex.LoaderExceptions[0].Message, ex); } throw new InvalidOperationException("Failed to reflect the assembly " + assembly.FullName, ex); } } private static IEnumerable GetPropeableAssemblies() { return from assembly in AppDomain.CurrentDomain.GetAssemblies() where IsProbeableAssembly(assembly.FullName) select assembly; } public static bool IsProbeableAssembly(string assemblyFullName) { string lowerAssemblyName = assemblyFullName.ToLowerInvariant(); if (lowerAssemblyName.IndexOf(',') > -1) { lowerAssemblyName = lowerAssemblyName.Substring(0, lowerAssemblyName.IndexOf(',')); } foreach (string excludeName in GlobalSettingsFacade.NonProbableAssemblyNames.Where(n => n.Contains("*") == false)) { if (lowerAssemblyName == excludeName.ToLowerInvariant()) return false; } foreach (string excludeStartName in GlobalSettingsFacade.NonProbableAssemblyNames.Where(n => n.EndsWith("*"))) { if (lowerAssemblyName.StartsWith(excludeStartName.Replace("*", "").ToLowerInvariant())) return false; } return true; } private static bool IsConcreteType(Type type) { return (type.IsClass || type.IsValueType) && !type.IsAbstract; } private static IList> SelectFuntions(TypeIncludes flags) { bool includeAllInterfaces = IsSet(flags, TypeIncludes.InterfaceTypes); bool includeConcreteTypes = IsSet(flags, TypeIncludes.ConcreteTypes); List> functions = new List>(); if (includeAllInterfaces) { functions.Add(x => x.IsInterface); } if (includeConcreteTypes) { functions.Add(x => (IsConcreteType(x))); } return functions; } private static Func BuildPredicate(TypeIncludes flags) { IList> functions = SelectFuntions(flags); Func, Func, Func> or = (f1, f2) => (t => f1(t) || f2(t)); Func current = (x => false); foreach (Func func in functions) { current = or(func, current); } return current; } private static bool IsSet(TypeIncludes flags, TypeIncludes compareFlag) { return ((flags & compareFlag) == compareFlag); } } } ================================================ FILE: Composite/Core/Types/TypeManager.cs ================================================ using System; using Composite.C1Console.Events; namespace Composite.Core.Types { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class TypeManager { private static ITypeManager _implementation = new TypeManagerImpl(); internal static ITypeManager Implementation { get { return _implementation; } set { _implementation = value; } } static TypeManager() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } /// /// Gets a type by name, throws an exception if no type found. /// /// The full name of the type. /// A instance. public static Type GetType(string fullName) { return _implementation.GetType(fullName); } /// /// Returns the type with the provided fullName (or null). /// /// A type or null public static Type TryGetType(string fullName) { return _implementation.TryGetType(fullName); } /// public static string GetRuntimeFullName(string fullName) { if (fullName.StartsWith("DynamicType:")) return fullName.Remove(0, "DynamicType:".Length); return fullName; } /// /// In C1 2.1 and older dynamic types had a "DynamicType:" prefix in references. /// This method removes this no longer used prefix. /// internal static string FixLegasyTypeName(string typeManagerTypeName) { if (typeManagerTypeName.StartsWith("DynamicType:", StringComparison.InvariantCultureIgnoreCase)) { return typeManagerTypeName.Remove(0, "DynamicType:".Length); } return typeManagerTypeName; } /// public static string SerializeType(Type type) { return _implementation.SerializeType(type); } /// public static string TrySerializeType(Type type) { return _implementation.TrySerializeType(type); } /// /// This method return true if there is type with the fullname typeFullname anywhere in the system. /// /// Full name: namespace+name. X.Y.Z where X.Y is the namespace and Z is the type. /// public static bool HasTypeWithName(string typeFullname) { return _implementation.HasTypeWithName(typeFullname); } private static void OnFlushEvent(FlushEventArgs args) { _implementation.OnFlush(); } } } ================================================ FILE: Composite/Core/Types/TypeManagerImpl.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Linq; using System.Xml.Linq; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.Core.Types.BuildinPlugins.BuildinTypeManagerTypeHandler; using Composite.Core.Types.Foundation.PluginFacades; using Composite.Core.Types.Plugins.TypeManagerTypeHandler; using Composite.Core.Types.Plugins.TypeManagerTypeHandler.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Types { internal sealed class TypeManagerImpl : ITypeManager { private ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize, false); private ConcurrentDictionary _serializedTypeLookup = new ConcurrentDictionary(); public Type GetType(string fullName) { return GetType(fullName, true); } private Type GetType(string fullName, bool throwIfNotFound) { Verify.ArgumentNotNullOrEmpty(fullName, "fullName"); Type type; // A little nasty check here... /MRJ if (fullName.StartsWith(" /// Returns the type with the provided fullName (or null). /// /// A type or null public Type TryGetType(string fullName) { try { return GetType(fullName, false); } catch { return null; } } public string SerializeType(Type type) { string serializedType = TrySerializeType(type); if (string.IsNullOrEmpty(serializedType)) { throw new InvalidOperationException( $"No TypeManagerTypeHandler plugins could serialize the given type '{type}'"); } return serializedType; } public string TrySerializeType(Type type) { Verify.ArgumentNotNull(type, nameof(type)); return _serializedTypeLookup.GetOrAdd(type, t => t.IsGenericType ? TrySerializeGenericType(t).ToString() : TrySerializeNonGenericType(t)); } public void AddCompiledType(Type compiledType) { } /// /// This method return true if there is type with the fullname typeFullname anywhere in the system. /// /// Full name: namespace+name. X.Y.Z where X.Y is the namespace and Z is the type. /// public bool HasTypeWithName(string typeFullname) { using (_resourceLocker.ReadLocker) { if (_resourceLocker.Resources.BuildinHandler != null) { return _resourceLocker.Resources.BuildinHandler.HasTypeWithName(typeFullname); } } var providerEntries = _resourceLocker.Resources.ProviderNameList; return providerEntries.Any(entry => TypeManagerTypeHandlerPluginFacade.HasTypeWithName(entry.ProviderName, typeFullname)); } public void OnFlush() { _serializedTypeLookup = new ConcurrentDictionary(); _resourceLocker.ResetInitialization(); } private Type GetGenericType(XElement element) { if (element.HasElements) { XAttribute attribute = element.Attribute("n"); if (attribute == null) return null; List genericArguments = new List(); foreach (XElement childElement in element.Elements()) { Type type = GetGenericType(childElement); if (type == null) return null; genericArguments.Add(type); } Type genericType = Type.GetType(attribute.Value); return genericType?.MakeGenericType(genericArguments.ToArray()); } else { XAttribute attribute = element.Attribute("n"); if (attribute == null) return null; return GetNonGenericType(attribute.Value); } } private Type GetNonGenericType(string fullName) { using (_resourceLocker.ReadLocker) { if (_resourceLocker.Resources.BuildinHandler != null) { return _resourceLocker.Resources.BuildinHandler.GetType(fullName); } } fullName = TypeManager.FixLegasyTypeName(fullName); // This should be the first thing tried, otherwise "old" types are found in Composite.Generated.dll instead of a possible new compiled version of the type /MRJ if (!fullName.Contains(",")) { Type compositeType = typeof (Composite.Data.IData).Assembly.GetType(fullName, false); if (compositeType != null) return compositeType; } List providerEntries = new List(_resourceLocker.Resources.ProviderNameList); foreach (ProviderEntry entry in providerEntries) { Type type = TypeManagerTypeHandlerPluginFacade.GetType(entry.ProviderName, fullName); if (type != null) { return type; } } return null; } private XElement TrySerializeGenericType(Type type) { if (type.IsGenericType) { Type genericType = type.GetGenericTypeDefinition(); Type[] genericArguments = type.GetGenericArguments(); XElement element = new XElement("t", new XAttribute("n", genericType.AssemblyQualifiedName) ); foreach (Type genericArgument in genericArguments) { XElement elm = TrySerializeGenericType(genericArgument); if (elm == null) return null; element.Add(elm); } return element; } string serializedType = TrySerializeNonGenericType(type); if (serializedType == null) return null; return new XElement("t", new XAttribute("n", serializedType)); } private string TrySerializeNonGenericType(Type type) { using (_resourceLocker.ReadLocker) { if (_resourceLocker.Resources.BuildinHandler != null) { string serializedType = _resourceLocker.Resources.BuildinHandler.SerializeType(type); if (serializedType != null) { return serializedType; } } } var providerEntries = new List(_resourceLocker.Resources.ProviderNameList); foreach (ProviderEntry entry in providerEntries) { string serializedType = TypeManagerTypeHandlerPluginFacade.SerializedType(entry.ProviderName, type); if (serializedType != null) { return serializedType; } } return null; } private static IConfigurationSource GetConfiguration() { IConfigurationSource source = ConfigurationServices.ConfigurationSource; if (null == source) { throw new ConfigurationErrorsException("No configuration source specified"); } return source; } private sealed class Resources { public List ProviderNameList; public ITypeManagerTypeHandler BuildinHandler; public static void Initialize(Resources resources) { resources.BuildinHandler = null; if (RuntimeInformation.IsUnittest && ConfigurationServices.ConfigurationSource?.GetSection(TypeManagerTypeHandlerSettings.SectionName) == null) { resources.BuildinHandler = new BuildinTypeManagerTypeHandler(); } else { IConfigurationSource source = GetConfiguration(); TypeManagerTypeHandlerSettings settings = source.GetSection(TypeManagerTypeHandlerSettings.SectionName) as TypeManagerTypeHandlerSettings; if (settings == null) { throw new ConfigurationErrorsException($"Failed to load the configuration section '{TypeManagerTypeHandlerSettings.SectionName}' from the configuration"); } resources.ProviderNameList = new List(); foreach (TypeManagerTypeHandlerData data in settings.TypeManagerTypeHandlerPlugins) { resources.ProviderNameList.Add(new ProviderEntry(data.Priority, data.Name)); } resources.ProviderNameList.Sort((e1, e2) => e1.Priority - e2.Priority); } } } [DebuggerDisplay("ProviderName = {ProviderName}, Priority = {Priority}")] private class ProviderEntry { public ProviderEntry(int priority, string providerName) { Priority = priority; ProviderName = providerName; } public int Priority { get; } public string ProviderName { get; } } } } ================================================ FILE: Composite/Core/Types/ValueTypeConverter.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Reflection; using System.Xml; using System.Xml.Linq; using Composite.C1Console.Users; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; using Composite.Core.Xml; using Composite.Data; namespace Composite.Core.Types { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ValueTypeConverter { private static readonly MethodInfo NewLazyObjectMethodInfo = StaticReflection.GetGenericMethodInfo(() => NewLazyObject(null)); /// public static object Convert(object value, Type targetType) { Exception conversionError; return TryConvert(value, targetType, out conversionError); } /// internal static object TryConvert(object value, Type targetType, out Exception conversionError) { conversionError = null; if (value == null) { if (!targetType.IsPrimitive) { return null; } throw new InvalidOperationException(string.Format("Can not convert null to type '{0}'", targetType)); } if (targetType.IsInstanceOfType(value)) { return value; } if (targetType.IsLazyGenericType() && !value.GetType().IsLazyGenericType()) { Type genericArgument = targetType.GetGenericArguments()[0]; object convertedValue = TryConvert(value, genericArgument, out conversionError); return CreateLazyObject(() => convertedValue, genericArgument); } var helper = targetType.GetCustomAttributesRecursively().FirstOrDefault(); if (helper != null) { object ret; if (helper.TryConvert(value, targetType, out ret)) { return ret; } } var helper2 = value.GetType().GetCustomAttributesRecursively().FirstOrDefault(); if (helper2 != null) { object ret; if (helper2.TryConvert(value, targetType, out ret)) { return ret; } } if (targetType == typeof(object)) { return value; } if ((IsGenericEnumerable(value.GetType())) && (IsGenericEnumerable(targetType))) { Type targetItemType = targetType.GetGenericArguments()[0]; IList targetValue = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(new [] { targetItemType })); foreach (object valueItem in ((IEnumerable)value)) { object convertedValueItem = Convert(valueItem, targetItemType); targetValue.Add(convertedValueItem); } return targetValue; } // Haz item, wantz list of it. if (!IsGenericEnumerable(value.GetType()) && IsGenericEnumerable(targetType)) { Type targetItemType = targetType.GetGenericArguments()[0]; if (targetItemType.IsInstanceOfType(value)) { IList targetValue = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(new [] { targetItemType })); if (value is string) { ((string)value).Split(',').ForEach(f => targetValue.Add(f)); } else { targetValue.Add(value); } return targetValue; } } var stringValue = value as string; if (stringValue != null) { return TryConvertStringValue(stringValue, targetType, ref conversionError); } if (targetType == typeof(string)) { if (value is Type) return TypeManager.SerializeType((Type)value); if (value is DateTime) return XmlConvert.ToString((DateTime)value, XmlDateTimeSerializationMode.Local); if (value is IEnumerable) return string.Join(",", ((IEnumerable)value).Cast().ToArray()); } TypeConverter targetConverter = TypeDescriptor.GetConverter(targetType); if (targetConverter.CanConvertFrom(value.GetType())) { return targetConverter.ConvertFrom(null, UserSettings.CultureInfo, value); } TypeConverter valueConverter = TypeDescriptor.GetConverter(value.GetType()); if (valueConverter.CanConvertTo(targetType)) { return valueConverter.ConvertTo(null, UserSettings.CultureInfo, value, targetType); } throw new InvalidOperationException(string.Format("No conversion from {0} to {1} could be found", value.GetType(), targetType)); } private static object TryConvertStringValue(string stringValue, Type targetType, ref Exception conversionError) { if (targetType == typeof (Type)) { return stringValue != string.Empty ? TypeManager.GetType(stringValue) : null; } if (targetType == typeof (XhtmlDocument)) { if (stringValue == string.Empty) { return new XhtmlDocument(); } return XhtmlDocument.Parse(stringValue); } if (targetType == typeof (XDocument)) { return XDocument.Parse(stringValue); } if (targetType == typeof (XElement)) { return XElement.Parse(stringValue); } if (targetType == typeof (IEnumerable)) { try { XElement wrapper = XElement.Parse(string.Format("{0}", stringValue)); return wrapper.Nodes(); } catch { throw new InvalidCastException(string.Format("Unable to convert string '{0}' to a list of XNodes.", stringValue)); } } if (targetType == typeof (IEnumerable)) { try { XElement wrapper = XElement.Parse(string.Format("{0}", stringValue)); return wrapper.Elements(); } catch { throw new InvalidCastException(string.Format("Unable to convert string '{0}' to a list of XElements.", stringValue)); } } if (targetType == typeof (XNamespace)) { return XNamespace.Get(stringValue); } if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof (Nullable<>)) { Type valueType = targetType.GetGenericArguments()[0]; if (IsOneOfTheHandledValueTypes(valueType)) { if (stringValue.Trim().Length == 0) { return null; } return TryConvertValueType(stringValue, valueType, out conversionError); } } if (IsOneOfTheHandledValueTypes(targetType)) { return TryConvertValueType(stringValue, targetType, out conversionError); } TypeConverter tc = TypeDescriptor.GetConverter(targetType); CultureInfo culture = LocalizationScopeManager.CurrentLocalizationScope; object convertedResult = tc.ConvertFromString(null, culture, stringValue); if (convertedResult == null && !string.IsNullOrEmpty(stringValue)) { throw new InvalidOperationException(string.Format("Unable to convert string value '{0}' to type '{1}'", stringValue, targetType.FullName)); } return convertedResult; } private static object CreateLazyObject(Func func, Type type) { return NewLazyObjectMethodInfo.MakeGenericMethod(type).Invoke(null, new object[] { func }); } private static Lazy NewLazyObject(Func func) { return new Lazy(() => (T)func(), true); } private static bool IsOneOfTheHandledValueTypes(Type type) { return type == typeof (bool) || type == typeof (Guid) || type == typeof (int) || type == typeof (Decimal); } private static object TryConvertValueType(string stringValue, Type targetType, out Exception conversionError) { conversionError = null; if (targetType == typeof(bool)) { bool boolResult; if (!bool.TryParse(stringValue, out boolResult)) { boolResult = false; // TODO: localize conversionError = new InvalidOperationException("Failed to convert value '{0}' into a Boolean".FormatWith(stringValue)); } return boolResult; } if (targetType == typeof(int)) { int intResult = 0; try { intResult = Int32.Parse(stringValue); } catch(OverflowException) { conversionError = new InvalidOperationException(LocalizationFiles.Composite_Management.Validation_Int32_Overflow); } catch (Exception ex) { conversionError = ex; } return intResult; } if (targetType == typeof(decimal)) { // TODO: localize decimal decimalResult; if (!decimal.TryParse(stringValue, out decimalResult)) { conversionError = new InvalidOperationException("Failed to convert value '{0}' into a Decimal".FormatWith(stringValue)); } return decimalResult; } if (targetType == typeof(Guid)) { Guid guidResult = Guid.Empty; if (string.IsNullOrEmpty(stringValue) || !Guid.TryParse(stringValue, out guidResult)) { // TODO: localize conversionError = new InvalidOperationException("Failed to convert value '{0}' into a Guid".FormatWith(stringValue)); } return guidResult; } throw new NotImplementedException("Supported types should be defined in IsOneOfTheHandledValueTypes() method"); } /// public static T Convert(object value) { return (T)Convert(value, typeof(T)); } private static bool IsGenericEnumerable(Type type) { if (!type.IsGenericType) return false; type = type.GetGenericTypeDefinition(); return typeof (IEnumerable<>).IsAssignableFrom(type) || typeof (List<>).IsAssignableFrom(type) || typeof (IList<>).IsAssignableFrom(type); } } } ================================================ FILE: Composite/Core/Types/ValueTypeConverterHelperAttribute.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Composite.Core.Types { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class ValueTypeConverterHelperAttribute : Attribute { /// public abstract bool TryConvert(object sourcevalue, Type targetType, out object targetValue); } } ================================================ FILE: Composite/Core/UrlBuilder.cs ================================================ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Web; using Composite.Core.Extensions; using Composite.Core.Routing.Pages; namespace Composite.Core { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class UrlBuilder { private static readonly string IncorrectValueParam = "__***IncorrectValue***__"; private string _pathInfo; private string _filePath; private string _anchor; private readonly List> _queryParameters; /// public UrlBuilder(string url) { Verify.ArgumentNotNull(url, nameof(url)); _queryParameters = new List>(); int anchorIndex = url.IndexOf('#'); if(anchorIndex > -1) { Anchor = (anchorIndex == url.Length - 1) ? string.Empty : url.Substring(anchorIndex + 1); url = url.Substring(0, anchorIndex); } int questionMarkIndex = url.IndexOf('?'); if (questionMarkIndex < 0) { ExtractPathInfo(url, url, out _filePath, out _pathInfo); return; } ExtractPathInfo(url, url.Substring(0, questionMarkIndex), out _filePath, out _pathInfo); if (questionMarkIndex + 1 == url.Length) { return; } string queryParamStr = url.Substring(questionMarkIndex + 1, url.Length - questionMarkIndex - 1); foreach (string queryParam in queryParamStr.Split(new[] { "&", "&" }, StringSplitOptions.RemoveEmptyEntries)) { string[] parts = queryParam.Split(new[] { '=' }); bool badUrl = parts.Length != 2; if (!badUrl) { string encodedKey = parts[0]; string encodedValue = parts[1]; string key = DefaultHttpEncoder.UrlDecode(encodedKey); string value = DefaultHttpEncoder.UrlDecode(encodedValue); // For media URLs we need to support "/" character in a query parameter value badUrl = DefaultHttpEncoder.UrlEncode(key) != encodedKey.Replace("%20", "+") || DefaultHttpEncoder.UrlEncode(value) != encodedValue.Replace("%20", "+").Replace("/", "%2f"); if (!badUrl) { _queryParameters.Add(new KeyValuePair(key, value)); continue; } } _queryParameters.Add(new KeyValuePair(queryParam, IncorrectValueParam)); } } internal static class DefaultHttpEncoder { public static string UrlEncode(string urlPart) { using (new NoHttpContext()) { return HttpUtility.UrlEncode(urlPart); } } public static string UrlPathEncode(string urlPart) { using (new NoHttpContext()) { return HttpUtility.UrlPathEncode(urlPart); } } public static string UrlDecode(string urlPart) { using (new NoHttpContext()) { return HttpUtility.UrlDecode(urlPart); } } private class NoHttpContext : IDisposable { private readonly HttpContext _context; public NoHttpContext() { _context = HttpContext.Current; HttpContext.Current = null; } public void Dispose() { HttpContext.Current = _context; #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~NoHttpContext() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } private static void ExtractPathInfo(string originalUrl, string relativePath, out string filePath, out string pathInfo) { // Checking if pageInfo has already been extracted by C1PageRoute. It enables backward compatibility with some modules var httpContext = HttpContext.Current; if(httpContext != null && httpContext.RequestIsAvaliable() && originalUrl == httpContext.Request.RawUrl && C1PageRoute.PageUrlData != null) { pathInfo = C1PageRoute.PageUrlData.PathInfo; int pathInfoLength = (pathInfo ?? string.Empty).Length; filePath = relativePath.Substring(0, relativePath.Length - pathInfoLength); return; } int aspxExtOffset = relativePath.IndexOf(".aspx", StringComparison.Ordinal); if (aspxExtOffset < 0 || aspxExtOffset == relativePath.Length - 5) { pathInfo = null; filePath = relativePath; return; } filePath = relativePath.Substring(0, aspxExtOffset + 5); pathInfo = relativePath.Substring(aspxExtOffset + 5); } /// public override string ToString() { // NOTE: StringBuilder shouldn't be used here - it is to slow string queryString = QueryString; string result = _filePath; if (_pathInfo != null) { // TODO: encode symbols in path info result += _pathInfo; } if (queryString != string.Empty) { result += "?" + queryString; } if(_anchor != null) { result += "#" + _anchor; } return result; // _filePath + _pathInfo + "?" + queryString + ("#" + _anchor)" } /// public void AddQueryParameters(NameValueCollection parameters) { foreach (string key in parameters) { this[key] = parameters[key]; } } /// public NameValueCollection GetQueryParameters() { var result = new NameValueCollection(); foreach (KeyValuePair pair in _queryParameters) { result.Add(pair.Key, pair.Value); } return result; } /// public string this[string key] { get { string value = _queryParameters.Where(pair => pair.Key == key).Select(pair => pair.Value).FirstOrDefault(); return value ?? string.Empty; } set { for (int i = 0; i < _queryParameters.Count; i++) { if (_queryParameters[i].Key == key) { if (value == null) { _queryParameters.RemoveAt(i); } else { _queryParameters[i] = new KeyValuePair(key, value); } return; } } if (value != null) { _queryParameters.Add(new KeyValuePair(key, value)); } } } /// public string PathInfo { get { return _pathInfo ?? string.Empty; } set { _pathInfo = value; } } /// public string FilePath { get { return _filePath; } set { Verify.ArgumentNotNull(value, "value"); _filePath = value; } } /// /// Returns FilePath + PathInfo /// /// internal string FullPath { get { return (_filePath ?? string.Empty) + (_pathInfo ?? string.Empty); } } /// public string RelativeFilePath { get { string serverUrl = ServerUrl; return (serverUrl == string.Empty) ? _filePath : _filePath.Substring(serverUrl.Length - 1); } } /// public string ServerUrl { get { if (_filePath.IsNullOrEmpty()) { return string.Empty; } int index1 = _filePath.IndexOf("://", StringComparison.Ordinal); if (index1 <= 0 || _filePath.Length == index1 + 4) { return string.Empty; } int index2 = _filePath.IndexOf('/', index1 + 3); if (index2 < 0) { // Urls like "http://ww.composite.net" return _filePath; } return _filePath.Substring(0, index2 + 1); } set { if (!ServerUrl.IsNullOrEmpty()) { throw new NotImplementedException(); } if (value.IsNullOrEmpty()) return; Verify.IsTrue(value.EndsWith("/"), "Wrong server url string"); if (_filePath.StartsWith("/")) _filePath = _filePath.Substring(1); _filePath = value + _filePath; } } /// public string QueryString { get { if (_queryParameters.Count == 0) { return string.Empty; } var sb = new StringBuilder(); for (int i = 0; i < _queryParameters.Count; i++) { if (i != 0) { sb.Append("&"); } if (_queryParameters[i].Value == IncorrectValueParam) { sb.Append(_queryParameters[i].Key); } else { sb.Append(DefaultHttpEncoder.UrlEncode(_queryParameters[i].Key)); sb.Append('='); sb.Append(DefaultHttpEncoder.UrlEncode(_queryParameters[i].Value)); } } return sb.ToString(); } } /// public static implicit operator string(UrlBuilder builder) { return builder.ToString(); } /// public string Anchor { get { return _anchor; } set { _anchor = value; } } } } ================================================ FILE: Composite/Core/WebClient/Ajax/AjaxResponseHttpModule.cs ================================================ using System; using System.Web; using System.Web.UI; using System.Web.WebPages; namespace Composite.Core.WebClient.Ajax { internal class AjaxResponseHttpModule : IHttpModule { public void Init(HttpApplication context) { context.PostMapRequestHandler += AttachFilter; } private static void AttachFilter(object sender, EventArgs e) { var httpContext = HttpContext.Current; if (httpContext.Handler != null && (httpContext.Handler is Page || httpContext.Handler is WebPageHttpHandler) && httpContext.Request.RequestType == "GET") { var response = httpContext.Response; response.Filter = new AjaxStream(response.Filter); } } public void Dispose() { } } } ================================================ FILE: Composite/Core/WebClient/Ajax/AjaxStream.cs ================================================ using System; using System.IO; using System.Web; using Composite.Core.WebClient.HttpModules; namespace Composite.Core.WebClient.Ajax { internal class AjaxStream : Utf8StringTransformationStream { private static readonly string ScriptManagerJS = "UpdateManager.xhtml = null;"; public AjaxStream(Stream innerOuputStream): base(innerOuputStream) { } public override string Process(string str) { int jsCodePosition = str.IndexOf(ScriptManagerJS, StringComparison.Ordinal); if (jsCodePosition == -1) { return str; } // Removing encoding symbol if (str[0] != '<') // Method StartsWith(...) doesn't work correctly here { str = str.Substring(1); jsCodePosition--; } string encodedText = HttpContext.Current.Server.UrlEncode(str).Replace("+", "%20"); //EncodeJsString(str); return string.Format("{0}UpdateManager.xhtml = \"{1}\";{2}", str.Substring(0, jsCodePosition), encodedText, str.Substring(jsCodePosition + ScriptManagerJS.Length)); } } } ================================================ FILE: Composite/Core/WebClient/ApplicationLevelEventHandlers.cs ================================================ using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Globalization; using System.Text; using System.Web; using Composite.AspNet; using Composite.C1Console.Actions.Data; using Composite.C1Console.Elements; using Composite.C1Console.Events; using Composite.Search; using Composite.Core.Application; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.Implementation; using Composite.Core.Instrumentation; using Composite.Core.Logging; using Composite.Core.Routing; using Composite.Core.Threading; using Composite.Core.Types; using Composite.Core.WebClient.Media; using Composite.Data.Types; using Composite.Functions; using Composite.Plugins.Elements.UrlToEntityToken; using Composite.Plugins.Routing.InternalUrlConverters; using Microsoft.Extensions.DependencyInjection; namespace Composite.Core.WebClient { /// /// ASP.NET Application level logic. This class primarily interact between C1 CMS and the ASP.NET Application. /// Most of the members on this class is not documented, except for those which developers may find useful to interact with. /// public static class ApplicationLevelEventHandlers { private const string _verboseLogEntryTitle = "RGB(205, 92, 92)ApplicationEventHandler"; static readonly object _syncRoot = new object(); private static DateTime _startTime; private static bool _systemIsInitialized; private static readonly ConcurrentDictionary> _c1PageCustomStringProviders = new ConcurrentDictionary>(); /// public static bool LogRequestDetails { get; set; } /// public static bool LogApplicationLevelErrors { get; set; } /// public static void Application_Start(object sender, EventArgs e) { _startTime = DateTime.Now; if (RuntimeInformation.IsDebugBuild) { Log.LogInformation(_verboseLogEntryTitle, "AppDomain {0} started at {1} in process {2}", AppDomain.CurrentDomain.Id, _startTime.ToString("HH:mm:ss:ff"), Process.GetCurrentProcess().Id); } SystemSetupFacade.SetFirstTimeStart(); InitializeServices(); if (!SystemSetupFacade.IsSystemFirstTimeInitialized) { return; } if (_systemIsInitialized) { return; } if (AppDomain.CurrentDomain.BaseDirectory.Length > GlobalSettingsFacade.MaximumRootPathLength) { throw new InvalidOperationException("Windows limitation problem detected! You have installed the website at a place where the total path length of the file with the longest filename exceeds the maximum allowed in Windows. See http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx#paths"); } AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload; lock (_syncRoot) { if (_systemIsInitialized) return; ApplicationStartInitialize(RuntimeInformation.IsDebugBuild); _systemIsInitialized = true; } } private static void InitializeServices() { UrlToEntityTokenFacade.Register(new DataUrlToEntityTokenMapper()); UrlToEntityTokenFacade.Register(new MediaUrlToEntityTokenMapper()); UrlToEntityTokenFacade.Register(new ServerLogUrlToEntityTokenMapper()); UrlToEntityTokenFacade.Register(new WebsiteFileUrlToEntityTokenMapper()); var services = ServiceLocator.ServiceCollection; services.AddLogging(); services.AddRoutedData(); services.AddDataActionTokenResolver(); services.AddDefaultSearchDocumentSourceProviders(); services.AddDefaultImageFileFormatProviders(); InternalUrls.Register(new MediaInternalUrlConverter()); InternalUrls.Register(new PageInternalUrlConverter()); services.AddSingleton(new SmtpMailer()); services.AddTransient(); VersionedDataHelper.Initialize(); } /// public static void Application_End(object sender, EventArgs e) { if (RuntimeInformation.IsDebugBuild) { Log.LogInformation(_verboseLogEntryTitle, "AppDomain {0} ended at {1} in process {2}", AppDomain.CurrentDomain.Id, DateTime.Now.ToString("HH:mm:ss:ff"), Process.GetCurrentProcess().Id); } if (!SystemSetupFacade.IsSystemFirstTimeInitialized) { return; } using (ThreadDataManager.Initialize()) { try { CodeGenerationManager.ValidateCompositeGenerate(_startTime); CodeGenerationManager.GenerateCompositeGeneratedAssembly(); } catch (Exception ex) { Log.LogCritical("Global.asax", "Error updating Composite.Generated.dll"); Log.LogCritical("Global.asax", ex); } try { GlobalEventSystemFacade.PrepareForShutDown(); if (RuntimeInformation.IsDebugBuild) { LogShutDownReason(); } GlobalEventSystemFacade.ShutDownTheSystem(); TempDirectoryFacade.OnApplicationEnd(); } catch (Exception ex) { Log.LogCritical("Global.asax", ex); throw; } Log.LogVerbose("Global.asax", $"--- Web Application End, {DateTime.Now.ToLongTimeString()} Id = {AppDomain.CurrentDomain.Id}---"); } } /// public static void Application_BeginRequest(object sender, EventArgs e) { var context = ((HttpApplication) sender).Context; ThreadDataManager.InitializeThroughHttpContext(); if (SystemSetupFacade.IsSystemFirstTimeInitialized) { ServiceLocator.CreateRequestServicesScope(context); } if (LogRequestDetails) { // LoggingService.LogVerbose("Begin request", string.Format("{0}", Request.Path)); context.Items.Add("Global.asax timer", Environment.TickCount); } } /// public static void Application_EndRequest(object sender, EventArgs e) { var context = ((HttpApplication) sender).Context; try { ServiceLocator.DisposeRequestServicesScope(context); if (LogRequestDetails && context.Items.Contains("Global.asax timer")) { int startTimer = (int)context.Items["Global.asax timer"]; string requestPath = context.Request.Path; Log.LogVerbose("End request", $"{requestPath} - took {Environment.TickCount - startTimer} ms"); } } finally { ThreadDataManager.FinalizeThroughHttpContext(); } } /// public static void Application_Error(object sender, EventArgs e) { var httpApplication = (HttpApplication) sender; Exception exception = httpApplication.Server.GetLastError(); var eventType = TraceEventType.Error; var httpContext = httpApplication.Context; if (httpContext != null) { bool is404 = exception is HttpException httpException && httpException.GetHttpCode() == 404; if (is404) { string rawUrl = httpContext.Request.RawUrl; if (!UrlUtils.IsAdminConsoleRequest(rawUrl)) { string customPageNotFoundUrl = HostnameBindingsFacade.GetCustomPageNotFoundUrl(); if (!customPageNotFoundUrl.IsNullOrEmpty()) { if (rawUrl == customPageNotFoundUrl) { throw new HttpException(500, $"'Page not found' url isn't handled. Url: '{rawUrl}'"); } httpContext.Server.ClearError(); httpContext.Response.Clear(); httpContext.Response.Redirect(customPageNotFoundUrl, true); return; } eventType = TraceEventType.Verbose; } } // Logging request url if (LogApplicationLevelErrors) { HttpRequest request = null; try { request = httpContext.Request; } catch { // Request may not be available at this point } if (request != null) { LoggingService.LogEntry("Application Error", $"Failed to process '{request.RequestType}' request to url '{request.RawUrl}'", LoggingService.Category.General, eventType); } } } if (LogApplicationLevelErrors) { while (exception != null) { LoggingService.LogEntry("Application Error", exception.ToString(), LoggingService.Category.General, eventType); exception = exception.InnerException; } } } /// public static string GetVaryByCustomString(HttpContext context, string custom) { if (custom == "C1Page") { string rawUrl = context.Request.RawUrl; UrlKind urlKind; var pageUrl = PageUrls.UrlProvider.ParseUrl(rawUrl, new UrlSpace(context), out urlKind); var page = pageUrl?.GetPage(); if (page != null) { var pageCacheKey = new StringBuilder(page.ChangeDate.ToString(CultureInfo.InvariantCulture)); if (context.Request.IsSecureConnection) { pageCacheKey.Append("https"); } // Adding the relative path from RawUrl as a part of cache key to make ASP.NET cache respect casing of urls pageCacheKey.Append(new UrlBuilder(rawUrl).FullPath); foreach (string key in _c1PageCustomStringProviders.Keys) { pageCacheKey.Append(_c1PageCustomStringProviders[key](context)); } return pageCacheKey.ToString(); } return string.Empty; } return null; } /// /// Register a function that provide a custom string to be part of a C1 Page cache key. You should register a function just once and during the application initialization. /// Your function will be called with the current HttpContext and should return either null or a string for the C1 Page request in relation to caching. /// An example situation where this can be used: You want to have full page caching, but you have C1 Page content being dependant on client settings, such as HTTP CLIENT. /// You should kep the 'spread in values' you return to a minimum - each unique string will create a new cache entry and consume memory. /// /// A string unique for your function - used to ensure this is only registered once /// Your function the can return a custom string public static void RegisterC1PageVaryByCustomStringProvider( string providerId, Func customStringBuilder) { _c1PageCustomStringProviders.GetOrAdd(providerId, customStringBuilder); } /// public static void ApplicationStartInitialize(bool displayDebugInfo = false) { ThreadDataManager.InitializeThroughHttpContext(); if (displayDebugInfo) { Log.LogVerbose("Global.asax", "--- Web Application Start, {0} Id = {1} ---", DateTime.Now.ToLongTimeString(), AppDomain.CurrentDomain.Id); } PerformanceCounterFacade.SystemStartupIncrement(); using (GlobalInitializerFacade.GetPreInitHandlersScope()) { ApplicationStartupFacade.FireConfigureServices(ServiceLocator.ServiceCollection); ServiceLocator.BuildServiceProvider(); ServiceLocator.CreateRequestServicesScope(HttpContext.Current); HttpRuntime.WebObjectActivator = new WebObjectActivator(ServiceLocator.ServiceProvider); ApplicationStartupFacade.FireBeforeSystemInitialize(ServiceLocator.ServiceProvider); } TempDirectoryFacade.OnApplicationStart(); HostnameBindingsFacade.Initialize(); ApplicationStartupFacade.FireSystemInitialized(ServiceLocator.ServiceProvider); ThreadDataManager.FinalizeThroughHttpContext(); } private static void CurrentDomain_DomainUnload(object sender, EventArgs e) { if (RuntimeInformation.IsDebugBuild) { Log.LogInformation(_verboseLogEntryTitle, $"AppDomain {AppDomain.CurrentDomain.Id} unloaded at {DateTime.Now:HH:mm:ss:ff}"); } } private static void LogShutDownReason() { HttpRuntime runtime = (HttpRuntime)typeof(System.Web.HttpRuntime).InvokeMember("_theRuntime", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.GetField, null, null, null); if (runtime == null) { Log.LogWarning("ASP.NET Shut Down", "Unable to determine cause of shut down"); return; } string shutDownMessage = (string)runtime.GetType().InvokeMember("_shutDownMessage", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.GetField, null, runtime, null); string shutDownStack = (string)runtime.GetType().InvokeMember("_shutDownStack", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.GetField, null, runtime, null); shutDownMessage = (shutDownMessage ?? "null").Replace("\n", " \n"); Log.LogVerbose("RGB(250,50,50)ASP.NET Shut Down", $"_shutDownMessage=\n{shutDownMessage}\n\n_shutDownStack=\n{shutDownStack}"); } } } ================================================ FILE: Composite/Core/WebClient/BrowserRender.cs ================================================ // #define BrowserRender_NoCache using System; using System.Collections.Generic; using System.IO; using System.Web; using Composite.C1Console.Events; using Composite.Core.Application; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.PackageSystem; using Composite.Core.Parallelization; using Composite.Data.Plugins.DataProvider.Streams; using Timer = System.Timers.Timer; using System.Threading.Tasks; using Composite.Core.WebClient.PhantomJs; namespace Composite.Core.WebClient { internal static class BrowserRender { private static readonly string LogTitle = typeof (BrowserRender).Name; private static readonly string CacheImagesFolder = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.CacheDirectory), "PreviewImages"); static BrowserRender() { GlobalEventSystemFacade.SubscribeToShutDownEvent(a => ShutdownPhantomJsExeSilent()); PackageInstaller.OnPackageInstallation += ShutdownPhantomJsExeSilent; FileChangeNotificator.Subscribe(PhantomServer.ScriptFilePath, (a, b) => PhantomServer.ShutDown(false)); } private static Timer _recycleTimer; private static DateTime _lastUsageDate = DateTime.MinValue; private static readonly TimeSpan RecycleOnIdleInterval = TimeSpan.FromSeconds(30); private const int RecycleTimerInterval_ms = 10000; private const int EnsureReadinessDelay_ms = 30000; private static volatile bool Enabled = true; private static volatile bool ServerAvailabilityChecked; private static readonly AsyncLock _serverAvailabilityCheckLock = new AsyncLock(); /// /// Ensures that the BrowserRenderer service is launched, without blocking the current thread /// public static void EnsureReadiness() { if (!GlobalSettingsFacade.FunctionPreviewEnabled) return; _lastUsageDate = DateTime.Now; if (ServerAvailabilityChecked) return; var context = HttpContext.Current; HttpCookie[] cookies = GetAuthenticationCookies(context); Task.Factory.StartNew(async () => { const int delaySlice = 500; for (int i = 0; i < EnsureReadinessDelay_ms / delaySlice; i++) { if (!SystemFullyOnline) return; await Task.Delay(delaySlice); } await CheckServerAvailabilityAsync(context, cookies); }); } public static DateTime GetLastCacheUpdateTime(string mode) { string folderPath = GetCacheFolder(mode); if (!C1Directory.Exists(folderPath)) { C1Directory.CreateDirectory(folderPath); } return C1Directory.GetCreationTime(folderPath); } /// /// Renders a url and return a full path to a rendered image, or null when rendering process is failing or inaccessible. /// public static async Task RenderUrlAsync(HttpContext context, string url, string mode) { string dropFolder = GetCacheFolder(mode); if (!C1Directory.Exists(dropFolder)) { C1Directory.CreateDirectory(dropFolder); } string urlHash = Convert.ToBase64String(BitConverter.GetBytes(url.GetHashCode())).Substring(0, 6).Replace('+', '-').Replace('/', '_'); string outputImageFileName = Path.Combine(dropFolder, urlHash + ".png"); string outputFileName = Path.Combine(dropFolder, urlHash + ".output"); string redirectLogFileName = Path.Combine(dropFolder, urlHash + ".redirect"); string errorFileName = Path.Combine(dropFolder, urlHash + ".error"); if (C1File.Exists(outputImageFileName) || C1File.Exists(outputFileName)) { #if BrowserRender_NoCache File.Delete(outputFileName); #else string[] output = C1File.Exists(outputFileName) ? C1File.ReadAllLines(outputFileName) : null; return new RenderingResult { FilePath = outputImageFileName, Output = output, Status = RenderingResultStatus.Success}; #endif } if (!Enabled) { return null; } var result = await MakePreviewRequestAsync(context, url, outputImageFileName, mode); if (result.Status >= RenderingResultStatus.Error) { C1File.WriteAllLines(errorFileName, result.Output); } if (!Enabled) { return null; } if (result.Status == RenderingResultStatus.Success) { C1File.WriteAllLines(outputFileName, result.Output); } else if (result.Status == RenderingResultStatus.Redirect) { C1File.WriteAllLines(redirectLogFileName, result.Output); } return result; } public static void ClearCache(string renderingMode) { var folder = GetCacheFolder(renderingMode); if (C1Directory.Exists(folder)) { Task.Run(() => ClearCacheInt(folder)); } } private static string GetCacheFolder(string mode) { return CacheImagesFolder + "\\" + mode; } private static async Task MakePreviewRequestAsync(HttpContext context, string url, string outputFileName, string mode) { var cookies = GetAuthenticationCookies(context); await CheckServerAvailabilityAsync(context, cookies); if (!Enabled) { return null; } _lastUsageDate = DateTime.Now; return await PhantomServer.RenderUrlAsync(cookies, url, outputFileName, mode); } private static HttpCookie[] GetAuthenticationCookies(HttpContext context) { var allCookies = context.Request.Cookies; var result = new List(); foreach (string cookieName in allCookies) { var cookie = allCookies[cookieName]; result.Add(cookie); } return result.ToArray(); } private static bool SystemFullyOnline => ApplicationOnlineHandlerFacade.IsApplicationOnline && GlobalInitializerFacade.SystemCoreInitialized && !GlobalInitializerFacade.SystemCoreInitializing && SystemSetupFacade.IsSystemFirstTimeInitialized; private static async Task CheckServerAvailabilityAsync(HttpContext context, HttpCookie[] cookies) { if (ServerAvailabilityChecked || cookies == null) return; using (await _serverAvailabilityCheckLock.LockAsync()) { if (ServerAvailabilityChecked) return; if (!SystemFullyOnline) return; try { string testUrl = UrlUtils.Combine(new UrlBuilder(context.Request.Url.ToString()).ServerUrl, UrlUtils.PublicRootPath); SetupRecycleTimer(); string outputFileName = Path.Combine(TempDirectoryFacade.TempDirectoryPath, "phantomtest.png"); var result = await PhantomServer.RenderUrlAsync(cookies, testUrl, outputFileName, "test"); if (result.Status == RenderingResultStatus.PhantomServerTimeout || result.Status == RenderingResultStatus.PhantomServerIncorrectResponse || result.Status == RenderingResultStatus.PhantomServerNoOutput) { Enabled = false; Log.LogWarning(LogTitle, "The function preview feature will be turned off as PhantomJs server failed to complete a test HTTP request"); } } catch (Exception ex) { Log.LogWarning(LogTitle, "PhantomJs server unable to complete HTTP requests, preventing C1 Function preview images from being generated. " + Environment.NewLine + ex); Enabled = false; PhantomServer.ShutDown(false); } finally { ServerAvailabilityChecked = true; } } } private static void ShutdownPhantomJsExeSilent() { Enabled = false; try { PhantomServer.ShutDown(false, true); } catch { } } private static void ClearCacheInt(string folder) { foreach (var file in C1Directory.GetFiles(folder, "*.*")) { try { C1File.Delete(file); } catch { } } C1Directory.SetCreationTime(folder, DateTime.Now); } private static void SetupRecycleTimer() { if (_recycleTimer != null) return; var timer = new Timer(RecycleTimerInterval_ms) {AutoReset = true}; timer.Elapsed += (a, b) => RecycleIfNotUsed(); timer.Start(); _recycleTimer = timer; } private static void RecycleIfNotUsed() { if (DateTime.Now - _lastUsageDate < RecycleOnIdleInterval) { return; } PhantomServer.ShutDown(false); } } } ================================================ FILE: Composite/Core/WebClient/BuildManagerHelper.cs ================================================ using Composite.Core.IO; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Web.Compilation; using System.Web.Hosting; using System.Xml.Linq; using Composite.Core.Extensions; namespace Composite.Core.WebClient { internal static class BuildManagerHelper { private static DateTime? _delayPreloadTo = null; private static TimeSpan PreloadDelay = TimeSpan.FromSeconds(2); private static TimeSpan InitializationDelay = TimeSpan.FromSeconds(30); private static readonly string LogTitle = typeof (BuildManagerHelper).Name; private static int _preloadingInitiated; /// /// Preloading (compiling) all the controls. Speeds up first time editing in console. /// public static void InitializeControlPreLoading() { if (_preloadingInitiated == 0 && Interlocked.Increment(ref _preloadingInitiated) == 1) { Task.Factory.StartNew(LoadAllControls); } } private static bool IsRestarting => HostingEnvironment.ApplicationHost.ShutdownInitiated(); private static void LoadAllControls() { try { const int waitSlice = 500; for (int i = 0; i < InitializationDelay.TotalMilliseconds / waitSlice; i++) { if(IsRestarting) return; Thread.Sleep(waitSlice); } const string configFileFilePath = "~/App_Data/Composite/Composite.config"; var config = XDocument.Load(PathUtil.Resolve(configFileFilePath)); var controlPathes = from element in config.Descendants() let userControlVirtualPath = (string) element.Attribute("userControlVirtualPath") where userControlVirtualPath != null select userControlVirtualPath; var controlsToCompile = new List(); foreach (var controlPath in controlPathes) { if (!C1File.Exists(PathUtil.Resolve(controlPath))) { Log.LogWarning(LogTitle, $"Missing a control file '{controlPath}' referenced in '{configFileFilePath}'"); continue; } controlsToCompile.Add(controlPath); } Func isAshxAsmxPath = f => f == ".ashx" || f == ".asmx"; Func isAspNetPath = f => f == ".aspx" || isAshxAsmxPath(f); var aspnetPaths = DirectoryUtils.GetFilesRecursively(PathUtil.Resolve("~/Composite")).Where(f => isAshxAsmxPath(Path.GetExtension(f))) .Concat(DirectoryUtils.GetFilesRecursively(PathUtil.Resolve("~/Renderers")).Where(f => isAspNetPath(Path.GetExtension(f)))) .Select(PathUtil.GetWebsitePath) .ToList(); var compileGroups = new List>>() { new Tuple>("ASP.NET controls", controlsToCompile), new Tuple>("ASP.NET pages and handlers", aspnetPaths), }; foreach (var compileGroup in compileGroups) { if (HostingEnvironment.ApplicationHost.ShutdownInitiated()) return; Log.LogVerbose(LogTitle, "Preloading " + compileGroup.Item1); var stopWatch = new Stopwatch(); stopWatch.Start(); foreach (var virtualPath in compileGroup.Item2) { while (true) { if (IsRestarting) return; Thread.MemoryBarrier(); var waitUntil = _delayPreloadTo; var now = DateTime.Now; if (waitUntil == null || waitUntil <= now) { break; } Thread.Sleep(waitUntil.Value - now); } try { using (new DisableUrlMedataScope()) { string compilePath = (virtualPath.StartsWith("~") ? "" : "~") + virtualPath; BuildManager.GetCompiledType(compilePath); } } catch (ThreadAbortException) { // this exception is automatically rethrown after this catch } catch (Exception ex) { Log.LogWarning(LogTitle, ex); } } stopWatch.Stop(); Log.LogVerbose(LogTitle, $"Preloading {compileGroup.Item1} completed in {stopWatch.ElapsedMilliseconds} ms"); } } catch (ThreadAbortException) { } catch (Exception ex) { Log.LogWarning(LogTitle, ex); } } /// /// Gets a user control. Prevents an exception that appears in Visual Studio while debugging /// /// /// public static Type GetCompiledType(string virtualPath) { using (DisableUrlMetadataCachingScope()) { return BuildManager.GetCompiledType(virtualPath); } } /// /// Disabling the "url metadata caching" prevents in debugger /// /// public static void DisableUrlMetadataCaching(bool disableCaching) { if (!RuntimeInformation.IsDebugBuild) { return; } var systemWeb = typeof(System.Web.TraceMode).Assembly; Type cachedPathData = systemWeb.GetType("System.Web.CachedPathData", false); var field = cachedPathData?.GetField("s_doNotCacheUrlMetadata", BindingFlags.Static | BindingFlags.NonPublic); field?.SetValue(null, disableCaching); } /// /// Disabling the "url metadata caching" prevents in debugger /// public static IDisposable DisableUrlMetadataCachingScope() { _delayPreloadTo = DateTime.Now.Add(PreloadDelay); return new DisableUrlMedataScope(); } internal class DisableUrlMedataScope : IDisposable { public DisableUrlMedataScope() { DisableUrlMetadataCaching(true); } public void Dispose() { DisableUrlMetadataCaching(false); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// ~DisableUrlMedataScope() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } } ================================================ FILE: Composite/Core/WebClient/Captcha/Captcha.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Composite.Core.Collections.Generic; using Composite.Core.Extensions; namespace Composite.Core.WebClient.Captcha { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Captcha { private static readonly string DateTimeFormat = "yyyyMMddHHmmss"; private static readonly string CaptchaCharacters = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"; private static readonly string CaptchaServiceUrl = UrlUtils.PublicRootPath + "/Renderers/Captcha.ashx"; private static readonly int CaptchaLength = 4; private static readonly int CaptchaExpiration = 30; // In minutes private static int _counter = 0; private static readonly Random _random = new Random(); // munute offset -> set of used records private static readonly Hashtable> _alreadyUsedRecords = new Hashtable>(); /// public static string CreateEncryptedValue() { DateTime now = DateTime.Now; string value = now.ToString(DateTimeFormat); value += "|" + GenerateText(); return Encryption.Encrypt(value); } /// public static bool IsValid(string encryptedValue) { string value; DateTime now = DateTime.Now; DateTime timeStamp; return !string.IsNullOrEmpty(encryptedValue) && Decrypt(encryptedValue, out timeStamp, out value) && timeStamp.AddMinutes(CaptchaExpiration) > now && now >= timeStamp && !IsAlreadyUsed(encryptedValue); } /// public static bool IsValid(string value, string encryptedValue) { string correctValue; DateTime now = DateTime.Now; DateTime timeStamp; return Decrypt(encryptedValue, out timeStamp, out correctValue) && string.Compare(value, correctValue, true) == 0 && timeStamp.AddMinutes(CaptchaExpiration) > now && now >= timeStamp && !IsAlreadyUsed(encryptedValue); } /// public static void RegisterUsage(string encryptedValue) { string value; DateTime dateTime; Decrypt(encryptedValue, out dateTime, out value); int minute = GetMinute(dateTime); Hashset usedRecords = _alreadyUsedRecords[minute]; if (usedRecords == null) { lock(_alreadyUsedRecords) { usedRecords = _alreadyUsedRecords[minute]; if (usedRecords == null) { usedRecords = new Hashset(); _alreadyUsedRecords.Add(minute, usedRecords); } } } lock(usedRecords) { if(!usedRecords.Contains(encryptedValue)) { usedRecords.Add(encryptedValue); } } // Periodic clean-up _counter++; if(_counter % 1000 == 0) { lock(_alreadyUsedRecords) { int currentMinute = GetMinute(DateTime.Now); ICollection keys = _alreadyUsedRecords.GetKeys(); foreach(int key in keys) { if (key < currentMinute - CaptchaExpiration || key > currentMinute + 10) { _alreadyUsedRecords.Remove(key); } } } } } /// public static bool IsAlreadyUsed(string encryptedValue) { string value; DateTime dateTime; Decrypt(encryptedValue, out dateTime, out value); int offset = GetMinute(dateTime); var records = _alreadyUsedRecords[offset]; return records != null && records.Contains(encryptedValue); } private static int GetMinute(DateTime dateTime) { return dateTime.Hour * 60 + dateTime.Minute; } /// public static bool Decrypt(string encryptedValue, out DateTime timestamp, out string value) { timestamp = DateTime.MinValue; value = null; string decrypted = Encryption.Decrypt(encryptedValue); if (decrypted.IsNullOrEmpty()) { return false; } int separatorIndex = decrypted.IndexOf("|"); if (separatorIndex <= 0 || separatorIndex == decrypted.Length - 1) { return false; } string datePart = decrypted.Substring(0, separatorIndex); string captchaPart = decrypted.Substring(separatorIndex + 1); if (!DateTime.TryParseExact(datePart, DateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out timestamp)) { return false; } value = captchaPart; return true; } /// public static string GetImageUrl(string encryptedCaptchaValue) { var url = new UrlBuilder(CaptchaServiceUrl); url["value"] = encryptedCaptchaValue; return url.ToString(); } private static string GenerateText() { StringBuilder sb = new StringBuilder(CaptchaLength); for (int i = 0; i < CaptchaLength; i++) { sb.Append(CaptchaCharacters[_random.Next(0, CaptchaCharacters.Length)]); } return sb.ToString(); } } } ================================================ FILE: Composite/Core/WebClient/Captcha/CaptchaConfiguration.cs ================================================ using System; using System.IO; using System.Xml; using Composite.Core.Extensions; using Composite.Core.IO; namespace Composite.Core.WebClient.Captcha { internal static class CaptchaConfiguration { private static readonly string CaptchaConfigurationFilePath = @"App_Data\Composite\Configuration\Captcha.xml"; public static string Password { get; } static CaptchaConfiguration() { string configurationFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CaptchaConfigurationFilePath); string password = null; if (C1File.Exists(configurationFilePath)) { var doc = new XmlDocument(); try { using (var sr = new C1StreamReader(configurationFilePath)) { doc.Load(sr); } var passwordNode = doc.SelectSingleNode("captcha/password"); if (!string.IsNullOrEmpty(passwordNode?.InnerText)) { password = passwordNode.InnerText; } } catch (Exception) { // Do nothing } if (password != null) { Password = password; return; } // Deleting configuration file C1File.Delete(configurationFilePath); } password = Guid.NewGuid().ToString(); string configFile = @" {0} ".FormatWith(password); C1File.WriteAllText(configurationFilePath, configFile); Password = password; } } } ================================================ FILE: Composite/Core/WebClient/Captcha/Encryption.cs ================================================ using System; using System.Globalization; using System.IO; using System.Security.Cryptography; using System.Text; using Composite.Core.Configuration; using Composite.Core.IO; namespace Composite.Core.WebClient.Captcha { internal static class Encryption { private static readonly byte[] _encryptionKey; private static readonly byte[] RijndaelIV = { 1, 84, 22, 19, 154, 221, 4, 30, 56, 4, 114, 59, 90, 2, 5, 10 }; static Encryption() { string key = InstallationInformationFacade.InstallationId + CaptchaConfiguration.Password; byte[] keyBytes = Encoding.UTF8.GetBytes(key); using (var hashAlgorithm = MD5.Create()) { _encryptionKey = hashAlgorithm.ComputeHash(keyBytes); } } public static string Encrypt(string value) { Verify.ArgumentNotNullOrEmpty(value, nameof(value)); return ByteToHexString(RijndaelEncrypt(value)); } private static byte[] RijndaelEncrypt(string value) { // Create a RijndaelManaged object // with the specified key and IV. using (var rima = new RijndaelManaged()) { rima.Key = _encryptionKey; rima.IV = RijndaelIV; // Create a decrytor to perform the stream transform. ICryptoTransform encryptor = rima.CreateEncryptor(); // Create the streams used for encryption. using (var msEncrypt = new MemoryStream()) { using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) using (var swEncrypt = new C1StreamWriter(csEncrypt)) { //Write all data to the stream. swEncrypt.Write(value); } // Return the encrypted bytes from the memory stream. return msEncrypt.ToArray(); } } } public static string Decrypt(string encryptedValue) { Verify.ArgumentNotNullOrEmpty(encryptedValue, nameof(encryptedValue)); byte[] encodedSequence = HexStringToByteArray(encryptedValue); return RijndaelDecrypt(encodedSequence); } private static string RijndaelDecrypt(byte[] bytes) { using (var rima = new RijndaelManaged()) { rima.Key = _encryptionKey; rima.IV = RijndaelIV; // Create a decrytor to perform the stream transform. ICryptoTransform decryptor = rima.CreateDecryptor(); // Create the streams used for decryption. using (var msDecrypt = new MemoryStream(bytes)) using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) using (var srDecrypt = new C1StreamReader(csDecrypt)) { // Read the decrypted bytes from the decrypting stream // and place them in a string. return srDecrypt.ReadToEnd(); } } } private static string ByteToHexString(byte[] myArray) { return BitConverter.ToString(myArray); } private static byte[] HexStringToByteArray(string myArray) { string[] hexElements = myArray.Split('-'); byte[] recreatedByteArray = new byte[hexElements.Length]; for (int i = 0; i < hexElements.Length; i++) { recreatedByteArray[i] = byte.Parse(hexElements[i].Trim(), NumberStyles.HexNumber, CultureInfo.InvariantCulture); } return recreatedByteArray; } } } ================================================ FILE: Composite/Core/WebClient/Captcha/ImageCreator.cs ================================================ using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; namespace Composite.Core.WebClient.Captcha { /// /// Image creator /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ImageCreator { #region private members int Height; int Width; string ImageText = string.Empty; string _FontFamilyName = string.Empty; FontWarpFactor _FontWarp; NoiseLevel _Noise; LineNoiseLevel _LineNoise; Color _BackgroundColor = Color.White; Color _NoiseColor = Color.Black; Color _LineNoiseColor = Color.Black; Color _FontColor = Color.Black; Random Rand = new Random(); // a list of known good fonts in on both Windows XP and Windows Server 2003 string[] FontWhitelist = { "arial", "arial black", "comic sans ms", "courier new", "estrangelo edessa", "franklin gothic medium", "georgia", "lucida console", "lucida sans unicode", "mangal", "microsoft sans serif", "palatino linotype", "sylfaen", "tahoma", "times new roman", "trebuchet ms", "verdana"}; #endregion #region properties /// public string FontFamilyName { get { return _FontFamilyName; } set { _FontFamilyName = value; } } /// public FontWarpFactor FontWarp { get { return _FontWarp; } set { _FontWarp = value; } } /// public NoiseLevel Noise { get { return _Noise; } set { _Noise = value; } } /// public LineNoiseLevel LineNoise { get { return _LineNoise; } set { _LineNoise = value; } } /// public Color BackgroundColor { get { return _BackgroundColor; } set { _BackgroundColor = value; } } /// public Color NoiseColor { get { return _NoiseColor; } set { _NoiseColor = value; } } /// public Color LineNoiseColor { get { return _LineNoiseColor; } set { _LineNoiseColor = value; } } /// public Color FontColor { get { return _FontColor; } set { _FontColor = value; } } #endregion #region Constructors /// /// Class for generating CAPTCHA images /// /// Width of the image /// Height of the image public ImageCreator(int width, int height) { if (height < 10 || height > 400) { throw new ArgumentOutOfRangeException("height"); } if (width < 100 || height > 500) { throw new ArgumentOutOfRangeException("width"); } Height = height; Width = width; } #endregion #region Public methods /// public Bitmap CreateImage(string text) { ImageText = text; return GenerateImagePrivate(); } #endregion #region Private Members private Bitmap GenerateImagePrivate() { Rectangle rectangle; Bitmap bitmap = new Bitmap(Width, Height, PixelFormat.Format32bppArgb); Graphics graphics = Graphics.FromImage(bitmap); graphics.SmoothingMode = SmoothingMode.AntiAlias; // fill an empty white rectangle rectangle = new Rectangle(0, 0, Width, Height); using (var backgroundBrush = new SolidBrush(BackgroundColor)) { graphics.FillRectangle(backgroundBrush, rectangle); } int charOffset = 0; double charWidth = Width / ImageText.Length; Rectangle rectangleChar; using (var solidFontBrush = new SolidBrush(FontColor)) foreach (char c in ImageText) { // establish font and draw area rectangleChar = new Rectangle(Convert.ToInt32(charOffset * charWidth), 0, Convert.ToInt32(charWidth), Height); // warp the character GraphicsPath graphicsPath; // TODO: Creating a font is the heaviest operation, takes ~ 300ms every CAPTCHA request, some caching logic can be done here using (Font font = GetFont()) { graphicsPath = TextPath(c, font, rectangleChar); } WarpText(graphicsPath, rectangleChar); // draw the character graphics.FillPath(solidFontBrush, graphicsPath); charOffset += 1; } AddNoise(graphics, rectangle); AddLine(graphics, rectangle); // clean up unmanaged resources graphics.Dispose(); return bitmap; } /// /// Returns the CAPTCHA font in an appropriate size /// private Font GetFont() { Single FontSize; string FontName = FontFamilyName; if (String.IsNullOrEmpty(FontName)) { FontName = RandomFontFamily(); } switch (FontWarp) { case FontWarpFactor.None: FontSize = Convert.ToInt32(Height * 0.7); break; case FontWarpFactor.Low: FontSize = Convert.ToInt32(Height * 0.8); break; case FontWarpFactor.Medium: FontSize = Convert.ToInt32(Height * 0.85); break; case FontWarpFactor.High: FontSize = Convert.ToInt32(Height * 0.9); break; default: FontSize = Convert.ToInt32(Height * 0.95); break; } return new Font(FontName, FontSize, FontStyle.Bold); } /// /// Returns a random font family from the font whitelist /// private string RandomFontFamily() { return FontWhitelist[Rand.Next(0, FontWhitelist.GetLength(0) - 1)]; } /// /// Returns a GraphicsPath containing the specified string and font /// private static GraphicsPath TextPath(char s, Font font, Rectangle rectangle) { StringFormat stringFormat = new StringFormat(); stringFormat.Alignment = StringAlignment.Near; stringFormat.LineAlignment = StringAlignment.Near; GraphicsPath graphicsPath = new GraphicsPath(); graphicsPath.AddString(s.ToString(), font.FontFamily, (int)font.Style, font.Size, rectangle, stringFormat); stringFormat.Dispose(); return graphicsPath; } /// /// Warp the provided text GraphicsPath by a variable amount /// private void WarpText(GraphicsPath textPath, Rectangle rectangle) { float WarpDivisor; float RangeModifier; switch (FontWarp) { case FontWarpFactor.None: return; case FontWarpFactor.Low: WarpDivisor = 6f; RangeModifier = 1f; break; case FontWarpFactor.Medium: WarpDivisor = 5f; RangeModifier = 1.3f; break; case FontWarpFactor.High: WarpDivisor = 4.5f; RangeModifier = 1.4f; break; default: WarpDivisor = 4f; RangeModifier = 1.5f; break; } RectangleF rectangleF; rectangleF = new RectangleF(Convert.ToSingle(rectangle.Left), 0, Convert.ToSingle(rectangle.Width), rectangle.Height); int HeightRange = Convert.ToInt32(rectangle.Height / WarpDivisor); int WidthRange = Convert.ToInt32(rectangle.Width / WarpDivisor); int Left = rectangle.Left - Convert.ToInt32(WidthRange * RangeModifier); int Top = rectangle.Top - Convert.ToInt32(HeightRange * RangeModifier); int Width = rectangle.Left + rectangle.Width + Convert.ToInt32(WidthRange * RangeModifier); int Height = rectangle.Top + rectangle.Height + Convert.ToInt32(HeightRange * RangeModifier); if (Left < 0) { Left = 0; } if (Top < 0) { Top = 0; } if (Width > this.Width) { Width = this.Width; } if (Height > this.Height) { Height = this.Height; } PointF LeftTop = RandomPoint(Left, Left + WidthRange, Top, Top + HeightRange); PointF RightTop = RandomPoint(Width - WidthRange, Width, Top, Top + HeightRange); PointF LeftBottom = RandomPoint(Left, Left + WidthRange, Height - HeightRange, Height); PointF RightBottom = RandomPoint(Width - WidthRange, Width, Height - HeightRange, Height); PointF[] Points = { LeftTop, RightTop, LeftBottom, RightBottom }; Matrix matrix = new Matrix(); matrix.Translate(0, 0); textPath.Warp(Points, rectangleF, matrix, WarpMode.Perspective, 0); matrix.Dispose(); } /// /// Add a variable level of graphic noise to the image /// private void AddNoise(Graphics graphics1, Rectangle rect) { int density; int size; switch (Noise) { case NoiseLevel.None: return; case NoiseLevel.Low: density = 150; size = 40; break; case NoiseLevel.Medium: density = 100; size = 40; break; case NoiseLevel.High: density = 50; size = 39; break; default: density = 20; size = 38; break; } using (SolidBrush br = new SolidBrush(NoiseColor)) { int max = Convert.ToInt32(Math.Max(rect.Width, rect.Height)/size); for (int i = 0; i <= Convert.ToInt32((rect.Width*rect.Height)/density); i++) { graphics1.FillEllipse(br, Rand.Next(rect.Width), Rand.Next(rect.Height), Rand.Next(max), Rand.Next(max)); } } } /// /// Add variable level of curved lines to the image /// private void AddLine(Graphics graphics1, Rectangle rect) { int length; float width; int linecount; switch (LineNoise) { case LineNoiseLevel.None: return; case LineNoiseLevel.Low: length = 4; width = Convert.ToSingle(Height / 31.25); // 1.6 linecount = 1; break; case LineNoiseLevel.Medium: length = 5; width = Convert.ToSingle(Height / 27.7777); // 1.8 linecount = 1; break; case LineNoiseLevel.High: length = 3; width = Convert.ToSingle(Height / 25); // 2.0 linecount = 2; break; default: length = 3; width = Convert.ToSingle(Height / 22.7272); // 2.2 linecount = 3; break; } using(Pen p = new Pen(LineNoiseColor, width)) { PointF[] pf = new PointF[length]; for (int l = 1; l <= linecount; l++) { for (int i = 0; i < length; i++) { pf[i] = RandomPoint(rect); } graphics1.DrawCurve(p, pf, 1.75f); } } } /// /// Returns a random point within the specified rectangle /// private PointF RandomPoint(Rectangle rect) { return RandomPoint(rect.Left, rect.Width, rect.Top, rect.Bottom); } /// /// Returns a random point within the specified x and y ranges /// private PointF RandomPoint(int xmin, int xmax, int ymin, int ymax) { return new PointF(Rand.Next(xmin, xmax), Rand.Next(ymin, ymax)); } #endregion } /// /// Amount of random font warping to apply to rendered text /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum FontWarpFactor { /// None = 0, /// Low = 1, /// Medium = 2, /// High = 3, /// Extreme = 4 } /// /// Amount of background noise to add to rendered image /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum NoiseLevel { /// None = 0, /// Low = 1, /// Medium = 2, /// High = 3, /// Extreme = 4 } /// /// Amount of curved line noise to add to rendered image /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum LineNoiseLevel { /// None = 0, /// Low = 1, /// Medium = 2, /// High = 3, /// Extreme = 4 } } ================================================ FILE: Composite/Core/WebClient/ConsoleInfo.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace Composite.Core.WebClient { internal static class ConsoleInfo { public static string TryGetConsoleId() { if (HttpContext.Current != null && HttpContext.Current.Request != null && HttpContext.Current.Request.QueryString != null) { return HttpContext.Current.Request.QueryString["consoleId"]; } else { return null; } } } } ================================================ FILE: Composite/Core/WebClient/ControlCompilerService.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.Core.Configuration; using Composite.C1Console.Forms.Flows.Plugins.UiContainerFactory; using Composite.C1Console.Forms.Flows.Plugins.UiContainerFactory.Runtime; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.Plugins.UiControlFactory.Runtime; using Composite.Core.Instrumentation; using Composite.Core.Logging; using System.Collections; namespace Composite.Core.WebClient { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ControlCompilerService { /// public static IEnumerable GetControlPaths() { UiControlFactorySettings uiControlFactorySettings = ConfigurationServices.ConfigurationSource.GetSection(UiControlFactorySettings.SectionName) as UiControlFactorySettings; foreach (Composite.C1Console.Forms.Plugins.UiControlFactory.Runtime.ChannelConfigurationElement channelElement in uiControlFactorySettings.Channels) { foreach (NamespaceConfigurationElement namespaceElement in channelElement.Namespaces) { foreach (UiControlFactoryData uiControlFactoryData in namespaceElement.Factories) { PropertyInfo propertyInfo = uiControlFactoryData.GetType().GetProperty("UserControlVirtualPath"); if (propertyInfo != null) { string path = (string)propertyInfo.GetValue(uiControlFactoryData, null); yield return path; } } } } UiContainerFactorySettings uiContainerFactorySettings = ConfigurationServices.ConfigurationSource.GetSection(UiContainerFactorySettings.SectionName) as UiContainerFactorySettings; foreach (Composite.C1Console.Forms.Flows.Plugins.UiContainerFactory.Runtime.ChannelConfigurationElement channelElement in uiContainerFactorySettings.Channels) { foreach (UiContainerFactoryData uiControlFactoryData in channelElement.Factories) { PropertyInfo propertyInfo = uiControlFactoryData.GetType().GetProperty("UserControlVirtualPath"); if (propertyInfo != null) { string path = (string)propertyInfo.GetValue(uiControlFactoryData, null); yield return path; } } } } /// public static void CompileAll() { FieldInfo theBuildManagerFieldInfo = typeof(System.Web.Compilation.BuildManager).GetField("_theBuildManager", BindingFlags.NonPublic | BindingFlags.Static); FieldInfo cachesManagerFieldInfo = typeof(System.Web.Compilation.BuildManager).GetField("_caches", BindingFlags.NonPublic | BindingFlags.Instance); object currentBuilderManager = theBuildManagerFieldInfo.GetValue(null); IEnumerable caches = cachesManagerFieldInfo.GetValue(currentBuilderManager) as IEnumerable; Type standardDiskBuildResultCacheType = caches.OfType().Where(f => f.GetType().FullName == "System.Web.Compilation.StandardDiskBuildResultCache").Select(f => f.GetType()).Single(); FieldInfo maxRecompilationsFieldInfo = standardDiskBuildResultCacheType.BaseType.GetField("s_maxRecompilations", BindingFlags.NonPublic | BindingFlags.Static); object oldValue = maxRecompilationsFieldInfo.GetValue(null); maxRecompilationsFieldInfo.SetValue(null, 500); IEnumerable paths = GetControlPaths(); IPerformanceCounterToken performanceCounterToken = PerformanceCounterFacade.BeginAspNetControlCompile(); // ParallelFacade.ForEach(paths, path => // Call to parallelization facade causes a deadlock while starting-up!!! foreach (string path in paths) { int t1 = Environment.TickCount; Type type = BuildManagerHelper.GetCompiledType(path); int t2 = Environment.TickCount; LoggingService.LogVerbose("RGB(180, 180, 255)ControlCompilerService", string.Format("{0} compiled in {1} ms", path, t2 - t1)); } PerformanceCounterFacade.EndAspNetControlCompile(performanceCounterToken, paths.Count()); // maxRecompilationsFieldInfo.SetValue(null, oldValue); } } } ================================================ FILE: Composite/Core/WebClient/CookieHandler.cs ================================================ using System; using System.Linq; using System.Web; using Composite.Core.Configuration; namespace Composite.Core.WebClient { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class CookieHandler { /// /// Gets a cookie value specific for the current application instance (port and virtual path). /// The actual cookie name will be appended port and path info to ensure a unique cookie across multiple /// C1 sites running on the same host name. /// To have explicit control over cookie naming, use the ASP.NET Cookies class. /// /// The name used to set this cookie /// Value of the cookie, or null if the cookie was not found public static string Get(string cookieName) { var context = HttpContext.Current; Verify.That(context != null, "HttpContext is not available."); cookieName = GetApplicationSpecificCookieName(cookieName); if (context.Items["setCookies"]!=null) { var setCookies = context.Items["setCookies"] as HttpCookieCollection; var responseCookie = GetCookie(setCookies, cookieName); if (responseCookie != null) { return responseCookie.Value; } } var requestCookie = GetCookie(context.Request.Cookies, cookieName); return requestCookie?.Value; } /// /// Sets a cookie specific for the current application instance (port and virtual path). In order to read this cookie you should use the Get() methos on this class. /// To have explicit control over cookie naming, use the ASP.NET Cookies class. /// public static void Set(string cookieName, string value) { SetCookieInternal(cookieName, value); } /// /// Sets a cookie specific for the current application instance (port and virtual path). In order to read this cookie you should use the Get() methos on this class. /// To have explicit control over cookie naming, use the ASP.NET Cookies class. /// public static void Set(string cookieName, string value, DateTime expires) { var cookie = SetCookieInternal(cookieName, value); cookie.Expires = expires; } internal static HttpCookie SetCookieInternal(string cookieName, string value) { var context = HttpContext.Current; Verify.That(context != null, "HttpContext is not available."); cookieName = GetApplicationSpecificCookieName(cookieName); var cookie = context.Response.Cookies[cookieName]; cookie.Value = value; context.Items["setCookies"] = context.Response.Cookies; return cookie; } internal static string GetApplicationSpecificCookieName(string cookieName) { int siteUniqueHash = InstallationInformationFacade.InstallationId.GetHashCode(); return string.Format("{0}_{1}_{2}", cookieName, siteUniqueHash, UrlUtils.PublicRootPath.GetHashCode()); } private static HttpCookie GetCookie(HttpCookieCollection cookies, string key) { if(!cookies.AllKeys.Any(cookieKey => cookieKey == key)) { return null; } return cookies[key]; } } } ================================================ FILE: Composite/Core/WebClient/ErrorServices.cs ================================================ using System; using System.Text; using System.Web; using Composite.Core.Extensions; using Composite.Core.Logging; using Composite.C1Console.Events; namespace Composite.Core.WebClient { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ErrorServices { /// public static void DocumentAdministrativeError(Exception exception) { StringBuilder consoleMsg = new StringBuilder(); consoleMsg.AppendLine(exception.GetBaseException().ToString()); Log.LogCritical("Web Application Error, Exception", exception); var httpContext = HttpContext.Current; if (httpContext != null && httpContext.Request != null && httpContext.Request.Url != null) { consoleMsg.AppendLine(); consoleMsg.AppendLine("URL: " + HttpContext.Current.Request.Url); if (HttpContext.Current.Request.UrlReferrer != null) { consoleMsg.AppendLine("Referer: " + httpContext.Request.UrlReferrer.AbsolutePath); } } string consoleId = ConsoleInfo.TryGetConsoleId(); if (consoleId != null) { ConsoleMessageQueueFacade.Enqueue(new LogEntryMessageQueueItem { Level = LogLevel.Error, Message = consoleMsg.ToString(), Sender = typeof(ErrorServices) }, consoleId); } } /// public static void RedirectUserToErrorPage(string uiContainerName, Exception exception) { if (HttpContext.Current == null) return; string redirectUrl; switch (uiContainerName) { case "Document": redirectUrl = UrlUtils.ResolveAdminUrl("content/misc/errors/error.aspx") + "?" + ConvertExceptionToQueryString(exception); break; case null: case "Wizard": case "DataDialog": case "ConfirmDialog": redirectUrl = UrlUtils.ResolveAdminUrl("content/misc/errors/error_dialog.aspx") + "?" + ConvertExceptionToQueryString(exception); break; default: Log.LogWarning("ErrorServices", string.Format("Unhandled redirect! Unknown container: '{0}", uiContainerName)); throw new NotImplementedException(string.Format("Unknown container: '{0}'", uiContainerName)); } HttpContext.Current.Response.Redirect(redirectUrl, true); } private static string ConvertExceptionToQueryString(Exception exception) { var sbResult = new StringBuilder(); int exceptionIndex = 0; while (exception != null) { if(sbResult.Length > 0) { sbResult.Append("&"); } string encodedExceptionType = HttpUtility.UrlEncode(exception.GetType().Name); string encodedExceptionMessage = HttpUtility.UrlEncode(exception.Message); string encodedExceptionStackTrace = HttpUtility.UrlEncode(exception.StackTrace); if (encodedExceptionStackTrace.Length > 1000) encodedExceptionStackTrace = encodedExceptionStackTrace.Substring(0, 1000); string indexStr = exceptionIndex == 0 ? string.Empty : exceptionIndex.ToString(); sbResult.Append("type{0}=".FormatWith(indexStr) + encodedExceptionType); sbResult.Append("&msg{0}=".FormatWith(indexStr) + encodedExceptionMessage); sbResult.Append("&stack{0}=".FormatWith(indexStr) + encodedExceptionStackTrace); exceptionIndex++; exception = exception.InnerException; } return sbResult.ToString(); } } } ================================================ FILE: Composite/Core/WebClient/FlowMediators/ActionExecutionMediator.cs ================================================ using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Elements; using Composite.C1Console.Security; namespace Composite.Core.WebClient.FlowMediators { internal static class ActionExecutionMediator { public static void ExecuteElementAction(ElementHandle elementHandle, ActionHandle actionHandle, string consoleId) { var flowServicesContainer = new FlowControllerServicesContainer( new ManagementConsoleMessageService(consoleId), new ElementDataExchangeService(elementHandle.ProviderName), new ActionExecutionService(elementHandle.ProviderName, consoleId), new ElementInformationService(elementHandle) ); FlowToken flowToken = ActionExecutorFacade.Execute(elementHandle.EntityToken, actionHandle.ActionToken, flowServicesContainer); IFlowUiDefinition uiDefinition = FlowControllerFacade.GetCurrentUiDefinition(flowToken, flowServicesContainer); if (uiDefinition is FlowUiDefinitionBase flowUiDefinition) { string serializedEntityToken = EntityTokenSerializer.Serialize(elementHandle.EntityToken, true); ViewTransitionHelper.HandleNew(consoleId, elementHandle.ProviderName, serializedEntityToken, flowToken, flowUiDefinition); } } public static bool ExecuteElementDraggedAndDropped(ElementHandle draggedElementHandle, ElementHandle newParentdElementHandle, int dropIndex, string consoleId, bool isCopy) { var flowServicesContainer = new FlowControllerServicesContainer( new ManagementConsoleMessageService(consoleId), new ElementDataExchangeService(draggedElementHandle.ProviderName), new ActionExecutionService(draggedElementHandle.ProviderName, consoleId) ); return ElementFacade.ExecuteElementDraggedAndDropped(draggedElementHandle, newParentdElementHandle, dropIndex, isCopy, flowServicesContainer); } } } ================================================ FILE: Composite/Core/WebClient/FlowMediators/ActionExecutionService.cs ================================================ using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.C1Console.Tasks; namespace Composite.Core.WebClient.FlowMediators { internal sealed class ActionExecutionService : IActionExecutionService { public ActionExecutionService(string elementProviderName, string consoleId) { this.ElementProviderName = elementProviderName; this.ConsoleId = consoleId; } private string ElementProviderName { get; } private string ConsoleId { get; } public void Execute(EntityToken entityToken, ActionToken actionToken, TaskManagerEvent taskManagerEvent) { var flowServicesContainer = new FlowControllerServicesContainer( new ManagementConsoleMessageService(this.ConsoleId), new ElementDataExchangeService(this.ElementProviderName), this ); FlowToken flowToken = ActionExecutorFacade.Execute(entityToken, actionToken, flowServicesContainer, taskManagerEvent); IFlowUiDefinition uiDefinition = FlowControllerFacade.GetCurrentUiDefinition(flowToken, flowServicesContainer); if (uiDefinition is FlowUiDefinitionBase flowUiDefinition) { string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken, true); ViewTransitionHelper.HandleNew(this.ConsoleId, this.ElementProviderName, serializedEntityToken, flowToken, flowUiDefinition); } } } } ================================================ FILE: Composite/Core/WebClient/FlowMediators/FormFlowRendering/FormFlowRenderingService.cs ================================================ using System.Web.UI; namespace Composite.Core.WebClient.FlowMediators.FormFlowRendering { internal class FormFlowWebRenderingService : IFormFlowWebRenderingService { public void SetNewPageOutput(Control pageOutput) { this.NewPageOutput = pageOutput; } public void SetNewPageMimeType(string mimyType) { this.NewPageMimeType = mimyType; } public Control NewPageOutput { get; private set; } public string NewPageMimeType { get; private set; } } } ================================================ FILE: Composite/Core/WebClient/FlowMediators/FormFlowRendering/FormFlowUiDefinitionRenderer.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Xml; using System.Xml.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Flows; using Composite.C1Console.Forms.Flows.Foundation.PluginFacades; using Composite.C1Console.Forms.WebChannel; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; using Composite.Core.Xml; using Composite.Data.Validation.ClientValidationRules; namespace Composite.Core.WebClient.FlowMediators.FormFlowRendering { internal static class FormFlowUiDefinitionRenderer { public static IUiControl Render( string consoleId, string elementProviderName, FlowToken flowToken, FormFlowUiDefinition formFlowUiCommand, IFormChannelIdentifier channel, bool debugMode, FlowControllerServicesContainer servicesContainer) { FlowControllerServicesContainer formServicesContainer = new FlowControllerServicesContainer(servicesContainer); formServicesContainer.AddService(new FormFlowRenderingService()); formServicesContainer.AddService(new FormFlowWebRenderingService()); IFormMarkupProvider formMarkupProvider = formFlowUiCommand.MarkupProvider; IFormMarkupProvider customToolbarItemsMarkupProvider = formFlowUiCommand.CustomToolbarItemsMarkupProvider; Dictionary innerFormBindings = formFlowUiCommand.BindingsProvider.GetBindings(); Dictionary eventHandlers = formFlowUiCommand.EventHandlers; Dictionary> bindingsValidationRules = formFlowUiCommand.BindingsValidationRules; FormTreeCompiler formCompiler = new FormTreeCompiler(); IUiContainer renderingContainer = GetRenderingContainer(channel, formFlowUiCommand.UiContainerType); // Setting state related objects so the delegate below can access them "fresh" CurrentFormTreeCompiler = formCompiler; CurrentInnerFormBindings = innerFormBindings; CurrentControlContainer = (IWebUiContainer)renderingContainer; Dictionary containerEventHandlerStubs = new Dictionary(); foreach (IFormEventIdentifier eventIdentifier in eventHandlers.Keys) { IFormEventIdentifier localScopeEventIdentifier = eventIdentifier; // See: Local variable usage with anonymous methods within loop control structures EventHandler handlerStub = delegate(object sender, EventArgs e) { try { BaseEventHandler(consoleId, elementProviderName, flowToken, formFlowUiCommand, servicesContainer, eventHandlers, localScopeEventIdentifier, formServicesContainer); } catch (Exception ex) { formServicesContainer.GetService().ShowLogEntry(typeof(FormFlowUiDefinitionRenderer), ex); throw; } }; containerEventHandlerStubs.Add(eventIdentifier.BindingName, handlerStub); if (innerFormBindings.ContainsKey(eventIdentifier.BindingName)) { innerFormBindings.Remove(eventIdentifier.BindingName); } innerFormBindings.Add(eventIdentifier.BindingName, handlerStub); } XDocument document; using (XmlReader formMarkupReader = formMarkupProvider.GetReader()) { document = XDocument.Load(formMarkupReader); formMarkupReader.Close(); } formCompiler.Compile(document, channel, innerFormBindings, debugMode, "", bindingsValidationRules); IUiControl innerForm = formCompiler.UiControl; IUiControl customToolbarItems = null; if (customToolbarItemsMarkupProvider != null) { var toolbarCompiler = new FormTreeCompiler(); CurrentCustomToolbarFormTreeCompiler = toolbarCompiler; using (XmlReader formMarkupReader = customToolbarItemsMarkupProvider.GetReader()) { toolbarCompiler.Compile(formMarkupReader, channel, innerFormBindings, debugMode, bindingsValidationRules); } customToolbarItems = toolbarCompiler.UiControl; } CurrentControlTreeRoot = (IWebUiControl)innerForm; string label = formCompiler.Label; if(label.IsNullOrEmpty()) { label = formFlowUiCommand.ContainerLabel ?? ""; } string labelField = GetFormLabelField(document); ResourceHandle containerIcon = formCompiler.Icon; return renderingContainer.Render(formCompiler.UiControl, customToolbarItems, channel, containerEventHandlerStubs, label, labelField, formCompiler.Tooltip, containerIcon); } private static void BaseEventHandler(string consoleId, string elementProviderName, FlowToken flowToken, FormFlowUiDefinition formFlowUiCommand, FlowControllerServicesContainer servicesContainer, Dictionary eventHandlers, IFormEventIdentifier localScopeEventIdentifier, FlowControllerServicesContainer formServicesContainer) { FormTreeCompiler activeFormTreeCompiler = CurrentFormTreeCompiler; Dictionary activeInnerFormBindings = CurrentInnerFormBindings; FormFlowEventHandler handler = eventHandlers[localScopeEventIdentifier]; Dictionary bindingErrors = activeFormTreeCompiler.SaveAndValidateControlProperties(); FormTreeCompiler activeCustomToolbarFormTreeCompiler = CurrentCustomToolbarFormTreeCompiler; if (activeCustomToolbarFormTreeCompiler != null) { var toolbarBindingErrors = activeCustomToolbarFormTreeCompiler.SaveAndValidateControlProperties(); foreach (var pair in toolbarBindingErrors) { bindingErrors.Add(pair.Key, pair.Value); } } formServicesContainer.AddService(new BindingValidationService(bindingErrors)); handler.Invoke(flowToken, activeInnerFormBindings, formServicesContainer); if (formServicesContainer.GetService().CloseCurrentViewRequested) { ViewTransitionHelper.HandleCloseCurrentView(formFlowUiCommand.UiContainerType); return; } var formFlowService = formServicesContainer.GetService(); bool replacePageOutput = (formServicesContainer.GetService().NewPageOutput != null); bool rerenderView = formFlowService.RerenderViewRequested; if (formFlowService.BindingPathedMessages != null) { ShowFieldMessages(CurrentControlTreeRoot, formFlowService.BindingPathedMessages, CurrentControlContainer, servicesContainer); } List boolCounterList = new List {replacePageOutput, rerenderView}; if (boolCounterList.Count(f => f) > 1) { StringBuilder sb = new StringBuilder("Flow returned conflicting directives for post handling:\n"); if (replacePageOutput) sb.AppendLine(" - Replace page output with new web control."); if (rerenderView) sb.AppendLine(" - Rerender view."); throw new InvalidOperationException(sb.ToString()); } if (rerenderView) { Log.LogVerbose("FormFlowRendering", "Re-render requested"); IFlowUiDefinition newFlowUiDefinition = FlowControllerFacade.GetCurrentUiDefinition(flowToken, servicesContainer); if (!(newFlowUiDefinition is FlowUiDefinitionBase)) throw new NotImplementedException("Unable to handle transitions to ui definition of type " + newFlowUiDefinition.GetType()); ViewTransitionHelper.HandleRerender(consoleId, elementProviderName, flowToken, formFlowUiCommand, (FlowUiDefinitionBase) newFlowUiDefinition, servicesContainer); } if (replacePageOutput) { Log.LogVerbose("FormFlowRendering", "Replace pageoutput requested"); IFormFlowWebRenderingService webRenderingService = formServicesContainer.GetService(); Control newPageOutput = webRenderingService.NewPageOutput; foreach (Control control in GetNestedControls(newPageOutput).Where(f => f is ScriptManager).ToList()) { control.Parent.Controls.Remove(control); } Page currentPage = HttpContext.Current.Handler as Page; HtmlHead newHeadControl = GetNestedControls(newPageOutput).FirstOrDefault(f => f is HtmlHead) as HtmlHead; HtmlHead oldHeadControl = currentPage.Header; ControlCollection headContainer = null; bool headersHasToBeSwitched = newHeadControl != null && oldHeadControl != null; if (headersHasToBeSwitched) { headContainer = newHeadControl.Parent.Controls; headContainer.Remove(newHeadControl); } currentPage.Controls.Clear(); if (string.IsNullOrEmpty(webRenderingService.NewPageMimeType)) { currentPage.Response.ContentType = "text/html"; } else { currentPage.Response.ContentType = webRenderingService.NewPageMimeType; } currentPage.Controls.Add(newPageOutput); if (headersHasToBeSwitched) { oldHeadControl.Controls.Clear(); oldHeadControl.InnerHtml = ""; oldHeadControl.InnerText = ""; if (newHeadControl.ID != null) { oldHeadControl.ID = newHeadControl.ID; } oldHeadControl.Title = newHeadControl.Title; headContainer.AddAt(0, oldHeadControl); foreach (Control c in newHeadControl.Controls.Cast().ToList()) { oldHeadControl.Controls.Add(c); } } } } private static string GetFormLabelField(XDocument formMarkup) { var labelElement = formMarkup.Descendants(Namespaces.BindingForms10 + "layout.label").FirstOrDefault() ?? formMarkup.Descendants().FirstOrDefault(e => e.Name.LocalName == "TabPanels.Label"); var readBinding = labelElement?.Element(Namespaces.BindingForms10 + "read"); if(readBinding == null) return null; return (string)readBinding.Attribute("source"); } private static IUiContainer GetRenderingContainer(IFormChannelIdentifier channel, IFlowUiContainerType containerIdentifier) { return UiContainerFactoryFactoryPluginFacade.CreateContainer(channel, containerIdentifier); } private static readonly string _formTreeCompilerLookupKey = typeof(FormFlowUiDefinitionRenderer).FullName + "FormTreeCompiler"; private static readonly string _customToolbarFormTreeCompilerLookupKey = typeof(FormFlowUiDefinitionRenderer).FullName + "CustomToolbarFormTreeCompiler"; private static readonly string _innerFormBindingsLookupKey = typeof(FormFlowUiDefinitionRenderer).FullName + "InnerFormBindings"; private static readonly string _currentControlTreeRoot = typeof(FormFlowUiDefinitionRenderer).FullName + "ControlTreeRoot"; private static readonly string _currentControlContainer = typeof(FormFlowUiDefinitionRenderer).FullName + "ControlContainer"; internal static FormTreeCompiler CurrentFormTreeCompiler { get { return HttpContext.Current.Items[_formTreeCompilerLookupKey] as FormTreeCompiler; } set { HttpContext.Current.Items[_formTreeCompilerLookupKey] = value; } } private static FormTreeCompiler CurrentCustomToolbarFormTreeCompiler { get { return HttpContext.Current.Items[_customToolbarFormTreeCompilerLookupKey] as FormTreeCompiler; } set { HttpContext.Current.Items[_customToolbarFormTreeCompilerLookupKey] = value; } } private static Dictionary CurrentInnerFormBindings { get { return HttpContext.Current.Items[_innerFormBindingsLookupKey] as Dictionary; } set { HttpContext.Current.Items[_innerFormBindingsLookupKey] = value; } } private static IWebUiControl CurrentControlTreeRoot { get { return HttpContext.Current.Items[_currentControlTreeRoot] as IWebUiControl; } set { HttpContext.Current.Items[_currentControlTreeRoot] = value; } } private static IWebUiContainer CurrentControlContainer { get { return HttpContext.Current.Items[_currentControlContainer] as IWebUiContainer; } set { HttpContext.Current.Items[_currentControlContainer] = value; } } private static void ShowFieldMessages(IWebUiControl webUiControlTreeRoot, Dictionary bindingPathedMessages, IWebUiContainer container, FlowControllerServicesContainer servicesContainer) { var pathToClientIDMappings = new Dictionary(); ResolveBindingPathToClientIDMappings(webUiControlTreeRoot, pathToClientIDMappings); var cliendIDPathedMessages = new Dictionary(); var homelessMessages = new Dictionary(); foreach (var msgElement in bindingPathedMessages) { string clientId = null; if (pathToClientIDMappings.TryGetValue(msgElement.Key, out clientId)) { cliendIDPathedMessages.Add(clientId, msgElement.Value); } else { homelessMessages.Add(msgElement.Key, msgElement.Value); } } container.ShowFieldMessages(cliendIDPathedMessages); if (homelessMessages.Count > 0) { StringBuilder sb = new StringBuilder(); foreach (var msgElement in homelessMessages) { sb.AppendFormat("{0}: {1}\n", msgElement.Key, msgElement.Value); } var consoleMsgService = servicesContainer.GetService(); consoleMsgService.ShowMessage(DialogType.Warning, "Field messages", sb.ToString()); } } internal static void ResolveBindingPathToClientIDMappings(IWebUiControl webUiControl, Dictionary resolvedMappings) { var container = webUiControl as ContainerUiControlBase; if (container != null) { foreach (IUiControl child in container.UiControls) { ResolveBindingPathToClientIDMappings((IWebUiControl)child, resolvedMappings); } } if (webUiControl.SourceBindingPaths != null && webUiControl.ClientName != null && webUiControl.SourceBindingPaths.Count > 0) { foreach (string sourceBindingPath in webUiControl.SourceBindingPaths) { resolvedMappings.Add(sourceBindingPath, webUiControl.ClientName); } } } private static IEnumerable GetNestedControls(Control control) { foreach (Control child in control.Controls) { yield return child; foreach (Control nested in GetNestedControls(child)) { yield return nested; } } } } } ================================================ FILE: Composite/Core/WebClient/FlowMediators/FormFlowRendering/IFormFlowWebRenderingService.cs ================================================ using Composite.C1Console.Actions; using System.Web.UI; namespace Composite.Core.WebClient.FlowMediators.FormFlowRendering { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IFormFlowWebRenderingService : IFlowControllerService { /// void SetNewPageOutput(Control pageOutput); /// void SetNewPageMimeType(string mimyType); /// Control NewPageOutput { get; } /// string NewPageMimeType { get; } } } ================================================ FILE: Composite/Core/WebClient/FlowMediators/TreeServicesFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Events; using Composite.C1Console.Elements; using Composite.Core.Logging; using Composite.Core.ResourceSystem.Icons; using Composite.C1Console.Security; using Composite.C1Console.Users; using Composite.Core.WebClient.Services.TreeServiceObjects; using Composite.Core.WebClient.Services.TreeServiceObjects.ExtensionMethods; namespace Composite.Core.WebClient.FlowMediators { internal class NullRootEntityToken : EntityToken { public override string Type { get { return "null"; } } public override string Source { get { return "null"; } } public override string Id { get { return "null"; } } public override string Serialize() { return "NullRootEntiryToken"; } } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class TreeServicesFacade { /// public static ClientElement GetRoot() { List roots = ElementFacade.GetRoots(null).ToList(); if (roots.Count == 0) { // user with out any access logging in - return "empty root" roots = ElementFacade.GetRootsWithNoSecurity().ToList(); if (roots.Count == 0) throw new InvalidOperationException("No roots specified"); if (roots.Count > 1) throw new InvalidOperationException("More than one root specified"); var emptyElement = new Element(new ElementHandle("nullRoot", new NullRootEntityToken())); emptyElement.VisualData = new ElementVisualizedData { HasChildren = false, Label = "nullroot", Icon = CommonElementIcons.Folder }; roots.Clear(); roots.Add(emptyElement); } else if (roots.Count > 1) { throw new InvalidOperationException("More than one root specified"); } return roots[0].GetClientElement(); } /// public static List GetRoots(string providerHandle, string serializedSearchToken) { SearchToken searchToken = null; if (!string.IsNullOrEmpty(serializedSearchToken)) { searchToken = SearchToken.Deserialize(serializedSearchToken); } List roots; if (UserSettings.ForeignLocaleCultureInfo == null || UserSettings.ForeignLocaleCultureInfo.Equals(UserSettings.ActiveLocaleCultureInfo)) { roots = ElementFacade.GetRoots(new ElementProviderHandle(providerHandle), searchToken).ToList(); } else { roots = ElementFacade.GetForeignRoots(new ElementProviderHandle(providerHandle), searchToken).ToList(); } return roots.ToClientElementList(); } /// public static List GetLocaleAwarePerspectiveElements() { IEnumerable elements = ElementFacade.GetPerspectiveElements(true); List clientElementKeys = new List(); foreach (Element element in elements) { if (element.IsLocaleAware) { clientElementKeys.Add(element.GetClientElement().ElementKey); } } return clientElementKeys; } /// public static List GetPerspectiveElementsWithNoSecurity() { return ElementFacade.GetPerspectiveElementsWithNoSecurity().ToList().ToClientElementList(); } /// public static List GetChildren(string providerName, string serializedEntityToken, string piggybag, string serializedSearchToken) { //LoggingService.LogVerbose("RGB(255, 0, 255)TreeServiceFacade", "----- Start -----------------------------------------------"); int t1 = Environment.TickCount; EntityToken entityToken = EntityTokenSerializer.Deserialize(serializedEntityToken); ElementHandle elementHandle = new ElementHandle(providerName, entityToken, piggybag); //int t2 = Environment.TickCount; SearchToken searchToken = null; if (!string.IsNullOrEmpty(serializedSearchToken)) { searchToken = SearchToken.Deserialize(serializedSearchToken); } List childElements; if (UserSettings.ForeignLocaleCultureInfo == null || UserSettings.ForeignLocaleCultureInfo.Equals(UserSettings.ActiveLocaleCultureInfo)) { childElements = ElementFacade.GetChildren(elementHandle, searchToken).ToList(); } else { childElements = ElementFacade.GetForeignChildren(elementHandle, searchToken).ToList(); } //int t3 = Environment.TickCount; List resultList = childElements.ToClientElementList(); int t4 = Environment.TickCount; //LoggingService.LogVerbose("RGB(255, 0, 255)TreeServiceFacade", string.Format("ElementHandle: {0} ms", t2 - t1)); //LoggingService.LogVerbose("RGB(255, 0, 255)TreeServiceFacade", string.Format("GetChildren: {0} ms", t3 - t2)); //LoggingService.LogVerbose("RGB(255, 0, 255)TreeServiceFacade", string.Format("ToClientElementList: {0} ms", t4 - t3)); //LoggingService.LogVerbose("RGB(255, 0, 255)TreeServiceFacade", string.Format("Total: {0} ms", t4 - t1)); //LoggingService.LogVerbose("RGB(255, 0, 255)TreeServiceFacade", "----- End -------------------------------------------------"); //LoggingService.LogVerbose("TreeServiceFacade", string.Format("GetChildren: {0} ms", t4 - t1)); return resultList; } /// public static List GetMultipleChildren(List nodesToBeRefreshed) { int t1 = Environment.TickCount; var result = new List(); foreach (RefreshChildrenParams node in nodesToBeRefreshed) { EntityToken entityToken; try { entityToken = EntityTokenSerializer.Deserialize(node.EntityToken); } catch (EntityTokenSerializerException) { continue; } var elementHandle = new ElementHandle(node.ProviderName, entityToken, node.Piggybag); SearchToken searchToken = null; if (!string.IsNullOrEmpty(node.SearchToken)) { searchToken = SearchToken.Deserialize(node.SearchToken); } List childElements; if (UserSettings.ForeignLocaleCultureInfo == null || UserSettings.ForeignLocaleCultureInfo.Equals(UserSettings.ActiveLocaleCultureInfo)) { childElements = ElementFacade.GetChildren(elementHandle, searchToken).ToList(); } else { childElements = ElementFacade.GetForeignChildren(elementHandle, searchToken).ToList(); } result.Add(new RefreshChildrenInfo { ElementKey = GetElementKey(node.ProviderName, node.EntityToken, node.Piggybag), ClientElements = childElements.ToClientElementList() }); } int t2 = Environment.TickCount; //LoggingService.LogVerbose("TreeServiceFacade", string.Format("GetMultipleChildren: {0} ms", t2 - t1)); return result; } /// public static List GetLabeledProperties(string providerName, string serializedEntityToken, string piggybag) { var elementEntityToken = EntityTokenSerializer.Deserialize(serializedEntityToken); var elementHandle = new ElementHandle(providerName, elementEntityToken, piggybag); bool showForeign = UserSettings.ForeignLocaleCultureInfo != null && UserSettings.ForeignLocaleCultureInfo.Equals(UserSettings.ActiveLocaleCultureInfo); var labeledProperties = showForeign ? ElementFacade.GetForeignLabeledProperties(elementHandle) : ElementFacade.GetLabeledProperties(elementHandle); return (from property in labeledProperties select new ClientLabeledProperty(property)).ToList(); } /// public static void ExecuteElementAction(string providerName, string serializedEntityToken, string piggybag, string serializedActionToken, string consoleId) { using (DebugLoggingScope.MethodInfoScope) { EntityToken entityToken = EntityTokenSerializer.Deserialize(serializedEntityToken); if (!entityToken.IsValid()) { ShowInvalidEntityMessage(consoleId); return; } var elementHandle = new ElementHandle(providerName, entityToken, piggybag); ActionToken actionToken = ActionTokenSerializer.Deserialize(serializedActionToken, true); ActionHandle actionHandle = new ActionHandle(actionToken); ActionExecutionMediator.ExecuteElementAction(elementHandle, actionHandle, consoleId); } } /// public static bool ExecuteElementDraggedAndDropped(string draggedElementProviderName, string draggedElementSerializedEntityToken, string draggedElementPiggybag, string newParentElementProviderName, string newParentElementSerializedEntityToken, string newParentElementPiggybag, int dropIndex, string consoleId, bool isCopy) { if (draggedElementProviderName != newParentElementProviderName) { throw new InvalidOperationException("Only drag'n'drop internal in element providers are allowed"); } EntityToken draggedElementEntityToken = EntityTokenSerializer.Deserialize(draggedElementSerializedEntityToken); ElementHandle draggedElementHandle = new ElementHandle(draggedElementProviderName, draggedElementEntityToken, draggedElementPiggybag); EntityToken newParentElementEntityToken = EntityTokenSerializer.Deserialize(newParentElementSerializedEntityToken); ElementHandle newParentdElementHandle = new ElementHandle(newParentElementProviderName, newParentElementEntityToken, newParentElementPiggybag); return ActionExecutionMediator.ExecuteElementDraggedAndDropped(draggedElementHandle, newParentdElementHandle, dropIndex, consoleId, isCopy); } /// public static List FindEntityToken(string serializedAncestorEntityToken, string serializedEntityToken, List openedNodes) { Verify.ArgumentNotNullOrEmpty(serializedAncestorEntityToken, "serializedAncestorEntityToken"); Verify.ArgumentNotNullOrEmpty(serializedEntityToken, "serializedEntityToken"); EntityToken ancestorEntityToken = EntityTokenSerializer.Deserialize(serializedAncestorEntityToken); EntityToken entityToken = EntityTokenSerializer.Deserialize(serializedEntityToken); return FindEntityToken(ancestorEntityToken, entityToken, openedNodes); } internal static List FindEntityToken(EntityToken ancestorEntityToken, EntityToken entityToken, List nodesToRefresh) { var openedNodes = nodesToRefresh.Select(node => new { EntityToken = EntityTokenSerializer.Deserialize(node.EntityToken), ElementData = node }).ToList(); foreach (List ancestorChain in GetAncestorChains(ancestorEntityToken, entityToken)) { if (ancestorChain == null || ancestorChain.Count == 0) { continue; } List ancestorEntityTokens = ancestorChain.ToList(); int lastAlreadyOpenedNodeIndex = 0; while (lastAlreadyOpenedNodeIndex + 1 < ancestorChain.Count && openedNodes.Any(node => node.EntityToken.Equals(ancestorEntityTokens[lastAlreadyOpenedNodeIndex + 1]))) { lastAlreadyOpenedNodeIndex++; } var openNode = openedNodes.FirstOrDefault(node => node.EntityToken.Equals(ancestorEntityTokens[lastAlreadyOpenedNodeIndex])); if (openNode == null) { return null; } // Expanding all the nodes under the root var nodesToBeExpanded = new List(); nodesToBeExpanded.AddRange(ancestorEntityTokens.Skip(lastAlreadyOpenedNodeIndex)); nodesToBeExpanded.RemoveAt(nodesToBeExpanded.Count - 1); // Last node is a target one, so doesn't have to be expanded nodesToBeExpanded.AddRange(openedNodes.Select(node => node.EntityToken)); var result = new List(); // Expanding all the nodes, and checking if all of the nodes in the ancestor chain is marked // as seen in TreeLockBehaviour bool success = ExpandNodesRec(openNode.ElementData.EntityToken, openNode.ElementData.ProviderName, openNode.ElementData.Piggybag, nodesToBeExpanded, result, ancestorEntityTokens); if (success) { return result; } } return null; } /// /// Expands nodes recurcively. /// /// /// /// /// /// /// /// Returns false, if there's a key node, that has [element.TreeLockBehavior == None] private static bool ExpandNodesRec(string entityToken, string elementProviderName, string piggybag, List entityTokensToBeExpanded, List resultList, List keyNodes) { if (resultList.Count > 1000) // Preventing an infinite loop { return true; } List children = GetChildren(elementProviderName, entityToken, piggybag, null); var refreshChildrenInfo = new RefreshChildrenInfo { ElementKey = GetElementKey(elementProviderName, entityToken, piggybag), ClientElements = children }; resultList.Add(refreshChildrenInfo); foreach (ClientElement child in children) { var childEntityToken = EntityTokenSerializer.Deserialize(child.EntityToken); if (!child.TreeLockEnabled && keyNodes.Contains(childEntityToken)) { return false; } if (entityTokensToBeExpanded.Contains(childEntityToken)) { if (ExpandNodesRec(child.EntityToken, child.ProviderName, child.Piggybag, entityTokensToBeExpanded, resultList, keyNodes)) { return true; } } else { if (keyNodes.Contains(childEntityToken)) { return true; } } } return false; } // TODO: Move logic to another place private static string GetElementKey(string providerName, string entityToken, string piggybag) { return providerName + entityToken + piggybag; } private static IEnumerable> GetAncestorChains(EntityToken ancestorEnitityToken, EntityToken entityToken) { foreach (List ancestorChain in GetAncestorChains(entityToken, 20)) { if (ancestorChain.Count > 1) { int index = ancestorChain.IndexOf(ancestorEnitityToken); if(index < 0) continue; yield return (index == 0) ? ancestorChain : ancestorChain.GetRange(index, ancestorChain.Count - index); } } } private static IEnumerable> GetAncestorChains(EntityToken descendant, int deep, List visitedParents = null) { if (deep == 0) { yield return new List(); yield break; } if (visitedParents == null) { visitedParents = new List(); } visitedParents.Add(descendant); List parents = ParentsFacade.GetAllParents(descendant); if (parents.Count == 0) { var newChain = new List {descendant}; yield return newChain; yield break; } // NOTE: A workaround which gives "AllFunctionElementProvider" search results less priority that other function element providers if (parents.Count == 2 && parents[0].Id != null && parents[0].Id.StartsWith("ROOT:AllFunctionsElementProvider")) { parents.Reverse(); } foreach (var parent in parents) { foreach (List chain in GetAncestorChains(parent, deep - 1, visitedParents)) { chain.Add(descendant); yield return chain; } } } private static void ShowInvalidEntityMessage(string consoleId) { // TODO: Add tree refreshing, localize message var msgBoxEntry = new MessageBoxMessageQueueItem { DialogType = DialogType.Error, Title = "Data item not found", Message = "This item seems to have been deleted.\n\nPlease update the tree by using the context menu \"Refresh\" command." }; ConsoleMessageQueueFacade.Enqueue(msgBoxEntry, consoleId); } } } ================================================ FILE: Composite/Core/WebClient/FlowMediators/ViewTransitionHelper.cs ================================================ using System; using Composite.C1Console.Actions; using Composite.C1Console.Events; using System.Web; using Composite.C1Console.Elements; namespace Composite.Core.WebClient.FlowMediators { internal static class ViewTransitionHelper { internal static string MakeViewId(string serializedFlowHandle) { return "view" + serializedFlowHandle.GetHashCode(); } internal static void HandleRerender(string consoleId, string elementProviderName, FlowToken flowToken, FlowUiDefinitionBase oldUiDefinition, FlowUiDefinitionBase newUiDefinition, FlowControllerServicesContainer servicesContainer) { if (newUiDefinition.UiContainerType.ActionResultResponseType != oldUiDefinition.UiContainerType.ActionResultResponseType) { var messageService = servicesContainer.GetService(); messageService.CloseCurrentView(); HandleNew(consoleId, elementProviderName, string.Empty, flowToken, newUiDefinition); } else { // Force update in same container HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.PathAndQuery, false); } } internal static void HandleNew(string consoleId, string elementProviderName, string serializedEntityToken, FlowToken flowToken, FlowUiDefinitionBase uiDefinition) { ActionResultResponseType actionViewType = uiDefinition.UiContainerType.ActionResultResponseType; if (actionViewType != ActionResultResponseType.None) { FlowHandle flowHandle = new FlowHandle(flowToken); string serializedFlowHandle = flowHandle.Serialize(); string viewId = MakeViewId(serializedFlowHandle); ViewType viewType; switch (actionViewType) { case ActionResultResponseType.OpenDocument: viewType = ViewType.Main; break; case ActionResultResponseType.OpenModalDialog: viewType = ViewType.ModalDialog; break; default: throw new Exception("unknown action response type"); } string url = string.Format("{0}?consoleId={1}&flowHandle={2}&elementProvider={3}", UrlUtils.ResolveAdminUrl("content/flow/FlowUi.aspx"), consoleId, HttpUtility.UrlEncode(serializedFlowHandle), HttpUtility.UrlEncode(elementProviderName)); OpenViewMessageQueueItem openView = new OpenViewMessageQueueItem { ViewType = viewType, EntityToken = serializedEntityToken, FlowHandle = flowHandle.Serialize(), Url = url, ViewId = viewId }; if (uiDefinition is VisualFlowUiDefinitionBase) { VisualFlowUiDefinitionBase visualUiDefinition = (VisualFlowUiDefinitionBase)uiDefinition; if (string.IsNullOrEmpty(visualUiDefinition.ContainerLabel) == false) openView.Label = visualUiDefinition.ContainerLabel; } ConsoleMessageQueueFacade.Enqueue(openView, consoleId); } } internal static void HandleCloseCurrentView(IFlowUiContainerType uiContainerType) { string redirectUrl; switch (uiContainerType.ContainerName) { case "Document": redirectUrl = UrlUtils.ResolveAdminUrl("content/flow/FlowUiCompleted.aspx"); break; case "Wizard": case "DataDialog": case "ConfirmDialog": redirectUrl = UrlUtils.ResolveAdminUrl("content/flow/FlowUiCompletedDialog.aspx"); break; default: throw new NotImplementedException("Unknown container " + uiContainerType.ContainerName); } HttpContext.Current.Response.Redirect(redirectUrl, false); } } } ================================================ FILE: Composite/Core/WebClient/FlowMediators/WebFlowUiMediator.cs ================================================ using System; using System.Web.UI; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Elements; using Composite.C1Console.Forms; using Composite.C1Console.Forms.Flows; using Composite.C1Console.Forms.WebChannel; using Composite.Core.WebClient.FlowMediators.FormFlowRendering; using System.Linq; using System.Web.UI.HtmlControls; namespace Composite.Core.WebClient.FlowMediators { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class WebFlowUiMediator { /// public static Control GetFlowUi(FlowHandle flowHandle, string elementProviderName, string consoleId, out string uiContainerName) { uiContainerName = null; try { Control webControl = null; string viewId = ViewTransitionHelper.MakeViewId(flowHandle.Serialize()); var flowServicesContainer = new FlowControllerServicesContainer( new ActionExecutionService(elementProviderName, consoleId), new ManagementConsoleMessageService(consoleId, viewId), new ElementDataExchangeService(elementProviderName) ); FlowToken flowToken = flowHandle.FlowToken; IFlowUiDefinition flowUiDefinition = FlowControllerFacade.GetCurrentUiDefinition(flowToken, flowServicesContainer); if (flowUiDefinition is FormFlowUiDefinition formFlowUiDefinition) { uiContainerName = formFlowUiDefinition.UiContainerType.ContainerName; IUiControl uiForm = FormFlowUiDefinitionRenderer.Render(consoleId, elementProviderName, flowToken, formFlowUiDefinition, WebManagementChannel.Identifier, false, flowServicesContainer); IWebUiControl webForm = (IWebUiControl)uiForm; webControl = webForm.BuildWebControl(); if (string.IsNullOrEmpty(webControl.ID)) webControl.ID = "FlowUI"; if (RuntimeInformation.TestAutomationEnabled && formFlowUiDefinition.MarkupProvider is ITestAutomationLocatorInformation testAutomationLocatorInformation) { var htmlform = webControl.Controls.OfType().FirstOrDefault(); htmlform?.Attributes.Add("data-qa", testAutomationLocatorInformation.TestAutomationLocator); } } return webControl; } catch (Exception ex) { ErrorServices.DocumentAdministrativeError(ex); ErrorServices.RedirectUserToErrorPage(uiContainerName, ex); } return new LiteralControl("ERROR"); } } } ================================================ FILE: Composite/Core/WebClient/FlowPage.cs ================================================ using System; using System.Web.UI; namespace Composite.Core.WebClient { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class FlowPage: Page { /// public bool SaveStepSucceeded { get; set; } /// public EventHandler OnSave { get; set; } /// public EventHandler OnSaveAndPublish { get; set; } } } ================================================ FILE: Composite/Core/WebClient/FunctionBoxRouteHandler.cs ================================================ using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Routing; using Composite.C1Console.Drawing; using Composite.C1Console.Security; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.WebClient.Renderings; namespace Composite.Core.WebClient { internal class FunctionBoxRoute : Route { // Adding "x" as a fictional paramter, so MVC wouldn't use this route for producing outbound links public FunctionBoxRoute() : base("Renderers/FunctionBo{x}", new FunctionBoxRouteHandler()) { } } internal class FunctionBoxRouteHandler : IRouteHandler { public IHttpHandler GetHttpHandler(RequestContext requestContext) { return new FunctionBoxHttpHandler(); } } /// /// Renders image that shows information about a function information in Visual Editor /// internal class FunctionBoxHttpHandler : HttpTaskAsyncHandler { private const int MinCharsPerDescriptionLine = 55; private static readonly string LogTitle = nameof(FunctionBoxHttpHandler); public override async Task ProcessRequestAsync(HttpContext context) { if (!UserValidationFacade.IsLoggedIn()) { context.Response.ContentType = MimeTypeInfo.Text; context.Response.Write("No user logged in"); context.Response.StatusCode = 401; return; } try { string title = context.Request["title"]; bool editable = context.Request["editable"] == "true"; Verify.That(!title.IsNullOrEmpty(), "Missing query string argument 'title'"); string boxtype = context.Request["type"]; Verify.That(!boxtype.IsNullOrEmpty(), "Missing query string argument 'boxtype'"); IEnumerable existingTemplateImages = new[] { "html", "function", "warning" }; Verify.That(existingTemplateImages.Contains(boxtype), "Query string argument 'boxtype' expected to be one of the following values: " + string.Join(", ", existingTemplateImages)); string description = context.Request["description"]; string encodedMarkup = context.Request["markup"]; string language = context.Request["lang"]; if (!string.IsNullOrEmpty(language)) { Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(language); } List textLines = null; if (description != null) { textLines = GetDescriptionLines(description); } Bitmap previewImage = null; try { if (GlobalSettingsFacade.FunctionPreviewEnabled && encodedMarkup != null) { try { string fileName = await FunctionPreview.GetPreviewFunctionPreviewImageFile(context); if (!context.Response.IsClientConnected) { return; } if (fileName != null) { previewImage = new Bitmap(fileName); if (previewImage.Width <= 1 && previewImage.Height <= 1) { previewImage = null; } } } catch (Exception ex) { Log.LogError("Function preview", ex); } } if (boxtype == "function") { if (previewImage != null) { FunctionPresentation.GenerateFunctionBoxWithPreview(context, title, previewImage, editable, context.Response.OutputStream); } else { FunctionPresentation.GenerateFunctionBoxWithText(context, title, false, editable, textLines, context.Response.OutputStream); } } else if (boxtype == "warning") { FunctionPresentation.GenerateFunctionBoxWithText(context, title, true, editable, textLines, context.Response.OutputStream); } else { GenerateBoxImage(context, boxtype, title, previewImage, textLines); } } finally { previewImage?.Dispose(); } } catch (Exception ex) { if (ex is HttpException && !context.Response.IsClientConnected) { return; } Log.LogError(LogTitle, ex); if (context.Response.IsClientConnected) { try { context.Response.Redirect(UrlUtils.AdminRootPath + "/images/function.png", false); } catch (Exception redirectError) { Log.LogError(LogTitle, redirectError); } } } } private static void GenerateBoxImage(HttpContext context, string boxtype, string title, Bitmap previewImage, List textLines) { string filePath = context.Server.MapPath(UrlUtils.ResolveAdminUrl($"images/{boxtype}box.png")); using (var bitmap = (Bitmap) Bitmap.FromFile(filePath)) { var imageCreator = new ImageTemplatedBoxCreator(bitmap, new Point(55, 40), new Point(176, 78)) { MinHeight = 50 }; int textLeftPadding = (boxtype == "function" ? 30 : 36); imageCreator.SetTitle(title, new Size(textLeftPadding, 9), new Size(70, 15), Color.Black, "Tahoma", 8.0f, FontStyle.Bold); if (previewImage != null) { imageCreator.SetPreviewImage(previewImage, new Size(10, 32), new Size(10, 16)); } else { if (textLines != null) { imageCreator.SetTextLines(textLines, new Size(textLeftPadding, 0), new Size(100, 80), Color.Black, "Tahoma", 8.0f, FontStyle.Regular); } } context.Response.ContentType = "image/png"; context.Response.Cache.SetExpires(DateTime.Now.AddDays(10)); using (Bitmap boxBitmap = imageCreator.CreateBitmap()) { boxBitmap.Save(context.Response.OutputStream, ImageFormat.Png); } } } private static List GetDescriptionLines(string description) { var lines = new List(); if (!description.IsNullOrEmpty()) { description = UrlUtils.UnZipContent(description); foreach (string naturalLine in description.Split('\n')) { if (naturalLine.Length == 0) lines.Add(""); string rest = naturalLine.Trim(); while (rest.Length > MinCharsPerDescriptionLine && rest.IndexOf(' ') > -1) { int firstSpaceIndex = rest.LastIndexOf(' ', MinCharsPerDescriptionLine); if (firstSpaceIndex == -1) firstSpaceIndex = rest.IndexOf(' '); if (firstSpaceIndex > -1) { lines.Add(rest.Substring(0, firstSpaceIndex)); rest = rest.Substring(firstSpaceIndex + 1).Trim(); } } if (rest.Length > 0) { lines.Add(rest); } } } return lines; } /// public override bool IsReusable => true; } } ================================================ FILE: Composite/Core/WebClient/FunctionCallEditor/FunctionCallEditorStateSimple.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using System.Xml.Serialization; using Composite.Functions; using Composite.Core.Types; namespace Composite.Core.WebClient.FunctionCallEditor { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class FunctionCallEditorStateSimple : IFunctionCallEditorState { /// public string FunctionCallsXml { get; set; } /// public bool ShowLocalFunctionNames { get; set; } /// public bool AllowLocalFunctionNameEditing { get; set; } /// public bool AllowSelectingInputParameters { get; set; } /// public string AllowedTypes { get; set; } [XmlIgnore] List IFunctionCallEditorState.FunctionCalls { get { var functionList = new List(); if (FunctionCallsXml != null) { XElement root = XElement.Parse(FunctionCallsXml); foreach (XElement functionElement in root.Elements()) { string localname; XAttribute localNameAttr = functionElement.Attribute("localname"); localname = localNameAttr != null ? localNameAttr.Value : string.Empty; var functionDefinition = (BaseFunctionRuntimeTreeNode) FunctionTreeBuilder.Build(functionElement, true); functionList.Add(new NamedFunctionCall(localname, functionDefinition)); } } return functionList; } set { List functionCalls = value; Verify.IsNotNull(functionCalls, "Failed to get function calls"); XElement functionsNode = new XElement("functions"); foreach (var localNamedFunctionCall in functionCalls) { Guid handle = Guid.NewGuid(); BaseFunctionRuntimeTreeNode functionRuntime = localNamedFunctionCall.FunctionCall; XElement function = functionRuntime.Serialize(); function.Add(new XAttribute("localname", localNamedFunctionCall.Name)); function.Add(new XAttribute("handle", handle)); functionsNode.Add(function); } FunctionCallsXml = functionsNode.ToString(); } } [XmlIgnore] List IParameterEditorState.Parameters { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// [XmlIgnore] public List ParameterTypeOptions { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// [XmlIgnore] public Type[] AllowedResultTypes { get { var result = new List(); if (AllowedTypes != null) { foreach (string typeName in AllowedTypes.Split(new [] {';'}, StringSplitOptions.RemoveEmptyEntries)) { result.Add(TypeManager.GetType(typeName)); } } return result.ToArray(); } set { AllowedTypes = value == null ? null : string.Join(";", from t in value select TypeManager.SerializeType(t)); } } /// public bool WidgetFunctionSelection { get; set; } bool IFunctionCallEditorState.ShowLocalFunctionNames { get { return ShowLocalFunctionNames; } } bool IFunctionCallEditorState.AllowLocalFunctionNameEditing { get { return AllowLocalFunctionNameEditing; } } bool IFunctionCallEditorState.AllowSelectingInputParameters { get { return AllowSelectingInputParameters; } } /// public int MaxFunctionAllowed { get; set; } int IFunctionCallEditorState.MaxFunctionAllowed { get { return MaxFunctionAllowed; } } /// public string ConsoleId { get; set; } } } ================================================ FILE: Composite/Core/WebClient/FunctionCallEditor/FunctionMarkupHelper.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.Core.Extensions; using Composite.Core.Types; using Composite.Core.Xml; using Composite.Functions; namespace Composite.Core.WebClient.FunctionCallEditor { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class FunctionMarkupHelper { private static readonly string LogTitle = typeof (FunctionMarkupHelper).Name; private static readonly XName ParameterNodeXName = Namespaces.Function10 + "param"; private static readonly XName ParameterValueElementXName = Namespaces.Function10 + "paramelement"; /// /// Gets simple parameter value from it's markup. /// /// public static object GetParameterValue(XElement parameterNode, ParameterProfile parameterProfile) { List parameterElements = parameterNode.Elements(ParameterValueElementXName).ToList(); if (parameterElements.Any()) { return parameterElements.Select(element => element.Attribute("value").Value).ToList(); } var valueAttr = parameterNode.Attribute("value"); if (valueAttr != null) { try { return XmlSerializationHelper.Deserialize(valueAttr, parameterProfile.Type); } catch (Exception ex) { Log.LogError(LogTitle, ex); return parameterProfile.GetDefaultValue(); } } if (parameterNode.Elements().Any()) { Type paramType = parameterProfile.Type; if (paramType.IsSubclassOf(typeof(XContainer)) || (paramType.IsLazyGenericType() && paramType.GetGenericArguments()[0].IsSubclassOf(typeof(XContainer)))) { return ValueTypeConverter.Convert(parameterNode.Elements().First(), parameterProfile.Type); } throw new NotImplementedException("Not supported type of function parameter element node: '{0}'".FormatWith(paramType.FullName)); } return parameterProfile.GetDefaultValue(); } /// public static void SetParameterValue(XElement functionMarkup, ParameterProfile parameter, object parameterValue) { bool newValueNotEmpty = parameterValue != null && (!(parameterValue is IList) || ((IList) parameterValue).Count > 0) && !(parameter.IsRequired && parameterValue as string == string.Empty); var parameterNode = functionMarkup.Elements(ParameterNodeXName).FirstOrDefault(p => (string)p.Attribute("name") == parameter.Name); if (parameterNode != null) { parameterNode.Remove(); } if (newValueNotEmpty && parameterValue != parameter.GetDefaultValue()) { var newConstantParam = new ConstantObjectParameterRuntimeTreeNode(parameter.Name, parameterValue); functionMarkup.Add(newConstantParam.Serialize()); } } /// public static IDictionary GetParameterNodes(XElement functionMarkup) { return functionMarkup.Elements(ParameterNodeXName).ToDictionary(e => (string)e.Attribute("name")); } } } ================================================ FILE: Composite/Core/WebClient/FunctionCallEditor/IFunctionCallEditorState.cs ================================================ using System; using System.Collections.Generic; using System.Xml.Serialization; using Composite.Functions; using Composite.Functions.ManagedParameters; namespace Composite.Core.WebClient.FunctionCallEditor { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IParameterEditorState { /// [XmlIgnore] List Parameters { get; set; } /// [XmlIgnore] List ParameterTypeOptions { get; set; } } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IFunctionCallEditorState : IParameterEditorState { /// [XmlIgnore] List FunctionCalls { get; set; } /// bool ShowLocalFunctionNames { get; } // Check if this setting is used /// bool WidgetFunctionSelection { get; } /// bool AllowLocalFunctionNameEditing { get; } /// bool AllowSelectingInputParameters { get; } /// Type[] AllowedResultTypes { get; } /// int MaxFunctionAllowed { get; } /// string ConsoleId { get; } } } ================================================ FILE: Composite/Core/WebClient/FunctionCallEditor/TreeHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.Functions; using Composite.Core.Xml; namespace Composite.Core.WebClient.FunctionCallEditor { /// /// Contains helper methods to work with serialized function calls tree /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class TreeHelper { /// public static readonly string PathSeparator = "/"; private static readonly XName ParameterNodeName = Namespaces.Function10 + "param"; private static readonly XName FunctionNodeName = Namespaces.Function10 + "function"; private static readonly XName WidgetFunctionNodeName = Namespaces.Function10 + "widgetfunction"; /// public static string GetRootFunctionPath(int functionIndex) { return string.Format("/function[{0}]", functionIndex); } /// public static string GetParameterPath(string parentFunctionPath, string parameterName) { return string.Format("{0}/@{1}", parentFunctionPath, parameterName); } /// public static string GetFunctionCallPath(string parameterNodePath) { return string.Format("{0}/function", parameterNodePath); } /// public static Dictionary GetElementToPathMap(XDocument functionMarkup) { return GetElementToPathMap(functionMarkup.Root); } /// public static Dictionary GetElementToPathMap(XElement root) { var functionToPathMap = new Dictionary(); // Creating node->path dictionary int functionCounter = 0; foreach (XElement rootFunctionElement in root.Elements().GetFunctionsAndWidgetFunctions()) { functionCounter++; functionToPathMap.Add(rootFunctionElement, GetRootFunctionPath(functionCounter)); foreach (XElement element in rootFunctionElement.Descendants().Where(f=>f.Name == ParameterNodeName || f.Name == FunctionNodeName)) { string parentPathId; if (functionToPathMap.TryGetValue(element.Parent, out parentPathId)) { if (element.Name == ParameterNodeName) { functionToPathMap.Add(element, GetParameterPath(parentPathId, element.Attribute("name").Value)); } else if (element.Name == FunctionNodeName) { functionToPathMap.Add(element, GetFunctionCallPath(parentPathId)); } } } } return functionToPathMap; } /// public static Dictionary GetElementToIdMap(XDocument functionMarkup, Dictionary pathToIDmap) { Dictionary functionToPathMap = GetElementToPathMap(functionMarkup); var result = new Dictionary(); foreach (XElement element in functionToPathMap.Keys) { string elementPath = functionToPathMap[element]; if (pathToIDmap.ContainsKey(elementPath)) { result.Add(element, pathToIDmap[elementPath]); } else { throw new InvalidOperationException("Function tree xml has already been changed"); // TODO: should this ever happen? //result.Add(element, GetNewId()); } } return result; } /// public static Dictionary BuildTreePathToIdDictionary(XDocument functionMarkup) { // Populating path->id dictionary var treePathToIdMapping = new Dictionary(); var elementToPathMap = GetElementToPathMap(functionMarkup); elementToPathMap.Values.ToList().ForEach( value => treePathToIdMapping.Add(value, GetNewId()) ); List functionNodes = functionMarkup .Descendants() .Where(node => (node.Name == FunctionNodeName || node.Name == WidgetFunctionNodeName) && !node.Ancestors().Where(f=>f.Parent!=null).Any(g=>g.Name.Namespace != Namespaces.Function10)) .ToList(); foreach (XElement functionNode in functionNodes) { foreach (string parameterName in GetUndefinedParameterNames(functionNode)) { string functionPath = elementToPathMap[functionNode]; treePathToIdMapping.Add(GetParameterPath(functionPath, parameterName), GetNewId()); } } return treePathToIdMapping; } /// public static XElement GetParameterNode(XElement functionNode, string parameterName) { return (from parameter in functionNode.Elements() let nameAttribute = parameter.Attribute("name") where nameAttribute != null && nameAttribute.Value == parameterName select parameter).FirstOrDefault(); } /// public static string GetNewId() { return Guid.NewGuid().ToString(); } /// public static XElement FindByPath(XElement root, string path) { int functionCounter = 0; foreach (XElement rootFunctionElement in root.Elements().GetFunctionsAndWidgetFunctions()) { functionCounter++; string rootFunctionPath = GetRootFunctionPath(functionCounter); if (path == rootFunctionPath) { return rootFunctionElement; } if (!path.StartsWith(rootFunctionPath + PathSeparator)) { continue; } foreach (XElement element in rootFunctionElement.Elements()) { XElement result = FindByPathRec(element, rootFunctionPath, path); if (result != null) return result; } break; } return null; } internal static XElement FindByPathRec(XElement element, string parentPath, string pathToFind) { string path; if (element.Name == ParameterNodeName) { path = GetParameterPath(parentPath, element.Attribute("name").Value); } else if (element.Name == FunctionNodeName) { path = GetFunctionCallPath(parentPath); } else return null; if (pathToFind == path) { return element; } if (pathToFind.StartsWith(path + PathSeparator)) { foreach (XElement child in element.Elements()) { XElement result = FindByPathRec(child, path, pathToFind); if (result != null) return result; } } return null; } /// public static string[] GetUndefinedParameterNames(XElement functionXElement) { var result = new List(); // Can be optimized foreach (string paramName in GetParameterNames(functionXElement)) { if (!FunctionHasParameterDefined(functionXElement, paramName)) { result.Add(paramName); } } return result.ToArray(); } /// public static string[] GetParameterNames(XElement functionXElement) { if (functionXElement.Name != FunctionNodeName && functionXElement.Name != WidgetFunctionNodeName) { return new string[0]; } string functionName = functionXElement.Attribute("name").Value; IMetaFunction function = (functionXElement.Name == FunctionNodeName) ? (IMetaFunction)FunctionFacade.GetFunction(functionName) : FunctionFacade.GetWidgetFunction(functionName); return function.ParameterProfiles.Select(parameter => parameter.Name).ToArray(); } private static bool FunctionHasParameterDefined(XElement functionXElement, string parameterName) { return functionXElement.Elements(ParameterNodeName).Any(node => node.Attribute("name").Value == parameterName); } /// public static IMetaFunction GetFunction(XElement functionNode) { string functionName = functionNode.Attribute("name").Value; if(functionNode.Name == WidgetFunctionNodeName) { return FunctionFacade.GetWidgetFunction(functionName); } return FunctionFacade.GetFunction(functionName); } /// public static IEnumerable GetFunctionsAndWidgetFunctions(this IEnumerable elements) { return elements.Where(element => element.Name == FunctionNodeName || element.Name == WidgetFunctionNodeName); } } } ================================================ FILE: Composite/Core/WebClient/FunctionUiHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web.UI; using System.Xml; using System.Xml.Linq; using Composite.C1Console.Forms; using Composite.C1Console.Forms.WebChannel; using Composite.Core.Types; using Composite.Core.Xml; using Composite.Data.Validation.ClientValidationRules; using Composite.Functions; namespace Composite.Core.WebClient { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class FunctionUiHelper { /// public static FormTreeCompiler AttachAndCompileParameterWidgets(Control attachmentControl, IEnumerable parameterProfiles, Dictionary bindings, string uniqueName, string panelLabel, IFormChannelIdentifier channelIdentifier, bool reset) { FormTreeCompiler compiler = FunctionUiHelper.BuildWidgetForParameters(parameterProfiles, bindings, uniqueName, panelLabel, channelIdentifier); IWebUiControl webUiControl = (IWebUiControl)compiler.UiControl; Control form = webUiControl.BuildWebControl(); attachmentControl.Controls.Add(form); if (reset) { webUiControl.InitializeViewState(); } return compiler; } /// public static FormTreeCompiler BuildWidgetForParameters(IEnumerable parameterProfiles, Dictionary bindings, string uniqueName, string panelLabel, IFormChannelIdentifier channelIdentifier) { XNamespace stdControlLibSpace = Namespaces.BindingFormsStdUiControls10; var bindingsDeclaration = new XElement(Namespaces.BindingForms10 + "bindings"); var widgetPlaceholder = new XElement(stdControlLibSpace + "FieldGroup", new XAttribute("Label", panelLabel)); var bindingsValidationRules = new Dictionary>(); foreach (ParameterProfile parameterProfile in parameterProfiles.Where(f=>f.WidgetFunction!=null)) { IWidgetFunction widgetFunction = parameterProfile.WidgetFunction; Type bindingType = widgetFunction != null && parameterProfile.Type.IsLazyGenericType() ? widgetFunction.ReturnType : parameterProfile.Type; bindingsDeclaration.Add( new XElement(Namespaces.BindingForms10 + "binding", new XAttribute("optional", true), new XAttribute("name", parameterProfile.Name), new XAttribute("type", bindingType.AssemblyQualifiedName))); var context = new FunctionContextContainer(); XElement uiMarkup = FunctionFacade.GetWidgetMarkup(widgetFunction, parameterProfile.Type, parameterProfile.WidgetFunctionParameters, parameterProfile.Label, parameterProfile.HelpDefinition, parameterProfile.Name, context); widgetPlaceholder.Add(uiMarkup); if (!bindings.ContainsKey(parameterProfile.Name)) { bindings.Add(parameterProfile.Name, ""); } if (parameterProfile.IsRequired) { bindingsValidationRules.Add(parameterProfile.Name, new List { new NotNullClientValidationRule() }); } } FormDefinition widgetFormDefinition = BuildFormDefinition(bindingsDeclaration, widgetPlaceholder, bindings); var compiler = new FormTreeCompiler(); using (XmlReader reader = widgetFormDefinition.FormMarkup) { compiler.Compile(reader, channelIdentifier, widgetFormDefinition.Bindings, false, "WidgetParameterSetters" + uniqueName, bindingsValidationRules); } return compiler; } /// /// /// /// Binding declarations - a list of elements like <binding name="..." type="..." optional="false" xmlns="http://www.composite.net/ns/management/bindingforms/1.0" /> /// The visual content of the form. All namespaces that controls and functions belong to must be declared. /// /// private static FormDefinition BuildFormDefinition(XNode bindingsDeclarationMarkup, XNode uiControlMarkup, Dictionary bindings) { XNamespace placeholderSpace = "#internal"; XNamespace stdControlLibSpace = Namespaces.BindingFormsStdUiControls10; string formXml = #region XML for form @" "; #endregion var formMarkup = XDocument.Parse(formXml); XElement bindingDeclarationPlaceholder = formMarkup.Descendants(placeholderSpace + "bindingsDeclarationPlaceholder").First(); bindingDeclarationPlaceholder.ReplaceWith(bindingsDeclarationMarkup); XElement uiControlPlaceholder = formMarkup.Descendants(placeholderSpace + "uiControlPlaceholder").First(); uiControlPlaceholder.ReplaceWith(uiControlMarkup); return new FormDefinition(formMarkup.CreateReader(), bindings); } } } ================================================ FILE: Composite/Core/WebClient/HttpModules/AdministrativeAuthorizationHttpModule.cs ================================================ using Composite.C1Console.Security; using Composite.Core.Application; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.Xml; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Web.Hosting; using System.Xml.Linq; namespace Composite.Core.WebClient.HttpModules { /// /// Http Module that ensures that only authenticated users can access /Composite/* files not explicitly allowed to everyone. /// Also ensure that HTTPS rules are enforced. /// internal class AdministrativeAuthorizationHttpModule : IHttpModule { private static readonly List _allAllowedPaths = new List(); private static string _adminRootPath; private static string _servicesPath; private static string _loginPagePath; private static readonly object _lock = new object(); private static bool _allowC1ConsoleRequests; private static bool _forceHttps = true; private static bool _allowFallbackToHttp = true; private static int? _customHttpsPortNumber; private const string webauthorizationRelativeConfigPath = "~/Composite/webauthorization.config"; private const string c1ConsoleAccessRelativeConfigPath = "~/App_Data/Composite/Configuration/C1ConsoleAccess.xml"; private const string unsecureRedirectRelativePath = "~/Composite/unsecure.aspx"; private const string loginPagePathAttributeName = "loginPagePath"; private const string allowElementName = "allow"; private const string allow_pathAttributeName = "path"; private const string c1ConsoleRequestsNotAllowedHtmlTemplate = @" Access Denied

Access Denied

Administrative access has been disabled on this site.

IE Padding, preventing it from showing a generic error page: {0}

"; static AdministrativeAuthorizationHttpModule() { _allowC1ConsoleRequests = false; string adminRootPath = HostingEnvironment.MapPath(UrlUtils.AdminRootPath); bool adminFolderExists; try { adminFolderExists = C1Directory.Exists(adminRootPath); } catch (Exception ex) { // we fail miserably here when write permissions are missing, also the default exception is exceptionally crappy throw new IOException("Please ensure that the web application process has permissions to read and modify the entire web app directory structure.", ex); } if (adminFolderExists) { _allowC1ConsoleRequests = true; LoadConfiguration(); } } public void Dispose() { } public void Init(HttpApplication context) { if (!SystemSetupFacade.IsSystemFirstTimeInitialized) { return; } context.AuthorizeRequest += context_AuthorizeRequest; } private static bool AlwaysAllowUnsecured(string requestPath) { string fileName = Path.GetFileName(requestPath); return fileName.StartsWith("unsecure") || fileName == "blank.png" || fileName == "box.png" || fileName == "button.png" || fileName == "startcomposite.png" || fileName == "default.css.aspx"; } private void context_AuthorizeRequest(object sender, EventArgs e) { var application = (HttpApplication)sender; HttpContext context = application.Context; string currentPath = context.Request.Path.ToLowerInvariant(); if (_adminRootPath == null || !currentPath.StartsWith(_adminRootPath)) { return; } if (!_allowC1ConsoleRequests) { context.Response.ContentType = "text/html"; string iePadding = new String('!', 512); context.Response.Write(string.Format(c1ConsoleRequestsNotAllowedHtmlTemplate, iePadding)); context.Response.End(); return; } var url = context.Request.Url; // https check if (_forceHttps && url.Scheme != "https") { if (!AlwaysAllowUnsecured(url.LocalPath) && !UserOptedOutOfHttps(context)) { context.Response.Redirect( $"{unsecureRedirectRelativePath}?fallback={_allowFallbackToHttp.ToString().ToLower()}&httpsport={_customHttpsPortNumber}"); } } // access check if (currentPath.Length > _adminRootPath.Length && !UserValidationFacade.IsLoggedIn() && !_allAllowedPaths.Any(p => currentPath.StartsWith(p, StringComparison.OrdinalIgnoreCase))) { if (currentPath.StartsWith(_servicesPath)) { context.Response.StatusCode = 403; context.Response.End(); return; } Log.LogWarning("Authorization", "DENIED {0} access to {1}", context.Request.UserHostAddress, currentPath); string redirectUrl =$"{_loginPagePath}?ReturnUrl={HttpUtility.UrlEncode(url.PathAndQuery, Encoding.UTF8)}"; context.Response.Redirect(redirectUrl, true); return; } // On authenticated request make sure these resources gets compiled / launched. if (IsConsoleOnline) { BrowserRender.EnsureReadiness(); BuildManagerHelper.InitializeControlPreLoading(); } } private bool IsConsoleOnline => ApplicationOnlineHandlerFacade.IsApplicationOnline && GlobalInitializerFacade.SystemCoreInitialized && !GlobalInitializerFacade.SystemCoreInitializing && SystemSetupFacade.IsSystemFirstTimeInitialized; private bool UserOptedOutOfHttps(HttpContext context) { if (!_allowFallbackToHttp) { return false; } HttpCookie cookie = context.Request.Cookies["avoidc1consolehttps"]; return cookie?.Value == "true"; } private static void LoadConfiguration() { lock (_lock) { _adminRootPath = UrlUtils.AdminRootPath.ToLowerInvariant(); if (!_adminRootPath.EndsWith("/")) { _adminRootPath = $"{_adminRootPath}/"; } _servicesPath = _adminRootPath + "services/"; LoadAllowedPaths(); _allowC1ConsoleRequests = true; LoadC1ConsoleAccessConfig(); } } private static void LoadC1ConsoleAccessConfig() { // defaults - keeping these if config file is missing or fucked up somehow _forceHttps = false; _allowFallbackToHttp = true; _customHttpsPortNumber = null; string c1ConsoleAccessConfigPath = HostingEnvironment.MapPath(c1ConsoleAccessRelativeConfigPath); if (C1File.Exists(c1ConsoleAccessConfigPath)) { try { XDocument accessDoc = XDocumentUtils.Load(c1ConsoleAccessConfigPath); _allowC1ConsoleRequests = _allowC1ConsoleRequests && (bool)accessDoc.Root.Attribute("enabled"); XElement protocolElement = accessDoc.Root.Element("ClientProtocol"); _forceHttps = (bool)protocolElement.Attribute("forceHttps"); _allowFallbackToHttp = (bool)protocolElement.Attribute("allowFallbackToHttp"); var customHttpsPortNumberAttrib = protocolElement.Attribute("customHttpsPortNumber"); if (customHttpsPortNumberAttrib != null && customHttpsPortNumberAttrib.Value.Length > 0) { _customHttpsPortNumber = (int)customHttpsPortNumberAttrib; } } catch (Exception ex) { Log.LogError("Authorization", "Problem parsing '{0}'. Will use defaults and allow normal access. Error was '{1}'", c1ConsoleAccessRelativeConfigPath, ex.Message); } } } private static void LoadAllowedPaths() { _allAllowedPaths.Clear(); string webauthorizationConfigPath = HostingEnvironment.MapPath(webauthorizationRelativeConfigPath); if (!C1File.Exists(webauthorizationConfigPath)) { Log.LogInformation(nameof(AdministrativeAuthorizationHttpModule), "File '{0}' not found - all access to the ~/Composite folder will be blocked", webauthorizationConfigPath); return; } XDocument webauthorizationConfigDocument = XDocumentUtils.Load(webauthorizationConfigPath); XAttribute loginPagePathAttribute = Verify.ResultNotNull(webauthorizationConfigDocument.Root.Attribute("loginPagePath"), "Missing '{0}' attribute on '{1}' root element", loginPagePathAttributeName, webauthorizationRelativeConfigPath); string relativeLoginPagePath = Verify.StringNotIsNullOrWhiteSpace(loginPagePathAttribute.Value, "Unexpected empty '{0}' attribute on '{1}' root element", loginPagePathAttributeName, webauthorizationRelativeConfigPath); _loginPagePath = UrlUtils.ResolveAdminUrl(relativeLoginPagePath); foreach (XElement allowElement in webauthorizationConfigDocument.Root.Elements(allowElementName)) { XAttribute relativePathAttribute = Verify.ResultNotNull(allowElement.Attribute(allow_pathAttributeName), "Missing '{0}' attribute on '{1}' element in '{2}'.", allow_pathAttributeName, allowElement, webauthorizationRelativeConfigPath); string relativePath = Verify.StringNotIsNullOrWhiteSpace(relativePathAttribute.Value, "Empty '{0}' attribute on '{1}' element in '{2}'.", allow_pathAttributeName, allowElement, webauthorizationRelativeConfigPath); string fullPath = UrlUtils.ResolveAdminUrl(relativePath).ToLowerInvariant(); _allAllowedPaths.Add(fullPath); } } } } ================================================ FILE: Composite/Core/WebClient/HttpModules/AdministrativeCultureSetterHttpModule.cs ================================================ using System; using System.Globalization; using System.Threading; using System.Web; using Composite.C1Console.Security; using Composite.C1Console.Users; using Composite.Core.Configuration; namespace Composite.Core.WebClient.HttpModules { internal class AdministrativeCultureSetterHttpModule : IHttpModule { public void Init(HttpApplication context) { if (!SystemSetupFacade.IsSystemFirstTimeInitialized) { return; } context.AuthorizeRequest += context_AuthorizeRequest; } void context_AuthorizeRequest(object sender, EventArgs e) { HttpApplication application = (HttpApplication)sender; HttpContext context = application.Context; bool adminRootRequest = UrlUtils.IsAdminConsoleRequest(context); if (adminRootRequest) { if (UserValidationFacade.IsLoggedIn()) { Thread.CurrentThread.CurrentCulture = UserSettings.CultureInfo; Thread.CurrentThread.CurrentUICulture = UserSettings.C1ConsoleUiLanguage; } else { var defaultCulture = CultureInfo.CreateSpecificCulture(GlobalSettingsFacade.DefaultCultureName); Thread.CurrentThread.CurrentCulture = defaultCulture; Thread.CurrentThread.CurrentUICulture = defaultCulture; } } } public void Dispose() { } } } ================================================ FILE: Composite/Core/WebClient/HttpModules/AdministrativeDataScopeSetterHttpModule.cs ================================================ using System; using System.Web; using Composite.C1Console.Security; using Composite.C1Console.Users; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Elements.Foundation; using Composite.Core.Configuration; using Composite.Data; namespace Composite.Core.WebClient.HttpModules { internal class AdministrativeDataScopeSetterHttpModule : IHttpModule { private static bool _consoleArtifactsInitialized = false; private static object _consoleArtifactsInitializeLock = new object(); public void Init(HttpApplication context) { if (!SystemSetupFacade.IsSystemFirstTimeInitialized) { return; } var moduleInstance = new ModuleInstance(); context.AuthorizeRequest += moduleInstance.AuthorizeRequest; context.EndRequest += moduleInstance.EndRequest; } private class ModuleInstance { private DataScope _dataScope; public void AuthorizeRequest(object sender, EventArgs e) { if (!SystemSetupFacade.IsSystemFirstTimeInitialized) return; HttpApplication application = (HttpApplication)sender; HttpContext context = application.Context; bool adminRootRequest = UrlUtils.IsAdminConsoleRequest(context); if (adminRootRequest && UserValidationFacade.IsLoggedIn()) { _dataScope = new DataScope(DataScopeIdentifier.Administrated, UserSettings.ActiveLocaleCultureInfo); if (!_consoleArtifactsInitialized) { lock(_consoleArtifactsInitializeLock) { if (!_consoleArtifactsInitialized && !SystemSetupFacade.SetupIsRunning) { HookingFacade.EnsureInitialization(); FlowControllerFacade.Initialize(); ConsoleFacade.Initialize(); ElementProviderLoader.LoadAllProviders(); _consoleArtifactsInitialized = true; } } } } } public void EndRequest(object sender, EventArgs e) { _dataScope?.Dispose(); _dataScope = null; } } public void Dispose() { } } } ================================================ FILE: Composite/Core/WebClient/HttpModules/AdministrativeResponseFilterHttpModule.cs ================================================ using System; using System.IO; using System.Text; using System.Web; using System.Web.UI; using Composite.Core.Types; using System.Web.WebPages; namespace Composite.Core.WebClient.HttpModules { internal class AdministrativeResponseFilterHttpModule : IHttpModule { private static readonly Pair[] ReplacementRules = new [] { new Pair(@" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""", @""), new Pair(@" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""", @""), new Pair(@"xmlns:ui=""http://www.composite.net/ns/ui/1.0""", @"xmlns:ui=""http://www.w3.org/1999/xhtml""") }; public void Init(HttpApplication context) { context.PostMapRequestHandler += AttachFilter; } private static void AttachFilter(object sender, EventArgs e) { var httpContext = HttpContext.Current; if (!UrlUtils.IsAdminConsoleRequest(httpContext)) return; if (httpContext.Handler is Page || httpContext.Handler is WebPageHttpHandler) { httpContext.Response.Filter = new ReplacementStream(httpContext.Response.Filter); } } public void Dispose() { } internal class ReplacementStream : Utf8StringTransformationStream { public ReplacementStream(Stream innerStream) : base(innerStream) {} public override string Process(string str) { var sb = new StringBuilder(str); foreach(var kvp in ReplacementRules) { sb.Replace(kvp.First, kvp.Second); } return sb.ToString(); } } } } ================================================ FILE: Composite/Core/WebClient/HttpModules/Utf8StringTransformationStream.cs ================================================ using System; using System.IO; using System.Linq; using System.Text; using System.Web; namespace Composite.Core.WebClient.HttpModules { internal abstract class Utf8StringTransformationStream : Stream { private readonly Stream _innerStream; private MemoryStream _ms = new MemoryStream(); private bool? _responseIsUtf8; public Utf8StringTransformationStream(Stream innerOuputStream) { _innerStream = innerOuputStream; } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override void Flush() { // DO NOTHING HERE } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { if (_responseIsUtf8 == null) { _responseIsUtf8 = buffer.Take(3).SequenceEqual(Encoding.UTF8.GetPreamble()); } if (!_responseIsUtf8.Value) { _innerStream.Write(buffer, offset, count); return; } if (!_ms.CanWrite) { // Reopening stream if it was empty _ms = new MemoryStream(); } _ms.Write(buffer, offset, count); } public override void Close() { if (_responseIsUtf8 == null || !_responseIsUtf8.Value) { _innerStream.Close(); return; } // Checking if the stream was already closed if (!_ms.CanSeek) { return; } _ms.Seek(0, SeekOrigin.Begin); var bytes = _ms.ToArray(); string str = Encoding.UTF8.GetString(bytes); string newValue = Process(str); if (newValue != str) { bytes = Encoding.UTF8.GetBytes(newValue); } _innerStream.Write(bytes, 0, bytes.Length); _innerStream.Close(); _ms.Close(); } public abstract string Process(string str); } } ================================================ FILE: Composite/Core/WebClient/Logging/WFC/ILogService.cs ================================================ using System; using System.ServiceModel; using System.ServiceModel.Web; namespace Composite.Core.WebClient.Logging.WCF { [ServiceContract] internal interface ILogService { [OperationContract] [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)] string GetVersion(); [OperationContract] [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)] string Authenticate(string adminPassword); [OperationContract] [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)] DateTime GetLastStartupTime(); [OperationContract] [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)] DateTime GetServerTime(); [OperationContract] [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)] DateTime[] GetLoggingDates(); [OperationContract] [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)] int GetLogEntriesCount(DateTime timeFrom, DateTime timeTo, bool includeVerbose); [OperationContract] [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)] int GetLogEntriesCountByDate(DateTime date, bool includeVerbose); [OperationContract] [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)] LogEntry[] GetLogEntries(DateTime timeFrom, DateTime timeTo, bool includeVerbose, int maximumAmount); [OperationContract] [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)] LogEntry[] GetLogEntriesFrom(DateTime timeFrom, bool includeVerbose, int maximumAmount); } } ================================================ FILE: Composite/Core/WebClient/Logging/WFC/LogEntry.cs ================================================ using System; using System.Runtime.Serialization; namespace Composite.Core.WebClient.Logging.WCF { [DataContract(Name = "LogEntry", Namespace = "http://schemas.datacontract.org/2004/07/Composite.Logging.WCF")] internal class LogEntry { public LogEntry() { } public LogEntry(Composite.Core.Logging.LogEntry fileLogEntry) { TimeStamp = fileLogEntry.TimeStamp; ApplicationDomainId = fileLogEntry.ApplicationDomainId; ThreadId = fileLogEntry.ThreadId; Severity = fileLogEntry.Severity; Title = fileLogEntry.Title; DisplayOptions = fileLogEntry.DisplayOptions; Message = fileLogEntry.Message; } [DataMember] public DateTime TimeStamp; [DataMember] public int ApplicationDomainId; [DataMember] public int ThreadId; [DataMember] public string Severity; [DataMember] public string Title; [DataMember] public string DisplayOptions; [DataMember] public string Message; } } ================================================ FILE: Composite/Core/WebClient/Logging/WFC/LogService.cs ================================================ using System; using System.IO; using System.Linq; using System.ServiceModel; using System.ServiceModel.Activation; using System.Xml; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.C1Console.Security.Foundation.PluginFacades; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Logging; using Composite.Core.Threading; namespace Composite.Core.WebClient.Logging.WCF { [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] internal class LogService : ILogService { private static readonly string LoggerConfigurationFilePath = @"App_Data\Composite\Configuration\Logger.xml"; private static readonly object _syncRoot = new object(); private static string _loggerPassword; private static string LoggerPassword { get { if (_loggerPassword == null) { lock (_syncRoot) { if (_loggerPassword == null) { string configurationFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, LoggerConfigurationFilePath); if (C1File.Exists(configurationFilePath)) { var doc = new XmlDocument(); try { using (var sr = new C1StreamReader(configurationFilePath)) { doc.Load(sr); } var passwordNode = doc.SelectSingleNode("logger/password"); if (passwordNode != null && !string.IsNullOrEmpty(passwordNode.InnerText)) { _loggerPassword = passwordNode.InnerText; } } catch (Exception) { // Do nothing } if (_loggerPassword == null) { // Deleting configuration file C1File.Delete(configurationFilePath); } } if (_loggerPassword == null) { _loggerPassword = Guid.NewGuid().ToString(); string configFile = @" {0} ".FormatWith(_loggerPassword); C1File.WriteAllText(configurationFilePath, configFile); } } } } return _loggerPassword; } } public string GetVersion() { return "2.0"; } public string Authenticate(string loginAndPassword) { if (SystemSetupFacade.IsSystemFirstTimeInitialized == false) return ""; bool userIsValid; string login; string password; int separatorOffset = loginAndPassword.IndexOf("|"); if (separatorOffset > 0 && separatorOffset < loginAndPassword.Length - 1) { login = loginAndPassword.Substring(0, separatorOffset); password = loginAndPassword.Substring(separatorOffset + 1); } else { // Backward compatibility with old LogViewer login = "admin"; password = loginAndPassword; } bool userIsAdmin = false; using (ThreadDataManager.Initialize()) { userIsValid = LoginProviderPluginFacade.FormValidateUser(login, password) == LoginResult.Success; if (userIsValid) { string userName = login.ToLowerInvariant(); var userPermissionDefinitions = PermissionTypeFacade.GetUserPermissionDefinitions(userName).ToList(); var userGroupPermissionDefinitions = PermissionTypeFacade.GetUserGroupPermissionDefinitions(userName).ToList(); EntityToken rootEntityToken = AttachingPoint.PerspectivesRoot.EntityToken; var permissions = PermissionTypeFacade.GetCurrentPermissionTypes(new UserToken(userName), rootEntityToken, userPermissionDefinitions, userGroupPermissionDefinitions); userIsAdmin = permissions.Contains(PermissionType.Administrate); } } return (userIsValid && userIsAdmin) ? LoggerPassword : string.Empty; } public DateTime GetLastStartupTime() { if (SystemSetupFacade.IsSystemFirstTimeInitialized == false) return DateTime.MinValue; CheckSecurity(); return LogManager.GetLastStartupTime(); } public DateTime GetServerTime() { if (SystemSetupFacade.IsSystemFirstTimeInitialized == false) return DateTime.MinValue; CheckSecurity(); return DateTime.Now; } public DateTime[] GetLoggingDates() { if (SystemSetupFacade.IsSystemFirstTimeInitialized == false) return new DateTime[] { }; CheckSecurity(); return LogManager.GetLoggingDates(); } public int GetLogEntriesCount(DateTime timeFrom, DateTime timeTo, bool includeVerbose) { if (SystemSetupFacade.IsSystemFirstTimeInitialized == false) return 0; CheckSecurity(); return LogManager.GetLogEntriesCount(timeFrom, timeTo, includeVerbose); } public int GetLogEntriesCountByDate(DateTime date, bool includeVerbose) { if (SystemSetupFacade.IsSystemFirstTimeInitialized == false) return 0; CheckSecurity(); return LogManager.GetLogEntriesCountByDate(date, includeVerbose); } public LogEntry[] GetLogEntries(DateTime timeFrom, DateTime timeTo, bool includeVerbose, int maximumAmount) { if (SystemSetupFacade.IsSystemFirstTimeInitialized == false) return new LogEntry[] { }; CheckSecurity(); return Wrap(LogManager.GetLogEntries(timeFrom, timeTo, includeVerbose, maximumAmount)); } public LogEntry[] GetLogEntriesFrom(DateTime timeFrom, bool includeVerbose, int maximumAmount) { if (SystemSetupFacade.IsSystemFirstTimeInitialized == false) return new LogEntry[] { }; CheckSecurity(); return GetLogEntries(timeFrom, DateTime.MaxValue, includeVerbose, maximumAmount); } private static void CheckSecurity() { if (SystemSetupFacade.IsSystemFirstTimeInitialized == false) return; string header = OperationContext.Current.IncomingMessageHeaders.GetHeader("AuthToken", "Composite.Logger"); Verify.That(header == LoggerPassword, "User hasn't been authentificated"); } private static LogEntry[] Wrap(Composite.Core.Logging.LogEntry[] logEntries) { if (logEntries == null) { return null; } var result = new LogEntry[logEntries.Length]; for (int i = 0; i < result.Length; i++) { result[i] = new LogEntry(logEntries[i]); } return result; } } } ================================================ FILE: Composite/Core/WebClient/Media/DefaultImageFileFormatProvider.cs ================================================ using System; using System.Drawing; using System.IO; namespace Composite.Core.WebClient.Media { internal class DefaultImageFileFormatProvider: IImageFileFormatProvider { private readonly Action _saveAction; public DefaultImageFileFormatProvider(string mediaType, string extension, Action saveAction, bool canSetImageQuality = false) { MediaType = mediaType ?? throw new ArgumentNullException(nameof(mediaType)); FileExtension = extension ?? throw new ArgumentNullException(nameof(extension)); _saveAction = saveAction ?? throw new ArgumentNullException(nameof(saveAction)); CanSetImageQuality = canSetImageQuality; } public string MediaType { get; } public string FileExtension { get; } public bool CanSetImageQuality { get; } public bool CanReadImageSize => true; public bool TryGetSize(Stream imageStream, out Size size) { return ImageSizeReader.TryGetSize(imageStream, out size); } public Bitmap LoadImageFromStream(Stream stream) => new Bitmap(stream); public void SaveImageToFile(Bitmap image, string outputFilePath, int? qualityPercentage = null) { _saveAction(image, outputFilePath, qualityPercentage); } } } ================================================ FILE: Composite/Core/WebClient/Media/IImageFileFormatProvider.cs ================================================ using System.Drawing; using System.IO; namespace Composite.Core.WebClient.Media { /// /// A provider that enables reading/saving images for a specific image format. /// public interface IImageFileFormatProvider { /// /// A media type (aka MIME type) that describes the image format (f.e. "image/jpeg"). /// string MediaType { get; } /// /// A file extension that is associated with the image format. /// string FileExtension { get; } /// /// Indicates whether the provider allows specifying quality percentage when saving an image. /// bool CanSetImageQuality { get; } /// /// Indicates whether the provider allows reading image dimensions from the beginning of the stream. /// bool CanReadImageSize { get; } /// /// Tries to read image's size from the file header. /// /// The input stream with an image. /// The size of the image /// True if the image size was extracted successfully. bool TryGetSize(Stream imageStream, out Size size); /// /// Loads a out of stream . /// /// The input stream. /// Bitmap LoadImageFromStream(Stream stream); /// /// Saves an image to a file with a given quality. /// /// The image to be saved. /// The full path to a file. /// The desired quality of the image - from 1 to 100. void SaveImageToFile(Bitmap image, string outputFilePath, int? qualityPercentage = null); } } ================================================ FILE: Composite/Core/WebClient/Media/ImageFormatProviders.cs ================================================ using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using Composite.Core.IO; using Microsoft.Extensions.DependencyInjection; namespace Composite.Core.WebClient.Media { internal static class ImageFormatProviders { private static readonly ImageCodecInfo JpegCodecInfo = ImageCodecInfo.GetImageEncoders().First(codec => codec.FormatID == ImageFormat.Jpeg.Guid); private static Action GetSaveInFormatFunction(ImageFormat imageFormat) => (resizedImage, outputFilePath, quality) => resizedImage.Save(outputFilePath, imageFormat); internal static void AddDefaultImageFileFormatProviders(this IServiceCollection services) { var providers = new List { new DefaultImageFileFormatProvider(MimeTypeInfo.Jpeg, "jpeg", (resizedImage, outputFilePath, quality) => { var parameters = new EncoderParameters(1); parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality ?? 75); resizedImage.Save(outputFilePath, JpegCodecInfo, parameters); }, canSetImageQuality: true), new DefaultImageFileFormatProvider(MimeTypeInfo.Png, "png", GetSaveInFormatFunction(ImageFormat.Png)), new DefaultImageFileFormatProvider(MimeTypeInfo.Gif, "gif", GetSaveInFormatFunction(ImageFormat.Gif)), new DefaultImageFileFormatProvider(MimeTypeInfo.Tiff, "tiff", GetSaveInFormatFunction(ImageFormat.Tiff)), new DefaultImageFileFormatProvider(MimeTypeInfo.Bmp, "bmp", GetSaveInFormatFunction(ImageFormat.Bmp)) }; providers.ForEach(p => services.AddSingleton(p)); } } } ================================================ FILE: Composite/Core/WebClient/Media/ImageResizer.cs ================================================ using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Web.Caching; using System.Web.Hosting; using Composite.Core.IO; using Composite.Data.Plugins.DataProvider.Streams; using Composite.Data.Types; namespace Composite.Core.WebClient.Media { /// /// Class that performs image resizing /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ImageResizer { private const string ResizedImagesCacheDirectory = "~/App_Data/Composite/Cache/Resized images"; private static Dictionary _imageFormatProviders; private static Dictionary ImageFormatProviders { get { if (_imageFormatProviders != null) return _imageFormatProviders; var customProviders = ServiceLocator.GetServices().ToList(); var result = new Dictionary(); customProviders.ForEach(provider => { var mediaType = provider.MediaType; if (string.IsNullOrWhiteSpace(mediaType)) throw new InvalidOperationException($"Empty MediaType returned by provider {provider.GetType().FullName}"); result[mediaType] = provider; }); return _imageFormatProviders = result; } } private static readonly TimeSpan CacheExpirationTimeSpan = new TimeSpan(1, 0, 0, 0); private static string _resizedImagesDirectoryPath; private static string ResizedImagesDirectoryPath { get { if (_resizedImagesDirectoryPath == null) { _resizedImagesDirectoryPath = HostingEnvironment.MapPath(ResizedImagesCacheDirectory); if (!C1Directory.Exists(_resizedImagesDirectoryPath)) { C1Directory.CreateDirectory(_resizedImagesDirectoryPath); } } return _resizedImagesDirectoryPath; } } /// /// Gets the resized image. /// /// The media file. /// The resizing options. /// The media type of the image. /// The media type for the resized image. /// A full file path to a resized image; null if there's no need to resize the image public static string GetResizedImage(IMediaFile file, ResizingOptions resizingOptions, string sourceMediaType, string targetMediaType) { Verify.ArgumentNotNull(file, nameof(file)); Verify.ArgumentNotNullOrEmpty(sourceMediaType, nameof(sourceMediaType)); Verify.ArgumentNotNullOrEmpty(targetMediaType, nameof(targetMediaType)); if (!ImageFormatProviders.TryGetValue(sourceMediaType, out var sourceImageFormatProvider)) throw new ArgumentException($"Unsupported media type '{sourceMediaType}'", nameof(sourceMediaType)); if (!ImageFormatProviders.TryGetValue(targetMediaType, out var imageFileFormatProvider)) throw new ArgumentException($"Unsupported media type '{targetMediaType}'", nameof(targetMediaType)); string imageKey = file.CompositePath; string imageSizeCacheKey = nameof(ImageResizer) + imageKey; Size? imageSize = HttpRuntime.Cache.Get(imageSizeCacheKey) as Size?; Func loadImageFunc = sourceImageFormatProvider.LoadImageFromStream; Bitmap bitmap = null; Stream fileStream = null; try { if (imageSize == null) { if (sourceImageFormatProvider.CanReadImageSize) { fileStream = file.GetReadStream(); if (sourceImageFormatProvider.TryGetSize(fileStream, out var imageSizeFromProvider)) { imageSize = imageSizeFromProvider; } fileStream.Close(); fileStream.Dispose(); fileStream = null; } if (imageSize == null) { fileStream = file.GetReadStream(); bitmap = loadImageFunc(fileStream); imageSize = new Size { Width = bitmap.Width, Height = bitmap.Height }; } // We can provider cache dependency only for the native media provider CacheDependency cacheDependency = null; if (file is FileSystemFileBase fileSystemFile) { cacheDependency = new CacheDependency(fileSystemFile.SystemPath); } HttpRuntime.Cache.Add(imageSizeCacheKey, imageSize, cacheDependency, DateTime.MaxValue, CacheExpirationTimeSpan, CacheItemPriority.Normal, null); } bool needToResize = CalculateSize(imageSize.Value.Width, imageSize.Value.Height, resizingOptions, out int newWidth, out int newHeight, out bool centerCrop); needToResize = needToResize || resizingOptions.CustomQuality; if (!needToResize) { return null; } string mediaFileHash = GetMediaHash(imageKey); string centerCroppedString = centerCrop ? "c" : string.Empty; string fileExtension = imageFileFormatProvider.FileExtension; string qualityCacheKeyPart = imageFileFormatProvider.CanSetImageQuality ? $"_{resizingOptions.Quality}" : ""; string resizedImageFileName = $"{newWidth}x{newHeight}{centerCroppedString}_{mediaFileHash}{qualityCacheKeyPart}.{fileExtension}"; string resizedImageFullPath = Path.Combine(ResizedImagesDirectoryPath, resizedImageFileName); if (!C1File.Exists(resizedImageFullPath) || C1File.GetLastWriteTime(resizedImageFullPath) != file.LastWriteTime) { if (bitmap == null) { fileStream = file.GetReadStream(); bitmap = loadImageFunc(fileStream); } using (Bitmap resizedImage = ResizeImage(bitmap, newWidth, newHeight, centerCrop)) { int? imageQuality = imageFileFormatProvider.CanSetImageQuality ? (int?)resizingOptions.Quality : null; imageFileFormatProvider.SaveImageToFile(resizedImage, resizedImageFullPath, imageQuality); } if (file.LastWriteTime.HasValue) { C1File.SetLastWriteTime(resizedImageFullPath, file.LastWriteTime.Value); } } return resizedImageFullPath; } finally { bitmap?.Dispose(); fileStream?.Dispose(); } } private static string GetMediaHash(string mediaKeyPath) { var guid = HashingHelper.ComputeMD5Hash(mediaKeyPath, Encoding.UTF8); return UrlUtils.CompressGuid(guid).Substring(10); } private static bool CalculateSize(int width, int height, ResizingOptions resizingOptions, out int newWidth, out int newHeight, out bool centerCrop) { // Can be refactored to use System.Drawing.Size class instead of (width & height). if (width == 0 || height == 0) { newHeight = newWidth = 0; centerCrop = false; return false; } Verify.ArgumentCondition(width > 0, "width", "Negative values aren't allowed"); Verify.ArgumentCondition(height > 0, "height", "Negative values aren't allowed"); centerCrop = false; // If both height and width are defined - we have "scaling" if (resizingOptions.Height != null && resizingOptions.Width != null) { newHeight = (int)resizingOptions.Height; newWidth = (int)resizingOptions.Width; // we do not allow scaling to a size, bigger than original one if (newHeight > height) { newHeight = height; } if (newWidth > width) { newWidth = width; } // If the target dimensions are bigger or the same size as of the image - no resizing is done if (newWidth == width && newHeight == height) { return false; } switch (resizingOptions.ResizingAction) { case ResizingAction.Stretch: // no additional logic break; case ResizingAction.Crop: centerCrop = true; break; case ResizingAction.Fit: case ResizingAction.Fill: // No float point division for better precision Int64 heightProportionArea = (Int64)newHeight * width; Int64 widthProportionArea = (Int64)newWidth * height; if (heightProportionArea == widthProportionArea) { break; } if ((heightProportionArea > widthProportionArea) // (newHeight / height) > (newWidth / width) ^ (resizingOptions.ResizingAction == ResizingAction.Fit)) { newWidth = (int)(heightProportionArea / height); // newWidth = width * (newHeight / height) } else { newHeight = (int)(widthProportionArea / width); // newHeight = height * (newWidth / width) } break; } return true; } newWidth = width; newHeight = height; // If image doesn't fit to boundaries "maxWidth X maxHeight", downsizing it int? maxWidth = resizingOptions.Width; if (resizingOptions.MaxWidth != null && (maxWidth == null || resizingOptions.MaxWidth < maxWidth)) { maxWidth = resizingOptions.MaxWidth; } int? maxHeight = resizingOptions.Height; if (resizingOptions.MaxHeight != null && (maxHeight == null || resizingOptions.MaxHeight < maxHeight)) { maxHeight = resizingOptions.MaxHeight; } // Applying MaxHeight and MaxWidth limitations if (maxHeight != null && (int)maxHeight < newHeight) { newHeight = (int)maxHeight; newWidth = (int)(width * (double)(int)maxHeight / height); } if (maxWidth != null && (int)maxWidth < newWidth) { newWidth = (int)maxWidth; newHeight = (int)(height * (double)(int)maxWidth / width); } return newWidth != width || newHeight != height; } /// /// Resizes an image /// /// source /// width /// height /// when true, cropping will happen /// the resized image public static Bitmap ResizeImage(Bitmap image, int newWidth, int newHeight, bool centerCrop) { Verify.ArgumentNotNull(image, "image"); Bitmap resizedImage = new Bitmap(newWidth, newHeight); resizedImage.SetResolution(72, 72); using (Graphics newGraphic = Graphics.FromImage(resizedImage)) { newGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; newGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; // newGraphic.PixelOffsetMode = PixelOffsetMode.HighQuality; if (centerCrop) { float xRatio = image.Width / (float)newWidth; float yRatio = image.Height / (float)newHeight; if (xRatio > yRatio) { float dx = (image.Width / yRatio) - newWidth; DrawWithoutBlending(newGraphic, image, -dx / 2.0f, 0.0f, newWidth + dx, newHeight); } else if (yRatio > xRatio) { float dy = (image.Height / xRatio) - newHeight; DrawWithoutBlending(newGraphic, image, 0.0f, -dy / 2.0f, newWidth, newHeight + dy); } else { DrawWithoutBlending(newGraphic, image, 0, 0, newWidth, newHeight); } } else { DrawWithoutBlending(newGraphic, image, 0, 0, newWidth, newHeight); } } return resizedImage; } /// /// Draws a bitmap without background blending on first row and first column /// private static void DrawWithoutBlending(Graphics graphic, Bitmap bitmap, int x, int y, int width, int height) { using (var wrapMode = new ImageAttributes()) { wrapMode.SetWrapMode(WrapMode.TileFlipXY); graphic.DrawImage(bitmap, new Rectangle(x, y, width, height), 0, 0, bitmap.Width, bitmap.Height, GraphicsUnit.Pixel, wrapMode); } } private static void DrawWithoutBlending(Graphics graphic, Bitmap bitmap, float x, float y, float width, float height) { const double delta = 0.001; DrawWithoutBlending(graphic, bitmap, (int)Math.Floor(x + delta), (int)Math.Floor(y + delta), (int)Math.Ceiling(width - delta), (int)Math.Ceiling(height - delta)); } /// /// Returns a value indicating whether an image of a given media type can be resized. /// /// A media type. public static bool SourceMediaTypeSupported(string mediaType) { if (mediaType == null) throw new ArgumentNullException(nameof(mediaType)); return ImageFormatProviders.ContainsKey(mediaType); } /// /// Returns a value indicating whether resized imaged can be saved in the specified media type. /// /// A media type. public static bool TargetMediaTypeSupported(string mediaType) { if (mediaType == null) throw new ArgumentNullException(nameof(mediaType)); return ImageFormatProviders.ContainsKey(mediaType); } /// [Obsolete] public class SupportedImageFormats { /// public static ImageFormat JPG => ImageFormat.Jpeg; /// public static ImageFormat PNG => ImageFormat.Png; /// public static ImageFormat TIFF => ImageFormat.Tiff; /// public static ImageFormat GIF => ImageFormat.Gif; /// public static ImageFormat BMP => ImageFormat.Bmp; } } } ================================================ FILE: Composite/Core/WebClient/Media/ImageSizeReader.cs ================================================ using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; namespace Composite.Core.WebClient.Media { /// /// Kudos to http://stackoverflow.com/a/112711/396091 /// internal static class ImageSizeReader { const string errorMessage = "Could not recognise image format."; private static Dictionary> imageFormatDecoders = new Dictionary>() { { new byte[]{ 0x42, 0x4D }, DecodeBitmap}, { new byte[]{ 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, DecodeGif }, { new byte[]{ 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }, DecodeGif }, { new byte[]{ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, DecodePng }, { new byte[]{ 0xff, 0xd8 }, DecodeJfif }, }; /// /// Gets the width and height of an image. /// /// Stream containing image bytes /// The calculated size of the image /// True if the size was calculated internal static bool TryGetSize(Stream imageStream, out Size size) { try { using (BinaryReader binaryReader = new BinaryReader(imageStream)) { size = GetSize(binaryReader); return true; } } catch (Exception) { size = new Size(-1, -1); return false; } } private static Size GetSize(BinaryReader binaryReader) { int maxMagicBytesLength = imageFormatDecoders.Keys.OrderByDescending(x => x.Length).First().Length; byte[] magicBytes = new byte[maxMagicBytesLength]; for (int i = 0; i < maxMagicBytesLength; i += 1) { magicBytes[i] = binaryReader.ReadByte(); foreach (var kvPair in imageFormatDecoders) { if (magicBytes.StartsWith(kvPair.Key)) { return kvPair.Value(binaryReader); } } } throw new ArgumentException(errorMessage, "binaryReader"); } private static bool StartsWith(this byte[] thisBytes, byte[] thatBytes) { for (int i = 0; i < thatBytes.Length; i += 1) { if (thisBytes[i] != thatBytes[i]) { return false; } } return true; } private static short ReadLittleEndianInt16(this BinaryReader binaryReader) { byte[] bytes = new byte[sizeof(short)]; for (int i = 0; i < sizeof(short); i += 1) { bytes[sizeof(short) - 1 - i] = binaryReader.ReadByte(); } return BitConverter.ToInt16(bytes, 0); } private static int ReadLittleEndianInt32(this BinaryReader binaryReader) { byte[] bytes = new byte[sizeof(int)]; for (int i = 0; i < sizeof(int); i += 1) { bytes[sizeof(int) - 1 - i] = binaryReader.ReadByte(); } return BitConverter.ToInt32(bytes, 0); } private static Size DecodeBitmap(BinaryReader binaryReader) { binaryReader.ReadBytes(16); int width = binaryReader.ReadInt32(); int height = binaryReader.ReadInt32(); return new Size(width, height); } private static Size DecodeGif(BinaryReader binaryReader) { int width = binaryReader.ReadInt16(); int height = binaryReader.ReadInt16(); return new Size(width, height); } private static Size DecodePng(BinaryReader binaryReader) { binaryReader.ReadBytes(8); int width = binaryReader.ReadLittleEndianInt32(); int height = binaryReader.ReadLittleEndianInt32(); return new Size(width, height); } private static Size DecodeJfif(BinaryReader binaryReader) { while (binaryReader.ReadByte() == byte.MaxValue) { byte marker = binaryReader.ReadByte(); ushort chunkLength = (ushort)binaryReader.ReadLittleEndianInt16(); if (marker == 0xc0 || marker == 0xc2) { binaryReader.ReadByte(); short height = binaryReader.ReadLittleEndianInt16(); short width = binaryReader.ReadLittleEndianInt16(); return new Size(width, height); } binaryReader.ReadBytes(chunkLength - 2); } throw new ArgumentException("Could not recognise image format."); } } } ================================================ FILE: Composite/Core/WebClient/Media/ResizingAction.cs ================================================ namespace Composite.Core.WebClient.Media { /// /// Resizing action for /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum ResizingAction { /// /// Stretches image so it fills the specified area. The result image dimensions are newer bigger than original dimensions. /// It is the default action /// Stretch = 0, /// /// Scales image proportionally down (if necessary) so it fits the specified area. /// Also knows as "touch from inside"; /// Fit = 1, /// /// Scales image proportionally down (if necessary) so it fills the specified area. /// Fill = 2, /// /// Scales image proportionally down (if necessary) so it fills the specified area, and crops the parts that are outside area's boundaries. /// Also knows as "touch from outside"; /// Crop = 3 } } ================================================ FILE: Composite/Core/WebClient/Media/ResizingOptions.cs ================================================ using System; using System.Collections.Specialized; using System.Configuration; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Web; using System.Web.Caching; using System.Xml.Linq; using Composite.Core.IO; using Composite.Core.Xml; using Composite.Core.Configuration; namespace Composite.Core.WebClient.Media { /// /// Resizing options for /// public class ResizingOptions { private const string ResizedImageKeys = "~/App_Data/Composite/Media/ResizingOptions.xml"; private static string _resizedImageKeysFilePath; private const string ResizingOptionsConfigFileName = "ImageResizing.xml"; private static volatile string _hashSalt; private static readonly object SyncRoot = new object(); private int? _qualityOverride; /// /// Image height /// public int? Height { get; set; } /// /// Image width /// public int? Width { get; set; } /// /// Maximum height /// public int? MaxHeight { get; set; } /// /// Maximum width /// public int? MaxWidth { get; set; } /// /// Indicate if resizing options has a default or non-default quality setting (used when doing lossy compression). /// public bool CustomQuality => _qualityOverride.HasValue; /// /// Image quality (when doing lossy compression) /// public int Quality { get => _qualityOverride ?? GlobalSettingsFacade.ImageQuality; set { _qualityOverride = value; if (_qualityOverride < 1) { _qualityOverride = 1; } if (_qualityOverride > 100) { _qualityOverride = 100; } } } /// /// Resizing action /// public ResizingAction ResizingAction { get; set; } /// /// The preferred media type for the generated resized image. /// If the media type isn't supported, the original image will be returned. /// public string MediaType { get; set; } /// /// Indicates whether any options were specified /// public bool IsEmpty => Height == null && Width == null && MaxHeight == null && MaxWidth == null && _qualityOverride == null; /// public ResizingOptions() { } /// /// Parses resizing options from query string collection /// /// An instance of . /// The query string. /// Resizing options [Obsolete("Use an overload not taking an HttpServerUtility instance as a parameter")] public static ResizingOptions Parse(HttpServerUtility httpServerUtility, NameValueCollection queryString) { return Parse(queryString); } /// /// Parses resizing options from query string collection /// /// The query string. /// Resizing options public static ResizingOptions Parse(NameValueCollection queryString) { var resizingKey = queryString["k"]; return string.IsNullOrEmpty(resizingKey) ? FromQueryString(queryString) : new ResizingOptions(resizingKey); } /// internal ResizingOptions(string predefinedOptionsName) { //Load the xml file var options = GetPredefinedResizingOptions().Elements("image"); foreach (var e in options.Where(e => (string)e.Attribute("name") == predefinedOptionsName)) { Height = ParseOptionalIntAttribute(e, "height"); Width = ParseOptionalIntAttribute(e, "width"); MaxHeight = ParseOptionalIntAttribute(e, "maxheight"); MaxWidth = ParseOptionalIntAttribute(e, "maxwidth"); _qualityOverride = ParseOptionalIntAttribute(e, "quality"); var attr = e.Attribute("action"); if (attr != null) { ResizingAction = (ResizingAction)Enum.Parse(typeof(ResizingAction), attr.Value, true); } MediaType = (string) e.Attribute("mediaType"); } } private static int? ParseOptionalIntAttribute(XElement element, string attributeName) { var attribute = element.Attribute(attributeName); return attribute == null ? (int?)null : int.Parse(attribute.Value); } /// /// Gets resizing options from query string /// /// The query string. /// Resizing options private static ResizingOptions FromQueryString(NameValueCollection queryString) { var result = new ResizingOptions(); var str = queryString["w"]; if (!string.IsNullOrEmpty(str)) { result.Width = int.Parse(str); } str = queryString["h"]; if (!string.IsNullOrEmpty(str)) { result.Height = int.Parse(str); } str = queryString["mw"]; if (!string.IsNullOrEmpty(str)) { result.MaxWidth = int.Parse(str); } str = queryString["mh"]; if (!string.IsNullOrEmpty(str)) { result.MaxHeight = int.Parse(str); } str = queryString["q"]; if (!string.IsNullOrEmpty(str)) { result.Quality = int.Parse(str); } var action = queryString["action"]; if (!string.IsNullOrEmpty(action) && Enum.TryParse(action, true, out ResizingAction resizingAction)) { result.ResizingAction = resizingAction; } else { result.ResizingAction = ResizingAction.Stretch; } var mediaType = queryString["mt"]; if (!string.IsNullOrEmpty(mediaType)) { result.MediaType = mediaType; } return result; } private static XElement GetPredefinedResizingOptions() { //If it's not there, load the xml document and then add it to the cache if (!(HttpRuntime.Cache.Get("ResizedImageKeys") is XElement xel)) { if (_resizedImageKeysFilePath == null) { _resizedImageKeysFilePath = PathUtil.Resolve(ResizedImageKeys); } if (!C1File.Exists(_resizedImageKeysFilePath)) { var directoryPath = Path.GetDirectoryName(_resizedImageKeysFilePath); if (!C1Directory.Exists(directoryPath)) C1Directory.CreateDirectory(directoryPath); var config = new XElement("ResizedImages", new XElement("image", new XAttribute("name", "thumbnail"), new XAttribute("maxwidth", "100"), new XAttribute("maxheight", "100")), new XElement("image", new XAttribute("name", "normal"), new XAttribute("maxwidth", "200")), new XElement("image", new XAttribute("name", "large"), new XAttribute("maxheight", "300")) ); config.SaveToPath(_resizedImageKeysFilePath); } xel = XElementUtils.Load(_resizedImageKeysFilePath); var cd = new CacheDependency(_resizedImageKeysFilePath); var cacheExpirationTimeSpan = new TimeSpan(24, 0, 0); HttpRuntime.Cache.Add("ResizedImageKeys", xel, cd, Cache.NoAbsoluteExpiration, cacheExpirationTimeSpan, CacheItemPriority.Default, null); } return xel; } private static string GetHashSalt() { if (_hashSalt != null) return _hashSalt; lock (SyncRoot) { if (_hashSalt != null) return _hashSalt; string filePath = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.ConfigurationDirectory), ResizingOptionsConfigFileName); if (!C1File.Exists(filePath)) { var config = new XElement("ResizedImages", new XAttribute("hashSalt", Guid.NewGuid())); config.SaveToPath(filePath); } var xml = XElementUtils.Load(filePath); var hashSalt = (string)xml.Attribute("hashSalt"); if (hashSalt == null) throw new ConfigurationErrorsException("Missing required attribute 'hashSalt'", null, filePath, 0); return _hashSalt = hashSalt; } } /// public override string ToString() { var sb = new StringBuilder(); var parameters = new[] { Width, Height, MaxWidth, MaxHeight, _qualityOverride }; var parameterNames = new[] { "w", "h", "mw", "mh", "q" }; for (var i = 0; i < parameters.Length; i++) { if (parameters[i] == null) { continue; } sb.Append(sb.Length == 0 ? String.Empty : "&"); sb.Append(parameterNames[i]).Append("=").Append((int)parameters[i]); } if (ResizingAction != ResizingAction.Stretch) { sb.Append(sb.Length == 0 ? String.Empty : "&"); sb.Append("action=").Append(ResizingAction.ToString().ToLowerInvariant()); } if (!string.IsNullOrWhiteSpace(MediaType)) { sb.Append(sb.Length == 0 ? String.Empty : "&"); sb.Append("mt=").Append(MediaType); } return sb.ToString(); } /// /// Gets a secure hash for the current resizing options. The hash is salted with machine key and can be used to confirm that /// an image URL with resizing options was generated by the website. /// /// public string GetSecureHash(Guid mediaId) { var value = mediaId + this.ToString() + GetHashSalt(); var hash = HashingHelper.ComputeMD5Hash(value, Encoding.UTF8); return hash.ToString().Substring(0, 5); } } } ================================================ FILE: Composite/Core/WebClient/MediaUrlHelper.cs ================================================ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using Composite.Core.Extensions; using Composite.Core.Routing; using Composite.Core.Types; using Composite.Data; using Composite.Data.Caching; using Composite.Data.Types; using Composite.Plugins.Routing.InternalUrlConverters; namespace Composite.Core.WebClient { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class MediaUrlHelper { private static readonly string DefaultMediaStore = "MediaArchive"; private static readonly int MediaFileCacheSize = 2000; private static readonly Cache> _mediaFileCache = new Cache>("Media files", MediaFileCacheSize); static MediaUrlHelper() { void OnMediaFileChanged(object sender, DataEventArgs args) { if (args.Data is IMediaFile mediaFile) { _mediaFileCache.Remove(GetCacheKey(mediaFile.StoreId, mediaFile.Id)); } if (args.Data is IMediaFileData mediaFileData) { _mediaFileCache.Remove(GetCacheKey(DefaultMediaStore, mediaFileData.Id)); } } void OnStoreChanged(object sender, StoreEventArgs storeEventArgs) { if (!storeEventArgs.DataEventsFired) { _mediaFileCache.Clear(); } } DataEvents.OnAfterAdd += OnMediaFileChanged; DataEvents.OnAfterUpdate += OnMediaFileChanged; DataEvents.OnDeleted += OnMediaFileChanged; DataEvents.OnStoreChanged += OnStoreChanged; DataEvents.OnAfterAdd += OnMediaFileChanged; DataEvents.OnAfterUpdate += OnMediaFileChanged; DataEvents.OnDeleted += OnMediaFileChanged; DataEvents.OnStoreChanged += OnStoreChanged; } /// public static string GetUrl(IMediaFile file) => GetUrl(file, true, false); /// public static string GetUrl(IMediaFile file, bool isInternal) => GetUrl(file, isInternal, false); /// public static string GetUrl(IMediaFile file, bool isInternal, bool downloadableMedia) { string url = MediaUrls.BuildUrl(file, isInternal ? UrlKind.Internal : UrlKind.Public); if (!downloadableMedia) return url; var urlBuilder = new UrlBuilder(url) { ["download"] = "true" }; return urlBuilder.ToString(); } /// public static IMediaFile GetFileFromQueryString(NameValueCollection queryParameters) { Verify.ArgumentNotNull(queryParameters, nameof(queryParameters)); string idStr = queryParameters["id"]; // In order to support old-style queries, checking composite path in "i" and "src" query parameters string compositePath = queryParameters["i"]; if (compositePath.IsNullOrEmpty()) { compositePath = queryParameters["src"]; if (compositePath.IsNullOrEmpty() && idStr != null && idStr.Contains(":")) { compositePath = idStr; } } string storeId; IMediaFile result; if (!compositePath.IsNullOrEmpty()) { // Parsing a friendly media url int separatorIndex = compositePath.IndexOf(":", System.StringComparison.Ordinal); if (separatorIndex < 0 || separatorIndex == compositePath.Length - 1) throw new InvalidOperationException(); storeId = compositePath.Substring(0, separatorIndex); string secondPart = compositePath.Substring(separatorIndex + 1); try { if (Guid.TryParse(secondPart, out Guid fileId)) { result = GetFileById(storeId, fileId); } else { compositePath = compositePath.Replace("://", ":/"); result = GetFileByCompositePath(storeId, compositePath); } } catch (Exception ex) { throw new FileNotFoundException($"File '{compositePath}' was not found.", ex); } } else { // Parsing an internal media url storeId = queryParameters["store"] ?? DefaultMediaStore; if (storeId.IsNullOrEmpty() || idStr.IsNullOrEmpty()) { throw new InvalidOperationException("Missing id from query"); } Guid id = new Guid(idStr); try { result = GetFileById(storeId, id); } catch (Exception ex) { throw new FileNotFoundException($"File not found. Storage: '{storeId}', Id: {id}", ex); } } return result ?? throw new FileNotFoundException("File not found."); } internal static string GetCacheKey(string storeId, Guid fileId) => storeId + fileId; internal static IMediaFile GetFileById(string storeId, Guid fileId) { string cacheKey = GetCacheKey(storeId, fileId); var cachedValue = _mediaFileCache.Get(cacheKey); if (cachedValue != null) { return cachedValue.Value; } using (new DataScope(DataScopeIdentifier.Public)) { var query = DataFacade.GetData(); var result = query.IsEnumerableQuery() ? (query as IEnumerable).FirstOrDefault(f => f.Id == fileId && f.StoreId == storeId) : query.FirstOrDefault(f => f.StoreId == storeId && f.Id == fileId); _mediaFileCache.Add(cacheKey, new ExtendedNullable { Value = result }); return result; } } private static IMediaFile GetFileByCompositePath(string storeId, string compositePath) { using (new DataScope(DataScopeIdentifier.Public)) { var query = DataFacade.GetData(); if (query.IsEnumerableQuery()) { return (query as IEnumerable) .FirstOrDefault(f => f.CompositePath == compositePath && f.StoreId == storeId); } return query .FirstOrDefault(f => f.StoreId == storeId && f.CompositePath == compositePath); } } /// [Obsolete("Use Guid.TryParse()")] public static bool IsValidGuid(string value) => Guid.TryParse(value, out _); /// public static string ChangeInternalMediaUrlsToPublic(string content) { return InternalUrls.ConvertInternalUrlsToPublic(content, new[] { new MediaInternalUrlConverter() }); } } } ================================================ FILE: Composite/Core/WebClient/PageStructureRpc.cs ================================================ using Composite.Core.Application; using Composite.Core.WebClient.Services.WampRouter; using Composite.Plugins.Components.ComponentsEndpoint; using Composite.Plugins.Search.Endpoint; using WampSharp.V2.Rpc; namespace Composite.Core.WebClient { [ApplicationStartup] class ComponentsEndpoint { public static void OnInitialized() { WampRouterFacade.RegisterCallee(new PageStructureRpc()); } } /// /// Rpcs related to page structure /// public class PageStructureRpc : IRpcService { /// /// To get page structure by its name /// /// Page structure [WampProcedure("structure.page")] public object Get(string name) { // TODO: use an interface to resolve a page structure object if (name == "search") { return new ConsoleSearchPageStructure(); } return new ComponentsResponseMessage(); } } } ================================================ FILE: Composite/Core/WebClient/PageUrlHelper.cs ================================================ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.Linq; using System.Web; using System.Xml.Linq; using Composite.Core.Routing; using Composite.Data; using Composite.Data.Types; using Composite.Core.WebClient.Renderings.Page; using Composite.Core.Extensions; using Composite.Plugins.Routing.InternalUrlConverters; namespace Composite.Core.WebClient { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Use 'Composite.Data' namespace instead")] public sealed class PageUrlOptions { /// public PageUrlOptions(string dataScopeIdentifierName, CultureInfo locale, Guid pageId) : this(dataScopeIdentifierName, locale, pageId, UrlType.Undefined) { } /// public PageUrlOptions(string dataScopeIdentifierName, CultureInfo locale, Guid pageId, UrlType urlType) { Verify.ArgumentNotNullOrEmpty(dataScopeIdentifierName, "dataScopeIdentifierName"); Verify.ArgumentNotNull(locale, "locale"); Verify.ArgumentCondition(pageId != Guid.Empty, "pageId", "PageId should not be an empty guid."); DataScopeIdentifierName = dataScopeIdentifierName; Locale = locale; PageId = pageId; UrlType = urlType; } /// public UrlType UrlType { get; private set; } /// public string DataScopeIdentifierName { get; private set; } /// public CultureInfo Locale { get; private set; } /// public Guid PageId { get; private set; } /// public DataScopeIdentifier DataScopeIdentifier { get { return DataScopeIdentifier.Deserialize(DataScopeIdentifierName); } } /// public IPage GetPage() { var dataScope = DataScopeIdentifier.Deserialize(DataScopeIdentifierName); using (new DataScope(dataScope, Locale)) { return PageManager.GetPageById(PageId); } } } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Use 'Composite.Data' namespace instead")] public enum UrlType { /// Undefined = 0, /// Public = 1, /// Internal = 2, /// Friendly = 3 } /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PageUrlHelper { /// [Obsolete("Use Composite.Data.PageUrl instead")] public static PageUrlOptions ParseUrl(string url) { var urlString = new UrlString(url); return IsPublicUrl(urlString) ? ParsePublicUrl(url) : ParseInternalUrl(url); } /// [Obsolete("Use Composite.Data.PageUrl instead")] public static PageUrlOptions ParseUrl(string url, out NameValueCollection notUsedQueryStringParameters) { return IsPublicUrl(url) ? ParsePublicUrl(url, out notUsedQueryStringParameters) : ParseInternalUrl(url, out notUsedQueryStringParameters); } /// [Obsolete("Use Composite.Data.PageUrl instead")] public static PageUrlOptions ParseInternalUrl(string url) { NameValueCollection notUsedQueryStringParameters; return ParseInternalUrl(url, out notUsedQueryStringParameters); } /// [Obsolete("Use Composite.Data.PageUrl instead")] public static PageUrlOptions ParseInternalUrl(string url, out NameValueCollection notUsedQueryStringParameters) { var urlString = new UrlString(url); return ParseQueryString(urlString.GetQueryParameters(), out notUsedQueryStringParameters); } /// [Obsolete("Use Composite.Data.PageUrl instead")] public static PageUrlOptions ParsePublicUrl(string url) { NameValueCollection notUsedQueryParameters; return ParsePublicUrl(url, out notUsedQueryParameters); } /// [Obsolete("Use Composite.Data.PageUrl instead")] public static PageUrlOptions ParsePublicUrl(string url, out NameValueCollection notUsedQueryParameters) { var urlString = new UrlString(url); notUsedQueryParameters = null; if (!IsPublicUrl(urlString.FilePath)) { return null; } string requestPath; Uri uri; if (Uri.TryCreate(urlString.FilePath, UriKind.Absolute, out uri)) { requestPath = HttpUtility.UrlDecode(uri.AbsolutePath).ToLower(); } else { requestPath = urlString.FilePath.ToLower(); } string requestPathWithoutUrlMappingName; CultureInfo locale = PageUrl.GetCultureInfo(requestPath, out requestPathWithoutUrlMappingName); if (locale == null) { return null; } string dataScopeName = urlString["dataScope"]; if(dataScopeName.IsNullOrEmpty()) { dataScopeName = DataScopeIdentifier.GetDefault().Name; } Guid pageId = Guid.Empty; using (new DataScope(DataScopeIdentifier.Deserialize(dataScopeName), locale)) { if (PageStructureInfo.GetLowerCaseUrlToIdLookup().TryGetValue(requestPath.ToLower(), out pageId) == false) { return null; } } urlString["dataScope"] = null; notUsedQueryParameters = urlString.GetQueryParameters(); return new PageUrlOptions(dataScopeName, locale, pageId, UrlType.Public); } /// [Obsolete("To be removed")] public static CultureInfo GetCultureInfo(string requestPath) { string newRequestPath; return PageUrl.GetCultureInfo(requestPath, out newRequestPath); } /// [Obsolete("To be removed")] public static CultureInfo GetCultureInfo(string requestPath, out string requestPathWithoutUrlMappingName) { return PageUrl.GetCultureInfo(requestPath, out requestPathWithoutUrlMappingName); } /// [Obsolete("To be removed")] public static bool IsPublicUrl(string relativePath) { relativePath = relativePath.ToLower(); return relativePath.Contains(".aspx") && !relativePath.Contains("/renderers/page.aspx") && !IsAdminPath(relativePath); } /// [Obsolete("To be removed")] public static bool IsPublicUrl(UrlString url) { return IsPublicUrl(url.FilePath); } /// public static bool IsInternalUrl(string url) { return IsInternalUrl(new UrlBuilder(url)); } /// [Obsolete("To be removed")] public static bool IsInternalUrl(UrlString url) { return url.FilePath.EndsWith("Renderers/Page.aspx", true); } private static bool IsInternalUrl(UrlBuilder url) { return url.FilePath.EndsWith("Renderers/Page.aspx", true); } /// [Obsolete("Use Composite.Data.PageUrl.Build() instead")] public static UrlString BuildUrl(PageUrlOptions options) { Verify.ArgumentNotNull(options, "options"); Verify.ArgumentCondition(options.UrlType != UrlType.Undefined, "options", "Url type is undefined"); return BuildUrl(options.UrlType, options); } /// [Obsolete("To be removed")] public static bool IsAdminPath(string relativeUrl) { return string.Compare(relativeUrl, UrlUtils.AdminRootPath, true) == 0 || relativeUrl.StartsWith(UrlUtils.AdminRootPath + "/", true); } /// [Obsolete("Use Composite.Data.PageUrl.Build() instead")] public static UrlString BuildUrl(UrlType urlType, PageUrlOptions options) { Verify.ArgumentNotNull(options, "options"); Verify.ArgumentCondition(urlType != UrlType.Undefined, "urlType", "Url type is undefined"); if (urlType == UrlType.Public) { var lookupTable = PageStructureInfo.GetIdToUrlLookup(options.DataScopeIdentifierName, options.Locale); if (!lookupTable.ContainsKey(options.PageId)) { return null; } var publicUrl = new UrlString(lookupTable[options.PageId]); if(options.DataScopeIdentifierName != DataScopeIdentifier.GetDefault().Name) { publicUrl["dataScope"] = options.DataScopeIdentifierName; } return publicUrl; } if(urlType == UrlType.Internal) { string basePath = UrlUtils.ResolvePublicUrl("Renderers/Page.aspx"); var result = new UrlString(basePath); result["pageId"] = options.PageId.ToString(); result["cultureInfo"] = options.Locale.ToString(); result["dataScope"] = options.DataScopeIdentifierName; return result; } throw new NotImplementedException("BuildUrl function supports only 'Public' and 'Unternal' urls."); } /// [Obsolete("To be removed, use Composite.Data.PageUrl.TryParseFriendlyUrl(...) instead")] public static bool TryParseFriendlyUrl(string relativeUrl, out PageUrlOptions urlOptions) { if (IsAdminPath(relativeUrl)) { urlOptions = null; return false; } string path; CultureInfo cultureInfo = PageUrl.GetCultureInfo(relativeUrl, out path); if (cultureInfo == null) { urlOptions = null; return false; } string loweredRelativeUrl = relativeUrl.ToLower(CultureInfo.InvariantCulture); // Getting the site map IEnumerable siteMap; DataScopeIdentifier dataScope = DataScopeIdentifier.GetDefault(); using (new DataScope(dataScope, cultureInfo)) { siteMap = PageStructureInfo.GetSiteMap(); } XAttribute matchingAttributeNode = siteMap.DescendantsAndSelf() .Attributes("FriendlyUrl") .FirstOrDefault(f => string.Equals(f.Value, loweredRelativeUrl, StringComparison.OrdinalIgnoreCase)); if(matchingAttributeNode == null) { urlOptions = null; return false; } XElement pageNode = matchingAttributeNode.Parent; XAttribute pageIdAttr = pageNode.Attributes("Id").FirstOrDefault(); Verify.IsNotNull(pageIdAttr, "Failed to get 'Id' attribute from the site map"); Guid pageId = new Guid(pageIdAttr.Value); urlOptions = new PageUrlOptions(dataScope.Name, cultureInfo, pageId, UrlType.Friendly); return true; } /// /// To be used for handling 'internal' links. /// /// Query string. /// Query string parameters that were not used. /// [Obsolete("To be removed. Use Composite.Core.Routing.PageUrls instead.")] public static PageUrlOptions ParseQueryString(NameValueCollection queryString, out NameValueCollection notUsedQueryParameters) { if (string.IsNullOrEmpty(queryString["pageId"])) throw new InvalidOperationException("Invalid query string. The 'pageId' parameter of the GUID type is expected."); string dataScopeName = queryString["dataScope"] ?? DataScopeIdentifier.PublicName; string cultureInfoStr = queryString["cultureInfo"]; if(cultureInfoStr.IsNullOrEmpty()) { cultureInfoStr = queryString["CultureInfo"]; } CultureInfo cultureInfo; if (!cultureInfoStr.IsNullOrEmpty()) { cultureInfo = new CultureInfo(cultureInfoStr); } else { cultureInfo = LocalizationScopeManager.CurrentLocalizationScope; if(cultureInfo.Equals(CultureInfo.InvariantCulture)) { cultureInfo = DataLocalizationFacade.DefaultLocalizationCulture; } } Guid pageId = new Guid(queryString["pageId"]); notUsedQueryParameters = new NameValueCollection(); var queryKeys = new[] { "pageId", "dataScope", "cultureInfo", "CultureInfo" }; var notUsedKeys = queryString.AllKeys.Where(key => !queryKeys.Contains(key, StringComparer.InvariantCultureIgnoreCase)); foreach (string key in notUsedKeys) { notUsedQueryParameters.Add(key, queryString[key]); } return new PageUrlOptions(dataScopeName, cultureInfo, pageId, UrlType.Internal); } /// public static string ChangeRenderingPageUrlsToPublic(string html) { return InternalUrls.ConvertInternalUrlsToPublic(html, new[] {new PageInternalUrlConverter()}); } /// /// "PathInfo" it is a part between aspx page path /// /// /// internal static string GetPathInfoFromInternalUrl(string url) { // From string ".../Renderers/Page.aspx/AAAA/VVV/CCC?pageId=..." will extract "/AAAA/VVV/CCC" int aspxOffset = url.IndexOf(".aspx", StringComparison.Ordinal); if(url[aspxOffset + 5] == '?') return null; return url.Substring(aspxOffset + 5, url.IndexOf('?', aspxOffset + 6) - aspxOffset - 5); } } } ================================================ FILE: Composite/Core/WebClient/PhantomJs/PhantomServer.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.Serialization.Json; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Hosting; using Composite.Core.Application; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Parallelization; namespace Composite.Core.WebClient.PhantomJs { /// /// Contains information about currently running instance of a PhantomJS server /// internal class PhantomServer : IDisposable { private const string LogTitle = nameof(PhantomServer); private const string EndOfReplyMarker = "END_OF_REPLY"; const string ConfigFileName = "config.json"; const string ScriptFileName = "renderingServer.js"; static readonly string _phantomJsFolder = HostingEnvironment.MapPath("~/App_Data/Composite/PhantomJs"); static readonly string _phantomJsPath = Path.Combine(_phantomJsFolder, "phantomjs.exe"); private readonly StreamWriter _stdin; private readonly StreamReader _stdout; private readonly StreamReader _stderror; private readonly Process _process; private readonly Job _job; private static PhantomServer _instance; private static readonly AsyncLock _instanceAsyncLock = new AsyncLock(); [SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] private PhantomServer() { var tempDirectory = PathUtil.Resolve(GlobalSettingsFacade.TempDirectory); var cachePath = Path.Combine(tempDirectory, "phantomjs_cache"); var localStoragePath = Path.Combine(tempDirectory, "phantomjs_ls"); _process = new Process { StartInfo = { WorkingDirectory = _phantomJsFolder, FileName = "\"" + _phantomJsPath + "\"", Arguments = $"\"--local-storage-path={localStoragePath}\" \"--disk-cache-path={cachePath}\" --config={ConfigFileName} {ScriptFileName}", RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true, CreateNoWindow = true, StandardOutputEncoding = Encoding.UTF8, UseShellExecute = false, WindowStyle = ProcessWindowStyle.Hidden } }; _process.Start(); _stdin = _process.StandardInput; _stdout = _process.StandardOutput; _stderror = _process.StandardError; _stdin.AutoFlush = true; _job = new Job(); _job.AddProcess(_process.Handle); } public static void ShutDown(bool alreadyLocked, bool silent = false) { PhantomServer ps; using (alreadyLocked ? null : _instanceAsyncLock.Lock()) { if (_instance == null) { return; } ps = _instance; _instance = null; } ps.DisposeInternal(silent); GC.SuppressFinalize(ps); } // Ensures that an instance have been started //public async static Task StartAsync() //{ // using (await _instanceAsyncLock.LockAsync()) // { // var instance = PhantomServer.Instance; // } //} private static PhantomServer Instance { get { return _instance ?? (_instance = new PhantomServer()); } } public static async Task RenderUrlAsync(HttpCookie[] cookies, string url, string outputImageFilePath, string mode) { url = url.Replace(" ", "%20"); // Preventing a redirect in PhantomJS using (await _instanceAsyncLock.LockAsync()) { var renderingResult = Instance.RenderUrlImpl(cookies, url, outputImageFilePath, mode); if (renderingResult.Status == RenderingResultStatus.PhantomServerTimeout || renderingResult.Status == RenderingResultStatus.PhantomServerIncorrectResponse || renderingResult.Status == RenderingResultStatus.PhantomServerNoOutput) { Log.LogWarning(LogTitle, "Shutting down PhantomJs server. Reason: {0}, Output: {1}", renderingResult.Status, string.Join(Environment.NewLine, renderingResult.Output)); try { ShutDown(true); } catch (Exception shutdownException) { Log.LogError(LogTitle, shutdownException); } } return renderingResult; } } private bool IsEndOfReply(string line) { return line.StartsWith(EndOfReplyMarker); } private RenderingResult RenderUrlImpl(HttpCookie[] cookies, string url, string outputImageFilePath, string mode) { Verify.ArgumentNotNull(cookies, nameof(cookies)); string cookieDomain = new Uri(url).Host; var request = new RenderPreviewRequest { requestId = "1", mode = mode, url = url, outputFilePath = outputImageFilePath, cookies = cookies.Select(cookie => new CookieInformation { name = cookie.Name, value = cookie.Value, domain = cookieDomain }).ToArray() }; var ms = new MemoryStream(); var ser = new DataContractJsonSerializer(typeof(RenderPreviewRequest)); ser.WriteObject(ms, request); var json = Encoding.UTF8.GetString(ms.ToArray()); var output = new List(); Task readerTask = Task.Run(() => { _stdin.WriteLine(json); string line; do { line = _stdout.ReadLine(); lock (output) { output.Add(line); } } while (!IsEndOfReply(line)); }); var secondsSinceStartup = (DateTime.Now - _process.StartTime).TotalSeconds; double timeout = secondsSinceStartup < 120 || mode == "test" ? 65 : 30; readerTask.Wait(TimeSpan.FromSeconds(timeout)); // TODO: check for theother task statuses switch (readerTask.Status) { case TaskStatus.RanToCompletion: if (output.Count == 0) { return new RenderingResult { Status = RenderingResultStatus.PhantomServerNoOutput, Output = new [] { "(null)" } }; } break; default: string[] outputCopy; lock (output) { outputCopy = output.ToArray(); } string logMessage = "Request failed to complete within expected time: " + #if DEBUG json #else url + " " + mode #endif ; return new RenderingResult { Status = RenderingResultStatus.PhantomServerTimeout, Output = new [] { logMessage}.Concat(outputCopy).ToArray(), FilePath = outputImageFilePath }; } if (C1File.Exists(outputImageFilePath)) { return new RenderingResult { Status = RenderingResultStatus.Success, Output = output, FilePath = outputImageFilePath }; } var lastMessage = output.Last(); if (!lastMessage.StartsWith(EndOfReplyMarker)) { Log.LogError(LogTitle, $"Missing {EndOfReplyMarker} in the response"); } string redirectUrl = null; RenderingResultStatus? status = null; foreach (var line in output) { const string redirectResponsePrefix = "REDIRECT: "; if (line == "SUCCESS") { status = RenderingResultStatus.Success; } else if (line.StartsWith(redirectResponsePrefix)) { status = RenderingResultStatus.Redirect; redirectUrl = line.Substring(redirectResponsePrefix.Length); } else if (line.StartsWith("TIMEOUT: ")) { status = RenderingResultStatus.Timeout; } else if (line.StartsWith("ERROR: ")) { status = RenderingResultStatus.Error; } } status = status ?? RenderingResultStatus.PhantomServerIncorrectResponse; return new RenderingResult { Status = status.Value, Output = output, RedirectUrl = redirectUrl }; } public static string ScriptFilePath { get { return Path.Combine(_phantomJsFolder, ScriptFileName); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #if LeakCheck private string stack = Environment.StackTrace; #endif ~PhantomServer() { #if LeakCheck Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); #endif // Finalizer calls Dispose(false) Dispose(false); } void Dispose(bool disposing) { if (!disposing) { return; } DisposeInternal(false); } void DisposeInternal(bool silent) { bool processHasExited; try { processHasExited = _process.HasExited; } catch (Exception) { processHasExited = true; } if (!processHasExited) { _stdin.WriteLine("exit"); } bool streamsClosed = false; Task errorFeedbackTask = null; string processOutputSummary = null; if (!silent) { errorFeedbackTask = Task.Factory.StartNew(() => { try { if (streamsClosed) { // Simplifies debugging return null; } string stdOut = _stdout.ReadToEnd(); string stdError = _stderror.ReadToEnd(); string result = !string.IsNullOrEmpty(stdOut) ? $"stdout: '{stdOut}'" : ""; if (!string.IsNullOrWhiteSpace(stdError)) { if (result.Length > 0) { result += Environment.NewLine; } result += $"stderr: {stdError}"; } return result; } catch (Exception ex) { return ex.Message; } }); errorFeedbackTask.Wait(500); processOutputSummary = errorFeedbackTask.Status == TaskStatus.RanToCompletion ? errorFeedbackTask.Result : "Process Hang"; } if (!processHasExited) { try { processHasExited = _process.HasExited; } catch (Exception) { processHasExited = true; } if (!processHasExited) { streamsClosed = true; _stdin.Close(); _stdout.Close(); _stderror.Close(); _process.Kill(); _process.WaitForExit(500); } } int exitCode = _process.ExitCode; streamsClosed = true; _stdin.Dispose(); _stdout.Dispose(); _stderror.Dispose(); _process.Dispose(); _job.Dispose(); bool meaningfullExitCode = exitCode != 0 && exitCode != -1073741819 /* Access violation, the ExitCode property returns this value by default for some reason */; if (silent) { return; } if (meaningfullExitCode || errorFeedbackTask.Status != TaskStatus.RanToCompletion || !string.IsNullOrEmpty(processOutputSummary)) { string errorMessage = "Error executing PhantomJs.exe"; if (meaningfullExitCode) errorMessage += "; Exit code: {0}".FormatWith(exitCode); if (!string.IsNullOrEmpty(processOutputSummary)) { errorMessage += Environment.NewLine + processOutputSummary; } throw new InvalidOperationException(errorMessage); } } } } ================================================ FILE: Composite/Core/WebClient/PhantomJs/RenderPreviewRequest.cs ================================================ using System.Runtime.Serialization; namespace Composite.Core.WebClient.PhantomJs { [DataContract] internal class CookieInformation { [DataMember] public string name { get; set; } [DataMember] public string value { get; set; } [DataMember] public string domain { get; set; } } [DataContract] internal class RenderPreviewRequest { [DataMember] public string requestId { get; set; } [DataMember] public string mode { get; set; } [DataMember] public string url { get; set; } [DataMember] public string outputFilePath { get; set; } [DataMember] public CookieInformation[] cookies { get; set; } } } ================================================ FILE: Composite/Core/WebClient/PhantomJs/RenderingResult.cs ================================================ using System.Collections.Generic; namespace Composite.Core.WebClient.PhantomJs { internal class RenderingResult { public RenderingResultStatus Status { get; set; } public string FilePath { get; set; } public ICollection Output { get; set; } public string RedirectUrl { get; set; } } } ================================================ FILE: Composite/Core/WebClient/PhantomJs/RenderingResultStatus.cs ================================================ namespace Composite.Core.WebClient.PhantomJs { internal enum RenderingResultStatus { Success = 0, Redirect = 1, Error = 2, Timeout = 3, PhantomServerTimeout = 4, PhantomServerIncorrectResponse = 5, PhantomServerNoOutput = 6 } } ================================================ FILE: Composite/Core/WebClient/Presentation/CssRequestHandler.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Web; using Composite.Core.IO; /* * Important notice: This setup has been hardwired to handle MY personal * CSS authoring preferences (formatting and indentation etc). Also notice * that the excecptionhanding is currently miserable, CSS author can easily * fire an indexOutOfBounds and stuff. For now, please use my precise syntax. */ namespace Composite.Core.WebClient.Presentation { class CssRequestHandler : IHttpHandler { // carries browser and platform info private class User { public bool isMozilla = false, isWebKit = false, isOpera = false, isIE = false, isIE6 = false, isIE7 = false, isIE8 = false, isIE9 = false, isVista = false, isOSX = false, isDefault = false; public User(HttpContext context) { string agent = context.Request.UserAgent ?? string.Empty; this.isIE = agent.Contains("MSIE")/* || agent.Contains("Trident")*/; this.isIE6 = agent.Contains("MSIE 6"); this.isIE7 = agent.Contains("MSIE 7"); this.isIE8 = agent.Contains("MSIE 8"); this.isIE9 = agent.Contains("MSIE 9"); this.isWebKit = agent.Contains ( "WebKit" ); this.isOpera = agent.Contains ( "Opera" ); // NOTE: WEBKIT AND OPERA IS MOZILLA FOR NOW!!! this.isMozilla = !this.isIE; // && !this.isWebKit && !this.isOpera; // analyze os this.isVista = agent.Contains("NT 6"); // Windows7 now counts as Vista! this.isOSX = agent.Contains("OS X"); this.isDefault = !this.isVista && !this.isOSX; /* // analyze browser this.isMozilla = agent.Contains("Gecko"); this.isIE = !this.isMozilla; this.isIE6 = this.isIE && agent.Contains("MSIE 6"); this.isIE7 = this.isIE && agent.Contains("MSIE 7"); this.isIE8 = this.isIE && agent.Contains("MSIE 8"); this.isIE9 = this.isIE && agent.Contains("MSIE 9"); */ } } // stores various variables while iterating lines private class State { public string rootPath { get; private set; } public string skinPath { get; private set; } public string folderPath { get; private set; } public bool isValid = true; public State(HttpContext context) { // the root of the administratin console this.rootPath = UrlUtils.AdminRootPath; // the root of the skin folder - hardcoded for now this.skinPath = UrlUtils.AdminRootPath + "/skins/system"; // the folder of the currently parsed CSS file this.folderPath = Path.GetDirectoryName(context.Request.Path).Replace('\\', '/'); } } private class Colors { private Dictionary scheme = new Dictionary(); public Colors ( User user ) { scheme.Add("threedface", "#FFFFFF"); scheme.Add("threedshadow", "#DDDDDD"); scheme.Add("threedlightshadow", "rgb(227,227,227)"); scheme.Add("threedhighlight", "rgb(255,255,255)"); scheme.Add("threeddarkshadow", "rgb(105,105,105)"); scheme.Add("highlighttext", "rgb(255,255,255)"); scheme.Add("highlight", "rgb(51,153,255)"); scheme.Add("appworkspace", "rgb(171,171,171)"); scheme.Add("graytext", "rgb(109,109,109)"); scheme.Add("infobackground", "rgb(255,255,225)"); scheme.Add("infotext", "rgb(0,0,0)"); scheme.Add("menutext", "rgb(0,0,0)"); scheme.Add("menu", "rgb(240,240,240)"); scheme.Add("windowtext", "rgb(0,0,0)"); scheme.Add("window", "rgb(250,250,250)"); scheme.Add("toolbar", "#D3DAED"); // c1 special! /* scheme.Add ( "buttonface", "pink" ); scheme.Add ( "buttonhighlight", "pink"); scheme.Add ( "buttonshadow", "pink" ); scheme.Add("buttontext", "pink"); */ } public string get (string key) { key = key.ToLowerInvariant(); string result = key; if ( scheme.ContainsKey ( key )) { result = scheme[key]; } return result; } } public bool IsReusable { get { return false; } } /** * Process request. */ public void ProcessRequest(HttpContext context) { if (CookieHandler.Get("mode") == "develop") { context.Response.Cache.SetExpires(DateTime.Now.AddMonths(-1)); context.Response.Cache.SetCacheability(HttpCacheability.NoCache); } else { context.Response.Cache.SetExpires(DateTime.Now.AddMonths(1)); context.Response.Cache.SetCacheability(HttpCacheability.Private); } string webPath = context.Request.Path; string cssPath = webPath.Substring(0, webPath.LastIndexOf(".aspx")); string filePath = context.Server.MapPath(cssPath); context.Response.ContentType = "text/css"; State state = new State( context ); User user = new User ( context ); Colors colors = new Colors (user); if (C1File.Exists(filePath)) { var sb = new StringBuilder(); string[] lines = C1File.ReadAllLines(filePath); foreach (string line in lines) { // context.Response.Write ( "/*" + line.ToString() + "*/" + "\n" ); string result = Parse(line, user, state, colors); if (result != null) { sb.Append(result).Append("\n"); } } context.Response.Write ( sb.ToString() ); } else { // Make it obvious that there is some kind of css fåk up. context.Response.Write("body { border: 1px solid red ! important; }"); context.Response.StatusCode = 404; } } /** * Parse a sigle line */ private string Parse(string line, User user, State state, Colors colors) { string trim = line.Trim(); if (trim.Length == 0) return null; char firstChar = trim[0]; if (firstChar == '#' && trim.StartsWith("#endregion", StringComparison.Ordinal)) { state.isValid = true; return null; } if (!state.isValid) { return null; } if (firstChar == '-' && trim.StartsWith("-vendor-", StringComparison.Ordinal)) { String was = line; if (user.isWebKit) { line = line.Replace("-vendor-", "-webkit-"); } else if (user.isMozilla) { line = line.Replace("-vendor-", "-moz-"); } else if (user.isOpera) { line = line.Replace("-vendor-", "-o-"); } else { line = line.Replace("-vendor-", "-ms-"); } line += "\n" + was.Replace("-vendor-", ""); } if (firstChar == '#' && trim.StartsWith("#region", StringComparison.Ordinal)) { if ( trim.IndexOf ( " " ) >-1 ) { string statement = trim.Split(' ')[ 1 ]; switch (statement) { case "vista" : state.isValid = user.isVista; break; case "osx" : state.isValid = user.isOSX; break; case "default" : state.isValid = user.isDefault; break; case "moz" : state.isValid = user.isMozilla; break; case "ie" : state.isValid = !user.isMozilla; break; case "ie6" : state.isValid = user.isIE6; break; } } return null; } if (firstChar == '@') { string statement = line.Substring(0, line.IndexOf(" ")); switch (statement) { case "@import": string url = getURLPart ( line ); line = line.Replace(url, url + ".aspx"); break; case "@namespace" : line = user.isMozilla ? line : null; break; } } else if (firstChar == '#') { string originalLine = line; string statement = line.Substring(0, line.IndexOf(" ")); line = line.Substring(statement.Length + 1); // cutting statement and the following space switch (statement.Trim()) { case "#ie": line = user.isIE ? line : null; break; case "#ie6": line = user.isIE6 ? line : null; break; case "#ie7": line = user.isIE7 ? line : null; break; case "#ie8": line = user.isIE8 ? line : null; break; case "#moz": line = user.isMozilla ? line : null; break; case "#opacity:": string value = getValuePart(line); line = "opacity: " + value + ";"; break; case "#alphabackdrop:": string url = getURLPart(line); line = "background-image: url(\"" + url + "\");"; break; case "#alphaimage:": string url2 = getURLPart(line); line = "background-image: url(\"" + url2 + "\"); background-repeat: no-repeat;"; break; default: // Line may contain an identifier line = originalLine; break; } } if (line != null) { if (!user.isMozilla) { line = line.Replace("ui|", string.Empty); } if(line.Contains("$")) { line = line.Replace("${root}", state.rootPath) .Replace("${folder}", state.folderPath) .Replace("${skin}", state.skinPath); while (line.Contains("$(color:")) { line = colorize(line, colors); } } } return line; } private string colorize (string line, Colors colors ) { string START = "$(color:"; string STOP = ")"; int index1 = line.IndexOf(START); string before = line.Substring(0,index1); string after = line.Substring(index1 , line.Length - index1); int index2 = after.IndexOf(STOP); string final = after.Substring(index2 + 1, after.Length - (index2 + 1)); string key = after.Substring( START.Length, after.Length - START.Length - ( after.Length - index2 )); line = before + colors.get ( key ) + final; return line; } /** * Isolate URL part of a line */ private string getURLPart(string line) { return line.Split('\"')[1]; } /** * Isolate value part of a line */ private string getValuePart(string line) { string two = line.Split(';')[0]; return two.Trim(); } // * // * Isolate $ notation part of a line // */ //private string getVarPart (string line) //{ // string result = line; // if ( line.Contains ( "${" ) && line.Contains ( "}" )) { // int start = line.LastIndexOf("${"); // int stop = line.LastIndexOf("}"); // result = line.Substring(start, stop - start + 1); // } // return result; //} } } ================================================ FILE: Composite/Core/WebClient/Presentation/OutputTransformationManager.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Web.Caching; using System.Web.Hosting; using System.Xml; using System.Xml.Xsl; using Composite.Core.Application; using Composite.Core.Extensions; using Composite.Core.IO; namespace Composite.Core.WebClient.Presentation { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class OutputTransformationManager { private const string _contextItemKey = "AdministrativeOutputTransformationHttpModule.TransformationList"; /// public static void Activate() { EnsureResponseFilter(); } /// public static void RegisterTransformation(string transformationPath, int position) { HttpContext context = HttpContext.Current; if (context.Items.Contains(_contextItemKey) == false) throw new InvalidOperationException("Activate must be called first"); List transformations = (List)context.Items[_contextItemKey]; transformations.Add(new Transformation { TransformationPath = transformationPath, Position = position }); } internal static IEnumerable GetTransformationsInPriority() { HttpContext context = HttpContext.Current; if (context.Items.Contains(_contextItemKey) == false) throw new InvalidOperationException("Activate must be called first"); List transformations = (List)context.Items[_contextItemKey]; foreach (Transformation transformation in transformations.OrderBy(f => f.Position)) { yield return transformation.TransformationPath; } } private static void EnsureResponseFilter() { HttpContext context = HttpContext.Current; if (context.Items.Contains(_contextItemKey) == false) { context.Response.Filter = new XslTransformationStream(context.Response.Filter); context.Items.Add(_contextItemKey, new List()); } } #region Helper classes private class Transformation { public string TransformationPath { get; set; } public int Position { get; set; } } private class XslTransformationStream : Stream { public XslTransformationStream(Stream outputStream) { _buffer = new MemoryStream(8192); _responseOutputStream = outputStream; } private readonly Stream _responseOutputStream; private readonly MemoryStream _buffer; /* * Moth knows about the ugly parameters, please refactor! * We should probably supply XSLT params by webcontrol markup... */ public static MemoryStream Transform(MemoryStream buffer, String mode, String browser, String platform) { List xsltFilePaths = GetTransformationsInPriority().ToList(); if (xsltFilePaths.Count == 0) { return buffer; } // Detection doctype buffer.Seek(0, SeekOrigin.Begin); string line; using (var reader = new StreamReader(buffer, Encoding.UTF8, true, 1024, true)) { line = reader.ReadLine(); } var doctype = line.Contains(" -1 /*&& !userAgent.Contains("Trident")*/) { browser = "mozilla"; } else { browser = "explorer"; } if (userAgent.IndexOf("Windows NT", StringComparison.Ordinal) > -1) { platform = "vista"; } else if (userAgent.IndexOf("OS X", StringComparison.Ordinal) > -1) { platform = "osx"; } else { platform = "default"; } } output = Transform(_buffer, mode, browser, platform); } catch (Exception ex) { Log.LogCritical("AdministrativeOutputTransformationHttpModule", ex); throw; } } if(output.Position != 0) { output.Seek(0, SeekOrigin.Begin); } output.WriteTo(_responseOutputStream); } finally { _responseOutputStream.Close(); } } public override bool CanRead => _responseOutputStream.CanRead; public override bool CanSeek => _responseOutputStream.CanSeek; public override bool CanWrite => _responseOutputStream.CanWrite; public override long Length => _responseOutputStream.Length; public override long Position { get { return _responseOutputStream.Position; } set { _responseOutputStream.Position = value; } } public override long Seek(long offset, SeekOrigin origin) { return _responseOutputStream.Seek(offset, origin); } public override void SetLength(long value) { _responseOutputStream.SetLength(value); } public override void Flush() { _responseOutputStream.Flush(); } public override int Read(byte[] buffer, int offset, int count) { return _responseOutputStream.Read(buffer, offset, count); } } #endregion } } ================================================ FILE: Composite/Core/WebClient/Presentation/ViewServices.cs ================================================ using System.Web; namespace Composite.Core.WebClient.Presentation { /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ViewServices { private static HttpRequest Request { get { return HttpContext.Current.Request; } } private static HttpResponse Response { get { return HttpContext.Current.Response; } } /// /// For ~/Composite requests - register basix XSL transformations /// public static void RegisterCommonTransformations() { OutputTransformationManager.Activate(); OutputTransformationManager.RegisterTransformation( Request.MapPath("~/Composite/transformations/defaultfilters/structurefilter.xsl"), 1); OutputTransformationManager.RegisterTransformation( Request.MapPath("~/Composite/transformations/defaultfilters/masterfilter.xsl"), 10); OutputTransformationManager.RegisterTransformation( Request.MapPath("~/Composite/transformations/defaultfilters/finalizefilter.xsl"), 20); } /// public static void RegisterMimeType() { if (Request.UserAgent != null && !Request.UserAgent.Contains("MSIE")) { Response.ContentType = "application/xhtml+xml"; } } } } ================================================ FILE: Composite/Core/WebClient/Renderings/CultureExtrator.cs ================================================ using System; using System.Globalization; using System.Linq; using Composite.Data; using Composite.Core.WebClient; namespace Composite.Core.WebClient.Renderings { [Obsolete("No longer used")] internal static class CultureExtrator { public static CultureInfo GetCultureInfo(string requestPath) { string newRequestPath; return GetCultureInfo(requestPath, out newRequestPath); } public static CultureInfo GetCultureInfo(string requestPath, out string requestPathWithoutUrlMappingName) { requestPathWithoutUrlMappingName = requestPath; int startIndex = requestPath.IndexOf('/', UrlUtils.PublicRootPath.Length) + 1; if (startIndex >= 0) { int endIndex = requestPath.IndexOf('/', startIndex) - 1; if (endIndex >= 0) { string urlMappingName = requestPath.Substring(startIndex, endIndex - startIndex + 1).ToLowerInvariant(); if (DataLocalizationFacade.UrlMappingNames.Contains(urlMappingName)) { CultureInfo cultureInfo = DataLocalizationFacade.GetCultureInfoByUrlMappingName(urlMappingName); bool exists = DataLocalizationFacade.ActiveLocalizationNames.Contains(cultureInfo.Name); if (exists) { requestPathWithoutUrlMappingName = requestPath.Remove(startIndex - 1, endIndex - startIndex + 2); return cultureInfo; } return null; } } } return DataLocalizationFacade.DefaultUrlMappingCulture; } } } ================================================ FILE: Composite/Core/WebClient/Renderings/Data/DataXhtmlRenderingServices.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Data; using Composite.Core.Types; using Composite.Core.Xml; namespace Composite.Core.WebClient.Renderings.Data { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DataXhtmlRenderingServices { /// public static bool CanRender(Type dataTypeToRender, XhtmlRenderingType renderingType) { IEnumerable rendererAttributes = dataTypeToRender.GetCustomInterfaceAttributes(); return rendererAttributes.Any(f => f.SupportedRenderingType == renderingType); } /// public static XhtmlDocument Render(IDataReference dataToRender, XhtmlRenderingType renderingType) { Type dataTypeToRender = dataToRender.ReferencedType; IEnumerable rendererAttributes = dataTypeToRender.GetCustomInterfaceAttributes(); XhtmlRendererProviderAttribute rendererAttribute = rendererAttributes.FirstOrDefault(f => f.SupportedRenderingType == renderingType); if (rendererAttribute == null) throw new NotImplementedException(string.Format("No '{0}' xhtml renderer found for type '{1}'",renderingType, dataTypeToRender.FullName)); IDataXhtmlRenderer renderer = rendererAttribute.BuildRenderer(); return renderer.Render(dataToRender); } } } ================================================ FILE: Composite/Core/WebClient/Renderings/Data/IDataXhtmlRenderer.cs ================================================ using System; using Composite.Data; using Composite.Core.Xml; namespace Composite.Core.WebClient.Renderings.Data { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IDataXhtmlRenderer { /// XhtmlDocument Render(IDataReference dataToRender); } } ================================================ FILE: Composite/Core/WebClient/Renderings/Data/KeyTemplatedXhtmlRendererAttribute.cs ================================================ using System; using System.Collections.Generic; using System.Reflection; using Composite.Core.Collections.Generic; using Composite.Data; using System.Xml.Linq; using Composite.Data.Types; using Composite.Core.Logging; using Composite.Core.Extensions; using Composite.Core.Xml; using Composite.Core.WebClient; using System.Web; namespace Composite.Core.WebClient.Renderings.Data { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class KeyTemplatedXhtmlRendererAttribute : XhtmlRendererProviderAttribute { private XhtmlRenderingType _supportedRenderingType; private IDataXhtmlRenderer _renderer; private XhtmlRenderingEncoding _renderingEncoding; /// /// Created a XHTML Renderer that uses the specified template to create markup. /// The key of the data will be inserted into the specified template where '{id}' is. /// If you spcify '{label}' the system will fetch the value of the label field and insert it. /// You also can use '{field:__a field name__}' syntax to insert a field value. /// Use '~' to create absolute paths. /// Example: <a href='~/showProduct.aspx?id={id}'>read more about {label}</a> /// public KeyTemplatedXhtmlRendererAttribute(XhtmlRenderingType renderingType, string formatedTemplate) { this.FormatedTemplate = formatedTemplate; _supportedRenderingType = renderingType; _renderingEncoding = XhtmlRenderingEncoding.None; } /// /// Created a XHTML Renderer that uses the specified template to create markup. /// The key of the data will be inserted into the specified template where '{id}' is. /// If you spcify '{label}' the system will fetch the value of the label field and insert it. /// You also can use '{field:__a field name__}' syntax to insert a field value. /// Use '~' to create absolute paths. /// Example: <a href='~/showProduct.aspx?id={id}'>read more about {label}</a> /// public KeyTemplatedXhtmlRendererAttribute(XhtmlRenderingType renderingType, XhtmlRenderingEncoding renderingEncoding, string formatedTemplate) { this.FormatedTemplate = formatedTemplate; _supportedRenderingType = renderingType; _renderingEncoding = renderingEncoding; } /// public string FormatedTemplate { get; private set; } /// public override IDataXhtmlRenderer BuildRenderer() { if (_renderer == null) { _renderer = new KeyBasedXhtmlRenderer(this.FormatedTemplate, _renderingEncoding); } return _renderer; } /// public override XhtmlRenderingType SupportedRenderingType { get { return _supportedRenderingType; } } private class KeyBasedXhtmlRenderer : IDataXhtmlRenderer { private static readonly string LogTitle = "KeyBasedXhtmlRenderer"; private readonly string _templateString; private readonly List _fieldNames = new List(); private readonly List _fieldPatterns = new List(); private readonly bool _labelHasToBeEvaluated; private readonly bool _idHasToBeEvaluated; private readonly XhtmlRenderingEncoding _renderingEncoding; private readonly Hashtable> _reflectionCache = new Hashtable>(); public KeyBasedXhtmlRenderer(string templateString, XhtmlRenderingEncoding renderingEncoding) { templateString = templateString.Replace("~", UrlUtils.PublicRootPath); templateString = templateString.Replace("{label}", "{0}"); templateString = templateString.Replace("{id}", "{1}"); _labelHasToBeEvaluated = templateString.Contains("{0}"); _idHasToBeEvaluated = templateString.Contains("{1}"); _renderingEncoding = renderingEncoding; int stringFormattingIndex = 2; while (true) { int fieldDefinitionOffset = templateString.IndexOf("{field:"); if (fieldDefinitionOffset < 0) break; int closingBraceIndex = templateString.IndexOf("}", fieldDefinitionOffset + 7); Verify.That(closingBraceIndex > 0, "Invalid rendering template."); string fieldName = templateString.Substring(fieldDefinitionOffset + 7, closingBraceIndex - fieldDefinitionOffset - 7); _fieldNames.Add(fieldName); string fieldPattern = templateString.Substring(fieldDefinitionOffset, closingBraceIndex - fieldDefinitionOffset + 1); _fieldPatterns.Add(fieldPattern); templateString = templateString.Replace(fieldPattern, "{" + (stringFormattingIndex++) + "}"); } _templateString = string.Format("{1}", Namespaces.Xhtml, templateString); } public XhtmlDocument Render(IDataReference dataReferenceToRender) { if (!dataReferenceToRender.IsSet) { return new XhtmlDocument(); } IData dataToRender; if (dataReferenceToRender.ReferencedType == typeof(IPage)) { dataToRender = DataFacade.TryGetDataByUniqueKey(dataReferenceToRender.KeyValue); if (dataToRender == null) { return new XhtmlDocument(); } } else { dataToRender = dataReferenceToRender.Data; } string markup = _templateString; string labelEncoded = ""; string keyValue = ""; if (_labelHasToBeEvaluated) { labelEncoded = HttpUtility.HtmlEncode(dataToRender.GetLabel()); } if (_idHasToBeEvaluated) { keyValue = dataReferenceToRender.KeyValue.ToString(); } var parameters = new object[2 + _fieldNames.Count]; parameters[0] = labelEncoded; parameters[1] = keyValue; // Getting field values for (int i = 0; i < _fieldNames.Count; i++) { Type referenceType = dataReferenceToRender.ReferencedType; var propertiesMap = _reflectionCache.EnsureValue(referenceType, () => new Hashtable()); string fieldName = _fieldNames[i]; PropertyInfo propertyInfo; if (!propertiesMap.TryGetValue(fieldName, out propertyInfo)) { lock (propertiesMap) { if (!propertiesMap.TryGetValue(fieldName, out propertyInfo)) { Type type = referenceType; while (type != null && type != typeof(object)) { propertyInfo = type.GetProperty(fieldName); if (propertyInfo != null) { propertiesMap.Add(fieldName, propertyInfo); break; } if (type.GetInterfaces().Length > 0) { type = type.GetInterfaces()[0]; } } if (propertyInfo == null) { LoggingService.LogWarning(LogTitle, "Failed to find property '{0}' on type '{1}'" .FormatWith(fieldName, referenceType.FullName)); propertiesMap.Add(fieldName, null); } } } } string value = String.Empty; if (propertyInfo != null) { value = (propertyInfo.GetValue(dataToRender, new object[0]) ?? String.Empty).ToString(); } switch (_renderingEncoding) { case XhtmlRenderingEncoding.None: break; case XhtmlRenderingEncoding.AttributeContent: value = HttpUtility.HtmlAttributeEncode(value); break; case XhtmlRenderingEncoding.TextContent: value = HttpUtility.HtmlEncode(value); break; default: throw new NotImplementedException("Unexpected XhtmlRenderingEncoding value"); } parameters[2 + i] = value; } string evaluatedMarkup = string.Format(markup, parameters); XElement bodyMarkup = XElement.Parse(evaluatedMarkup); XhtmlDocument xhtmlDocument = new XhtmlDocument(); xhtmlDocument.Body.Add(bodyMarkup.Nodes()); return xhtmlDocument; } } } } ================================================ FILE: Composite/Core/WebClient/Renderings/Data/XhtmlRendererProviderAttribute.cs ================================================ using System; namespace Composite.Core.WebClient.Renderings.Data { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Interface, AllowMultiple = true, Inherited = true)] public abstract class XhtmlRendererProviderAttribute : Attribute { /// public abstract XhtmlRenderingType SupportedRenderingType { get; } /// public abstract IDataXhtmlRenderer BuildRenderer(); } } ================================================ FILE: Composite/Core/WebClient/Renderings/Data/XhtmlRenderingEncodingEnum.cs ================================================ namespace Composite.Core.WebClient.Renderings.Data { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum XhtmlRenderingEncoding { /// Do not encode (data fields are parsable as xml snippet) None = 0, /// Data fields should be parsed for use in xml attribute values AttributeContent = 1, /// Data fields should be parsed for use xml text TextContent = 2, } } ================================================ FILE: Composite/Core/WebClient/Renderings/Data/XhtmlRenderingTypeEnum.cs ================================================ namespace Composite.Core.WebClient.Renderings.Data { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum XhtmlRenderingType { /// Embedable } } ================================================ FILE: Composite/Core/WebClient/Renderings/Foundation/IRenderingResponseHandlerRegistry.cs ================================================ using System.Collections.Generic; namespace Composite.Core.WebClient.Renderings.Foundation { internal interface IRenderingResponseHandlerRegistry { IEnumerable RenderingResponseHandlerNames { get; } void Flush(); } } ================================================ FILE: Composite/Core/WebClient/Renderings/Foundation/PluginFacades/RenderingResponseHandlerPluginFacade.cs ================================================ using System; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.Data; using Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandler; using Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandler.Runtime; namespace Composite.Core.WebClient.Renderings.Foundation.PluginFacades { internal static class RenderingResponseHandlerPluginFacade { private static readonly ResourceLocker _resourceLocker = new ResourceLocker(new Resources(), Resources.Initialize); public static RenderingResponseHandlerResult GetDataResponseHandling(string handlerName, DataEntityToken requestedItemEntityToken) { IDataRenderingResponseHandler handler = GetRenderingResponseHandler(handlerName) as IDataRenderingResponseHandler; Verify.IsNotNull(handler, "The Rendering Response Handler named '{0}' does not implement the required interface '{1}'", handlerName, typeof(IDataRenderingResponseHandler)); return handler.GetDataResponseHandling(requestedItemEntityToken); } public static bool IsDataRenderingResponseHandler(string handlerName) { IDataRenderingResponseHandler handler = GetRenderingResponseHandler(handlerName) as IDataRenderingResponseHandler; return handler != null; } private static IRenderingResponseHandler GetRenderingResponseHandler(string handlerName) { IRenderingResponseHandler applicationStartupHandler; var resources = _resourceLocker; var providerCache = resources.Resources.ProviderCache; if (providerCache.TryGetValue(handlerName, out applicationStartupHandler)) { return applicationStartupHandler; } using (resources.Locker) { if (providerCache.TryGetValue(handlerName, out applicationStartupHandler) == false) { try { applicationStartupHandler = resources.Resources.Factory.Create(handlerName); providerCache.Add(handlerName, applicationStartupHandler); } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } } return applicationStartupHandler; } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", RenderingResponseHandlerSettings.SectionName), ex); } private sealed class Resources { public RenderingResponseHandlerFactory Factory { get; set; } public Hashtable ProviderCache { get; set; } public static void Initialize(Resources resources) { try { resources.Factory = new RenderingResponseHandlerFactory(); } catch (NullReferenceException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } resources.ProviderCache = new Hashtable(); } } } } ================================================ FILE: Composite/Core/WebClient/Renderings/Foundation/RenderingResponseHandlerRegistry.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Events; namespace Composite.Core.WebClient.Renderings.Foundation { internal static class RenderingResponseHandlerRegistry { private static IRenderingResponseHandlerRegistry _implementation = new RenderingResponseHandlerRegistryImpl(); static RenderingResponseHandlerRegistry() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } internal static IRenderingResponseHandlerRegistry Implementation { get { return _implementation; } set { _implementation = value; } } public static IEnumerable RenderingResponseHandlerNames { get { return _implementation.RenderingResponseHandlerNames; } } private static void Flush() { _implementation.Flush(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } } } ================================================ FILE: Composite/Core/WebClient/Renderings/Foundation/RenderingResponseHandlerRegistryImpl.cs ================================================ using System.Collections.Generic; using Composite.Core.Configuration; using Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandler; using Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandler.Runtime; namespace Composite.Core.WebClient.Renderings.Foundation { internal sealed class RenderingResponseHandlerRegistryImpl : IRenderingResponseHandlerRegistry { private List _renderingResponseHandlerNames = null; private static object _lock = new object(); public IEnumerable RenderingResponseHandlerNames { get { Initialize(); foreach (string name in _renderingResponseHandlerNames) { yield return name; } } } public void Flush() { lock (_lock) { _renderingResponseHandlerNames = null; } } private void Initialize() { if (_renderingResponseHandlerNames == null) { lock (_lock) { if (_renderingResponseHandlerNames == null) { _renderingResponseHandlerNames = new List(); RenderingResponseHandlerSettings renderingResponseHandlerSettings = ConfigurationServices.ConfigurationSource.GetSection(RenderingResponseHandlerSettings.SectionName) as RenderingResponseHandlerSettings; foreach (RenderingResponseHandlerData renderingResponseHandlerData in renderingResponseHandlerSettings.RenderingResponseHandlerPlugins) { _renderingResponseHandlerNames.Add(renderingResponseHandlerData.Name); } } } } } } } ================================================ FILE: Composite/Core/WebClient/Renderings/FunctionPreview.cs ================================================ using System; using System.Threading.Tasks; using System.Web; using Composite.C1Console.Events; using Composite.Core.Configuration; using Composite.Core.WebClient.PhantomJs; namespace Composite.Core.WebClient.Renderings { /// public static class FunctionPreview { private const string RenderingMode = "function"; static FunctionPreview() { GlobalEventSystemFacade.OnDesignChange += () => BrowserRender.ClearCache(RenderingMode); } internal static async Task GetPreviewFunctionPreviewImageFile(HttpContext context) { string previewUrl = context.Request.Url.ToString().Replace("/FunctionBox?", "/FunctionPreview.ashx?"); var renderingResult = await BrowserRender.RenderUrlAsync(context, previewUrl, RenderingMode); if (renderingResult == null) { return null; } if (renderingResult.Status == RenderingResultStatus.Success) { return renderingResult.FilePath; } if (renderingResult.Status >= RenderingResultStatus.Error) { string functionTitle = context.Request.QueryString["title"] ?? "null"; Log.LogWarning("FunctionPreview", "Failed to build preview for function '{0}'. Reason: {1}; Output:\r\n{2}", functionTitle, renderingResult.Status, string.Join(Environment.NewLine, renderingResult.Output)); } return null; } /// public static int GetFunctionPreviewHash() { if (!GlobalSettingsFacade.FunctionPreviewEnabled) { return 0; } return BrowserRender.GetLastCacheUpdateTime(RenderingMode).GetHashCode(); } } } ================================================ FILE: Composite/Core/WebClient/Renderings/INonCachebleRequestHostnameMapper.cs ================================================ namespace Composite.Core.WebClient.Renderings { /// /// Enables redirecting hostnames for extranet protected media requests in reverse caching proxy configuration. /// public interface INonCachebleRequestHostnameMapper { /// /// Gets a hostname to redirect to. /// /// /// string GetRedirectToHostname(string hostname); } } ================================================ FILE: Composite/Core/WebClient/Renderings/IRenderingResponseHandlerFacade.cs ================================================ using Composite.Data; namespace Composite.Core.WebClient.Renderings { internal interface IRenderingResponseHandlerFacade { RenderingResponseHandlerResult GetDataResponseHandling(DataEntityToken requestedItemEntityToken); } } ================================================ FILE: Composite/Core/WebClient/Renderings/Page/IPageContentFilter.cs ================================================ using Composite.Core.Xml; using Composite.Data.Types; namespace Composite.Core.WebClient.Renderings.Page { /// /// An interface that allows post processing of pages generated with class. /// public interface IPageContentFilter { /// /// Filters the output. /// /// The document to be updated. /// The C1 page currently being rendered. /// void Filter(XhtmlDocument document, IPage page); /// /// Gets the execution order. Filters with lower values will be executed first. /// int Order { get; } } } ================================================ FILE: Composite/Core/WebClient/Renderings/Page/IXElementToControlMapper.cs ================================================ using System.Xml.Linq; using System.Web.UI; using Composite.Functions; namespace Composite.Core.WebClient.Renderings.Page { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IXElementToControlMapper { /// bool TryGetControlFromXElement(XElement element, out Control control); } } ================================================ FILE: Composite/Core/WebClient/Renderings/Page/PageAssociationScopeEnum.cs ================================================ //namespace Composite.Core.WebClient.Renderings.Page //{ // /// // /// // /// // [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] // public enum SitemapScope // { // CurrentPage = 0, // CurrentAndDescendantPages = 1, // ChildPages = 2, // SiblingPages = 15, // AncestorPages = 3, // AncestorAndCurrent = 4, // ParentPage = 5, // Level1Page = 6, // Level2Page = 7, // Level3Page = 8, // Level4Page = 9, // Level1AndSiblings = 16, // Level2AndSiblings = 17, // Level3AndSiblings = 18, // Level4AndSiblings = 19, // Level1AndDescendants = 10, // Level2AndDescendants = 11, // Level3AndDescendants = 12, // Level4AndDescendants = 13, // AllPages = 14 // } //} ================================================ FILE: Composite/Core/WebClient/Renderings/Page/PagePreviewBuilder.cs ================================================ using System; using System.Collections.Generic; using System.Web; using Composite.Data.Types; namespace Composite.Core.WebClient.Renderings.Page { /// /// Allow previewing a page 'in mem' in a simulated GET request. Requires IIS to run in "Integrated" pipeline mode. /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class PagePreviewBuilder { /// /// Execute an 'im mem' preview request of the provided page and content. Requires IIS to run in "Integrated" pipeline mode. /// /// Page to render. Functionality reading the rendered page ID will get the ID from this object. /// Content to render on the page /// /// In Pipeline mode the content is written directly to the HttpContext and an empty string is returned. /// The IIS classic mode is no longer supported and will throw an exception. /// public static string RenderPreview(IPage selectedPage, IList contents) { return RenderPreview(selectedPage, contents, RenderingReason.PreviewUnsavedChanges); } /// /// Execute an 'im mem' preview request of the provided page and content. Requires IIS to run in "Integrated" pipeline mode. /// /// Page to render. Functionality reading the rendered page ID will get the ID from this object. /// Content to render on the page /// The rendering reason /// /// In Pipeline mode the content is written directly to the HttpContext and an empty string is returned. /// The IIS classic mode is no longer supported and will throw an exception. /// public static string RenderPreview(IPage selectedPage, IList contents, RenderingReason renderingReason) { if (!HttpRuntime.UsingIntegratedPipeline) { throw new InvalidOperationException("IIS classic mode not supported"); } var previewKey = Guid.NewGuid(); PagePreviewContext.Save(previewKey, selectedPage, contents, renderingReason); // The header trick here is to work around (what seems to be) a bug in .net 4.5, where preserveForm=false is ignored // asp.net 4.5 request validation will see the 'page edit http post' data and start bitching. It really should not. var headers = new System.Collections.Specialized.NameValueCollection { {"Content-Length", "0"} }; var ctx = HttpContext.Current; string cookieHeader = ctx.Request.Headers["Cookie"]; if (!string.IsNullOrEmpty(cookieHeader)) { headers.Add("Cookie", cookieHeader); } string previewPath = $"~/Renderers/PagePreview?{PagePreviewContext.PreviewKeyUrlParameter}={previewKey}"; ctx.Server.TransferRequest(previewPath, false, "GET", headers); return String.Empty; } } } ================================================ FILE: Composite/Core/WebClient/Renderings/Page/PagePreviewContext.cs ================================================ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Web; using System.Web.Caching; using Composite.Data.Types; namespace Composite.Core.WebClient.Renderings.Page { public static class PagePreviewContext { public static readonly string PreviewKeyUrlParameter = "previewKey"; private static readonly TimeSpan PreviewExpirationTimeSpan = new TimeSpan(0, 20, 0); private static string CacheKey_Page(Guid key) => key + "_SelectedPage"; private static string CacheKey_Contents(Guid key) => key + "_SelectedContents"; private static string CacheKey_RenderingReason(Guid key) => key + "_RenderingReason"; public static void Save(Guid previewKey, IPage selectedPage, IList contents, RenderingReason renderingReason) { var cache = HttpRuntime.Cache; cache.Add(CacheKey_Page(previewKey), selectedPage, null, Cache.NoAbsoluteExpiration, PreviewExpirationTimeSpan, CacheItemPriority.NotRemovable, null); cache.Add(CacheKey_Contents(previewKey), contents, null, Cache.NoAbsoluteExpiration, PreviewExpirationTimeSpan, CacheItemPriority.NotRemovable, null); cache.Add(CacheKey_RenderingReason(previewKey), renderingReason, null, Cache.NoAbsoluteExpiration, PreviewExpirationTimeSpan, CacheItemPriority.NotRemovable, null); } public static bool TryGetPreviewKey(HttpRequest request, out Guid previewKey) { return TryGetPreviewKey(request.QueryString, out previewKey); } public static bool TryGetPreviewKey(HttpRequestBase request, out Guid previewKey) { return TryGetPreviewKey(request.QueryString, out previewKey); } private static bool TryGetPreviewKey(NameValueCollection queryString, out Guid previewKey) { var value = queryString[PreviewKeyUrlParameter]; if (!string.IsNullOrWhiteSpace(value) && Guid.TryParse(value, out previewKey)) { return true; } previewKey = Guid.Empty; return false; } public static IPage GetPage(Guid previewKey) => (IPage) HttpRuntime.Cache.Get(CacheKey_Page(previewKey)); public static IList GetPageContents(Guid previewKey) => (IList)HttpRuntime.Cache.Get(CacheKey_Contents(previewKey)); public static RenderingReason GetRenderingReason(Guid previewKey) => (RenderingReason)HttpRuntime.Cache.Get(CacheKey_RenderingReason(previewKey)); public static void Remove(Guid previewKey) { var cache = HttpRuntime.Cache; cache.Remove(CacheKey_Page(previewKey)); cache.Remove(CacheKey_Contents(previewKey)); cache.Remove(CacheKey_RenderingReason(previewKey)); } } } ================================================ FILE: Composite/Core/WebClient/Renderings/Page/PageRenderer.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Xml.Linq; using Composite.Core.Caching; using Composite.Core.Routing; using Composite.Core.Routing.Pages; using Composite.Data; using Composite.Data.Types; using Composite.Functions; using Composite.Core.Instrumentation; using Composite.Core.Localization; using Composite.Core.WebClient.Renderings.Template; using Composite.Core.Xml; using Composite.C1Console.Security; using Composite.Core.Configuration; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Caching; using Composite.Plugins.PageTemplates.XmlPageTemplates; namespace Composite.Core.WebClient.Renderings.Page { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PageRenderer { private static readonly string LogTitle = typeof(PageRenderer).Name; private static readonly NameBasedAttributeComparer _nameBasedAttributeComparer = new NameBasedAttributeComparer(); private static readonly XName XName_function = Namespaces.Function10 + "function"; private static readonly XName XName_Id = "id"; private static readonly XName XName_Name = "name"; /// public static FunctionContextContainer GetPageRenderFunctionContextContainer() { var mapper = new XEmbeddedControlMapper(); var contextContainer = new FunctionContextContainer { XEmbedableMapper = mapper, SuppressXhtmlExceptions = GlobalSettingsFacade.PrettifyRenderFunctionExceptions || PageRenderer.RenderingReason == RenderingReason.ScreenshotGeneration }; return contextContainer; } /// public static Control Render(this IPage page, IEnumerable placeholderContents, FunctionContextContainer functionContextContainer) { Verify.ArgumentNotNull(page, "page"); Verify.ArgumentNotNull(functionContextContainer, "functionContextContainer"); Verify.ArgumentCondition(functionContextContainer.XEmbedableMapper is XEmbeddedControlMapper, "functionContextContainer", $"Unknown or missing XEmbedableMapper on context container. Use {nameof(GetPageRenderFunctionContextContainer)}()."); CurrentPage = page; using (GlobalInitializerFacade.CoreIsInitializedScope) { string url = PageUrls.BuildUrl(page); using (TimerProfilerFacade.CreateTimerProfiler(url ?? "(no url)")) { var cultureInfo = page.DataSourceId.LocaleScope; System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo; System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo; XEmbeddedControlMapper mapper = (XEmbeddedControlMapper)functionContextContainer.XEmbedableMapper; XDocument document = TemplateInfo.GetTemplateDocument(page.TemplateId); ResolvePlaceholders(document, placeholderContents); Control c = Render(document, functionContextContainer, mapper, page); return c; } } } /// public static XhtmlDocument ParsePlaceholderContent(IPagePlaceholderContent placeholderContent) { if (string.IsNullOrEmpty(placeholderContent?.Content)) { return new XhtmlDocument(); } if (placeholderContent.Content.StartsWith("{placeholderContent.Content}"); } /// /// Replaces <rendering:placeholder ... /> tags with provided placeholder contents. Used by . /// /// The document to be updated. /// The placeholder content to be used. internal static void ResolvePlaceholders(XDocument document, IEnumerable placeholderContents) { using (TimerProfilerFacade.CreateTimerProfiler()) { var placeHolders = (from placeholder in document.Descendants(RenderingElementNames.PlaceHolder) let idAttribute = placeholder.Attribute(RenderingElementNames.PlaceHolderIdAttribute) where idAttribute != null select new { Element = placeholder, IdAttribute = idAttribute}).ToList(); foreach (var placeholder in placeHolders) { string placeHolderId = placeholder.IdAttribute.Value; placeholder.IdAttribute.Remove(); IPagePlaceholderContent placeHolderContent = placeholderContents.FirstOrDefault(f => f.PlaceHolderId == placeHolderId); XhtmlDocument xhtmlDocument = ParsePlaceholderContent(placeHolderContent); placeholder.Element.ReplaceWith(xhtmlDocument.Root); } } } /// public static Control Render(this IPage page, IEnumerable placeholderContents) { return page.Render(placeholderContents, GetPageRenderFunctionContextContainer()); } /// public static Guid CurrentPageId => CurrentPage?.Id ?? Guid.Empty; /// /// Returns true if the page is rendered in a "Preview" mode /// public static RenderingReason RenderingReason { get { return RequestLifetimeCache.TryGet("PageRenderer.RenderingReason"); } set { RequestLifetimeCache.Add("PageRenderer.RenderingReason", value); } } /// public static IPage CurrentPage { get { return RequestLifetimeCache.TryGet("PageRenderer.IPage"); } set { var currentValue = CurrentPage; if (currentValue == value) { return; } Verify.IsNull(currentValue, "CurrentPage is already set"); RequestLifetimeCache.Add("PageRenderer.IPage", value); } } /// public static CultureInfo CurrentPageCulture => CurrentPage?.DataSourceId.LocaleScope; /// [Obsolete] public static IEnumerable GetCurrentPageAssociatedData(Type type) { return PageRenderer.CurrentPage.GetReferees(type); } /// [Obsolete] public static IEnumerable GetCurrentPageAssociatedData() where T : IData { return PageRenderer.CurrentPage.GetReferees(typeof(T)); } internal static void ProcessXhtmlDocument(XhtmlDocument xhtmlDocument, IPage page) { using (Profiler.Measure("Normalizing XHTML document")) { NormalizeXhtmlDocument(xhtmlDocument); } using (Profiler.Measure("Resolving relative paths")) { ResolveRelativePaths(xhtmlDocument); } using (Profiler.Measure("Appending C1 meta tags")) { AppendC1MetaTags(page, xhtmlDocument); } using (Profiler.Measure("Sorting elements")) { PrioritizeHeadNodes(xhtmlDocument); } using (Profiler.Measure("Parsing localization strings")) { LocalizationParser.Parse(xhtmlDocument); } using (Profiler.Measure("Converting URLs from internal to public format (XhtmlDocument)")) { InternalUrls.ConvertInternalUrlsToPublic(xhtmlDocument); } var filters = ServiceLocator.GetServices().OrderBy(f => f.Order).ToList(); if (filters.Any()) { using (Profiler.Measure("Executing page content filters")) { filters.ForEach(filter => { using (Profiler.Measure($"Filter: {filter.GetType().FullName}")) { filter.Filter(xhtmlDocument, page); } }); } } } private static bool IsTitleOrMetaTag(XElement e) => e.Name.LocalName.Equals("title", StringComparison.OrdinalIgnoreCase) || e.Name.LocalName.Equals("meta", StringComparison.OrdinalIgnoreCase); private static bool CheckForDuplication(HashSet values, string value) { if (!string.IsNullOrWhiteSpace(value)) { if (values.Contains(value)) return true; values.Add(value); } return false; } private static string AttributesAsString(this XElement e) { var str = new StringBuilder(); foreach (var attr in e.Attributes().OrderBy(a => a.Name.NamespaceName).ThenBy(a => a.Name.LocalName)) { str.Append(attr.Name.LocalName); str.Append("=\""); str.Append(attr.Value); str.Append("\" "); } return str.ToString(); } /// public static void ProcessDocumentHead(XhtmlDocument xhtmlDocument) { RemoveDuplicates(xhtmlDocument.Head); } private static void RemoveDuplicates(XElement head) { var uniqueIdValues = new HashSet(StringComparer.OrdinalIgnoreCase); var uniqueMetaNameValues = new HashSet(StringComparer.OrdinalIgnoreCase); var uniqueScriptAttributes = new HashSet(StringComparer.OrdinalIgnoreCase); var uniqueLinkAttributes = new HashSet(StringComparer.OrdinalIgnoreCase); var priorityOrderedElements = new List(); priorityOrderedElements.AddRange(head.Elements().Where(IsTitleOrMetaTag)); priorityOrderedElements.Reverse(); priorityOrderedElements.AddRange(head.Elements().Where(e => !IsTitleOrMetaTag(e))); bool titleTagEncountered = false; foreach (var e in priorityOrderedElements) { var tagName = e.Name.LocalName.ToLowerInvariant(); bool toBeRemoved; if (tagName == "title") { toBeRemoved = titleTagEncountered; titleTagEncountered = true; } else { var id = (string)e.Attribute(XName_Id); toBeRemoved = CheckForDuplication(uniqueIdValues, id); if (!toBeRemoved && !e.Nodes().Any()) { switch (tagName) { case "meta": var name = (string)e.Attribute(XName_Name); toBeRemoved = CheckForDuplication(uniqueMetaNameValues, name); break; case "script": toBeRemoved = CheckForDuplication(uniqueScriptAttributes, e.AttributesAsString()); break; case "link": toBeRemoved = CheckForDuplication(uniqueLinkAttributes, e.AttributesAsString()); break; } } } if (toBeRemoved) { e.Remove(); } } } /// public static Control Render(XDocument document, FunctionContextContainer contextContainer, IXElementToControlMapper mapper, IPage page) { using (TimerProfilerFacade.CreateTimerProfiler()) { bool disableCaching = false; using (Profiler.Measure("Executing embedded functions")) { ExecuteFunctionsRec(document.Root, contextContainer, func => { if (!disableCaching && !FunctionAllowsCaching(func)) { disableCaching = true; } return true; }); } if (disableCaching) { using (Profiler.Measure("PageRenderer: Disabling HTTP caching as at least one of the functions is not cacheable")) { HttpContext.Current?.Response.Cache.SetCacheability(HttpCacheability.NoCache); } } using (Profiler.Measure("Resolving page fields")) { ResolvePageFields(document, page); } using (Profiler.Measure("Normalizing ASP.NET forms")) { NormalizeAspNetForms(document); } if (document.Root.Name != RenderingElementNames.Html) { return new LiteralControl(document.ToString()); } var xhtmlDocument = new XhtmlDocument(document); ProcessXhtmlDocument(xhtmlDocument, page); using (Profiler.Measure("Converting XHTML document into an ASP.NET control")) { return xhtmlDocument.AsAspNetControl(mapper); } } } private static void PrioritizeHeadNodes(XhtmlDocument xhtmlDocument) { var prioritizedHeadNodes = new List>(); foreach (var node in xhtmlDocument.Head.Nodes().ToList()) { int p = GetHeadNodePriority(node); prioritizedHeadNodes.Add(new Tuple(p, node)); node.Remove(); } xhtmlDocument.Head.Add(prioritizedHeadNodes.OrderBy(f => f.Item1).Select(f => f.Item2)); } private static string AttributeValueLowered(this XElement element, string attributeName) { string value = (string)element.Attribute(attributeName); return value?.ToLowerInvariant(); } private static int GetHeadNodePriority(XNode headNode) { if (headNode is XElement headElement) { if (headElement.Name.LocalName == "title") return 0; if (headElement.Name.LocalName == "meta") { if (headElement.AttributeValueLowered("http-equiv") == "content-type") return 10; if (headElement.Attribute("charset") != null) return 11; if (headElement.Attribute("http-equiv") != null) return 11; if (headElement.AttributeValueLowered("name") == "description") return 12; if (headElement.Attribute("name") != null) return 20; if (headElement.Attribute("property") != null) return 25; return 20; } if (headElement.Name.LocalName == "link") return 30; if (headElement.Name.LocalName == "script") return 40; } return 100; } /// /// Appends the c1 meta tags to the head section. Those tag are used later on by SEO assistant. /// /// The page. /// The XHTML document. public static void AppendC1MetaTags(IPage page, XhtmlDocument xhtmlDocument) { if (UserValidationFacade.IsLoggedIn()) { bool emitMenuTitleMetaTag = string.IsNullOrEmpty(page.MenuTitle) == false; bool emitUrlMetaTag = string.IsNullOrEmpty(page.UrlTitle) == false; if (emitMenuTitleMetaTag || emitUrlMetaTag) { xhtmlDocument.Head.Add( new XComment("The C1.* meta tags are only emitted when you are logged in"), new XElement(Namespaces.Xhtml + "link", new XAttribute("rel", "schema.C1"), new XAttribute("href", "http://www.composite.net/ns/c1/seoassistant"))); if (emitMenuTitleMetaTag) { xhtmlDocument.Head.Add( new XElement(Namespaces.Xhtml + "meta", new XAttribute("name", "C1.menutitle"), new XAttribute("content", page.MenuTitle))); } if (emitUrlMetaTag) { var editPreview = PageRenderer.RenderingReason == RenderingReason.PreviewUnsavedChanges; string url = PageUrls.BuildUrl(page) ?? PageUrls.BuildUrl(page, UrlKind.Internal); var pageUrl = string.Format("{0}{1}{2}", url.Replace("/c1mode(unpublished)", "").Replace("/c1mode(relative)",""), editPreview ? "/" + page.UrlTitle : C1PageRoute.GetPathInfo(), editPreview ? "" : HttpContext.Current.Request.Url.Query); xhtmlDocument.Head.Add( new XElement(Namespaces.Xhtml + "meta", new XAttribute("name", "C1.urlseowords"), new XAttribute("content", pageUrl))); } } } } /// public static void ResolveRelativePaths(XhtmlDocument xhtmlDocument) { IEnumerable xhtmlElements = xhtmlDocument.Descendants().Where(f => f.Name.Namespace == Namespaces.Xhtml); IEnumerable pathAttributes = xhtmlElements.Attributes().Where(f => f.Name.LocalName == "src" || f.Name.LocalName == "href" || f.Name.LocalName == "action"); string applicationVirtualPath = UrlUtils.PublicRootPath; List relativePathAttributes = pathAttributes.Where(f => f.Value.StartsWith("~/") || f.Value.StartsWith("%7E/")).ToList(); foreach (XAttribute relativePathAttribute in relativePathAttributes) { int tildePrefixLength = (relativePathAttribute.Value.StartsWith("~") ? 1 : 3); relativePathAttribute.Value = applicationVirtualPath + relativePathAttribute.Value.Substring(tildePrefixLength); } if (applicationVirtualPath.Length > 1) { List hardRootedPathAttributes = pathAttributes.Where(f => f.Value.StartsWith("/Renderers/")).ToList(); foreach (XAttribute hardRootedPathAttribute in hardRootedPathAttributes) { hardRootedPathAttribute.Value = applicationVirtualPath + hardRootedPathAttribute.Value; } } } private static void NormalizeAspNetForms(XDocument document) { var aspNetFormXName = Namespaces.AspNetControls + "form"; List aspNetFormElements = document.Descendants(aspNetFormXName).Reverse().ToList(); foreach (XElement aspNetFormElement in aspNetFormElements) { if (aspNetFormElement.Ancestors(aspNetFormXName).Any()) { aspNetFormElement.ReplaceWith(aspNetFormElement.Nodes()); } } } /// public static void ResolvePageFields(XDocument document, IPage page) { foreach (XElement elem in document.Descendants(RenderingElementNames.PageTitle).ToList()) { elem.ReplaceWith(page.Title); } foreach (XElement elem in document.Descendants(RenderingElementNames.PageAbstract).ToList()) { elem.ReplaceWith(page.Description); } foreach (XElement elem in document.Descendants(RenderingElementNames.PageMetaTagDescription).ToList()) { if (string.IsNullOrEmpty(page.Description)) { elem.Remove(); continue; } elem.ReplaceWith(new XElement(Namespaces.Xhtml + "meta", new XAttribute("name", "description"), new XAttribute("content", page.Description))); } } /// /// Executes functions that match the predicate recursively, /// /// /// /// /// A predicate that defines whether a function should be executed based on its name. /// True if all of the functions has matched the predicate internal static bool ExecuteFunctionsRec( XElement element, FunctionContextContainer functionContext, Predicate functionShouldBeExecuted = null) { if (element.Name != XName_function) { var children = element.Elements(); if (element.Elements(XName_function).Any()) { // Allows replacing the function elements without breaking the iterator children = children.ToList(); } bool allChildrenExecuted = true; foreach (var childElement in children) { if (!ExecuteFunctionsRec(childElement, functionContext, functionShouldBeExecuted)) { allChildrenExecuted = false; } } return allChildrenExecuted; } bool allRecFunctionsExecuted = true; string functionName = (string) element.Attribute(XName_Name); object result; try { // Evaluating function calls in parameters IEnumerable parameters = element.Elements(); bool allParametersEvaluated = true; foreach (XElement parameterNode in parameters.ToList()) { var parameterName = (string)parameterNode.Attribute(XName_Name); if (ParameterIsLazyEvaluated(functionName, parameterName)) { continue; } if (!ExecuteFunctionsRec(parameterNode, functionContext, functionShouldBeExecuted)) { allParametersEvaluated = false; } } if (!allParametersEvaluated) { return false; } if (functionShouldBeExecuted != null && !functionShouldBeExecuted(functionName)) { return false; } // Executing a function call BaseRuntimeTreeNode runtimeTreeNode = FunctionTreeBuilder.Build(element); result = runtimeTreeNode.GetValue(functionContext); if (result != null) { // Evaluating functions in a result of a function call result = functionContext.MakeXEmbedable(result); foreach (XElement xelement in GetXElements(result).ToList()) { if (!ExecuteFunctionsRec(xelement, functionContext, functionShouldBeExecuted)) { allRecFunctionsExecuted = false; } } } } catch (Exception ex) { using (Profiler.Measure("PageRenderer. Logging exception: " + ex.Message)) { XElement errorBoxHtml; if (!functionContext.ProcessException(functionName, ex, LogTitle, out errorBoxHtml)) { throw; } result = errorBoxHtml; } } ReplaceFunctionWithResult(element, result); return allRecFunctionsExecuted; } private static bool ParameterIsLazyEvaluated(string functionName, string parameterName) { return functionName == PageObjectCacheFunction.FunctionName && parameterName == PageObjectCacheFunction.ParameterNames.ObjectToCache; } /// public static void ExecuteEmbeddedFunctions(XElement element, FunctionContextContainer functionContext) { ExecuteFunctionsRec(element, functionContext, null); } /// /// Executes all cacheable (not dynamic) functions and returns True /// if all of the functions were cacheable. /// /// /// /// internal static bool ExecuteCacheableFunctions(XElement element, FunctionContextContainer functionContext) { return ExecuteFunctionsRec(element, functionContext, FunctionAllowsCaching); } private static bool FunctionAllowsCaching(string name) { var function = FunctionFacade.GetFunction(name); return !(function is IDynamicFunction df && df.PreventFunctionOutputCaching); } private static void ReplaceFunctionWithResult(XElement functionCall, object result) { if (result == null) { functionCall.Remove(); return; } if (result is XAttribute && functionCall.Parent != null) { functionCall.Parent.Add(result); functionCall.Remove(); } else { functionCall.ReplaceWith(result); } } private static IEnumerable GetXElements(object source) { if (source is XElement element) { yield return element; } if (source is IEnumerable nodes) { foreach (var xElement in nodes.OfType()) { yield return xElement; } } } private class NameBasedAttributeComparer : IEqualityComparer { public bool Equals(XAttribute x, XAttribute y) { return x.Name == y.Name; } public int GetHashCode(XAttribute obj) { return obj.Name.GetHashCode(); } } /// public static void NormalizeXhtmlDocument(XhtmlDocument rootDocument) { using (TimerProfilerFacade.CreateTimerProfiler()) { while (true) { XElement nestedDocument = rootDocument.Root.Descendants(XhtmlDocument.XName_html).FirstOrDefault(); if (nestedDocument == null) break; var nestedHead = nestedDocument.Element(XhtmlDocument.XName_head); var nestedBody = nestedDocument.Element(XhtmlDocument.XName_body); Verify.IsNotNull(nestedHead, "XHTML document is missing element"); Verify.IsNotNull(nestedBody, "XHTML document is missing element"); rootDocument.Root.Add(nestedDocument.Attributes().Except(rootDocument.Root.Attributes(), _nameBasedAttributeComparer)); rootDocument.Head.Add(nestedHead.Nodes()); rootDocument.Head.Add(nestedHead.Attributes().Except(rootDocument.Head.Attributes(), _nameBasedAttributeComparer)); rootDocument.Body.Add(nestedBody.Attributes().Except(rootDocument.Body.Attributes(), _nameBasedAttributeComparer)); nestedDocument.ReplaceWith(nestedBody.Nodes()); } } } /// public static bool DisableAspNetPostback(Control c) { bool formDisabled; DisableAspNetPostback(c, out formDisabled); return formDisabled; } private static void DisableAspNetPostback(Control c, out bool formDisabled) { formDisabled = false; if (c is HtmlForm form) { form.Attributes.Add("onsubmit", "alert('Postback disabled in preview mode'); return false;"); formDisabled = true; return; } if (c is HtmlHead) { return; } foreach (Control child in c.Controls) { DisableAspNetPostback(child, out formDisabled); if (formDisabled) break; } } } } ================================================ FILE: Composite/Core/WebClient/Renderings/Page/PageStructureInfo.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Xml.Linq; using Composite.Core.Collections.Generic; using Composite.Core.Routing; using Composite.Core.Routing.Plugins.PageUrlsProviders; using Composite.Data; using Composite.Data.Types; using Composite.Core.Logging; using Composite.Core.Extensions; using Composite.Core.Linq; using MapKey = System.Tuple; namespace Composite.Core.WebClient.Renderings.Page { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PageStructureInfo { /// [Obsolete("Now sitemap generates xml that belongs to empty namespace, so this constant shouldn't be used", true)] public const string SitemapNamespaceString = ""; internal static class AttributeNames { public static XName Id = "Id"; public static XName Title = "Title"; public static XName MenuTitle = "MenuTitle"; public static XName UrlTitle = "UrlTitle"; public static XName Description = "Description"; public static XName ChangedDate = "ChangedDate"; public static XName ChangedBy = "ChangedBy"; public static XName URL = "URL"; public static XName FriendlyUrl = "FriendlyUrl"; public static XName Depth = "Depth"; } internal static class ElementNames { public static XName Page = "Page"; } private class Version { public int VersionNumber; } /// /// An immutable instanse of a pages map /// private class Map { public IEnumerable RootPagesLookup; public Dictionary UrlToIdLookup; public Dictionary LowerCaseUrlToIdLookup; public Dictionary IdToUrlLookup; #pragma warning disable 612 public IPageUrlBuilder PageUrlBuilder; #pragma warning restore 612 } private static readonly Hashtable _generatedMaps = new Hashtable(); private static readonly Hashtable _versions = new Hashtable(); private static readonly object _updatingLock = new object(); //private static readonly object[] _buildingLock = new[] { new object(), new object() }; // Separated objects for 'Public' and 'Administrated' scopes private static readonly HashSet _knownNotUniqueUrls = new HashSet(); private static readonly XName PageElementName = "Page"; private static readonly string LogTitle = "PageStructureInfo"; static PageStructureInfo() { DataEventSystemFacade.SubscribeToStoreChanged(OnPagesChanged, true); DataEventSystemFacade.SubscribeToStoreChanged(OnPageStructureChanged, true); DataEventSystemFacade.SubscribeToStoreChanged((a, b) => ClearCachedData(), true); DataEventSystemFacade.SubscribeToStoreChanged((a, b) => ClearCachedData(), true); DataEventSystemFacade.SubscribeToStoreChanged((a, b) => ClearCachedData(), true); } /// /// Builds a list of [Page Id, Page label] pairs. /// The items in the list is returned in document order and the labels are indented with one space for each depth level /// of the page. /// [Obsolete] public static IEnumerable> PageListInDocumentOrder() { return PageListInDocumentOrder(GetSiteMap(), 0); } private static IEnumerable> PageListInDocumentOrder(IEnumerable pageElements, int indentLevel) { var indentString = new string(' ', indentLevel); foreach (XElement pageElement in pageElements) { string label = GetLabelForPageElement(indentString, pageElement); var id = GetIdForPageElement(pageElement); yield return new KeyValuePair(id, label); foreach (KeyValuePair childOption in PageListInDocumentOrder(pageElement.Elements(), indentLevel + 1)) { yield return childOption; } } } internal static Guid GetIdForPageElement(XElement pageElement) { string id = pageElement.Attribute(AttributeNames.Id).Value; return Guid.Parse(id); } internal static string GetLabelForPageElement(string indentString, XElement pageElement) { string labelText = (pageElement.Attribute(AttributeNames.MenuTitle) ?? pageElement.Attribute(AttributeNames.Title)).Value; return string.Format("{0}{1}", indentString, labelText); } /// public static IEnumerable GetSiteMap() { return GetMap().RootPagesLookup; } /// public static IEnumerable GetSiteMapWithActivePageAnnotations() { Guid pageId = PageRenderer.CurrentPageId; return GetSiteMapWithActivePageAnnotations(pageId); } /// public static IEnumerable GetSiteMapWithActivePageAnnotations(Guid pageId) { return GetSitemapByScope(SitemapScope.All, pageId); } /// /// Returns portions of the sitemap in acordance with the specified scope. Sitemap elements are hierarchically /// ordered and are marked with 'isopen' and 'iscurrent' attributes when open/selected relative to the supplied pageId. /// /// The scope of pages to return. This is relative to the specified pageId. /// The C1 Page ID to use when defining the scope. This must be a valid page id. /// public static IEnumerable GetSitemapByScope(SitemapScope associationScope, Guid pageId) { List pageElements = GetSitemapByScopeUnannotated(associationScope, pageId).ToList(); AnnotatePagesWithOpenAndCurrent(pageId, pageElements); return pageElements; } private static IEnumerable GetDescendants(Guid pageId) { foreach (var childId in PageManager.GetChildrenIDs(pageId)) { foreach (var descendantOrSelf in GetDescendantsAndSelf(childId)) { yield return descendantOrSelf; } } } private static IEnumerable GetDescendantsAndSelf(Guid pageId) { yield return pageId; foreach (var childId in PageManager.GetChildrenIDs(pageId)) { foreach (var descendantOrSelf in GetDescendantsAndSelf(childId)) { yield return descendantOrSelf; } } } private static List GetAncestors(Guid pageId, bool andSelf) { var result = new List(); if (andSelf) { result.Add(pageId); } pageId = PageManager.GetParentId(pageId); while (pageId != Guid.Empty) { result.Add(pageId); pageId = PageManager.GetParentId(pageId); } return result; } /// public static IEnumerable GetAssociatedPageIds(Guid pageId, SitemapScope associationScope) { switch (associationScope) { case SitemapScope.Current: return new[] {pageId}; case SitemapScope.All: return DataFacade.GetData().Select(p => p.Id).ToList(); case SitemapScope.Descendants: return GetDescendants(pageId); case SitemapScope.DescendantsAndCurrent: return GetDescendantsAndSelf(pageId); case SitemapScope.Children: return PageManager.GetChildrenIDs(pageId); case SitemapScope.Siblings: Guid parentId = PageManager.GetParentId(pageId); return PageManager.GetChildrenIDs(parentId).Where(i => i != pageId); case SitemapScope.SiblingsAndSelf: parentId = PageManager.GetParentId(pageId); return PageManager.GetChildrenIDs(parentId); case SitemapScope.Ancestors: return GetAncestors(pageId, false); case SitemapScope.AncestorsAndCurrent: return GetAncestors(pageId, true); case SitemapScope.Parent: parentId = PageManager.GetParentId(pageId); return parentId != Guid.Empty ? new[] {parentId} : new Guid[0]; case SitemapScope.Level1: case SitemapScope.Level2: case SitemapScope.Level3: case SitemapScope.Level4: case SitemapScope.Level1AndDescendants: case SitemapScope.Level2AndDescendants: case SitemapScope.Level3AndDescendants: case SitemapScope.Level4AndDescendants: case SitemapScope.Level1AndSiblings: case SitemapScope.Level2AndSiblings: case SitemapScope.Level3AndSiblings: case SitemapScope.Level4AndSiblings: int level = int.Parse(associationScope.ToString().Substring(5, 1)); var ancestors = GetAncestors(pageId, true); ancestors.Reverse(); bool andSiblings = associationScope.ToString().EndsWith("AndSiblings"); if (andSiblings) { if (ancestors.Count < level - 1) { return new Guid[0]; } Guid parentPageId = level == 1 ? Guid.Empty : ancestors[level - 2]; return GetAssociatedPageIds(parentPageId, SitemapScope.Children); } if (ancestors.Count < level) { return new Guid[0]; } Guid levelPageId = ancestors[level - 1]; bool andDescendants = associationScope.ToString().EndsWith("AndDescendants"); if (andDescendants) { return GetDescendantsAndSelf(levelPageId); } return new[] {levelPageId}; default: throw new NotImplementedException("Unhandled SitemapScope type: " + associationScope); } } /// public static IEnumerable GetAssociatedPageIds(Guid pageId, SitemapScope associationScope, IEnumerable sitemaps) { switch (associationScope) { case SitemapScope.Current: yield return pageId; break; case SitemapScope.All: #pragma warning disable 618 foreach (Guid id in GetIdToUrlLookup().Keys) #pragma warning restore 618 { yield return id; } break; case SitemapScope.Descendants: case SitemapScope.DescendantsAndCurrent: case SitemapScope.Children: case SitemapScope.Siblings: case SitemapScope.Ancestors: case SitemapScope.AncestorsAndCurrent: case SitemapScope.Parent: case SitemapScope.Level1: case SitemapScope.Level2: case SitemapScope.Level3: case SitemapScope.Level4: case SitemapScope.Level1AndDescendants: case SitemapScope.Level2AndDescendants: case SitemapScope.Level3AndDescendants: case SitemapScope.Level4AndDescendants: case SitemapScope.Level1AndSiblings: case SitemapScope.Level2AndSiblings: case SitemapScope.Level3AndSiblings: case SitemapScope.Level4AndSiblings: string pageIdString = pageId.ToString(); XAttribute idMatchAttrib = sitemaps.DescendantsAndSelf().Attributes(AttributeNames.Id).FirstOrDefault(id => id.Value == pageIdString); if (idMatchAttrib != null) { XElement currentPageElement = idMatchAttrib.Parent; IEnumerable scopeElements = GetPageElementsByScope(associationScope, currentPageElement); foreach (XElement pageElement in scopeElements) { yield return new Guid(pageElement.Attribute(AttributeNames.Id).Value); } } break; default: throw new NotImplementedException("Unhandled SitemapScope type: " + associationScope); } } private static Map GetMap() { return GetMap(DataScopeManager.CurrentDataScope.ToPublicationScope(), LocalizationScopeManager.CurrentLocalizationScope); } private static Map GetMap(PublicationScope publicationScope, CultureInfo localizationScope) { return GetMap(publicationScope, localizationScope, new UrlSpace()); } private static Map GetMap(PublicationScope publicationScope, CultureInfo localizationScope, UrlSpace urlSpace) { Verify.ArgumentNotNull(localizationScope, "localizationScope"); Verify.ArgumentNotNull(urlSpace, "urlSpace"); if (System.Transactions.Transaction.Current != null) { var exceptionToLog = new Exception("It is not safe to use PageStructureInfo/SiteMap functionality in transactional context. Method Composite.Data.PageManager can be used instead."); Log.LogWarning(typeof(PageStructureInfo).Name, exceptionToLog); } var scopeKey = GetScopeKey(publicationScope, localizationScope, urlSpace); Map map = _generatedMaps[scopeKey]; if (map != null) { return map; } // Using different sync roots for different datascopes //object buildingLock = _buildingLock[scopeKey.First == DataScopeIdentifier.Public.Name ? 0 : 1]; // NOTE: Do not using a lock because it could because GetAssociatedPageIds is used inside transactions on some sites and it causes deadlocks // lock (buildingLock) { map = _generatedMaps[scopeKey]; if (map != null) { return map; } Version version = _versions[scopeKey]; if (version == null) { lock (_updatingLock) { version = _versions[scopeKey]; if (version == null) { _versions.Add(scopeKey, version = new Version()); } } } Thread.MemoryBarrier(); int currentVersion = version.VersionNumber; Thread.MemoryBarrier(); using(new DataScope(publicationScope, localizationScope)) { map = BuildMap(urlSpace); } lock (_updatingLock) { if (_versions[scopeKey].VersionNumber == currentVersion) { _generatedMaps.Remove(scopeKey); _generatedMaps.Add(scopeKey, map); } } return map; } } private static Tuple GetScopeKey(PublicationScope publicationScope, CultureInfo cultureInfo, UrlSpace urlSpace) { string hostnameScopeKey = urlSpace.ForceRelativeUrls ? "relative urls" : urlSpace.Hostname; return new Tuple(publicationScope, cultureInfo.Name, hostnameScopeKey); } /// [Obsolete("Use Composite.Core.Routing namespace to work with URLs")] public static bool TryGetPageUrl(Guid guid, out string pageUrl) { return GetMap().IdToUrlLookup.TryGetValue(guid, out pageUrl); } /// [Obsolete("Use Composite.Core.WebClient.UrlPageHelper class")] public static bool TryGetPageUrlByFriendlyUrl(string friendlyUrl, out string pageUrl) { string lowerFriendlyUrl = friendlyUrl.ToLowerInvariant(); string matchingUrl = GetSiteMap().DescendantsAndSelf().Attributes("FriendlyUrl").Where(f => f.Value.ToLowerInvariant() == lowerFriendlyUrl).Select(f => f.Parent.Attribute("URL").Value).FirstOrDefault(); pageUrl = matchingUrl; return matchingUrl != null; } /// [Obsolete("Use Composite.Core.Routing namespace to work with URLs")] public static Dictionary GetUrlToIdLookup() { return GetMap().UrlToIdLookup; } /// [Obsolete("Use Composite.Core.Routing namespace to work with URLs")] public static Dictionary GetLowerCaseUrlToIdLookup() { return GetMap().LowerCaseUrlToIdLookup; } /// [Obsolete("Use Composite.Core.Routing namespace to work with URLs")] public static IPageUrlBuilder GetPageUrlBuilder(PublicationScope publicationScope, CultureInfo localizationScope, UrlSpace urlSpace) { return GetMap(publicationScope, localizationScope, urlSpace).PageUrlBuilder; } /// [Obsolete("Use Composite.Core.Routing namespace to work with URLs")] public static Dictionary GetIdToUrlLookup() { return GetIdToUrlLookup(DataScopeManager.CurrentDataScope.Name, LocalizationScopeManager.CurrentLocalizationScope); } /// [Obsolete("Use Composite.Core.Routing namespace to work with URLs")] public static Dictionary GetIdToUrlLookup(string dataScopeIdentifier, CultureInfo culture) { using (new DataScope(DataScopeIdentifier.Deserialize(dataScopeIdentifier), culture)) { return GetMap().IdToUrlLookup; } } private static IEnumerable GetPageElementBySiteDepth(XElement associatedPageElement, int siteDepth) { XElement match = associatedPageElement.AncestorsAndSelf(PageElementName).Reverse().Take(siteDepth).LastOrDefault(); if (match != null && match.Attribute("Depth").Value == siteDepth.ToString()) { yield return match; } } internal static IEnumerable GetPageElementsByScope(SitemapScope associationScope, XElement currentPageElement) { IEnumerable scopeElements = null; XElement matchPage; switch (associationScope) { case SitemapScope.Parent: if (currentPageElement.Parent != null && currentPageElement.Parent.Name == PageElementName) { yield return currentPageElement.Parent; } break; case SitemapScope.Descendants: scopeElements = currentPageElement.Descendants(PageElementName); break; case SitemapScope.DescendantsAndCurrent: scopeElements = currentPageElement.DescendantsAndSelf(PageElementName); break; case SitemapScope.Children: scopeElements = currentPageElement.Elements(PageElementName); break; case SitemapScope.Siblings: scopeElements = currentPageElement.Parent.Elements(PageElementName); break; case SitemapScope.Ancestors: scopeElements = currentPageElement.Ancestors(PageElementName); break; case SitemapScope.AncestorsAndCurrent: scopeElements = currentPageElement.AncestorsAndSelf(PageElementName); break; case SitemapScope.Level1: scopeElements = GetPageElementBySiteDepth(currentPageElement, 1); break; case SitemapScope.Level2: scopeElements = GetPageElementBySiteDepth(currentPageElement, 2); break; case SitemapScope.Level3: scopeElements = GetPageElementBySiteDepth(currentPageElement, 3); break; case SitemapScope.Level4: scopeElements = GetPageElementBySiteDepth(currentPageElement, 4); break; case SitemapScope.Level1AndDescendants: scopeElements = GetPageElementBySiteDepth(currentPageElement, 1).DescendantsAndSelf(); break; case SitemapScope.Level2AndDescendants: scopeElements = GetPageElementBySiteDepth(currentPageElement, 2).DescendantsAndSelf(); break; case SitemapScope.Level3AndDescendants: scopeElements = GetPageElementBySiteDepth(currentPageElement, 3).DescendantsAndSelf(); break; case SitemapScope.Level4AndDescendants: scopeElements = GetPageElementBySiteDepth(currentPageElement, 4).DescendantsAndSelf(); break; case SitemapScope.Level1AndSiblings: matchPage = GetPageElementBySiteDepth(currentPageElement, 1).FirstOrDefault(); if (matchPage != null && matchPage.Parent != null) { scopeElements = matchPage.Parent.Elements(PageElementName); } break; case SitemapScope.Level2AndSiblings: matchPage = GetPageElementBySiteDepth(currentPageElement, 1).FirstOrDefault(); if (matchPage != null) { scopeElements = matchPage.Elements(PageElementName); } break; case SitemapScope.Level3AndSiblings: matchPage = GetPageElementBySiteDepth(currentPageElement, 2).FirstOrDefault(); if (matchPage != null) { scopeElements = matchPage.Elements(PageElementName); } break; case SitemapScope.Level4AndSiblings: matchPage = GetPageElementBySiteDepth(currentPageElement, 3).FirstOrDefault(); if (matchPage != null) { scopeElements = matchPage.Elements(PageElementName); } break; default: throw new NotImplementedException("Unhandled SitemapScope type: " + associationScope); } if (scopeElements != null) { foreach (XElement scopeElement in scopeElements) { yield return scopeElement; } } } private class PageTreeInfo { public Guid ID; public int LocalOrdering; public XElement Element; } private class SitemapBuildingData { private class PageIdComparer : IEqualityComparer { public bool Equals(IPage x, IPage y) => x.Id == y.Id; public int GetHashCode(IPage obj) => obj.Id.GetHashCode(); } public SitemapBuildingData() { Pages = DataFacade.GetData().Evaluate().Distinct(new PageIdComparer()).ToList(); Structures = DataFacade.GetData().ToList(); PageById = new Hashtable(); foreach (IPage page in Pages) { PageById.Add(page.Id, page); } StructureById = new Hashtable(); foreach (IPageStructure structure in Structures) { StructureById.Add(structure.Id, structure); } } public List Pages { get; private set; } public List Structures { get; private set; } public Hashtable PageById { get; private set; } public Hashtable StructureById { get; private set; } } private static Map BuildMap(UrlSpace urlSpace) { using (DebugLoggingScope.MethodInfoScope) { var publicationScope = DataScopeManager.CurrentDataScope.ToPublicationScope(); var localizationScope = LocalizationScopeManager.CurrentLocalizationScope; Log.LogVerbose(LogTitle, string.Format("Building page structure in the publication scope '{0}' with the localization scope '{1}'", publicationScope, localizationScope)); var urlToIdLookup = new Dictionary(); var idToUrlLookup = new Dictionary(); var pagesData = new SitemapBuildingData(); var pageToToChildElementsTable = new Hashtable>(); foreach (IPage page in pagesData.Pages) { IPageStructure pageStructure = pagesData.StructureById[page.Id]; if (pageStructure == null) { Log.LogWarning(LogTitle, "Failed to find PageStructure data. Page ID is '{0}'".FormatWith(page.Id)); continue; } int localOrdering = pageStructure.LocalOrdering; var pageElement = new XElement(ElementNames.Page, new XAttribute(AttributeNames.Id, page.Id), new XAttribute(AttributeNames.Title, page.Title), (string.IsNullOrEmpty(page.MenuTitle) ? null : new XAttribute(AttributeNames.MenuTitle, page.MenuTitle)), new XAttribute(AttributeNames.UrlTitle, page.UrlTitle), new XAttribute(AttributeNames.Description, page.Description ?? string.Empty), new XAttribute(AttributeNames.ChangedDate, page.ChangeDate), new XAttribute(AttributeNames.ChangedBy, page.ChangedBy ?? string.Empty)); var list = pageToToChildElementsTable[pageStructure.ParentId]; if (list == null) { list = new List(); pageToToChildElementsTable[pageStructure.ParentId] = list; } list.Add(new PageTreeInfo { ID = page.Id, LocalOrdering = localOrdering, Element = pageElement }); } var root = new XElement("root"); BuildXmlStructure(root, Guid.Empty, pageToToChildElementsTable, 100); #pragma warning disable 612 var pageUrlBuilder = PageUrls.UrlProvider.CreateUrlBuilder(publicationScope, localizationScope, urlSpace); BuildFolderPaths(pagesData, root.Elements(), pageUrlBuilder, urlToIdLookup); #pragma warning restore 612 foreach (var urlLookupEntry in urlToIdLookup) { idToUrlLookup.Add(urlLookupEntry.Value, urlLookupEntry.Key); } var lowerCaseUrlToIdLookup = new Dictionary(); foreach (KeyValuePair keyValuePair in urlToIdLookup) { string loweredUrl = keyValuePair.Key.ToLowerInvariant(); if (lowerCaseUrlToIdLookup.ContainsKey(loweredUrl)) { if (!_knownNotUniqueUrls.Contains(loweredUrl)) { lock (_knownNotUniqueUrls) { _knownNotUniqueUrls.Add(loweredUrl); } Log.LogError(LogTitle, "Multiple pages share the same path '{0}'. Page ID: '{1}'. Duplicates are ignored.".FormatWith(loweredUrl, keyValuePair.Value)); } continue; } lowerCaseUrlToIdLookup.Add(loweredUrl, keyValuePair.Value); } return new Map { IdToUrlLookup = idToUrlLookup, UrlToIdLookup = urlToIdLookup, LowerCaseUrlToIdLookup = lowerCaseUrlToIdLookup, RootPagesLookup = root.Elements(), PageUrlBuilder = pageUrlBuilder }; } } private static void BuildXmlStructure(XElement root, Guid currentPageId, Hashtable> pageToChildElementsTable, int depth) { if (depth == 0) return; List children = pageToChildElementsTable[currentPageId]; if (children == null) { return; } foreach (PageTreeInfo pageInfo in children.OrderBy(pageInfo => pageInfo.LocalOrdering)) { root.Add(pageInfo.Element); BuildXmlStructure(pageInfo.Element, pageInfo.ID, pageToChildElementsTable, depth - 1); } } [Obsolete("Use Composite.Core.Routing namespace to work with URLs")] private static void BuildFolderPaths(SitemapBuildingData pagesData, IEnumerable roots, IPageUrlBuilder pageUrlBuilder, IDictionary urlToIdLookup) { BuildFolderPaths(pagesData, roots, urlToIdLookup, pageUrlBuilder); } [Obsolete("Use Composite.Core.Routing namespace to work with URLs")] private static void BuildFolderPaths(SitemapBuildingData pagesData, IEnumerable elements, IDictionary urlToIdLookup, IPageUrlBuilder builder) { foreach (XElement element in elements) { Guid pageId = new Guid(element.Attribute(AttributeNames.Id).Value); IPage page = pagesData.PageById[pageId]; IPageStructure pageStructure = pagesData.StructureById[pageId]; if (pageStructure == null) { continue; } Guid parentId = pageStructure.ParentId; PageUrlSet pageUrls = builder.BuildUrlSet(page, parentId); if(pageUrls == null) { continue; } element.Add(new XAttribute(AttributeNames.URL, pageUrls.PublicUrl)); string lookupUrl = pageUrls.PublicUrl; if(pageUrls.FriendlyUrl != null) { element.Add(new XAttribute(AttributeNames.FriendlyUrl, pageUrls.FriendlyUrl)); } //// FolderPath isn't used any more //element.Add(new XAttribute("FolderPath", builder.FolderPaths[pageId])); element.Add(new XAttribute(AttributeNames.Depth, 1 + element.Ancestors(PageElementName).Count())); // NOTE: urlToIdLookup is obsolete, but old API needs it if (urlToIdLookup.ContainsKey(lookupUrl)) { Log.LogError(LogTitle, "Multiple pages share the same path '{0}', page ID: '{1}'. Duplicates are ignored.".FormatWith(pageUrls.PublicUrl, pageId)); continue; } urlToIdLookup.Add(lookupUrl, pageId); BuildFolderPaths(pagesData, element.Elements(), urlToIdLookup, builder); } } private static void OnPagesChanged(object sender, StoreEventArgs args) { IncrementVersion(DataScopeIdentifier.FromPublicationScope(args.PublicationScope)); } private static void OnPageStructureChanged(object sender, StoreEventArgs args) { IncrementVersion(DataScopeIdentifier.Public); IncrementVersion(DataScopeIdentifier.Administrated); } private static void IncrementVersion(DataScopeIdentifier dataScopeIdentifier) { var publicationScope = dataScopeIdentifier.ToPublicationScope(); ClearCachedData(key => key.Item1 == publicationScope); } private static void ClearCachedData() { ClearCachedData(c => true); } private static void ClearCachedData(Func condition) { lock (_updatingLock) { var keysToUpdate = _versions.GetKeys().Where(condition).ToList(); foreach (var key in keysToUpdate) { // Updating versions Interlocked.Increment(ref _versions[key].VersionNumber); // Clearing cached data _generatedMaps.Remove(key); } } } private static void AnnotatePagesWithOpenAndCurrent(Guid pageId, List pageElements) { string pageIdAsString = pageId.ToString(); XAttribute matchingPageIdAttrib = GetSiteMap().DescendantsAndSelf().Attributes(AttributeNames.Id).FirstOrDefault(f => f.Value == pageIdAsString); if (matchingPageIdAttrib != null) { List openPageIdList = matchingPageIdAttrib.Parent.AncestorsAndSelf(PageElementName).Attributes(AttributeNames.Id).Select(f => f.Value).ToList(); foreach (XElement openPage in pageElements.DescendantsAndSelf(PageElementName).Where(f => openPageIdList.Contains(f.Attribute(AttributeNames.Id).Value))) { openPage.Add(new XAttribute("isopen", "true")); if (openPage.Attribute(AttributeNames.Id).Value == pageIdAsString) { openPage.Add(new XAttribute("iscurrent", "true")); } } } } private static IEnumerable GetSitemapByScopeUnannotated(SitemapScope associationScope, Guid pageId) { if (associationScope == SitemapScope.All) { foreach (XElement homepage in GetSiteMap()) { yield return new XElement(homepage); } yield break; } Verify.ArgumentCondition(pageId != Guid.Empty, "pageId", "The parameter is Guid.Empty"); XElement currentPageElement = PageStructureInfo.GetSiteMap().DescendantsAndSelf().FirstOrDefault(f => f.Attribute("Id").Value == pageId.ToString()); // finde dybden - hvis scope dybden == nuværende dybde + 1, så skift nuværende til first child if (currentPageElement == null) throw new ArgumentException("No page with the given ID could be located in the current data scope ('{0}').".FormatWith(pageId), "pageId"); XElement pageCopy = null; switch (associationScope) { case SitemapScope.Current: yield return new XElement(currentPageElement.Name, currentPageElement.Attributes()); break; case SitemapScope.Parent: if (currentPageElement.Parent != null && currentPageElement.Parent.Name == PageElementName) { yield return new XElement(currentPageElement.Parent.Name, currentPageElement.Parent.Attributes()); } break; case SitemapScope.Descendants: foreach (XElement child in currentPageElement.Elements(PageElementName)) { yield return new XElement(child); } break; case SitemapScope.DescendantsAndCurrent: yield return new XElement(currentPageElement); break; case SitemapScope.Children: foreach (XElement page in currentPageElement.Elements(PageElementName)) { yield return new XElement(page.Name, page.Attributes()); } break; case SitemapScope.Siblings: foreach (XElement page in currentPageElement.Parent.Elements(PageElementName)) { yield return new XElement(page.Name, page.Attributes()); } break; case SitemapScope.Ancestors: foreach (XElement page in currentPageElement.Ancestors(PageElementName)) { pageCopy = new XElement(page.Name, page.Attributes(), pageCopy); } yield return pageCopy; break; case SitemapScope.AncestorsAndCurrent: foreach (XElement page in currentPageElement.AncestorsAndSelf(PageElementName)) { pageCopy = new XElement(page.Name, page.Attributes(), pageCopy); } yield return pageCopy; break; case SitemapScope.Level1: pageCopy = GetPageCopyBySiteDepth(currentPageElement, 1, true); if (pageCopy != null) { yield return pageCopy; } break; case SitemapScope.Level2: pageCopy = GetPageCopyBySiteDepth(currentPageElement, 2, true); if (pageCopy != null) { yield return pageCopy; } break; case SitemapScope.Level3: pageCopy = GetPageCopyBySiteDepth(currentPageElement, 3, true); if (pageCopy != null) { yield return pageCopy; } break; case SitemapScope.Level4: pageCopy = GetPageCopyBySiteDepth(currentPageElement, 4, true); if (pageCopy != null) { yield return pageCopy; } break; case SitemapScope.Level1AndSiblings: foreach (XElement page in PageStructureInfo.GetSiteMap()) { yield return new XElement(page.Name, page.Attributes()); } break; case SitemapScope.Level2AndSiblings: foreach (XElement page in GetSiblingsCopyBySiteDepth(currentPageElement, 2)) { yield return page; } break; case SitemapScope.Level3AndSiblings: foreach (XElement page in GetSiblingsCopyBySiteDepth(currentPageElement, 3)) { yield return page; } break; case SitemapScope.Level4AndSiblings: foreach (XElement page in GetSiblingsCopyBySiteDepth(currentPageElement, 4)) { yield return page; } break; case SitemapScope.Level1AndDescendants: pageCopy = GetPageCopyBySiteDepth(currentPageElement, 1, false); if (pageCopy != null) { yield return pageCopy; } break; case SitemapScope.Level2AndDescendants: pageCopy = GetPageCopyBySiteDepth(currentPageElement, 2, false); if (pageCopy != null) { yield return pageCopy; } break; case SitemapScope.Level3AndDescendants: pageCopy = GetPageCopyBySiteDepth(currentPageElement, 3, false); if (pageCopy != null) { yield return pageCopy; } break; case SitemapScope.Level4AndDescendants: pageCopy = GetPageCopyBySiteDepth(currentPageElement, 4, false); if (pageCopy != null) { yield return pageCopy; } break; default: throw new NotImplementedException("Unhandled SitemapScope type: " + associationScope); } } private static XElement GetPageCopyBySiteDepth(XElement associatedPageElement, int siteDepth, bool shallow) { string siteDepthStr = siteDepth.ToString(); XElement match = associatedPageElement.AncestorsAndSelf(PageElementName).SingleOrDefault(f => f.Attribute(AttributeNames.Depth).Value == siteDepthStr); if (match == null) { return null; } if (shallow) { return new XElement(match.Name, match.Attributes()); } return new XElement(match); } private static IEnumerable GetSiblingsCopyBySiteDepth(XElement associatedPageElement, int siteDepth) { int currentPageDepth = Int32.Parse(associatedPageElement.Attribute(AttributeNames.Depth).Value); IEnumerable elementsToCopy = null; if (siteDepth == 1) { elementsToCopy = associatedPageElement.AncestorsAndSelf(PageElementName).Where(f => f.Attribute(AttributeNames.Depth).Value == "1"); } else if (currentPageDepth >= siteDepth) { elementsToCopy = associatedPageElement.AncestorsAndSelf(PageElementName).Where(f => f.Attribute(AttributeNames.Depth).Value == (siteDepth - 1).ToString()).Elements(PageElementName); } else { if (currentPageDepth == siteDepth - 1) { elementsToCopy = associatedPageElement.Elements(PageElementName); } } if (elementsToCopy != null) { foreach (XElement pageElement in elementsToCopy) { yield return new XElement(pageElement.Name, pageElement.Attributes()); } } } } } ================================================ FILE: Composite/Core/WebClient/Renderings/Page/RenderingReason.cs ================================================ namespace Composite.Core.WebClient.Renderings.Page { /// /// Describes a rendering reason /// public enum RenderingReason { /// /// Undefined /// Undefined = 0, /// /// A page was requested through a browser /// PageView = 1, /// /// A page is viewed from C1 Console's browser /// C1ConsoleBrowserPageView = 2, /// /// A page is rendered from withing an "Edit page" workflow /// PreviewUnsavedChanges = 4, /// /// A page is rendered to generate an image to be used for function/template visualization /// ScreenshotGeneration = 8, /// /// A page is rendered to build a search index. /// BuildSearchIndex = 16 } } ================================================ FILE: Composite/Core/WebClient/Renderings/Page/XElementToAspNetExtensions.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Xml.Linq; using Composite.Core.Instrumentation; using Composite.Core.Xml; namespace Composite.Core.WebClient.Renderings.Page { /// /// /// [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class XElementToAspNetExtensions { private static readonly XName XName_Id = "id"; private static readonly XName XName_Xmlns = "xmlns"; private static readonly XName XName_Title = Namespaces.Xhtml + "title"; private static readonly XName XName_Meta = Namespaces.Xhtml + "meta"; private static readonly HashSet VoidElements = new HashSet { "area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr" }; /// public static Control AsAspNetControl(this XhtmlDocument xhtmlDocument) { return xhtmlDocument.AsAspNetControl(NoMappingMapper.GetInstance()); } /// public static Control AsAspNetControl(this XhtmlDocument xhtmlDocument, IXElementToControlMapper controlMapper) { using (TimerProfilerFacade.CreateTimerProfiler()) { var htmlControl = new HtmlGenericControl("html"); CopyAttributes(xhtmlDocument.Root, htmlControl); HtmlHead headControl = xhtmlDocument.BuildHtmlHeadControl(controlMapper); Control bodyControl = xhtmlDocument.Body.AsAspNetControl(controlMapper); htmlControl.Controls.Add(headControl); htmlControl.Controls.Add(bodyControl); PlaceHolder pageHolder = new PlaceHolder(); if (xhtmlDocument.DocumentType != null) { string docType = xhtmlDocument.DocumentType.ToString(); var offset = docType.IndexOf("[]", StringComparison.Ordinal); if (offset >= 0) { docType = docType.Remove(offset, 2); } pageHolder.Controls.Add(new LiteralControl(docType)); } pageHolder.Controls.Add(htmlControl); return pageHolder; } } /// public static Control AsAspNetControl(this XNode xnode) { return xnode.AsAspNetControl(NoMappingMapper.GetInstance()); } /// public static Control AsAspNetControl(this XNode xnode, IXElementToControlMapper controlMapper) { if (xnode is XElement element) return element.AsAspNetControl(controlMapper); if (xnode is XDocument document) return document.Root.AsAspNetControl(controlMapper); if (xnode is XText text) return new LiteralControl(text.Value); if (xnode is XComment comment) return new LiteralControl($""); throw new NotImplementedException($"Type '{xnode.GetType().Name}' not handled"); } /// public static Control AsAspNetControl(this XElement element) { return element.AsAspNetControl(NoMappingMapper.GetInstance()); } /// public static Control AsAspNetControl(this XElement element, IXElementToControlMapper controlMapper) { Control control; if (!controlMapper.TryGetControlFromXElement(element, out control)) { if (IsHtmlControlElement(element) || element.Attribute(XName_Id) != null) { control = new HtmlGenericControl(element.Name.LocalName) { ClientIDMode = ClientIDMode.Static }; CopyAttributes(element, (HtmlControl)control); ExportChildNodes(element.Nodes(), control, controlMapper); } else { XElement copy = CopyWithoutNamespace(element, Namespaces.Xhtml); control = new LiteralControl(copy.ToString()); } } return control; } private static XElement CopyWithoutNamespace(XElement source, XNamespace namespaceToRemove) { XNamespace sourceNs = source.Name.Namespace; XName newName = sourceNs.Equals(namespaceToRemove) ? source.Name.LocalName : source.Name; XElement copy = new XElement(newName); if (!sourceNs.Equals(namespaceToRemove) && sourceNs != source.Parent.Name.Namespace && source.Attribute(XName_Xmlns) == null && (sourceNs == Namespaces.Xhtml.NamespaceName || sourceNs == Namespaces.Svg.NamespaceName)) { copy.Add(new XAttribute(XName_Xmlns, source.Name.Namespace)); } copy.Add(source.Attributes().Where(a => a.Name.Namespace == namespaceToRemove) .Select(a => new XAttribute(a.Name.LocalName, a.Value))); Func isNotHtmlRelatedNsDeclaration = ns => !ns.IsNamespaceDeclaration || (ns.Value != Namespaces.Xhtml.NamespaceName && ns.Value != Namespaces.Svg.NamespaceName); copy.Add(source.Attributes().Where(a => a.Name.Namespace != namespaceToRemove && isNotHtmlRelatedNsDeclaration(a)) .Select(a => new XAttribute(a.Name, a.Value))); foreach (XNode child in source.Nodes()) { if (child is XElement) { copy.Add(CopyWithoutNamespace(child as XElement, namespaceToRemove)); } else { copy.Add(child); } } return copy; } private static bool IsHtmlControlElement(XElement element) { var name = element.Name; string xNamespace = element.Name.Namespace.NamespaceName; return (xNamespace == Namespaces.Xhtml.NamespaceName || xNamespace == string.Empty) && !VoidElements.Contains(name.LocalName); } private static void ExportChildNodes(IEnumerable nodes, Control containerControl, IXElementToControlMapper controlMapper) { foreach (var childNode in nodes) { if (childNode is XElement element) { containerControl.Controls.Add(element.AsAspNetControl(controlMapper)); continue; } if (childNode is XCData cdata) { if (!childNode.Ancestors().Any(f => f.Name.LocalName == "script")) { var literal = new LiteralControl(cdata.Value); containerControl.Controls.Add(literal); continue; } } if (childNode is XText) { var literal = new LiteralControl(childNode.ToString()); containerControl.Controls.Add(literal); continue; } if (childNode is XComment) { containerControl.Controls.Add(new LiteralControl(childNode + "\n")); continue; } throw new NotImplementedException($"Unhandled XNode type '{childNode.GetType()}'"); } } /// public static void CopyAttributes(this XElement source, HtmlControl target) { CopyAttributes(source, target, true); } /// public static void CopyAttributes(this XElement source, HtmlControl target, bool copyXmlnsAttribute) { foreach (var attribute in source.Attributes()) { if (attribute.Name.LocalName == "id") { target.ID = attribute.Value; continue; } if (attribute.Name.Namespace == Namespaces.XmlNs) { string namespaceName = attribute.Value; if (namespaceName != "http://www.w3.org/1999/xhtml" && !namespaceName.StartsWith("http://www.composite.net/ns")) { target.Attributes.Add($"xmlns:{attribute.Name.LocalName}", attribute.Value); } continue; } string localName = attribute.Name.LocalName; if (localName != XName_Xmlns || (copyXmlnsAttribute && (source.Parent == null || source.Name.Namespace != source.Parent.Name.Namespace))) { string htmlAttributeName; if (attribute.Name.Namespace != source.Name.Namespace && attribute.Name.Namespace.NamespaceName != string.Empty) { string namespacePrefix = source.GetPrefixOfNamespace(attribute.Name.NamespaceName); htmlAttributeName = namespacePrefix + ":" + localName; } else { htmlAttributeName = localName; } target.Attributes.Add(htmlAttributeName, attribute.Value); } } } internal static void MergeToHeadControl(this XhtmlDocument xhtmlDocument, HtmlHead headControl, IXElementToControlMapper controlMapper) { XElement headSource = xhtmlDocument.Head; if (headSource == null) return; CopyAttributes(headSource, headControl); XElement titleElement = headSource.Elements(XName_Title).LastOrDefault(); if (titleElement != null) { HtmlTitle existingControl = headControl.Controls.OfType().FirstOrDefault(); if (existingControl != null) { headControl.Controls.Remove(existingControl); } // NOTE: we aren't using headControl.Title property since it adds "" tag as the last one headControl.Controls.AddAt(0, new HtmlTitle { Text = HttpUtility.HtmlEncode(titleElement.Value) }); } var metaTags = headSource.Elements().Where(f => f.Name == XName_Meta); int metaTagPosition = Math.Min(1, headControl.Controls.Count); foreach (var metaTag in metaTags) { var metaControl = new HtmlMeta(); foreach (var attribute in metaTag.Attributes()) { if (attribute.Name.LocalName == "id") { metaControl.ID = attribute.Value; } else { metaControl.Attributes.Add(attribute.Name.LocalName, attribute.Value); } } headControl.Controls.AddAt(metaTagPosition++, metaControl); } ExportChildNodes(headSource.Nodes().Where(f => !(f is XElement element) || (element.Name != XName_Title && element.Name != XName_Meta)), headControl, controlMapper); headControl.RemoveDuplicates(); } private static void RemoveDuplicates(this HtmlHead headControl) { HashSet<string> uniqueIdValues = new HashSet<string>(); HashSet<string> uniqueMetaNameValues = new HashSet<string>(); HashSet<string> uniqueScriptAttributes = new HashSet<string>(); HashSet<string> uniqueLinkAttributes = new HashSet<string>(); IEnumerable<HtmlControl> controls = headControl.Controls.OfType<HtmlControl>(); // Leaving last instances of each meta tag, and first instances of script/link tags var priorityOrderedControls = new List<HtmlControl>(); var ignoreCase = StringComparison.OrdinalIgnoreCase; priorityOrderedControls.AddRange(controls.Where(c => c.TagName.Equals("meta", ignoreCase)).Reverse()); priorityOrderedControls.AddRange(controls.Where(c => !c.TagName.Equals("meta", ignoreCase))); foreach (HtmlControl c in priorityOrderedControls) { bool remove = IsDuplicate(uniqueIdValues, c.ClientID); if (c.Controls.Count == 0) { switch (c.TagName.ToLower()) { case "meta": remove = remove || IsDuplicate(uniqueMetaNameValues, c.Attributes["name"]); break; case "script": remove = remove || IsDuplicate(uniqueScriptAttributes, c.AttributesAsString()); break; case "link": remove = remove || IsDuplicate(uniqueLinkAttributes, c.AttributesAsString()); break; } } if (remove) { headControl.Controls.Remove(c); } } } private static string AttributesAsString(this HtmlControl c) { var str = new StringBuilder(c.ClientID); var keys = c.Attributes.Keys.Cast<string>().OrderBy(f => f); foreach (string key in keys) { str.Append(key); str.Append("=\""); str.Append(c.Attributes[key]); str.Append("\" "); } return str.ToString(); } private static bool IsDuplicate(HashSet<string> uniqueList, string uniqueString) { if (!string.IsNullOrEmpty(uniqueString)) { var lowered = uniqueString.ToLowerInvariant(); if (uniqueList.Contains(lowered)) { return true; } uniqueList.Add(lowered); } return false; } private static HtmlHead BuildHtmlHeadControl(this XhtmlDocument xhtmlDocument, IXElementToControlMapper controlMapper) { var headControl = new HtmlHead(); xhtmlDocument.MergeToHeadControl(headControl, controlMapper); return headControl; } #region Private helper class private class NoMappingMapper : IXElementToControlMapper { private static readonly NoMappingMapper _instance = new NoMappingMapper(); public static IXElementToControlMapper GetInstance() { return _instance; } public bool TryGetControlFromXElement(XElement element, out Control control) { control = null; return false; } } #endregion } } ================================================ FILE: Composite/Core/WebClient/Renderings/Page/XEmbeddedControlMapper.cs ================================================ using System; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Xml.Linq; using Composite.Core.Collections.Generic; using Composite.Core.Xml; using Composite.Core.Extensions; using Composite.Functions; namespace Composite.Core.WebClient.Renderings.Page { internal sealed class XEmbeddedControlMapper : IFunctionResultToXEmbedableMapper, IXElementToControlMapper { private static readonly XName _markerElementName = Namespaces.AspNetControls + "marker"; private static readonly XName _formElementName = Namespaces.AspNetControls + "form"; private static readonly XName _placeholderElementName = Namespaces.AspNetControls + "placeholder"; private readonly Hashtable<string, Control> _controls = new Hashtable<string, Control>(); // IFunctionResultToXElementMapper public bool TryMakeXEmbedable(FunctionContextContainer contextContainer, object resultObject, out XNode resultElement) { var control = resultObject as Control; if (control == null) { resultElement = null; return false; } string controlMarkerKey; lock (_controls) { controlMarkerKey = string.Format("[Composite.Function.Render.Asp.Net.Control.{0}]", _controls.Count); _controls.Add(controlMarkerKey, control); } resultElement = XElement.Parse(@"<c1marker:{0} xmlns:c1marker=""{1}"" key=""{2}"" />" .FormatWith(_markerElementName.LocalName, _markerElementName.Namespace, controlMarkerKey)); return true; } // IXElementToControlMapper public bool TryGetControlFromXElement(XElement element, out Control control) { if (element.Name.Namespace != Namespaces.AspNetControls) { control = null; return false; } if (element.Name == _markerElementName) { control = _controls[element.Attribute("key").Value]; return true; } if (element.Name == _formElementName) { control = new HtmlForm(); element.CopyAttributes(control as HtmlForm, false); foreach (var child in element.Nodes()) { control.Controls.Add(child.AsAspNetControl(this)); } return true; } if (element.Name == _placeholderElementName) { control = new PlaceHolder(); XAttribute idAttribute = element.Attribute("id"); if (idAttribute != null) { control.ID = idAttribute.Value; } foreach (var child in element.Nodes()) { control.Controls.Add(child.AsAspNetControl(this)); } return true; } throw new InvalidOperationException(string.Format("Unhandled ASP.NET tag '{0}'.", element.Name)); } } } ================================================ FILE: Composite/Core/WebClient/Renderings/Plugins/RenderingResponseHandler/IDataRenderingResponseHandler.cs ================================================ using Composite.Data; namespace Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandler { /// <summary> /// C1 CMS allow you to build a RenderingResponseHandler plug-in. It enables developers to intercept /// page and media requests and control if the request should be accepted or redirected and if the rendered /// resource is allowed to be publicly cached. /// </summary> /// <remarks> /// To create a RenderingResponseHandler plug-in: /// <list type="number"> /// <item> /// <description>In Visual Studio, create a new "Class Library" project (or use an existing project if you have one).</description> /// </item> /// <item> /// <description>Add references to the following assemblies ( Browse and located on your web site): /// <list type="bullet"> /// <item> /// <description>/bin/Composite.dll</description> /// </item> /// <item> /// <description>/bin/Microsoft.Practices.EnterpriseLibrary.Common.dll</description> /// </item> /// </list></description> /// </item> /// <item> /// <description>In each assembly reference's properties, set Copy Local to 'False'.</description> /// </item> /// <item> /// <description>Add a reference to System.Configuration (.NET)</description> /// </item> /// <item> /// <description>Create a new class for your plug-in (see the source code example below).</description> /// </item> /// <item> /// <description>Compile the project and copy the DLL to the website /bin folder.</description> /// </item> /// </list> /// To register a RenderingResponseHandler plug-in: /// <list type="number"> /// <item> /// <description>Edit the file /App_Data/Composite/Composite.config.</description> /// </item> /// <item> /// <description>Locate the element <RenderingResponseHandlerPlugins />.</description> /// </item> /// <item> /// <description>Add a new element inside the <RenderingResponseHandlerPlugins /> element: /// /// <add name="Sample" type="TypeName, AssemblyName"/> /// /// changing 'Sample' to a name relevant to your project and 'TypeName, AssemblyName' to the fully qualified class name of your plug-in class.</description> /// </item> /// <item> /// <description>Restart the C1 site (recycle app pool or use C1 Console; Tools | Restart Server)</description> /// </item> /// </list> /// </remarks> /// <example> /// Sample plugin: /// <code> ///using System; ///using Composite.Data; ///using Composite.Data.Types; ///using Composite.Core.Logging; ///using Composite.Core.WebClient.Renderings; ///using Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandler; /// ///using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; /// /// ///namespace RenderingResponseHandlerSample ///{ /// [ConfigurationElementType(typeof(NonConfigurableRenderingResponseHandler))] /// public class RenderingResponseHandlerPluginSample : IDataRenderingResponseHandler /// { /// // Have the TCP logger running to see the string being logged - see Composite.Tools.TcpCustomTraceListener /// // This sample will redirect requests for pages and media containing the word 'secret' in their title / path. /// public RenderingResponseHandlerResult GetDataResponseHandling(DataEntityToken requestedItemEntityToken) /// { /// IData requestedData = requestedItemEntityToken.Data; /// /// bool redirect = false; /// /// if (requestedData is IPage) /// { /// IPage requestedPage = (IPage)requestedData; /// LoggingService.LogVerbose("Sample", string.Format("Request for page '{0}'.", requestedPage.Title)); /// /// if (requestedPage.Title.ToLower().Contains("secret")) /// { /// redirect = true; /// } /// } /// else if (requestedData is IMediaFile) /// { /// IMediaFile requestedMediaFile = (IMediaFile)requestedData; /// LoggingService.LogVerbose("Sample", string.Format("Request for media file '{0}'.", requestedMediaFile.CompositePath)); /// /// if (requestedMediaFile.CompositePath.ToLower().Contains("secret")) /// { /// redirect = true; /// } /// } /// /// if (redirect) /// { /// return new RenderingResponseHandlerResult /// { /// PreventPublicCaching = true, /// RedirectRequesterTo = new Uri("http://docs.composite.net/") /// }; /// } /// else /// { /// return new RenderingResponseHandlerResult /// { /// PreventPublicCaching = false /// }; /// } /// } /// } ///} /// </code> /// Sample configuration snippet from Composite.config: /// <code> /// <Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandlerConfiguration> /// <RenderingResponseHandlerPlugins> /// <add name="Sample" type="RenderingResponseHandlerSample.RenderingResponseHandlerPluginSample, RenderingResponseHandlerSample" /> /// </RenderingResponseHandlerPlugins> /// </Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandlerConfiguration> /// </code> /// </example> public interface IDataRenderingResponseHandler : IRenderingResponseHandler { /// <summary> /// Method which gets called for all C1 media file requests and (un-cached) C1 page requests. /// The fate of the request is described in the <see cref="RenderingResponseHandlerResult"/> return value. /// </summary> /// <param name="requestedItemEntityToken">The data being rendered. This can be <see cref="Composite.Data.Types.IPage"/> and <see cref="Composite.Data.Types.IMediaFile"/>.</param> /// <returns>A <see cref="RenderingResponseHandlerResult"/> object detailing what should happen to the user request. Returning null means no special handling should be done (request should continue).</returns> RenderingResponseHandlerResult GetDataResponseHandling(DataEntityToken requestedItemEntityToken); } } ================================================ FILE: Composite/Core/WebClient/Renderings/Plugins/RenderingResponseHandler/IRenderingResponseHandler.cs ================================================ using Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandler.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandler { /// <summary> /// Base interface - use the interface <see cref="IDataRenderingResponseHandler"/> for handling page and media requests. /// </summary> [CustomFactory(typeof(RenderingResponseHandlerCustomFactory))] [ConfigurationNameMapper(typeof(RenderingResponseHandlerDefaultNameRetriever))] public interface IRenderingResponseHandler { } } ================================================ FILE: Composite/Core/WebClient/Renderings/Plugins/RenderingResponseHandler/NonConfigurableHookRegistrator.cs ================================================ using System; using Microsoft.Practices.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandler { /// <summary> /// Configuration object with no custom config settings. When developing your own <see cref="IRenderingResponseHandler"/> /// plugin you can use this if you do not require any special configuration in the Composite.config file. /// </summary> [Assembler(typeof(NonConfigurableRenderingResponseHandlerAssembler))] public sealed class NonConfigurableRenderingResponseHandler : RenderingResponseHandlerData { } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class NonConfigurableRenderingResponseHandlerAssembler : IAssembler<IRenderingResponseHandler, RenderingResponseHandlerData> { /// <exclude /> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IRenderingResponseHandler Assemble(IBuilderContext context, RenderingResponseHandlerData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IRenderingResponseHandler)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/Core/WebClient/Renderings/Plugins/RenderingResponseHandler/RenderingResponseHandlerData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandler { /// <summary> /// Base class for <see cref="IRenderingResponseHandler"/> plugin configuration. If you do not require special /// configuration, use <see cref="NonConfigurableRenderingResponseHandler"/>. /// </summary> [ConfigurationElementType(typeof(NonConfigurableRenderingResponseHandler))] public class RenderingResponseHandlerData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/Core/WebClient/Renderings/Plugins/RenderingResponseHandler/Runtime/RenderingResponseHandlerCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandler.Runtime { internal sealed class RenderingResponseHandlerCustomFactory : AssemblerBasedCustomFactory<IRenderingResponseHandler, RenderingResponseHandlerData> { protected override RenderingResponseHandlerData GetConfiguration(string name, IConfigurationSource configurationSource) { RenderingResponseHandlerSettings settings = configurationSource.GetSection(RenderingResponseHandlerSettings.SectionName) as RenderingResponseHandlerSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", RenderingResponseHandlerSettings.SectionName)); } return settings.RenderingResponseHandlerPlugins.Get(name); } } } ================================================ FILE: Composite/Core/WebClient/Renderings/Plugins/RenderingResponseHandler/Runtime/RenderingResponseHandlerDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandler.Runtime { internal sealed class RenderingResponseHandlerDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/Core/WebClient/Renderings/Plugins/RenderingResponseHandler/Runtime/RenderingResponseHandlerFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandler.Runtime { internal sealed class RenderingResponseHandlerFactory : NameTypeFactoryBase<IRenderingResponseHandler> { public RenderingResponseHandlerFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/Core/WebClient/Renderings/Plugins/RenderingResponseHandler/Runtime/RenderingResponseHandlerSettings.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using System.Configuration; using Composite.Core.Configuration; namespace Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandler.Runtime { internal sealed class RenderingResponseHandlerSettings : SerializableConfigurationSection { public const string SectionName = "Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandlerConfiguration"; private const string _hookRegistratorPluginsProperty = "RenderingResponseHandlerPlugins"; [ConfigurationProperty(_hookRegistratorPluginsProperty)] public NameTypeManagerTypeConfigurationElementCollection<RenderingResponseHandlerData> RenderingResponseHandlerPlugins { get { return (NameTypeManagerTypeConfigurationElementCollection<RenderingResponseHandlerData>)base[_hookRegistratorPluginsProperty]; } } } } ================================================ FILE: Composite/Core/WebClient/Renderings/RenderingContext.cs ================================================ using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Web; using Composite.C1Console.Security; using Composite.Core.Extensions; using Composite.Core.Instrumentation; using Composite.Core.PageTemplates; using Composite.Core.Routing; using Composite.Core.Routing.Pages; using Composite.Core.WebClient.Renderings.Page; using Composite.Data; using Composite.Data.Types; using Composite.Plugins.Routing.Pages; namespace Composite.Core.WebClient.Renderings { /// <summary> /// Rendering context /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class RenderingContext: IDisposable { private static readonly string LogTitle = typeof (RenderingContext).Name; /// <summary> /// Indicates whether performance profiling is enabled. /// </summary> /// <value><c>true</c> if profiling is enabled; otherwise, <c>false</c>.</value> public bool ProfilingEnabled { get; private set; } /// <summary> /// Indicates whether page is shown in preview mode. /// </summary> /// <value><c>true</c> if page is shown in preview mode; otherwise, <c>false</c>.</value> public bool PreviewMode { get; private set; } /// <summary> /// Gets the current c1 page. /// </summary> /// <value>The page.</value> public IPage Page { get; private set; } internal PageContentToRender PageContentToRender { get; private set; } /// <summary> /// Indicates whether page caching is disabled. /// </summary> /// <value><c>true</c> if page caching is disabled; otherwise, <c>false</c>.</value> public bool CachingDisabled { get; private set; } private static readonly List<string> _prettifyErrorUrls = new List<string>(); private static int _prettifyErrorCount; private Guid _previewKey; private IDisposable _pagePerfMeasuring; private string _cachedUrl; private IDisposable _dataScope; private RenderingContext() { } /// <exclude /> public static RenderingContext InitializeFromHttpContext() { var renderingContext = new RenderingContext(); renderingContext.InitializeFromHttpContextInternal(); return renderingContext; } /// <summary> /// Runs the response handlers. /// </summary> /// <returns><c>true</c> if a handler has already processed the request and no further writing to response should be done; otherwise, <c>false</c>.</returns> public bool RunResponseHandlers() { if (PreviewMode) { return false; } var httpContext = HttpContext.Current; var response = httpContext.Response; var responseHandling = RenderingResponseHandlerFacade.GetDataResponseHandling(PageRenderer.CurrentPage.GetDataEntityToken()); if (responseHandling != null) { if (responseHandling.PreventPublicCaching) { response.Cache.SetCacheability(HttpCacheability.NoCache); CachingDisabled = true; } if (responseHandling.EndRequest || responseHandling.RedirectRequesterTo != null) { if (responseHandling.RedirectRequesterTo != null) { response.Redirect(responseHandling.RedirectRequesterTo.ToString(), false); } httpContext.ApplicationInstance.CompleteRequest(); return true; } } return false; } /// <exclude /> public IEnumerable<IPagePlaceholderContent> GetPagePlaceholderContents() { return PreviewMode ? PagePreviewContext.GetPageContents(_previewKey) : PageManager.GetPlaceholderContent(Page.Id, Page.VersionId); } /// <exclude /> public string ConvertInternalLinks(string xhtml) { using (Profiler.Measure("Converting internal urls to public")) { return InternalUrls.ConvertInternalUrlsToPublic(xhtml); } } /// <exclude /> public string FormatXhtml(string xhtml) { try { using (Profiler.Measure("Formatting output XHTML with Composite.Core.Xml.XhtmlPrettifier")) { xhtml = Composite.Core.Xml.XhtmlPrettifier.Prettify(xhtml); } } catch { if (!PreviewMode) { const int maxWarningsToShow = 3; if (_prettifyErrorCount < maxWarningsToShow) { lock (_prettifyErrorUrls) { if (!_prettifyErrorUrls.Contains(_cachedUrl) && _prettifyErrorCount < maxWarningsToShow) { _prettifyErrorUrls.Add(_cachedUrl); _prettifyErrorCount++; Log.LogWarning(LogTitle, "Failed to format output xhtml in a pretty way - your page output is likely not strict xml. Url: " + (HttpUtility.UrlDecode(_cachedUrl) ?? "undefined")); if (maxWarningsToShow == _prettifyErrorCount) { Log.LogInformation(LogTitle, $"{maxWarningsToShow} xhtml format errors logged since startup. No more will be logged until next startup."); } } } } } } return xhtml; } /// <exclude /> public string BuildProfilerReport() { _pagePerfMeasuring.Dispose(); Measurement measurement = Profiler.EndProfiling(); var url = new UrlBuilder(HttpContext.Current.Request.Url.ToString()) { ["c1mode"] = null }; return ProfilerReport.BuildReport(measurement, url); } private void InitializeFromHttpContextInternal() { HttpContext httpContext = HttpContext.Current; var request = httpContext.Request; var response = httpContext.Response; ProfilingEnabled = request.Url.OriginalString.Contains("c1mode=perf"); if (ProfilingEnabled) { if (!UserValidationFacade.IsLoggedIn()) { string loginUrl = GetLoginRedirectUrl(request.RawUrl); response.Write(@"You must be logged into <a href=""" + loginUrl + @""">C1 console</a> to have the performance view enabled"); response.End(); // throws ThreadAbortException return; } Profiler.BeginProfiling(); _pagePerfMeasuring = Profiler.Measure("C1 Page"); } PreviewMode = PagePreviewContext.TryGetPreviewKey(request, out _previewKey); if (PreviewMode) { Page = PagePreviewContext.GetPage(_previewKey); C1PageRoute.PageUrlData = new PageUrlData(Page); PageRenderer.RenderingReason = PagePreviewContext.GetRenderingReason(_previewKey); } else { PageUrlData pageUrl = C1PageRoute.PageUrlData ?? PageUrls.UrlProvider.ParseInternalUrl(request.Url.OriginalString); Page = pageUrl.GetPage(); _cachedUrl = request.Url.PathAndQuery; PageRenderer.RenderingReason = new UrlSpace(httpContext).ForceRelativeUrls ? RenderingReason.C1ConsoleBrowserPageView : RenderingReason.PageView; } ValidateViewUnpublishedRequest(httpContext); if (Page == null) { throw new HttpException(404, "Page not found - either this page has not been published yet or it has been deleted."); } if (Page.DataSourceId.PublicationScope != PublicationScope.Published) { response.Cache.SetCacheability(HttpCacheability.NoCache); CachingDisabled = true; } PageRenderer.CurrentPage = Page; var culture = Page.DataSourceId.LocaleScope; _dataScope = new DataScope(Page.DataSourceId.PublicationScope, culture); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; var pagePlaceholderContents = GetPagePlaceholderContents(); PageContentToRender = new PageContentToRender(Page, pagePlaceholderContents, PreviewMode); AttachRendererToAspNetPage(httpContext); } private void AttachRendererToAspNetPage(HttpContext context) { Verify.IsNotNull(context.Handler, "HttpHandler isn't defined"); var aspnetPage = context.Handler as System.Web.UI.Page; if (aspnetPage == null) { return; } var pageRenderer = PageTemplateFacade.BuildPageRenderer(Page.TemplateId); pageRenderer.AttachToPage(aspnetPage, PageContentToRender); } private void ValidateViewUnpublishedRequest(HttpContext httpContext) { bool isPreviewingUrl = httpContext.Request.Url.OriginalString.Contains(DefaultPageUrlProvider.UrlMarker_RelativeUrl); bool isUnpublishedPage = Page != null && Page.DataSourceId.PublicationScope != PublicationScope.Published; if ((isUnpublishedPage || isPreviewingUrl) && !UserValidationFacade.IsLoggedIn()) { string redirectUrl = GetLoginRedirectUrl(httpContext.Request.Url.OriginalString); httpContext.Response.Redirect(redirectUrl, true); } } /// <summary> /// Redirects to 404 page if PathInfo wasn't used. Adds 404 status code if the current page is specified as 404 page in hostname binding. /// Note that all C1 functions on page have to be executed before calling this method. /// </summary> /// <returns><c>True</c> if the request was transferred to a 404 page and rendering should be stopped.</returns> public bool PreRenderRedirectCheck() { var httpContext = HttpContext.Current; if (!C1PageRoute.GetPathInfo().IsNullOrEmpty() && !C1PageRoute.PathInfoUsed) { // Redirecting to PageNotFoundUrl or setting 404 response code if PathInfo url part hasn't been used if (HostnameBindingsFacade.ServeCustomPageNotFoundPage(httpContext)) { return true; } throw new HttpException(404, $"Page not found"); } // Setting 404 response code if it is a request to a custom "Page not found" page if (HostnameBindingsFacade.IsPageNotFoundRequest()) { httpContext.Response.StatusCode = 404; } return false; } private static string GetLoginRedirectUrl(string url) { return UrlUtils.PublicRootPath + "/Composite/Login.aspx?ReturnUrl=" + HttpUtility.UrlEncode(url, Encoding.UTF8); } /// <exclude /> public void Dispose() { PageRenderingHistory.MarkPageAsRendered(this.Page); _dataScope?.Dispose(); if (PreviewMode) { PagePreviewContext.Remove(_previewKey); } } } } ================================================ FILE: Composite/Core/WebClient/Renderings/RenderingElementNames.cs ================================================ using System.Xml.Linq; using Composite.Core.Xml; namespace Composite.Core.WebClient.Renderings { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class RenderingElementNames { /// <exclude /> public static XName Html { get; } = Namespaces.Xhtml + "html"; /// <exclude /> public static XName PlaceHolder { get; } = Namespaces.Rendering10 + "placeholder"; /// <exclude /> public static XName PlaceHolderIdAttribute { get; } = "id"; /// <exclude /> public static XName PlaceHolderTitleAttribute { get; } = "title"; /// <exclude /> public static XName PlaceHolderDefaultAttribute { get; } = "default"; /// <exclude /> public static XName PageTitle { get; } = Namespaces.Rendering10 + "page.title"; /// <exclude /> public static XName PageAbstract { get; } = Namespaces.Rendering10 + "page.description"; /// <exclude /> public static XName PageMetaTagDescription { get; } = Namespaces.Rendering10 + "page.metatag.description"; } } ================================================ FILE: Composite/Core/WebClient/Renderings/RenderingResponseHandlerFacade.cs ================================================ using Composite.Data; namespace Composite.Core.WebClient.Renderings { /// <summary> /// Pass information about a request through all <see cref="Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandler.IDataRenderingResponseHandler"/> /// plugins registered on the C1 CMS site. Use this if you are handling raw page / media http requests yourself. /// /// </summary> public static class RenderingResponseHandlerFacade { private static IRenderingResponseHandlerFacade _implementation = new RenderingResponseHandlerFacadeImpl(); internal static IRenderingResponseHandlerFacade Implementation { get { return _implementation; } set { _implementation = value; } } /// <summary> /// Pass information about a request through all <see cref="Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandler.IDataRenderingResponseHandler"/> /// plugins registered on the C1 CMS site. The resulting <see cref="RenderingResponseHandlerResult"/> define how you should treat the request. /// </summary> /// <param name="requestedItemEntityToken">The data being rendered. This can be <see cref="Composite.Data.Types.IPage"/> and <see cref="Composite.Data.Types.IMediaFile"/>.</param> /// <returns>A <see cref="RenderingResponseHandlerResult"/> object detailing what should happen to the user request. Returning null means no special handling should be done (request should continue).</returns> public static RenderingResponseHandlerResult GetDataResponseHandling(DataEntityToken requestedItemEntityToken) { return _implementation.GetDataResponseHandling(requestedItemEntityToken); } } } ================================================ FILE: Composite/Core/WebClient/Renderings/RenderingResponseHandlerFacadeImpl.cs ================================================ using Composite.Data; using Composite.Core.WebClient.Renderings.Foundation; using Composite.Core.WebClient.Renderings.Foundation.PluginFacades; using Composite.Core.WebClient.Renderings.Plugins.RenderingResponseHandler; namespace Composite.Core.WebClient.Renderings { internal sealed class RenderingResponseHandlerFacadeImpl : IRenderingResponseHandlerFacade { public RenderingResponseHandlerResult GetDataResponseHandling(DataEntityToken requestedItemEntityToken) { foreach (string name in RenderingResponseHandlerRegistry.RenderingResponseHandlerNames) { if (!RenderingResponseHandlerPluginFacade.IsDataRenderingResponseHandler(name)) continue; var result = RenderingResponseHandlerPluginFacade.GetDataResponseHandling(name, requestedItemEntityToken); if (result != null && result.IsNotEmpty) { return result; } } foreach (var responseHandler in ServiceLocator.GetServices<IDataRenderingResponseHandler>()) { var result = responseHandler.GetDataResponseHandling(requestedItemEntityToken); if (result != null && result.IsNotEmpty) { return result; } } return null; } } } ================================================ FILE: Composite/Core/WebClient/Renderings/RenderingResponseHandlerResult.cs ================================================ using System; namespace Composite.Core.WebClient.Renderings { /// <summary> /// Describe how a request should be handled in terms of allowing the request, ending it, redirecting it and caching it. /// </summary> public sealed class RenderingResponseHandlerResult { /// <summary> /// When true full page caching will explicitly be denied. Page caching can greatly increase website performance, /// but is not desireable on pages that require validation or contain personalized content. Default is false. /// </summary> public bool PreventPublicCaching { get; set; } /// <summary> /// To block the request and have the user redirected to another location specify the destination URL here. /// Default is null. /// </summary> public Uri RedirectRequesterTo { get; set; } /// <summary> /// When true, the request will not continue. Default is false /// </summary> public bool EndRequest { get; set; } internal bool IsNotEmpty => PreventPublicCaching || EndRequest || RedirectRequesterTo != null; } } ================================================ FILE: Composite/Core/WebClient/Renderings/RequestInterceptorHttpModule.cs ================================================ using System; using System.Globalization; using System.Web; using Composite.Core.Extensions; using Composite.Core.Routing; using Composite.Core.Routing.Pages; using Composite.Core.Threading; using Composite.Core.Configuration; using Composite.Data.Types; namespace Composite.Core.WebClient.Renderings { internal class RequestInterceptorHttpModule : IHttpModule { public void Init(HttpApplication context) { context.BeginRequest += context_BeginRequest; context.PreRequestHandlerExecute += context_PreRequestHandlerExecute; } void context_BeginRequest(object sender, EventArgs e) { if (!SystemSetupFacade.IsSystemFirstTimeInitialized) return; ThreadDataManager.InitializeThroughHttpContext(); var httpContext = (sender as HttpApplication).Context; if (CheckForHostnameAliasRedirect(httpContext)) { return; } IHostnameBinding hostnameBinding = HostnameBindingsFacade.GetBindingForCurrentRequest(); if (hostnameBinding != null && hostnameBinding.EnforceHttps && !httpContext.Request.IsSecureConnection) { RedirectToHttps(httpContext); return; } if (HandleMediaRequest(httpContext)) { return; } SetCultureByHostname(hostnameBinding); PrettifyPublicMarkup(httpContext); HandleRootRequestInClassicMode(httpContext); } private void RedirectToHttps(HttpContext context) { var url = context.Request.Url.ToString(); const string expectedPrefix = "http:"; Verify.That(url.StartsWith(expectedPrefix, StringComparison.OrdinalIgnoreCase), "Unexpected protocol, url: '{0}'", url); var redirectUrl = "https:" + url.Substring(expectedPrefix.Length); context.Response.Redirect(redirectUrl, false); } static void SetCultureByHostname(IHostnameBinding hostnameBinding) { if ((hostnameBinding?.Culture).IsNullOrEmpty()) { return; } var cultureInfo = new CultureInfo(hostnameBinding.Culture); var thread = System.Threading.Thread.CurrentThread; thread.CurrentCulture = cultureInfo; thread.CurrentUICulture = cultureInfo; } static void PrettifyPublicMarkup(HttpContext httpContext) { httpContext.Response.AppendHeader("X-Powered-By", GlobalSettingsFacade.ApplicationName); } static bool HandleMediaRequest(HttpContext httpContext) { string rawUrl = httpContext.Request.RawUrl; UrlKind urlKind; var mediaUrlData = MediaUrls.ParseUrl(rawUrl, out urlKind); // Redirecting to public media url if it isn't pointing to our handler if (urlKind == UrlKind.Internal && mediaUrlData.MediaStore != MediaUrls.DefaultMediaStore) { string publicUrl = MediaUrls.BuildUrl(mediaUrlData, UrlKind.Public); if (!string.IsNullOrEmpty(publicUrl) && !publicUrl.StartsWith(MediaUrls.MediaUrl_PublicPrefix)) { httpContext.Response.Redirect(publicUrl, false); httpContext.Response.ExpiresAbsolute = DateTime.Now.AddDays(1); httpContext.ApplicationInstance.CompleteRequest(); return true; } } if(mediaUrlData != null && (urlKind == UrlKind.Public || urlKind == UrlKind.Internal)) { string rendererUrl = MediaUrls.BuildUrl(mediaUrlData, UrlKind.Renderer); httpContext.RewritePath(rendererUrl); return true; } return false; } void context_PreRequestHandlerExecute(object sender, EventArgs e) { if (!SystemSetupFacade.IsSystemFirstTimeInitialized) return; // Left for backward compatibility with Contrib master pages support, to be removed // when support for master pages is implemented in C1 // RenderingContext.PreRenderRedirectCheck() does the same logic var httpContext = (sender as HttpApplication).Context; var page = httpContext.Handler as System.Web.UI.Page; if (page == null) { return; } if (!string.IsNullOrEmpty(C1PageRoute.GetPathInfo())) { page.PreRender += (a, b) => CheckThatPathInfoHasBeenUsed(httpContext, page); } // Setting 404 response code if it is a request to a custom "Page not found" page if (HostnameBindingsFacade.IsPageNotFoundRequest()) { page.PreRender += (a, b) => { httpContext.Response.TrySkipIisCustomErrors = true; httpContext.Response.StatusCode = 404; }; } } private static void HandleRootRequestInClassicMode(HttpContext httpContext) { if (HttpRuntime.UsingIntegratedPipeline) { return; } // Resolving root path "/" for classic mode string rawUrl = httpContext.Request.RawUrl; string rootPath = UrlUtils.PublicRootPath + (UrlUtils.PublicRootPath.EndsWith("/") ? "" : "/"); string defaultAspxPath = rootPath + "default.aspx"; if (rawUrl.StartsWith(defaultAspxPath, StringComparison.InvariantCultureIgnoreCase)) { string query = rawUrl.Substring(defaultAspxPath.Length); string shorterQuery = rootPath + query; // Checking that there's a related page) if (PageUrls.ParseUrl(shorterQuery) != null) { httpContext.RewritePath(shorterQuery); } } } private static void CheckThatPathInfoHasBeenUsed(HttpContext httpContext, System.Web.UI.Page page) { if (C1PageRoute.PathInfoUsed) { return; } // Redirecting to PageNotFoundUrl or setting 404 response code if PathInfo url part hasn't been used if (!HostnameBindingsFacade.ServeCustomPageNotFoundPage(httpContext)) { page.Response.StatusCode = 404; } page.Response.End(); } public void Dispose() { } static bool CheckForHostnameAliasRedirect(HttpContext httpContext) { if (UrlUtils.IsAdminConsoleRequest(httpContext) || UrlUtils.IsRendererRequest(httpContext) || new UrlSpace(httpContext).ForceRelativeUrls) { return false; } var hostnameBinding = HostnameBindingsFacade.GetAliasBinding(httpContext); if (hostnameBinding == null) { return false; } string hostname = httpContext.Request.Url.Host.ToLowerInvariant(); var request = httpContext.Request; string newUrl = request.Url.AbsoluteUri.Replace("://" + hostname, "://" + hostnameBinding.Hostname); if (hostnameBinding.UsePermanentRedirect) { httpContext.Response.RedirectPermanent(newUrl, false); } else { httpContext.Response.Redirect(newUrl, false); } httpContext.ApplicationInstance.CompleteRequest(); return true; } } } ================================================ FILE: Composite/Core/WebClient/Renderings/Template/PageTemplateFeatureFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using Composite.Core.Xml; using Composite.Core.IO; using Composite.Core.Configuration; using System.IO; using Composite.Data.Caching; namespace Composite.Core.WebClient.Renderings.Template { /// <summary> /// Provides access to Page Template Features /// </summary> public static class PageTemplateFeatureFacade { private static readonly Cache<string, XhtmlDocument> _featureCache = new Cache<string, XhtmlDocument>("Page Template Features"); private static List<string> _featureNamesCache; private static readonly object _lock = new object(); private static C1FileSystemWatcher _featureDirectoryFileSystemWatcher; /// <summary> /// Gets a Page Template Feature based on name. /// </summary> /// <param name="featureName">Name of the Page Template Feature to return.</param> /// <returns></returns> public static XhtmlDocument GetPageTemplateFeature(string featureName) { EnsureWatcher(); string featureKey = featureName.ToLowerInvariant(); XhtmlDocument cachedFeatureDocument = _featureCache.Get(featureKey); if (cachedFeatureDocument == null) { lock (_lock) { cachedFeatureDocument = _featureCache.Get(featureKey); if (cachedFeatureDocument == null) { cachedFeatureDocument = LoadPageTemplateFeature(featureName); _featureCache.Add(featureKey, cachedFeatureDocument); } } } return new XhtmlDocument(cachedFeatureDocument); } /// <summary> /// Gets the feature names. /// </summary> public static IEnumerable<string> FeatureNames { get { EnsureWatcher(); List<string> featureNames = _featureNamesCache; if (featureNames == null) { lock (_lock) { featureNames = _featureNamesCache; if (featureNames == null) { string featureDirectoryPath = PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory); C1DirectoryInfo featureDirectory = new C1DirectoryInfo(featureDirectoryPath); var files = featureDirectory.GetFiles("*.xml").Concat(featureDirectory.GetFiles("*.html")); featureNames = new List<string>(); foreach (var file in files) { featureNames.Add(Path.GetFileNameWithoutExtension(file.Name)); } featureNames = featureNames.Distinct().ToList(); _featureNamesCache = featureNames; } } } return featureNames; } } /// <summary> /// Gets the path of a named feature /// </summary> /// <param name="featureName">Name of the Page Template Feature to get path for.</param> /// <returns></returns> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static string GetPageTemplateFeaturePath(string featureName) { string extensionlessPath = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory), featureName); if (C1File.Exists(extensionlessPath + ".html")) { return extensionlessPath + ".html"; } else if (C1File.Exists(extensionlessPath + ".xml")) { return extensionlessPath + ".xml"; } else { return null; } } /// <summary> /// Gets the path of a named feature /// </summary> /// <param name="featureName">Name of the Page Template Feature to get path for.</param> /// <param name="extension">The extension.</param> /// <returns></returns> /// <exclude/> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static string GetNewPageTemplateFeaturePath(string featureName, string extension) { if (!extension.StartsWith(".")) { extension = "." + extension; } if (extension != ".xml" && extension != ".html") { throw new ArgumentException("Expecting '.xml' or '.html'", "extension"); } return Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory), featureName + extension); } /// <summary> /// Loads a Page Template Feature based on name. /// </summary> /// <param name="featureName">Name of the Page Template Feature to load.</param> /// <returns></returns> private static XhtmlDocument LoadPageTemplateFeature(string featureName) { string featurePath = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory), featureName + ".xml"); if (!C1File.Exists(featurePath)) { featurePath = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory), featureName + ".html"); } if (!C1File.Exists(featurePath)) { throw new InvalidOperationException("Unknown feature '" + featureName + "'"); } var doc = XDocumentUtils.Load(featurePath); return new XhtmlDocument(doc); } private static void EnsureWatcher() { if (_featureDirectoryFileSystemWatcher==null) { lock (_lock) { if (_featureDirectoryFileSystemWatcher == null) { string featureDirectoryPath = PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory); _featureDirectoryFileSystemWatcher = new C1FileSystemWatcher(featureDirectoryPath,"*"); _featureDirectoryFileSystemWatcher.Changed += FeatureDirectory_Changed; _featureDirectoryFileSystemWatcher.Created += FeatureDirectory_Changed; _featureDirectoryFileSystemWatcher.Deleted += FeatureDirectory_Changed; _featureDirectoryFileSystemWatcher.Renamed += FeatureDirectory_Changed; _featureDirectoryFileSystemWatcher.EnableRaisingEvents = true; } } } } private static void FeatureDirectory_Changed(object sender, FileSystemEventArgs e) { lock (_lock) { _featureNamesCache = null; _featureCache.Clear(); } } } } ================================================ FILE: Composite/Core/WebClient/Renderings/Template/TemplateInfo.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web.Hosting; using System.Xml.Linq; using Composite.Core.Extensions; using Composite.Data; using Composite.Data.Caching; using Composite.Data.Plugins.DataProvider.Streams; using Composite.Data.Streams; using Composite.Data.Types; using Composite.Core.Types; namespace Composite.Core.WebClient.Renderings.Template { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class TemplateInfo { private static readonly Cache<Guid, IXmlPageTemplate> PageTemplateCache = new Cache<Guid, IXmlPageTemplate>("Page templates", 100); /// <exclude /> static TemplateInfo() { DataEventSystemFacade.SubscribeToDataAfterUpdate<IXmlPageTemplate>(PageTemplate_Changed, true); DataEventSystemFacade.SubscribeToDataDeleted<IXmlPageTemplate>(PageTemplate_Changed, true); DataEventSystemFacade.SubscribeToStoreChanged<IXmlPageTemplate>(PageTemplate_StoreChanged, true); } private static void PageTemplate_StoreChanged(object sender, StoreEventArgs storeEventArgs) { if (!storeEventArgs.DataEventsFired) { PageTemplateCache.Clear(); } } private static void PageTemplate_Changed(object sender, DataEventArgs dataEventArgs) { var pageTemplate = dataEventArgs.Data as IXmlPageTemplate; Verify.ArgumentCondition(pageTemplate != null, "dataEventArgs", "Data is null or has an incorrect data type."); PageTemplateCache.Remove(pageTemplate.Id); } /// <exclude /> public static TemplatePlaceholdersInfo GetRenderingPlaceHolders(Guid templateId) { XDocument document = GetTemplateDocument(templateId); IEnumerable<XElement> placeHoldersWithId = document.Descendants(RenderingElementNames.PlaceHolder).Where( e=>e.Attribute(RenderingElementNames.PlaceHolderIdAttribute)!=null); TemplatePlaceholdersInfo info = new TemplatePlaceholdersInfo(); info.Placeholders = ( from placeHolder in placeHoldersWithId orderby GetPlaceHolderTitle(placeHolder) select new KeyValuePair( placeHolder.Attribute(RenderingElementNames.PlaceHolderIdAttribute).Value, GetPlaceHolderTitle(placeHolder))).ToList(); XAttribute defaultTrueAttribute = placeHoldersWithId.Attributes(RenderingElementNames.PlaceHolderDefaultAttribute).Where(a => a.Value == "true").FirstOrDefault(); if (defaultTrueAttribute != null) { info.DefaultPlaceholderId = defaultTrueAttribute.Parent.Attribute(RenderingElementNames.PlaceHolderIdAttribute).Value; } else { if (info.Placeholders.Any()) { info.DefaultPlaceholderId = info.Placeholders.First().Key; } } return info; } /// <exclude /> public static XDocument GetTemplateDocument(Guid templateId) { IXmlPageTemplate template = GetTemplate(templateId); var templateWrapper = PageTemplateFileWrapper.Get(template); string templateMarkup = templateWrapper.Content; XDocument document; try { document = XDocument.Parse(templateMarkup); } catch (Exception ex) { throw new InvalidOperationException("Failed to parse template markup for file '{0}'" .FormatWith(templateWrapper.RelativeFilePath), ex); } return document; } private static IXmlPageTemplate GetTemplate(Guid templateId) { IXmlPageTemplate cachedValue = PageTemplateCache.Get(templateId); if(cachedValue != null) { return cachedValue; } var templates = from template in DataFacade.GetData<Composite.Data.Types.IXmlPageTemplate>() where template.Id == templateId select template; IXmlPageTemplate result = templates.FirstOrDefault(); Verify.That(result != null, "Failed to get a page template by id. Id = '{0}'", templateId); PageTemplateCache.Add(templateId, result); return result; } private static string GetPlaceHolderTitle(XElement placeHolder) { XAttribute titleAttribute = placeHolder.Attribute(RenderingElementNames.PlaceHolderTitleAttribute); if (titleAttribute != null) { return titleAttribute.Value; } else { return placeHolder.Attribute(RenderingElementNames.PlaceHolderIdAttribute).Value; } } /// <summary> /// In order to avoid memory leaks we have a separate object that represents loaded file content. /// </summary> private class PageTemplateFileWrapper { private readonly string _content; private readonly string _pageTemplateFilePath; private readonly string _fileFullPath; private static Cache<string, PageTemplateFileWrapper> _cache = new Cache<string, PageTemplateFileWrapper>("Page template files", 100); internal PageTemplateFileWrapper(IXmlPageTemplate pageTemplate) { _pageTemplateFilePath = pageTemplate.PageTemplateFilePath; IFile file = IFileServices.GetFile<IPageTemplateFile>(_pageTemplateFilePath); _content = file.ReadAllText(); var systemFile = file as FileSystemFileBase; Verify.IsNotNull(systemFile, "File should be of type '{0}'", typeof(FileSystemFileBase).Name); _fileFullPath = systemFile.SystemPath; file.SubscribeOnChanged(OnFileChanged); } public string Content { get { return _content; } } public string RelativeFilePath { get { return _fileFullPath.Substring(HostingEnvironment.ApplicationPhysicalPath.Length - 1); } } private void OnFileChanged(string filePath, FileChangeType changeType) { _cache.Remove(_pageTemplateFilePath); } public static PageTemplateFileWrapper Get(IXmlPageTemplate pageTemplate) { PageTemplateFileWrapper result = _cache.Get(pageTemplate.PageTemplateFilePath); if(result != null) { return result; } result = new PageTemplateFileWrapper(pageTemplate); _cache.Add(result._pageTemplateFilePath, result); return result; } } } } ================================================ FILE: Composite/Core/WebClient/Renderings/Template/TemplatePlaceholdersInfo.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Core.Types; namespace Composite.Core.WebClient.Renderings.Template { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class TemplatePlaceholdersInfo { /// <exclude /> public IEnumerable<KeyValuePair> Placeholders { get; set; } /// <exclude /> public string DefaultPlaceholderId { get; set; } } } ================================================ FILE: Composite/Core/WebClient/ScriptHandler.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml.Linq; using Composite.Core.IO; using Composite.Core.Xml; namespace Composite.Core.WebClient { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum CompositeScriptMode { /// <exclude /> OPERATE = 0, /// <exclude /> DEVELOP = 1, /// <exclude /> COMPILE = 2, }; /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ScriptHandler { private static string _compileScriptsFilename = "CompileScripts.xml"; /// <exclude /> public static string MergeScripts(string type, IEnumerable<string> scriptFilenames, string folderPath, string targetPath) { string sourcesFilename = targetPath + "\\" + type + "-uncompressed.js"; FileUtils.RemoveReadOnly(sourcesFilename); C1File.WriteAllText(sourcesFilename, string.Empty /* GetTimestampString() */); foreach (string scriptFilename in scriptFilenames) { string scriptPath = scriptFilename.Replace("${root}", folderPath).Replace("/", "\\"); string lines = C1File.ReadAllText(scriptPath); C1File.AppendAllText(sourcesFilename, lines); C1File.AppendAllText(sourcesFilename, Environment.NewLine + Environment.NewLine); } return sourcesFilename; } /// <exclude /> public static string BuildTopLevelClassNames(IEnumerable<string> scriptFilenames, string folderPath, string targetPath) { var classes = new StringBuilder(); classes.AppendLine("var topLevelClassNames = [ // Don't edit! This file is automatically generated."); bool first = true; foreach (string scriptFilename in scriptFilenames) { string scriptPath = scriptFilename.Replace("${root}", folderPath); if (scriptPath.IndexOf("/scripts/source/page/") == -1) { if (first) { first = false; } else { classes.AppendLine(","); } int _start = scriptPath.LastIndexOf("/") + 1; int _length = scriptPath.LastIndexOf(".js") - _start; string className = scriptPath.Substring(_start, _length); classes.Append("\t\"" + className + "\""); } } classes.AppendLine("];"); string classesFilename = targetPath + "\\" + "toplevelclassnames.js"; FileUtils.RemoveReadOnly(classesFilename); C1File.WriteAllText(classesFilename, string.Empty /* GetTimestampString() */); C1File.AppendAllText(classesFilename, classes.ToString()); return classesFilename; } /// <exclude /> public static IEnumerable<string> GetTopScripts(CompositeScriptMode scriptMode, string folderPath) { IEnumerable<string> result = GetStrings("top", scriptMode.ToString().ToLower(), folderPath); return result; } /// <exclude /> public static IEnumerable<string> GetSubScripts(CompositeScriptMode scriptMode, string folderPath) { IEnumerable<string> result = GetStrings("sub", scriptMode.ToString().ToLower(), folderPath); return result; } private static IEnumerable<string> GetStrings(string type, string mode, string folderPath) { string filename = Path.Combine(folderPath, _compileScriptsFilename); XDocument doc = XDocumentUtils.Load(filename); if (mode == "compile") mode = "develop"; XName name = "name"; XElement topElement = doc.Root.Elements().Single(f => f.Attribute(name).Value == type); XElement modeElement = topElement.Elements().Single(f => f.Attribute(name).Value == mode); return from e in modeElement.Elements() select e.Attribute("filename").Value; } } } ================================================ FILE: Composite/Core/WebClient/ScriptLoader.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Hosting; using System.Xml.Linq; using Composite.Core.IO; using Composite.Core.Xml; namespace Composite.Core.WebClient { /// <summary> /// A common Scriptloader class for Razor and Aspx Pages. /// </summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ScriptLoader { static bool _hasServerToServerConnection; private readonly HttpContext _ctx; private readonly string _type; private readonly bool _updateManagerDisabled; private readonly CompositeScriptMode _mode; private readonly IEnumerable<string> _defaultscripts; /// <exclude /> public ScriptLoader(string type, string directive = null, bool updateManagerDisabled = false) { _ctx = HttpContext.Current; _type = type; _updateManagerDisabled = updateManagerDisabled; if (directive == "compile") { _mode = CompositeScriptMode.COMPILE; } else if (CookieHandler.Get("mode") == "develop") { _mode = CompositeScriptMode.DEVELOP; } else { _mode = CompositeScriptMode.OPERATE; } string folderPath = Path.Combine(_ctx.Request.PhysicalApplicationPath, "Composite"); switch (type) { case "top": _defaultscripts = ScriptHandler.GetTopScripts(_mode, folderPath); break; case "sub": _defaultscripts = ScriptHandler.GetSubScripts(_mode, folderPath); break; } } /// <summary> /// Create and render the markup for Razor Pages /// </summary> /// <param name="type"></param> /// <param name="directive"></param> /// <returns></returns> public static string Render(string type , string directive = null) { return new ScriptLoader(type, directive).Render(); } /// <exclude /> public string Render() { var builder = new StringBuilder(); switch (_mode) { case CompositeScriptMode.OPERATE: case CompositeScriptMode.DEVELOP: RenderMarkup(builder); break; case CompositeScriptMode.COMPILE: CompileScript(builder); break; } return builder.ToString(); } #region Private Methods private void CompileScript(StringBuilder writer) { try { string folderPath = Path.Combine(_ctx.Request.PhysicalApplicationPath, "Composite"); string targetPath = folderPath + "\\scripts\\compressed"; ScriptHandler.MergeScripts(_type, _defaultscripts, folderPath, targetPath); if (_type == "top") { ScriptHandler.BuildTopLevelClassNames(_defaultscripts, folderPath, targetPath); } } catch (Exception e) { Log.LogError(typeof(ScriptLoader).FullName, new InvalidOperationException("Failed to compile scripts", e)); writer.Append("<p> Failed to compile scripts. Exception text:"); writer.Append(HttpUtility.HtmlEncode(e.ToString())); writer.Append("</p>"); } } /** * Render markup */ private void RenderMarkup(StringBuilder builder) { //string thisVirtualFolder = Composite.Core.IO.Path.GetDirectoryName(this.AppRelativeVirtualPath); //string parentVirtualFolder = thisVirtualFolder.Substring(0, thisVirtualFolder.LastIndexOf(Composite.Core.IO.Path.DirectorySeparatorChar)); //string fullPathWindowsStyle = parentVirtualFolder.Replace( "~", HttpContext.Current.Request.ApplicationPath ); string root = UrlUtils.AdminRootPath; string scriptMarkup = GetScriptMarkup(); foreach (string ss in _defaultscripts) { string relativeLink = ss.Replace("${root}", root); string filePath = PathUtil.Resolve(ss.Replace("${root}", "~/Composite")); if (C1File.Exists(filePath)) { DateTime lastModified = C1File.GetLastWriteTimeUtc(filePath); relativeLink += "?timestamp=" + lastModified.GetHashCode(); } builder.AppendLine( scriptMarkup.Replace("${scriptsource}", relativeLink) ); } if (_type == "top") { // We emit a version number - which we want the client to remember _ctx.Response.Cache.SetExpires(DateTime.Now.AddYears(-10)); _ctx.Response.Cache.SetCacheability(HttpCacheability.Private); var url = _ctx.Request.Url; bool isLocalHost = url.Host.ToLowerInvariant() == "localhost"; _hasServerToServerConnection = HasServerToServerConnection(); builder.AppendLine(@"<script type=""text/javascript"">"); Func<bool, string> toJson = b => b.ToString().ToLowerInvariant(); builder.AppendFormat(@"Application.hasExternalConnection = {0};", toJson(_hasServerToServerConnection)); builder.AppendFormat(@"Application.isDeveloperMode = {0};", toJson(_mode == CompositeScriptMode.DEVELOP)); builder.AppendFormat(@"Application.isLocalHost = {0};", toJson(isLocalHost)); builder.AppendFormat(@"Application.isOnPublicNet = {0};", toJson(UrlIsOnPublicNet(url))); builder.AppendLine(@"</script>"); } else { if (!_updateManagerDisabled) { builder.AppendLine(@"<script type=""text/javascript"">"); builder.AppendLine(@"UpdateManager.xhtml = null;"); builder.AppendLine(@"</script>"); } } } /// <summary> /// When there are lots of scripts around, Mozilla cannot grok the closing /// script tag. It throws a "Error: mismatched tag. Expected: </head>". /// Explorer, on the other hand, needs the closing script tag. /// </summary> private string GetScriptMarkup() { string userAgent = _ctx.Request.UserAgent; if (userAgent != null && userAgent.IndexOf("Gecko", StringComparison.InvariantCulture) > -1) { return @"<script type=""application/javascript"" src=""${scriptsource}""/>"; } return @"<script type=""text/javascript"" src=""${scriptsource}""></script>"; } /** * Attempt remote connection. We test the connection by * looking for the exact document title "Start" in the response. */ [SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationManagerClass:DoNotUseConfigurationManagerClass")] private static bool HasServerToServerConnection() { bool result = false; try { string uri = ConfigurationManager.AppSettings["Composite.StartPage.Url"]; if (string.IsNullOrEmpty(uri)) { return false; } XDocument loaded = null; Task task = Task.Factory.StartNew(() => loaded = TryLoad(uri)); task.Wait(2500); if (task.IsCompleted && loaded != null) { XElement titleElement = loaded.Descendants(Namespaces.Xhtml + "title").FirstOrDefault(); result = (titleElement != null && titleElement.Value == "Start"); } } catch (Exception) { } return result; } private bool UrlIsOnPublicNet(Uri currentUri) { if (currentUri.HostNameType != UriHostNameType.Dns) return false; string hostname = currentUri.Host.ToLowerInvariant(); if (hostname.IndexOf('.') == -1) return false; IPHostEntry dnsResult; try { dnsResult = System.Net.Dns.GetHostEntry(hostname); } catch (SocketException) { return false; } if (dnsResult.AddressList.Length == 0) { return false; } var address = dnsResult.AddressList.First().MapToIPv6(); return !address.IsIPv6SiteLocal && !address.IsIPv6LinkLocal; } /// <exclude /> public static bool UnbundledScriptsAvailable() { var filePath = HostingEnvironment.MapPath(UrlUtils.AdminRootPath + "/scripts/source/top/interfaces/IAcceptable.js"); return C1File.Exists(filePath); } [DebuggerStepThrough] private static XDocument TryLoad(string uri) { try { return XDocumentUtils.Load(uri); } catch { /* silent */ return null; } } #endregion } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/ActionTypeEnum.cs ================================================ namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum ActionType { /// <exclude /> OpenView = 0, /// <exclude /> OpenExternalView = 17, /// <exclude /> OpenGenericView = 1, /// <exclude /> OpenViewDefinition = 2, /// <exclude /> CloseView = 3, /// <exclude /> DownloadFile = 4, /// <exclude /> MessageBox = 5, /// <exclude /> RefreshTree = 6, /// <exclude /> LogEntry = 7, /// <exclude /> Reboot = 8, /// <exclude /> CollapseAndRefresh = 9, /// <exclude /> CloseAllViews = 10, /// <exclude /> LockSystem = 11, /// <exclude /> BroadcastMessage = 12, /// <exclude /> SaveStatus = 13, /// <exclude /> BindEntityTokenToView = 14, /// <exclude /> ExpandTreeNode = 15, /// <exclude /> SelectElement = 16, /// <exclude /> OpenSlideView = 18, } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/BindEntityTokenToViewParams.cs ================================================ namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class BindEntityTokenToViewParams { /// <exclude /> public string ViewId { get; set; } /// <exclude /> public string EntityToken { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/BroadcastMessageParams.cs ================================================ namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class BroadcastMessageParams { /// <exclude /> public string Name { get; set; } /// <exclude /> public string Value { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/CloseAllViewsParams.cs ================================================ namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class CloseAllViewsParams { /// <exclude /> public string Reason { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/CloseViewParams.cs ================================================  namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class CloseViewParams { /// <exclude /> public string ViewId { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/ConsoleAction.cs ================================================ using System; namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ConsoleAction { /// <exclude /> public ConsoleAction() { this.Id = Guid.NewGuid().ToString(); } /// <exclude /> public string Id { get; set; } /// <exclude /> public int SequenceNumber { get; set; } /// <exclude /> public ActionType ActionType { get; set; } /// <exclude /> public OpenViewParams OpenViewParams { get; set; } /// <exclude /> public OpenGenericViewParams OpenGenericViewParams { get; set; } /// <exclude /> public OpenExternalViewParams OpenExternalViewParams { get; set; } /// <exclude /> public OpenSlideViewParams OpenSlideViewParams { get; set; } /// <exclude /> public DownloadFileParams DownloadFileParams { get; set; } /// <exclude /> public OpenViewDefinitionParams OpenViewDefinitionParams { get; set; } /// <exclude /> public CloseViewParams CloseViewParams { get; set; } /// <exclude /> public RefreshTreeParams RefreshTreeParams { get; set; } /// <exclude /> public MessageBoxParams MessageBoxParams { get; set; } /// <exclude /> public LogEntryParams LogEntryParams { get; set; } /// <exclude /> public BroadcastMessageParams BroadcastMessageParams { get; set; } /// <exclude /> public CloseAllViewsParams CloseAllViewsParams { get; set; } /// <exclude /> public SaveStatusParams SaveStatusParams { get; set; } /// <exclude /> public BindEntityTokenToViewParams BindEntityTokenToViewParams { get; set; } /// <exclude /> public SelectElementParams SelectElementParams { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/ConsoleMessageServiceFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Events; using Composite.C1Console.Events.Foundation; using Composite.C1Console.Security; using Composite.Core.Types; using Composite.C1Console.Users; using Composite.Core.ResourceSystem; using Composite.Core.Logging; using Composite.Core.Configuration; using Composite.Core.ResourceSystem.Icons; namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ConsoleMessageServiceFacade { /// <exclude /> public static int CurrentChangeNumber { get { return ConsoleMessageQueueFacade.CurrentChangeNumber; } } /// <exclude /> public static GetMessagesResult GetNewMessages(string consoleId, int lastKnownChangeNumber) { ConsoleFacade.RegisterConsole(UserSettings.Username, consoleId); List<ConsoleAction> newMessages = new List<ConsoleAction>(); GetMessagesResult result = new GetMessagesResult(); result.CurrentSequenceNumber = ConsoleMessageQueueFacade.CurrentChangeNumber; List<ConsoleMessageQueueElement> messageQueueElements = ConsoleMessageQueueFacade.GetQueueElements(lastKnownChangeNumber, consoleId).ToList(); if (messageQueueElements.Any() && messageQueueElements.Max(f => f.QueueItemNumber) > result.CurrentSequenceNumber) { result.CurrentSequenceNumber = messageQueueElements.Max(f => f.QueueItemNumber); } DocumentSuspectMessageRequests(consoleId, lastKnownChangeNumber, result, messageQueueElements); // Open views... foreach (ConsoleMessageQueueElement queueElement in messageQueueElements.Where(f => f.QueueItem is OpenViewMessageQueueItem)) { OpenViewMessageQueueItem openViewItem = (OpenViewMessageQueueItem)queueElement.QueueItem; List<KeyValuePair> arguments = new List<KeyValuePair>(); if (openViewItem.UrlPostArguments != null) { foreach (var entry in openViewItem.UrlPostArguments) { arguments.Add(new KeyValuePair(entry.Key, entry.Value)); } } OpenViewParams openViewParams = new OpenViewParams { Url = openViewItem.Url, Argument = arguments, EntityToken = openViewItem.EntityToken, FlowHandle = openViewItem.FlowHandle, ViewId = openViewItem.ViewId, ViewType = openViewItem.ViewType.AsConsoleType(), Label = openViewItem.Label, ToolTip = openViewItem.ToolTip ?? openViewItem.Label }; openViewParams.Image = GetImage(openViewItem.IconResourceHandle); newMessages.Add(new ConsoleAction { SequenceNumber = queueElement.QueueItemNumber, ActionType = ActionType.OpenView, OpenViewParams = openViewParams }); } // Open view definitions... foreach (ConsoleMessageQueueElement queueElement in messageQueueElements.Where(f => f.QueueItem is OpenHandledViewMessageQueueItem)) { OpenHandledViewMessageQueueItem openViewDefItem = (OpenHandledViewMessageQueueItem)queueElement.QueueItem; List<KeyValuePair> arguments = new List<KeyValuePair>(); foreach (var entry in openViewDefItem.Arguments) { arguments.Add(new KeyValuePair(entry.Key, entry.Value)); } OpenViewDefinitionParams openViewDefParams = new OpenViewDefinitionParams { ViewId = openViewDefItem.Handle + Guid.NewGuid().ToString(), EntityToken = openViewDefItem.EntityToken, Handle = openViewDefItem.Handle, Argument = arguments }; newMessages.Add(new ConsoleAction { SequenceNumber = queueElement.QueueItemNumber, ActionType = ActionType.OpenViewDefinition, OpenViewDefinitionParams = openViewDefParams }); } // Open generic views... foreach (ConsoleMessageQueueElement queueElement in messageQueueElements.Where(f => f.QueueItem is OpenGenericViewQueueItem)) { OpenGenericViewQueueItem openGenericView = (OpenGenericViewQueueItem)queueElement.QueueItem; List<KeyValuePair> arguments = new List<KeyValuePair>(); foreach (var entry in openGenericView.UrlPostArguments) { arguments.Add(new KeyValuePair(entry.Key, entry.Value)); } OpenGenericViewParams openGenericViewParams = new OpenGenericViewParams { ViewId = openGenericView.ViewId, EntityToken = openGenericView.EntityToken, Label = openGenericView.Label, ToolTip = openGenericView.ToolTip ?? openGenericView.Label, Url = openGenericView.Url, UrlPostArguments = arguments }; openGenericViewParams.Image = GetImage(openGenericView.IconResourceHandle); newMessages.Add(new ConsoleAction { SequenceNumber = queueElement.QueueItemNumber, ActionType = ActionType.OpenGenericView, OpenGenericViewParams = openGenericViewParams }); } // Open external views... foreach (ConsoleMessageQueueElement queueElement in messageQueueElements.Where(f => f.QueueItem is OpenExternalViewQueueItem)) { var openExternalView = (OpenExternalViewQueueItem)queueElement.QueueItem; var arguments = new List<KeyValuePair>(); foreach (var entry in openExternalView.UrlPostArguments) { arguments.Add(new KeyValuePair(entry.Key, entry.Value)); } var openExternalViewParams = new OpenExternalViewParams { ViewId = openExternalView.ViewId, EntityToken = openExternalView.EntityToken, Label = openExternalView.Label, ToolTip = openExternalView.ToolTip ?? openExternalView.Label, ViewType = openExternalView.ViewType, Url = openExternalView.Url, UrlPostArguments = arguments }; openExternalViewParams.Image = GetImage(openExternalView.IconResourceHandle); newMessages.Add(new ConsoleAction { SequenceNumber = queueElement.QueueItemNumber, ActionType = ActionType.OpenExternalView, OpenExternalViewParams = openExternalViewParams }); } // Open slide views... foreach (ConsoleMessageQueueElement queueElement in messageQueueElements.Where(f => f.QueueItem is OpenSlideViewQueueItem)) { var openSlideView = (OpenSlideViewQueueItem)queueElement.QueueItem; var openSlideViewParams = new OpenSlideViewParams { ViewId = openSlideView.ViewId, EntityToken = openSlideView.EntityToken, Url = openSlideView.Url }; newMessages.Add(new ConsoleAction { SequenceNumber = queueElement.QueueItemNumber, ActionType = ActionType.OpenSlideView, OpenSlideViewParams = openSlideViewParams }); } // Download files... foreach (ConsoleMessageQueueElement queueElement in messageQueueElements.Where(f => f.QueueItem is DownloadFileMessageQueueItem)) { DownloadFileMessageQueueItem downloadFileItem = (DownloadFileMessageQueueItem)queueElement.QueueItem; DownloadFileParams downloadFileParams = new DownloadFileParams { Url = downloadFileItem.Url, }; newMessages.Add(new ConsoleAction { SequenceNumber = queueElement.QueueItemNumber, ActionType = ActionType.DownloadFile, DownloadFileParams = downloadFileParams }); } // Close views... foreach (ConsoleMessageQueueElement queueElement in messageQueueElements.Where(f => f.QueueItem is CloseViewMessageQueueItem)) { CloseViewMessageQueueItem closeViewItem = (CloseViewMessageQueueItem)queueElement.QueueItem; newMessages.Add(new ConsoleAction { SequenceNumber = queueElement.QueueItemNumber, ActionType = ActionType.CloseView, CloseViewParams = new CloseViewParams { ViewId = closeViewItem.ViewId } }); } // Refresh tree... Ignoring requests for the same entity tokens var entityTokensToRefresh = new HashSet<string>(); var refreshMessages = new List<ConsoleAction>(); foreach (var queueElement in messageQueueElements.Where(f => f.QueueItem is RefreshTreeMessageQueueItem) .OrderByDescending(f => f.QueueItemNumber)) { var refreshTreeItem = (RefreshTreeMessageQueueItem)queueElement.QueueItem; string serializedEntityToken = EntityTokenSerializer.Serialize(refreshTreeItem.EntityToken, true); if (entityTokensToRefresh.Contains(serializedEntityToken)) { continue; } entityTokensToRefresh.Add(serializedEntityToken); refreshMessages.Add(new ConsoleAction { SequenceNumber = queueElement.QueueItemNumber, ActionType = ActionType.RefreshTree, RefreshTreeParams = new RefreshTreeParams { EntityToken = serializedEntityToken, } }); } refreshMessages.Reverse(); newMessages.AddRange(refreshMessages); // Send message boxes... foreach (ConsoleMessageQueueElement queueElement in messageQueueElements.Where(f => f.QueueItem is MessageBoxMessageQueueItem)) { MessageBoxMessageQueueItem messageBoxItem = (MessageBoxMessageQueueItem)queueElement.QueueItem; DialogType clientDialogType = DialogType.Message; switch (messageBoxItem.DialogType) { case Composite.C1Console.Events.DialogType.Message: clientDialogType = DialogType.Message; break; case Composite.C1Console.Events.DialogType.Question: clientDialogType = DialogType.Question; break; case Composite.C1Console.Events.DialogType.Warning: clientDialogType = DialogType.Warning; break; case Composite.C1Console.Events.DialogType.Error: clientDialogType = DialogType.Error; break; default: clientDialogType = DialogType.Message; break; } newMessages.Add(new ConsoleAction { SequenceNumber = queueElement.QueueItemNumber, ActionType = ActionType.MessageBox, MessageBoxParams = new MessageBoxParams { DialogType = clientDialogType, Title = messageBoxItem.Title, Message = messageBoxItem.Message } }); } // Send log entries... foreach (ConsoleMessageQueueElement queueElement in messageQueueElements.Where(f => f.QueueItem is LogEntryMessageQueueItem)) { var logEntryItem = (LogEntryMessageQueueItem)queueElement.QueueItem; newMessages.Add(new ConsoleAction { SequenceNumber = queueElement.QueueItemNumber, ActionType = ActionType.LogEntry, LogEntryParams = new LogEntryParams { SenderId = logEntryItem.Sender.Name, Level = logEntryItem.Level.AsConsoleType(), Message = logEntryItem.Message } }); } // Restart console application (like culture change)... foreach (ConsoleMessageQueueElement queueElement in messageQueueElements.Where(f => f.QueueItem is RebootConsoleMessageQueueItem)) { var rebootConsoleItem = (RebootConsoleMessageQueueItem)queueElement.QueueItem; newMessages.Add(new ConsoleAction { SequenceNumber = queueElement.QueueItemNumber, ActionType = ActionType.Reboot }); } // Collaps the tree and refresh foreach (ConsoleMessageQueueElement queueElement in messageQueueElements.Where(f => f.QueueItem is CollapseAndRefreshConsoleMessageQueueItem)) { var collapseAndRefreshConsoleMessageQueueItem = (CollapseAndRefreshConsoleMessageQueueItem)queueElement.QueueItem; newMessages.Add(new ConsoleAction { SequenceNumber = queueElement.QueueItemNumber, ActionType = ActionType.CollapseAndRefresh }); } // Close all open views foreach (ConsoleMessageQueueElement queueElement in messageQueueElements.Where(f => f.QueueItem is CloseAllViewsMessageQueueItem)) { var closeAllViewsMessageQueueItem = (CloseAllViewsMessageQueueItem)queueElement.QueueItem; newMessages.Add(new ConsoleAction { SequenceNumber = queueElement.QueueItemNumber, ActionType = ActionType.CloseAllViews, CloseAllViewsParams = new CloseAllViewsParams { Reason = closeAllViewsMessageQueueItem.Reason } }); } // Lock the console application foreach (ConsoleMessageQueueElement queueElement in messageQueueElements.Where(f => f.QueueItem is LockSystemConsoleMessageQueueItem)) { var lockSystemConsoleMessageQueueItem = (LockSystemConsoleMessageQueueItem)queueElement.QueueItem; newMessages.Add(new ConsoleAction { SequenceNumber = queueElement.QueueItemNumber, ActionType = ActionType.LockSystem }); } // Lock the console application foreach (ConsoleMessageQueueElement queueElement in messageQueueElements.Where(f => f.QueueItem is BroadcastMessageQueueItem)) { var broadcastMessageQueueItem = (BroadcastMessageQueueItem)queueElement.QueueItem; newMessages.Add(new ConsoleAction { SequenceNumber = queueElement.QueueItemNumber, ActionType = ActionType.BroadcastMessage, BroadcastMessageParams = new BroadcastMessageParams { Name = broadcastMessageQueueItem.Name, Value = broadcastMessageQueueItem.Value } }); } // SaveStatus foreach (ConsoleMessageQueueElement queueElement in messageQueueElements.Where(f => f.QueueItem is SaveStatusConsoleMessageQueueItem)) { var saveStatusConsoleMessageQueueItem = (SaveStatusConsoleMessageQueueItem)queueElement.QueueItem; newMessages.Add(new ConsoleAction { SequenceNumber = queueElement.QueueItemNumber, ActionType = ActionType.SaveStatus, SaveStatusParams = new SaveStatusParams { ViewId = saveStatusConsoleMessageQueueItem.ViewId, Succeeded = saveStatusConsoleMessageQueueItem.Succeeded } }); } // BindEntityToken foreach (ConsoleMessageQueueElement queueElement in messageQueueElements.Where(f => f.QueueItem is BindEntityTokenToViewQueueItem)) { var bindEntityTokenToViewQueueItem = (BindEntityTokenToViewQueueItem)queueElement.QueueItem; newMessages.Add(new ConsoleAction { SequenceNumber = queueElement.QueueItemNumber, ActionType = ActionType.BindEntityTokenToView, BindEntityTokenToViewParams = new BindEntityTokenToViewParams { ViewId = bindEntityTokenToViewQueueItem.ViewId, EntityToken = bindEntityTokenToViewQueueItem.EntityToken } }); } // BindEntityToken foreach (ConsoleMessageQueueElement queueElement in messageQueueElements.Where(f => f.QueueItem is SelectElementQueueItem)) { var selectElementQueueItem = (SelectElementQueueItem)queueElement.QueueItem; newMessages.Add(new ConsoleAction { SequenceNumber = queueElement.QueueItemNumber, ActionType = ActionType.SelectElement, SelectElementParams = new SelectElementParams { EntityToken = selectElementQueueItem.EntityToken, PerspectiveElementKey = selectElementQueueItem.PerspectiveElementKey } }); } result.ConsoleActions = newMessages.OrderBy(f => f.SequenceNumber).ToList(); return result; } /// <summary> /// If the client feeding from the queue goes haywire, we start to log details about it for debug purposes. /// </summary> private static void DocumentSuspectMessageRequests(string consoleId, int lastKnownChangeNumber, GetMessagesResult result, List<ConsoleMessageQueueElement> messageQueueElements) { int maxSecondsExpected = 60; if (lastKnownChangeNumber > result.CurrentSequenceNumber) { LoggingService.LogInformation("ConsoleMessageServiceFacade", string.Format("Console '{0}' has a last known change numer of {1}, but server current number is {2}.", consoleId, lastKnownChangeNumber, result.CurrentSequenceNumber)); } if (messageQueueElements.Any() && DateTime.Now.Subtract(messageQueueElements.Min(f => f.EnqueueTime)).TotalSeconds > maxSecondsExpected) { ConsoleMessageQueueFacade.DoDebugSerializationToFileSystem(); LoggingService.LogWarning("ConsoleMessageServiceFacade", string.Format("Console '{0}' are requesting messages that are more than {1} seconds old. Console has last known change number {2}, server is now at {3}. Debug XML dump saved at '{4}'.", consoleId, maxSecondsExpected, lastKnownChangeNumber, result.CurrentSequenceNumber, GlobalSettingsFacade.TempDirectory)); } } private static string GetImage(ResourceHandle resourceHandle) { if (resourceHandle == null) return null; return string.Format("${{icon:{0}:{1}}}", resourceHandle.ResourceNamespace, resourceHandle.ResourceName); } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/DialogTypeEnum.cs ================================================  namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum DialogType { /// <exclude /> Message, /// <exclude /> Question, /// <exclude /> Warning, /// <exclude /> Error } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/DownloadFileParams.cs ================================================  namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class DownloadFileParams { /// <exclude /> public string Url { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/GetMessagesResult.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class GetMessagesResult { /// <exclude /> public int CurrentSequenceNumber { get; set; } /// <exclude /> public List<ConsoleAction> ConsoleActions { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/LogEntryParams.cs ================================================  namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class LogEntryParams { /// <exclude /> public string SenderId { get; set; } /// <exclude /> public LogLevel Level { get; set; } /// <exclude /> public string Message { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/LogLevelEnum.cs ================================================ using System; namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum LogLevel { /// <exclude /> Fine, /// <exclude /> Info, /// <exclude /> Debug, /// <exclude /> Warn, /// <exclude /> Error, /// <exclude /> Fatal } internal static class InternalLogLevelConvertExtensions { internal static LogLevel AsConsoleType(this Composite.Core.Logging.LogLevel internalLogLevel) { switch (internalLogLevel) { case Composite.Core.Logging.LogLevel.Info: return LogLevel.Info; case Composite.Core.Logging.LogLevel.Debug: return LogLevel.Debug; case Composite.Core.Logging.LogLevel.Fine: return LogLevel.Fine; case Composite.Core.Logging.LogLevel.Warning: return LogLevel.Warn; case Composite.Core.Logging.LogLevel.Error: return LogLevel.Error; case Composite.Core.Logging.LogLevel.Fatal: return LogLevel.Fatal; default: throw new ArgumentException("Unknown Composite.Core.Logging.LogLevel " + internalLogLevel.ToString()); } } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/MessageBoxParams.cs ================================================  namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class MessageBoxParams { /// <exclude /> public string Title { get; set; } /// <exclude /> public string Message { get; set; } /// <exclude /> public DialogType DialogType { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/OpenExternalViewParams.cs ================================================ using System.Collections.Generic; using Composite.Core.Types; namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class OpenExternalViewParams { /// <exclude /> public string ViewId { get; set; } /// <exclude /> public string EntityToken { get; set; } /// <exclude /> public string Label { get; set; } /// <exclude /> public string ToolTip { get; set; } /// <exclude /> public string Image { get; set; } /// <exclude /> public string Url { get; set; } /// <exclude /> public string ViewType { get; set; } /// <exclude /> public List<KeyValuePair> UrlPostArguments { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/OpenGenericViewParams.cs ================================================ using System.Collections.Generic; using Composite.Core.Types; namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class OpenGenericViewParams { /// <exclude /> public string ViewId { get; set; } /// <exclude /> public string EntityToken { get; set; } /// <exclude /> public string Label { get; set; } /// <exclude /> public string ToolTip { get; set; } /// <exclude /> public string Image { get; set; } /// <exclude /> public string Url { get; set; } /// <exclude /> public List<KeyValuePair> UrlPostArguments { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/OpenSlideViewParams.cs ================================================ using System.Collections.Generic; using Composite.Core.Types; namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class OpenSlideViewParams { /// <exclude /> public string ViewId { get; set; } /// <exclude /> public string EntityToken { get; set; } /// <exclude /> public string Url { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/OpenViewDefinitionParams.cs ================================================ using System.Collections.Generic; using Composite.Core.Types; namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class OpenViewDefinitionParams { /// <exclude /> public string ViewId { get; set; } /// <exclude /> public string EntityToken { get; set; } /// <exclude /> public string Handle { get; set; } /// <exclude /> public List<KeyValuePair> Argument { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/OpenViewParams.cs ================================================ using System.Collections.Generic; using Composite.Core.Types; namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class OpenViewParams { /// <exclude /> public string ViewId { get; set; } /// <exclude /> public string EntityToken { get; set; } /// <exclude /> public string FlowHandle { get; set; } /// <exclude /> public string Handle { get; set; } /// <exclude /> public string Url { get; set; } /// <exclude /> public List<KeyValuePair> Argument { get; set; } /// <exclude /> public ViewType ViewType { get; set; } /// <summary> /// Label for view /// </summary> public string Label { get; set; } /// <summary> /// Icon URL /// </summary> public string Image { get; set; } /// <summary> /// Tooltip for view tab /// </summary> public string ToolTip { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/RefreshTreeParams.cs ================================================  namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class RefreshTreeParams { /// <exclude /> public string EntityToken { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/SaveStatusParams.cs ================================================ namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class SaveStatusParams { /// <exclude /> public string ViewId { get; set; } /// <exclude /> public bool Succeeded { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/SelectElementParams.cs ================================================  namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class SelectElementParams { /// <exclude /> public string EntityToken { get; set; } /// <exclude /> public string PerspectiveElementKey { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/ConsoleMessageService/ViewTypeEnum.cs ================================================ using System; namespace Composite.Core.WebClient.Services.ConsoleMessageService { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum ViewType { /// <exclude /> External = 6, /// <exclude /> Main = 0, /// <exclude /> ModalDialog = 1, /// <exclude /> RightTop = 2, /// <exclude /> RightBottom = 3, /// <exclude /> BottomLeft = 4, /// <exclude /> BottomRight = 5 } internal static class InternalViewTypeConvertExtensions { internal static ViewType AsConsoleType( this Composite.C1Console.Events.ViewType internalViewType ) { switch (internalViewType) { case Composite.C1Console.Events.ViewType.External: return ViewType.External; case Composite.C1Console.Events.ViewType.Main: return ViewType.Main; case Composite.C1Console.Events.ViewType.ModalDialog: return ViewType.ModalDialog; case Composite.C1Console.Events.ViewType.RightTop: return ViewType.RightTop; case Composite.C1Console.Events.ViewType.RightBottom: return ViewType.RightBottom; case Composite.C1Console.Events.ViewType.BottomLeft: return ViewType.BottomLeft; case Composite.C1Console.Events.ViewType.BottomRight: return ViewType.BottomRight; default: throw new ArgumentException( "Unknown Composite.C1Console.Events.ViewType " + internalViewType.ToString() ); } } } } ================================================ FILE: Composite/Core/WebClient/Services/LocalizationServiceObjects/ClientLocale.cs ================================================ namespace Composite.Core.WebClient.Services.LocalizationServiceObjects { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ClientLocale { /// <exclude /> public string Name { get; set; } /// <exclude /> public string IsoName { get; set; } /// <exclude /> public string UrlMappingName { get; set; } /// <exclude /> public string SerializedActionToken { get; set; } /// <exclude /> public bool IsCurrent { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/LocalizationServiceObjects/ClientLocales.cs ================================================ namespace Composite.Core.WebClient.Services.LocalizationServiceObjects { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ClientLocales { /// <exclude /> public string ActiveLocaleName { get; set; } /// <exclude /> public string ForeignLocaleName { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/LocalizationServiceObjects/PageLocale.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace Composite.Core.WebClient.Services.LocalizationServiceObjects { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DebuggerDisplay("Culture = {Name}, IsCurrent = {IsCurrent}, Url = {Url}")] public sealed class PageLocale { /// <exclude /> public string Name { get; set; } /// <exclude /> public string IsoName { get; set; } /// <exclude /> public string UrlMappingName { get; set; } /// <exclude /> public string Url { get; set; } /// <exclude /> public bool IsCurrent { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/SecurityServiceObjets/EntityPermissionDetails.cs ================================================ using System.Collections.Generic; namespace Composite.Core.WebClient.Services.SecurityServiceObjets { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class EntityPermissionDetails { /// <exclude /> public List<UserPermissions> InheritedUserPermissions { get; set; } /// <exclude /> public List<UserPermissions> EntityUserPermissions { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/SecurityServiceObjets/UserPermissions.cs ================================================ using System.Collections.Generic; namespace Composite.Core.WebClient.Services.SecurityServiceObjets { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class UserPermissions { /// <exclude /> public string UserName { get; set; } /// <exclude /> public List<string> PermissionTypes { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/TreeServiceObjects/ClientAction.cs ================================================ using Composite.Core.ResourceSystem; using System; using Composite.C1Console.Elements; namespace Composite.Core.WebClient.Services.TreeServiceObjects { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ClientAction { /// <exclude /> public string ActionToken { get; set; } /// <exclude /> public string Label { get; set; } /// <exclude /> public string ToolTip { get; set; } /// <exclude /> public bool Disabled { get; set; } /// <exclude /> public ResourceHandle Icon { get; set; } /// <exclude /> public ClientActionCategory ActionCategory { get; set; } /// <exclude /> public string CheckboxStatus { get; set; } /// <exclude /> public string TagValue { get; set; } /// <exclude /> public int ActivePositions { get; set; } /// <exclude /> public DialogStrings BulkExecutionDialog { get; set; } /// <exclude /> public string ActionKey { get { string secondaryValuesMashup = string.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}", this.Label, this.ToolTip, this.Disabled, this.Icon.ResourceName, this.Icon.ResourceNamespace, this.ActionCategory.FolderName, this.ActionCategory.GroupId, this.ActionCategory.IsInFolder, this.ActionCategory.IsInToolbar, this.ActionCategory.Name, this.CheckboxStatus); return (this.ActionToken + this.Label).GetHashCode() + "::" + secondaryValuesMashup.GetHashCode(); } set { // now being returned from client via SOAP! // throw new InvalidOperationException("This can not be set"); } } } } ================================================ FILE: Composite/Core/WebClient/Services/TreeServiceObjects/ClientActionCategory.cs ================================================ namespace Composite.Core.WebClient.Services.TreeServiceObjects { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ClientActionCategory { /// <exclude /> public string GroupId { get; set; } /// <exclude /> public string GroupName { get; set; } /// <exclude /> public string Name { get; set; } /// <exclude /> public bool IsInToolbar { get; set; } /// <exclude /> public bool IsInFolder { get; set; } /// <exclude /> public string FolderName { get; set; } /// <exclude /> public string ActionBundle { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/TreeServiceObjects/ClientBrowserViewSettings.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Composite.Core.WebClient.Services.TreeServiceObjects { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ClientBrowserViewSettings { /// <summary> /// Url to load in browser /// </summary> public string Url { get; set; } /// <summary> /// True if tooling (view, SEO tools etc) should be active for URL /// </summary> public bool ToolingOn { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/TreeServiceObjects/ClientElement.cs ================================================ using System.Collections.Generic; using System.Diagnostics; using Composite.Core.ResourceSystem; using Composite.Core.Types; namespace Composite.Core.WebClient.Services.TreeServiceObjects { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DebuggerDisplay("ClientElement: '{Label}'")] public sealed class ClientElement { /// <exclude /> public string ElementKey { get; set; } // CORE /// <exclude /> public string ProviderName { get; set; } /// <exclude /> public string EntityToken { get; set; } /// <exclude /> public string Piggybag { get; set; } /// <exclude /> public string PiggybagHash { get; set; } /// <exclude /> public string Label { get; set; } // CORE /// <exclude /> public string ToolTip { get; set; } // CORE /// <exclude /> public bool HasChildren { get; set; } // CORE /// <exclude /> public bool IsDisabled { get; set; } // CORE /// <exclude /> public ResourceHandle Icon { get; set; } // CORE /// <exclude /> public ResourceHandle OpenedIcon { get; set; } // CORE /// <exclude /> public List<ClientAction> Actions { get; set; } /// <exclude /> public List<string> ActionKeys { get; set; } /// <exclude /> public List<KeyValuePair> PropertyBag { get; set; } // CORE /// <exclude /> public List<string> DropTypeAccept { get; set; } /// <exclude /> public bool DetailedDropSupported { get; set; } /// <exclude /> public string DragType { get; set; } /// <exclude /> public string TagValue { get; set; } // CORE /// <exclude /> public bool ContainsTaggedActions { get; set; } // CORE /// <summary> /// When client is searching through elements to find the element with the given entity token, /// the client should disregard elements with TreeLockEnabled == <value>true</value> and continue searching. /// </summary> public bool TreeLockEnabled { get; set; } /// <summary> /// Having a common ElementBundle across elements will make the client bundle them up as a single node, and allow the user to select a specific element via a drop down, showing individual BundleElementName values /// </summary> public string ElementBundle { get; set; } /// <summary> /// When bundling elements this field is used to identify this specific element for selection /// </summary> public string BundleElementName { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/TreeServiceObjects/ClientElementChangeDescriptor.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Text; // Describes a set of changed elements by listing their ElementHandles // The latest sequence change number is returned as well. namespace Composite.Core.WebClient.Services.TreeServiceObjects { internal class ClientElementChangeDescriptor { public ClientElementChangeDescriptor() { this.ElementHandles = new List<string>(); } /// <summary> /// The client should use the "current sequence number" the next time it queries for changes /// </summary> public int CurrentSequenceNumber { get; set; } public List<string> ElementHandles { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/TreeServiceObjects/ClientLabeledProperty.cs ================================================  using Composite.C1Console.Elements; namespace Composite.Core.WebClient.Services.TreeServiceObjects { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ClientLabeledProperty { /// <exclude /> public ClientLabeledProperty() { } /// <exclude /> public ClientLabeledProperty(LabeledProperty labeledProperty) { this.Name = labeledProperty.Name; this.Label = labeledProperty.Label; this.Value = labeledProperty.Value; } /// <summary> /// The name of the property. The name is constant across cultures and is intended as an id other systems can use. /// </summary> public string Name { get; set; } /// <summary> /// The label the user should see. /// </summary> public string Label { get; set; } /// <summary> /// The value of the property /// </summary> public string Value { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/TreeServiceObjects/ClientProviderNameEntityTokenClientElementsTriple.cs ================================================ using System.Collections.Generic; namespace Composite.Core.WebClient.Services.TreeServiceObjects { internal sealed class ClientProviderNameEntityTokenClientElementsTriple { public string ProviderName { get; set; } public string EntityToken { get; set; } public List<ClientElement> ClientElements { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/TreeServiceObjects/ClientProviderNameEntityTokenPair.cs ================================================ namespace Composite.Core.WebClient.Services.TreeServiceObjects { internal sealed class ClientProviderNameEntityTokenPair { public string ProviderName { get; set; } public string EntityToken { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/TreeServiceObjects/ExtensionMethods/ElementActionExtensionMethods.cs ================================================ using System.Linq; using System.Collections.Generic; using Composite.C1Console.Elements; using Composite.C1Console.Security; using System; namespace Composite.Core.WebClient.Services.TreeServiceObjects.ExtensionMethods { internal static class ElementActionExtensionMethods { public static List<ClientAction> ToClientActionList(this IEnumerable<ElementAction> actions) { var clientActions = from action in actions let visualData = action.VisualData let actionLocation = visualData.ActionLocation orderby actionLocation.ActionGroup.Priority, actionLocation.ActionGroup.Name, actionLocation.ActionType select new ClientAction { ActionToken = ActionTokenSerializer.Serialize(action.ActionHandle.ActionToken, true), Label = visualData.Label, ToolTip = visualData.ToolTip, Disabled = visualData.Disabled, Icon = visualData.Icon, BulkExecutionDialog = visualData.BulkExecutionDialog, CheckboxStatus = GetCheckboxStatusString(visualData.ActionCheckedStatus), ActivePositions = (int)visualData.ActivePositions, TagValue = action.TagValue, ActionCategory = new ClientActionCategory { GroupId = CalculateActionCategoryGroupId(actionLocation.ActionGroup), GroupName = actionLocation.ActionGroup.Name, Name = actionLocation.ActionType.ToString(), IsInFolder = actionLocation.IsInFolder, IsInToolbar = actionLocation.IsInToolbar, FolderName = actionLocation.FolderName, ActionBundle = actionLocation.ActionBundle } }; return clientActions.ToList(); } private static string GetCheckboxStatusString(ActionCheckedStatus actionCheckedStatus) { switch (actionCheckedStatus) { case ActionCheckedStatus.Uncheckable: return null; case ActionCheckedStatus.Unchecked: return "Unchecked"; case ActionCheckedStatus.Checked: return "Checked"; default: throw new InvalidOperationException("Unexpected ActionCheckedStatus value"); } } private static string CalculateActionCategoryGroupId(ActionGroup actionGroup) { return "Key" + (actionGroup.Priority + actionGroup.Name).GetHashCode(); } } } ================================================ FILE: Composite/Core/WebClient/Services/TreeServiceObjects/ExtensionMethods/ElementExtensionMethods.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.Core.Types; namespace Composite.Core.WebClient.Services.TreeServiceObjects.ExtensionMethods { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ElementExtensionMethods { /// <exclude /> public static ClientElement GetClientElement(this Element element) { if (element.VisualData.Icon == null || element.Actions.Any(a => a.VisualData?.Icon == null)) { throw new InvalidOperationException($"Unable to create ClientElement from Element with entity token '{element.ElementHandle.EntityToken.Serialize()}'. The element or one of its actions is missing an icon definition."); } string entityToken = EntityTokenSerializer.Serialize(element.ElementHandle.EntityToken, true); string piggyBag = element.ElementHandle.SerializedPiggyback; var clientElement = new ClientElement { ElementKey = $"{element.ElementHandle.ProviderName}{entityToken}{piggyBag}", ProviderName = element.ElementHandle.ProviderName, EntityToken = entityToken, Piggybag = piggyBag, PiggybagHash = HashSigner.GetSignedHash(piggyBag).Serialize(), Label = element.VisualData.Label, HasChildren = element.VisualData.HasChildren, IsDisabled = element.VisualData.IsDisabled, Icon = element.VisualData.Icon, OpenedIcon = element.VisualData.OpenedIcon, ToolTip = element.VisualData.ToolTip, Actions = element.Actions.ToClientActionList(), PropertyBag = element.PropertyBag.ToClientPropertyBag(), TagValue = element.TagValue, ContainsTaggedActions = element.Actions.Any(f => f.TagValue != null), TreeLockEnabled = element.TreeLockBehavior == TreeLockBehavior.Normal, ElementBundle = element.VisualData.ElementBundle, BundleElementName = element.VisualData.BundleElementName }; clientElement.ActionKeys = (from clientAction in clientElement.Actions select clientAction.ActionKey).ToList(); if (element.MovabilityInfo.DragType != null) clientElement.DragType = element.MovabilityInfo.GetHashedTypeIdentifier(); List<string> apoptables = element.MovabilityInfo.GetDropHashTypeIdentifiers(); if (apoptables != null && apoptables.Count > 0) { clientElement.DropTypeAccept = apoptables; } clientElement.DetailedDropSupported = element.MovabilityInfo.SupportsIndexedPosition; return clientElement; } /// <exclude /> public static List<ClientElement> ToClientElementList(this List<Element> elements) { var list = new List<ClientElement>(elements.Count); list.AddRange(elements.Select(element => element.GetClientElement())); return list; } /// <exclude /> public static List<KeyValuePair> ToClientPropertyBag(this Dictionary<string, string> propertyBag) { if (propertyBag == null || propertyBag.Count == 0) return null; return propertyBag.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value)).ToList(); } } } ================================================ FILE: Composite/Core/WebClient/Services/TreeServiceObjects/RefreshChildrenInfo.cs ================================================ using System.Collections.Generic; namespace Composite.Core.WebClient.Services.TreeServiceObjects { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class RefreshChildrenInfo { /// <exclude /> public string ElementKey { get; set; } /// <exclude /> public List<ClientElement> ClientElements { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/TreeServiceObjects/RefreshChildrenParams.cs ================================================ namespace Composite.Core.WebClient.Services.TreeServiceObjects { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class RefreshChildrenParams { /// <exclude /> public string ProviderName { get; set; } /// <exclude /> public string EntityToken { get; set; } /// <exclude /> public string Piggybag { get; set; } /// <exclude /> public string SearchToken { get; set; } } } ================================================ FILE: Composite/Core/WebClient/Services/WampRouter/IRpcService.cs ================================================ namespace Composite.Core.WebClient.Services.WampRouter { /// <summary> /// This class should be implemented when a callee is going to be registered on Wamp Router /// </summary> public interface IRpcService { } } ================================================ FILE: Composite/Core/WebClient/Services/WampRouter/IWampEventHandler.cs ================================================ using System; namespace Composite.Core.WebClient.Services.WampRouter { /// <summary> /// This class should be implemented when a publisher is going to be registered on Wamp Router /// </summary> /// <typeparam name="TObservable"></typeparam> /// <typeparam name="TResult"></typeparam> public interface IWampEventHandler<out TObservable,out TResult> { /// <summary> /// Topic uri /// </summary> string Topic { get; } /// <summary> /// Observable event /// </summary> IObservable<TObservable> Event { get; } /// <summary> /// Data to be published from the observable event /// </summary> /// <returns></returns> TResult GetNewData(); } } ================================================ FILE: Composite/Core/WebClient/Services/WampRouter/UserNameBasedAuthenticationFactory.cs ================================================ using WampSharp.V2.Authentication; namespace Composite.Core.WebClient.Services.WampRouter { internal class UserNameBasedAuthenticationFactory : IWampSessionAuthenticatorFactory { public IWampSessionAuthenticator GetSessionAuthenticator(WampPendingClientDetails details, IWampSessionAuthenticator transportAuthenticator) { if (!transportAuthenticator.IsAuthenticated) { throw new WampAuthenticationException("Cookie wasn't present"); } return transportAuthenticator; } } } ================================================ FILE: Composite/Core/WebClient/Services/WampRouter/UserNameBasedAuthorizer.cs ================================================ using WampSharp.V2.Authentication; using WampSharp.V2.Core.Contracts; namespace Composite.Core.WebClient.Services.WampRouter { internal class UserNameBasedAuthorizer : IWampAuthorizer { public bool CanRegister(RegisterOptions options, string procedure) { return true; } public bool CanCall(CallOptions options, string procedure) { options.DiscloseMe = true; return true; } public bool CanPublish(PublishOptions options, string topicUri) { return true; } public bool CanSubscribe(SubscribeOptions options, string topicUri) { return true; } } } ================================================ FILE: Composite/Core/WebClient/Services/WampRouter/UserNameBasedCookieAuthenticationFactory.cs ================================================ using Composite.C1Console.Security; using WampSharp.V2.Authentication; namespace Composite.Core.WebClient.Services.WampRouter { internal class UserNameBasedCookieAuthenticationFactory : ICookieAuthenticatorFactory { public IWampSessionAuthenticator CreateAuthenticator(ICookieProvider cookieProvider) { var userName = UserValidationFacade.GetUsername(); return new UserNameBasedCookieAuthenticator(userName); } } } ================================================ FILE: Composite/Core/WebClient/Services/WampRouter/UserNameBasedCookieAuthenticator.cs ================================================ using Composite.C1Console.Security; using WampSharp.V2.Authentication; using WampSharp.V2.Core.Contracts; namespace Composite.Core.WebClient.Services.WampRouter { internal class UserNameBasedCookieAuthenticator : WampSessionAuthenticator { public UserNameBasedCookieAuthenticator(string userName) { this.AuthenticationId = userName; } public override void Authenticate(string signature, AuthenticateExtraData extra) { throw new WampAuthenticationException("Cookie wasn't present"); } public override bool IsAuthenticated => true; public override string AuthenticationId { get; } public override IWampAuthorizer Authorizer => new UserNameBasedAuthorizer(); public override string AuthenticationMethod => nameof(UserValidationFacade); } } ================================================ FILE: Composite/Core/WebClient/Services/WampRouter/WampLogger.cs ================================================ using System; using System.Diagnostics; using System.Text.RegularExpressions; using Composite.Core.Logging; using WampSharp.Logging; using LogLevel = WampSharp.Logging.LogLevel; namespace Composite.Core.WebClient.Services.WampRouter { class WampLogger : ILogProvider { public Logger GetLogger(string name) { return new CompositeLoggerWrapper().Log; } public IDisposable OpenNestedContext(string message) { return null; } public IDisposable OpenMappedContext(string key, string value) { return null; } internal class CompositeLoggerWrapper { public bool Log(LogLevel logLevel, Func<string> messageFunc, Exception exception, params object[] formatParameters) { if (exception is OperationCanceledException) { return true; } if (messageFunc != null) { var eventType = GetTraceEventType(logLevel); var message = FormatMessage(messageFunc, formatParameters); LoggingService.LogEntry(nameof(WampLogger), message, LoggingService.Category.General, eventType); } if (exception != null) { Core.Log.LogError(nameof(WampLogger), exception); } return true; } private static TraceEventType GetTraceEventType(LogLevel logLevel) { switch (logLevel) { case LogLevel.Fatal: return TraceEventType.Critical; case LogLevel.Error: return TraceEventType.Error; case LogLevel.Warn: return TraceEventType.Warning; case LogLevel.Info: return TraceEventType.Information; case LogLevel.Trace: case LogLevel.Debug: return TraceEventType.Verbose; } return TraceEventType.Warning; } private string FormatMessage(Func<string> messageFunc, params object[] formatParameters) { var message = messageFunc(); var needle = new Regex(@"\{(.*?)\}"); int i = 0; while (needle.IsMatch(message)) { message = needle.Replace(message, "^" + i + "#", 1); i++; } return string.Format(message.Replace('#', '}').Replace('^', '{'), formatParameters); } } } } ================================================ FILE: Composite/Core/WebClient/Services/WampRouter/WampRouteWrapper.cs ================================================ using System.Web; using System.Web.Routing; namespace Composite.Core.WebClient.Services.WampRouter { /// <summary> /// A wrapper around a <see cref="RouteBase"/>, that prevent inner route's influence on MVC links resolution. /// </summary> internal class WampRouteWrapper : RouteBase { private readonly RouteBase _innerRoute; public WampRouteWrapper(RouteBase innerRoute) { _innerRoute = innerRoute; } public override RouteData GetRouteData(HttpContextBase context) => _innerRoute.GetRouteData(context); public override VirtualPathData GetVirtualPath(RequestContext r, RouteValueDictionary v) => null; } } ================================================ FILE: Composite/Core/WebClient/Services/WampRouter/WampRouter.cs ================================================ using System; using System.Linq; using System.Reactive.Subjects; using System.Web.Routing; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using WampSharp.AspNet.WebSockets.Server; using WampSharp.Binding; using WampSharp.Logging; using WampSharp.V2; using WampSharp.V2.Realm; namespace Composite.Core.WebClient.Services.WampRouter { internal class WampRouter { private const string DefaultRealmName = "realm"; private const string WampConsoleUrl = "api/Router"; private WampHost _host; public WampRouter() { LogProvider.SetCurrentLogProvider(new WampLogger()); try { StartWampRouter(); Log.LogVerbose(nameof(WampRouter),"WAMP router initiated successfully"); } catch (Exception e) { Log.LogCritical(nameof(WampRouter), "WAMP router could not be instantiated"); Log.LogCritical(nameof(WampRouter), e); } } public void RegisterCallee(IRpcService instance) { RegisterCallee(DefaultRealmName, instance); } public void RegisterCallee(string realmName, IRpcService instance) { var realm = _host.RealmContainer.GetRealmByName(realmName); var registrationTask = realm.Services.RegisterCallee(instance); registrationTask.Wait(); } public void RegisterPublisher<TObservable, TResult> (IWampEventHandler<TObservable, TResult> eventObservable) { RegisterPublisher(DefaultRealmName, eventObservable); } public void RegisterPublisher<TObservable, TResult> (string realmName, IWampEventHandler<TObservable,TResult> eventObservable) { IWampHostedRealm realm = _host.RealmContainer.GetRealmByName(realmName); ISubject<TResult> subject = realm.Services.GetSubject<TResult>(eventObservable.Topic); IObservable<TObservable> observableEvent = eventObservable.Event; observableEvent.Subscribe(x => { if (!realm.TopicContainer.TopicUris.Any(f => f.Equals(eventObservable.Topic))) { Log.LogVerbose(nameof(WampRouter), $"Trying to publish on topic: {eventObservable.Topic}, but there is no subscriber to this topic"); } else { subject.OnNext(eventObservable.GetNewData()); } }); } private void StartWampRouter() { _host = new WampAuthenticationHost(new UserNameBasedAuthenticationFactory()); string routeUrl = $"{UrlUtils.AdminFolderName}/{WampConsoleUrl}"; if (routeUrl.StartsWith("/")) { routeUrl = routeUrl.Substring(1); } _host.RegisterTransport( new AspNetWebSocketTransport(routeUrl, new UserNameBasedCookieAuthenticationFactory()), new JTokenJsonBinding(new JsonSerializer { ContractResolver = new CamelCasePropertyNamesContractResolver() })); IWampHostedRealm realm = _host.RealmContainer.GetRealmByName(DefaultRealmName); realm.SessionCreated += SessionCreated; realm.SessionClosed += SessionRemoved; _host.Open(); FixWampRoute(routeUrl); } private static void FixWampRoute(string routeUrl) { var routes = RouteTable.Routes; for (int i = 0; i < routes.Count; i++) { var route = routes[i] as Route; if (route?.Url == routeUrl) { routes.Remove(route); routes.Add(new WampRouteWrapper(route)); return; } } } private static void SessionCreated(object sender, WampSessionCreatedEventArgs e) { Log.LogVerbose(nameof(WampRouter),"A new WAMP client is connected"); } private static void SessionRemoved(object sender, WampSessionCloseEventArgs e) { Log.LogVerbose(nameof(WampRouter), "A connection error occured"); } } } ================================================ FILE: Composite/Core/WebClient/Services/WampRouter/WampRouterFacade.cs ================================================ namespace Composite.Core.WebClient.Services.WampRouter { /// <summary> /// Wamp Router Facade for registering clients /// </summary> public static class WampRouterFacade { /// <summary> /// Method for registering callee /// </summary> /// <param name="realmName"></param> /// <param name="instance"></param> /// <returns></returns> public static bool RegisterCallee(string realmName, IRpcService instance) { var wampRouter = ServiceLocator.GetRequiredService<WampRouter>(); if (wampRouter == null) return false; wampRouter.RegisterCallee(realmName,instance); return true; } /// <summary> /// Method for registering callee /// </summary> /// <param name="instance"></param> /// <returns></returns> public static bool RegisterCallee(IRpcService instance) { var wampRouter = ServiceLocator.GetRequiredService<WampRouter>(); if (wampRouter == null) return false; wampRouter.RegisterCallee(instance); return true; } /// <summary> /// Method for registering publisher /// </summary> /// <param name="realmName"></param> /// <param name="eventObservable"></param> /// <typeparam name="TObservable"></typeparam> /// <typeparam name="TResult"></typeparam> /// <returns></returns> public static bool RegisterPublisher<TObservable,TResult> (string realmName, IWampEventHandler<TObservable, TResult> eventObservable) { var wampRouter = ServiceLocator.GetRequiredService<WampRouter>(); if (wampRouter == null) return false; wampRouter.RegisterPublisher(realmName, eventObservable); return true; } /// <summary> /// Method for registering publisher /// </summary> /// <param name="eventObservable"></param> /// <typeparam name="TObservable"></typeparam> /// <typeparam name="TResult"></typeparam> /// <returns></returns> public static bool RegisterPublisher<TObservable,TResult> (IWampEventHandler<TObservable, TResult> eventObservable) { var wampRouter = ServiceLocator.GetRequiredService<WampRouter>(); if (wampRouter == null) return false; wampRouter.RegisterPublisher(eventObservable); return true; } } } ================================================ FILE: Composite/Core/WebClient/Services/WampRouter/WampRouterResolverRegistry.cs ================================================ using Composite.Core.Application; using Microsoft.Extensions.DependencyInjection; namespace Composite.Core.WebClient.Services.WampRouter { [ApplicationStartup] internal class WampRouterResolverRegistry { public void ConfigureServices(IServiceCollection serviceCollection) { serviceCollection.Add(ServiceDescriptor.Singleton(new WampRouter())); } } } ================================================ FILE: Composite/Core/WebClient/Services/WysiwygEditor/MarkupTransformationServices.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Linq; using System.Xml.Xsl; using Composite.Core.IO; using Composite.Core.Xml; using TidyNet; namespace Composite.Core.WebClient.Services.WysiwygEditor { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class TidyHtmlResult { /// <exclude /> public XDocument Output { get; set; } /// <exclude /> public string ErrorSummary { get; set; } } /// <summary> /// Summary description for HtmlTidyServices /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class MarkupTransformationServices { /// <exclude /> public static IEnumerable<string> Html5specificElementNames = new List<string> { "article", "aside", "audio", "canvas", "command", "datalist", "details", "embed", "figcaption", "figure", "footer", "header", "hgroup", "keygen", "mark", "meter", "nav", "output", "progress", "rp", "rt", "ruby", "section", "source", "summary", "time", "video", "wbr", "main", "link", "meta", "i" }; static readonly Regex _duplicateAttributesRegex = new Regex(@"<([^>]*?) (?<attributeName>\w*?)=(?<quote>"")([^>]*?)(\k<quote>)([^>]*?) (\k<attributeName>)=(?<quote2>"")([^>]*?)(\k<quote2>)([^>]*?)>", RegexOptions.Compiled); static readonly Regex _namespacePrefixedElement = new Regex(@"<([a-zA-Z0-9\._]*?):([a-zA-Z0-9\._]*)([^>]*?)(/?)>", RegexOptions.Multiline | RegexOptions.Compiled); static readonly Regex _elementWithNamespaceDeclaration = new Regex(@"<(.*?) xmlns:([a-zA-Z0-9\._]*)=""(.*?)""(.*?)(/?)>", RegexOptions.Compiled); static readonly Regex _elementsWithPrefixedAttributes = new Regex(@"<[^>]*? ([\w]):.*?>", RegexOptions.Compiled); static readonly Regex _customNamespaceDeclarations = new Regex(@"<(.*?) xmlns:(?<prefix>[a-zA-Z0-9\._]*?)=""(?<uri>.*?)""([^>]*?)>", RegexOptions.Compiled); /// <summary> /// Repairs an html fragment (makes it Xhtml) and executes a transformation on it. /// </summary> /// <param name="html">The html to repair</param> /// <param name="xsltPath">The path to the XSLT to use for transformation</param> /// <param name="xsltParameters"></param> /// <param name="errorSummary">out value - warnings generated while repairing the html</param> /// <returns></returns> public static XDocument RepairXhtmlAndTransform(string html, string xsltPath, Dictionary<string, string> xsltParameters, out string errorSummary) { TidyHtmlResult tidyHtmlResult = MarkupTransformationServices.TidyHtml(html); errorSummary = tidyHtmlResult.ErrorSummary; XNode tidiedXhtml = tidyHtmlResult.Output; XDocument outputDocument = new XDocument(); XslCompiledTransform xslt = XsltServices.GetCompiledXsltTransform(xsltPath); using (XmlWriter writer = outputDocument.CreateXhtmlWriter()) { using (XmlReader reader = tidiedXhtml.CreateReader()) { if (xsltParameters != null && xsltParameters.Count > 0) { XsltArgumentList xsltArgumentList = new XsltArgumentList(); foreach (var xsltParameter in xsltParameters) { xsltArgumentList.AddParam(xsltParameter.Key, "", xsltParameter.Value ); } xslt.Transform(reader, xsltArgumentList, writer); } else { xslt.Transform(reader, writer); } } } return outputDocument; } /// <summary> /// Repairs an html fragment (makes it Xhtml) and executes a transformation on it. /// </summary> /// <param name="xml">The xml to repair</param> /// <param name="xsltPath">The path to the XSLT to use for transformation</param> /// <returns></returns> public static XDocument RepairXmlAndTransform(string xml, string xsltPath) { XDocument tidiedXml = MarkupTransformationServices.TidyXml(xml); XDocument outputDocument = new XDocument(); XslCompiledTransform xslt = XsltServices.GetCompiledXsltTransform(xsltPath); using (XmlWriter writer = outputDocument.CreateWriter()) { using (XmlReader reader = tidiedXml.CreateReader()) { xslt.Transform(reader, writer); } } return outputDocument; } /// <summary> /// Cleans HTML documents or fragments into XHTML conformant markup /// </summary> /// <param name="htmlMarkup">The html to clean</param> /// <returns>A fully structured XHTML document, incl. html, head and body elements.</returns> public static TidyHtmlResult TidyHtml(string htmlMarkup) { Tidy tidy = GetXhtmlConfiguredTidy(); List<string> namespacePrefixedElementNames = LocateNamespacePrefixedElementNames(htmlMarkup); Dictionary<string, string> namespacePrefixToUri = LocateNamespacePrefixToUriDeclarations(htmlMarkup); List<string> badNamespacePrefixedElementNames = namespacePrefixedElementNames .Where(s => !namespacePrefixToUri.Any(d => s.StartsWith(d.Key))).ToList(); AllowNamespacePrefixedElementNames(tidy, namespacePrefixedElementNames); AllowHtml5ElementNames(tidy); string xhtml = ParseMarkup(htmlMarkup, tidy, out TidyMessageCollection tidyMessages); if (xhtml.IndexOf("<html>")>-1) { xhtml = xhtml.Replace("<html>", "<html xmlns=\"http://www.w3.org/1999/xhtml\">"); } if (xhtml.IndexOf("xmlns=\"http://www.w3.org/1999/xhtml\"") == -1) { xhtml = xhtml.Replace("<html", "<html xmlns=\"http://www.w3.org/1999/xhtml\""); } xhtml = RemoveDuplicateAttributes(xhtml); xhtml = RemoveXmlDeclarations(xhtml); xhtml = UndoLowerCasingOfElementNames(xhtml, namespacePrefixedElementNames); xhtml = UndoLowerCasingOfNamespacePrefixes(xhtml, namespacePrefixToUri); StringBuilder messageBuilder = new StringBuilder(); foreach (TidyMessage message in tidyMessages) { if (message.Level == MessageLevel.Warning) messageBuilder.AppendLine(message.ToString()); } List<string> badNamespacePrefixes = badNamespacePrefixedElementNames.Select(n => n.Substring(0, n.IndexOf(':'))).Union(LocateAttributeNamespacePrefixes(xhtml)).Distinct().Where(f => IsValidXmlName(f)).ToList(); XDocument outputResult; if (badNamespacePrefixedElementNames.Any()) { string badDeclared = string.Join(" ", badNamespacePrefixes.Select(p => $"xmlns:{p}='#bad'")); XDocument badDoc = XDocument.Parse($"<root {badDeclared}>{xhtml}</root>"); badDoc.Descendants().Attributes().Where(e => e.Name.Namespace == "#bad").Remove(); badDoc.Descendants().Where(e => e.Name.Namespace == "#bad").Remove(); outputResult = new XDocument(badDoc.Root.Descendants().First()); } else { outputResult = XDocument.Parse(xhtml, LoadOptions.PreserveWhitespace); } return new TidyHtmlResult { Output = outputResult, ErrorSummary = messageBuilder.ToString() }; } private static string ParseMarkup(string markup, Tidy tidy, out TidyMessageCollection tidyMessages) { string result; tidyMessages = new TidyMessageCollection(); byte[] htmlByteArray = Encoding.UTF8.GetBytes(markup); using (var inputStream = new MemoryStream(htmlByteArray)) { using (var outputStream = new MemoryStream()) { tidy.Parse(inputStream, outputStream, tidyMessages); outputStream.Position = 0; using (var sr = new C1StreamReader(outputStream)) { result = sr.ReadToEnd(); } } } if (tidyMessages.Errors > 0) { var errorMessageBuilder = new StringBuilder(); foreach (TidyMessage message in tidyMessages) { if (message.Level == MessageLevel.Error) errorMessageBuilder.AppendLine(message.ToString()); } throw new InvalidOperationException($"Failed to parse html:\n\n{errorMessageBuilder}"); } return result; } /// <summary> /// Cleans HTML documents or fragments into XHTML conformant markup /// </summary> /// <param name="xmlMarkup">The html to clean</param> /// <returns></returns> public static XDocument TidyXml(string xmlMarkup) { try { return XhtmlDocument.Parse(xmlMarkup); } catch (Exception) { // take the slow road below... } Tidy tidy = GetXmlConfiguredTidy(); List<string> namespacePrefixedElementNames = LocateNamespacePrefixedElementNames(xmlMarkup); AllowNamespacePrefixedElementNames(tidy, namespacePrefixedElementNames); AllowHtml5ElementNames(tidy); string xml = ParseMarkup(xmlMarkup, tidy, out TidyMessageCollection _); xml = RemoveDuplicateAttributes(xml); return XDocument.Parse(xml); } /// <exclude /> public static string OutputBodyDescendants(XDocument source) { string bodyInnerXhtml = ""; XmlWriterSettings settings = CustomizedWriterSettings(); using (var memoryStream = new MemoryStream()) { using (var writer = XmlWriter.Create(memoryStream, settings)) { XNamespace xhtml = "http://www.w3.org/1999/xhtml"; XElement bodyElement = source.Descendants(xhtml + "body").First(); foreach (XNode element in bodyElement.Nodes()) { element.WriteTo(writer); } writer.Close(); } memoryStream.Position = 0; using (var sr = new C1StreamReader(memoryStream)) { bodyInnerXhtml = sr.ReadToEnd(); } } bodyInnerXhtml = bodyInnerXhtml.Replace(" xmlns=\"http://www.w3.org/1999/xhtml\"", ""); var prefixToUriLookup = new Dictionary<string, string>(); int lastLength = -1; while (bodyInnerXhtml.Length != lastLength) { lastLength = bodyInnerXhtml.Length; MatchCollection matchCollection = _customNamespaceDeclarations.Matches(bodyInnerXhtml); foreach (Match match in matchCollection) { string prefix = match.Groups["prefix"].Value; if (!prefixToUriLookup.ContainsKey(prefix)) { prefixToUriLookup.Add(prefix, match.Groups["uri"].Value); } } if (matchCollection.Count > 0) { bodyInnerXhtml = _customNamespaceDeclarations.Replace(bodyInnerXhtml, "<$1$2>"); } } foreach (var prefixInfo in prefixToUriLookup) { Regex namespacePrefixedElement = new Regex("<(" + prefixInfo.Key + @":[a-zA-Z0-9\._]*?)([^>]*?)( ?/?)>", RegexOptions.Compiled); bodyInnerXhtml = namespacePrefixedElement.Replace(bodyInnerXhtml, "<$1$2 xmlns:" + prefixInfo.Key + "=\"" + prefixInfo.Value + "\"$3>"); } return bodyInnerXhtml; } private static XmlWriterSettings CustomizedWriterSettings() { return new XmlWriterSettings { OmitXmlDeclaration = true, ConformanceLevel = ConformanceLevel.Fragment, CloseOutput = false, Indent = true, IndentChars = "\t" }; } private static string RemoveXmlDeclarations(string html) { Regex duplicateAttributesRegex = new Regex(@"<\?.*?>"); int prevLength = -1; while (html.Length != prevLength) { prevLength = html.Length; html = duplicateAttributesRegex.Replace(html, ""); } return html; } private static string RemoveDuplicateAttributes(string html) { // TODO: optimize, way to slow, takes 150ms! int prevLength = -1; while (html.Length != prevLength) { prevLength = html.Length; html = _duplicateAttributesRegex.Replace(html, @"<$1 ${attributeName}=""$2""$4$8>"); } return html; } private static string UndoLowerCasingOfNamespacePrefixes(string html, Dictionary<string, string> namespacePrefixToUri) { foreach (var namespaceMapping in namespacePrefixToUri.Where(f => f.Key.ToLower() != f.Key)) { Regex tidyCasedElement = new Regex(@"<(.*?) xmlns:" + namespaceMapping.Key.ToLower() + @"=""" + namespaceMapping.Value + @"""(.*?)>"); html = tidyCasedElement.Replace(html, "<$1 xmlns:" + namespaceMapping.Key + @"=""" + namespaceMapping.Value + @"""$2>"); } return html; } private static string UndoLowerCasingOfElementNames(string html, List<string> elementNames) { foreach (string elementName in elementNames.Where(f => f.ToLower() != f)) { Regex tidyCasedElement = new Regex(@"<(/?)" + elementName.ToLower() + @"(.*?)>"); html = tidyCasedElement.Replace(html, "<$1" + elementName + "$2>"); } return html; } private static Tidy GetXhtmlConfiguredTidy() { var t = new Tidy(); t.Options.RawOut = true; t.Options.TidyMark = false; t.Options.CharEncoding = CharEncoding.UTF8; t.Options.DocType = DocType.Omit; t.Options.WrapLen = 0; t.Options.BreakBeforeBR = true; t.Options.DropEmptyParas = true; t.Options.Word2000 = true; t.Options.MakeClean = false; t.Options.Xhtml = true; t.Options.QuoteNbsp = false; t.Options.NumEntities = true; t.Options.AllowElementPruning = false; t.Options.LogicalEmphasis = true; return t; } private static Tidy GetXmlConfiguredTidy() { Tidy t = new Tidy(); t.Options.RawOut = true; t.Options.TidyMark = false; t.Options.CharEncoding = CharEncoding.UTF8; t.Options.DocType = DocType.Omit; t.Options.WrapLen = 0; t.Options.Xhtml = false; t.Options.XmlOut = true; t.Options.QuoteNbsp = false; t.Options.NumEntities = true; return t; } private static void AllowHtml5ElementNames(Tidy tidy) { foreach (string elementName in Html5specificElementNames) { tidy.Options.AddTag(elementName.ToLower()); } } private static void AllowNamespacePrefixedElementNames(Tidy tidy, List<string> elementNames) { foreach (string elementName in elementNames.Where(en => en != "f:function" && en != "f:param")) // f:* written into TidyNet.dll to fix http://compositec1.codeplex.com/workitem/1144 { tidy.Options.AddTag(elementName.ToLower()); } } private static List<string> LocateNamespacePrefixedElementNames(string htmlMarkup) { var prefixedElementNames = new List<string>(); MatchCollection matches = _namespacePrefixedElement.Matches(htmlMarkup); foreach (Match match in matches) { string prefixedElementName = $"{match.Groups[1].Value}:{match.Groups[2].Value}"; if (!prefixedElementNames.Contains(prefixedElementName)) { prefixedElementNames.Add(prefixedElementName); } } return prefixedElementNames; } private static List<string> LocateAttributeNamespacePrefixes(string htmlMarkup) { List<string> prefixes = new List<string>(); MatchCollection matches = _elementsWithPrefixedAttributes.Matches(htmlMarkup); foreach (Match match in matches) { string prefix = match.Groups[1].Value; if (prefixes.Contains(prefix) == false) { prefixes.Add(prefix); } } return prefixes; } private static Dictionary<string, string> LocateNamespacePrefixToUriDeclarations(string htmlMarkup) { var prefixToUri = new Dictionary<string, string>(); MatchCollection matches = _elementWithNamespaceDeclaration.Matches(htmlMarkup); foreach (Match match in matches) { string prefix = match.Groups[2].Value; string uri = match.Groups[3].Value; if (!prefixToUri.ContainsKey(prefix)) { prefixToUri.Add(prefix, uri); } else { if (prefixToUri[prefix] != uri) throw new NotImplementedException($"The namespace prefix {prefix} is used to identify multiple namespaces. This may be legal XML but is not supported here"); } } return prefixToUri; } private static bool IsValidXmlName(string name) { try { return name == XmlConvert.VerifyName(name); } catch (Exception) { return false; } } } } ================================================ FILE: Composite/Core/WebClient/Services/WysiwygEditor/PageTemplatePreview.cs ================================================ using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Web; using Composite.C1Console.Events; using System.Threading.Tasks; using Composite.Core.WebClient.PhantomJs; namespace Composite.Core.WebClient.Services.WysiwygEditor { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PageTemplatePreview { private static readonly string ServiceUrl = UrlUtils.ResolvePublicUrl("~/Renderers/TemplatePreview.ashx"); private const string RenderingMode = "template"; static PageTemplatePreview() { GlobalEventSystemFacade.OnDesignChange += ClearCache; } /// <exclude /> public class PlaceholderInformation { /// <exclude /> public string PlaceholderId { get; set; } /// <exclude /> public Rectangle ClientRectangle { get; set; } /// <exclude /> public Rectangle ClientRectangleWithZoom { get; set; } } /// <exclude /> public static bool GetPreviewInformation(HttpContext context, Guid pageId, Guid templateId, out string imageFilePath, out PlaceholderInformation[] placeholders) { int updateHash = BrowserRender.GetLastCacheUpdateTime(RenderingMode).GetHashCode(); string requestUrl = new UrlBuilder(context.Request.Url.ToString()).ServerUrl + ServiceUrl + $"?p={pageId}&t={templateId}&hash={updateHash}"; RenderingResult result = null; var renderTask = BrowserRender.RenderUrlAsync(context, requestUrl, RenderingMode); renderTask.Wait(10000); if (renderTask.Status == TaskStatus.RanToCompletion) { result = renderTask.Result; } if (result == null) { imageFilePath = null; placeholders = null; return false; } if (result.Status != RenderingResultStatus.Success) { Log.LogWarning("PageTemplatePreview", "Failed to build preview for page template '{0}'. Reason: {1}; Output:\r\n{2}", templateId, result.Status, string.Join(Environment.NewLine, result.Output)); imageFilePath = null; placeholders = null; return false; } imageFilePath = result.FilePath; ICollection<string> output = result.Output; const string templateInfoPrefix = "templateInfo:"; var placeholderData = output.FirstOrDefault(l => l.StartsWith(templateInfoPrefix)); var pList = new List<PlaceholderInformation>(); // TODO: use JSON if (placeholderData != null) { foreach (var infoPart in placeholderData.Substring(templateInfoPrefix.Length).Split('|')) { string[] parts = infoPart.Split(','); double left, top, width, height; if (parts.Length != 5 || !double.TryParse(parts[1], out left) || !double.TryParse(parts[2], out top) || !double.TryParse(parts[3], out width) || !double.TryParse(parts[4], out height)) { throw new InvalidOperationException($"Incorrectly serialized template part info: {infoPart}"); } var zoom = 1.0; pList.Add(new PlaceholderInformation { PlaceholderId = parts[0], ClientRectangle = new Rectangle((int)left, (int)top, (int)width, (int)height), ClientRectangleWithZoom = new Rectangle( (int)Math.Round(zoom * left), (int)Math.Round(zoom * top), (int)Math.Round(zoom * width), (int)Math.Round(zoom * height)) }); } } placeholders = pList.ToArray(); return true; } /// <exclude /> public static void ClearCache() { BrowserRender.ClearCache(RenderingMode); } } } ================================================ FILE: Composite/Core/WebClient/Setup/SetupServiceFacade.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.ServiceModel; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using Composite.C1Console.Security; using Composite.Core.Application; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.Localization; using Composite.Core.PackageSystem; using Composite.Core.WebClient.Setup.WebServiceClient; using Composite.Core.Xml; using Composite.C1Console.Users; using Composite.Core.ResourceSystem; using Composite.Data; namespace Composite.Core.WebClient.Setup { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class SetupServiceFacade { /// <exclude /> public static XNamespace XmlNamespace = (XNamespace)"urn:Composte.C1.Setup"; /// <exclude /> public static XName PackageElementName = XmlNamespace + "package"; /// <exclude /> public static string UrlAttributeName = "url"; /// <exclude /> public static string IdAttributeName = "id"; /// <exclude /> public static string KeyAttributeName = "key"; /// <exclude /> public static string PackageServicePingUrlFormat = "{0}/C1.asmx"; private static readonly string SetupServiceUrl = "{0}/Setup/Setup.asmx"; private static string _packageServerUrl; private static readonly string LogTitle = typeof(SetupServiceFacade).Name; private static readonly string VerboseLogTitle = "RGB(255, 55, 85)" + LogTitle; /// <exclude /> public static string PackageServerUrl { get { if (_packageServerUrl == null) { string filepath = PathUtil.Resolve(@"~/App_Data/Composite/Composite.config"); XDocument doc = XDocumentUtils.Load(filepath); XElement element = doc.Root.Descendants("Composite.SetupConfiguration").Single(); _packageServerUrl = element.Attribute("PackageServerUrl").Value; } return _packageServerUrl; } } /// <exclude /> public static bool SetUp(string setupDescriptionXml, string username, string password, string email, string language, string consoleLanguage, bool newsletter) { ApplicationOnlineHandlerFacade.TurnApplicationOffline(false); username = username.Trim().ToLowerInvariant(); XElement setupDescription = XElement.Parse(setupDescriptionXml); XElement setupRegistrationDescription = new XElement("registration", new XElement("user_email", email), new XElement("user_newsletter", newsletter), new XElement("user_consolelanguage", consoleLanguage), new XElement("user_websitelanguage", language), setupDescription); bool success = false; try { Log.LogInformation(VerboseLogTitle, "Downloading packages"); string[] packageUrls = GetPackageUrls(setupDescription).ToArray(); MemoryStream[] packages = new MemoryStream[packageUrls.Length]; Parallel.For(0, packageUrls.Length, i => { packages[i] = DownloadPackage(packageUrls[i]); }); Log.LogInformation(VerboseLogTitle, "Setting up the system for the first time"); CultureInfo locale = new CultureInfo(language); CultureInfo userCulture = new CultureInfo(consoleLanguage); ApplicationLevelEventHandlers.ApplicationStartInitialize(); Log.LogInformation(VerboseLogTitle, "Creating first locale: " + language); LocalizationFacade.AddLocale(locale, "", true, true, true); Log.LogInformation(VerboseLogTitle, "Creating first user: " + username); AdministratorAutoCreator.AutoCreateAdministrator(username, password, email, false); UserValidationFacade.FormValidateUser(username, password); UserSettings.SetUserCultureInfo(username, userCulture); CultureInfo installedLanguagePackageCulture = InstallLanguagePackage(userCulture); UserSettings.SetUserC1ConsoleUiLanguage(username, installedLanguagePackageCulture ?? StringResourceSystemFacade.GetDefaultStringCulture()); using (new DataScope(locale)) { for (int i = 0; i < packageUrls.Length; i++) { Log.LogVerbose(VerboseLogTitle, "Installing package from url " + packageUrls[i]); InstallPackage(packageUrls[i], packages[i]); // Releasing a reference to reduce memory usage packages[i].Dispose(); packages[i] = null; } } RegisterSetup(setupRegistrationDescription.ToString(), ""); Log.LogInformation(VerboseLogTitle, "Done setting up the system for the first time! Enjoy!"); success = true; } catch (Exception ex) { Log.LogCritical(LogTitle, ex); Log.LogWarning(LogTitle, "First time setup failed - could not download, install package or otherwise complete the setup."); RegisterSetup(setupRegistrationDescription.ToString(), ex.ToString()); if (RuntimeInformation.IsDebugBuild) { ApplicationOnlineHandlerFacade.TurnApplicationOnline(); throw; } } ApplicationOnlineHandlerFacade.TurnApplicationOnline(); return success; } /// <exclude /> public static bool PingServer() { SetupSoapClient client = CreateClient(); return client.Ping(); } /// <exclude /> public static XElement GetSetupDescription() { SetupSoapClient client = CreateClient(); return client.GetSetupDescription( RuntimeInformation.ProductVersion.ToString(), InstallationInformationFacade.InstallationId.ToString()); } /// <exclude /> public static XElement GetLanguages() { SetupSoapClient client = CreateClient(); return client.GetLanguages(RuntimeInformation.ProductVersion.ToString(), InstallationInformationFacade.InstallationId.ToString()); } /// <exclude /> public static Dictionary<CultureInfo, string> GetLanguagePackages() { SetupSoapClient client = CreateClient(); XElement xml = client.GetLanguagePackages(RuntimeInformation.ProductVersion.ToString(), InstallationInformationFacade.InstallationId.ToString()); return xml.Descendants("Language") .ToDictionary(f => new CultureInfo(f.Attribute("key").Value), f => f.Attribute("url").Value); } /// <exclude /> public static XmlDocument GetGetLicense() { SetupSoapClient client = CreateClient(); XElement xml = client.GetGetLicense(RuntimeInformation.ProductVersion.ToString(), InstallationInformationFacade.InstallationId.ToString()); var doc = new XmlDocument(); using (var reader = xml.CreateReader()) { doc.Load(reader); } return doc; } private static void RegisterSetup(string setupDescriptionXml, string exception) { SetupSoapClient client = CreateClient(); client.RegisterSetup(RuntimeInformation.ProductVersion.ToString(), InstallationInformationFacade.InstallationId.ToString(), setupDescriptionXml, exception); } private static CultureInfo InstallLanguagePackage(CultureInfo userCulture) { Dictionary<CultureInfo, string> languagePackages = GetLanguagePackages(); CultureInfo installLanguagePackageCulture = languagePackages.ContainsKey(userCulture) ? userCulture : languagePackages.Keys.FirstOrDefault(f => f.TwoLetterISOLanguageName == userCulture.TwoLetterISOLanguageName); if (installLanguagePackageCulture != null) { string url = languagePackages[installLanguagePackageCulture]; string packageUrl = ResolvePackageUrl(url); Log.LogInformation(VerboseLogTitle, "Installing package: " + packageUrl); var packageStream = DownloadPackage(packageUrl); InstallPackage(packageUrl, packageStream); } return installLanguagePackageCulture; } private static MemoryStream DownloadPackage(string packageUrl) { var packageStream = new MemoryStream(); try { var request = (HttpWebRequest) WebRequest.Create(packageUrl); var response = (HttpWebResponse) request.GetResponse(); const int bufferSize = 32768; byte[] buffer = new byte[bufferSize]; using (Stream inputStream = response.GetResponseStream()) { int read; while ((read = inputStream.Read(buffer, 0, bufferSize)) > 0) { packageStream.Write(buffer, 0, read); } inputStream.Close(); } } catch(ThreadAbortException) {} catch(Exception ex) { throw new InvalidOperationException($"Failed to download package '{packageUrl}'", ex); } packageStream.Seek(0, SeekOrigin.Begin); return packageStream; } private static void InstallPackage(string packageUrl, Stream packageStream) { PackageManagerInstallProcess packageManagerInstallProcess = PackageManager.Install(packageStream, true); if (packageManagerInstallProcess.PreInstallValidationResult.Count > 0) { throw WrapFirstValidationException(packageUrl, packageManagerInstallProcess.PreInstallValidationResult); } List<PackageFragmentValidationResult> validationResult = packageManagerInstallProcess.Validate(); if (validationResult.Count > 0) { throw WrapFirstValidationException(packageUrl, validationResult); } List<PackageFragmentValidationResult> installResult = packageManagerInstallProcess.Install(); if (installResult.Count > 0) { throw WrapFirstValidationException(packageUrl, installResult); } } private static SetupSoapClient CreateClient() { var timeout = TimeSpan.FromMinutes(RuntimeInformation.IsDebugBuild ? 2 : 1); var basicHttpBinding = new BasicHttpBinding { CloseTimeout = timeout, OpenTimeout = timeout, ReceiveTimeout = timeout, SendTimeout = timeout, MaxReceivedMessageSize = int.MaxValue }; if (PackageServerUrl.StartsWith("https://")) { basicHttpBinding.Security.Mode = BasicHttpSecurityMode.Transport; } return new SetupSoapClient(basicHttpBinding, new EndpointAddress(string.Format(SetupServiceUrl, PackageServerUrl))); } private static IEnumerable<string> GetPackageUrls(XElement setupDescription) { var keyAttributes = setupDescription.Descendants().Attributes(KeyAttributeName).ToList(); if (!keyAttributes.Any()) { throw new InvalidOperationException("Invalid setup description: " + setupDescription); } int maxkey = keyAttributes.Select(f => (int)f).Max(); SetupSoapClient client = CreateClient(); XElement originalSetupDescription = client.GetSetupDescription(RuntimeInformation.ProductVersion.ToString(), InstallationInformationFacade.InstallationId.ToString()); var element = (from elm in originalSetupDescription.Descendants() let keyAttr = elm.Attribute(KeyAttributeName) where keyAttr != null && (int)keyAttr == maxkey select elm).Single(); foreach (XElement packageElement in setupDescription.Descendants(PackageElementName)) { XAttribute idAttribute = packageElement.Attribute(IdAttributeName); if (idAttribute == null) { throw new InvalidOperationException($"Setup XML malformed, '{IdAttributeName}' is missing on a '{PackageElementName}' element"); } string url = (from elm in element.Descendants(PackageElementName) where elm.Attribute(IdAttributeName).Value == idAttribute.Value select elm.Attribute(UrlAttributeName).Value).SingleOrDefault(); yield return ResolvePackageUrl(url); } } private static string ResolvePackageUrl(string url) { if (url.StartsWith("http://") || url.StartsWith("https://")) { return url; } return PackageServerUrl + url; } private static Exception WrapFirstValidationException(string packageUrl, IEnumerable<PackageFragmentValidationResult> packageFragmentValidationResults) { var firstError = packageFragmentValidationResults.First(); var innerException = firstError.Exception ?? new InvalidOperationException(firstError.Message); throw new InvalidOperationException($"Failed to install package '{packageUrl}'", innerException); } } } ================================================ FILE: Composite/Core/WebClient/Setup/WebServiceClient/Reference.cs ================================================ //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Composite.Core.WebClient.Setup.WebServiceClient { [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ServiceModel.ServiceContractAttribute(Namespace = "http://www.composite.net/ns/management", ConfigurationName = "ServiceReference1.SetupSoap")] internal interface SetupSoap { [System.ServiceModel.OperationContractAttribute(Action = "http://www.composite.net/ns/management/Ping", ReplyAction = "*")] bool Ping(); // CODEGEN: Generating message contract since element name version from namespace http://www.composite.net/ns/management is not marked nillable [System.ServiceModel.OperationContractAttribute(Action = "http://www.composite.net/ns/management/GetSetupDescription", ReplyAction = "*")] Composite.Core.WebClient.Setup.WebServiceClient.GetSetupDescriptionResponse GetSetupDescription(Composite.Core.WebClient.Setup.WebServiceClient.GetSetupDescriptionRequest request); // CODEGEN: Generating message contract since element name version from namespace http://www.composite.net/ns/management is not marked nillable [System.ServiceModel.OperationContractAttribute(Action = "http://www.composite.net/ns/management/GetGetLicense", ReplyAction = "*")] Composite.Core.WebClient.Setup.WebServiceClient.GetGetLicenseResponse GetGetLicense(Composite.Core.WebClient.Setup.WebServiceClient.GetGetLicenseRequest request); // CODEGEN: Generating message contract since element name version from namespace http://www.composite.net/ns/management is not marked nillable [System.ServiceModel.OperationContractAttribute(Action = "http://www.composite.net/ns/management/GetLanguages", ReplyAction = "*")] Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagesResponse GetLanguages(Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagesRequest request); // CODEGEN: Generating message contract since element name version from namespace http://www.composite.net/ns/management is not marked nillable [System.ServiceModel.OperationContractAttribute(Action = "http://www.composite.net/ns/management/GetLanguagePackages", ReplyAction = "*")] Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagePackagesResponse GetLanguagePackages(Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagePackagesRequest request); // CODEGEN: Generating message contract since element name version from namespace http://www.composite.net/ns/management is not marked nillable [System.ServiceModel.OperationContractAttribute(Action = "http://www.composite.net/ns/management/RegisterSetup", ReplyAction = "*")] Composite.Core.WebClient.Setup.WebServiceClient.RegisterSetupResponse RegisterSetup(Composite.Core.WebClient.Setup.WebServiceClient.RegisterSetupRequest request); } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] internal partial class GetSetupDescriptionRequest { [System.ServiceModel.MessageBodyMemberAttribute(Name = "GetSetupDescription", Namespace = "http://www.composite.net/ns/management", Order = 0)] public Composite.Core.WebClient.Setup.WebServiceClient.GetSetupDescriptionRequestBody Body; public GetSetupDescriptionRequest() { } public GetSetupDescriptionRequest(Composite.Core.WebClient.Setup.WebServiceClient.GetSetupDescriptionRequestBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://www.composite.net/ns/management")] internal partial class GetSetupDescriptionRequestBody { [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 0)] public string version; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 1)] public string installationId; public GetSetupDescriptionRequestBody() { } public GetSetupDescriptionRequestBody(string version, string installationId) { this.version = version; this.installationId = installationId; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] internal partial class GetSetupDescriptionResponse { [System.ServiceModel.MessageBodyMemberAttribute(Name = "GetSetupDescriptionResponse", Namespace = "http://www.composite.net/ns/management", Order = 0)] public Composite.Core.WebClient.Setup.WebServiceClient.GetSetupDescriptionResponseBody Body; public GetSetupDescriptionResponse() { } public GetSetupDescriptionResponse(Composite.Core.WebClient.Setup.WebServiceClient.GetSetupDescriptionResponseBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://www.composite.net/ns/management")] internal partial class GetSetupDescriptionResponseBody { [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 0)] public System.Xml.Linq.XElement GetSetupDescriptionResult; public GetSetupDescriptionResponseBody() { } public GetSetupDescriptionResponseBody(System.Xml.Linq.XElement GetSetupDescriptionResult) { this.GetSetupDescriptionResult = GetSetupDescriptionResult; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] internal partial class GetGetLicenseRequest { [System.ServiceModel.MessageBodyMemberAttribute(Name = "GetGetLicense", Namespace = "http://www.composite.net/ns/management", Order = 0)] public Composite.Core.WebClient.Setup.WebServiceClient.GetGetLicenseRequestBody Body; public GetGetLicenseRequest() { } public GetGetLicenseRequest(Composite.Core.WebClient.Setup.WebServiceClient.GetGetLicenseRequestBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://www.composite.net/ns/management")] internal partial class GetGetLicenseRequestBody { [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 0)] public string version; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 1)] public string installationId; public GetGetLicenseRequestBody() { } public GetGetLicenseRequestBody(string version, string installationId) { this.version = version; this.installationId = installationId; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] internal partial class GetGetLicenseResponse { [System.ServiceModel.MessageBodyMemberAttribute(Name = "GetGetLicenseResponse", Namespace = "http://www.composite.net/ns/management", Order = 0)] public Composite.Core.WebClient.Setup.WebServiceClient.GetGetLicenseResponseBody Body; public GetGetLicenseResponse() { } public GetGetLicenseResponse(Composite.Core.WebClient.Setup.WebServiceClient.GetGetLicenseResponseBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://www.composite.net/ns/management")] internal partial class GetGetLicenseResponseBody { [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 0)] public System.Xml.Linq.XElement GetGetLicenseResult; public GetGetLicenseResponseBody() { } public GetGetLicenseResponseBody(System.Xml.Linq.XElement GetGetLicenseResult) { this.GetGetLicenseResult = GetGetLicenseResult; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] internal partial class GetLanguagesRequest { [System.ServiceModel.MessageBodyMemberAttribute(Name = "GetLanguages", Namespace = "http://www.composite.net/ns/management", Order = 0)] public Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagesRequestBody Body; public GetLanguagesRequest() { } public GetLanguagesRequest(Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagesRequestBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://www.composite.net/ns/management")] internal partial class GetLanguagesRequestBody { [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 0)] public string version; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 1)] public string installationId; public GetLanguagesRequestBody() { } public GetLanguagesRequestBody(string version, string installationId) { this.version = version; this.installationId = installationId; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] internal partial class GetLanguagesResponse { [System.ServiceModel.MessageBodyMemberAttribute(Name = "GetLanguagesResponse", Namespace = "http://www.composite.net/ns/management", Order = 0)] public Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagesResponseBody Body; public GetLanguagesResponse() { } public GetLanguagesResponse(Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagesResponseBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://www.composite.net/ns/management")] internal partial class GetLanguagesResponseBody { [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 0)] public System.Xml.Linq.XElement GetLanguagesResult; public GetLanguagesResponseBody() { } public GetLanguagesResponseBody(System.Xml.Linq.XElement GetLanguagesResult) { this.GetLanguagesResult = GetLanguagesResult; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] internal partial class GetLanguagePackagesRequest { [System.ServiceModel.MessageBodyMemberAttribute(Name = "GetLanguagePackages", Namespace = "http://www.composite.net/ns/management", Order = 0)] public Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagePackagesRequestBody Body; public GetLanguagePackagesRequest() { } public GetLanguagePackagesRequest(Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagePackagesRequestBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://www.composite.net/ns/management")] internal partial class GetLanguagePackagesRequestBody { [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 0)] public string version; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 1)] public string installationId; public GetLanguagePackagesRequestBody() { } public GetLanguagePackagesRequestBody(string version, string installationId) { this.version = version; this.installationId = installationId; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] internal partial class GetLanguagePackagesResponse { [System.ServiceModel.MessageBodyMemberAttribute(Name = "GetLanguagePackagesResponse", Namespace = "http://www.composite.net/ns/management", Order = 0)] public Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagePackagesResponseBody Body; public GetLanguagePackagesResponse() { } public GetLanguagePackagesResponse(Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagePackagesResponseBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://www.composite.net/ns/management")] internal partial class GetLanguagePackagesResponseBody { [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 0)] public System.Xml.Linq.XElement GetLanguagePackagesResult; public GetLanguagePackagesResponseBody() { } public GetLanguagePackagesResponseBody(System.Xml.Linq.XElement GetLanguagePackagesResult) { this.GetLanguagePackagesResult = GetLanguagePackagesResult; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] internal partial class RegisterSetupRequest { [System.ServiceModel.MessageBodyMemberAttribute(Name = "RegisterSetup", Namespace = "http://www.composite.net/ns/management", Order = 0)] public Composite.Core.WebClient.Setup.WebServiceClient.RegisterSetupRequestBody Body; public RegisterSetupRequest() { } public RegisterSetupRequest(Composite.Core.WebClient.Setup.WebServiceClient.RegisterSetupRequestBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://www.composite.net/ns/management")] internal partial class RegisterSetupRequestBody { [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 0)] public string version; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 1)] public string installationId; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 2)] public string setupDescriptionXml; [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 3)] public string exception; public RegisterSetupRequestBody() { } public RegisterSetupRequestBody(string version, string installationId, string setupDescriptionXml, string exception) { this.version = version; this.installationId = installationId; this.setupDescriptionXml = setupDescriptionXml; this.exception = exception; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] internal partial class RegisterSetupResponse { [System.ServiceModel.MessageBodyMemberAttribute(Name = "RegisterSetupResponse", Namespace = "http://www.composite.net/ns/management", Order = 0)] public Composite.Core.WebClient.Setup.WebServiceClient.RegisterSetupResponseBody Body; public RegisterSetupResponse() { } public RegisterSetupResponse(Composite.Core.WebClient.Setup.WebServiceClient.RegisterSetupResponseBody Body) { this.Body = Body; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://www.composite.net/ns/management")] internal partial class RegisterSetupResponseBody { [System.Runtime.Serialization.DataMemberAttribute(Order = 0)] public bool RegisterSetupResult; public RegisterSetupResponseBody() { } public RegisterSetupResponseBody(bool RegisterSetupResult) { this.RegisterSetupResult = RegisterSetupResult; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] internal interface SetupSoapChannel : Composite.Core.WebClient.Setup.WebServiceClient.SetupSoap, System.ServiceModel.IClientChannel { } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] internal partial class SetupSoapClient : System.ServiceModel.ClientBase<Composite.Core.WebClient.Setup.WebServiceClient.SetupSoap>, Composite.Core.WebClient.Setup.WebServiceClient.SetupSoap { public SetupSoapClient() { } public SetupSoapClient(string endpointConfigurationName) : base(endpointConfigurationName) { } public SetupSoapClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public SetupSoapClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public SetupSoapClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } public bool Ping() { return base.Channel.Ping(); } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] Composite.Core.WebClient.Setup.WebServiceClient.GetSetupDescriptionResponse Composite.Core.WebClient.Setup.WebServiceClient.SetupSoap.GetSetupDescription(Composite.Core.WebClient.Setup.WebServiceClient.GetSetupDescriptionRequest request) { return base.Channel.GetSetupDescription(request); } public System.Xml.Linq.XElement GetSetupDescription(string version, string installationId) { Composite.Core.WebClient.Setup.WebServiceClient.GetSetupDescriptionRequest inValue = new Composite.Core.WebClient.Setup.WebServiceClient.GetSetupDescriptionRequest(); inValue.Body = new Composite.Core.WebClient.Setup.WebServiceClient.GetSetupDescriptionRequestBody(); inValue.Body.version = version; inValue.Body.installationId = installationId; Composite.Core.WebClient.Setup.WebServiceClient.GetSetupDescriptionResponse retVal = ((Composite.Core.WebClient.Setup.WebServiceClient.SetupSoap)(this)).GetSetupDescription(inValue); return retVal.Body.GetSetupDescriptionResult; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] Composite.Core.WebClient.Setup.WebServiceClient.GetGetLicenseResponse Composite.Core.WebClient.Setup.WebServiceClient.SetupSoap.GetGetLicense(Composite.Core.WebClient.Setup.WebServiceClient.GetGetLicenseRequest request) { return base.Channel.GetGetLicense(request); } public System.Xml.Linq.XElement GetGetLicense(string version, string installationId) { Composite.Core.WebClient.Setup.WebServiceClient.GetGetLicenseRequest inValue = new Composite.Core.WebClient.Setup.WebServiceClient.GetGetLicenseRequest(); inValue.Body = new Composite.Core.WebClient.Setup.WebServiceClient.GetGetLicenseRequestBody(); inValue.Body.version = version; inValue.Body.installationId = installationId; Composite.Core.WebClient.Setup.WebServiceClient.GetGetLicenseResponse retVal = ((Composite.Core.WebClient.Setup.WebServiceClient.SetupSoap)(this)).GetGetLicense(inValue); return retVal.Body.GetGetLicenseResult; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagesResponse Composite.Core.WebClient.Setup.WebServiceClient.SetupSoap.GetLanguages(Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagesRequest request) { return base.Channel.GetLanguages(request); } public System.Xml.Linq.XElement GetLanguages(string version, string installationId) { Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagesRequest inValue = new Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagesRequest(); inValue.Body = new Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagesRequestBody(); inValue.Body.version = version; inValue.Body.installationId = installationId; Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagesResponse retVal = ((Composite.Core.WebClient.Setup.WebServiceClient.SetupSoap)(this)).GetLanguages(inValue); return retVal.Body.GetLanguagesResult; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagePackagesResponse Composite.Core.WebClient.Setup.WebServiceClient.SetupSoap.GetLanguagePackages(Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagePackagesRequest request) { return base.Channel.GetLanguagePackages(request); } public System.Xml.Linq.XElement GetLanguagePackages(string version, string installationId) { Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagePackagesRequest inValue = new Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagePackagesRequest(); inValue.Body = new Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagePackagesRequestBody(); inValue.Body.version = version; inValue.Body.installationId = installationId; Composite.Core.WebClient.Setup.WebServiceClient.GetLanguagePackagesResponse retVal = ((Composite.Core.WebClient.Setup.WebServiceClient.SetupSoap)(this)).GetLanguagePackages(inValue); return retVal.Body.GetLanguagePackagesResult; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] Composite.Core.WebClient.Setup.WebServiceClient.RegisterSetupResponse Composite.Core.WebClient.Setup.WebServiceClient.SetupSoap.RegisterSetup(Composite.Core.WebClient.Setup.WebServiceClient.RegisterSetupRequest request) { return base.Channel.RegisterSetup(request); } public bool RegisterSetup(string version, string installationId, string setupDescriptionXml, string exception) { Composite.Core.WebClient.Setup.WebServiceClient.RegisterSetupRequest inValue = new Composite.Core.WebClient.Setup.WebServiceClient.RegisterSetupRequest(); inValue.Body = new Composite.Core.WebClient.Setup.WebServiceClient.RegisterSetupRequestBody(); inValue.Body.version = version; inValue.Body.installationId = installationId; inValue.Body.setupDescriptionXml = setupDescriptionXml; inValue.Body.exception = exception; Composite.Core.WebClient.Setup.WebServiceClient.RegisterSetupResponse retVal = ((Composite.Core.WebClient.Setup.WebServiceClient.SetupSoap)(this)).RegisterSetup(inValue); return retVal.Body.RegisterSetupResult; } } } ================================================ FILE: Composite/Core/WebClient/StandardPlugins/SessionStateProviders/DefaultSessionStateProvider/DefaultSessionStateProvider.cs ================================================ using System; using System.Linq; using System.Threading; using Composite.Data; using Composite.Core.Logging; using Composite.Core.WebClient.State; using Composite.Core.Extensions; using Composite.Core.WebClient.State.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.WebClient.SessionStateProviders.DefaultSessionStateProvider { [ConfigurationElementType(typeof(SessionStateProviderData))] internal class DefaultSessionStateProvider : ISessionStateProvider { private static int _counter = 0; public void AddState<T>(Guid stateId, T value, DateTime exirationDate) { PerformCleanUpIfNeeded(); var sessionStateEntry = DataFacade.BuildNew<ISessionStateEntry>(); sessionStateEntry.Id = stateId; sessionStateEntry.ExpirationDate = exirationDate; sessionStateEntry.SerializedValue = SerializationUtil.Serialize(value); using(new DataScope(PublicationScope.Unpublished)) using (Composite.Data.Transactions.TransactionsFacade.SuppressTransactionScope()) { DataFacade.AddNew(sessionStateEntry); } } public bool TryGetState<T>(Guid stateId, out T state) { ISessionStateEntry entry = GetSessionStateEntry(stateId); if (entry == null) { state = default(T); return false; } state = SerializationUtil.Deserialize<T>(entry.SerializedValue); return true; } public void SetState<T>(Guid stateId, T value, DateTime expirationDate) { Verify.ArgumentNotNull(value, "value"); Verify.ArgumentCondition(expirationDate != DateTime.MaxValue, "expirationDate", "Expiration date has to be achievable"); Verify.ArgumentCondition(stateId != Guid.Empty, "stateId", "Guid.Empty isn't an exceptable value."); ISessionStateEntry entry = GetSessionStateEntry(stateId); if (entry == null) { AddState(stateId, value, expirationDate); return; } entry.SerializedValue = SerializationUtil.Serialize(value); entry.ExpirationDate = expirationDate; using (new DataScope(PublicationScope.Unpublished)) using (Composite.Data.Transactions.TransactionsFacade.SuppressTransactionScope()) { DataFacade.Update(entry); } } public void RemoveState(Guid stateId) { ISessionStateEntry entry = GetSessionStateEntry(stateId); if (entry == null) { return; } using (Composite.Data.Transactions.TransactionsFacade.SuppressTransactionScope()) { DataFacade.Delete(entry); } } private static ISessionStateEntry GetSessionStateEntry(Guid stateId) { using (new DataScope(PublicationScope.Unpublished)) { var queryable = DataFacade.GetData<ISessionStateEntry>(); ISessionStateEntry entry; if (queryable.IsEnumerableQuery()) { entry = queryable.AsEnumerable().FirstOrDefault(row => row.Id == stateId); } else { entry = queryable.FirstOrDefault(row => row.Id == stateId); } return entry; } } private static void PerformCleanUpIfNeeded() { // Performingc cleaning-up at the first time with probability 20%, and on once per every 100 calls int counter = Interlocked.Increment(ref _counter); if (counter == 1) { if(DateTime.Now.Second % 5 != 3) { return; } } else if (counter % 100 != 1) { return; } CleanUpData(); } private static void CleanUpData() { var now = DateTime.Now; try { using (new DataScope(PublicationScope.Unpublished)) using (Composite.Data.Transactions.TransactionsFacade.SuppressTransactionScope()) { DataFacade.Delete<ISessionStateEntry>(entry => entry.ExpirationDate < now); } } catch(Exception e) { LoggingService.LogWarning(typeof(DefaultSessionStateProvider).Name, new InvalidOperationException("Failed to perform clean-up", e)); } } } } ================================================ FILE: Composite/Core/WebClient/StandardPlugins/SessionStateProviders/DefaultSessionStateProvider/ISessionStateEntry.cs ================================================ using System; using Composite.Data; namespace Composite.Plugins.WebClient.SessionStateProviders.DefaultSessionStateProvider { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Title("Session State Entry")] [AutoUpdateble] [ImmutableTypeId("{91964c1b-35c1-446c-9e47-6b8d8e65997f}")] [KeyPropertyName("Id")] [DataScope(DataScopeIdentifier.AdministratedName)] [Caching(CachingType.Full)] public interface ISessionStateEntry : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{8e0f00dc-a364-4bdc-bed4-0fa771cce148}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.DateTime)] [ImmutableFieldId("{f2ba2a81-cd6a-4e48-8f12-a4446a1df046}")] DateTime ExpirationDate { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{174b9f86-c45b-434a-a3a1-083f78fcfa93}")] string SerializedValue { get; set; } } } ================================================ FILE: Composite/Core/WebClient/StandardPlugins/SessionStateProviders/DefaultSessionStateProvider/SerializationUtil.cs ================================================ using System; using System.IO; using System.Text; using System.Xml; using System.Xml.Serialization; namespace Composite.Plugins.WebClient.SessionStateProviders.DefaultSessionStateProvider { internal static class SerializationUtil { internal static readonly Encoding Encoding = Encoding.UTF8; public static string SerializeInternal<T>(T value) { return SerializeInternal(typeof (T), value); } public static string SerializeInternal(Type type, object value) { XmlSerializer serializer = GetSerializer(type); using (MemoryStream ms = new MemoryStream()) { using (var xmlTextWriter = new XmlTextWriter(ms, Encoding)) { serializer.Serialize(xmlTextWriter, value); } return Encoding.GetString(ms.ToArray()); } } public static object DeserializeInternal(Type type, string serializedValue) { XmlSerializer serializer = GetSerializer(type); byte[] bytes = Encoding.GetBytes(serializedValue); using (var stream = new MemoryStream(bytes)) { return serializer.Deserialize(stream); } } public static string Serialize<T>(T value) { Type type = typeof (T); if(TypeRequiresWrapping(type)) { return SerializeInternal(new XmlSerializationWrapper(value)); } return SerializeInternal<T>(value); } public static T Deserialize<T>(string serializedValue) { Type type = typeof (T); if (TypeRequiresWrapping(type)) { var wrapper = (XmlSerializationWrapper)DeserializeInternal(typeof (XmlSerializationWrapper), serializedValue); return (T)wrapper.Deserialize(); } return (T) DeserializeInternal(type, serializedValue); } private static bool TypeRequiresWrapping(Type type) { return type.IsInterface || type.FullName == "System.Object" || (type.IsClass && !type.IsSealed); } private static XmlSerializer GetSerializer(Type type) { // TODO: implement caching return new XmlSerializer(type); } } } ================================================ FILE: Composite/Core/WebClient/StandardPlugins/SessionStateProviders/DefaultSessionStateProvider/XmlSerializationWrapper.cs ================================================ using System; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Xml.Serialization; using Composite.Core.Extensions; namespace Composite.Plugins.WebClient.SessionStateProviders.DefaultSessionStateProvider { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] [XmlRootAttribute(ElementName = "root")] public sealed class XmlSerializationWrapper { /// <exclude /> public string TypeName; /// <exclude /> public string AssebmlyName; /// <exclude /> public string Value; // For serialization purposes /// <exclude /> public XmlSerializationWrapper() { } internal XmlSerializationWrapper(object value) { Verify.ArgumentNotNull(value, "value"); Type type = value.GetType(); TypeName = type.FullName; AssebmlyName = type.Assembly.GetName().Name; Value = SerializationUtil.SerializeInternal(type, value); } /// <exclude /> public object Deserialize() { Verify.IsNotNull(AssebmlyName, "'AssebmlyName' is null"); Verify.IsNotNull(TypeName, "'TypeName' is null"); // TODO: Caching? Assembly asm = AppDomain.CurrentDomain.GetAssemblies().Where(a => a.GetName().Name == AssebmlyName).FirstOrDefault(); if(asm == null) throw new SerializationException("Failed to find assembly '{0}'".FormatWith(AssebmlyName)); Type type = asm.GetType(TypeName); Verify.IsNotNull(type, "Failed to get type '{0}' from assembly '{1}'", AssebmlyName, TypeName); return SerializationUtil.DeserializeInternal(type, Value); } } } ================================================ FILE: Composite/Core/WebClient/State/ISessionStateProvider.cs ================================================ using System; using Composite.Core.WebClient.State.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.WebClient.State { /// <summary> /// Defines access to a session state /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [CustomFactory(typeof(SessionStateProviderCustomFactory))] public interface ISessionStateProvider { /// <exclude /> void AddState<T>(Guid stateId, T value, DateTime exirationDate); /// <exclude /> bool TryGetState<T>(Guid stateId, out T state); /// <exclude /> void SetState<T>(Guid stateId, T value, DateTime exirationDate); /// <exclude /> void RemoveState(Guid stateId); } } ================================================ FILE: Composite/Core/WebClient/State/Runtime/SessionStateProviderCustomFactory.cs ================================================ using System; using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.WebClient.State.Runtime { internal sealed class SessionStateProviderCustomFactory : AssemblerBasedCustomFactory<ISessionStateProvider, SessionStateProviderData> { protected override SessionStateProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { SessionStateProviderSettings settings = configurationSource.GetSection(SessionStateProviderSettings.SectionName) as SessionStateProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", SessionStateProviderSettings.SectionName)); } return settings.Providers.Get(name); } } } ================================================ FILE: Composite/Core/WebClient/State/Runtime/SessionStateProviderFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Core.WebClient.State.Runtime { internal class SessionStateProviderFactory : NameTypeFactoryBase<ISessionStateProvider> { public SessionStateProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/Core/WebClient/State/Runtime/SessionStateProviderSettings.cs ================================================ using System; using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Core.WebClient.State.Runtime { internal sealed class SessionStateProviderSettings : SerializableConfigurationSection { public const string SectionName = "Composite.Core.WebClient.Plugins.SessionStateProviderConfiguration"; private const string _providersPropertyName = "Providers"; [ConfigurationProperty(_providersPropertyName)] public NameTypeConfigurationElementCollection<SessionStateProviderData, SessionStateProviderData> Providers { get { return (NameTypeConfigurationElementCollection<SessionStateProviderData, SessionStateProviderData>)base[_providersPropertyName]; } } } [Assembler(typeof(NonConfigurableSessionStateProviderDataAssembler))] internal class SessionStateProviderData : NameTypeConfigurationElement { } internal sealed class NonConfigurableSessionStateProviderDataAssembler : IAssembler<ISessionStateProvider, SessionStateProviderData> { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public ISessionStateProvider Assemble(IBuilderContext context, SessionStateProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (ISessionStateProvider)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/Core/WebClient/State/StateManager.cs ================================================ using System; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.C1Console.Events; using Composite.Core.Extensions; using Composite.Core.WebClient.State.Runtime; namespace Composite.Core.WebClient.State { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class SessionStateManager { /// <exclude /> public static readonly string DefaultProviderName = "Default"; private static readonly ResourceLocker<Resources> _resourceLocker = new ResourceLocker<Resources>(new Resources(), Resources.Initialize); static SessionStateManager() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } /// <exclude /> public static ISessionStateProvider DefaultProvider { get { return GetProvider(DefaultProviderName); } } /// <exclude /> public static ISessionStateProvider GetProvider(string name) { var resources = _resourceLocker; ISessionStateProvider provider; if (!resources.Resources.Providers.TryGetValue(name, out provider)) { lock (resources) { if (!resources.Resources.Providers.TryGetValue(name, out provider)) { try { provider = resources.Resources.Factory.Create(name); resources.Resources.Providers.Add(name, provider); } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } } } return provider; } private static void Flush() { var resourceLocker = _resourceLocker; lock (resourceLocker) { resourceLocker.ResetInitialization(); } } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException("Failed to load the configuration section '{0}' from the configuration.".FormatWith(SessionStateProviderSettings.SectionName), ex); } private sealed class Resources { public SessionStateProviderFactory Factory { get; set; } public Hashtable<string, ISessionStateProvider> Providers { get; set; } public static void Initialize(Resources resources) { try { resources.Factory = new SessionStateProviderFactory(); } catch (NullReferenceException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } resources.Providers = new Hashtable<string, ISessionStateProvider>(); } } } } ================================================ FILE: Composite/Core/WebClient/StyleLoader.cs ================================================ using Composite.Core.IO; namespace Composite.Core.WebClient { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class StyleLoader { /// <exclude /> public static string Render(string directive = null) { string root = UrlUtils.AdminRootPath; bool isInDevelopMode = CookieHandler.Get("mode") == "develop"; string styleFile = isInDevelopMode ? "/styles/styles.css" : "/styles/styles.min.css"; string cssLink = root + styleFile; string filePath = PathUtil.Resolve("~/Composite" + styleFile); if (C1File.Exists(filePath)) { cssLink += "?timestamp=" + C1File.GetLastWriteTimeUtc(filePath).GetHashCode(); } return stylesheet(cssLink); } private static string stylesheet(string url) { return @"<link rel=""stylesheet"" type=""text/css"" href=""" + url + @"""/>"; } } } ================================================ FILE: Composite/Core/WebClient/TemplatePreviewRouteHandler.cs ================================================ using System; using System.Web; using System.Web.Routing; using Composite.C1Console.Security; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.WebClient.Services.WysiwygEditor; namespace Composite.Core.WebClient { internal class TemplatePreviewRoute : Route { // Adding "x" as a fictional paramter, so MVC wouldn't use this route for producing outbound links public TemplatePreviewRoute() : base("Renderers/TemplatePreviewImag{e}", new TemplatePreviewRouteHandler()) { } } internal class TemplatePreviewRouteHandler : IRouteHandler { public IHttpHandler GetHttpHandler(RequestContext requestContext) { return new TemplatePreviewHttpHandler(); } } /// <summary> /// Renders image that shows information about a function information in Visual Editor /// </summary> internal class TemplatePreviewHttpHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { if (!UserValidationFacade.IsLoggedIn()) { context.Response.ContentType = MimeTypeInfo.Text; context.Response.Write("No user logged in"); context.Response.StatusCode = 401; return; } try { string t = context.Request["t"]; Verify.That(!t.IsNullOrEmpty(), "Missing query string argument 't'"); string p = context.Request["p"]; Verify.That(!p.IsNullOrEmpty(), "Missing query string argument 'p'"); Guid templateId = Guid.Parse(t); Guid pageId = Guid.Parse(p); PageTemplatePreview.GetPreviewInformation(context, pageId, templateId, out string filePath, out _); Verify.That(C1File.Exists(filePath), "Preview file missing"); context.Response.ContentType = "image/png"; context.Response.WriteFile(filePath); } catch (Exception ex) { Log.LogError(nameof(TemplatePreviewHttpHandler), ex); throw; } } public bool IsReusable => true; } } ================================================ FILE: Composite/Core/WebClient/UiControlLib/BindingUpdatePanel.cs ================================================ //using System.ComponentModel; //using System.Web.UI; //using System.Web.UI.WebControls; //using Composite.Core.IO; //using System.Globalization; //using Composite.Core.WebClient.UiControlLib.Foundation; //namespace Composite.Core.WebClient.UiControlLib //{ // public enum RepaintModeOptions // { // Normal, // Hidden, // Suspended // } // public class DisabledUpdatePanel : PlaceHolder // { // public DisabledUpdatePanel() // { // ChildrenAsTriggers = true; // UpdateMode = UpdatePanelUpdateMode.Always; // } // public bool IsInPartialRendering // { // get // { // return false; // } // } // public UpdatePanelUpdateMode UpdateMode { get; set; } // public bool ChildrenAsTriggers { get; set; } // public Control ContentTemplateContainer // { // get // { // return this; // } // } // public void Update() // { // // Do nothing // } // } // public class BindingUpdatePanel : /* DisabledUpdatePanel */ UpdatePanel // { // public BindingUpdatePanel() // { // this.RepaintMode = RepaintModeOptions.Normal; // } // private bool _rendered = false; // [Category("Appearance"), DefaultValue(""), Description("CSS class names")] // public string CssClass { get; set; } // [Category("Appearance"), DefaultValue(""), Description("How repaints should be handled on the client (Normal, Hidden or Suspended)")] // public RepaintModeOptions RepaintMode { get; set; }// normal, hidden, suspended // [Category("Appearance"), DefaultValue("")] // public string Flex { get; set; } // [Category("Appearance"), DefaultValue("")] // public string ForceFitness { get; set; } // [Category("Appearance"), DefaultValue(""), Description("Some ui:updatepanels may be of a specialized type")] // public string ClientType { get; set; } // protected override void RenderChildren(HtmlTextWriter writer) // { // if (this.IsInPartialRendering==false) // { // if (string.IsNullOrEmpty(this.CssClass) == false) // { // writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass); // } // writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); // writer.AddAttribute("repaintmode", this.RepaintMode.ToString().ToLower()); // if (string.IsNullOrEmpty(this.Flex)==false) writer.AddAttribute("flex", this.Flex); // if (string.IsNullOrEmpty(this.ForceFitness)==false) writer.AddAttribute("forcefitness", this.ForceFitness); // if (string.IsNullOrEmpty(this.ClientType) == false) writer.AddAttribute("type", this.ClientType); // writer.RenderBeginTag("ui:updatepanel"); // writer.RenderBeginTag("ui:updatepanelbody"); // HtmlTextWriter writer2 = new HtmlTextWriter(new StringWriter(Users.UserSettings.CultureInfo)); // base.RenderChildren(writer2); // string innerMarkupWithUnwantedDiv = writer2.InnerWriter.ToString(); // int openTagEnd = innerMarkupWithUnwantedDiv.IndexOf('>'); // int closeTagStart = innerMarkupWithUnwantedDiv.LastIndexOf('<'); // if (closeTagStart > openTagEnd) // { // writer.Write( innerMarkupWithUnwantedDiv.Substring( openTagEnd+1, (closeTagStart - openTagEnd)-1 )); // } // writer.RenderEndTag(); // writer.RenderEndTag(); // } // else // { // if (_rendered==true) // { // return; // } // base.RenderChildren(writer); // } // _rendered = true; // } // } //} ================================================ FILE: Composite/Core/WebClient/UiControlLib/CheckBox.cs ================================================ using System; using System.Web.UI; using Composite.Core.ResourceSystem; using Composite.Core.WebClient.UiControlLib.Foundation; namespace Composite.Core.WebClient.UiControlLib { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class CheckBox : System.Web.UI.WebControls.CheckBox { /// <exclude /> public string ItemLabel { get { return (string) ViewState[nameof(ItemLabel)]; } set { ViewState[nameof(ItemLabel)] = value; } } /// <exclude /> protected override void Render(HtmlTextWriter writer) { writer.WriteBeginTag("ui:checkbox"); writer.WriteAttribute("label", StringResourceSystemFacade.ParseString(this.ItemLabel ?? "")); if (!string.IsNullOrEmpty(this.ToolTip)) { writer.WriteAttribute("title", StringResourceSystemFacade.ParseString(this.ToolTip ?? "")); } writer.WriteAttribute("name", this.UniqueID); if (this.AutoPostBack) { writer.WriteAttribute("callbackid", this.ClientID); writer.WriteAttribute("oncommand", "this.dispatchAction(PageBinding.ACTIONEVENT_DOPOSTBACK);"); } writer.WriteAttribute("ischecked", this.Checked.ToString().ToLower()); this.WriteClientAttributes(writer); writer.Write(HtmlTextWriter.SelfClosingTagEnd); } } } ================================================ FILE: Composite/Core/WebClient/UiControlLib/ClickButton.cs ================================================ using System.ComponentModel; using System.Web.UI; using System.Web.UI.WebControls; using Composite.Core.WebClient.UiControlLib.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Core.WebClient.UiControlLib { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ClickButton : LinkButton { /// <exclude /> public ClickButton() { this.AutoPostBack = true; } /// <exclude /> [Category("Appearance"), DefaultValue(""), Description("The id the ui client should see")] public virtual string CustomClientId { get; set; } /// <exclude /> [Category("Appearance"), DefaultValue(""), Description("Client sceipt that ensure post back should be appended to CustomClientScript. Default is true.")] public virtual bool AutoPostBack { get; set; } /// <exclude /> [Category("Appearance"), DefaultValue(""), Description("Image to show in the buttom")] public virtual string ImageUrl { get; set; } /// <exclude /> [Category("Appearance"), DefaultValue(""), Description("Image to show in the buttom when the button is disabled")] public virtual string ImageUrlWhenDisabled { get; set; } /// <exclude /> protected override void Render(HtmlTextWriter writer) { writer.WriteBeginTag("ui:clickbutton"); writer.WriteAttribute("label", StringResourceSystemFacade.ParseString(this.Text)); writer.WriteAttribute("callbackid", this.ClientID); string oncommand = ""; if (string.IsNullOrEmpty(this.OnClientClick) == false) { oncommand += this.OnClientClick; } if (this.AutoPostBack) { if (oncommand.Length > 0 && oncommand.Trim().EndsWith(";") == false) { oncommand += ";"; } // now implied by callbackid! // oncommand += "this.dispatchAction(PageBinding.ACTION_DOPOSTBACK)"; } if (string.IsNullOrEmpty(oncommand) == false) { writer.WriteAttribute("oncommand", oncommand); } if (string.IsNullOrEmpty(this.CustomClientId) == false) { writer.WriteAttribute("id", this.CustomClientId); } if (string.IsNullOrEmpty(this.ImageUrl) == false) { writer.WriteAttribute("image", this.ImageUrl); } if (string.IsNullOrEmpty(this.ImageUrlWhenDisabled) == false) { writer.WriteAttribute("image-disabled", this.ImageUrlWhenDisabled); } if (this.Enabled == false) { writer.WriteAttribute("isdisabled", "true"); } this.WriteClientAttributes(writer); writer.Write(HtmlTextWriter.SelfClosingTagEnd); } } } ================================================ FILE: Composite/Core/WebClient/UiControlLib/ComboBox.cs ================================================ using System; using System.Web.UI; using System.Web.UI.WebControls; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; using Composite.Core.WebClient.UiControlLib.Foundation; namespace Composite.Core.WebClient.UiControlLib { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ComboBox : DropDownList { private static readonly string ReservedKey = "___reserved value"; /// <exclude /> public bool SelectionRequired { get; set; } /// <exclude /> public string SelectionRequiredLabel { get; set; } /// <exclude /> protected override HtmlTextWriterTag TagKey { get { return HtmlTextWriterTag.Unknown; } } /// <exclude /> protected override string TagName { get { return "ui:datainputselector"; } } /// <exclude /> protected override void AddAttributesToRender(HtmlTextWriter writer) { writer.AddAttribute("name", this.UniqueID); writer.AddAttribute("callbackid", this.ClientID); if (this.AutoPostBack) { writer.AddAttribute("onselectionchange", "this.dispatchAction(PageBinding.ACTION_DOPOSTBACK)"); } if (this.SelectionRequired) { writer.AddAttribute("required", "true"); string requiredLabel = this.SelectionRequiredLabel; if (string.IsNullOrEmpty(requiredLabel)) requiredLabel = StringResourceSystemFacade.GetString("Composite.Management", "AspNetUiControl.Selector.SelectValueLabel"); writer.AddAttribute("label", requiredLabel); } if(!SelectedValue.IsNullOrEmpty()) { writer.AddAttribute("value", SelectedValue); } this.AddClientAttributes(writer); } /// <exclude /> public override string SelectedValue { get { return base.SelectedValue; } set { if(this.Items.FindByValue(value) == null) { this.Items.Add(new ListItem(ReservedKey, value)); } base.SelectedValue = value; } } /// <exclude /> protected override void RenderContents(HtmlTextWriter writer) { for (int i = 0; i < this.Items.Count; i++) { if (Items[i].Text == ReservedKey) { continue; } string label = StringResourceSystemFacade.ParseString(this.Items[i].Text); int firstNonSpaceSpacePosition = 0; while (firstNonSpaceSpacePosition < label.Length && label.Substring(firstNonSpaceSpacePosition, 1) == " ") firstNonSpaceSpacePosition++; string spacing = new String(Convert.ToChar(160), firstNonSpaceSpacePosition * 2); this.Items[i].Text = string.Concat(spacing, label.Substring(firstNonSpaceSpacePosition)); } ListItemCollection items = this.Items; if (items.Count == 0) { return; } foreach(ListItem item in items) { if (!item.Enabled || item.Text == ReservedKey) { continue; } writer.WriteBeginTag("ui:selection"); writer.WriteAttribute("value", item.Value, true); //if (this.Page != null) //{ // this.Page.ClientScript.RegisterForEventValidation(this.UniqueID, item.Value); //} writer.Write(HtmlTextWriter.SelfClosingTagEnd); } } /// <exclude /> protected override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) { string postedValue = postCollection[postDataKey]; if(!postedValue.IsNullOrEmpty() && this.Items.FindByValue(postedValue) == null) { this.Items.Add(new ListItem(ReservedKey, postedValue)); } return base.LoadPostData(postDataKey, postCollection); } } } ================================================ FILE: Composite/Core/WebClient/UiControlLib/DataInput.cs ================================================ using System.ComponentModel; using System.Web.UI; using System.Web.UI.WebControls; using Castle.Core.Internal; using Composite.Core.WebClient.UiControlLib.Foundation; namespace Composite.Core.WebClient.UiControlLib { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum DataInputType { /// <exclude /> Default, /// <exclude /> Integer, /// <exclude /> Decimal, /// <exclude /> Password, /// <exclude /> ProgrammingIdentifier, /// <exclude /> ProgrammingNamespace, /// <exclude /> ReadOnly } /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class DataInput : TextBox { /// <exclude /> public DataInput() : base() { this.InputType = DataInputType.Default; } /// <exclude /> [Category("Appearance"), DefaultValue(""), Description("The type of data expected in this field")] public virtual DataInputType InputType { get; set; } /// <exclude /> [Category("Appearance"), DefaultValue(""), Description("Language to use for spell check for input field")] public virtual string Language { get; set; } /// <exclude /> [Category("Appearance"), DefaultValue(0), Description("The required minimum length of this field. Default is 0 (no minimum).")] public virtual int MinLength { get; set; } /// <exclude /> protected override HtmlTextWriterTag TagKey { get { return HtmlTextWriterTag.Unknown; } } /// <exclude /> protected override string TagName { get { return "ui:datainput"; } } /// <exclude /> protected override void AddAttributesToRender(HtmlTextWriter writer) { writer.AddAttribute("value", this.Text); writer.AddAttribute("name", this.UniqueID); if (this.MaxLength > 0) { writer.AddAttribute("maxlength", this.MaxLength.ToString()); } if (this.MinLength > 0) { writer.AddAttribute("minlength", this.MinLength.ToString()); } if (this.AutoPostBack) { writer.AddAttribute("callbackid", this.ClientID); writer.AddAttribute("onvaluechange", "this.dispatchAction ( PageBinding.ACTION_DOPOSTBACK )"); } if (!this.Language.IsNullOrEmpty()) { writer.AddAttribute("lang", Language); } if (!Enabled) { writer.AddAttribute("isdisabled", "true"); } if (this.InputType != DataInputType.Default) { switch (this.InputType) { case DataInputType.Integer: writer.AddAttribute("type", "integer"); break; case DataInputType.Decimal: writer.AddAttribute("type", "number"); break; case DataInputType.Password: writer.AddAttribute("password", "true"); break; case DataInputType.ProgrammingIdentifier: writer.AddAttribute("type", "programmingidentifier"); break; case DataInputType.ProgrammingNamespace: writer.AddAttribute("type", "programmingnamespace"); break; case DataInputType.ReadOnly: writer.AddAttribute("readonly", "true"); break; default: break; } } this.AddClientAttributes(writer); } } } ================================================ FILE: Composite/Core/WebClient/UiControlLib/DocumentDirtyEvent.cs ================================================ using System; using System.Web.UI; using Composite.Core.Extensions; using Composite.Core.WebClient.UiControlLib.Foundation; namespace Composite.Core.WebClient.UiControlLib { /// <summary> /// When added to a document, the document will be marked as 'dirty' and the save button will be enabled. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class DocumentDirtyEvent : BaseControl { /// <exclude /> public DocumentDirtyEvent() : base("ui:binding") { } /// <exclude /> protected override void RenderAttributes(HtmlTextWriter writer) { Attributes["onattach"] = "this.dispatchAction(Binding.ACTION_DIRTY);"; base.RenderAttributes(writer); } } } ================================================ FILE: Composite/Core/WebClient/UiControlLib/Feedback.cs ================================================ using System; using System.Web; using Composite.Core.Extensions; namespace Composite.Core.WebClient.UiControlLib { /// <summary> /// Creates a few tags that are responsible for communiation with C1 backend UI's javascript. /// </summary> /// <example> /// <code> /// <aspui:Feedback runat="server" OnCommand="MethodToBeExecutedOnCommand" ResponseStatus="ResponseStatus" /> /// </code> /// /// is an equivalent to the following markup: /// <code> /// <ui:feedbackset id="feedback"> /// <!-- request --> /// <aspui:Generic runat="server" /// ID="btnRequest" /// OnCommand="MethodToBeExecutedOnCommand" /// TagName="ui:request" /// clientid="request" /// callbackid="request" /// value=""/> /// /// <!-- response --> /// <aspui:Generic runat="server" /// ID="tagResponse" /// TagName="ui:response" /// clientid="response" /// status="ResponseStatus"/> /// /// </ui:feedbackset> /// </code> /// </example> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Feedback : Generic { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum Status { /// <exclude /> Empty = 0, /// <exclude /> Success = 1, /// <exclude /> Failure = 2, /// <exclude /> Ping = 3 } private Generic _requestTag; private Generic _responseTag; private Generic _consoleIdField; private Generic _viewIdField; private string _consoleId; /// <exclude /> public Feedback(string emptyParameter) : base("ui:feedbackset") { this.Attributes["clientid"] = "feedback"; _requestTag = new Generic("ui:request"); _requestTag.Attributes["clientid"] = "__REQUEST"; _requestTag.Attributes["callbackid"] = "__REQUEST"; _responseTag = new Generic("ui:response"); _responseTag.Attributes["clientid"] = "__RESPONSE"; _responseTag.Attributes["checksum"] = DateTime.Now.Ticks.ToString(); _consoleIdField = new Generic("input"); _consoleIdField.Attributes["type"] = "hidden"; _consoleIdField.Attributes["clientid"] = "__CONSOLEID"; _consoleIdField.Attributes["name"] = "__CONSOLEID"; _viewIdField = new Generic("input"); _viewIdField.Attributes["type"] = "hidden"; _viewIdField.Attributes["clientid"] = "__VIEWID"; _viewIdField.Attributes["name"] = "__VIEWID"; // Persisting "__CONSOLEID" field value _consoleId = GetConsoleId(); if (!_consoleId.IsNullOrEmpty()) { _consoleIdField.Attributes["value"] = _consoleId; } this.Controls.Add(_requestTag); this.Controls.Add(_responseTag); _requestTag.Controls.Add(_consoleIdField); _requestTag.Controls.Add(_viewIdField); } /// <exclude /> public string OnCommand { set { _requestTag.Attributes["OnCommand"] = value; } } /// <exclude /> public string ResponseStatus { set { _responseTag.Attributes["status"] = value; } } /// <exclude /> public void SetStatus(Status status) { switch (status) { case Status.Empty: _responseTag.Attributes.Remove("status"); break; case Status.Success: ResponseStatus = "success"; break; case Status.Failure: ResponseStatus = "failure"; break; case Status.Ping: ResponseStatus = "ooookay"; break; default: Core.Logging.LoggingService.LogWarning(typeof(Feedback).FullName, "Unexpected status value "); break; } } /// <exclude /> public void SetStatus(bool success) { SetStatus(success ? Status.Success : Status.Failure); } /// <exclude /> public string GetPostedMessage() { return this.Page.IsPostBack ? this.Page.Request.Form["__REQUEST"] : string.Empty; } /// <exclude /> public override bool IsPosted { get { return Page.IsPostBack && Page.Request.Form["__EVENTTARGET"].Replace('$', '_') == _requestTag.Attributes["clientid"].Replace('$', '_'); } } /// <exclude /> protected override void OnPreRender(EventArgs e) { // Setting default status value - "Ping" if (_requestTag.IsPosted && _responseTag.Attributes["status"].IsNullOrEmpty() && GetPostedMessage() == "refresh") { SetStatus(Status.Ping); } // Updating information about console mesages system if (_consoleId != null) { int messageNumber = C1Console.Events.ConsoleMessageQueueFacade.GetLatestMessageNumber(_consoleId); _responseTag.Attributes["messagequeueindex"] = messageNumber.ToString(); } base.OnPreRender(e); } private static string GetConsoleId() { var httpContext = HttpContext.Current; if (httpContext != null && httpContext.Request != null) { var request = httpContext.Request; return request.QueryString["consoleId"] ?? httpContext.Request.Form["__CONSOLEID"]; } return null; } /// <exclude /> public void MarkAsDirty() { this._responseTag.Attributes["dirty"] = "true"; } } } ================================================ FILE: Composite/Core/WebClient/UiControlLib/FieldMessage.cs ================================================  using System; using System.Web.UI; using System.Web.UI.WebControls; using System.Web; using Composite.Core.ResourceSystem; namespace Composite.Core.WebClient.UiControlLib { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class FieldMessage : Label { /// <exclude /> public FieldMessage(string targetName, string text) { this.TargetName = targetName; this.Text = text; } /// <exclude /> public virtual string TargetName { get; set; } /// <exclude /> protected override void Render(HtmlTextWriter writer) { writer.WriteBeginTag("ui:errorset"); writer.WriteAttribute("timestamp", HttpUtility.HtmlAttributeEncode(DateTime.Now.Ticks.ToString())); writer.Write(HtmlTextWriter.TagRightChar); writer.WriteBeginTag("ui:error"); writer.WriteAttribute("text", HttpUtility.HtmlAttributeEncode(StringResourceSystemFacade.ParseString(this.Text))); writer.WriteAttribute("targetname", HttpUtility.HtmlAttributeEncode(this.TargetName)); writer.Write(HtmlTextWriter.SelfClosingTagEnd); writer.WriteEndTag("ui:errorset"); } } } ================================================ FILE: Composite/Core/WebClient/UiControlLib/Foundation/BaseControl.cs ================================================ using System; using System.Web.UI.HtmlControls; using Composite.Core.Extensions; namespace Composite.Core.WebClient.UiControlLib.Foundation { /// <summary> /// A generic control with support for client identifiers. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class BaseControl : HtmlGenericControl { private string _clientID; /// <exclude /> public BaseControl(string tagName) : base(tagName) { } /// <exclude /> protected override void OnInit(EventArgs e) { string clientID = this.Attributes["ClientID"]; if(clientID.IsNullOrEmpty()) { clientID = Attributes["clientid"]; if (clientID.IsNullOrEmpty()) { clientID = null; } } _clientID = clientID; base.OnInit(e); } /// <exclude /> public override string ClientID { get { if(_clientID != null) { return _clientID; } if(this.ID != null) { return base.UniqueID; } return null; } } } } ================================================ FILE: Composite/Core/WebClient/UiControlLib/Foundation/ClientAttributes.cs ================================================ using System.Web.UI.WebControls; using System.Web.UI; namespace Composite.Core.WebClient.UiControlLib.Foundation { /// <exclude /> public static class ClientAttributes { internal static void WriteClientAttributes(this WebControl uiControl, HtmlTextWriter writer) { foreach (string attributeName in uiControl.Attributes.Keys) { string attributeNameLower = attributeName.ToLowerInvariant(); if (attributeNameLower.StartsWith("client_")) { string clientAttributeName = attributeNameLower.Substring("client_".Length); writer.WriteAttribute(clientAttributeName, uiControl.Attributes[attributeName]); } } } internal static void AddClientAttributes(this WebControl uiControl, HtmlTextWriter writer) { foreach (string attributeName in uiControl.Attributes.Keys) { string attributeNameLower = attributeName.ToLowerInvariant(); if (attributeNameLower.StartsWith("client_")) { string clientAttributeName = attributeNameLower.Substring("client_".Length); writer.AddAttribute(clientAttributeName, uiControl.Attributes[attributeName]); } } } /// <exclude /> public static void CopyClientAttributesTo(this UserControl uiControl, WebControl targetControl) { foreach (string attributeName in uiControl.Attributes.Keys) { string attributeNameLower = attributeName.ToLowerInvariant(); if (attributeNameLower.StartsWith("client_")) { targetControl.Attributes[attributeName] = uiControl.Attributes[attributeName]; } } } } } ================================================ FILE: Composite/Core/WebClient/UiControlLib/Generic.cs ================================================ using System; using System.Reflection; using System.Web.UI; using System.Web.UI.HtmlControls; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; namespace Composite.Core.WebClient.UiControlLib { /// <summary> /// To be used for creating stateless tags. Copies all the attributes from markup to the generated tag, /// the "clientid" attribute will be transformed to "id" attribute. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Generic : HtmlGenericControl { private string _callbackid; private string _methodName; private bool? _posted; /// <exclude /> public Generic(string tag) : base(tag) { base.EnableViewState = false; } /// <exclude /> public virtual bool IsPosted { get { Verify.IsNotNull(_posted, "This property isn't awailable until 'PageLoad' event"); return _posted.Value; } } /// <exclude /> protected override void OnLoad(System.EventArgs e) { _posted = false; base.OnLoad(e); if (Attributes["HasCallbackId"] == "true" && Attributes["callbackid"].IsNullOrEmpty()) { Attributes.Remove("HasCallbackId"); Attributes["callbackid"] = this.UniqueID; } _callbackid = this.Attributes["callbackid"] ?? string.Empty; _methodName = Attributes["OnCommand"]; // NOTE: to be removed if(_methodName.IsNullOrEmpty()) { _methodName = Attributes["OnServerClick"]; } if(_callbackid != null && Page.IsPostBack && !Page.Request.Form["__EVENTTARGET"].IsNullOrEmpty() && Page.Request.Form["__EVENTTARGET"].Replace('$', '_') == _callbackid.Replace('$', '_')) { _posted = true; if(_methodName != null) { this.Page.RegisterRequiresRaiseEvent(new PostBackEventHandler(this)); } } } /// <exclude /> protected override void RenderAttributes(HtmlTextWriter writer) { string clientId = Attributes["clientid"]; if(clientId.IsNullOrEmpty() && !ID.IsNullOrEmpty()) { clientId = ID; } if (!clientId.IsNullOrEmpty()) { writer.WriteAttribute("id", clientId); Attributes.Remove("clientid"); } string label = Attributes["label"]; if (!label.IsNullOrEmpty()) { Attributes["label"] = StringResourceSystemFacade.ParseString(label); } Attributes.Remove("OnServerClick"); // Server-side attribute Attributes.Remove("OnCommand"); // Server-side attribute this.Attributes.Render(writer); } /// <exclude /> protected class PostBackEventHandler : IPostBackEventHandler { private Generic _control; /// <exclude /> public PostBackEventHandler(Generic control) { _control = control; } /// <exclude /> public void RaisePostBackEvent(string eventArgument) { string methodName = _control._methodName; Control controlThatHandlesEvent = GetControlThatHandlesEvent(_control); if (controlThatHandlesEvent == null) { Core.Logging.LoggingService.LogError(typeof(Generic).FullName, "Failed to find parent control, that appropriate for event handling".FormatWith(methodName)); return; } Type type = controlThatHandlesEvent.GetType(); MethodInfo methodInfo = null; while(methodInfo == null && type != typeof(object)) { methodInfo = type.GetMethod(methodName); type = type.BaseType; } if(methodInfo == null) { Log.LogError(typeof(Generic).FullName, "Failed to find method '{0}'", methodName); return; } methodInfo.Invoke(controlThatHandlesEvent, new object[0]); } private static Control GetControlThatHandlesEvent(Generic generic) { Control control = generic; do { control = control.Parent; } while (control != null && !(control is UserControl) && !(control is Page)); return control; } } } } ================================================ FILE: Composite/Core/WebClient/UiControlLib/HtmlEncodedPlaceHolder.cs ================================================ using System.IO; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Composite.Core.WebClient.UiControlLib { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class HtmlEncodedPlaceHolder : PlaceHolder { /// <exclude /> protected override void Render(HtmlTextWriter writer) { StringBuilder markupBuilder = new StringBuilder(); StringWriter sw = new StringWriter(markupBuilder); base.Render(new HtmlTextWriter(sw)); writer.Write( HttpUtility.HtmlEncode(markupBuilder.ToString())); } } } ================================================ FILE: Composite/Core/WebClient/UiControlLib/PostBackDialog.cs ================================================ using System; using System.Web; using Composite.Core.Extensions; using Composite.Core.WebClient.UiControlLib.Foundation; namespace Composite.Core.WebClient.UiControlLib { /// <summary> /// Generates a tag like /// <ui:postbackdialog id="uniqueID" callbackid="uniqueCallbackID" label="Hello" tooltip="Hello Master!" handle="Composite.Management.PageSelectorDialog" value="DEFAULT VALUE!" /> /// and persists "value" attribute. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class PostBackDialog : BaseControl { private static readonly string ZipPrefix = "ZIP_"; /// <exclude /> protected const string DefaultSelectorTagName = "ui:postbackdialog"; /// <exclude /> protected const string NullableSelectorTagName = "ui:nullpostbackdialog"; /// <exclude /> public PostBackDialog(string emptyParameter) : base(DefaultSelectorTagName) { } /// <exclude /> protected override void OnInit(EventArgs e) { base.OnInit(e); // Persisting value from postback string formKey = this.Attributes["callbackid"]; if (formKey.IsNullOrEmpty()) { formKey = this.ClientID; } if (Page.IsPostBack && Page.Request.Form["__EVENTTARGET"] == formKey || !Page.Request.Form[formKey].IsNullOrEmpty()) { string postedValue = Page.Request.Form[formKey]; Value = EncodeValue && postedValue.StartsWith(ZipPrefix) ? UrlUtils.UnZipContent(postedValue.Substring(ZipPrefix.Length)) : HttpContext.Current.Server.UrlDecode(postedValue); } } /// <summary> /// Setting to true leads to inserting "ui:nullpostbackdatadialog" tag /// </summary> public bool Nullable { get { return TagName == NullableSelectorTagName; } set { TagName = value ? NullableSelectorTagName : DefaultSelectorTagName; } } /// <exclude /> public string Value { get; set; } /// <exclude /> public string DefaultValue { get; set; } /// <summary> /// When <value>true</value>, the values are encoded in a way it is safe to use them in url's query string /// </summary> public bool EncodeValue { get; set; } /// <exclude /> protected override void RenderAttributes(System.Web.UI.HtmlTextWriter writer) { // added for error balloons to fixitup good Attributes["name"] = ClientID; if(Attributes["callbackid"].IsNullOrEmpty()) { Attributes["callbackid"] = ClientID; Attributes["name"] = ClientID; } if (Value != null) { Attributes["value"] = EncodeValue ? (ZipPrefix + UrlUtils.ZipContent(Value)) : Value; } if (DefaultValue != null) { Attributes["defaultValue"] = EncodeValue ? (ZipPrefix + UrlUtils.ZipContent(DefaultValue)) : DefaultValue; } base.RenderAttributes(writer); } } } ================================================ FILE: Composite/Core/WebClient/UiControlLib/Selector.cs ================================================ using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Composite.Core.WebClient.UiControlLib.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Core.WebClient.UiControlLib { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Selector : DropDownList { /// <exclude /> public Selector() : base() { bool isInternetExplorer = HttpContext.Current.Request.UserAgent.Contains("MSIE"); this.SimpleSelectorMode = false; // isInternetExplorer; } /// <exclude /> public bool SelectionRequired { get; set; } /// <exclude /> public string SelectionRequiredLabel { get; set; } /// <exclude /> public bool SimpleSelectorMode { get; set; } /// <exclude /> public bool IsDisabled { get; set; } /// <exclude /> protected override HtmlTextWriterTag TagKey { get { return HtmlTextWriterTag.Unknown; } } /// <exclude /> protected override string TagName { get { return this.SimpleSelectorMode ? "ui:simpleselector" : "ui:selector"; } } /// <exclude /> protected override void AddAttributesToRender(HtmlTextWriter writer) { writer.AddAttribute("name", this.UniqueID); writer.AddAttribute("callbackid", this.ClientID); if (this.AutoPostBack) { writer.AddAttribute("onchange", "this.dispatchAction(PageBinding.ACTION_DOPOSTBACK)"); } if (this.SelectionRequired) { writer.AddAttribute("required", "true"); string requiredLabel = this.SelectionRequiredLabel; if (string.IsNullOrEmpty(requiredLabel)) requiredLabel = StringResourceSystemFacade.GetString("Composite.Management", "AspNetUiControl.Selector.SelectValueLabel"); writer.AddAttribute("label", requiredLabel); } if (this.IsDisabled) { writer.AddAttribute("isdisabled", "true"); } this.AddClientAttributes(writer); } /// <exclude /> protected override void RenderContents(HtmlTextWriter writer) { for (int i = 0; i < this.Items.Count; i++) { string label = StringResourceSystemFacade.ParseString(this.Items[i].Text); int firstNonSpaceSpacePosition = 0; while (firstNonSpaceSpacePosition < label.Length && label.Substring(firstNonSpaceSpacePosition, 1) == " ") firstNonSpaceSpacePosition++; string spacing = new String(Convert.ToChar(160), firstNonSpaceSpacePosition * 2); this.Items[i].Text = string.Concat(spacing, label.Substring(firstNonSpaceSpacePosition)); } if (this.SimpleSelectorMode == false) { ListItemCollection items = this.Items; int count = items.Count; if (count > 0) { bool flag = false; for (int i = 0; i < count; i++) { ListItem item = items[i]; if (item.Enabled) { writer.WriteBeginTag("ui:selection"); if (item.Selected && this.SelectionRequired == false) { if (flag) { this.VerifyMultiSelect(); } flag = true; writer.WriteAttribute("selected", "true"); } writer.WriteAttribute("label", item.Text, true); writer.WriteAttribute("value", item.Value, true); writer.WriteAttribute("tooltip", item.Text, true); if (this.Page != null) { this.Page.ClientScript.RegisterForEventValidation(this.UniqueID, item.Value); } writer.Write(HtmlTextWriter.SelfClosingTagEnd); } } } } else { base.RenderContents(writer); } } /// <exclude /> public override void RenderBeginTag(HtmlTextWriter writer) { base.RenderBeginTag(writer); if (this.SimpleSelectorMode) { writer.WriteFullBeginTag("select"); } } /// <exclude /> public override void RenderEndTag(HtmlTextWriter writer) { if (this.SimpleSelectorMode) { writer.WriteEndTag("select"); } base.RenderEndTag(writer); } } } ================================================ FILE: Composite/Core/WebClient/UiControlLib/TextArea.cs ================================================ using System; using System.Web.UI; using Composite.Core.Extensions; using Composite.Core.WebClient.UiControlLib.Foundation; namespace Composite.Core.WebClient.UiControlLib { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class TextArea : BaseControl { /// <exclude /> public TextArea(string tagName): base("ui:textbox") { // TODO: refactor } /// <exclude /> protected override void OnInit(EventArgs e) { base.OnInit(e); // Loading postback data if (Page.IsPostBack) { Text = this.Page.Request.Form[ClientID]; } } /// <exclude /> protected override void RenderChildren(HtmlTextWriter writer) { writer.WriteBeginTag("textarea"); writer.Write((char)'>'); if(!Text.IsNullOrEmpty()) { writer.WriteEncodedText(Text); } writer.WriteEndTag("textarea"); } /// <exclude /> protected override void RenderAttributes(HtmlTextWriter writer) { Attributes["name"] = ClientID; base.RenderAttributes(writer); } /// <exclude /> public string Text { get; set; } } } ================================================ FILE: Composite/Core/WebClient/UiControlLib/TextBox.cs ================================================ using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Composite.Core.WebClient.UiControlLib { /// <summary> /// Fixes a basic 'System.Web.UI.WebControls.TextBox' control, so it renders correctly in 'MultiLine' mode /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class TextBox : System.Web.UI.WebControls.TextBox { /// <exclude /> protected override void Render(HtmlTextWriter writer) { this.RenderBeginTag(writer); if (this.TextMode == TextBoxMode.MultiLine) { HttpUtility.HtmlEncode(/* Environment.NewLine + */this.Text, writer); } this.RenderEndTag(writer); } } } ================================================ FILE: Composite/Core/WebClient/UiControlLib/ToolbarButton.cs ================================================ using System.ComponentModel; using System.Web.UI; using System.Web.UI.WebControls; using Composite.Core.WebClient.UiControlLib.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Core.WebClient.UiControlLib { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ToolbarButton : LinkButton { /// <exclude /> [Category("Behavior"), DefaultValue(""), Description("The id as the UI client should see")] public virtual string CustomClientId { get; set; } /// <exclude /> [Category("Appearance"), DefaultValue(""), Description("Image to show on the button")] public virtual string ImageUrl { get; set; } /// <exclude /> [Category("Appearance"), DefaultValue(""), Description("Image to show on the button when it is disabled")] public virtual string ImageUrlWhenDisabled { get; set; } /// <exclude /> [Category("Behavior"), DefaultValue(""), Description("ID of ui:broadcaster to observe")] public virtual string ObservesClientBroadcaster { get; set; } /// <exclude /> protected override void Render(HtmlTextWriter writer) { writer.WriteBeginTag("ui:toolbarbutton"); writer.WriteAttribute("label", StringResourceSystemFacade.ParseString(this.Text)); writer.WriteAttribute("callbackid", this.ClientID); /* * PageBinding.ACTION_DOPOSTBACK emitted by default when callbackid is specified. * Note that this uncomment has disabled support for further clientside oncommand actions... * string clientScripting = string.Format("this.dispatchAction(PageBinding.ACTION_DOPOSTBACK);{0}", this.OnClientClick); writer.WriteAttribute("oncommand", clientScripting); */ if (string.IsNullOrEmpty(this.CustomClientId) == false) { writer.WriteAttribute("id", this.CustomClientId); } else { writer.WriteAttribute("id", this.ClientID); } if (string.IsNullOrEmpty(this.ObservesClientBroadcaster) == false) { writer.WriteAttribute("observes", this.ObservesClientBroadcaster); } if (string.IsNullOrEmpty(this.ImageUrl) == false) { writer.WriteAttribute("image", this.ImageUrl); } if (string.IsNullOrEmpty(this.ImageUrlWhenDisabled) == false) { writer.WriteAttribute("image-disabled", this.ImageUrlWhenDisabled); } if (this.Enabled == false) { writer.WriteAttribute("isdisabled", "true"); } this.WriteClientAttributes(writer); writer.Write( HtmlTextWriter.SelfClosingTagEnd ); } } } ================================================ FILE: Composite/Core/WebClient/UiControlLib/TreeNode.cs ================================================ using System; using System.ComponentModel; using System.Web.UI; using System.Web.UI.WebControls; using Composite.Core.WebClient.UiControlLib.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Core.WebClient.UiControlLib { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class TreeNode : LinkButton { /// <exclude /> [Category("Appearance"), DefaultValue(""), Description("Image to show as tree node bullet")] public virtual string ImageUrl { get { return ViewState["imageUrl"] as string; } set { ViewState["imageUrl"] = value; } } /// <exclude /> public override void Focus() { this.Focused = true; } /// <exclude /> public virtual bool Focused { get; set; } /// <exclude /> protected override void Render(HtmlTextWriter writer) { writer.WriteBeginTag("ui:treenode"); writer.WriteAttribute("label", StringResourceSystemFacade.ParseString(this.Text)); writer.WriteAttribute("id", this.ClientID); // bool checksumAttrRequired = false; if(!Focused) { writer.WriteAttribute("callbackid", this.ClientID); } if (!string.IsNullOrEmpty(this.ImageUrl)) { writer.WriteAttribute("image", this.ImageUrl); } if(this.Focused) { // checksumAttrRequired = true; writer.WriteAttribute("focused", "true"); } //if(checksumAttrRequired) //{ // writer.WriteAttribute("checksum", DateTime.Now.Ticks.ToString()); //} //if (this.Focused) //{ // writer.WriteAttribute("focused", "true"); // if (string.IsNullOrEmpty(this.OnClientClick) == false) // { // writer.WriteAttribute("onbindingfocus", this.OnClientClick); // } //} //else //{ // string clientScripting = string.Format("this.dispatchAction(PageBinding.ACTION_DOPOSTBACK);{0}", this.OnClientClick); // writer.WriteAttribute("onbindingfocus", clientScripting); //} this.WriteClientAttributes(writer); writer.Write( HtmlTextWriter.SelfClosingTagEnd ); } } } ================================================ FILE: Composite/Core/WebClient/UrlString.cs ================================================ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Web; using Composite.Core.Extensions; namespace Composite.Core.WebClient { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Use Composite.UrlBuilder")] public sealed class UrlString { private static readonly string IncorrectValueParam = "__***IncorrectValue***__"; private string _pathInfo; private string _filePath; private List<KeyValuePair<string, string>> _queryParameters; /// <exclude /> public UrlString(string url) { _queryParameters = new List<KeyValuePair<string, string>>(); int questionMarkIndex = url.IndexOf("?"); if (questionMarkIndex < 0) { ExtractPathInfo(url, out _filePath, out _pathInfo); return; } ExtractPathInfo(url.Substring(0, questionMarkIndex), out _filePath, out _pathInfo); if (questionMarkIndex + 1 == url.Length) { return; } string queryParamStr = url.Substring(questionMarkIndex + 1, url.Length - questionMarkIndex - 1); foreach (string queryParam in queryParamStr.Split(new[] { "&", "&" }, StringSplitOptions.RemoveEmptyEntries)) { string[] parts = queryParam.Split(new[] { '=' }); bool badUrl = parts.Length != 2; if (!badUrl) { string encodedKey = parts[0]; string encodedValue = parts[1]; string key = HttpUtility.UrlDecode(encodedKey); string value = HttpUtility.UrlDecode(encodedValue); badUrl = HttpUtility.UrlEncode(key) != encodedKey || HttpUtility.UrlEncode(value) != encodedValue; if (!badUrl) { _queryParameters.Add(new KeyValuePair<string, string>(key, value)); continue; } } _queryParameters.Add(new KeyValuePair<string, string>(queryParam, IncorrectValueParam)); } } private void ExtractPathInfo(string relativePath, out string filePath, out string pathInfo) { int aspxExtOffset = relativePath.IndexOf(".aspx"); if (aspxExtOffset < 0 || aspxExtOffset == relativePath.Length - 5) { pathInfo = null; filePath = relativePath; return; } filePath = relativePath.Substring(0, aspxExtOffset + 5); pathInfo = relativePath.Substring(aspxExtOffset + 5); } /// <exclude /> public override string ToString() { // NOTE: StringBuilder shouldn't be used - it is to slow string queryString = QueryString; string result = _filePath; if (_pathInfo != null) { result += _pathInfo; } if (queryString != string.Empty) { result += "?" + queryString; } return result; // _filePath + _pathInfo + "?" + queryString } /// <exclude /> public void AddQueryParameters(NameValueCollection parameters) { foreach (string key in parameters) { this[key] = parameters[key]; } } /// <exclude /> public NameValueCollection GetQueryParameters() { var result = new NameValueCollection(); foreach (KeyValuePair<string, string> pair in _queryParameters) { result.Add(pair.Key, pair.Value); } return result; } /// <exclude /> public string this[string key] { get { string value = _queryParameters.Where(pair => pair.Key == key).Select(pair => pair.Value).FirstOrDefault(); return value ?? string.Empty; } set { for (int i = 0; i < _queryParameters.Count; i++) { if (_queryParameters[i].Key == key) { if (value == null) { _queryParameters.RemoveAt(i); } else { _queryParameters[i] = new KeyValuePair<string, string>(key, value); } return; } } if (value != null) { _queryParameters.Add(new KeyValuePair<string, string>(key, value)); } } } /// <exclude /> public string PathInfo { get { return _pathInfo ?? string.Empty; } set { _pathInfo = value; } } /// <exclude /> public string FilePath { get { return _filePath; } set { Verify.ArgumentNotNull(value, "value"); _filePath = value; } } /// <exclude /> public string ServerUrl { get { if (_filePath.IsNullOrEmpty()) { return string.Empty; } int index1 = _filePath.IndexOf("://"); if (index1 <= 0 || _filePath.Length == index1 + 4) { return string.Empty; } int index2 = _filePath.IndexOf("/", index1 + 3); if (index2 < 0) { return string.Empty; } return _filePath.Substring(0, index2 + 1); } set { if (!ServerUrl.IsNullOrEmpty()) { throw new NotImplementedException(); } if (value.IsNullOrEmpty()) return; Verify.IsTrue(value.EndsWith("/"), "Wrong server url string"); if (_filePath.StartsWith("/")) _filePath = _filePath.Substring(1); _filePath = value + _filePath; } } /// <exclude /> public string QueryString { get { if (_queryParameters.Count == 0) { return string.Empty; } var sb = new StringBuilder(); for (int i = 0; i < _queryParameters.Count; i++) { if (i != 0) { sb.Append("&"); } if (_queryParameters[i].Value == IncorrectValueParam) { sb.Append(_queryParameters[i].Key); } else { sb.Append(HttpUtility.UrlEncode(_queryParameters[i].Key)); sb.Append('='); sb.Append(HttpUtility.UrlEncode(_queryParameters[i].Value)); } } return sb.ToString(); } } } } ================================================ FILE: Composite/Core/WebClient/UrlUtils.cs ================================================ using System; using System.IO; using System.IO.Compression; using System.Security.Cryptography; using System.Text; using System.Web; using System.Web.Hosting; using System.Collections.Generic; using Composite.Core.Collections.Generic; using Composite.Core.Extensions; using Composite.Core.WebClient.State; using Composite.Data; namespace Composite.Core.WebClient { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class UrlUtils { private const char UrlEncode_EscapeCharacter = '$'; private const char UrlEncode_SpaceReplacement = '-'; private const char UrlEncode_SpaceReplacementReplacement = '_'; private static readonly string _adminFolderName = "Composite"; private static readonly string _renderersFolderName = "Renderers"; private static readonly string _applicationVirtualPath; private static readonly string[] UrlStartMarkers = { "\"", "\'", "'", """ }; private static readonly string SessionUrlPrefix = "Session_"; /// <exclude /> public static string PublicRootPath => _applicationVirtualPath; /// <exclude /> public static string AdminRootPath => $"{_applicationVirtualPath}/{_adminFolderName}"; /// <exclude /> public static string RenderersRootPath => $"{_applicationVirtualPath}/{_renderersFolderName}"; /// <exclude /> internal static string AdminFolderName => _adminFolderName; static UrlUtils() { string appPath = HostingEnvironment.ApplicationVirtualPath ?? ""; if (appPath.EndsWith("/") || appPath.EndsWith(@"\")) { appPath = appPath.Remove(appPath.Length - 1, 1); } _applicationVirtualPath = appPath; } /// <exclude /> public static string ResolveAdminUrl(string adminRelativePath) { if (adminRelativePath == null) throw new ArgumentNullException(nameof(adminRelativePath)); if (adminRelativePath.IndexOf('~') > -1 || adminRelativePath.StartsWith("/") ) { throw new ArgumentException("The relative URL may not be rooted or contain '~'"); } string[] split = adminRelativePath.Split('?'); string checkForBackSlashes = split[0]; if (checkForBackSlashes.Contains(@"\")) { Log.LogWarning("ResolveAdminUrl", $@"The url '{checkForBackSlashes}' contains '\' which is not allowed."); } return $"{_applicationVirtualPath}/{_adminFolderName}/{adminRelativePath}"; } /// <exclude /> public static string ResolvePublicUrl(string publicRelativePath) { if (publicRelativePath == null) throw new ArgumentNullException(nameof(publicRelativePath)); if (publicRelativePath.StartsWith("/")) { throw new ArgumentException("The relative URL may not be rooted. It should be either relative to root or start with ~/"); } if (publicRelativePath.StartsWith("~/")) { publicRelativePath = publicRelativePath.Remove(0, 2); } return $"{_applicationVirtualPath}/{publicRelativePath}"; } /// <summary> /// Determines whether the current request is administration console request. /// (Requests to [/virtual path]/Composite/*) /// </summary> internal static bool IsAdminConsoleRequest(HttpContext httpContext) { string relativeUrl = httpContext.Request.Path; return IsAdminConsoleRequest(relativeUrl); } /// <summary> /// Determines whether the current request is a renderer request. /// (Requests to [/virtual path]/Composite/*) /// </summary> internal static bool IsRendererRequest(HttpContext httpContext) { string requestPath = httpContext.Request.Path; return string.Compare(requestPath, RenderersRootPath, StringComparison.OrdinalIgnoreCase) == 0 || requestPath.StartsWith(RenderersRootPath + "/", StringComparison.OrdinalIgnoreCase); } /// <summary> /// Determines whether the current request is administration console request. /// (Requests to [/virtual path]/Composite/*) /// </summary> public static bool IsAdminConsoleRequest(string requestPath) { return string.Compare(requestPath, UrlUtils.AdminRootPath, StringComparison.OrdinalIgnoreCase) == 0 || requestPath.StartsWith(UrlUtils.AdminRootPath + "/", StringComparison.OrdinalIgnoreCase); } /// <exclude /> public static string Combine( string path1, string path2 ) { if (string.IsNullOrEmpty(path1)) return path2; if (string.IsNullOrEmpty(path2)) return path1; bool path1EndsWithSlash = path1.EndsWith("/"); bool path2StartsWithSlash = path2.StartsWith("/"); if (path1EndsWithSlash != path2StartsWithSlash) { return path1 + path2; } if (path1EndsWithSlash) { return path1 + path2.Substring(1); } return path1 + "/" + path2; } internal class UrlMatch { public int Index; public string Value; } /// <summary> /// Finds all the urls that start with <paramref name="urlPrefix"/>. /// We assume that each url ends before one of the following strings: /// double quote, single quote, or ' which is single quote mark (') encoded in xml attribute /// </summary> /// <param name="html">The html content.</param> /// <param name="urlPrefix">The url prefix</param> /// <returns>List of urls, sorted by the order they appear</returns> internal static List<UrlMatch> FindUrlsInHtml(string html, string urlPrefix) { var result = new List<UrlMatch>(); int startIndex = 0; while (true) { int urlOffset = html.IndexOf(urlPrefix, startIndex, StringComparison.OrdinalIgnoreCase); if (urlOffset < 5) break; int prefixEndOffset = urlOffset + urlPrefix.Length; int endOffset = -1; char lastQuoteSymbol = html[urlOffset - 1]; // If starts with a quote symbol- should end with the same quote symbol if (lastQuoteSymbol == '\'' || lastQuoteSymbol == '\"') { endOffset = html.IndexOf(lastQuoteSymbol, prefixEndOffset); } else if (lastQuoteSymbol == ';' && urlOffset > 5) { string fiveCharsPrefix = html.Substring(urlOffset - 5, 5); if (fiveCharsPrefix == """ || fiveCharsPrefix == "'") { endOffset = html.IndexOf(fiveCharsPrefix, prefixEndOffset, StringComparison.Ordinal); } } // Skipping match if the quotes aren't defined if(endOffset < 0) { startIndex = prefixEndOffset; continue; } // Skipping html anchors int hashSignIndex = html.IndexOf('#', prefixEndOffset, endOffset - prefixEndOffset); if (hashSignIndex > 0) { endOffset = hashSignIndex; } result.Add(new UrlMatch { Index = urlOffset, Value = html.Substring(urlOffset, endOffset - urlOffset) }); startIndex = endOffset; } return result; } internal static string ReplaceUrlPrefix(string html, string oldPrefix, string newPrefix) { foreach (string urlStartMarker in UrlStartMarkers) { html = html.Replace(urlStartMarker + oldPrefix, urlStartMarker + newPrefix); } return html; } /// <exclude /> public static string ZipContent(string text) { if (text.IsNullOrEmpty()) return text; byte[] bytes = Encoding.UTF8.GetBytes(text); byte[] newBytes; using (var compressStream = new MemoryStream()) using (var compressor = new DeflateStream(compressStream, CompressionMode.Compress)) { compressor.Write(bytes, 0, bytes.Length); compressor.Close(); newBytes = compressStream.ToArray(); } string base64 = Convert.ToBase64String(newBytes); if (base64.Length <= 512) { string urlFriendlyBase64 = base64.Replace("+", "_").Replace("/", ".").Replace("=", "-"); return urlFriendlyBase64; } Guid stateId = GetMD5Hash(bytes); using (new DataConnection()) { SessionStateManager.DefaultProvider.SetState(stateId, text, DateTime.Now.AddHours(1.0)); } return SessionUrlPrefix + stateId; } private static Guid GetMD5Hash(byte[] bytes) { using (MD5 md5 = MD5.Create()) { return new Guid(md5.ComputeHash(bytes)); } } /// <exclude /> public static string UnZipContent(string zippedContent) { if (zippedContent.IsNullOrEmpty()) return zippedContent; if (zippedContent.StartsWith(SessionUrlPrefix)) { Guid stateId = Guid.Parse(zippedContent.Substring(SessionUrlPrefix.Length)); using (new DataConnection()) { string urlFromSession; bool succeed = SessionStateManager.DefaultProvider.TryGetState(stateId, out urlFromSession); Verify.That(succeed, "Failed to extract a url part from session"); return urlFromSession; } } string base64 = zippedContent.Replace("_", "+").Replace(".", "/").Replace("-", "="); byte[] bytes = Convert.FromBase64String(base64); using (var ms = new MemoryStream(bytes)) using (var result = new MemoryStream()) using (var deflateStream = new DeflateStream(ms, CompressionMode.Decompress)) { deflateStream.CopyTo(result); deflateStream.Close(); return Encoding.UTF8.GetString(result.ToArray()); } } /// <exclude /> public static string CompressGuid(Guid guid) { return Convert.ToBase64String(guid.ToByteArray()) .Substring(0, 22) .Replace('+', '-') .Replace('/', '_'); } /// <exclude /> public static bool TryExpandGuid(string urlPart, out Guid guid) { if (urlPart == null || urlPart.Length != 22 || urlPart.Contains("/") || urlPart.Contains("+")) { guid = Guid.Empty; return false; } string base64 = urlPart .Replace('_', '/') .Replace('-', '+') + "=="; try { var bytes = Convert.FromBase64String(base64); guid = new Guid(bytes); return true; } catch { guid = Guid.Empty; return false; } } /// <exclude /> public static string EncodeUrlInvalidCharacters(string value) { var symbolsToEncode = new Hashset<char>(new[] { '<', '>', '*', '%', '&', '\\', '?', '/' }); symbolsToEncode.Add(UrlEncode_EscapeCharacter); symbolsToEncode.Add(UrlEncode_SpaceReplacementReplacement); var sb = new StringBuilder(value.Length); foreach (var ch in value) { if (ch == UrlEncode_SpaceReplacement) { sb.Append(UrlEncode_SpaceReplacementReplacement); continue; } if (ch == ' ') { sb.Append(UrlEncode_SpaceReplacement); continue; } if (!symbolsToEncode.Contains(ch)) { sb.Append(ch); continue; } int code = (int)ch; Verify.That(code <= 256, "1 byte ASCII code expected"); sb.Append(UrlEncode_EscapeCharacter).Append(code.ToString("X2")); } return sb.ToString(); } /// <exclude /> public static string DecodeUrlInvalidCharacters(string value) { var sb = new StringBuilder(value.Length); for (int position = 0; position < value.Length; position++) { var ch = value[position]; if (ch == UrlEncode_SpaceReplacement) { sb.Append(' '); continue; } if (ch == UrlEncode_SpaceReplacementReplacement) { sb.Append(UrlEncode_SpaceReplacement); continue; } if (ch == UrlEncode_EscapeCharacter && position + 2 < value.Length) { var hexCode = value.Substring(position + 1, 2).ToLowerInvariant(); const string hexadecimalDigits = "0123456789abcdef"; int firstDigit = hexadecimalDigits.IndexOf(hexCode[0]); int secondDigit = hexadecimalDigits.IndexOf(hexCode[1]); if (firstDigit > -1 && secondDigit > -1) { sb.Append((char) ((firstDigit << 4) + secondDigit)); position += 2; continue; } } sb.Append(ch); } return sb.ToString(); } } } ================================================ FILE: Composite/Core/WebClient/XhtmlPage.cs ================================================ using System.IO; using System.Text.RegularExpressions; using System.Web.UI; namespace Composite.Core.WebClient { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class XhtmlPage : Page { /// <exclude /> protected override void Render(HtmlTextWriter writer) { Regex xmlScriptRegex = new Regex(@"(<script\stype=""text/javascript"">)(\s*<!--)((?:.|\n)*?)(\s*-->\s*)(</script>)"); string xmlScriptCDATAWrapper = "$1\n// <![CDATA[$3 // ]]>\n$5"; StringWriter sw = new StringWriter(); base.Render(new HtmlTextWriter(sw)); string html = sw.ToString(); html = xmlScriptRegex.Replace(html, xmlScriptCDATAWrapper); writer.Write(html); } } } ================================================ FILE: Composite/Core/WebClient/XsltServices.cs ================================================ using System; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; using System.Xml.Xsl; using Composite.Core.IO; using Composite.Core.Xml; namespace Composite.Core.WebClient { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class XsltServices { private static Dictionary<string, XslCompiledTransform> _xsltLookup = new Dictionary<string, XslCompiledTransform>(); private static Dictionary<string, DateTime> _xsltFileTimestamps = new Dictionary<string, DateTime>(); private static object _lock = new object(); /// <exclude /> public static XslCompiledTransform GetCompiledXsltTransform(string stylesheetPath) { lock (_lock) { DateTime lastXsltFileWrite = C1File.GetLastWriteTime(stylesheetPath); bool compiledVersionExists = _xsltLookup.ContainsKey(stylesheetPath); bool reloadFresh = (DateTime.Now - lastXsltFileWrite).TotalMinutes < 30; if (compiledVersionExists == false || lastXsltFileWrite > _xsltFileTimestamps[stylesheetPath] || reloadFresh) { XslCompiledTransform xslt = new XslCompiledTransform(); using (XmlReader reader = XmlReaderUtils.Create(stylesheetPath)) { xslt.Load(reader); } if (compiledVersionExists) { _xsltLookup.Remove(stylesheetPath); _xsltFileTimestamps.Remove(stylesheetPath); } _xsltLookup.Add(stylesheetPath, xslt); _xsltFileTimestamps.Add(stylesheetPath, lastXsltFileWrite); } } return _xsltLookup[stylesheetPath]; } /// <exclude /> public static XDocument XslTransform(this XDocument sourceDocument, string xsltFilePath) { XDocument outputDocument = new XDocument(); XslCompiledTransform xslt = XsltServices.GetCompiledXsltTransform(xsltFilePath); using (XmlWriter writer = outputDocument.CreateWriter()) { using (XmlReader reader = sourceDocument.CreateReader()) { xslt.Transform(reader, writer); } } return outputDocument; } } } ================================================ FILE: Composite/Core/Xml/LimitedDepthXmlWriter.cs ================================================ using System; using System.Xml; namespace Composite.Core.Xml { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class LimitedDepthXmlWriter : XmlWriter { private readonly XmlWriter _innerWriter; private readonly int _maxDepth; private int _depth; /// <exclude /> public LimitedDepthXmlWriter(XmlWriter innerWriter): this(innerWriter, 100) { } /// <exclude /> public LimitedDepthXmlWriter(XmlWriter innerWriter, int maxDepth) { _maxDepth = maxDepth; _innerWriter = innerWriter; } /// <exclude /> public override void Close() { _innerWriter.Close(); } /// <exclude /> public override void Flush() { _innerWriter.Flush(); } /// <exclude /> public override string LookupPrefix(string ns) { return _innerWriter.LookupPrefix(ns); } /// <exclude /> public override void WriteBase64(byte[] buffer, int index, int count) { _innerWriter.WriteBase64(buffer, index, count); } /// <exclude /> public override void WriteCData(string text) { _innerWriter.WriteCData(text); } /// <exclude /> public override void WriteCharEntity(char ch) { _innerWriter.WriteCharEntity(ch); } /// <exclude /> public override void WriteChars(char[] buffer, int index, int count) { _innerWriter.WriteChars(buffer, index, count); } /// <exclude /> public override void WriteComment(string text) { _innerWriter.WriteComment(text); } /// <exclude /> public override void WriteDocType(string name, string pubid, string sysid, string subset) { _innerWriter.WriteDocType(name, pubid, sysid, subset); } /// <exclude /> public override void WriteEndAttribute() { _innerWriter.WriteEndAttribute(); } /// <exclude /> public override void WriteEndDocument() { _innerWriter.WriteEndDocument(); } /// <exclude /> public override void WriteEndElement() { _depth--; _innerWriter.WriteEndElement(); } /// <exclude /> public override void WriteEntityRef(string name) { _innerWriter.WriteEntityRef(name); } /// <exclude /> public override void WriteFullEndElement() { _innerWriter.WriteFullEndElement(); } /// <exclude /> public override void WriteProcessingInstruction(string name, string text) { _innerWriter.WriteProcessingInstruction(name, text); } /// <exclude /> public override void WriteRaw(string data) { _innerWriter.WriteRaw(data); } /// <exclude /> public override void WriteRaw(char[] buffer, int index, int count) { _innerWriter.WriteRaw(buffer, index, count); } /// <exclude /> public override void WriteStartAttribute(string prefix, string localName, string ns) { _innerWriter.WriteStartAttribute(prefix, localName, ns); } /// <exclude /> public override void WriteStartDocument(bool standalone) { _innerWriter.WriteStartDocument(standalone); } /// <exclude /> public override void WriteStartDocument() { _innerWriter.WriteStartDocument(); } /// <exclude /> public override void WriteStartElement(string prefix, string localName, string ns) { if (_depth++ > _maxDepth) ThrowException(); _innerWriter.WriteStartElement(prefix, localName, ns); } /// <exclude /> public override WriteState WriteState { get { return _innerWriter.WriteState; } } /// <exclude /> public override void WriteString(string text) { _innerWriter.WriteString(text); } /// <exclude /> public override void WriteSurrogateCharEntity(char lowChar, char highChar) { _innerWriter.WriteSurrogateCharEntity(lowChar, highChar); } /// <exclude /> public override void WriteWhitespace(string ws) { _innerWriter.WriteWhitespace(ws); } private void ThrowException() { throw new InvalidOperationException(string.Format("Result xml has more the {0} nested tags. It is possible that xslt transformation contains an endless recursive call.", _maxDepth)); } } } ================================================ FILE: Composite/Core/Xml/Namespaces.cs ================================================ using System.Collections.Generic; using System.Xml.Linq; namespace Composite.Core.Xml { /// <summary> /// Commonly used XML namespaces /// </summary> public static class Namespaces { private static readonly Dictionary<XNamespace, string> _canonicalPrefixes = new Dictionary<XNamespace, string>(); static Namespaces() { Namespaces.BindingForms10 = Composite.C1Console.Forms.Foundation.FormTreeCompiler.CompilerGlobals.RootNamespaceURI; Namespaces.BindingFormsStdUiControls10 = "http://www.composite.net/ns/management/bindingforms/std.ui.controls.lib/1.0"; Namespaces.BindingFormsStdFuncLib10 = "http://www.composite.net/ns/management/bindingforms/std.function.lib/1.0"; Namespaces.Function10 = "http://www.composite.net/ns/function/1.0"; Namespaces.Rendering10 = "http://www.composite.net/ns/rendering/1.0"; Namespaces.Localization10 = "http://www.composite.net/ns/localization/1.0"; Namespaces.DynamicData10 = "http://www.composite.net/ns/dynamicdata/1.0"; Namespaces.AspNetControls = "http://www.composite.net/ns/asp.net/controls"; Namespaces.Data = "http://www.composite.net/ns/data"; Namespaces.XmlNs = "http://www.w3.org/2000/xmlns/"; Namespaces.Xhtml = "http://www.w3.org/1999/xhtml"; Namespaces.Svg = "http://www.w3.org/2000/svg"; Namespaces.Xsl = "http://www.w3.org/1999/XSL/Transform"; Namespaces.Xsi = "http://www.w3.org/2001/XMLSchema-instance"; Namespaces.Xsd = "http://www.w3.org/2001/XMLSchema"; Namespaces.Components = "http://www.composite.net/ns/components/1.0"; _canonicalPrefixes.Add(Namespaces.Function10, "f"); _canonicalPrefixes.Add(Namespaces.Svg, "svg"); _canonicalPrefixes.Add(Namespaces.Rendering10, "rendering"); _canonicalPrefixes.Add(Namespaces.Xsl, "xsl"); _canonicalPrefixes.Add(Namespaces.AspNetControls, "asp"); } /// <summary> /// Namespace for handling forms in the C1 Console: http://www.composite.net/ns/management/bindingforms/1.0 /// </summary> public static XNamespace BindingForms10 { get; private set; } /// <summary> /// Namespace for handling forms in the C1 Console: http://www.composite.net/ns/management/bindingforms/std.ui.controls.lib/1.0 /// </summary> public static XNamespace BindingFormsStdUiControls10 { get; private set; } /// <summary> /// Namespace for handling forms in the C1 Console: http://www.composite.net/ns/management/bindingforms/std.function.lib/1.0 /// </summary> public static XNamespace BindingFormsStdFuncLib10 { get; private set; } /// <summary> /// Namespace for C1 Functions: http://www.composite.net/ns/function/1.0 /// </summary> public static XNamespace Function10 { get; private set; } /// <summary> /// Namespace for rendering page title, description and content: http://www.composite.net/ns/rendering/1.0 /// </summary> public static XNamespace Rendering10 { get; private set; } /// <summary> /// Namespace for getting localized strings or content: http://www.composite.net/ns/localization/1.0 /// </summary> public static XNamespace Localization10 { get; private set; } /// <summary> /// Namespace for ASP.NET Web Forms in C1 CMS pages: http://www.composite.net/ns/asp.net/controls /// </summary> public static XNamespace AspNetControls { get; private set; } /// <summary> /// Namespace for refering to data types: http://www.composite.net/ns/data /// </summary> public static XNamespace Data { get; private set; } /// <summary> /// Namespace /// </summary> public static XNamespace DynamicData10 { get; private set; } /// <summary> /// Namespace /// </summary> public static XNamespace XmlNs { get; private set; } /// <summary> /// Namespace for XHTML documents in C1 CMS: http://www.w3.org/1999/xhtml /// </summary> public static XNamespace Xhtml { get; private set; } /// <summary> /// Namespace /// </summary> public static XNamespace Svg { get; private set; } /// <summary> /// Namespace /// </summary> public static XNamespace Xsl { get; private set; } /// <summary> /// Namespace /// </summary> public static XNamespace Xsi { get; private set; } /// <summary> /// Namespace /// </summary> public static XNamespace Xsd { get; private set; } /// <summary> /// Namespace /// </summary> public static XNamespace Components { get; private set; } /// <summary> /// If known returns a canonical prefix for a given XML namespace /// </summary> /// <param name="xmlns">Namespace to match</param> /// <param name="prefix">prefix for namespace, if any</param> /// <returns>True when a prefix was found, otherwise false</returns> public static bool TryGetCanonicalPrefix(XNamespace xmlns, out string prefix) { return _canonicalPrefixes.TryGetValue(xmlns, out prefix); } } } ================================================ FILE: Composite/Core/Xml/UriResolver.cs ================================================ using System; using System.IO; using System.Net; using Composite.Core.IO; namespace Composite.Core.Xml { internal static class UriResolver { public static Stream GetStream(string inputUri) { Uri resolvedUri = ResolveUri(inputUri); if (resolvedUri.Scheme == "file") { return new C1FileStream(resolvedUri.LocalPath, FileMode.Open, FileAccess.Read, FileShare.Read); } else { WebRequest request = WebRequest.Create(resolvedUri); WebResponse response = request.GetResponse(); return response.GetResponseStream(); } } public static Uri ResolveUri(string inputUri) { Uri uri = new Uri(inputUri, UriKind.RelativeOrAbsolute); if (!uri.IsAbsoluteUri && (uri.OriginalString.Length > 0)) { uri = new Uri(Path.GetFullPath(inputUri)); } return uri; } } } ================================================ FILE: Composite/Core/Xml/XAttributeUtils.cs ================================================ using System; using System.Xml.Linq; namespace Composite.Core.Xml { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class XAttributeUtils { /// <exclude /> public static string GetValueOrDefault(this XAttribute attribute, string defaultValue) { if (attribute == null) return defaultValue; return attribute.Value; } /// <exclude /> public static bool TryGetIntValue(this XAttribute attribute, out int value) { if (attribute == null) throw new ArgumentNullException("attribute"); value = default(int); try { value = (int)attribute; } catch(FormatException) { return false; } return true; } /// <exclude /> public static bool TryGetBoolValue(this XAttribute attribute, out bool value) { if (attribute == null) throw new ArgumentNullException("attribute"); value = default(bool); try { value = (bool)attribute; } catch (FormatException) { return false; } return true; } /// <exclude /> public static bool TryGetGuidValue(this XAttribute attribute, out Guid value) { if (attribute == null) throw new ArgumentNullException("attribute"); value = default(Guid); try { value = (Guid)attribute; } catch (FormatException) { return false; } return true; } } } ================================================ FILE: Composite/Core/Xml/XDocumentUtils.cs ================================================ using System; using System.IO; using System.Xml.Linq; using Composite.Core.IO; namespace Composite.Core.Xml { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class XDocumentUtils { /// <summary> /// This should be a part of the I/O layer /// </summary> /// <param name="inputUri">This could be a file or a url</param> public static XDocument Load(string inputUri) { return Load(inputUri, LoadOptions.None); } /// <summary> /// This should be a part of the I/O layer /// </summary> /// <param name="loadOptions">Load options.</param> /// <param name="inputUri">This could be a file or a url</param> public static XDocument Load(string inputUri, LoadOptions loadOptions) { if (inputUri.Contains("://")) { using (Stream stream = UriResolver.GetStream(inputUri)) { return XDocument.Load(stream, loadOptions); } } return XDocument.Load(inputUri, loadOptions); } /// <summary> /// This should be a part of the I/O layer /// </summary> public static void Save(XDocument document, string filename) { using (C1FileStream stream = new C1FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read)) { document.Save(stream); } } /// <summary> /// This should be a part of the I/O layer /// </summary> public static void SaveToFile(this XDocument document, string filename) { Save(document, filename); } /// <exclude /> public static string GetDocumentAsString(this XDocument document) { Verify.ArgumentNotNull(document, "document"); using (var ms = new MemoryStream()) { using (var sw = new C1StreamWriter(ms)) { document.Save(sw); ms.Seek(0, SeekOrigin.Begin); using (var sr = new C1StreamReader(ms)) { return sr.ReadToEnd(); } } } } } } ================================================ FILE: Composite/Core/Xml/XElementUtils.cs ================================================ using System; using System.IO; using System.Linq; using System.Xml.Linq; using Composite.Core.IO; using System.Collections.Generic; namespace Composite.Core.Xml { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class XElementUtils { /// <summary> /// This should be a part of the I/O layer /// </summary> /// <param name="inputUri">This could be a file or a url</param> public static XElement Load(string inputUri) { XElement element; using (Stream stream = UriResolver.GetStream(inputUri)) { element = XElement.Load(stream); } return element; } /// <summary> /// This should be a part of the I/O layer /// </summary> public static void SaveToPath(this XElement element, string fileName) { using (var stream = new C1FileStream(fileName, FileMode.Create, FileAccess.Write)) { element.Save(stream); } } /// <exclude /> public static bool HasSameSiblings(this XElement element) { if (element == null) throw new ArgumentNullException("element"); if (element.Parent == null) return false; return element.Parent.Elements().Count(f => f.Name == element.Name) > 1; } /// <exclude /> public static int GetSameSiblingsBeforeCount(this XElement element) { if (element == null) throw new ArgumentNullException("element"); return element.NodesBeforeSelf().Count(f => f is XElement && ((XElement)f).Name == element.Name); } /// <summary> /// Returns the value of the XElement attribute with the specified name. /// </summary> /// <param name="element"></param> /// <param name="attributeName">The name of the attribute to (try to) get</param> /// <returns>The value of the attribute or null if the attribute does not exist.</returns> public static string GetAttributeValue(this XElement element, string attributeName) { if (element == null) throw new ArgumentNullException("element"); if (string.IsNullOrEmpty(attributeName)) throw new ArgumentNullException("attributeName"); return GetAttributeValue(element, (XName)attributeName); } /// <summary> /// Returns the value of the XElement attribute with the specified name. /// </summary> /// <param name="element">The element.</param> /// <param name="attributeXName">XName of the attribute.</param> /// <returns> /// The value of the attribute or null if the attribute does not exist. /// </returns> public static string GetAttributeValue(this XElement element, XName attributeXName) { Verify.ArgumentNotNull(element, "element"); Verify.ArgumentNotNull(attributeXName, "attributeXName"); return (string) element.Attribute(attributeXName); } /// <summary> /// Merge in elements and attributes. New child elements and new attributes are imported to the source. Conflicts are ignored (not merged). /// </summary> /// <param name="source">the structure to add new elements and attributes to</param> /// <param name="toBeImported">what to import</param> /// <returns>The modified source.</returns> public static XElement ImportSubtree(this XElement source, XElement toBeImported) { if (toBeImported != null) { foreach (XAttribute targetAttribute in from targetAttribute in toBeImported.Attributes() let sourceAttribute = source.Attribute(targetAttribute.Name) where sourceAttribute == null select targetAttribute) { source.Add(targetAttribute); } foreach (XElement targetChild in toBeImported.Elements()) { XElement sourceChild = FindElement(source, targetChild); if (sourceChild != null && !HasConflict(sourceChild, targetChild)) { sourceChild.ImportSubtree(targetChild); } else { if (targetChild.Name.LocalName == "configSections") { source.AddFirst(targetChild); } else { source.Add(targetChild); } } } } return source; } /// <summary> /// Removes attributes and child elements from source which match ditto 100% in tatoBeExcludedget. Elements in source which has other child elements or attributes are not removed. /// </summary> /// <param name="source">XElement to modify</param> /// <param name="toBeExcluded">what to locate and remove</param> /// <returns>The modified source.</returns> public static XElement RemoveMatches(this XElement source, XElement toBeExcluded) { if (toBeExcluded != null) { foreach (XAttribute a in source.Attributes().Where(a => toBeExcluded.GetAttributeValue(a.Name) == a.Value).ToList()) { a.Remove(); } foreach (XElement sourceChild in source.Elements().ToList()) { XElement targetChild = FindElement(toBeExcluded, sourceChild); if (targetChild != null && !HasConflict(sourceChild, targetChild)) { RemoveMatches(sourceChild, targetChild); if (!sourceChild.HasAttributes && !sourceChild.HasElements) { sourceChild.Remove(); targetChild.Remove(); } } } } return source; } private static bool HasConflict(XElement source, XElement target) { foreach (XAttribute targetAttribute in target.Attributes()) { string sourceAttributeValue = source.GetAttributeValue(targetAttribute.Name); if (sourceAttributeValue != null && sourceAttributeValue != targetAttribute.Value) { return true; } } return false; } private static int CountEquals(XElement target, XElement left, XElement right) { int leftEqualsCount = CountEquals(left, target, IsAttributeEqual); int rightEqualsCount = CountEquals(right, target, IsAttributeEqual); if (leftEqualsCount == rightEqualsCount) { int leftNameMatches = CountEquals(left, target, (a, b) => a.Name == b.Name); int rightNameMatches = CountEquals(right, target, (a, b) => a.Name == b.Name); return rightNameMatches.CompareTo(leftNameMatches); } return rightEqualsCount.CompareTo(leftEqualsCount); } private static int CountEquals(XElement left, XElement right, Func<XAttribute, XAttribute, bool> equal) { IEnumerable<XAttribute> equals = from l in left.Attributes() from r in right.Attributes() where equal(l, r) select l; return equals.Count(); } private static bool IsAttributeEqual(XAttribute source, XAttribute target) { if (source == null && target == null) { return true; } if (source == null || target == null) { return false; } return source.Name == target.Name && source.Value == target.Value; } private static XElement FindElement(XElement source, XElement target) { List<XElement> sourceElements = source.Elements(target.Name).ToList(); sourceElements.Sort((l, r) => CountEquals(target, l, r)); return sourceElements.FirstOrDefault(); } } } ================================================ FILE: Composite/Core/Xml/XNodeExtensionMethods.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using System.Xml; namespace Composite.Core.Xml { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class XNodeExtensionMethods { /// <summary> /// Returns an XPath to the specified XObject for documentation purposes. Namespaces /// are not handled by this function and using the returned XPath to look up the element /// is not guaranteed to work. /// </summary> /// <param name="xObject"></param> /// <returns></returns> public static string GetXPath(this XObject xObject) { StringBuilder sb = new StringBuilder(); GetXPath(xObject, sb); return sb.ToString(); } private static void GetXPath(this XObject xObject, StringBuilder currentPath) { if (xObject == null) throw new ArgumentNullException("xObject"); XElement element = xObject as XElement; if (element != null) { if (element.Parent != null) { if (element.HasSameSiblings() == false) { currentPath.Insert(0, element.Name.LocalName); currentPath.Insert(0, "/"); } else { int count = 1 + element.GetSameSiblingsBeforeCount(); currentPath.Insert(0, "]"); currentPath.Insert(0, count); currentPath.Insert(0, "["); currentPath.Insert(0, element.Name.LocalName); currentPath.Insert(0, "/"); } GetXPath(element.Parent, currentPath); return; } else { currentPath.Insert(0, element.Name.LocalName); currentPath.Insert(0, "/"); return; } } XAttribute attribute = xObject as XAttribute; if (attribute != null) { currentPath.Insert(0, attribute.Name); currentPath.Insert(0, "@"); GetXPath(attribute.Parent, currentPath); return; } throw new NotSupportedException("Only XElement and XAttribute supported"); } /// <exclude /> public static string[] InlineElements = new string[] { "a", "abbr", "acronym", "b", "basefont", "bdo", "big", "br", "cite", "code", "dfn", "em", "font", "i", "img", "input", "kbd", "label", "q", "s", "samp", "select", "small", "span", "strike", "strong", "sub", "sup", "textarea", "tt", "u", "var" }; private static readonly HashSet<string> InlineElementsLookup = new HashSet<string>(InlineElements); /// <exclude /> public static bool IsBlockElement(this XNode node) { if (node == null) return false; XElement element = node as XElement; if (element == null) return false; if (element.Name.Namespace == Namespaces.Xhtml) { if (InlineElementsLookup.Contains(element.Name.LocalName.ToLowerInvariant())) return false; } return true; } /// <exclude /> public static bool IsWhitespaceAware(this XNode node) { if (node == null) return false; XElement element = node as XElement; if (element == null) return false; string localName = element.Name.LocalName.ToLowerInvariant(); return (localName == "pre") || (localName == "textarea"); } } } ================================================ FILE: Composite/Core/Xml/XhtmlDocument.cs ================================================ using System.Xml.Linq; using System; using Composite.Core.Types; using System.Linq; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; using Composite.Core.IO; namespace Composite.Core.Xml { /// <summary> /// Represents an XHTML Document inside C1 CMS. /// /// This structure can contain both head elements and body elements (content) and XhtmlDocuments that are being rendered /// can be nested within each other. The C1 CMS core will normalize such a nested structure when rendering a page, ensuring head elementsa flow to the top level /// document and body content is left, ultimately yielding one complete and correctly structured xhtml page. /// </summary> [XhtmlDocumentConverter] public sealed class XhtmlDocument : XDocument { internal static readonly XName XName_html = Namespaces.Xhtml + "html"; internal static readonly XName XName_head = Namespaces.Xhtml + "head"; internal static readonly XName XName_body = Namespaces.Xhtml + "body"; private static readonly string XhtmlFragmentDtdInternalSubset; private static readonly string EntityFileName = PathUtil.Resolve("~/App_Data/Composite/Configuration/Entities.xml"); static XhtmlDocument() { if (File.Exists(EntityFileName)) { var doc = XDocument.Load(EntityFileName); var sb = new StringBuilder(); foreach (var element in doc.Root.Elements()) { string name = (string) element.Attribute("name"); string xmlsafe = (string) element.Attribute("xmlsafe"); if (!string.IsNullOrEmpty(name) && xmlsafe != null) { sb.AppendFormat(@"<!ENTITY {0} '{1}'>", name, xmlsafe); } } XhtmlFragmentDtdInternalSubset = sb.ToString(); } } /// <summary> /// Constructs an empty XhtmlDocument /// </summary> public XhtmlDocument() : base(new XElement(XName_html, new XElement(XName_head), new XElement(XName_body))) { } /// <summary> /// Constructs a XhtmlDocument based on an existing html element /// </summary> /// <param name="htmlElement">Existing html element the XhtmlDocument should be cloned from</param> public XhtmlDocument(XElement htmlElement) : base(htmlElement) { this.Validate(); } /// <summary> /// Constructs a XhtmlDocument based on an existing XDocument /// </summary> /// <param name="other">Existing XDocument instance the XhtmlDocument should be cloned from</param> public XhtmlDocument(XDocument other) : base(other) { this.Validate(); } /// <summary> /// The head element for the XHTML Document /// </summary> public XElement Head => this.Root.Element(XName_head); /// <summary> /// The body element for the XHTML Document /// </summary> public XElement Body => this.Root.Element(XName_body); /// <summary> /// Returns true if the XhtmlDocument has empty head and body sections. /// </summary> public bool IsEmpty { get { bool hasContent = this.Head.Nodes().Any() || this.Body.Nodes().Any() || this.Body.Attributes().Any(); return !hasContent; } } /// <summary> /// Parses a serialized xhtml document and returns XhtmlDocument. /// </summary> /// <param name="xhtml">xhtml to parse.</param> /// <returns>XhtmlDocument representing the supplied string</returns> public new static XhtmlDocument Parse(string xhtml) { var doc = new XhtmlDocument(XDocument.Parse(xhtml)); List<XElement> sourceWhitespaceSensitiveElements = GetWhitespaceSensitiveElements(doc); if (sourceWhitespaceSensitiveElements.Any()) { XhtmlDocument docWithWhitespaces = new XhtmlDocument(XDocument.Parse(xhtml, LoadOptions.PreserveWhitespace)); List<XElement> fixedWhitespaceSensitiveElements = GetWhitespaceSensitiveElements(docWithWhitespaces); for (int i = 0; i < sourceWhitespaceSensitiveElements.Count; i++) { sourceWhitespaceSensitiveElements[i].ReplaceWith(fixedWhitespaceSensitiveElements[i]); } } return doc; } /// <summary> /// Parses a serialized xhtml document and returns XhtmlDocument. /// </summary> /// <param name="xhtml">xhtml to parse.</param> /// <param name="options">This parameter is here for informative purposes - only LoadOptions.None is accepted, since anything else is a change to the DOM and a breeding ground for bugs</param> /// <returns>XhtmlDocument representing the supplied string</returns> public new static XhtmlDocument Parse(string xhtml, LoadOptions options) { if (options != LoadOptions.None) throw new NotImplementedException("PreserveWhitespace (anything but None) option is explicitly disallowed to prevent bugs - it will turn insignificant whitespace into text nodes, changing the DOM."); return Parse(xhtml); } private void Validate() { if (this.Root != null) { Verify.That(this.Root.Name == XName_html, "Supplied XDocument must have a root named html belonging to the namespace xmlns=\"{0}\"", Namespaces.Xhtml); Verify.IsNotNull(this.Head, "XHTML document is missing <head /> element"); Verify.IsNotNull(this.Body, "XHTML document is missing <body /> element"); } } private static List<XElement> GetWhitespaceSensitiveElements(XhtmlDocument doc) { return doc.Descendants().Where(node => node.Name.Namespace == Namespaces.Xhtml && (node.Name.LocalName == "pre" || node.Name.LocalName == "textarea")).ToList(); } /// <summary> /// Parses an xhtml fragment of into an XhtmlDocument. /// </summary> /// <param name="fragment"></param> /// <returns></returns> public static XhtmlDocument ParseXhtmlFragment(string fragment) { if (string.IsNullOrEmpty(fragment)) { return new XhtmlDocument(); } var nodes = new List<XNode>(); using (var stringReader = new StringReader(fragment)) { var xmlReaderSettings = new XmlReaderSettings { IgnoreWhitespace = true, DtdProcessing = DtdProcessing.Parse, MaxCharactersFromEntities = 10000000, XmlResolver = null, ConformanceLevel = ConformanceLevel.Fragment // Allows multiple XNode-s }; var inputContext = FragmentContainsHtmlEntities(fragment) ? GetXhtmlFragmentParserContext() : null; using (var xmlReader = XmlReader.Create(stringReader, xmlReaderSettings, inputContext)) { xmlReader.MoveToContent(); while (!xmlReader.EOF) { XNode node = XNode.ReadFrom(xmlReader); nodes.Add(node); } } } if (nodes.Count == 1 && nodes[0] is XElement element && element.Name.LocalName == "html") { return new XhtmlDocument(element); } var document = new XhtmlDocument(); document.Body.Add(nodes); return document; } private static bool FragmentContainsHtmlEntities(string fragment) { int searchOffset = 0; while (searchOffset != -1) { int ampersandOffset = fragment.IndexOf("&", searchOffset, StringComparison.Ordinal); if (ampersandOffset == -1) { return false; } searchOffset = ampersandOffset + 1; int symbolsLeft = fragment.Length - ampersandOffset - 1; if ((symbolsLeft > 0 && fragment[ampersandOffset + 1] == '#') || (symbolsLeft >= 4 && fragment[ampersandOffset + 1] == 'a' && fragment[ampersandOffset + 2] == 'm' && fragment[ampersandOffset + 3] == 'p' && fragment[ampersandOffset + 4] == ';') || (symbolsLeft >= 5 && fragment[ampersandOffset + 1] == 'a' && fragment[ampersandOffset + 2] == 'p' && fragment[ampersandOffset + 3] == 'o' && fragment[ampersandOffset + 4] == 's' && fragment[ampersandOffset + 5] == ';') || (symbolsLeft >= 5 && fragment[ampersandOffset + 1] == 'q' && fragment[ampersandOffset + 2] == 'u' && fragment[ampersandOffset + 3] == 'o' && fragment[ampersandOffset + 4] == 't' && fragment[ampersandOffset + 5] == ';') || (symbolsLeft >= 3 && fragment[ampersandOffset + 1] == 'g' && fragment[ampersandOffset + 2] == 't' && fragment[ampersandOffset + 3] == ';') || (symbolsLeft >= 3 && fragment[ampersandOffset + 1] == 'l' && fragment[ampersandOffset + 2] == 't' && fragment[ampersandOffset + 3] == ';')) { continue; } return true; } // this line should not be reachable return false; } private static XmlParserContext GetXhtmlFragmentParserContext() { if (XhtmlFragmentDtdInternalSubset == null) { return null; } return new XmlParserContext(null, null, "internal", String.Empty, String.Empty, XhtmlFragmentDtdInternalSubset, String.Empty, String.Empty, XmlSpace.Default, Encoding.UTF8); } } internal sealed class XhtmlDocumentConverterAttribute : ValueTypeConverterHelperAttribute { public override bool TryConvert(object value, Type targetType, out object targetValue) { Verify.ArgumentNotNull(value, "value"); if (targetType == typeof(XhtmlDocument) && value is XElement element) { targetValue = new XhtmlDocument(element); return true; } if ((targetType == typeof(XElement) || targetType == typeof(XNode)) && value is XhtmlDocument document) { targetValue = document.Root; return true; } targetValue = null; return false; } } } ================================================ FILE: Composite/Core/Xml/XhtmlErrorFormatter.cs ================================================ using System; using System.Reflection; using System.Web; using System.Xml.Linq; using Composite.Core.IO; namespace Composite.Core.Xml { /// <summary> /// Provide html formatting for errors /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class XhtmlErrorFormatter { private const string ErrorDivStyle = "border: 1px solid red; padding: 2px 6px 2px 6px; background-color: InfoBackground; color: InfoText; -moz-border-radius: 4px; -moz-box-shadow: 1px 1px 3px 0 rgba(0,0,0,0.75); margin-bottom: 5px;font-size: 12px; line-height: 16px;"; private const string SourceCodeStyle = "border: 1px solid #AAAAAA; padding: 5px; background-color: #EEEEEE;font-size: 12px;"; private const string SourceCodeErrorLineStyle = "background-color: white; color: red"; private static readonly string ExceptionData_SourceCode = "C1.SourceCode"; /// <exclude /> [Obsolete("Use EmbedSourceCodeInformation() instead")] public static void EmbedSouceCodeInformation(Exception ex, string[] sourceCodeLines, int errorLine) { EmbedSourceCodeInformation(ex, sourceCodeLines, errorLine); } /// <summary> /// Embeds the source code information. /// </summary> /// <param name="ex">The exception.</param> /// <param name="sourceCodeLines">The source code lines.</param> /// <param name="errorLine">The error line number.</param> public static void EmbedSourceCodeInformation(Exception ex, string[] sourceCodeLines, int errorLine) { if (ex.Data.Contains(ExceptionData_SourceCode)) { return; } ex.Data[ExceptionData_SourceCode] = SourceCodePreview(sourceCodeLines, errorLine).ToString(); } private static XElement SourceCodePreview(string filePath, int errorLine) { string[] lines = C1File.ReadAllLines(filePath); return SourceCodePreview(lines, errorLine); } private static XElement SourceCodePreview(string[] sourceCodeLines, int errorLine) { var result = new XElement(Namespaces.Xhtml + "pre", new XAttribute("style", SourceCodeStyle)); int firstLineIndexToShow = Math.Max(0, errorLine - 3); int lastLineIndexToShow = Math.Min(sourceCodeLines.Length - 1, errorLine + 1); for (int i = firstLineIndexToShow; i <= lastLineIndexToShow; i++) { string text = (i + 1) + ": " + sourceCodeLines[i]; if (i == errorLine - 1) { result.Add(new XElement(Namespaces.Xhtml + "div", new XAttribute("style", SourceCodeErrorLineStyle), text)); } else { result.Add(text + Environment.NewLine); } } return result; } /// <summary> /// Create a html element documenting an exception. If the page being rendered is requested by an authenticated C1 Console user the /// exception information is more verbose. /// </summary> /// <param name="ex"></param> /// <param name="functionName"></param> /// <returns></returns> internal static XElement GetErrorDescriptionHtmlElement(Exception ex, string functionName) { if (!Composite.C1Console.Security.UserValidationFacade.IsLoggedIn()) { return new XElement(Namespaces.Xhtml + "span", new XAttribute("class", "c1error"), "[ Error ]"); } XElement functionInfo = functionName == null ? null : new XElement(Namespaces.Xhtml + "div", "Function: " + functionName); XElement sourceCode = GetSourceCodeInfo(ex); bool sourceAlreadyShown = false; XElement nestedExceptionInfo = ex.InnerException == null ? null : new XElement(Namespaces.Xhtml + "div", new XAttribute("style", "font-size: 0.9em"), GetNestedHtmlListFromExceptions(ex.InnerException, ref sourceAlreadyShown)); return new XElement(Namespaces.Xhtml + "div", new XAttribute("class", "c1errordetails"), new XAttribute("style", ErrorDivStyle), new XElement(Namespaces.Xhtml + "strong", new XAttribute("title", ex.StackTrace), string.Format("Error: {0}", ex.Message)), !sourceAlreadyShown ? sourceCode : null, functionInfo, nestedExceptionInfo ); } private static XElement GetNestedHtmlListFromExceptions(Exception ex, ref bool sourceCodeShown) { if (ex == null) { return null; } XElement sourceCode = GetSourceCodeInfo(ex); XElement nestedExceptionsInfo = GetNestedHtmlListFromExceptions(ex.InnerException, ref sourceCodeShown); bool showSourceCode = !sourceCodeShown && sourceCode != null; sourceCodeShown |= showSourceCode; return new XElement(Namespaces.Xhtml + "div", new XAttribute("style", "padding-left: 10px;"), new XAttribute("title", ex.StackTrace ?? ""), ex.Message, showSourceCode ? sourceCode : null, nestedExceptionsInfo); } private static XElement GetSourceCodeInfo(Exception ex) { if (ex.Data.Contains(ExceptionData_SourceCode)) { return XElement.Parse((string)ex.Data[ExceptionData_SourceCode]); } if (ex is HttpCompileException) { object firstCompileError = GetPropertyValue(ex, "FirstCompileError"); if (firstCompileError != null) { string filePath = (string)GetPropertyValue(firstCompileError, "FileName"); int line = (int)GetPropertyValue(firstCompileError, "Line"); if (!string.IsNullOrEmpty(filePath)) { return SourceCodePreview(filePath, line); } } } var httpParseException = ex as HttpParseException; if (httpParseException != null) { return SourceCodePreview(httpParseException.FileName, httpParseException.Line); } return null; } private static object GetPropertyValue(object @object, string name) { var property = @object.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); Verify.IsNotNull(property, "Missing property '{0}' on type '{1}'", name, @object.GetType()); return property.GetValue(@object, null); } } } ================================================ FILE: Composite/Core/Xml/XhtmlPrettifier.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Xml; namespace Composite.Core.Xml { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class XhtmlPrettifier { private static string _ampersandWord = "C1AMPERSAND"; private static readonly Regex _encodeCDataRegex = new Regex(@"<!\[CDATA\[((?:[^]]|\](?!\]>))*)\]\]>", RegexOptions.Compiled); private static readonly Regex _decodeCDataRegex = new Regex("C1CDATAREPLACE(?<counter>[0-9]*)", RegexOptions.Compiled); private static readonly Regex _encodeRegex = new Regex(@"&(?<tag>[^\;]+;)", RegexOptions.Compiled); private static readonly Regex _decodeRegex = new Regex(@"C1AMPERSAND(?<tag>[^\;]+;)", RegexOptions.Compiled); private static readonly char[] IncorrectEscapeSequenceCharacters = { '\'', '\"', '<', '>', ' ' }; private static readonly char[] WhitespaceChars = { '\t', '\n', '\v', '\f', '\r', ' ', '\x0085', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '​', '\u2028', '\u2029', ' ', '' }; private static readonly HashSet<char> WhitespaceCharsLookup = new HashSet<char>(WhitespaceChars); private static readonly HashSet<NamespaceName> CompactElements = new HashSet<NamespaceName>(new [] { new NamespaceName { Name = "title", Namespace = "" } }); private static readonly HashSet<NamespaceName> AlwaysWrapElements = new HashSet<NamespaceName>(new[] { new NamespaceName { Name = "html", Namespace = "" }, new NamespaceName { Name = "head", Namespace = "" }, new NamespaceName { Name = "body", Namespace = "" } }); internal static readonly HashSet<NamespaceName> InlineElements = new HashSet<NamespaceName>(new [] { new NamespaceName { Name = "a", Namespace = "" }, new NamespaceName { Name = "abbr", Namespace = "" }, new NamespaceName { Name = "acronym", Namespace = "" }, new NamespaceName { Name = "b", Namespace = "" }, new NamespaceName { Name = "basefont", Namespace = "" }, new NamespaceName { Name = "bdo", Namespace = "" }, new NamespaceName { Name = "big", Namespace = "" }, new NamespaceName { Name = "br", Namespace = "" }, new NamespaceName { Name = "cite", Namespace = "" }, new NamespaceName { Name = "code", Namespace = "" }, new NamespaceName { Name = "dfn", Namespace = "" }, new NamespaceName { Name = "em", Namespace = "" }, new NamespaceName { Name = "fieldreference", Namespace = Namespaces.DynamicData10.NamespaceName }, new NamespaceName { Name = "font", Namespace = "" }, new NamespaceName { Name = "i", Namespace = "" }, new NamespaceName { Name = "img", Namespace = "" }, new NamespaceName { Name = "input", Namespace = "" }, new NamespaceName { Name = "kbd", Namespace = "" }, new NamespaceName { Name = "label", Namespace = "" }, new NamespaceName { Name = "mark", Namespace = "" }, new NamespaceName { Name = "page.description", Namespace = Namespaces.Rendering10.NamespaceName }, new NamespaceName { Name = "page.title", Namespace = Namespaces.Rendering10.NamespaceName }, new NamespaceName { Name = "q", Namespace = "" }, new NamespaceName { Name = "s", Namespace = "" }, new NamespaceName { Name = "samp", Namespace = "" }, new NamespaceName { Name = "select", Namespace = "" }, new NamespaceName { Name = "small", Namespace = "" }, new NamespaceName { Name = "span", Namespace = "" }, new NamespaceName { Name = "strike", Namespace = "" }, new NamespaceName { Name = "strong", Namespace = "" }, new NamespaceName { Name = "sub", Namespace = "" }, new NamespaceName { Name = "sup", Namespace = "" }, new NamespaceName { Name = "textarea", Namespace = "" }, new NamespaceName { Name = "tt", Namespace = "" }, new NamespaceName { Name = "u", Namespace = "" }, new NamespaceName { Name = "var", Namespace = "" }, }); private static readonly HashSet<NamespaceName> WhitespaceAwareElements = new HashSet<NamespaceName>(new[] { new NamespaceName { Name = "style", Namespace = "" }, new NamespaceName { Name = "script", Namespace = "" }, new NamespaceName { Name = "pre", Namespace = "" }, new NamespaceName { Name = "textarea", Namespace = "" }, new NamespaceName { Name = "variable", Namespace = "http://www.w3.org/1999/xsl/transform" } }); private static readonly HashSet<NamespaceName> SelfClosingElements = new HashSet<NamespaceName>(new [] { // "Void elements" defined in HTML5 new NamespaceName { Name = "area", Namespace = "" }, new NamespaceName { Name = "base", Namespace = "" }, new NamespaceName { Name = "br", Namespace = "" }, new NamespaceName { Name = "col", Namespace = "" }, new NamespaceName { Name = "command", Namespace = "" }, new NamespaceName { Name = "embed", Namespace = "" }, new NamespaceName { Name = "hr", Namespace = "" }, new NamespaceName { Name = "img", Namespace = "" }, new NamespaceName { Name = "input", Namespace = "" }, new NamespaceName { Name = "keygen", Namespace = "" }, new NamespaceName { Name = "link", Namespace = "" }, new NamespaceName { Name = "meta", Namespace = "" }, new NamespaceName { Name = "param", Namespace = "" }, new NamespaceName { Name = "source", Namespace = "" }, new NamespaceName { Name = "track", Namespace = "" }, new NamespaceName { Name = "wbr", Namespace = "" }, // Obsolete element types new NamespaceName { Name = "basefont", Namespace = "" }, new NamespaceName { Name = "frame", Namespace = "" } }); /// <exclude /> public static string Prettify(string xmlString) { return Prettify(xmlString, "\t"); } /// <exclude /> public static string Prettify(string xmlString, string indentString) { xmlString = XmlUtils.RemoveXmlDeclaration(xmlString); CDataMatchHandler cdataMatchHandler; IEnumerable<XmlNode> tree = BuildTree(xmlString, out cdataMatchHandler); var sb = new StringBuilder(); NodeTreeToString(tree, sb, indentString, false); string result = sb.ToString(); result = _decodeCDataRegex.Replace(result, cdataMatchHandler.Decode); return result; } private static void NodeTreeToString(IEnumerable<XmlNode> nodes, StringBuilder stringBuilder, string indentString, bool keepWhiteSpaces) { foreach (XmlNode node in nodes) { if (node.NodeType == XmlNodeType.Element) { if (!keepWhiteSpaces && (node.IsBlockElement() || node.ContainsBlockElements || (node.ParentNode != null && node.ParentNode.ContainsBlockElements)) && (node.Level > 0)) { stringBuilder.AppendLine().AddIndent(node.Level, indentString); } stringBuilder.Append("<").Append(node.Name); foreach (XmlAttribute attribute in node.Attributes) { if (!attribute.Name.StartsWith("xmlns", StringComparison.OrdinalIgnoreCase) || node.ParentNode == null || node.ParentNode.NamespaceByPrefix(attribute.Name) != node.NamespaceURI) { stringBuilder.Append(" ").Append(attribute.Name).Append("=\"").Append(EncodeAttributeString(attribute.Value)).Append("\""); } } bool isSelfClosingAndEmpty = node.IsSelfClosingElement() && !node.IsAlwaysWrapElement() && (node.IsEmpty || !node.ChildNodes.Any(f => f.NodeType == XmlNodeType.Element || f.NodeType == XmlNodeType.Text)); stringBuilder.Append(isSelfClosingAndEmpty ? " />" : ">"); bool nodeIsWhiteSpaceAware = node.IsWhitespaceAware(); // Recursive call NodeTreeToString(node.ChildNodes, stringBuilder, indentString, keepWhiteSpaces || nodeIsWhiteSpaceAware); if (!isSelfClosingAndEmpty) { if (!keepWhiteSpaces && !nodeIsWhiteSpaceAware && (node.ContainsBlockElements || node.IsAlwaysWrapElement()) && !node.IsCompactElement()) { stringBuilder.AppendLine().AddIndent(node.Level, indentString); } stringBuilder.Append("</").Append(node.Name).Append(">"); } } else if (node.NodeType == XmlNodeType.Text) { string value; bool addSpaceToBegin = false, addSpaceToEnd = false; if (!keepWhiteSpaces) { bool startsWithWhitespace = WhitespaceCharsLookup.Contains(node.Value[0]); bool endsWithWhitespace = WhitespaceCharsLookup.Contains(node.Value[node.Value.Length - 1]); value = SuperTrim(node.Value); if (startsWithWhitespace ) { if ((node.PreviousNode != null && !node.PreviousNode.IsBlockElement()) || (node.ParentNode != null && !node.ParentNode.IsBlockElement() && !node.ParentNode.IsCompactElement())) { addSpaceToBegin = true; } } if (endsWithWhitespace ) { if ((node.NextNode != null && !node.NextNode.IsBlockElement()) || (node.ParentNode != null && !node.ParentNode.IsBlockElement() && !node.ParentNode.IsCompactElement())) { addSpaceToEnd = true; } } } else { value = node.Value; } if (addSpaceToBegin) { stringBuilder.Append(" "); } stringBuilder.Append(EncodeElementString(value)); if (addSpaceToEnd) { stringBuilder.Append(" "); } } else if (node.NodeType == XmlNodeType.Whitespace || node.NodeType == XmlNodeType.SignificantWhitespace) { if (node.PreviousNode != null && node.PreviousNode.NodeType == XmlNodeType.Element && !node.PreviousNode.IsBlockElement() && node.NextNode != null && node.NextNode.NodeType == XmlNodeType.Element && !node.NextNode.IsBlockElement()) { stringBuilder.Append(" "); } else if (keepWhiteSpaces || (node.NextNode != null && node.NextNode.NodeType == XmlNodeType.Comment)) { stringBuilder.Append(node.Value); } } else if (node.NodeType == XmlNodeType.CDATA) { if(!keepWhiteSpaces) { stringBuilder.AppendLine(); } stringBuilder.Append("<![CDATA["); stringBuilder.Append(node.Value); stringBuilder.Append("]]>"); if (!keepWhiteSpaces) { stringBuilder.AppendLine().AddIndent(node.Level - 1, indentString); } } else if (node.NodeType == XmlNodeType.Comment) { var previousNode = node.PreviousNode; if(previousNode == null || (previousNode.NodeType != XmlNodeType.Text && previousNode.NodeType != XmlNodeType.Whitespace)) { stringBuilder.AppendLine().AddIndent(node.Level, indentString); } stringBuilder.Append("<!--").Append(RemoveC1EncodedAmpersands(node.Value)).Append("-->"); if (node.ParentNode != null && !node.ParentNode.IsBlockElement()) { stringBuilder.AppendLine().AddIndent(node.Level - 1, indentString); } } else if (node.NodeType == XmlNodeType.DocumentType) { stringBuilder.Append("<!DOCTYPE " + node.Name); foreach (XmlAttribute attribute in node.Attributes) { if (attribute.Name.ToLowerInvariant() != "system") { stringBuilder.Append(" ").Append(attribute.Name).Append(" \"").Append(attribute.Value).Append("\""); } else { stringBuilder.Append(" \"").Append(attribute.Value).Append("\""); } } stringBuilder.AppendLine(">"); } else if (node.NodeType == XmlNodeType.XmlDeclaration) { stringBuilder.Append("<?"); stringBuilder.Append(node.Name); stringBuilder.Append(" "); stringBuilder.Append(node.Value); stringBuilder.AppendLine("?>"); } } } private static StringBuilder AddIndent(this StringBuilder sb, int level, string indentString) { for (int i = 0; i < level; i++) { sb.Append(indentString); } return sb; } private static string EncodeAttributeString(string value) { value = value.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\"", """); return RemoveC1EncodedAmpersands(value); } private static string EncodeElementString(string value) { value = value.Replace("&", "&").Replace("<", "<").Replace(">", ">"); return RemoveC1EncodedAmpersands(value); } private static string RemoveC1EncodedAmpersands(string value) { return _decodeRegex.Replace(value, match => "&" + match.Groups["tag"].Value); } /// <summary> /// Merges sequences of white spaces /// </summary> /// <exclude /> public static string SuperTrim(string value) { StringBuilder sb = null; value = value.Trim(WhitespaceChars); /* Symbol #160 - the non-breaking space, shouldn't be trimmed */ int index = 0; int oldIndex = 0; while (index < value.Length) { char ch = value[index]; // If there's just one space in a sequence, ignoring it if (ch == ' ' && !WhitespaceCharsLookup.Contains(value[index + 1])) { index += 2; continue; } if(WhitespaceCharsLookup.Contains(ch)) { sb = sb ?? new StringBuilder(); sb.Append(value, oldIndex, index - oldIndex); sb.Append(" "); do { ++index; } while (WhitespaceCharsLookup.Contains(value[index])); oldIndex = index; } index++; } if (sb == null) { return value; } sb.Append(value, oldIndex, index - oldIndex); return sb.ToString(); } private static IEnumerable<XmlNode> BuildTree(string xmlString, out CDataMatchHandler cdataMatchHandler) { cdataMatchHandler = new CDataMatchHandler(); xmlString = _encodeCDataRegex.Replace(xmlString, cdataMatchHandler.Encode); xmlString = _encodeRegex.Replace(xmlString, delegate(Match match) { string entiryStr = match.Groups["tag"].Value; return IsCorrectEscapeEntity(entiryStr) ? _ampersandWord + entiryStr : "&" + entiryStr; }); var xmlReaderSettings = new XmlReaderSettings {DtdProcessing = DtdProcessing.Parse, XmlResolver = null}; using (XmlReader xmlReader = XmlTextReader.Create(new StringReader(xmlString), xmlReaderSettings)) { return BuildTree(xmlReader, 0).ToList(); } } private static bool IsCorrectEscapeEntity(string match) { return (match.Length < 30) && match.IndexOfAny(IncorrectEscapeSequenceCharacters) == -1; } private static IEnumerable<XmlNode> BuildTree(XmlReader xmlReader, int level) { while (xmlReader.Read() ) { if (xmlReader.NodeType == XmlNodeType.EndElement) yield break; var node = new XmlNode { NodeType = xmlReader.NodeType, Name = xmlReader.Name, NamespaceURI = xmlReader.NamespaceURI ?? "", Value = xmlReader.Value, Level = level, IsEmpty = xmlReader.IsEmptyElement }; if (node.NodeType == XmlNodeType.Element || node.NodeType == XmlNodeType.DocumentType) { int attributeCount = xmlReader.AttributeCount; for (int i = 0; i < attributeCount; i++) { xmlReader.MoveToAttribute(i); var attribute = new XmlAttribute { Name = xmlReader.Name, Value = xmlReader.Value }; node.AddAttribute(attribute); } if (node.NodeType == XmlNodeType.Element) { if (!node.IsEmpty) { foreach (XmlNode childNode in BuildTree(xmlReader, level + 1)) { node.AddChild(childNode); } } } } yield return node; } } private enum TriState { Undefined = -1, False = 0, True = 1 } [DebuggerDisplay("Type = {NodeType}, Name = {Name}, Value = {Value}")] private class XmlNode { private static readonly IEnumerable<XmlAttribute> EmptyAttributeList = Enumerable.Empty<XmlAttribute>(); private XmlNode _firstNode; private XmlNode _lastNode; private List<XmlAttribute> _attributes; private TriState _containsBlockElements = TriState.Undefined; private TriState _isBlockElement = TriState.Undefined; private TriState _isCompactElement = TriState.Undefined; private TriState _isAlwaysWrapElement = TriState.Undefined; private NamespaceName _namespaceName; public XmlNodeType NodeType { get; internal set; } public string Name { get; internal set; } public string Value { get; internal set; } public bool IsEmpty { get; internal set; } public string NamespaceURI { get; internal set; } public int Level { get; internal set; } public XmlNode ParentNode { get; internal set; } public XmlNode PreviousNode { get; internal set; } public XmlNode NextNode { get; internal set; } private NamespaceName GetNamespaceName() { if (_namespaceName == null) { _namespaceName = new NamespaceName { Name = this.Name.ToLowerInvariant(), Namespace = GetCustomNamespace() }; } return _namespaceName; } public void AddChild(XmlNode childNode) { childNode.ParentNode = this; if (_lastNode != null) { _lastNode.NextNode = childNode; childNode.PreviousNode = _lastNode; } else { _firstNode = childNode; } _lastNode = childNode; } public void AddAttribute(XmlAttribute attribute) { if (_attributes == null) { _attributes = new List<XmlAttribute>(); } _attributes.Add(attribute); } public IEnumerable<XmlNode> ChildNodes { get { XmlNode currentNode = _firstNode; while (currentNode != null) { yield return currentNode; currentNode = currentNode.NextNode; } } } public IEnumerable<XmlAttribute> Attributes { get { return _attributes ?? EmptyAttributeList; } } public bool ContainsBlockElements { get { if(_containsBlockElements == TriState.Undefined) { _containsBlockElements = ChildNodes.Any(node => node.IsBlockElement() || node.ContainsBlockElements) ? TriState.True : TriState.False; } return _containsBlockElements == TriState.True; } } public string NamespaceByPrefix(string namespacePrefix) { var defined = _attributes == null ? null : _attributes.FirstOrDefault(f => f.Name == namespacePrefix); if (defined != null) { return defined.Value; } if (this.ParentNode != null) { return this.ParentNode.NamespaceByPrefix(namespacePrefix); } return null; } public bool IsCompactElement() { if (_isCompactElement == TriState.Undefined) { _isCompactElement = this.NodeType == XmlNodeType.Element && CompactElements.Contains(GetNamespaceName()) ? TriState.True : TriState.False; ; } return _isCompactElement == TriState.True; } public bool IsAlwaysWrapElement() { if (_isAlwaysWrapElement == TriState.Undefined) { _isAlwaysWrapElement = this.NodeType == XmlNodeType.Element && AlwaysWrapElements.Contains(GetNamespaceName()) ? TriState.True : TriState.False; ; } return _isAlwaysWrapElement == TriState.True; } public bool IsBlockElement() { if(_isBlockElement == TriState.Undefined) { _isBlockElement = this.NodeType == XmlNodeType.Element && !InlineElements.Contains(GetNamespaceName()) ? TriState.True : TriState.False; ; } return _isBlockElement == TriState.True; } public bool IsWhitespaceAware() { if (this.NodeType != XmlNodeType.Element) return false; if (WhitespaceAwareElements.Contains(GetNamespaceName())) return true; return false; } public bool IsSelfClosingElement() { if (this.NodeType != XmlNodeType.Element) return false; var name = GetNamespaceName(); if (SelfClosingElements.Contains(name)) return true; return name.Namespace != ""; } private string GetCustomNamespace() { string namespaceName = this.NamespaceURI.ToLowerInvariant(); if (namespaceName == "http://www.w3.org/1999/xhtml") { namespaceName = ""; } return namespaceName; } } [DebuggerDisplay("Name = {Name}, Value = {Value}")] private class XmlAttribute { public string Name { get; internal set; } public string Value { get; internal set; } } internal sealed class NamespaceName { public string Name; public string Namespace; public bool Equals(NamespaceName namespaceName) { if (namespaceName == null) return false; return this.Name == namespaceName.Name && this.Namespace == namespaceName.Namespace; } public override bool Equals(object obj) { return Equals(obj as NamespaceName); } public override int GetHashCode() { return this.Name.GetHashCode() ^ this.Namespace.GetHashCode(); } } private sealed class CDataMatchHandler { List<string> cDatas = new List<string>(); public string Encode(Match match) { string s = "C1CDATAREPLACE" + cDatas.Count.ToString(); cDatas.Add(match.Value); return s; } public string Decode(Match match) { int index = int.Parse(match.Groups["counter"].Value); return cDatas[index]; } } } } ================================================ FILE: Composite/Core/Xml/XhtmlWriter.cs ================================================ using System; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; namespace Composite.Core.Xml { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class XhtmlWriterExtensions { /// <exclude /> public static XmlWriter CreateXhtmlWriter(this XContainer container) { return new XhtmlWriter(container.CreateWriter()); } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class XhtmlWriter : XmlWriter { private readonly XmlWriter _innerWriter; private string openingElement = String.Empty; private static HashSet<string> selfClosingElements = new HashSet<string>( new []{ "area", "base", "basefont", "br", "hr", "input", "img", "link", "meta" }); /// <exclude /> public XhtmlWriter(XmlWriter innerWriter) { _innerWriter = innerWriter; } /// <exclude /> public override void Close() { _innerWriter.Close(); } /// <exclude /> public override void Flush() { _innerWriter.Flush(); } /// <exclude /> public override string LookupPrefix(string ns) { return _innerWriter.LookupPrefix(ns); } /// <exclude /> public override void WriteBase64(byte[] buffer, int index, int count) { _innerWriter.WriteBase64(buffer, index, count); } /// <exclude /> public override void WriteCData(string text) { _innerWriter.WriteCData(text); } /// <exclude /> public override void WriteCharEntity(char ch) { _innerWriter.WriteCharEntity(ch); } /// <exclude /> public override void WriteChars(char[] buffer, int index, int count) { _innerWriter.WriteChars(buffer, index, count); } /// <exclude /> public override void WriteComment(string text) { _innerWriter.WriteComment(text); } /// <exclude /> public override void WriteDocType(string name, string pubid, string sysid, string subset) { _innerWriter.WriteDocType(name, pubid, sysid, subset); } /// <exclude /> public override void WriteEndAttribute() { _innerWriter.WriteEndAttribute(); } /// <exclude /> public override void WriteEndDocument() { _innerWriter.WriteEndDocument(); } /// <exclude /> public override void WriteEndElement() { if (!selfClosingElements.Contains(openingElement)) { WriteFullEndElement(); } else { _innerWriter.WriteEndElement(); } } /// <exclude /> public override void WriteEntityRef(string name) { _innerWriter.WriteEntityRef(name); } /// <exclude /> public override void WriteFullEndElement() { _innerWriter.WriteFullEndElement(); } /// <exclude /> public override void WriteProcessingInstruction(string name, string text) { _innerWriter.WriteProcessingInstruction(name, text); } /// <exclude /> public override void WriteRaw(string data) { _innerWriter.WriteRaw(data); } /// <exclude /> public override void WriteRaw(char[] buffer, int index, int count) { _innerWriter.WriteRaw(buffer, index, count); } /// <exclude /> public override void WriteStartAttribute(string prefix, string localName, string ns) { _innerWriter.WriteStartAttribute(prefix, localName, ns); } /// <exclude /> public override void WriteStartDocument(bool standalone) { _innerWriter.WriteStartDocument(standalone); } /// <exclude /> public override void WriteStartDocument() { _innerWriter.WriteStartDocument(); } /// <exclude /> public override void WriteStartElement(string prefix, string localName, string ns) { _innerWriter.WriteStartElement(prefix, localName, ns); openingElement = localName; } /// <exclude /> public override WriteState WriteState { get { return _innerWriter.WriteState; } } /// <exclude /> public override void WriteString(string text) { _innerWriter.WriteString(text); } /// <exclude /> public override void WriteSurrogateCharEntity(char lowChar, char highChar) { _innerWriter.WriteSurrogateCharEntity(lowChar, highChar); } /// <exclude /> public override void WriteWhitespace(string ws) { _innerWriter.WriteWhitespace(ws); } } } ================================================ FILE: Composite/Core/Xml/XmlDocumentUtil.cs ================================================ using System.IO; using System.Xml; using Composite.Core.IO; namespace Composite.Core.Xml { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] internal static class XmlDocumentUtil { public static void Load(XmlDocument document, string filename) { using (Stream stream = new C1FileStream(filename, FileMode.Open)) { document.Load(stream); } } public static void Save(XmlDocument document, string filename) { using (Stream stream = new C1FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read)) { document.Save(stream); } } } } ================================================ FILE: Composite/Core/Xml/XmlReaderUtils.cs ================================================ using System.IO; using System.Xml; using Composite.Core.IO; namespace Composite.Core.Xml { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class XmlReaderUtils { /// <summary> /// This should be a part of the I/O layer /// </summary> public static XmlReader Create(string path) { return Create(path, null); } /// <summary> /// This should be a part of the I/O layer /// </summary> public static XmlReader Create(string path, XmlReaderSettings settings) { MemoryStream memoryStream = new MemoryStream(); using (Stream stream = new C1FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { StreamUtils.CopyStream(stream, memoryStream); } memoryStream.Seek(0, SeekOrigin.Begin); if (settings == null) { return XmlReader.Create(memoryStream); } else { return XmlReader.Create(memoryStream, settings); } } } } ================================================ FILE: Composite/Core/Xml/XmlSchemaSetUtils.cs ================================================ using System.Xml; using System.Xml.Schema; using Composite.Core.IO; namespace Composite.Core.Xml { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] internal static class XmlSchemaSetUtils { /// <summary> /// This should be a part of the I/O layer /// </summary> public static XmlSchema AddFromPath(this XmlSchemaSet xmlSchemaSet, string targetNamespace, string path) { using (C1StreamReader streamReader = new C1StreamReader(path)) { using (XmlReader xmlReader = XmlReader.Create(streamReader)) { return xmlSchemaSet.Add(targetNamespace, xmlReader); } } } } } ================================================ FILE: Composite/Core/Xml/XmlSerializationHelper.cs ================================================ using System; using System.Xml.Linq; using Composite.Core.Types; namespace Composite.Core.Xml { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class XmlSerializationHelper { /// <summary> /// Converts the object into an xml serializable object. /// </summary> /// <exclude /> public static object GetSerializableObject(object value) { if (value == null) return null; var type = value.GetType(); if (type == typeof (string) || type == typeof (double) || type == typeof (float) || type == typeof (decimal) || type == typeof (DateTime) || type == typeof (DateTimeOffset) || type == typeof (TimeSpan)) { return value; } return ValueTypeConverter.Convert<string>(value); } /// <exclude /> public static object Deserialize(XAttribute attribute, Type type) { if (type == typeof(string)) return (string)attribute; if (type == typeof(double) || type == typeof(double?)) return (double)attribute; if (type == typeof(float) || type == typeof(float?)) return (float)attribute; if (type == typeof(decimal) || type == typeof(decimal?)) return (decimal)attribute; if (type == typeof(DateTime) || type == typeof(DateTime?)) return (DateTime)attribute; if (type == typeof(DateTimeOffset) || type == typeof(DateTimeOffset?)) return (DateTimeOffset)attribute; if (type == typeof(TimeSpan) || type == typeof(TimeSpan?)) return (TimeSpan)attribute; return ValueTypeConverter.Convert(attribute.Value, type); } } } ================================================ FILE: Composite/Core/Xml/XmlUtils.cs ================================================ using System.Xml.Linq; namespace Composite.Core.Xml { /// <summary> /// /// </summary> public static class XmlUtils { /// <summary> /// Builds an XName - will use null namespace if namespaceName is null or empty. /// </summary> /// <param name="namespaceName">Namespace of element</param> /// <param name="localName">Local name of element</param> /// <returns>Corosponding XName</returns> public static XName GetXName(string namespaceName, string localName) { if (string.IsNullOrEmpty(namespaceName) == false) { return ((XNamespace)namespaceName) + localName; } else { return localName; } } /// <summary> /// Removes the XML declaration (like <?xml version="1.0" encoding="utf-8"?>) if present from the provided agrument. /// </summary> /// <param name="xml">The string to remove XML declaration from</param> /// <returns>The XML document without any XML declaration</returns> public static string RemoveXmlDeclaration(string xml) { xml = xml.Trim(); if (xml.StartsWith("<?xml") && xml.Contains("?>")) { xml = xml.Substring(xml.IndexOf("?>") + 2); } return xml; } } } ================================================ FILE: Composite/Core/Xml/XmlWriterUtils.cs ================================================ using System.IO; using System.Xml; using Composite.Core.IO; namespace Composite.Core.Xml { /// <summary> /// This class contains Composite IO versions of System.Xml.XmlWriter/System.Xml.XmlTextWriter Create. /// These method should be used instead of the ones in System.Xml.XmlWriter/System.Xml.XmlTextWriter. /// </summary> public static class XmlWriterUtils { /// <summary> /// Creates a new XmlWriter /// </summary> /// <param name="path">Path to file</param> /// <returns>Returns the newly created XmlWriter</returns> public static XmlWriter Create(string path) { Stream stream = new C1FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read); XmlWriterSettings settings = new XmlWriterSettings(); settings.CloseOutput = true; return XmlWriter.Create(stream, settings); } /// <summary> /// Creates a new XmlWriter /// </summary> /// <param name="path">Path to file</param> /// <param name="settings">An instance to XmlWriterSettings</param> /// <returns>Returns the newly created XmlWriter</returns> public static XmlWriter Create(string path, XmlWriterSettings settings) { Stream stream = new C1FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read); settings.CloseOutput = true; return XmlWriter.Create(stream, settings); } } } ================================================ FILE: Composite/Core/Xml/XslCompiledTransformUtils.cs ================================================ using System.Xml; using System.Xml.Xsl; using Composite.Core.IO; namespace Composite.Core.Xml { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class XslCompiledTransformUtils { /// <summary> /// This should be a part of the I/O layer /// </summary> public static void LoadFromPath(this XslCompiledTransform xslCompiledTransform, string path) { using (C1StreamReader streamReader = new C1StreamReader(path)) { using (XmlReader xmlReader = XmlReader.Create(streamReader)) { xslCompiledTransform.Load(xmlReader); } } } /// <summary> /// This should be a part of the I/O layer /// </summary> public static void LoadFromPath(this XslCompiledTransform xslCompiledTransform, string path, XsltSettings settings, XmlResolver stylesheetResolver) { using (C1StreamReader streamReader = new C1StreamReader(path)) { using (XmlReader xmlReader = XmlReader.Create(streamReader)) { xslCompiledTransform.Load(xmlReader, settings, stylesheetResolver); } } } } } ================================================ FILE: Composite/Core/Xml/XsltExtensionDefinition.cs ================================================ using System; using System.Xml.Linq; namespace Composite.Core.Xml { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IXsltExtensionDefinition { /// <exclude /> XNamespace ExtensionNamespace { get; } /// <exclude /> object EntensionObjectAsObject { get; } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class XsltExtensionDefinition<T> : IXsltExtensionDefinition { /// <exclude /> public XNamespace ExtensionNamespace { get; set; } /// <exclude /> public T EntensionObject { get; set; } /// <exclude /> public object EntensionObjectAsObject { get { return this.EntensionObject; } } } } ================================================ FILE: Composite/Data/AutoUpdatebleAttribute.cs ================================================ using System; namespace Composite.Data { /// <summary> /// IData types decorated with this attribute will be have their store auto created and updated if the interface changes. /// You should use this attribute for data types that C1 CMS should be able to auto support via data providers. /// </summary> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = true)] public sealed class AutoUpdatebleAttribute : Attribute { /// <exclude /> public AutoUpdatebleAttribute() { } } } ================================================ FILE: Composite/Data/BuildNewHandlerAttribute.cs ================================================ using System; namespace Composite.Data { /// <summary> /// This attribute is used to override the default behavior when creating new data items. /// See <see cref="IBuildNewHandler"/> for mor information on this subject. /// </summary> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = true)] public sealed class BuildNewHandlerAttribute : Attribute { /// <summary> /// Creates a new BuildNewHandlerAttribute /// </summary> /// <param name="buildNewHandlerType">This should be a type that inherits <see cref="IBuildNewHandler"/></param> public BuildNewHandlerAttribute(Type buildNewHandlerType) { this.BuildNewHandlerType = buildNewHandlerType; } /// <summary> /// The build handle type that inherits <see cref="IBuildNewHandler"/> /// </summary> public Type BuildNewHandlerType { get; private set; } } } ================================================ FILE: Composite/Data/Caching/Cache.cs ================================================ using System.Collections; using System.Collections.Generic; using Composite.C1Console.Events; using Composite.Core; using Composite.Core.Configuration; namespace Composite.Data.Caching { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Cache<K, V>: Cache where V: class { /// <exclude /> public Cache(string name) : base(name) { } /// <exclude /> public Cache(string name, int maximumSize) : base(name, maximumSize) { } /// <exclude /> public V Get(K key) { return base.Get(key) as V; } /// <exclude /> public void Remove(K key) { base.Remove(key); } /// <exclude /> public void Add(K key, V value) { base.Add(key, value); } /// <exclude /> public IEnumerable<K> GetKeys() { lock(_syncRoot) { ICollection keys = _table.Keys; K[] result = new K[keys.Count]; keys.CopyTo(result, 0); return result; } } } /// <summary> /// Represents a cache. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Cache { private static readonly int DefaultMaximumCacheSize = 1000; /// <exclude /> protected readonly Hashtable _table = new Hashtable(); /// <exclude /> protected readonly object _syncRoot = new object(); private bool _enabled = true; private bool _clearOnFlush = true; private int _maxSize; private readonly int _defaultMaximumSize; /// <exclude /> public Cache(string name): this(name, DefaultMaximumCacheSize) { } /// <exclude /> public Cache(string name, int defaultMaximumSize) { Verify.ArgumentCondition(defaultMaximumSize >= 10, "maximumSize", "Maximum cache size should be at least 10 element."); Verify.ArgumentNotNullOrEmpty(name, "name"); Name = name; _defaultMaximumSize = defaultMaximumSize; ReadConfiguration(); GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlush); GlobalEventSystemFacade.SubscribeToFlushEvent(OnPostFlush); } /// <exclude /> public bool Enabled => _enabled; /// <exclude /> public string Name { get; } /// <exclude /> protected object Get(object key) => _table[key]; /// <exclude /> protected void Add(object key, object value) { if(!_enabled) { return; } lock (_syncRoot) { if (_maxSize != -1 && _table.Count > _maxSize) { Log.LogWarning("Cache", $"Clearing cache '{Name}' as it exceeded maximum size {_maxSize} elements. Edit configuration file /App_Data/Composite/Composite.config to increase the cache size."); _table.Clear(); } if (_table.Contains(key)) { _table.Remove(key); } _table.Add(key, value); } } /// <exclude /> protected void Remove(object key) { if (!_enabled) { return; } if(!_table.Contains(key)) return; lock(_syncRoot) { if (!_table.Contains(key)) return; _table.Remove(key); } } /// <exclude /> public void Clear() { lock (_syncRoot) { _table.Clear(); } } void OnFlush(FlushEventArgs args) { if (_clearOnFlush) { Clear(); } } void OnPostFlush(FlushEventArgs args) { ReadConfiguration(); } /// <exclude /> public bool ClearOnFlush { set { _clearOnFlush = value; } } /// <exclude /> protected void ReadConfiguration() { CachingSettings cachingSettings = GlobalSettingsFacade.GetNamedCaching(this.Name); _enabled = cachingSettings.Enabled; _maxSize = cachingSettings.GetSize(_defaultMaximumSize); } } } ================================================ FILE: Composite/Data/Caching/CachedTable.cs ================================================ using System.Collections.Generic; using System.Linq; namespace Composite.Data.Caching { /// <summary> /// Cached table /// </summary> internal abstract class CachedTable { /// <summary> /// The queryable data /// </summary> public abstract IQueryable Queryable { get; } internal abstract bool Add(IEnumerable<IData> dataset); internal abstract bool Update(IEnumerable<IData> dataset); internal abstract bool Remove(IEnumerable<IData> dataset); /// <summary> /// Row by key table /// </summary> public abstract IReadOnlyDictionary<object, IEnumerable<IData>> RowsByKey { get; } } internal class CachedTable<T> : CachedTable { private IReadOnlyCollection<T> _items; private IReadOnlyDictionary<object, IEnumerable<IData>> _rowsByKey; public CachedTable(IReadOnlyCollection<T> items) { _items = items; } public override IQueryable Queryable => _items.AsQueryable(); internal override bool Add(IEnumerable<IData> dataset) { var toAdd = dataset.Cast<T>().ToList(); lock (this) { var existingRows = _items; var newTable = new List<T>(existingRows.Count + toAdd.Count); newTable.AddRange(existingRows); newTable.AddRange(toAdd); _items = newTable; _rowsByKey = null; // Can be optimized as well return true; } } internal override bool Update(IEnumerable<IData> dataset) { var toUpdate = dataset.ToDictionary(_ => _.DataSourceId); lock (this) { var existingRows = _items; var updated = new List<T>(existingRows.Count); int updatedTotal = 0; foreach (var data in existingRows) { bool matched = toUpdate.TryGetValue(((IData)data).DataSourceId, out IData updatedDataItem); if (matched) { updatedTotal++; } updated.Add(matched ? (T)updatedDataItem : data); } _items = updated.AsReadOnly(); _rowsByKey = null; // Can be optimized as well return updatedTotal == toUpdate.Count; } } internal override bool Remove(IEnumerable<IData> dataset) { var toRemove = new HashSet<DataSourceId>(dataset.Select(_ => _.DataSourceId)); lock (this) { var existingRows = _items; if (existingRows.Count < toRemove.Count) return false; var newTable = new List<T>(existingRows.Count - toRemove.Count); int removed = 0; foreach (var item in existingRows) { if (toRemove.Contains(((IData)item).DataSourceId)) { removed++; continue; } newTable.Add(item); } _items = newTable; _rowsByKey = null; // Can be optimized as well return removed == toRemove.Count; } } public override IReadOnlyDictionary<object, IEnumerable<IData>> RowsByKey { get { var result = _rowsByKey; if (result != null) return result; lock (this) { result = _rowsByKey; if (result != null) return result; var keyPropertyInfo = typeof(T).GetKeyProperties().Single(); result = _items .GroupBy(data => keyPropertyInfo.GetValue(data, null)) .ToDictionary(group => group.Key, group => group.ToArray() as IEnumerable<IData>); return _rowsByKey = result; } } } } } ================================================ FILE: Composite/Data/Caching/CachingEnumerator.cs ================================================ using System.Collections; using System.Collections.Generic; using System; using Composite.Data.Foundation.CodeGeneration; namespace Composite.Data.Caching { internal sealed class CachingEnumerator<T> : IEnumerator<T> { private readonly IEnumerator<T> _enumerator; private Func<T, T> _wrapperConstructor; public CachingEnumerator(IEnumerator<T> enumerator) { _enumerator = enumerator; } public T Current => WrapperConstructor(_enumerator.Current); public void Dispose() { _enumerator.Dispose(); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// <exclude /> ~CachingEnumerator() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif object IEnumerator.Current => WrapperConstructor(_enumerator.Current); public bool MoveNext() { return _enumerator.MoveNext(); } public void Reset() { _enumerator.Reset(); } private Func<T, T> WrapperConstructor { get { return _wrapperConstructor ?? (_wrapperConstructor = DataWrapperTypeManager.GetWrapperConstructor<T>()); } } } } ================================================ FILE: Composite/Data/Caching/CachingQueryable.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using Composite.Core.Types; using Composite.Data.Caching.Foundation; using System.Reflection; using Composite.Core.Linq; using Composite.Data.Foundation; namespace Composite.Data.Caching { internal sealed class CachingEnumerable<T> : IEnumerable<T> { private readonly IEnumerable<T> _enumerable; public CachingEnumerable(IEnumerable<T> enumerable) { _enumerable = enumerable; } public IEnumerator<T> GetEnumerator() { return new CachingEnumerator<T>(_enumerable.GetEnumerator()); } IEnumerator IEnumerable.GetEnumerator() { return new CachingEnumerator<T>(_enumerable.GetEnumerator()); } } internal interface ICachedQuery { IQueryable GetOriginalQuery(); } /// <summary> /// Used for optimizing execution of GetDataByUniqueKey method /// </summary> internal interface ICachingQueryable_CachedByKey { IData GetCachedValueByKey(object key); IEnumerable<IData> GetCachedVersionValuesByKey(object key); } internal sealed class CachingQueryable<T> : ICachedQuery, IOrderedQueryable<T>, IQueryProvider, ICachingQueryable, ICachingQueryable_CachedByKey { private readonly IQueryable _source; private readonly Expression _currentExpression; private readonly CachingEnumerable<T> _wrappedEnumerable; private readonly Func<IQueryable> _getQueryFunc; private volatile CachedTable _cachedTable; private static readonly MethodInfo _wrappingMethodInfo; private static readonly MethodInfo _listWrappingMethodInfo; private IEnumerable<T> _innerEnumerable; static CachingQueryable() { if (typeof(IData).IsAssignableFrom(typeof(T))) { _wrappingMethodInfo = StaticReflection.GetGenericMethodInfo(a => DataWrappingFacade.Wrap((IData) a)) .MakeGenericMethod(new[] {typeof (T)}); } if (typeof(IData).IsAssignableFrom(typeof(T))) { _listWrappingMethodInfo = StaticReflection.GetGenericMethodInfo(a => WrapData((IEnumerable<IData>)a)) .MakeGenericMethod(typeof(T)); } } private static IEnumerable<TData> WrapData<TData>(IEnumerable<TData> input) where TData : class, IData { return input.Select(DataWrappingFacade.Wrap<TData>); } public CachingQueryable(CachedTable cachedTable, Func<IQueryable> originalQueryGetter) { _cachedTable = cachedTable; _source = cachedTable.Queryable; _currentExpression = Expression.Constant(this); _getQueryFunc = originalQueryGetter; if (_source is IEnumerable<T>) { _innerEnumerable = _source as IEnumerable<T>; if(_innerEnumerable is CachingEnumerable<T>) { _wrappedEnumerable = _innerEnumerable as CachingEnumerable<T>; } } } public CachingQueryable(IQueryable source, Expression currentExpression, Func<IQueryable> originalQueryGetter) { _source = source; _currentExpression = currentExpression; _getQueryFunc = originalQueryGetter; } #region Generic methods public IQueryable<S> CreateQuery<S>(Expression expression) { return new CachingQueryable<S>(_source, expression, _getQueryFunc); } public IEnumerator<T> GetEnumerator() { var enumerable = BuildEnumerable(); if (_wrappedEnumerable != null) { return _wrappedEnumerable.GetEnumerator(); } var enumerator = enumerable.GetEnumerator(); if (_source.ElementType == typeof(T)) { return new CachingEnumerator<T>(enumerator); } return enumerator; } private IEnumerable<T> BuildEnumerable() { if (_innerEnumerable == null) { lock (this) { if (_innerEnumerable == null) { var visitor = new ChangeSourceExpressionVisitor(); Expression newExpression = visitor.Visit(_currentExpression); var result = (IQueryable<T>)_source.Provider.CreateQuery(newExpression); Verify.IsNotNull(result, "Failed to create an enumerator"); Thread.MemoryBarrier(); _innerEnumerable = result; } } } return _innerEnumerable; } public S Execute<S>(Expression expression) { var visitor = new ChangeSourceExpressionVisitor(); Expression newExpression = visitor.Visit(expression); object result = _source.Provider.Execute(newExpression); if (result != null && _source.ElementType == typeof(S)) { result = (S) _wrappingMethodInfo.Invoke(null, new [] { result }); } return (S) result; } #endregion #region Non generic methods IEnumerator IEnumerable.GetEnumerator() { MethodInfo methodInfo = CachingQueryableCache.GetCachingQueryableGetEnumeratorMethodInfo(typeof(T)); return (IEnumerator)methodInfo.Invoke(this, null); } public IQueryable CreateQuery(Expression expression) { if (_currentExpression == expression) return this; Type elementType = TypeHelpers.FindElementType(expression); Type queryableType = CachingQueryableCache.GetCachingQueryableType(elementType); return (IQueryable)Activator.CreateInstance( queryableType, new object[] { _source, expression, _getQueryFunc }); } public object Execute(Expression expression) { MethodInfo methodInfo = CachingQueryableCache.GetCachingQueryableExecuteMethodInfo(typeof(T), expression.Type); return methodInfo.Invoke(this, new object[] { expression }); } #endregion public IData GetCachedValueByKey(object key) { var filteredData = GetFromCacheFiltered(key); if (filteredData == null) return null; var result = filteredData.FirstOrDefault(); if (result == null) return null; return _wrappingMethodInfo.Invoke(null, new object[] { result }) as IData; } public IEnumerable<IData> GetCachedVersionValuesByKey(object key) { var result = GetFromCacheFiltered(key); if (result == null) return Enumerable.Empty<IData>(); return _listWrappingMethodInfo.Invoke(null, new object[] { result }) as IEnumerable<IData>; } private IEnumerable<T> GetFromCacheFiltered(object key) { var cachedTable = GetCachedTable().RowsByKey; IEnumerable<IData> cachedRows; if (!cachedTable.TryGetValue(key, out cachedRows)) { return null; } IEnumerable<T> filteredData = cachedRows.Cast<T>(); var filterMethodInfo = StaticReflection.GetGenericMethodInfo( () => ((DataInterceptor)null).InterceptGetData((IEnumerable<IData>)null)) .MakeGenericMethod(typeof(T)); foreach (var dataInterceptor in DataFacade.GetDataInterceptors(typeof(T))) { filteredData = (IEnumerable<T>)filterMethodInfo.Invoke(dataInterceptor, new object[] { filteredData }); } return filteredData; } private CachedTable GetCachedTable() { if (_cachedTable == null) { lock (this) { _cachedTable = _cachedTable ?? new CachedTable<T>(GetOriginalQuery().Cast<T>().ToList()); } } return _cachedTable; } public Expression Expression => _currentExpression; public Type ElementType => typeof(T); public IQueryProvider Provider => this; public IQueryable Source => _source; public IQueryable GetOriginalQuery() => _getQueryFunc(); } } ================================================ FILE: Composite/Data/Caching/DataCachingFacade.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using Composite.Data.DynamicTypes; using Composite.Data.Foundation; using Composite.Data.Foundation.PluginFacades; using Composite.C1Console.Events; using Composite.Core; using Composite.Core.Configuration; using ScopeKey = System.Tuple<Composite.Data.DataScopeIdentifier, System.Globalization.CultureInfo>; using TypeData = System.Collections.Concurrent.ConcurrentDictionary< System.Tuple<Composite.Data.DataScopeIdentifier, System.Globalization.CultureInfo>, Composite.Data.Caching.CachedTable>; namespace Composite.Data.Caching { /// <summary> /// Provide information about data caching and means to flush data from the active cache. /// </summary> public static class DataCachingFacade { private static readonly string CacheName = "DataAccess"; private static readonly ConcurrentDictionary<Type, TypeData> _cachedData = new ConcurrentDictionary<Type, TypeData>(); private static readonly ConcurrentDictionary<Type, byte> _disabledTypes = new ConcurrentDictionary<Type, byte>(); private static bool _isEnabled = true; private static int _maximumSize = -1; private static MethodInfo _queryableTakeMathodInfo; static DataCachingFacade() { ReadSettings(); GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); DataEvents<IData>.OnStoreChanged += (sender, args) => { if (!args.DataEventsFired) { ClearCache(args.DataType, args.PublicationScope, args.Locale); } }; } /// <summary> /// Gets a value indicating if data caching is enabled /// </summary> public static bool Enabled => _isEnabled; /// <summary> /// Gets a value indicating if data caching is possible for a specific data type /// </summary> /// <param name="interfaceType">The data type to check</param> /// <returns>True if caching is possible</returns> public static bool IsTypeCacheable(Type interfaceType) { Guid dataTypeId; DataTypeDescriptor dataTypeDescriptor; return _isEnabled && (DataAttributeFacade.GetCachingType(interfaceType) == CachingType.Full || (interfaceType.TryGetImmutableTypeId(out dataTypeId) && DynamicTypeManager.TryGetDataTypeDescriptor(interfaceType, out dataTypeDescriptor) && dataTypeDescriptor.Cachable)); } /// <summary> /// Gets a value indicating if data caching is enabled for a specific data type /// </summary> /// <param name="interfaceType">The data type to check</param> /// <returns>True if caching is enabled</returns> public static bool IsDataAccessCacheEnabled(Type interfaceType) { return IsTypeCacheable(interfaceType) && !_disabledTypes.ContainsKey(interfaceType); } /// <exclude /> internal static IQueryable<T> GetDataFromCache<T>(Func<IQueryable<T>> getQueryFunc) where T : class, IData { Verify.That(_isEnabled, "The cache is disabled."); var dataScopeIdentifier = DataScopeManager.MapByType(typeof(T)); var localizationScope = LocalizationScopeManager.MapByType(typeof(T)); var typeData = _cachedData.GetOrAdd(typeof(T), t => new TypeData()); var cacheKey = new Tuple<DataScopeIdentifier, CultureInfo>(dataScopeIdentifier, localizationScope); CachedTable cachedTable; if (!typeData.TryGetValue(cacheKey, out cachedTable)) { IQueryable<T> wholeTable = getQueryFunc(); if(!DataProvidersSupportDataWrapping(typeof(T))) { DisableCachingForType(typeof(T)); return Verify.ResultNotNull(wholeTable); } if(_maximumSize != -1) { List<T> cuttedTable = TakeElements(wholeTable, _maximumSize + 1).Cast<T>().ToList(); if(cuttedTable.Count > _maximumSize) { DisableCachingForType(typeof (T)); return Verify.ResultNotNull(wholeTable); } cachedTable = new CachedTable<T>(cuttedTable); } else { cachedTable = new CachedTable<T>(wholeTable.ToList()); } typeData[cacheKey] = cachedTable; } var typedData = cachedTable.Queryable as IQueryable<T>; Verify.IsNotNull(typedData, "Cached value is invalid."); // Leaving a possibility to extract original query Func<IQueryable> originalQueryGetter = () => { using (new DataScope(dataScopeIdentifier, localizationScope)) { return getQueryFunc(); } }; return new CachingQueryable<T>(cachedTable, originalQueryGetter); } private static bool DataProvidersSupportDataWrapping(Type T) { var providerNames = DataProviderRegistry.GetDataProviderNamesByInterfaceType(T); Verify.IsNotNull(providerNames, "Failed to get data provider names list"); return providerNames.All(DataProviderPluginFacade.AllowsResultsWrapping); } /// <summary> /// Flush cached data for a data type in the current data scope. /// </summary> /// <param name="interfaceType">The type of data to flush from the cache</param> public static void ClearCache(Type interfaceType) { ClearCache(interfaceType, null); } /// <summary> /// Flush cached data for a data type in the specified data scope. /// </summary> /// <param name="interfaceType">The type of data to flush from the cache</param> /// <param name="publicationScope">The publication scope to flush</param> public static void ClearCache(Type interfaceType, PublicationScope publicationScope) { ClearCache(interfaceType, DataScopeIdentifier.FromPublicationScope(publicationScope)); } /// <summary> /// Flush cached data for a data type in the specified data scope. /// </summary> /// <param name="interfaceType">The type of data to flush from the cache</param> /// <param name="publicationScope">The publication scope to flush</param> /// <param name="localizationScope">The localization scope to flush</param> public static void ClearCache(Type interfaceType, PublicationScope publicationScope, CultureInfo localizationScope) { ClearCache(interfaceType, DataScopeIdentifier.FromPublicationScope(publicationScope), localizationScope); } /// <summary> /// Flush cached data for a data type in the specified data scope. /// </summary> /// <param name="interfaceType">The type of data to flush from the cache</param> /// <param name="dataScopeIdentifier">The data scope to flush</param> public static void ClearCache(Type interfaceType, DataScopeIdentifier dataScopeIdentifier) { TypeData typeData; if(!_cachedData.TryGetValue(interfaceType, out typeData)) return; dataScopeIdentifier = dataScopeIdentifier ?? DataScopeManager.MapByType(interfaceType); var toRemove = typeData.Keys.Where(key => key.Item1 == dataScopeIdentifier).ToList(); foreach (var key in toRemove) { CachedTable value; typeData.TryRemove(key, out value); } } /// <summary> /// Removes the specified data collection from the cache. /// </summary> /// <param name="dataset"></param> internal static void RemoveDataFromCache(IReadOnlyCollection<IData> dataset) { UpdateCachedTables(dataset, (table, data) => table.Remove(data)); } /// <summary> /// Removes the specified data collection from the cache. /// </summary> /// <param name="dataset"></param> internal static void UpdateCachedData(IReadOnlyCollection<IData> dataset) { UpdateCachedTables(dataset, (table, data) => table.Update(data)); } /// <summary> /// Adds the specified data collection to the cache. /// </summary> /// <param name="dataset"></param> internal static void AddDataToCache(IReadOnlyCollection<IData> dataset) { UpdateCachedTables(dataset, (table, data) => table.Add(data)); } internal static void UpdateCachedTables( IReadOnlyCollection<IData> dataset, Func<CachedTable, IEnumerable<IData>, bool> action) { if (dataset.Count == 0) return; var groupedData = from data in dataset let ds = data.DataSourceId group data by new { ds.InterfaceType, ds.DataScopeIdentifier, ds.LocaleScope }; foreach (var group in groupedData) { TypeData typeData; if (!_cachedData.TryGetValue(group.Key.InterfaceType, out typeData)) { continue; } var scopeKey = new ScopeKey(group.Key.DataScopeIdentifier, group.Key.LocaleScope); CachedTable cachedTable; if (!typeData.TryGetValue(scopeKey, out cachedTable)) { continue; } bool success = action(cachedTable, group); if (!success) { var key = group.Key; Log.LogError(nameof(DataCachingFacade), $"Cache out of sync for type '{key.InterfaceType}' scope '{key.DataScopeIdentifier}' culture '{key.LocaleScope}'"); ClearCache(key.InterfaceType, key.DataScopeIdentifier, key.LocaleScope); } } // TODO: clear cache on transaction rollback? } internal static void ClearCache(Type interfaceType, DataScopeIdentifier dataScopeIdentifier, CultureInfo localizationScope) { if (!_cachedData.TryGetValue(interfaceType, out TypeData typeData)) return; dataScopeIdentifier = dataScopeIdentifier ?? DataScopeManager.MapByType(interfaceType); localizationScope = !DataLocalizationFacade.IsLocalized(interfaceType) ? CultureInfo.InvariantCulture : (localizationScope ?? LocalizationScopeManager.CurrentLocalizationScope); var key = new Tuple<DataScopeIdentifier, CultureInfo>(dataScopeIdentifier, localizationScope); typeData.TryRemove(key, out _); } /// <summary> /// This method is also called by the DataFacade /// </summary> internal static void Flush() { _cachedData.Clear(); _disabledTypes.Clear(); } private static void ReadSettings() { CachingSettings cachingSettings = GlobalSettingsFacade.GetNamedCaching(CacheName); _isEnabled = cachingSettings.Enabled; _maximumSize = cachingSettings.Size; } private static IQueryable TakeElements(IQueryable queryable, int count) { MethodInfo method = GetQueryableTakeMethodInfo(queryable.ElementType); var resultTable = (IQueryable) method.Invoke(null, new object[] {queryable, count}); return resultTable; } private static MethodInfo GetQueryableTakeMethodInfo(Type type) { if(_queryableTakeMathodInfo == null) { _queryableTakeMathodInfo = (from method in typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public) where method.Name == nameof(Queryable.Take) && method.IsGenericMethod select method).First(); } return _queryableTakeMathodInfo.MakeGenericMethod(type); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); ReadSettings(); } private static void DisableCachingForType(Type type) { _disabledTypes.TryAdd(type, 0); TypeData data; _cachedData.TryRemove(type, out data); } } } ================================================ FILE: Composite/Data/Caching/Foundation/CachingQueryableCache.cs ================================================ using System; using System.Collections.Concurrent; using System.Linq; using System.Reflection; using Composite.C1Console.Events; namespace Composite.Data.Caching.Foundation { internal static class CachingQueryableCache { private static readonly ConcurrentDictionary<Type, MethodInfo> _getEnumeratorMethodInfoCache = new ConcurrentDictionary<Type, MethodInfo>(); private static readonly ConcurrentDictionary<Type, Type> _queryableTypeCache = new ConcurrentDictionary<Type, Type>(); private static readonly ConcurrentDictionary<Tuple<Type, Type>, MethodInfo> _executeMethodInfoCache = new ConcurrentDictionary<Tuple<Type, Type>, MethodInfo>(); static CachingQueryableCache() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } public static MethodInfo GetCachingQueryableGetEnumeratorMethodInfo(Type genericType) { return _getEnumeratorMethodInfoCache.GetOrAdd(genericType, genType => { Type type = typeof (CachingQueryable<>).MakeGenericType(new[] {genType}); return type.GetMethods().First(method => method.Name == "GetEnumerator"); }); } public static Type GetCachingQueryableType(Type elementType) { return _queryableTypeCache.GetOrAdd(elementType, eType => typeof(CachingQueryable<>).MakeGenericType(new[] { eType })); } public static MethodInfo GetCachingQueryableExecuteMethodInfo(Type genericType, Type expressionType) { return _executeMethodInfoCache.GetOrAdd(new Tuple<Type, Type>(genericType, expressionType), pair => { Type type = typeof(CachingQueryable<>).MakeGenericType(new[] { pair.Item1 }); var genericMethodInfo = type.GetMethods().First(method => method.Name == "Execute" && method.IsGenericMethod); return genericMethodInfo.MakeGenericMethod(new[] { pair.Item2 }); }); } private static void Flush() { _getEnumeratorMethodInfoCache.Clear(); _queryableTypeCache.Clear(); _executeMethodInfoCache.Clear(); } } } ================================================ FILE: Composite/Data/Caching/Foundation/ChangeSourceExpressionVisitor.cs ================================================ using System.Linq.Expressions; namespace Composite.Data.Caching.Foundation { internal sealed class ChangeSourceExpressionVisitor : ExpressionVisitor { private readonly Expression _newSourceExpression; public ChangeSourceExpressionVisitor() { _newSourceExpression = null; } public ChangeSourceExpressionVisitor(Expression newSourceExpression) { _newSourceExpression = newSourceExpression; } protected override Expression VisitConstant(ConstantExpression c) { if (c.Value == null) return base.VisitConstant(c); if (c.Value is ICachingQueryable) { if (_newSourceExpression == null) { return ((ICachingQueryable)c.Value).Source.Expression; } return _newSourceExpression; } return base.VisitConstant(c); } } } ================================================ FILE: Composite/Data/Caching/ICachingQueryable.cs ================================================ using System.Linq; namespace Composite.Data.Caching { internal interface ICachingQueryable { IQueryable Source { get; } } } ================================================ FILE: Composite/Data/Caching/TableVersion.cs ================================================ using System; using System.Globalization; using System.Threading; using Composite.Core.Collections.Generic; using Composite.Data.Types; using Composite.C1Console.Events; using Composite.Core.Types; namespace Composite.Data.Caching { internal static class TableVersion { private static readonly Hashtable<string, ExtendedNullable<int>> _versionNumbers = new Hashtable<string, ExtendedNullable<int>>(); private static Hashset<Type> _subscribedTo = new Hashset<Type>(); private static int _flushCounter; static TableVersion() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static int Get(Type type) { Verify.ArgumentNotNull(type, "type"); if(typeof(IMediaFile).IsAssignableFrom(type)) { type = typeof (IMediaFileData); } EnsureSubscribtion(type); string key = GetKey(type); ExtendedNullable<int> record = _versionNumbers[key]; return _flushCounter + (record == null ? 0 : record.Value); } private static string GetKey(Type type) { return GetKey(type, DataScopeManager.MapByType(type), LocalizationScopeManager.MapByType(type)); } private static string GetKey(Type type, DataScopeIdentifier dataScopeIdentifier, CultureInfo cultureInfo) { return type.FullName + " " + dataScopeIdentifier.Name + " " + cultureInfo.Name; } private static void IncreaseTableVersion(Type type, DataScopeIdentifier dataScopeIdentifier, CultureInfo locale) { string key = GetKey(type, dataScopeIdentifier, locale); lock (_versionNumbers) { if (_versionNumbers.ContainsKey(key)) { _versionNumbers[key].Value++; } else { _versionNumbers.Add(key, 1); } } } private static void EnsureSubscribtion(Type type) { if (!_subscribedTo.Contains(type)) { lock (_subscribedTo) { if (!_subscribedTo.Contains(type)) { _subscribedTo.Add(type); DataEventSystemFacade.SubscribeToStoreChanged(type, (sender, storeEventArgs) => IncreaseTableVersion(type, DataScopeIdentifier.FromPublicationScope(storeEventArgs.PublicationScope), storeEventArgs.Locale), false); } } } } private static void OnFlushEvent(FlushEventArgs args) { Interlocked.Increment(ref _flushCounter); _subscribedTo = new Hashset<Type>(); } } } ================================================ FILE: Composite/Data/Caching/WeakRefCache.cs ================================================ using System; using System.Collections; using System.Collections.Generic; namespace Composite.Data.Caching { internal class WeakRefCache<K, V> : Cache where V : class { private int _counter; public WeakRefCache(string name) : base(name) { } public WeakRefCache(string name, int maximumSize) : base(name, maximumSize) { } public V Get(K key) { var weakReference = base.Get(key) as WeakReference; return (weakReference != null ? weakReference.Target : null) as V; } public void Remove(K key) { base.Remove(key); } public void Add(K key, V value) { base.Add(key, new WeakReference(value)); // Cleaning-up "dead" references _counter++; if (_counter % 500 == 0) { foreach (K k in GetKeys()) { WeakReference weakRef = Get(k) as WeakReference; if (weakRef != null && !weakRef.IsAlive) { Remove(k); } } } } public IEnumerable<K> GetKeys() { lock(_syncRoot) { ICollection keys = _table.Keys; K[] result = new K[keys.Count]; keys.CopyTo(result, 0); return result; } } } } ================================================ FILE: Composite/Data/CachingAttribute.cs ================================================ using System; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = true)] public sealed class CachingAttribute : Attribute { /// <exclude /> public CachingAttribute(CachingType cachingType) { this.CachingType = cachingType; } /// <exclude /> public CachingType CachingType { get; private set; } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum CachingType { /// <exclude /> Full, /// <exclude /> None } } ================================================ FILE: Composite/Data/CodeGeneratedAttribute.cs ================================================ using System; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = true)] public sealed class CodeGeneratedAttribute : Attribute { /// <exclude /> public CodeGeneratedAttribute() { } } } ================================================ FILE: Composite/Data/DataAssociationAttribute.cs ================================================ using System; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Interface, AllowMultiple = true, Inherited = true)] public sealed class DataAssociationAttribute : Attribute { /// <exclude /> public DataAssociationAttribute(Type associatedInterfaceType, string foreignKeyPropertyName, DataAssociationType dataAssociationType) { this.AssociatedInterfaceType = associatedInterfaceType; this.ForeignKeyPropertyName = foreignKeyPropertyName; this.AssociationType = dataAssociationType; } /// <exclude /> public Type AssociatedInterfaceType { get; private set; } /// <exclude /> public string ForeignKeyPropertyName { get; private set; } /// <exclude /> public DataAssociationType AssociationType { get; private set; } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum DataAssociationType { /// <exclude /> None = 0, /// <exclude /> Aggregation = 1, /// <exclude /> Composition = 2 } } ================================================ FILE: Composite/Data/DataAttributeFacade.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.Core; using Composite.Core.Collections.Generic; using Composite.C1Console.Events; using Composite.Core.Linq; using Composite.Core.ResourceSystem; using Composite.Core.Types; using Composite.Data.Types; namespace Composite.Data { /// <summary> /// This facade is used to obtain attribute informations for IData's and IData subinterface types /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DataAttributeFacade { private static ResourceLocker<Resources> _resourceLocker = new ResourceLocker<Resources>(new Resources(), Resources.Initialize, false); static DataAttributeFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } /// <exclude /> public static bool IsAutoUpdateble(this IData data) { Verify.ArgumentNotNull(data, "data"); return IsAutoUpdateble(data.DataSourceId.InterfaceType); } /// <exclude /> public static bool IsAutoUpdateble(this Type interfaceType) { Verify.ArgumentNotNull(interfaceType, "interfaceType"); bool isAutoUpdateble; if (!_resourceLocker.Resources.InterfaceToAutoUpdatebleCache.TryGetValue(interfaceType, out isAutoUpdateble)) { isAutoUpdateble = interfaceType.GetCustomInterfaceAttributes<AutoUpdatebleAttribute>().Any(); _resourceLocker.Resources.InterfaceToAutoUpdatebleCache.Add(interfaceType, isAutoUpdateble); } return isAutoUpdateble; } /// <summary> /// Checks whether the specified type is a custom defined IData interface, which is not generated /// </summary> /// <param name="interfaceType"></param> /// <exclude /> internal static bool IsStaticDataType(this Type interfaceType) { return typeof (IData).IsAssignableFrom(interfaceType) && interfaceType.Assembly != typeof (IData).Assembly && !IsGenerated(interfaceType); } /// <exclude /> public static bool IsGenerated(this Type interfaceType) { Verify.ArgumentNotNull(interfaceType, "interfaceType"); bool isGenerated; var cache = _resourceLocker.Resources.InterfaceToGeneratedCache; if (cache.TryGetValue(interfaceType, out isGenerated)) { return isGenerated; } lock (cache) { if (cache.TryGetValue(interfaceType, out isGenerated)) { return isGenerated; } isGenerated = interfaceType.GetCustomInterfaceAttributes<CodeGeneratedAttribute>().Any(); cache.Add(interfaceType, isGenerated); } return isGenerated; } /// <exclude /> public static Guid GetImmutableTypeId(this IData data) { return GetImmutableTypeId(data.DataSourceId.InterfaceType); } /// <exclude /> public static Guid GetImmutableTypeId(this Type interfaceType) { Verify.ArgumentNotNull(interfaceType, "interfaceType"); Guid immutableTypeId; bool success = TryGetImmutableTypeId(interfaceType, out immutableTypeId); Verify.That(success, "No '{0}' defined on the type '{1}'", typeof(ImmutableTypeIdAttribute), interfaceType); return immutableTypeId; } /// <exclude /> public static bool TryGetImmutableTypeId(this Type interfaceType, out Guid immutableTypeId) { Verify.ArgumentNotNull(interfaceType, "interfaceType"); var interfaceToImmutableTypeIdCache = _resourceLocker.Resources.InterfaceToImmutableTypeIdCache; immutableTypeId = interfaceToImmutableTypeIdCache.GetOrAdd(interfaceType, type => { var attributes = type.GetCustomInterfaceAttributes<ImmutableTypeIdAttribute>().ToList(); return attributes.Count == 0 ? Guid.Empty : attributes[0].ImmutableTypeId; }); return immutableTypeId != Guid.Empty; } /// <exclude /> public static bool IsNotReferenceable(this IData data) { if (data == null) throw new ArgumentNullException("data"); return IsNotReferenceable(data.DataSourceId.InterfaceType); } /// <exclude /> public static bool IsNotReferenceable(this Type interfaceType) { Verify.ArgumentNotNull(interfaceType, "interfaceType"); var map = _resourceLocker.Resources.InterfaceToNotReferenceableCache; return map.GetOrAdd(interfaceType, type => type.GetCustomInterfaceAttributes<NotReferenceableAttribute>().Any()); } /// <exclude /> public static string GetLabel(this IData data) { if (data == null) { return _resourceLocker.Resources.UndefinedDataLableValue; } return data.GetLabel(true); } /// <exclude /> public static string GetLabel(this IData data, bool useForeignLabel) { if (data == null) { return _resourceLocker.Resources.UndefinedDataLableValue; } int foreignKeysExpanded = 0; MethodInfo methodInfo; while (true) { string undefinedLabelValue; string propertyName; GetLabelVisualizationMethodInfo(data, useForeignLabel, out methodInfo, out propertyName, out undefinedLabelValue); if (methodInfo == null) { return undefinedLabelValue; } if (propertyName != null) { data = data.GetReferenced(propertyName); foreignKeysExpanded++; if (data == null) { return string.Format(undefinedLabelValue, propertyName); } // checking if we have an endless recursion while calculating field titles if(foreignKeysExpanded > 10) { return string.Format(undefinedLabelValue, propertyName); } continue; } break; } object result = methodInfo.Invoke(data, null); if ((result != null) && !(result is string)) { return result.ToString(); } return (string)result; } private static void GetLabelVisualizationMethodInfo(IData data, bool useForeignLabel, out MethodInfo methodInfo, out string propertyName, out string undefinedLabelValue) { using (_resourceLocker.Locker) { undefinedLabelValue = _resourceLocker.Resources.UndefinedLableValue; KeyValuePair<MethodInfo, string> cachedValue; if (_resourceLocker.Resources.InterfaceTypeToLabelMethodInfoCache.TryGetValue(data.DataSourceId.InterfaceType, out cachedValue)) { methodInfo = cachedValue.Key; propertyName = cachedValue.Value; return; } PropertyInfo propertyInfo = GetLabelPropertyInfo(data); propertyName = null; if (useForeignLabel) { List<ForeignKeyAttribute> foreignKeyAttributes = propertyInfo.GetCustomAttributesRecursively<ForeignKeyAttribute>().ToList(); if (foreignKeyAttributes.Count > 0) { propertyName = propertyInfo.Name; IData foreignData = data.GetReferenced(propertyInfo.Name); if (foreignData == null) { undefinedLabelValue = string.Format(undefinedLabelValue, propertyInfo.Name); methodInfo = null; return; } propertyInfo = GetLabelPropertyInfo(foreignData); } } methodInfo = propertyInfo.GetGetMethod(); var cacheEntry = new KeyValuePair<MethodInfo, string>(methodInfo, propertyName); _resourceLocker.Resources.InterfaceTypeToLabelMethodInfoCache.Add(data.DataSourceId.InterfaceType, cacheEntry); } } private static PropertyInfo GetLabelPropertyInfo(IData data) { return GetLabelPropertyInfo(data.DataSourceId.InterfaceType); } /// <exclude /> public static PropertyInfo GetLabelPropertyInfo(this Type interfaceType) { List<LabelPropertyNameAttribute> list = interfaceType.GetCustomInterfaceAttributes<LabelPropertyNameAttribute>().ToList(); PropertyInfo propertyInfo = null; if (list.Count != 0) { propertyInfo = interfaceType.GetPropertiesRecursively(pi => pi.Name == list[0].PropertyName).FirstOrDefault(); } else { propertyInfo = interfaceType.GetPropertiesRecursively(pi => typeof(IData).IsAssignableFrom(pi.DeclaringType)).FirstOrDefault(); } if (propertyInfo == null) { throw new InvalidOperationException("No label property defined or property not found"); } return propertyInfo; } /// <exclude /> public static CachingType GetCachingType(Type interfaceType) { var map = _resourceLocker.Resources.InterfaceTypeToCachingTypeCache; return map.GetOrAdd(interfaceType, type => { var list = type.GetCustomInterfaceAttributes<CachingAttribute>().ToList(); return (list.Count == 0) ? CachingType.None : list[0].CachingType; }); } /// <exclude /> [Obsolete("Use GetDataReferenceProperties() instead ")] public static List<ForeignPropertyInfo> GetDataReferencePropertyInfoes(Type interfaceType) { return new List<ForeignPropertyInfo>(GetDataReferenceProperties(interfaceType)); } /// <exclude /> public static IReadOnlyList<ForeignPropertyInfo> GetDataReferenceProperties(Type interfaceType) { var map = _resourceLocker.Resources.InterfaceTypeToDataReferenceProperties; return map.GetOrAdd(interfaceType, type => { var foreignKeyProperies = new List<ForeignPropertyInfo>(); foreach (PropertyInfo propertyInfo in type.GetPropertiesRecursively()) { var attributes = propertyInfo.GetCustomAttributesRecursively<ForeignKeyAttribute>().ToList(); Verify.That(attributes.Count <= 1, "More than one '{0}' specified for the property named '{1}'", typeof (ForeignKeyAttribute), propertyInfo.Name); if (attributes.Count == 1) { var attr = attributes[0]; if (attr.IsValid) { if (attr.InterfaceType == null) { throw new InvalidOperationException( $"Null argument is not allowed for the attribute '{typeof (ForeignKeyAttribute)}' on the property '{propertyInfo}'"); } if (!typeof (IData).IsAssignableFrom(attr.InterfaceType)) { throw new InvalidOperationException( $"The argument should inherit the type '{typeof (IData)}' for the attribute '{typeof (ForeignKeyAttribute)}' on the property '{propertyInfo}'"); } if (attr.IsNullReferenceValueSet) { foreignKeyProperies.Add(new ForeignPropertyInfo( propertyInfo, attr.InterfaceType, attr.KeyPropertyName, attr.AllowCascadeDeletes, attr.NullReferenceValue, attr.NullReferenceValueType, attr.NullableString )); } else { foreignKeyProperies.Add(new ForeignPropertyInfo( propertyInfo, attr.InterfaceType, attr.KeyPropertyName, attr.AllowCascadeDeletes, attr.NullableString )); } } else { Log.LogWarning("DataAttributeFacade", "Ignoring unknown foreign key reference from type '{0}' to type '{1}'. ", type.FullName, attr.TypeManagerName); } } } return foreignKeyProperies; }); } /// <exclude /> public static IReadOnlyList<string> GetKeyPropertyNames(this Type interfaceType) { Verify.ArgumentNotNull(interfaceType, "interfaceType"); var map = _resourceLocker.Resources.InterfaceTypeToKeyPropertyNames; return map.GetOrAdd(interfaceType, type => (from kpn in type.GetCustomAttributesRecursively<KeyPropertyNameAttribute>() orderby kpn.Index select kpn.KeyPropertyName).ToList()); } /// <exclude /> public static IReadOnlyList<string> GetVersionKeyPropertyNames(this Type interfaceType) { Verify.ArgumentNotNull(interfaceType, "interfaceType"); var map = _resourceLocker.Resources.InterfaceTypeToVersionKeyPropertyNames; return map.GetOrAdd(interfaceType, type => (from kpn in type.GetCustomAttributesRecursively<VersionKeyPropertyNameAttribute>() orderby kpn.VersionKeyPropertyName select kpn.VersionKeyPropertyName).ToList()); } /// <exclude /> [Obsolete("Use GetKeyProperties() instead")] public static List<PropertyInfo> GetKeyPropertyInfoes(this IData data) { return GetKeyProperties(data); } /// <exclude /> public static List<PropertyInfo> GetKeyProperties(this IData data) { Verify.ArgumentNotNull(data, "data"); // Return type is List<PropertyInfo> for backward compatibility with the PackageCreator package return new List<PropertyInfo>(GetKeyProperties(data.DataSourceId.InterfaceType)); } /// <exclude /> [Obsolete("Use GetKeyProperties() instead")] public static List<PropertyInfo> GetKeyPropertyInfoes(this Type interfaceType) { return new List<PropertyInfo>(GetKeyProperties(interfaceType)); } /// <exclude /> public static IReadOnlyList<PropertyInfo> GetPhysicalKeyProperties(this Type interfaceType) { var versionKeyAttributes = interfaceType .GetCustomAttributesRecursively<VersionKeyPropertyNameAttribute>(); var versionProperties = versionKeyAttributes .Select(v => interfaceType.GetDataPropertyRecursively(v.VersionKeyPropertyName)); var keyProperties = GetKeyProperties(interfaceType); return keyProperties.Concat(versionProperties).ToList(); } /// <exclude /> public static IReadOnlyList<PropertyInfo> GetKeyProperties(this Type interfaceType) { Verify.ArgumentNotNull(interfaceType, "interfaceType"); if (!typeof(IData).IsAssignableFrom(interfaceType)) { throw new ArgumentException($"The specified type must inherit from '{typeof (IData)}"); } var map = _resourceLocker.Resources.InterfaceTypeToKeyPropertyInfo; return map.GetOrAdd(interfaceType, type => { var keyProperties = new List<PropertyInfo>(); List<PropertyInfo> properties = type.GetPropertiesRecursively(); foreach (string name in GetKeyPropertyNames(type)) { PropertyInfo propertyInfo = properties.FirstOrDefault(pi => pi.Name == name); Verify.IsNotNull(propertyInfo, "Type '{0}' declare (or inherit) a '{1}' with a name '{2}' that was not found as a property on the type.", type, typeof(KeyPropertyNameAttribute), name); keyProperties.Add(propertyInfo); } return keyProperties; }); } internal static PropertyInfo GetSingleKeyProperty(this Type interfaceType) { return interfaceType.GetKeyProperties().SingleOrException( "No key properties defined on data type '{0}'", "Multiple key proterties defined for data type '{0}'", interfaceType); } /// <exclude /> public static string GetTypeTitle(this IData data) { if (data == null) throw new ArgumentNullException("data"); return GetTypeTitle(data.DataSourceId.InterfaceType); } /// <exclude /> public static string GetTypeTitle(this Type interfaceType) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); if (!typeof(IData).IsAssignableFrom(interfaceType)) throw new ArgumentException($"The specified type must inherit from '{typeof (IData)}"); string title; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.InterfaceTypeToTypeTitle.TryGetValue(interfaceType, out title) == false) { List<TitleAttribute> attributes = interfaceType.GetCustomAttributesRecursively<TitleAttribute>().ToList(); if (attributes.Count == 0) { title = interfaceType.Name; } else if (attributes.Count == 1) { title = attributes[0].Title; } else { throw new InvalidOperationException( $"More than one '{typeof (TitleAttribute)}' defined on the type '{interfaceType}'"); } _resourceLocker.Resources.InterfaceTypeToTypeTitle.Add(interfaceType, title); } } return title; } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private sealed class Resources { public string UndefinedLableValue { get; set; } public string UndefinedDataLableValue { get; set; } public Dictionary<Type, bool> InterfaceToAutoUpdatebleCache { get; set; } public Dictionary<Type, bool> InterfaceToGeneratedCache { get; set; } public ConcurrentDictionary<Type, Guid> InterfaceToImmutableTypeIdCache { get; set; } public ConcurrentDictionary<Type, bool> InterfaceToNotReferenceableCache { get; set; } public Dictionary<Type, KeyValuePair<MethodInfo, string>> InterfaceTypeToLabelMethodInfoCache { get; set; } public ConcurrentDictionary<Type, CachingType> InterfaceTypeToCachingTypeCache { get; set; } public ConcurrentDictionary<Type, IReadOnlyList<ForeignPropertyInfo>> InterfaceTypeToDataReferenceProperties { get; set; } public ConcurrentDictionary<Type, IReadOnlyList<PropertyInfo>> InterfaceTypeToKeyPropertyInfo { get; set; } public Dictionary<Type, string> InterfaceTypeToTypeTitle { get; set; } public ConcurrentDictionary<Type, IReadOnlyList<string>> InterfaceTypeToKeyPropertyNames { get; set; } public ConcurrentDictionary<Type, IReadOnlyList<string>> InterfaceTypeToVersionKeyPropertyNames { get; set; } public static void Initialize(Resources resources) { resources.UndefinedLableValue = StringResourceSystemFacade.GetString("Composite.Plugins.GeneratedDataTypesElementProvider", "UndefinedLabelTemplate"); resources.UndefinedDataLableValue = StringResourceSystemFacade.GetString("Composite.Plugins.GeneratedDataTypesElementProvider", "UndefinedDataLavelTemplate"); resources.InterfaceToAutoUpdatebleCache = new Dictionary<Type, bool>(); resources.InterfaceToGeneratedCache = new Dictionary<Type, bool>(); resources.InterfaceToImmutableTypeIdCache = new ConcurrentDictionary<Type, Guid>(); resources.InterfaceToNotReferenceableCache = new ConcurrentDictionary<Type, bool>(); resources.InterfaceTypeToLabelMethodInfoCache = new Dictionary<Type, KeyValuePair<MethodInfo, string>>(); resources.InterfaceTypeToCachingTypeCache = new ConcurrentDictionary<Type, CachingType>(); resources.InterfaceTypeToDataReferenceProperties = new ConcurrentDictionary<Type, IReadOnlyList<ForeignPropertyInfo>>(); resources.InterfaceTypeToKeyPropertyInfo = new ConcurrentDictionary<Type, IReadOnlyList<PropertyInfo>>(); resources.InterfaceTypeToTypeTitle = new Dictionary<Type, string>(); resources.InterfaceTypeToKeyPropertyNames = new ConcurrentDictionary<Type, IReadOnlyList<string>>(); resources.InterfaceTypeToVersionKeyPropertyNames = new ConcurrentDictionary<Type, IReadOnlyList<string>>(); } } } } ================================================ FILE: Composite/Data/DataConnection.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Composite.Core.Implementation; namespace Composite.Data { /// <summary> /// Represents a connection to the C1 CMS data system. /// </summary> /// <example> /// Here is an example of how to use it /// <code> /// using (DataConnection connection = new DataConnection()) /// { /// var q = /// from d in connection.Get<IMyDataType>() /// where d.Name == "Foo" /// select d; /// } /// </code> /// </example> public class DataConnection : ImplementationContainer<DataConnectionImplementation>, IDisposable { //private ImplementationContainer<PageDataConnection> _pageDataConnection; private readonly ImplementationContainer<SitemapNavigator> _sitemapNavigator; private bool _disposed; /// <summary> /// Resolve service of a specific type that is attached to connection's data scope /// </summary> /// <param name="t"></param> /// <returns></returns> public object GetService(Type t) { return ImplementationFactory.CurrentFactory.ResolveService(t); } /// <summary> /// attach service to data connection /// </summary> /// <param name="service"></param> public void AddService(object service) { Implementation.DataScope.AddService(service); } /// <summary> /// disable all services in the data connection /// </summary> public void DisableServices() { Implementation.DataScope.DisableServices(); } /// <summary> /// Creates a new <see cref="DataConnection"/> instance inheriting the <see cref="Composite.Data.PublicationScope"/> /// and locale set on the call stack. When outside an existing scope this default to PublicationScope,Published and the /// default language on the website. You should use this constructure unless you need to force data to come from an alternative /// scope. <see cref="DataConnection"/> can be used to access the C1 CMS storage. /// </summary> /// <example> /// Here is an example of how to use it /// <code> /// using (DataConnection connection = new DataConnection()) /// { /// var q = /// from d in connection.Get<IMyDataType>() /// where d.Name == "Foo" /// select d; /// } /// </code> /// </example> public DataConnection() : base(() => ImplementationFactory.CurrentFactory.CreateDataConnection(null, null)) { CreateImplementation(); //_pageDataConnection = new ImplementationContainer<PageDataConnection>(() => new PageDataConnection()); _sitemapNavigator = new ImplementationContainer<SitemapNavigator>(() => new SitemapNavigator(this)); } /// <summary> /// Creates a new <see cref="DataConnection"/> instance with the given <paramref name="scope"/> /// and current (or default) locale. <see cref="DataConnection"/> can be used to access the C1 CMS storage. /// </summary> /// <param name="scope">The <see cref="Composite.Data.PublicationScope"/> data should be read from.</param> /// <example> /// Here is an example of how to use it /// <code> /// using (DataConnection connection = new DataConnection(PublicationScope.Published)) /// { /// var q = /// from d in connection.Get<IMyDataType>() /// where d.Name == "Foo" /// select d; /// } /// </code> /// </example> public DataConnection(PublicationScope scope) : base(() => ImplementationFactory.CurrentFactory.CreateDataConnection(scope, null)) { if ((scope < PublicationScope.Unpublished) || (scope > PublicationScope.Published)) throw new ArgumentOutOfRangeException("scope"); CreateImplementation(); //_pageDataConnection = new ImplementationContainer<PageDataConnection>(() => new PageDataConnection(scope)); _sitemapNavigator = new ImplementationContainer<SitemapNavigator>(() => new SitemapNavigator(this)); } /// <summary> /// Creates a new <see cref="DataConnection"/> instance with current or default <see cref="Composite.Data.PublicationScope"/> /// and the given <paramref name="locale"/>. <see cref="DataConnection"/> can be used to access the C1 CMS storage. /// </summary> /// <param name="locale">The desired locale. This should be one of the locale found in <see cref="Composite.Data.DataConnection.AllLocales"/></param> /// <example> /// Here is an example of how to use it /// <code> /// using (DataConnection connection = new DataConnection(new CultureInfo("da-DK"))) /// { /// var q = /// from d in connection.Get<IMyDataType>() /// where d.Name == "Foo" /// select d; /// } /// </code> /// </example> public DataConnection(CultureInfo locale) : base(() => ImplementationFactory.CurrentFactory.CreateDataConnection(null, locale)) { CreateImplementation(); //_pageDataConnection = new ImplementationContainer<PageDataConnection>(() => new PageDataConnection(locale)); _sitemapNavigator = new ImplementationContainer<SitemapNavigator>(() => new SitemapNavigator(this)); } /// <summary> /// Creates a new <see cref="DataConnection"/> instance with the given <paramref name="scope"/> /// and the given <paramref name="locale"/>. <see cref="DataConnection"/> can be used to access the C1 CMS storage. /// </summary> /// <param name="scope">The <see cref="Composite.Data.PublicationScope"/> data should be read from.</param> /// <param name="locale">The desired locale. This should be one of the locale found in <see cref="Composite.Data.DataConnection.AllLocales"/></param> /// <example> /// Here is an example of how to use it /// <code> /// using (DataConnection connection = new DataConnection(PublicationScope.Published, new CultureInfo("da-DK"))) /// { /// var q = /// from d in connection.Get<IMyDataType>() /// where d.Name == "Foo" /// select d; /// } /// </code> /// </example> public DataConnection(PublicationScope scope, CultureInfo locale) : base(() => ImplementationFactory.CurrentFactory.CreateDataConnection(scope, locale)) { if ((scope < PublicationScope.Unpublished) || (scope > PublicationScope.Published)) throw new ArgumentOutOfRangeException("scope"); CreateImplementation(); //_pageDataConnection = new ImplementationContainer<PageDataConnection>(() => new PageDataConnection(scope, locale)); _sitemapNavigator = new ImplementationContainer<SitemapNavigator>(() => new SitemapNavigator(this)); } /// <summary> /// Returns an IQueryable of the given IData interface. /// If no storage supports the given IData interface, an exception is thrown. /// </summary> /// <example> /// <code> /// using (DataConnection connection = new DataConnection()) /// { /// var q = /// from d in connection.Get<IMyDataType>() /// where d.Name == "Foo" /// select d; /// } /// </code> /// </example> /// <typeparam name="TData">An IData interface</typeparam> /// <returns>Returns an IQueryable of the given IData interface for further querying</returns> public IQueryable<TData> Get<TData>() where TData : class, IData { return this.Implementation.Get<TData>(); } /// <summary> /// Adds the <typeparamref name="TData"/> instance to the default C1 storage. /// If the storage does not exist, then one is created. /// This method triggers the events OnBeforeAdd and OnAfterAdd for the item <paramref name="item"/>. /// </summary> /// <example> /// <code> /// using (DataConnection connection = new DataConnection()) /// { /// IMyDataType myDataType = DataConnection.New<IMyDataType>(); /// myDataType.Name = "John Doe"; /// myDataType = connection.Add<IMyDataType>(myDataType); /// /// // Note that the reassigned of myDataType is important here /// // if its used for an later update. /// /// myDataType.Name = "Jane Doe"; /// connection.Update<IMyDataType>(myDataType); /// } /// </code> /// </example> /// <typeparam name="TData">An IData interface</typeparam> /// <param name="item">The data item to add</param> /// <returns>The newly added data item. Note: This could differ from the <paramref name="item"/></returns> public TData Add<TData>(TData item) where TData : class, IData { return this.Implementation.Add<TData>(item); } /// <summary> /// Adds the <typeparamref name="TData"/> instances to the default C1 storage. /// If the storage does not exist, then one is created. /// This method triggers the events OnBeforeAdd and OnAfterAdd for each item in <paramref name="items"/> /// </summary> /// <example> /// <code> /// using (DataConnection connection = new DataConnection()) /// { /// List<IMyDataType> items = new List<IMyDataType>(); /// /// for (int i = 0; i < 10; i++) /// { /// IMyDataType myDataType = DataConnection.New<IMyDataType>(); /// myDataType.Name = "John Doe"; /// myDataType.Number = i; /// items.Add(myDataType); /// } /// /// connection.Add<IMyDataType>(items); /// } /// </code> /// </example> /// <typeparam name="TData">An IData interface</typeparam> /// <param name="items">The data items to add</param> /// <returns>The newly added data items. Note: These could differ from the items in <paramref name="items"/></returns> public IList<TData> Add<TData>(IEnumerable<TData> items) where TData : class, IData { return this.Implementation.Add<TData>(items); } /// <summary> /// Updates the given <typeparamref name="TData"/> instance in the C1 storage. /// If any property values has been changed, these would be saved into the storage. /// This method triggers the events OnBeforeUpdate and OnAfterUpdate for the item <paramref name="item"/> /// </summary> /// <example> /// <code> /// using (DataConnection connection = new DataConnection()) /// { /// IMyDataType myDataType = /// (from d in connection.Get<IMyDataType>() /// where d.Name == "Foo" /// select d).First(); /// /// myDataType.Name = "Bar"; /// /// connection.Update<IMyDataType>(myDataType); /// } /// </code> /// </example> /// <typeparam name="TData">An IData interface</typeparam> /// <param name="item">The item to update in the C1 storage</param> public void Update<TData>(TData item) where TData : class, IData { this.Implementation.Update<TData>(item); } /// <summary> /// Updates the geven <typeparamref name="TData"/> instances in the C1 storage. /// If any property values in any of the <typeparamref name="TData"/> instances, these would be saved into the storage. /// This method triggers the events OnBeforeUpdate and OnAfterUpdate for each item in <paramref name="items"/> /// </summary> /// <example> /// <code> /// using (DataConnection connection = new DataConnection()) /// { /// IEnumerable<IMyDataType> myDataTypes = /// from d in connection.Get<IMyDataType>() /// where d.Value > 10 /// select d; /// /// foreach (IMyDataType in myDataTypes) /// { /// myDataType.Value += 10; /// } /// /// connection.Update<IMyDataType>(myDataTypes); /// } /// </code> /// </example> /// <typeparam name="TData">An IData interface</typeparam> /// <param name="items">The items to update in the C1 storage</param> public void Update<TData>(IEnumerable<TData> items) where TData : class, IData { this.Implementation.Update<TData>(items); } /// <summary> /// Deletes the given <typeparamref name="TData"/> instance permently from the C1 storage. /// This method triggers the event OnDeleted for the item <paramref name="item"/> /// </summary> /// <example> /// <code> /// using (DataConnection connection = new DataConnection()) /// { /// IMyDataType myDataType = /// (from d in connection.Get<IMyDataType>() /// where d.Name == "Foo" /// select d).First(); /// /// /// connection.Delete<IMyDataType>(myDataType); /// } /// </code> /// </example> /// <typeparam name="TData">An IData interface</typeparam> /// <param name="item">The item to delete</param> public void Delete<TData>(TData item) where TData : class, IData { this.Implementation.Delete<TData>(item); } /// <summary> /// Deletes the given <typeparamref name="TData"/> instances permently from the C1 storage. /// This method triggers the event OnDeleted for each item in <paramref name="items"/> /// </summary> /// <example> /// <code> /// using (DataConnection connection = new DataConnection()) /// { /// IMyDataType myDataTypes = /// from d in connection.Get<IMyDataType>() /// where d.Name == "Foo" /// select d; /// /// /// connection.Delete<IMyDataType>(myDataTypes); /// } /// </code> /// </example> /// <typeparam name="TData">An IData interface</typeparam> /// <param name="items">The items to delete</param> public void Delete<TData>(IEnumerable<TData> items) where TData : class, IData { this.Implementation.Delete<TData>(items); } /// <summary> /// Create a new <typeparamref name="TData"/> that can be added using <see cref="Composite.Data.DataConnection.Add<TData>(TData)"/>. /// This method triggers the event OnNew for the return value of the method. /// </summary> /// <example> /// Here is an example of how to create a new IData instance and add it to the C1 storage. /// <code> /// using (DataConnection connection = new DataConnection()) /// { /// IMyDataType myDataType = DataConnection.New<IMyDataType>(); /// myDataType.Name = "John Doe"; /// connection.Add<IMyDataType>(myDataType); /// } /// </code> /// </example> /// <typeparam name="TData">An IData interface</typeparam> /// <returns>Returns a new instance of the <typeparamref name="TData"/></returns> public static TData New<TData>() where TData : class, IData { return ImplementationFactory.CurrentFactory.StatelessDataConnection.New<TData>(); } /// <summary> /// Create a new <typeparamref name="TData"/> that can be added using <see cref="Composite.Data.DataConnection.Add<TData>(TData)"/>. /// This method triggers the event OnNew for the return value of the method. /// </summary> /// Here is an example of how to create a new IData instance and add it to the C1 storage. /// <example> /// <code> /// using (DataConnection connection = new DataConnection()) /// { /// IMyDataType myDataType = connection.CreateNew<IMyDataType>(); /// myDataType.Name = "John Doe"; /// connection.Add<IMyDataType>(myDataType); /// } /// </code> /// </example> /// <typeparam name="TData">An IData interface</typeparam> /// <returns>Returns a new instance of the <typeparamref name="TData"/></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This is want we want")] public TData CreateNew<TData>() where TData : class, IData { return ImplementationFactory.CurrentFactory.StatelessDataConnection.New<TData>(); } /// <summary> /// The current publication scope. /// </summary> public PublicationScope CurrentPublicationScope { get { return this.Implementation.CurrentPublicationScope; } } /// <summary> /// The current locale. /// </summary> public CultureInfo CurrentLocale { get { return this.Implementation.CurrentLocale; } } /// <summary> /// All locales added to C1. /// </summary> /// <example> /// Here is an example of how to enumerate all locales added to C1. /// <code> /// foreach (CultureInfo locale in DataConnection.Locales) /// { /// // Use the locale /// } /// </code> /// </example> public static IEnumerable<CultureInfo> AllLocales { get { return ImplementationFactory.CurrentFactory.StatelessDataConnection.AllLocales; } } ///// <summary> ///// A PageDataConnection instanse. See <see cref="Composite.Data.PageDataConnection"/> ///// </summary> //public PageDataConnection PageDataConnection //{ // get // { // return _pageDataConnection.Implementation; // } //} /// <summary> /// A SitemapNavigator instance. See <see cref="Composite.Data.SitemapNavigator"/> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Sitemap")] public SitemapNavigator SitemapNavigator { get { return _sitemapNavigator.Implementation; } } /// <exclude /> public void Dispose() { Dispose(true); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// <exclude /> ~DataConnection() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); Dispose(false); } #endif /// <exclude /> protected virtual void Dispose(bool disposing) { if (!disposing) return; if (_disposed) { throw new ObjectDisposedException(nameof(DataConnection)); } this.DisposeImplementation(); _sitemapNavigator.Implementation.DisposeImplementation(); _disposed = true; } } } ================================================ FILE: Composite/Data/DataEntityToken.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Composite.C1Console.Security; using Composite.Core.Types; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Composite.Data { /// <summary> /// EntityToken that represents a C1 Data item. EntityToken is used through out C1 CMS to describe artifacts that can have security settings and be navigated and this class make it easy /// to move between data items and EntityToken. /// </summary> [SecurityAncestorProvider(typeof(DataSecurityAncestorProvider))] [JsonObject(MemberSerialization.OptIn)] public sealed class DataEntityToken : EntityToken { private IData _data; private bool _dataInitialized; private string _serializedDataSourceId; private string _serializedId; private string _serializedVersionId; private string _serializedInterfaceType; private Type _interfaceType; private DataSourceId _dataSourceId; internal DataEntityToken(IData data) { Verify.ArgumentNotNull(data, "data"); _data = data; _dataInitialized = true; _serializedDataSourceId = null; _dataSourceId = _data.DataSourceId; Verify.ArgumentCondition(_dataSourceId != null, "data", "DataSourceId can not be null"); _interfaceType = _dataSourceId.InterfaceType; } private DataEntityToken(string serializedDataSourceId) { _data = null; _dataInitialized = false; _serializedDataSourceId = serializedDataSourceId; _dataSourceId = null; } [JsonConstructor] private DataEntityToken(JRaw dataSourceId) { _data = null; _dataInitialized = false; _serializedDataSourceId = dataSourceId.Value.ToString(); _dataSourceId = null; } /// <exclude /> public override string Type { get { if (_serializedInterfaceType == null) { _serializedInterfaceType = TypeManager.SerializeType(this.DataSourceId.InterfaceType); } return _serializedInterfaceType; } } /// <exclude /> public override string Source => this.DataSourceId.ProviderName; /// <exclude /> public override string Id => this.SerializedId; /// <exclude /> public override string VersionId => this.SerializedVersionId; /// <exclude /> public override bool IsValid() => this.Data != null; /// <exclude /> public Type InterfaceType { get { if (_interfaceType == null) { _interfaceType = _dataSourceId != null ? _dataSourceId.InterfaceType : TypeManager.TryGetType(this.Type); } return _interfaceType; } } /// <summary> /// The <see cref="Composite.Data.DataSourceId"/> for the data object. /// </summary> public DataSourceId DataSourceId { get { if (_dataSourceId == null) { var dataSourceId = DataSourceId.Deserialize(_serializedDataSourceId); _dataSourceId = dataSourceId; _interfaceType = dataSourceId.InterfaceType; } return _dataSourceId; } } /// <exclude /> public override string Serialize() { return this.SerializedDataSourceId; } /// <exclude /> public static EntityToken Deserialize(string serializedData) { return new DataEntityToken(serializedData); } /// <summary> /// Retrieve the data object. Cast this to the expected IData interface to access the data fields. /// </summary> public IData Data { get { if (!_dataInitialized) { try { DataSourceId dataSourceId; if (!DataSourceId.TryDeserialize(this.SerializedDataSourceId, out dataSourceId)) { return null; } _data = DataFacade.GetDataFromDataSourceId(dataSourceId); } catch (Exception) { // Ignore exception - invalid data source id == no data } finally { _dataInitialized = true; } } return _data; } } /// <exclude /> public override void OnGetPrettyHtml(EntityTokenHtmlPrettyfier prettifier) { prettifier.OnWriteId = (token, helper) => { IDataId dataId = DataIdSerializer.Deserialize(this.Id, this.VersionId); var sb = new StringBuilder() .Append("<b>DataId</b><br />") .Append($"<b>Type:</b> {dataId.GetType()}<br />"); foreach (PropertyInfo propertyInfo in dataId.GetType().GetPropertiesRecursively()) { sb.Append($"<b>{propertyInfo.Name}:</b> {propertyInfo.GetValue(dataId, null)}<br />"); } helper.AddFullRow(new [] { "<b>Id</b>", sb.ToString() }); }; } [JsonProperty(PropertyName = "dataSourceId")] private JRaw rawSerializedDataSourceId => new JRaw(_serializedDataSourceId); private string SerializedDataSourceId { get { if (_serializedDataSourceId == null) { _serializedDataSourceId = this.Data.DataSourceId.Serialize(); } return _serializedDataSourceId; } } private string SerializedId { get { if (_serializedId == null) { var keyPropertyNames = GetVersionKeyPropertyNames().Any() ? GetKeyPropertyNames() : null; _serializedId = this.DataSourceId.DataId.Serialize(keyPropertyNames); } return _serializedId; } } private string SerializedVersionId { get { if (_serializedVersionId == null) { var versionKeyPropertyNames = GetVersionKeyPropertyNames(); _serializedVersionId = versionKeyPropertyNames.Any() ? this.DataSourceId.DataId.Serialize(versionKeyPropertyNames) : string.Empty; } return _serializedVersionId; } } private IEnumerable<string> GetKeyPropertyNames() { return this.InterfaceType.GetCustomAttributesRecursively<KeyPropertyNameAttribute>() .Select(f => f.KeyPropertyName); } private IEnumerable<string> GetVersionKeyPropertyNames() { return this.InterfaceType.GetCustomAttributesRecursively<VersionKeyPropertyNameAttribute>() .Select(f => f.VersionKeyPropertyName); } } } ================================================ FILE: Composite/Data/DataEntityTokenExtensions.cs ================================================ using System; using System.Globalization; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DataEntityTokenExtensions { /// <exclude /> public static DataEntityToken GetDataEntityToken(this IData data) { if (data == null) throw new ArgumentNullException("data"); return new DataEntityToken(data); } } } ================================================ FILE: Composite/Data/DataEventArgs.cs ================================================ using System; using Composite.Core.Extensions; namespace Composite.Data { /// <summary> /// This class contains information for data events. See also <see cref="Composite.Data.StoreEventArgs"/>. /// </summary> public class DataEventArgs : EventArgs { private readonly Type _dataType; private readonly IData _data; /// <summary> /// </summary> /// <param name="dataType"></param> /// <param name="data"></param> /// <exclude /> internal DataEventArgs(Type dataType, IData data) { _dataType = dataType; _data = data; } /// <summary> /// This is the data item that is the subject of the event fired. /// </summary> /// <example> /// <code> /// void MyMethod() /// { /// DataEvents<IMyDataType>().OnBeforeAdd += new DataEventHandler(DataEvents_OnBeforeAdd); /// /// using (DataConnection connection = new DataConnection()) /// { /// IMyDataType myDataType = DataConnection.New<IMyDataType>(); /// myDataType.Name = "Foo"; /// /// connection.Add<IMyDataType>(myDataType); // This will fire the event! /// } /// } /// /// /// void DataEvents_OnBeforeAdd(object sender, DataEventArgs dataEventArgs) /// { /// IData myData = dataEventArgs.Data; // This will be the myDataType instance just created /// } /// </code> /// </example> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "We had to be backwards compatible")] public IData Data { get { return _data; } } /// <summary> /// This is the type of the data item that is the subject of the event fired. /// </summary> /// <example> /// <code> /// void MyMethod() /// { /// DataEvents<IMyDataType>().OnBeforeAdd += new DataEventHandler(DataEvents_OnBeforeAdd); /// /// using (DataConnection connection = new DataConnection()) /// { /// IMyDataType myDataType = DataConnection.New<IMyDataType>(); /// myDataType.Name = "Foo"; /// /// connection.Add<IMyDataType>(myDataType); // This will fire the event! /// } /// } /// /// /// void DataEvents_OnBeforeAdd(object sender, DataEventArgs dataEventArgs) /// { /// Type type = dataEventArgs.DataType; // This will be the type of myDataType instance. E.i. IMyDataType /// } /// </code> /// </example> public Type DataType { get { return _dataType; } } /// <summary> /// This is the data item that is the subject of the event fired. /// </summary> /// <example> /// <code> /// void MyMethod() /// { /// DataEvents<IMyDataType>().OnBeforeAdd += new DataEventHandler(DataEvents_OnBeforeAdd); /// /// using (DataConnection connection = new DataConnection()) /// { /// IMyDataType myDataType = DataConnection.New<IMyDataType>(); /// myDataType.Name = "Foo"; /// /// connection.Add<IMyDataType>(myDataType); // This will fire the event! /// } /// } /// /// /// void DataEvents_OnBeforeAdd(DataEventArgs dataEventArgs) /// { /// IMyDataType myDataType = dataEventArgs.GetData<IMyDataType>(); // This will be the myDataType instance just created /// } /// </code> /// </example> /// <typeparam name="TData">An IData interface</typeparam> /// <returns>Returns a casted version of the data item that is the suvject of the event fired.</returns> public TData GetData<TData>() where TData : IData { if (_dataType.IsAssignableFrom(typeof(TData)) == false) { throw new ArgumentException("TData is of wrong type ('{0}'). Data type is '{1}'".FormatWith(typeof(TData), _dataType)); } return (TData)_data; } } } ================================================ FILE: Composite/Data/DataEventHandler.cs ================================================  namespace Composite.Data { /// <summary> /// The event handle type for detailed data change events which fire in-process. See also /// </summary> /// <param name="sender"></param> /// <param name="dataEventArgs"></param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Justification = "We had to be backwards compatible")] public delegate void DataEventHandler(object sender, DataEventArgs dataEventArgs); } ================================================ FILE: Composite/Data/DataEventSystemFacade.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using Composite.C1Console.Events; using Composite.Core.Caching; using Composite.Core.Extensions; using Composite.Core.Types; using Subscription = Composite.Core.Types.Pair<System.Delegate, bool>; using Subscriptions = Composite.Core.Collections.Generic.Hashtable<System.Type, System.Collections.Generic.List<Composite.Core.Types.Pair<System.Delegate, bool>>>; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class DataMoveEventArgs : DataEventArgs { internal DataMoveEventArgs(Type dataType, IData data, DataScopeIdentifier targetDataScopeIdentifier) : base(dataType, data) { this.TargetDataScopeIdentifier = targetDataScopeIdentifier; } /// <exclude /> public DataScopeIdentifier TargetDataScopeIdentifier { get; private set; } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DataEventSystemFacade { /// <exclude /> public delegate void DataAfterMoveDelegate(object sender, DataMoveEventArgs dataMoveEventArgs); private static readonly Subscriptions _dataBeforeAddEventDictionary = new Subscriptions(); private static readonly Subscriptions _dataAfterAddEventDictionary = new Subscriptions(); private static readonly Subscriptions _dataBeforeUpdateEventDictionary = new Subscriptions(); private static readonly Subscriptions _dataAfterUpdateEventDictionary = new Subscriptions(); private static readonly Subscriptions _dataDeletedEventDictionary = new Subscriptions(); private static readonly Subscriptions _dataAfterBuildNewEventDictionary = new Subscriptions(); private static readonly Subscriptions _storeChangedEventDictionary = new Subscriptions(); private static readonly object _collectionAccesslock = new object(); /// <exclude /> static DataEventSystemFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } private static void Add(this Subscriptions collection, Type dataType, Delegate callback, bool flushPersistent) { Verify.ArgumentNotNull(callback, "callback"); Add(collection, dataType, new Subscription(callback, flushPersistent)); } private static void Add(this Subscriptions collection, Type dataType, Subscription subscription) { Verify.ArgumentNotNull(collection, "collection"); Verify.ArgumentNotNull(dataType, "dataType"); Verify.ArgumentNotNull(subscription, "subscription"); Verify.ArgumentCondition(typeof (IData).IsAssignableFrom(dataType), "dataType", "dataType does not inherit the type '{0}'".FormatWith(typeof (IData))); lock(_collectionAccesslock) { if(!collection.ContainsKey(dataType)) { collection.Add(dataType, new List<Subscription>()); } collection[dataType].Add(subscription); } } private static void Remove(this Subscriptions collection, Type dataType, Delegate callback) { Verify.ArgumentCondition(typeof (IData).IsAssignableFrom(dataType), "dataType", "dataType does not inherit the type '{0}'".FormatWith(typeof (IData))); if(!collection.ContainsKey(dataType)) { return; } var list = collection[dataType]; lock (_collectionAccesslock) { for (int i = list.Count - 1; i >= 0; i--) { if (list[i].First == callback) { list.RemoveAt(i); return; } } } } private delegate void ExecuteCallback<T>(T callback); private static void Fire<DelegateType>(this Subscriptions collection, Type dataType, ExecuteCallback<DelegateType> runner) where DelegateType : class { Verify.ArgumentNotNull(collection, "collection"); Verify.ArgumentNotNull(dataType, "dataType"); Verify.ArgumentNotNull(runner, "runner"); if (SuppressEventScope.IsEnabled) { return; } List<Type> types = GetTypesToFire(dataType); foreach (Type type in types) { Pair<Delegate, bool>[] subscriptions = null; if (collection.ContainsKey(type)) { lock (_collectionAccesslock) { if (collection.ContainsKey(type)) { subscriptions = collection[type].ToArray(); } } } if (subscriptions == null) continue; foreach (Pair<Delegate, bool> subscription in subscriptions) { var callback = subscription.First as DelegateType; Verify.That(callback != null, "Wrong delegate type"); runner(callback); } } } /// <exclude /> public static void SubscribeToDataBeforeAdd<T>(DataEventHandler dataBeforeAddDelegate, bool flushPersistent) where T : IData { SubscribeToDataBeforeAdd(typeof(T), dataBeforeAddDelegate, flushPersistent); } /// <exclude /> [Obsolete("Use SubscribeToDataBeforeAdd<T>(DataEventHandler, bool)")] public static void SubscribeToDataBeforeAdd<T>(DataEventHandler dataBeforeAddDelegate) where T : IData { SubscribeToDataBeforeAdd(typeof(T), dataBeforeAddDelegate); } /// <exclude /> [Obsolete("Use SubscribeToDataBeforeAdd(Type, DataEventHandler, bool)")] public static void SubscribeToDataBeforeAdd(Type dataType, DataEventHandler dataBeforeAddDelegate) { SubscribeToDataBeforeAdd(dataType, dataBeforeAddDelegate, false); } /// <exclude /> public static void SubscribeToDataBeforeAdd(Type dataType, DataEventHandler dataBeforeAddDelegate, bool flushPersistent) { Verify.ArgumentNotNull(dataType, "dataType"); Verify.ArgumentNotNull(dataBeforeAddDelegate, "dataBeforeAddDelegate"); _dataBeforeAddEventDictionary.Add(dataType, new Subscription(dataBeforeAddDelegate, flushPersistent)); } /// <exclude /> public static void UnsubscribeToDataBeforeAdd(Type dataType, DataEventHandler dataBeforeAddDelegate) { Verify.ArgumentNotNull(dataType, "dataType"); Verify.ArgumentNotNull(dataBeforeAddDelegate, "dataBeforeAddDelegate"); _dataBeforeAddEventDictionary.Remove(dataType, dataBeforeAddDelegate); } /// <exclude /> public static void SubscribeToDataAfterAdd(Type dataType, DataEventHandler dataAfterAddDelegate, bool flushPersistent) { Verify.ArgumentNotNull(dataType, "dataType"); Verify.ArgumentNotNull(dataAfterAddDelegate, "dataAfterAddDelegate"); _dataAfterAddEventDictionary.Add(dataType, dataAfterAddDelegate, flushPersistent); } /// <exclude /> [Obsolete("Use SubscribeToDataAfterAdd(Type, DataEventHandler, bool)")] public static void SubscribeToDataAfterAdd(Type dataType, DataEventHandler dataAfterAddDelegate) { SubscribeToDataAfterAdd(dataType, dataAfterAddDelegate, false); } /// <exclude /> public static void SubscribeToDataAfterAdd<T>(DataEventHandler dataAfterAddDelegate, bool flushPersistent) { SubscribeToDataAfterAdd(typeof(T), dataAfterAddDelegate, flushPersistent); } /// <exclude /> [Obsolete("Use SubscribeToDataAfterAdd<T>(DataEventHandler, bool)")] public static void SubscribeToDataAfterAdd<T>(DataEventHandler dataAfterAddDelegate) where T : IData { SubscribeToDataAfterAdd(typeof(T), dataAfterAddDelegate); } /// <exclude /> public static void SubscribeToStoreChanged(Type dataType, StoreEventHandler storeChangeDelegate, bool flushPersistent) { Verify.ArgumentNotNull(dataType, "dataType"); Verify.ArgumentNotNull(storeChangeDelegate, "storeChangeDelegate"); _storeChangedEventDictionary.Add(dataType, storeChangeDelegate, flushPersistent); } /// <exclude /> public static void SubscribeToStoreChanged<T>(StoreEventHandler storeChangeDelegate, bool flushPersistent) { SubscribeToStoreChanged(typeof(T), storeChangeDelegate, flushPersistent); } /// <exclude /> public static void UnsubscribeToDataAfterAdd(Type dataType, DataEventHandler dataAfterAddDelegate) { if (dataType == null) throw new ArgumentNullException("dataType"); if (dataAfterAddDelegate == null) throw new ArgumentNullException("dataAfterAddDelegate"); _dataAfterAddEventDictionary.Remove(dataType, dataAfterAddDelegate); } /// <exclude /> public static void UnsubscribeToStoreChanged(Type dataType, StoreEventHandler storeChangeDelegate) { Verify.ArgumentNotNull(dataType, "dataType"); Verify.ArgumentNotNull(storeChangeDelegate, "storeChangeDelegate"); _storeChangedEventDictionary.Remove(dataType, storeChangeDelegate); } /// <exclude /> [Obsolete("Use SubscribeToDataBeforeUpdate(Type, DataEventHandler, bool)")] public static void SubscribeToDataBeforeUpdate(Type dataType, DataEventHandler dataBeforeUpdateDelegate) { SubscribeToDataBeforeUpdate(dataType, dataBeforeUpdateDelegate, false); } /// <exclude /> public static void SubscribeToDataBeforeUpdate(Type dataType, DataEventHandler dataBeforeUpdateDelegate, bool flushPersistent) { _dataBeforeUpdateEventDictionary.Add(dataType, dataBeforeUpdateDelegate, flushPersistent); } /// <exclude /> [Obsolete("Use SubscribeToDataBeforeUpdate<T>(DataEventHandler, bool)")] public static void SubscribeToDataBeforeUpdate<T>(DataEventHandler dataBeforeUpdateDelegate) where T : IData { SubscribeToDataBeforeUpdate(typeof(T), dataBeforeUpdateDelegate); } /// <exclude /> public static void SubscribeToDataBeforeUpdate<T>(DataEventHandler dataBeforeUpdateDelegate, bool flushPersistent) where T : IData { SubscribeToDataBeforeUpdate(typeof(T), dataBeforeUpdateDelegate, flushPersistent); } /// <exclude /> public static void UnsubscribeToDataBeforeUpdate(Type dataType, DataEventHandler dataBeforeUpdateDelegate) { _dataBeforeUpdateEventDictionary.Remove(dataType, dataBeforeUpdateDelegate); } /// <exclude /> [Obsolete("Use SubscribeToDataAfterUpdate(Type, DataEventHandler, bool)")] public static void SubscribeToDataAfterUpdate(Type dataType, DataEventHandler dataAfterUpdateDelegate) { SubscribeToDataAfterUpdate(dataType, dataAfterUpdateDelegate, false); } /// <exclude /> public static void SubscribeToDataAfterUpdate(Type dataType, DataEventHandler dataAfterUpdateDelegate, bool flushPersistent) { _dataAfterUpdateEventDictionary.Add(dataType, dataAfterUpdateDelegate, flushPersistent); } /// <exclude /> [Obsolete("Use SubscribeToDataAfterUpdate<T>(DataEventHandler, bool)")] public static void SubscribeToDataAfterUpdate<T>(DataEventHandler dataAfterUpdateDelegate) where T : IData { SubscribeToDataAfterUpdate(typeof(T), dataAfterUpdateDelegate); } /// <exclude /> public static void SubscribeToDataAfterUpdate<T>(DataEventHandler dataAfterUpdateDelegate, bool flushPersistent) where T : IData { SubscribeToDataAfterUpdate(typeof(T), dataAfterUpdateDelegate, flushPersistent); } /// <exclude /> public static void UnsubscribeToDataAfterUpdate(Type dataType, DataEventHandler dataAfterUpdateDelegate) { _dataAfterUpdateEventDictionary.Remove(dataType, dataAfterUpdateDelegate); } /// <exclude /> [Obsolete("Use SubscribeToDataDeleted(Type, DataEventHandler, bool)")] public static void SubscribeToDataDeleted(Type dataType, DataEventHandler dataDeletedDelegate) { SubscribeToDataDeleted(dataType, dataDeletedDelegate, false); } /// <exclude /> public static void SubscribeToDataDeleted(Type dataType, DataEventHandler dataDeletedDelegate, bool flushPersistent) { _dataDeletedEventDictionary.Add(dataType, dataDeletedDelegate, flushPersistent); } /// <exclude /> [Obsolete("Use SubscribeToDataDeleted<T>(DataEventHandler, bool)")] public static void SubscribeToDataDeleted<T>(DataEventHandler dataDeletedDelegate) where T : IData { SubscribeToDataDeleted(typeof(T), dataDeletedDelegate); } /// <exclude /> public static void SubscribeToDataDeleted<T>(DataEventHandler dataDeletedDelegate, bool flushPersistent) where T : IData { SubscribeToDataDeleted(typeof(T), dataDeletedDelegate, flushPersistent); } /// <exclude /> public static void UnsubscribeToDataDeleted(Type dataType, DataEventHandler dataDeletedDelegate) { _dataDeletedEventDictionary.Remove(dataType, dataDeletedDelegate); } /// <exclude /> [Obsolete("Use SubscribeToDataAfterBuildNew(Type, DataEventHandler, bool)")] public static void SubscribeToDataAfterBuildNew(Type dataType, DataEventHandler dataAfterBuildNewDelegate) { SubscribeToDataAfterBuildNew(dataType, dataAfterBuildNewDelegate, false); } /// <exclude /> public static void SubscribeToDataAfterBuildNew(Type dataType, DataEventHandler dataAfterBuildNewDelegate, bool flushPersistent) { _dataAfterBuildNewEventDictionary.Add(dataType, dataAfterBuildNewDelegate, flushPersistent); } /// <exclude /> [Obsolete("Use SubscribeToDataAfterBuildNew<T>(DataEventHandler, bool)")] public static void SubscribeToDataAfterBuildNew<T>(DataEventHandler dataAfterBuildNewDelegate) where T : IData { SubscribeToDataAfterBuildNew(typeof(T), dataAfterBuildNewDelegate); } /// <exclude /> public static void SubscribeToDataAfterBuildNew<T>(DataEventHandler dataAfterBuildNewDelegate, bool flushPersistent) where T : IData { SubscribeToDataAfterBuildNew(typeof(T), dataAfterBuildNewDelegate, flushPersistent); } /// <exclude /> public static void UnsubscribeToDataAfterBuildNew(Type dataType, DataEventHandler dataAfterBuildNewDelegate) { _dataAfterBuildNewEventDictionary.Remove(dataType, dataAfterBuildNewDelegate); } /// <summary> /// Fire this when an external store has changed outside the process to notify subscribers to the StoreChangeEvent. /// </summary> /// <param name="dataType"></param> /// <param name="publicationScope"></param> /// <param name="locale"></param> public static void FireExternalStoreChangedEvent(Type dataType, PublicationScope publicationScope, CultureInfo locale) { FireStoreChangedEvent(dataType, publicationScope, locale, false); } internal static void FireDataBeforeAddEvent(Type dataType, IData data) { var args = new DataEventArgs(dataType, data); _dataBeforeAddEventDictionary.Fire <DataEventHandler>(dataType, callback => callback(null, args)); } internal static void FireDataBeforeAddEvent<T>(IData data) where T : IData { FireDataBeforeAddEvent(typeof(T), data); } internal static void FireDataAfterAddEvent(Type dataType, IData data) { var args = new DataEventArgs(dataType, data); _dataAfterAddEventDictionary.Fire<DataEventHandler>(dataType, callback => callback(null, args)); FireStoreChangedEvent(dataType, data); } /// <summary> /// Follow up event for intally fired events /// </summary> private static void FireStoreChangedEvent(Type dataType, IData data) { FireStoreChangedEvent(dataType, data.DataSourceId.DataScopeIdentifier.ToPublicationScope(), data.DataSourceId.LocaleScope, true); } /// <summary> /// Call this indirectly. Use FireStoreChangedEvent or FireExternalStoreChangedEvent above. /// </summary> private static void FireStoreChangedEvent(Type dataType, PublicationScope publicationScope, CultureInfo locale, bool dataEventsFired) { var args = new StoreEventArgs(dataType, publicationScope, locale, dataEventsFired); // switch to the scope where event is happening using (new DataConnection(publicationScope, locale)) { _storeChangedEventDictionary.Fire<StoreEventHandler>(dataType, callback => callback(null, args)); } } internal static void FireDataAfterAddEvent<T>(IData data) where T : IData { FireDataAfterAddEvent(typeof(T), data); } internal static void FireDataBeforeUpdateEvent(Type dataType, IData data) { var args = new DataEventArgs(dataType, data); _dataBeforeUpdateEventDictionary.Fire<DataEventHandler>(dataType, callback => callback(null, args)); } internal static void FireDataBeforeUpdateEvent<T>(IData data) where T : IData { FireDataBeforeUpdateEvent(typeof(T), data); } internal static void FireDataAfterUpdateEvent(Type dataType, IData data) { var args = new DataEventArgs(dataType, data); _dataAfterUpdateEventDictionary.Fire<DataEventHandler>(dataType, callback => callback(null, args)); FireStoreChangedEvent(dataType, data); } internal static void FireDataAfterUpdateEvent<T>(IData data) where T : IData { FireDataAfterUpdateEvent(typeof(T), data); } internal static void FireDataDeletedEvent(Type dataType, IData data) { var args = new DataEventArgs(dataType, data); _dataDeletedEventDictionary.Fire<DataEventHandler>(dataType, callback => callback(null, args)); FireStoreChangedEvent(dataType, data); } internal static void FireDataDeletedEvent<T>(IData data) where T : IData { FireDataDeletedEvent(typeof(T), data); } internal static void FireDataAfterBuildNewEvent(Type dataType, IData data) { var args = new DataEventArgs(dataType, data); _dataAfterBuildNewEventDictionary.Fire<DataEventHandler>(dataType, callback => callback(null, args)); } internal static void FireDataAfterBuildNewEvent<T>(IData data) where T : IData { FireDataAfterBuildNewEvent(typeof(T), data); } private static List<Type> GetTypesToFire(Type type) { var types = new List<Type>(); types.Add(type); foreach (Type superInterface in type.GetInterfaces()) { if (typeof(IData).IsAssignableFrom(superInterface)) { types.Add(superInterface); } } return types; } private static void OnFlushEvent(FlushEventArgs args) { // Removing all non flush-persistent subscriptions var dictionaries = new[] { _dataBeforeAddEventDictionary, _dataAfterAddEventDictionary, _dataBeforeUpdateEventDictionary, _dataAfterUpdateEventDictionary, _dataDeletedEventDictionary, _dataAfterBuildNewEventDictionary, _storeChangedEventDictionary }; foreach (var dictionary in dictionaries) { foreach (var subscrList in dictionary.GetValues()) { for (int i = subscrList.Count - 1; i >= 0; i--) { if (!subscrList[i].Second) { subscrList.RemoveAt(i); } } } } } private class SuppressEventScope: IDisposable { private readonly bool _active; public SuppressEventScope(bool active) { if (!active) return; _active = true; Counter(1); } private sealed class CounterContainer { public CounterContainer() { this.Counter = 0; } public int Counter { get; set; } } private static CounterContainer SuppressEventScopeCounter { get { return RequestLifetimeCache.GetCachedOrNew<CounterContainer>("SuppressEventScope:Counter"); } } public static bool IsEnabled { get { return Counter(0) > 0; } } /// <summary> /// Adds a value to counter, and returns result value. /// </summary> /// <param name="incrementValue">Value to be added.</param> /// <returns></returns> private static int Counter(int incrementValue) { CounterContainer counter = SuppressEventScopeCounter; counter.Counter += incrementValue; return counter.Counter; } #region IDisposable Members public void Dispose() { if(!_active) return; Counter(-1); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// <exclude /> ~SuppressEventScope() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif #endregion } /// <exclude /> public static IDisposable SuppressEvents { get { return new SuppressEventScope(true); } } } } ================================================ FILE: Composite/Data/DataEvents.cs ================================================ using Composite.Core.Implementation; using System; using System.Globalization; namespace Composite.Data { /// <summary> /// This class contains all the event fired by C1 CMS when changes are made to data items. /// /// Use <see cref="Composite.Data.DataEvents<TData>.OnStoreChanged"/> to catch any data change event, including events originating from other servers in a load balance setup /// or changes made directly to a store (which C1 CMS can detect). This event do not contain details about the specific data item changed and is raised after the fact. /// /// Use the more detailed operations to catch data events that happen in the current website process. The 'OnBefore' events enable you to manipulate data before they are stored. /// The 'OnAfter' events let you react to data changes in detail, for instance updating a cache. /// /// A combination of <see cref="Composite.Data.DataEvents<TData>.OnStoreChanged"/> and the detailed data events can be used to create a highly optimized cache. /// </summary> /// <example> /// <code> /// void MyMethod() /// { /// DataEvents<IMyDataType>.OnBeforeAdd += new DataEventHandler(DataEvents_OnBeforeAdd); /// DataEvents<IMyDataType>.OnStoreChanged += new StoreEventHandler(DataEvents_OnStoreChanged); /// /// using (DataConnection connection = new DataConnection()) /// { /// IMyDataType myDataType = DataConnection.New<IMyDataType>(); /// myDataType.Name = "Foo"; /// /// connection.Add<IMyDataType>(myDataType); // This will fire both of the the events in the local process! /// // if other servers share data store with this site they will see OnStoreChanged fire. /// } /// } /// /// /// void DataEvents_OnBeforeAdd(object sender, DataEventArgs dataEventArgs) /// { /// // here a minor update to the cache could be done (like adding info about the new element only). /// } /// /// /// void DataEvents_OnStoreChanged(object sender, StoreEventArgs storeEventArgs) /// { /// if (!storeEventArgs.DataEventsFired) /// { /// // an external update event happened - DataEvents_OnBeforeAdd not fired /// // here a complete cache flush could be done /// } /// } /// </code> /// </example> /// <typeparam name="TData">Data type to attach events to</typeparam> public static class DataEvents<TData> where TData : class, IData { /// <summary> /// This event is fired just before a data item is added to the C1 CMS data store. /// See <see cref="Composite.Data.DataConnection.Add<TData>(TData)"/> /// </summary> /// <example> /// <code> /// void MyMethod() /// { /// DataEvents<IMyDataType>.OnBeforeAdd += new DataEventHandler(DataEvents_OnBeforeAdd); /// /// using (DataConnection connection = new DataConnection()) /// { /// IMyDataType myDataType = DataConnection.New<IMyDataType>(); /// myDataType.Name = "Foo"; /// /// connection.Add<IMyDataType>(myDataType); // This will fire the event! /// } /// } /// /// /// void DataEvents_OnBeforeAdd(object sender, DataEventArgs dataEventArgs) /// { /// } /// </code> /// </example> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly", Justification = "We had to be backwards compatible")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "We had to be backwards compatible")] public static event DataEventHandler OnBeforeAdd { add { ImplementationFactory.CurrentFactory.CreateStatelessDataEvents<TData>().OnBeforeAdd += value; } remove { ImplementationFactory.CurrentFactory.CreateStatelessDataEvents<TData>().OnBeforeAdd -= value; } } /// <summary> /// This event is fired just after a data item has been added to the C1 CMS data store. /// See <see cref="Composite.Data.DataConnection.Add<TData>(TData)"/> /// </summary> /// <example> /// <code> /// void MyMethod() /// { /// DataEvents<IMyDataType>.OnAfterAdd += new DataEventHandler(DataEvents_OnAfterAdd); /// /// using (DataConnection connection = new DataConnection()) /// { /// IMyDataType myDataType = DataConnection.New<IMyDataType>(); /// myDataType.Name = "Foo"; /// /// connection.Add<IMyDataType>(myDataType); // This will fire the event! /// } /// } /// /// /// void DataEvents_OnAfterAdd(object sender, DataEventArgs dataEventArgs) /// { /// } /// </code> /// </example> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly", Justification = "We had to be backwards compatible")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "We had to be backwards compatible")] public static event DataEventHandler OnAfterAdd { add { ImplementationFactory.CurrentFactory.CreateStatelessDataEvents<TData>().OnAfterAdd += value; } remove { ImplementationFactory.CurrentFactory.CreateStatelessDataEvents<TData>().OnAfterAdd -= value; } } /// <summary> /// This event is fired just before a data item is updated in the C1 CMS data store. /// See <see cref="Composite.Data.DataConnection.Update<TData>(TData)"/> /// </summary> /// <example> /// <code> /// void MyMethod() /// { /// DataEvents<IMyDataType>.OnBeforeUpdate += new DataEventHandler(DataEvents_OnBeforeUpdate); /// /// using (DataConnection connection = new DataConnection()) /// { /// IMyDataType myDataType = /// (from item in connection.get<IMyDataType>() /// where item.Id == 1 /// select item).First(); /// /// myDataType.Name = "Foo"; /// /// connection.Update<IMyDataType>(myDataType); // This will fire the event! /// } /// } /// /// /// void DataEvents_OnBeforeUpdate(object sender, DataEventArgs dataEventArgs) /// { /// } /// </code> /// </example> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly", Justification = "We had to be backwards compatible")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "We had to be backwards compatible")] public static event DataEventHandler OnBeforeUpdate { add { ImplementationFactory.CurrentFactory.CreateStatelessDataEvents<TData>().OnBeforeUpdate += value; } remove { ImplementationFactory.CurrentFactory.CreateStatelessDataEvents<TData>().OnBeforeUpdate -= value; } } /// <summary> /// This event is fired just after a data item has been updated in the C1 CMS data store. /// See <see cref="Composite.Data.DataConnection.Update<TData>(TData)"/> /// </summary> /// <example> /// <code> /// void MyMethod() /// { /// DataEvents<IMyDataType>.OnAfterUpdate += new DataEventHandler(DataEvents_OnAfterUpdate); /// /// using (DataConnection connection = new DataConnection()) /// { /// IMyDataType myDataType = /// (from item in connection.get<IMyDataType>() /// where item.Id == 1 /// select item).First(); /// /// myDataType.Name = "Foo"; /// /// connection.Update<IMyDataType>(myDataType); // This will fire the event! /// } /// } /// /// /// void DataEvents_OnAfterUpdate(object sender, DataEventArgs dataEventArgs) /// { /// } /// </code> /// </example> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly", Justification = "We had to be backwards compatible")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "We had to be backwards compatible")] public static event DataEventHandler OnAfterUpdate { add { ImplementationFactory.CurrentFactory.CreateStatelessDataEvents<TData>().OnAfterUpdate += value; } remove { ImplementationFactory.CurrentFactory.CreateStatelessDataEvents<TData>().OnAfterUpdate -= value; } } /// <summary> /// This event is fired after a data item has been deleted from the C1 CMS data store. /// See <see cref="Composite.Data.DataConnection.Delete<TData>(TData)"/> /// </summary> /// <example> /// <code> /// void MyMethod() /// { /// DataEvents<IMyDataType>.OnDeleted+= new DataEventHandler(DataEvents_OnDeleted); /// /// using (DataConnection connection = new DataConnection()) /// { /// IMyDataType myDataType = /// (from item in connection.get<IMyDataType>() /// where item.Id == 1 /// select item).First(); /// /// connection.Delete<IMyDataType>(myDataType); // This will fire the event! /// } /// } /// /// /// void DataEvents_OnDeleted(object sender, DataEventArgs dataEventArgs) /// { /// } /// </code> /// </example> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly", Justification = "We had to be backwards compatible")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "We had to be backwards compatible")] public static event DataEventHandler OnDeleted { add { ImplementationFactory.CurrentFactory.CreateStatelessDataEvents<TData>().OnDeleted += value; } remove { ImplementationFactory.CurrentFactory.CreateStatelessDataEvents<TData>().OnDeleted -= value; } } /// <summary> /// This event is fired after changes has happened to the C1 CMS data store. This may be atomic actions or a larger change to the underlying /// data store. The <see cref="Composite.Data.StoreEventArgs"/> class describe the change in broad terms, including a flag indicating is detailed data /// event have been raised or not. /// /// You can use this event as a simple way to react to data changes (like clearing a cache) or you can mix this with atomic data events (add, delete, update) /// to make a build a more advanced cache. /// /// You should listen to this event in order to support scale out across multiple servers, since this event is meant to be signaled when changes happen /// on another server. In such situations detailed data events will not fire on other machines. /// </summary> /// <example> /// <code> /// void MyMethod() /// { /// DataEvents<IMyDataType>.OnStoreChanged+= new StoreEventHandler(DataEvents_OnStoreChanged); /// /// using (DataConnection connection = new DataConnection()) /// { /// IMyDataType myDataType = /// (from item in connection.get<IMyDataType>() /// where item.Id == 1 /// select item).First(); /// /// connection.Delete<IMyDataType>(myDataType); // This will fire the event! /// } /// } /// /// /// void DataEvents_OnStoreChanged(object sender, StoreEventArgs storeEventArgs) /// { /// } /// </code> /// </example> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly", Justification = "We had to be backwards compatible")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "We had to be backwards compatible")] public static event StoreEventHandler OnStoreChanged { add { ImplementationFactory.CurrentFactory.CreateStatelessDataEvents<TData>().OnStoreChanged += value; } remove { ImplementationFactory.CurrentFactory.CreateStatelessDataEvents<TData>().OnStoreChanged -= value; } } /// <summary> /// This event is fired just after a new data item is created. /// See <see cref="Composite.Data.DataConnection.New<TData>()"/> /// </summary> /// <example> /// <code> /// void MyMethod() /// { /// DataEvents<IMyDataType>.OnNew += new DataEventHandler(DataEvents_OnNew); /// /// IMyDataType myDataType = DataConnection.New<IMyDataType>(); // This will fire the event! /// } /// /// /// void DataEvents_OnNew(object sender, DataEventArgs dataEventArgs) /// { /// } /// </code> /// </example> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly", Justification = "We had to be backwards compatible")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "We had to be backwards compatible")] public static event DataEventHandler OnNew { add { ImplementationFactory.CurrentFactory.CreateStatelessDataEvents<TData>().OnNew += value; } remove { ImplementationFactory.CurrentFactory.CreateStatelessDataEvents<TData>().OnNew -= value; } } /// <summary> /// Fire the event that signals that data in an external store has changed. /// </summary> /// <remarks> /// You should NOT fire this event if you do data changes through the C1 CMS data API since events will already be handled for you in this case. /// /// Use this method if you are responsible for flushing cached data originating from a store not fully managed by the local website process. /// /// This could be data stored in a central database, where updates happened on another webserver and you wish to signal update events to other webservers running /// in a farm. This could also be a situation where you have a custom data provider reading data from some 3rd party system or data store. /// /// Calling this event will result in cache invalidation on all data of this particular type. /// /// Handlers listening to the <see cref="Composite.Data.DataEvents<TData>.OnStoreChanged"/> event will be called with a <see cref="Composite.Data.StoreEventArgs"/> /// instance indicating that data events has not been fired. This signals that detail cache management is not possible and a complete cache flush is required on structures /// depending on this data type. /// </remarks> /// <example> /// <code> /// void MyMethod() /// { /// DataEvents<IMyDataType>.FireExternalStoreChangeEvent(PublicationScope.Published, new CultureInfo("da-DK")); /// } /// </code> /// </example> public static void FireExternalStoreChangeEvent(PublicationScope publicationScope, CultureInfo locale) { ImplementationFactory.CurrentFactory.CreateStatelessDataEvents<TData>().FireExternalStoreChangeEvent(publicationScope, locale); } } } ================================================ FILE: Composite/Data/DataFacade.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading; using System.Transactions; using Composite.Core.Collections.Generic; using Composite.Core.Linq; using Composite.Data.Caching; using Composite.Data.Foundation; using Composite.C1Console.Events; using Composite.Data.Transactions; using Composite.Core.Types; using Composite.Data.Types; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum CascadeDeleteType { /// <exclude /> Allow = 0, // Cascade delete are performed if the references allows it, if referees dont allow it and exception is thrown /// <exclude /> Disallow = 1, // Cascade deletes are not performed and if referees exists an exception is thrown /// <exclude /> Disable = 2// No check on existens of referees is done. This might result in foreign key violation } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DataMoveResult { internal DataMoveResult(IData movedData, IEnumerable<IData> movedRefereeDatas) { this.MovedData = movedData; this.MovedRefereeDatas = movedRefereeDatas; } /// <exclude /> public IData MovedData { get; private set; } /// <exclude /> public IEnumerable<IData> MovedRefereeDatas { get; private set; } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DataFacade { private static ResourceLocker<Resources> _resourceLocker = new ResourceLocker<Resources>(new Resources(), Resources.DoInitializeResources); private static IDataFacade _dataFacade = new DataFacadeImpl(); static DataFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } internal static IDataFacade Implementation { get { return _dataFacade; } set { _dataFacade = value; } } /// <summary> /// Gets an empty predicate (f => true) /// </summary> public static Expression<Func<T, bool>> GetEmptyPredicate<T>() where T : class { return EmptyPredicate<T>.Instance; } #region Data interception methods /// <exclude /> public static void SetDataInterceptor<T>(DataInterceptor dataInterceptor) where T : class, IData { _dataFacade.SetDataInterceptor<T>(dataInterceptor); } // Overload /// <exclude /> public static void SetDataInterceptor(Type interfaceType, DataInterceptor dataInterceptor) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); MethodInfo methodInfo = GetSetDataInterceptorMethodInfo(interfaceType); methodInfo.Invoke(null, new object[] { dataInterceptor }); } /// <exclude /> public static bool HasDataInterceptor<T>() where T : class, IData { return _dataFacade.HasDataInterceptor<T>(); } /// <exclude /> internal static IEnumerable<DataInterceptor> GetDataInterceptors(Type interfaceType) { return _dataFacade.GetDataInterceptors(interfaceType); } // Overload /// <exclude /> public static void HasDataInterceptor(Type interfaceType) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); MethodInfo methodInfo = GetHasDataInterceptorMethodInfo(interfaceType); methodInfo.Invoke(null, new object[] { }); } /// <exclude /> public static void ClearDataInterceptor<T>() where T : class, IData { _dataFacade.ClearDataInterceptor<T>(); } // Overload /// <exclude /> public static void ClearDataInterceptor(Type interfaceType) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); MethodInfo methodInfo = GetClearDataInterceptorMethodInfo(interfaceType); methodInfo.Invoke(null, new object[] { }); } /// <exclude /> public static void SetGlobalDataInterceptor<T>(DataInterceptor dataInterceptor) where T : class, IData { _dataFacade.SetGlobalDataInterceptor<T>(dataInterceptor); } /// <exclude /> public static bool HasGlobalDataInterceptor<T>() where T : class, IData { return _dataFacade.HasGlobalDataInterceptor<T>(); } /// <exclude /> public static void ClearGlobalDataInterceptor<T>() where T : class, IData { _dataFacade.ClearGlobalDataInterceptor<T>(); } #endregion #region GetData methods /// <exclude /> public static IQueryable<T> GetData<T>(bool useCaching, IEnumerable<string> providerNames) where T : class, IData { return _dataFacade.GetData<T>(useCaching, providerNames); } /// <exclude /> public static IQueryable<T> GetData<T>(bool useCaching) where T : class, IData { return _dataFacade.GetData<T>(useCaching, null); } // Overload /// <exclude /> public static IQueryable<T> GetData<T>() where T : class, IData { return GetData<T>(true, null); } // Overload /// <exclude /> public static IQueryable<T> GetData<T>(Expression<Func<T, bool>> predicate) where T : class, IData { Verify.ArgumentNotNull(predicate, "predicate"); IQueryable<T> result = GetData<T>(true, null); if (object.Equals(predicate, EmptyPredicate<T>.Instance)) { return result; } return result.Where(predicate); } // Overload /// <exclude /> public static IQueryable<T> GetData<T>(Expression<Func<T, bool>> predicate, bool useCaching) where T : class, IData { if (predicate == null) throw new ArgumentNullException("predicate"); IQueryable<T> result = GetData<T>(useCaching, null); if (object.Equals(predicate, EmptyPredicate<T>.Instance)) { return result; } return result.Where(predicate); } // Overload /// <exclude /> public static IQueryable GetData(Type interfaceType) { return GetData(interfaceType, true); } // Overload /// <exclude /> public static IQueryable GetData(Type interfaceType, bool useCaching) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); MethodInfo methodInfo = GetGetDataMethodInfo(interfaceType); return methodInfo.Invoke(null, new object[] { useCaching, null }) as IQueryable; } // Overload /// <exclude /> public static IQueryable GetData(Type interfaceType, string providerName) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); if (string.IsNullOrEmpty(providerName)) throw new ArgumentNullException("providerName"); MethodInfo methodInfo = GetGetDataMethodInfo(interfaceType); return methodInfo.Invoke(null, new object[] { false, new string[] { providerName } }) as IQueryable; } #endregion #region GetDataFromDataSourceId methods /// <exclude /> public static T GetDataFromDataSourceId<T>(DataSourceId dataSourceId, bool useCaching) where T : class, IData { if (null == dataSourceId) throw new ArgumentNullException("dataSourceId"); return _dataFacade.GetDataFromDataSourceId<T>(dataSourceId, useCaching); } // Overload /// <exclude /> public static T GetDataFromDataSourceId<T>(DataSourceId dataSourceId) where T : class, IData { if (null == dataSourceId) throw new ArgumentNullException("dataSourceId"); return GetDataFromDataSourceId<T>(dataSourceId, true); } // Overload /// <exclude /> public static IData GetDataFromDataSourceId(DataSourceId dataSourceId) { if (null == dataSourceId) throw new ArgumentNullException("dataSourceId"); MethodInfo methodInfo = GetGetDataFromDataSourceIdMethodInfo(dataSourceId.InterfaceType); IData data = (IData)methodInfo.Invoke(null, new object[] { dataSourceId, true }); return data; } // Overload /// <exclude /> public static IData GetDataFromDataSourceId(DataSourceId dataSourceId, bool useCaching) { if (null == dataSourceId) throw new ArgumentNullException("dataSourceId"); MethodInfo methodInfo = GetGetDataFromDataSourceIdMethodInfo(dataSourceId.InterfaceType); IData data = (IData)methodInfo.Invoke(null, new object[] { dataSourceId, useCaching }); return data; } #endregion #region GetDataFromOtherScope methods (Only helpers) /// <exclude /> public static IQueryable<T> GetDataFromOtherScope<T>(T data, DataScopeIdentifier dataScopeIdentifier) where T : class, IData { Verify.ArgumentNotNull(data, "data"); if (dataScopeIdentifier == null) throw new ArgumentNullException("dataScopeIdentifier"); if (GetSupportedDataScopes(data.DataSourceId.InterfaceType).Contains(dataScopeIdentifier) == false) throw new ArgumentException(string.Format("The data type '{0}' does not support the data scope '{1}'", data.DataSourceId.InterfaceType, dataScopeIdentifier)); using (new DataScope(dataScopeIdentifier)) { return DataExpressionBuilder.GetQueryableByData<T>(data); } } /// <exclude /> public static IQueryable<T> GetDataFromOtherLocale<T>(T data, CultureInfo cultureInfo) where T : class, IData { Verify.ArgumentNotNull(data, "data"); if (cultureInfo == null) throw new ArgumentNullException("cultureInfo"); using (new DataScope(cultureInfo)) { return DataExpressionBuilder.GetQueryableByData<T>(data); } } /// <exclude /> public static IEnumerable<IData> GetDataFromOtherScope(IData data, DataScopeIdentifier dataScopeIdentifier) { return GetDataFromOtherScope(data, dataScopeIdentifier, false); } /// <exclude /> public static IEnumerable<IData> GetDataFromOtherScope( IData data, DataScopeIdentifier dataScopeIdentifier, bool useCaching) { Verify.ArgumentNotNull(data, "data"); Verify.ArgumentNotNull(dataScopeIdentifier, nameof(dataScopeIdentifier)); if (!GetSupportedDataScopes(data.DataSourceId.InterfaceType).Contains(dataScopeIdentifier)) { throw new ArgumentException($"The data type '{data.DataSourceId.InterfaceType}' does not support the data scope '{dataScopeIdentifier}'"); } if (useCaching) { DataSourceId sourceId = data.DataSourceId; var newDataSource = new DataSourceId(sourceId.DataId, sourceId.ProviderName, sourceId.InterfaceType) { DataScopeIdentifier = dataScopeIdentifier }; IData fromDataSource = GetDataFromDataSourceId(newDataSource, true); return fromDataSource == null ? new IData[0] : new[] { fromDataSource }; } var result = new List<IData>(); using (new DataScope(dataScopeIdentifier)) { IQueryable table = GetData(data.DataSourceId.InterfaceType, false); IQueryable queryable = DataExpressionBuilder.GetQueryableByData(data, table); foreach (object obj in queryable) { result.Add((IData)obj); } } return result; } #endregion #region GetPredicateExpressionByUniqueKey methods (Only helpers) /// <exclude /> public static Expression<Func<T, bool>> GetPredicateExpressionByUniqueKey<T>(DataKeyPropertyCollection dataKeyPropertyCollection) where T : class, IData { Verify.ArgumentNotNull(dataKeyPropertyCollection, nameof(dataKeyPropertyCollection)); var keyProperties = typeof(T).GetKeyProperties(); ParameterExpression parameterExpression = Expression.Parameter(typeof(T), "data"); Expression currentExpression = GetPredicateExpressionByUniqueKeyFilterExpression(keyProperties, dataKeyPropertyCollection, parameterExpression); return Expression.Lambda<Func<T, bool>>(currentExpression, parameterExpression); } // Overload /// <exclude /> public static Expression<Func<T, bool>> GetPredicateExpressionByUniqueKey<T>(object dataKeyValue) where T : class, IData { return GetPredicateExpressionByUniqueKey<T>(ToKeyCollection(typeof(T), dataKeyValue)); } /// <exclude /> public static LambdaExpression GetPredicateExpressionByUniqueKey(Type interfaceType, DataKeyPropertyCollection dataKeyPropertyCollection) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); if (dataKeyPropertyCollection == null) throw new ArgumentNullException("dataKeyPropertyCollection"); var keyProperties = DataAttributeFacade.GetKeyProperties(interfaceType); ParameterExpression parameterExpression = Expression.Parameter(interfaceType, "data"); Expression currentExpression = GetPredicateExpressionByUniqueKeyFilterExpression(keyProperties, dataKeyPropertyCollection, parameterExpression); Type delegateType = typeof(Func<,>).MakeGenericType(interfaceType, typeof(bool)); return Expression.Lambda(delegateType, currentExpression, parameterExpression); } // Overload /// <exclude /> public static LambdaExpression GetPredicateExpressionByUniqueKey(Type interfaceType, object dataKeyValue) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); return GetPredicateExpressionByUniqueKey(interfaceType, ToKeyCollection(interfaceType, dataKeyValue)); } // Private helper private static Expression GetPredicateExpressionByUniqueKeyFilterExpression(IReadOnlyList<PropertyInfo> keyProperties, DataKeyPropertyCollection dataKeyPropertyCollection, ParameterExpression parameterExpression) { if (keyProperties.Count != dataKeyPropertyCollection.Count) throw new ArgumentException("Missing or too many key properties"); var propertiesWithValues = new List<Tuple<PropertyInfo, object>>(); foreach (var kvp in dataKeyPropertyCollection.KeyProperties) { PropertyInfo keyPropertyInfo = keyProperties.Single(f => f.Name == kvp.Key); object castedDataKey = ValueTypeConverter.Convert(kvp.Value, keyPropertyInfo.PropertyType); propertiesWithValues.Add(new Tuple<PropertyInfo, object>(keyPropertyInfo, castedDataKey)); } return ExpressionHelper.CreatePropertyPredicate(parameterExpression, propertiesWithValues); } #endregion #region GetDataByUniqueKey methods (Only helpers) // Overload /// <exclude /> public static T TryGetDataByUniqueKey<T>(object dataKeyValue) where T : class, IData { return TryGetDataByUniqueKey<T>(ToKeyCollection(typeof(T), dataKeyValue)); } /// <exclude /> public static T TryGetDataByUniqueKey<T>(DataKeyPropertyCollection dataKeyPropertyCollection) where T : class, IData { return (T) TryGetDataByUniqueKey(typeof(T), dataKeyPropertyCollection); } // Overload /// <exclude /> public static T GetDataByUniqueKey<T>(object dataKeyValue) where T : class, IData { IData data = TryGetDataByUniqueKey<T>(dataKeyValue); if (data == null) throw new InvalidOperationException("No data exist given the data key value"); return (T)data; } // Overload /// <exclude /> public static IData TryGetDataByUniqueKey(Type interfaceType, object dataKeyValue) { Verify.ArgumentNotNull(interfaceType, nameof(interfaceType)); return TryGetDataByUniqueKey(interfaceType, ToKeyCollection(interfaceType, dataKeyValue)); } // Overload /// <exclude /> public static IEnumerable<IData> TryGetDataVersionsByUniqueKey(Type interfaceType, object dataKeyValue) { Verify.ArgumentNotNull(interfaceType, "interfaceType"); return TryGetDataVersionsByUniqueKey(interfaceType, ToKeyCollection(interfaceType, dataKeyValue)); } /// <exclude /> public static IData TryGetDataByUniqueKey(Type interfaceType, DataKeyPropertyCollection dataKeyPropertyCollection) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); if (dataKeyPropertyCollection == null) throw new ArgumentNullException("dataKeyPropertyCollection"); if (dataKeyPropertyCollection.Count == 1 && DataCachingFacade.IsDataAccessCacheEnabled(interfaceType)) { var query = GetData(interfaceType); if (query is ICachingQueryable_CachedByKey cachedByKey) { return cachedByKey.GetCachedValueByKey(GetConvertedUniqueKey(interfaceType, dataKeyPropertyCollection)); } } LambdaExpression lambdaExpression = GetPredicateExpressionByUniqueKey(interfaceType, dataKeyPropertyCollection); MethodInfo methodInfo = GetGetDataWithPredicatMethodInfo(interfaceType); IQueryable queryable = (IQueryable)methodInfo.Invoke(null, new object[] { lambdaExpression }); var dataList = queryable.OfType<IData>().ToList(); if (dataList.Count > 1) throw new InvalidOperationException($"More than one data item of type '{interfaceType}' is matching the key: {dataKeyPropertyCollection}"); return dataList.SingleOrDefault(); } /// <summary> /// Returns all data items of the given type, which matches the provided dataPropertyCollection (property/value pairs) /// </summary> /// <param name="interfaceType">The data type to query - type is expected to implement a subinterface of IData</param> /// <param name="dataPropertyCollection">The properties and values to use for filtering</param> /// <returns>Data matching the provided property values</returns> public static IEnumerable<IData> TryGetDataByLookupKeys(Type interfaceType, DataPropertyValueCollection dataPropertyCollection) { Verify.ArgumentNotNull(interfaceType, nameof(interfaceType)); Verify.ArgumentNotNull(dataPropertyCollection, nameof(dataPropertyCollection)); LambdaExpression lambdaExpression = GetPredicateExpression(interfaceType, dataPropertyCollection); MethodInfo methodInfo = GetGetDataWithPredicatMethodInfo(interfaceType); var queryable = (IQueryable)methodInfo.Invoke(null, new object[] { lambdaExpression }); return ((IEnumerable)queryable).Cast<IData>(); } /// <exclude /> public static IEnumerable<IData> TryGetDataVersionsByUniqueKey(Type interfaceType, DataKeyPropertyCollection dataKeyPropertyCollection) { Verify.ArgumentNotNull(interfaceType, nameof(interfaceType)); Verify.ArgumentNotNull(dataKeyPropertyCollection, nameof(dataKeyPropertyCollection)); if (dataKeyPropertyCollection.Count == 1 && DataCachingFacade.IsDataAccessCacheEnabled(interfaceType)) { var query = GetData(interfaceType); if (query is ICachingQueryable_CachedByKey cachedByKey) { return cachedByKey.GetCachedVersionValuesByKey(GetConvertedUniqueKey(interfaceType, dataKeyPropertyCollection)); } } LambdaExpression lambdaExpression = GetPredicateExpressionByUniqueKey(interfaceType, dataKeyPropertyCollection); MethodInfo methodInfo = GetGetDataWithPredicatMethodInfo(interfaceType); var queryable = (IQueryable)methodInfo.Invoke(null, new object[] { lambdaExpression }); return ((IEnumerable) queryable).Cast<IData>(); } private static object GetConvertedUniqueKey(Type interfaceType, DataKeyPropertyCollection keyCollection) { var keyPropertyInfo = interfaceType.GetKeyProperties().Single(); var kvp = keyCollection.KeyProperties.Single(); if (keyPropertyInfo.Name != kvp.Key) { throw new InvalidOperationException($"Expected value for key '{keyPropertyInfo.Name}' but found '{kvp.Key}'"); } var result = ValueTypeConverter.TryConvert(kvp.Value, keyPropertyInfo.PropertyType, out var conversionException); if (conversionException != null) { throw conversionException; } return result; } // Overload /// <exclude /> public static IData GetDataByUniqueKey(Type interfaceType, object dataKeyValue) { Verify.ArgumentNotNull(interfaceType, nameof(interfaceType)); IData data = TryGetDataByUniqueKey(interfaceType, dataKeyValue); Verify.IsNotNull(data, "No data exist given the data key value"); return data; } // Overload /// <exclude /> public static IData GetDataByUniqueKey(Type interfaceType, DataKeyPropertyCollection dataKeyPropertyCollection) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); if (dataKeyPropertyCollection == null) throw new ArgumentNullException("dataKeyPropertyCollection"); IData data = TryGetDataByUniqueKey(interfaceType, dataKeyPropertyCollection); if (data == null) throw new InvalidOperationException("No data exist given the data key values"); return data; } private static DataKeyPropertyCollection ToKeyCollection(Type interfaceType, object dataKeyValue) { var keyPropertyInfo = interfaceType.GetKeyProperties().Single(); return ToKeyCollection(keyPropertyInfo, dataKeyValue); } private static DataKeyPropertyCollection ToKeyCollection(PropertyInfo keyPropertyInfo, object dataKeyValue) { var dataKeyPropertyCollection = new DataKeyPropertyCollection(); dataKeyPropertyCollection.AddKeyProperty(keyPropertyInfo, dataKeyValue); return dataKeyPropertyCollection; } #endregion #region GetDataOrderedBy methods (Only helpers) // Overload /// <exclude /> public static IEnumerable<IData> GetDataOrderedBy(Type interfaceType, PropertyInfo propertyInfo) { return GetDataOrderedByQueryable(interfaceType, propertyInfo).ToDataEnumerable(); } /// <exclude /> public static IQueryable GetDataOrderedByQueryable(Type interfaceType, PropertyInfo propertyInfo) { IQueryable source = DataFacade.GetData(interfaceType); ParameterExpression parameter = Expression.Parameter(interfaceType, "f"); LambdaExpression lambdaExpression = Expression.Lambda(Expression.Property(parameter, propertyInfo), parameter); MethodCallExpression methodCallExpression = Expression.Call ( typeof(Queryable), "OrderBy", new Type[] { interfaceType, propertyInfo.PropertyType }, source.Expression, Expression.Quote(lambdaExpression) ); return source.Provider.CreateQuery(methodCallExpression); } #endregion #region GetPredicateExpression methods (Only helpers) /// <exclude /> public static LambdaExpression GetPredicateExpression(Type interfaceType, DataPropertyValueCollection dataPropertyValueCollection) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); if (dataPropertyValueCollection == null) throw new ArgumentNullException("dataPropertyValueCollection"); ParameterExpression parameterExpression = Expression.Parameter(interfaceType, "data"); Expression currentExpression = GetPredicateExpressionFilterExpression(dataPropertyValueCollection, parameterExpression); Type delegateType = typeof(Func<,>).MakeGenericType(new Type[] { interfaceType, typeof(bool) }); LambdaExpression lambdaExpression = Expression.Lambda(delegateType, currentExpression, new ParameterExpression[] { parameterExpression }); return lambdaExpression; } // Private helper private static Expression GetPredicateExpressionFilterExpression(DataPropertyValueCollection dataPropertyValueCollection, ParameterExpression parameterExpression) { Expression currentExpression = null; foreach (var kvp in dataPropertyValueCollection.PropertyValues) { Expression left = LambdaExpression.Property(parameterExpression, kvp.Key); object castedValue = ValueTypeConverter.Convert(kvp.Value, kvp.Key.PropertyType); Expression right = Expression.Constant(castedValue); Expression filter = Expression.Equal(left, right); if (currentExpression == null) { currentExpression = filter; } else { currentExpression = Expression.And(currentExpression, filter); } } return currentExpression; } #endregion #region WillUpdateSucceed methods (Only helpers) /// <exclude /> public static bool WillUpdateSucceed(IData data) { Verify.ArgumentNotNull(data, "data"); return data.TryValidateForeignKeyIntegrity(); } /// <exclude /> public static bool WillUpdateSucceed(IEnumerable<IData> datas) { if (null == datas) throw new ArgumentNullException("datas"); foreach (IData data in datas) { if (data == null) throw new ArgumentException("datas may not contain nulls"); if (data.TryValidateForeignKeyIntegrity() == false) return false; } return true; } #endregion #region Update methods // Overload /// <exclude /> public static void Update(IData data) { Verify.ArgumentNotNull(data, "data"); Verify.ArgumentCondition(data.DataSourceId != null, "data", "DataSourceId isn't defined"); Verify.ArgumentCondition(data.DataSourceId.ProviderName != null, "data", "Data provider isn't defined. Use method AddNew() for instances created with BuildNew()"); Update(new[] { data }); } /// <exclude /> public static void Update(IData data, bool suppressEventing, bool performForeignKeyIntegrityCheck, bool performeValidation) { if (null == data) throw new ArgumentNullException("data"); Update(new[] { data }, suppressEventing, performForeignKeyIntegrityCheck, performeValidation); } /// <exclude /> public static void Update(IEnumerable<IData> dataset) { Verify.ArgumentNotNull(dataset, "dataset"); _dataFacade.Update(dataset, false, true, true); } /// <exclude /> public static void Update(IEnumerable<IData> dataset, bool suppressEventing, bool performForeignKeyIntegrityCheck) { Verify.ArgumentNotNull(dataset, "dataset"); _dataFacade.Update(dataset, suppressEventing, performForeignKeyIntegrityCheck, true); } /// <exclude /> public static void Update(IEnumerable<IData> dataset, bool suppressEventing, bool performForeignKeyIntegrityCheck, bool performeValidation) { Verify.ArgumentNotNull(dataset, "dataset"); _dataFacade.Update(dataset, suppressEventing, performForeignKeyIntegrityCheck, performeValidation); } #endregion #region BuildNew methods (Only helpers) // Overload /// <exclude /> public static T BuildNew<T>() where T : class, IData { return BuildNew<T>(false); } /// <exclude /> public static T BuildNew<T>(bool suppressEventing) where T : class, IData { return _dataFacade.BuildNew<T>(suppressEventing); } // Overload /// <exclude /> public static IData BuildNew(Type interfaceType) { return BuildNew(interfaceType, false); } /// <exclude /> public static IData BuildNew(Type interfaceType, bool suppressEventling) { return _dataFacade.BuildNew(interfaceType, suppressEventling); } #endregion #region WillAddNewSucceed (Only helpers) /// <exclude /> public static bool WillAddNewSucceed(IData data) { Verify.ArgumentNotNull(data, "data"); return data.TryValidateForeignKeyIntegrity(); } /// <exclude /> public static bool WillAddNewSucceed<T>(T data) where T : class, IData { Verify.ArgumentNotNull(data, "data"); return data.TryValidateForeignKeyIntegrity(); } /// <exclude /> public static bool WillAddNewSucceed<T>(IEnumerable<T> datas) where T : class, IData { if (datas == null) throw new ArgumentNullException("datas"); foreach (T data in datas) { if (data == null) throw new ArgumentException("datas may not contain nulls"); if (data.TryValidateForeignKeyIntegrity() == false) return false; } return true; } #endregion #region AddNew methods // Overload /// <exclude /> public static T AddNew<T>(T data) where T : class, IData { Verify.ArgumentNotNull(data, "data"); List<T> result = AddNew<T>(new T[] { data }, true, false, true, true, null); return result[0]; } // Overload /// <exclude /> public static T AddNew<T>(T data, string providerName) where T : class, IData { Verify.ArgumentNotNull(data, "data"); if (string.IsNullOrEmpty(providerName)) throw new ArgumentNullException("providerName"); List<T> result = AddNew<T>(new T[] { data }, true, false, true, true, new List<string> { providerName }); return result[0]; } // Overload /// <exclude /> public static List<T> AddNew<T>(IEnumerable<T> datas) where T : class, IData { if (datas == null) throw new ArgumentNullException("datas"); return AddNew<T>(datas, true, false, true, true, null); } // Overload /// <exclude /> public static List<T> AddNew<T>(IEnumerable<T> datas, string providerName) where T : class, IData { if (datas == null) throw new ArgumentNullException("datas"); if (string.IsNullOrEmpty(providerName)) throw new ArgumentNullException("providerName"); return AddNew<T>(datas, true, false, true, true, new List<string> { providerName }); } // Overload /// <summary> /// WARNING: Setting <paramref name="performForeignKeyIntegrityCheck"/> to 'false' can /// cause serious foreign key corruption. /// </summary> /// <param name="data"></param> /// <param name="performForeignKeyIntegrityCheck"></param> /// <returns></returns> public static T AddNew<T>(T data, bool performForeignKeyIntegrityCheck) where T : class, IData { Verify.ArgumentNotNull(data, "data"); List<T> result = AddNew<T>(new T[] { data }, true, false, performForeignKeyIntegrityCheck, true, null); return result[0]; } // Overload /// <summary> /// WARNING: Setting <paramref name="performForeignKeyIntegrityCheck"/> to 'false' can /// cause serious foreign key corruption. /// </summary> /// <param name="data"></param> /// <param name="suppressEventing"></param> /// <param name="performForeignKeyIntegrityCheck"></param> /// <returns></returns> public static T AddNew<T>(T data, bool suppressEventing, bool performForeignKeyIntegrityCheck) where T : class, IData { Verify.ArgumentNotNull(data, "data"); List<T> result = AddNew<T>(new T[] { data }, true, suppressEventing, performForeignKeyIntegrityCheck, true, null); return result[0]; } // Overload /// <summary> /// WARNING: Setting <paramref name="performForeignKeyIntegrityCheck"/> to 'false' can /// cause serious foreign key corruption. /// </summary> /// <param name="data"></param> /// <param name="suppressEventing"></param> /// <param name="performeValidation"></param> /// <param name="performForeignKeyIntegrityCheck"></param> /// <returns></returns> public static T AddNew<T>(T data, bool suppressEventing, bool performForeignKeyIntegrityCheck, bool performeValidation) where T : class, IData { Verify.ArgumentNotNull(data, "data"); List<T> result = AddNew<T>(new T[] { data }, true, suppressEventing, performForeignKeyIntegrityCheck, performeValidation, null); return result[0]; } // Overload /// <exclude /> public static IData AddNew(IData data) { Verify.ArgumentNotNull(data, "data"); MethodInfo methodInfo = GetAddNewMethodInfo(data.DataSourceId.InterfaceType); IData resultData = (IData)methodInfo.Invoke(null, new object[] { data, true, false, true, true, null }); return resultData; } /// <summary> /// WARNING: Setting <paramref name="performForeignKeyIntegrityCheck"/> to 'false' can cause serious foreign key corruption. /// </summary> /// <param name="data"></param> /// <param name="suppressEventing"></param> /// <param name="performForeignKeyIntegrityCheck"></param> /// <param name="providerName"></param> /// <returns></returns> public static IData AddNew(IData data, bool suppressEventing, bool performForeignKeyIntegrityCheck, string providerName) { Verify.ArgumentNotNull(data, "data"); MethodInfo methodInfo = GetAddNewMethodInfo(data.DataSourceId.InterfaceType); IData resultData = (IData)methodInfo.Invoke(null, new object[] { data, true, suppressEventing, performForeignKeyIntegrityCheck, true, new List<string> { providerName } }); return resultData; } /// <summary> /// WARNING: Setting <paramref name="performForeignKeyIntegrityCheck"/> to 'false' can cause serious foreign key corruption. /// </summary> /// <param name="data"></param> /// <param name="interfaceType"></param> /// <param name="suppressEventing"></param> /// <param name="performForeignKeyIntegrityCheck"></param> /// <param name="providerName"></param> /// <returns></returns> public static IData AddNew(IData data, Type interfaceType, bool suppressEventing, bool performForeignKeyIntegrityCheck, string providerName) { Verify.ArgumentNotNull(data, "data"); MethodInfo methodInfo = GetAddNewMethodInfo(interfaceType); IData resultData = (IData)methodInfo.Invoke(null, new object[] { data, true, suppressEventing, performForeignKeyIntegrityCheck, true, new List<string> { providerName } }); return resultData; } /// <summary> /// WARNING: Setting <paramref name="performForeignKeyIntegrityCheck"/> to 'false' can cause serious foreign key corruption. /// </summary> /// <param name="data"></param> /// <param name="suppressEventing"></param> /// <param name="performForeignKeyIntegrityCheck"></param> /// <param name="performeValidation"></param> /// <returns></returns> public static IData AddNew(IData data, bool suppressEventing, bool performForeignKeyIntegrityCheck, bool performeValidation) { Verify.ArgumentNotNull(data, "data"); MethodInfo methodInfo = GetAddNewMethodInfo(data.DataSourceId.InterfaceType); IData resultData = (IData)methodInfo.Invoke(null, new object[] { data, true, suppressEventing, performForeignKeyIntegrityCheck, performeValidation, null }); return resultData; } /// <summary> /// WARNING: Setting <paramref name="performForeignKeyIntegrityCheck"/> to 'false' can cause serious foreign key corruption. /// </summary> /// <param name="data"></param> /// <param name="interfaceType"></param> /// <param name="suppressEventing"></param> /// <param name="performForeignKeyIntegrityCheck"></param> /// <param name="performeValidation"></param> /// <returns></returns> public static IData AddNew(IData data, Type interfaceType, bool suppressEventing, bool performForeignKeyIntegrityCheck, bool performeValidation) { Verify.ArgumentNotNull(data, "data"); MethodInfo methodInfo = GetAddNewMethodInfo(interfaceType); IData resultData = (IData)methodInfo.Invoke(null, new object[] { data, true, suppressEventing, performForeignKeyIntegrityCheck, performeValidation, null }); return resultData; } /// <summary> /// WARNING: Setting <paramref name="performForeignKeyIntegrityCheck"/> to 'false' can cause serious foreign key corruption. /// </summary> /// <param name="data"></param> /// <param name="suppressEventing"></param> /// <param name="performForeignKeyIntegrityCheck"></param> /// <param name="performeValidation"></param> /// <param name="providerName"></param> /// <returns></returns> public static IData AddNew(IData data, bool suppressEventing, bool performForeignKeyIntegrityCheck, bool performeValidation, string providerName) { Verify.ArgumentNotNull(data, "data"); MethodInfo methodInfo = GetAddNewMethodInfo(data.DataSourceId.InterfaceType); IData resultData = (IData)methodInfo.Invoke(null, new object[] { data, true, suppressEventing, performForeignKeyIntegrityCheck, performeValidation, new List<string> { providerName } }); return resultData; } // Overload /// <summary> /// WARNING: Setting <paramref name="performForeignKeyIntegrityCheck"/> to 'false' can cause serious foreign key corruption. /// </summary> /// <param name="data"></param> /// <param name="performForeignKeyIntegrityCheck"></param> /// <returns></returns> public static IData AddNew(IData data, bool performForeignKeyIntegrityCheck) { Verify.ArgumentNotNull(data, "data"); MethodInfo methodInfo = GetAddNewMethodInfo(data.DataSourceId.InterfaceType); IData resultData = (IData)methodInfo.Invoke(null, new object[] { data, true, false, performForeignKeyIntegrityCheck, true, null }); return resultData; } private static T AddNew<T>(T data, bool allowStoreCreation, bool suppressEventing, bool performForeignKeyIntegrityCheck, bool performeValidation, List<string> writeableProviders) where T : class, IData { List<T> result = _dataFacade.AddNew<T>(new T[] { data }, allowStoreCreation, suppressEventing, performForeignKeyIntegrityCheck, performeValidation, writeableProviders); return result[0]; } private static List<T> AddNew<T>(IEnumerable<T> collection, bool allowStoreCreation, bool suppressEventing, bool performForeignKeyIntegrityCheck, bool performeValidation, List<string> writeableProviders) where T : class, IData { return _dataFacade.AddNew<T>(collection, allowStoreCreation, suppressEventing, performForeignKeyIntegrityCheck, performeValidation, writeableProviders); } #endregion #region WillDeleteSucceed methods (Only helpers) /// <exclude /> public static bool WillDeleteSucceed<T>(T data) where T : class, IData { Verify.ArgumentNotNull(data, "data"); return data.TryValidateDeleteSuccess(); } /// <exclude /> public static bool WillDeleteSucceed(IEnumerable<IData> datas) { if (datas == null) throw new ArgumentNullException("datas"); return WillDeleteSucceed<IData>(datas); } /// <exclude /> public static bool WillDeleteSucceed(IData data) { Verify.ArgumentNotNull(data, "data"); return data.TryValidateDeleteSuccess(); } /// <exclude /> public static bool WillDeleteSucceed<T>(IEnumerable<T> dataset) where T : class, IData { Verify.ArgumentNotNull(dataset, "dataset"); foreach (T data in dataset) { Verify.ArgumentCondition(data != null, "dataset", "The dataset may not contain null values"); if (!data.TryValidateDeleteSuccess()) { return false; } } return true; } #endregion #region Delete methods // Overload /// <exclude /> public static void Delete<T>(T data) where T : class, IData { Verify.ArgumentNotNull(data, "data"); Delete<T>(new T[] { data }, false, CascadeDeleteType.Allow, true); } // Overload /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data"></param> /// <param name="referencesFromAllScopes"> /// If this is true then cascade delete is performed on all data scopes. /// If this is false then cascade delete is only performed in the same scope as <paramref name="data"/> /// </param> public static void Delete<T>(T data, bool referencesFromAllScopes) where T : class, IData { Verify.ArgumentNotNull(data, "data"); Delete<T>(new T[] { data }, false, CascadeDeleteType.Allow, referencesFromAllScopes); } // Overload /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="datas"></param> /// <param name="suppressEventing"></param> /// <param name="referencesFromAllScopes"> /// If this is true then cascade delete is performed on all data scopes. /// If this is false then cascade delete is only performed in the same scope as <paramref name="datas"/> /// </param> public static void Delete<T>(IEnumerable<T> datas, bool suppressEventing, bool referencesFromAllScopes) where T : class, IData { if (datas == null) throw new ArgumentNullException("datas"); Delete<T>(datas, suppressEventing, CascadeDeleteType.Allow, referencesFromAllScopes); } // Overload /// <exclude /> public static void Delete<T>(IEnumerable<T> datas) where T : class, IData { if (datas == null) throw new ArgumentNullException("datas"); Delete<T>(datas, false, CascadeDeleteType.Allow, true); } // Overload /// <summary> /// Deletes the given datas. WARNING: Setting <paramref name="cascadeDeleteType"/> /// to 'Disable' can cause serious foreign key corruption. /// </summary> /// <param name="datas"></param> /// <param name="suppressEventing"></param> /// <param name="cascadeDeleteType"></param> public static void Delete<T>(IEnumerable<T> datas, bool suppressEventing, CascadeDeleteType cascadeDeleteType) where T : class, IData { if (datas == null) throw new ArgumentNullException("datas"); Delete<T>(datas, suppressEventing, cascadeDeleteType, true); } // Overload /// <summary> /// Deletes the given datas. WARNING: Setting <paramref name="cascadeDeleteType"/> /// to 'Disable' can cause serious foreign key corruption. /// </summary> /// <param name="datas"></param> /// <param name="cascadeDeleteType"></param> public static void Delete<T>(IEnumerable<T> datas, CascadeDeleteType cascadeDeleteType) where T : class, IData { if (datas == null) throw new ArgumentNullException("datas"); Delete<T>(datas, false, cascadeDeleteType, true); } // Overload /// <exclude /> public static void Delete<T>(Expression<Func<T, bool>> predicate) where T : class, IData { using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { IEnumerable<T> datasToDelete = DataFacade.GetData<T>(predicate, false); Delete<T>(datasToDelete, false, CascadeDeleteType.Allow, true); transactionScope.Complete(); } } // Overload /// <exclude /> public static void Delete(IEnumerable<IData> datas) { if (datas == null) throw new ArgumentNullException("datas"); Delete<IData>(datas, false, CascadeDeleteType.Allow, true); } // Overload /// <summary> /// Deletes the given datas. WARNING: Setting <paramref name="cascadeDeleteType"/> /// to 'Disable' can cause serious foreign key corruption. /// </summary> /// <param name="data"></param> /// <param name="cascadeDeleteType"></param> public static void Delete(IData data, CascadeDeleteType cascadeDeleteType) { Verify.ArgumentNotNull(data, "data"); Delete<IData>(new IData[] { data }, false, cascadeDeleteType, true); } // Overload /// <summary> /// Deletes the given datas. WARNING: Setting <paramref name="cascadeDeleteType"/> /// to 'Disable' can cause serious foreign key corruption. /// </summary> /// <param name="datas"></param> /// <param name="suppressEventing"></param> /// <param name="cascadeDeleteType"></param> public static void Delete(IEnumerable<IData> datas, bool suppressEventing, CascadeDeleteType cascadeDeleteType) { if (datas == null) throw new ArgumentNullException("datas"); Delete<IData>(datas, suppressEventing, cascadeDeleteType, true); } // Overload /// <summary> /// Deletes the given datas. WARNING: Setting <paramref name="cascadeDeleteType"/> /// to 'Disable' can cause serious foreign key corruption. /// </summary> /// <param name="datas"></param> /// <param name="cascadeDeleteType"></param> public static void Delete(IEnumerable<IData> datas, CascadeDeleteType cascadeDeleteType) { if (datas == null) throw new ArgumentNullException("datas"); Delete<IData>(datas, false, cascadeDeleteType, true); } // Overload /// <summary> /// Deletes the given datas. WARNING: Setting <paramref name="cascadeDeleteType"/> /// to 'Disable' can cause serious foreign key corruption. /// </summary> /// <param name="data"></param> /// <param name="suppressEventing"></param> /// <param name="cascadeDeleteType"></param> public static void Delete<T>(T data, bool suppressEventing, CascadeDeleteType cascadeDeleteType) where T : class, IData { if (null == data) throw new ArgumentNullException("data"); Delete<T>(new T[] { data }, suppressEventing, cascadeDeleteType, true); } private static void Delete<T>(IEnumerable<T> datas, bool suppressEventing, CascadeDeleteType cascadeDeleteType, bool referencesFromAllScopes) where T : class, IData { _dataFacade.Delete<T>(datas, suppressEventing, cascadeDeleteType, referencesFromAllScopes); } #endregion #region ValidatePath methods // Overload /// <exclude /> public static bool ValidatePath<TFile>(TFile file, string providerName) where TFile : IFile { string errorMessage; return ValidatePath(file, providerName, out errorMessage); } /// <exclude /> public static bool ValidatePath<TFile>(TFile file, string providerName, out string errorMessage) where TFile : IFile { return _dataFacade.ValidatePath(file, providerName, out errorMessage); } #endregion #region GetDataProviderNames method (Only helpers) /// <exclude /> public static IEnumerable<string> GetDataProviderNames() { return DataProviderRegistry.DataProviderNames; } /// <exclude /> public static IEnumerable<string> GetDynamicDataProviderNames() { return DataProviderRegistry.DynamicDataProviderNames; } #endregion #region GetInterfaces methods (Only helpers) /// <exclude /> public static List<Type> GetAllInterfaces() { return DataProviderRegistry.AllInterfaces.ToList(); } /// <exclude /> public static List<Type> GetAllInterfaces(UserType relevantToUserType) { return (from dataInterface in DataProviderRegistry.AllInterfaces where dataInterface.GetCustomInterfaceAttributes<RelevantToUserTypeAttribute>().Any(a => (a.UserType & relevantToUserType) == relevantToUserType) select dataInterface).ToList(); } /// <exclude /> public static List<Type> GetAllKnownInterfaces() { return DataProviderRegistry.AllKnownInterfaces.ToList(); } /// <exclude /> public static List<Type> GetAllKnownInterfaces(UserType relevantToUserType) { return (from dataInterface in DataProviderRegistry.AllKnownInterfaces where dataInterface.GetCustomInterfaceAttributes<RelevantToUserTypeAttribute>().Any(a => (a.UserType & relevantToUserType) == relevantToUserType) select dataInterface).ToList(); } /// <exclude /> public static List<Type> GetGeneratedInterfaces() { return DataProviderRegistry.GeneratedInterfaces.ToList(); } #endregion #region DataTag methods (Only helpers) // Overload /// <exclude /> public static void SetDataTag(IData data, string id, object value) { Verify.ArgumentNotNull(data, "data"); if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); SetDataTag(data.DataSourceId, id, value); } /// <exclude /> public static void SetDataTag(DataSourceId dataSourceId, string id, object value) { if (dataSourceId == null) throw new ArgumentNullException("dataSourceId"); if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); dataSourceId.SetTag(id, value); } // Overload /// <exclude /> public static bool TryGetDataTag<T>(IData data, string id, out T tag) { Verify.ArgumentNotNull(data, "data"); if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); return TryGetDataTag<T>(data.DataSourceId, id, out tag); } /// <exclude /> public static bool TryGetDataTag<T>(DataSourceId dataSourceId, string id, out T tag) { if (dataSourceId == null) throw new ArgumentNullException("dataSourceId"); if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); object tagValue = null; bool result = dataSourceId.TryGetTag(id, out tagValue); if (result) { tag = (T)tagValue; } else { tag = default(T); } return result; } // Overload /// <exclude /> public static T GetDataTag<T>(IData data, string id) { Verify.ArgumentNotNull(data, "data"); if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); return GetDataTag<T>(data.DataSourceId, id); } /// <exclude /> public static T GetDataTag<T>(DataSourceId dataSourceId, string id) { if (dataSourceId == null) throw new ArgumentNullException("dataSourceId"); if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); object value; if (dataSourceId.TryGetTag(id, out value) == false) { throw new InvalidOperationException(string.Format("The tag '{0}' has not been set on the data source id", id)); } return (T)value; } // Overload /// <exclude /> public static void RemoveDataTag(IData data, string id) { Verify.ArgumentNotNull(data, "data"); if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); RemoveDataTag(data.DataSourceId, id); } /// <exclude /> public static void RemoveDataTag(DataSourceId dataSourceId, string id) { if (dataSourceId == null) throw new ArgumentNullException("dataSourceId"); if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); dataSourceId.RemoveTag(id); } #endregion #region Mics methods (Only helpers) /// <exclude /> internal static void ForEachDataScope(Type interfaceType, ThreadStart action) { IEnumerable<DataScopeIdentifier> supportedDataScopes = interfaceType.GetSupportedDataScopes(); CultureInfo[] cultures = DataLocalizationFacade.IsLocalized(interfaceType) ? DataLocalizationFacade.ActiveLocalizationCultures.ToArray() : new[] { DataLocalizationFacade.DefaultLocalizationCulture }; foreach (DataScopeIdentifier dataScopeIdentifier in supportedDataScopes) { foreach (CultureInfo culture in cultures) { using (new DataScope(dataScopeIdentifier, culture)) { action(); } } } } /// <exclude /> public static IEnumerable<DataScopeIdentifier> GetSupportedDataScopes(Type interfaceType) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); IReadOnlyCollection<DataScopeIdentifier> supportedDataScope = interfaceType.GetSupportedDataScopes(); if (supportedDataScope.Count == 0) { throw new InvalidOperationException(string.Format("The data type '{0}' does not support any data scopes, use the '{1}' attribute", interfaceType, typeof(DataScopeAttribute))); } return supportedDataScope; } /// <exclude /> public static bool HasDataInAnyScope(Type interfaceType) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); foreach (var dataScopeIdentifier in GetSupportedDataScopes(interfaceType)) { using (new DataScope(dataScopeIdentifier)) { IData data = GetData(interfaceType).ToDataEnumerable().FirstOrDefault(); if (data != null) { return true; } } } return false; } /// <exclude /> public static bool ExistsInAnyLocale<T>(IEnumerable<CultureInfo> excludedCultureInfoes) where T : class, IData { return _dataFacade.ExistsInAnyLocale<T>(excludedCultureInfoes); } // Overload /// <exclude /> public static bool ExistsInAnyLocale<T>(CultureInfo excludedCultureInfo) where T : class, IData { return ExistsInAnyLocale<T>(new CultureInfo[] { excludedCultureInfo }); } // Overload /// <exclude /> public static bool ExistsInAnyLocale<T>() where T : class, IData { return ExistsInAnyLocale<T>(Enumerable.Empty<CultureInfo>()); } /// <exclude /> public static bool ExistsInAnyLocale(Type interfaceType) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); MethodInfo methodInfo = GetExistsInAnyLocaleMethodInfo(interfaceType); bool result = (bool)methodInfo.Invoke(null, null); return result; } // Overload /// <exclude /> public static bool ExistsInAnyLocale(Type interfaceType, CultureInfo excludedCultureInfo) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); MethodInfo methodInfo = GetExistsInAnyLocaleWithParamMethodInfo(interfaceType); bool result = (bool)methodInfo.Invoke(null, new object[] { new CultureInfo[] { excludedCultureInfo } }); return result; } #endregion #region GetXXXMethodInfo methods (Only helpers) /// <exclude /> public static MethodInfo GetSetDataInterceptorMethodInfo(Type interfaceType) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); if (typeof(IData).IsAssignableFrom(interfaceType) == false) throw new ArgumentException("The provided type must implement IData", "interfaceType"); MethodInfo methodInfo; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.GenericSetDataInterceptorMethodInfo.TryGetValue(interfaceType, out methodInfo) == false) { MethodInfo nonGenericMethod = typeof(DataFacade).GetMethod( nameof(SetDataInterceptor), BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(DataInterceptor) }, null); methodInfo = nonGenericMethod.MakeGenericMethod(interfaceType); _resourceLocker.Resources.GenericSetDataInterceptorMethodInfo.Add(interfaceType, methodInfo); } } return methodInfo; } /// <exclude /> public static MethodInfo GetHasDataInterceptorMethodInfo(Type interfaceType) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); if (!typeof(IData).IsAssignableFrom(interfaceType)) throw new ArgumentException("The provided type must implement IData", "interfaceType"); MethodInfo methodInfo; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.GenericHasDataInterceptorMethodInfo.TryGetValue(interfaceType, out methodInfo) == false) { MethodInfo nonGenericMethod = typeof(DataFacade).GetMethod( nameof(HasDataInterceptor), BindingFlags.Static | BindingFlags.Public, null, new Type[] { }, null); methodInfo = nonGenericMethod.MakeGenericMethod(interfaceType); _resourceLocker.Resources.GenericHasDataInterceptorMethodInfo.Add(interfaceType, methodInfo); } } return methodInfo; } /// <exclude /> public static MethodInfo GetClearDataInterceptorMethodInfo(Type interfaceType) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); if (!typeof(IData).IsAssignableFrom(interfaceType)) throw new ArgumentException("The provided type must implement IData", "interfaceType"); MethodInfo methodInfo; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.GenericClearDataInterceptorMethodInfo.TryGetValue(interfaceType, out methodInfo) == false) { MethodInfo nonGenericMethod = typeof(DataFacade).GetMethod( nameof(ClearDataInterceptor), BindingFlags.Static | BindingFlags.Public, null, new Type[] { }, null); methodInfo = nonGenericMethod.MakeGenericMethod(interfaceType); _resourceLocker.Resources.GenericClearDataInterceptorMethodInfo.Add(interfaceType, methodInfo); } } return methodInfo; } /// <exclude /> public static MethodInfo GetGetDataMethodInfo(Type interfaceType) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); if (!typeof(IData).IsAssignableFrom(interfaceType)) throw new ArgumentException("The provided type must implement IData", "interfaceType"); MethodInfo methodInfo; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.GenericGetDataFromTypeMethodInfo.TryGetValue(interfaceType, out methodInfo) == false) { MethodInfo nonGenericMethod = typeof(DataFacade).GetMethod( nameof(GetData), BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(bool), typeof(IEnumerable<string>) }, null); methodInfo = nonGenericMethod.MakeGenericMethod(interfaceType); _resourceLocker.Resources.GenericGetDataFromTypeMethodInfo.Add(interfaceType, methodInfo); } } return methodInfo; } /// <exclude /> public static MethodInfo GetGetDataFromDataSourceIdMethodInfo(Type interfaceType) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); if (!typeof(IData).IsAssignableFrom(interfaceType)) throw new ArgumentException("The provided type must implement IData", "interfaceType"); MethodInfo methodInfo; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.GenericGetDataFromDataSourceIdMethodInfo.TryGetValue(interfaceType, out methodInfo) == false) { MethodInfo nonGenericMethod = (from m in typeof(DataFacade).GetMethods(BindingFlags.Public | BindingFlags.Static) where m.Name == nameof(GetDataFromDataSourceId) && m.IsGenericMethodDefinition && m.GetParameters().Length == 2 select m).Single(); methodInfo = nonGenericMethod.MakeGenericMethod(interfaceType); _resourceLocker.Resources.GenericGetDataFromDataSourceIdMethodInfo.Add(interfaceType, methodInfo); } } return methodInfo; } /// <exclude /> public static MethodInfo GetGetDataWithPredicatMethodInfo(Type interfaceType) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); if (!typeof(IData).IsAssignableFrom(interfaceType)) throw new ArgumentException("The provided type must implement IData", "interfaceType"); MethodInfo methodInfo; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.GenericGetDataFromTypeWithPredicateMethodInfo.TryGetValue(interfaceType, out methodInfo) == false) { MethodInfo genericMethod = (from m in typeof(DataFacade).GetMethods(BindingFlags.Public | BindingFlags.Static) where m.Name == nameof(GetData) && m.IsGenericMethodDefinition && m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType.IsGenericType && m.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(Expression<>) select m).Single(); methodInfo = genericMethod.MakeGenericMethod(interfaceType); _resourceLocker.Resources.GenericGetDataFromTypeWithPredicateMethodInfo.Add(interfaceType, methodInfo); } } return methodInfo; } /// <exclude /> public static MethodInfo GetAddNewMethodInfo(Type interfaceType) { Verify.ArgumentNotNull(interfaceType, "interfaceType"); Verify.ArgumentCondition(typeof(IData).IsAssignableFrom(interfaceType), "interfaceType", "The provided type must implement IData"); MethodInfo methodInfo; using (_resourceLocker.Locker) { if (!_resourceLocker.Resources.GenericAddNewFromTypeMethodInfo.TryGetValue(interfaceType, out methodInfo)) { MethodInfo genericMethodInfo = StaticReflection.GetGenericMethodInfo(data => AddNew((IData) null, true, true, true, true, null)); methodInfo = genericMethodInfo.MakeGenericMethod(interfaceType); _resourceLocker.Resources.GenericAddNewFromTypeMethodInfo.Add(interfaceType, methodInfo); } } return methodInfo; } /// <exclude /> public static MethodInfo GetExistsInAnyLocaleMethodInfo(Type interfaceType) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); if (typeof(IData).IsAssignableFrom(interfaceType) == false) throw new ArgumentException("The provided type must implement IData", "interfaceType"); MethodInfo methodInfo; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.GenericExistsInAnyLocaleMethodInfo.TryGetValue(interfaceType, out methodInfo) == false) { methodInfo = (from method in typeof(DataFacade).GetMethods(BindingFlags.Static | BindingFlags.NonPublic) where method.Name == nameof(ExistsInAnyLocale) && typeof(IEnumerable).IsAssignableFrom(method.GetParameters()[0].ParameterType) == false select method).First(); methodInfo = methodInfo.MakeGenericMethod(interfaceType); _resourceLocker.Resources.GenericExistsInAnyLocaleMethodInfo.Add(interfaceType, methodInfo); } } return methodInfo; } /// <exclude /> public static MethodInfo GetExistsInAnyLocaleWithParamMethodInfo(Type interfaceType) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); if (!typeof(IData).IsAssignableFrom(interfaceType)) throw new ArgumentException("The provided type must implement IData", "interfaceType"); MethodInfo methodInfo; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.GenericExistsInAnyLocaleWithParamMethodInfo.TryGetValue(interfaceType, out methodInfo) == false) { methodInfo = (from method in typeof(DataFacade).GetMethods(BindingFlags.Static | BindingFlags.Public) where method.Name == nameof(ExistsInAnyLocale) && method.GetParameters().Length == 1 && typeof(IEnumerable).IsAssignableFrom(method.GetParameters()[0].ParameterType) select method).First(); methodInfo = methodInfo.MakeGenericMethod(interfaceType); _resourceLocker.Resources.GenericExistsInAnyLocaleWithParamMethodInfo.Add(interfaceType, methodInfo); } } return methodInfo; } #endregion private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private static class EmptyPredicate<T> where T : class { public static readonly Expression<Func<T, bool>> Instance = f => true; } private sealed class Resources { public Dictionary<Type, MethodInfo> GenericSetDataInterceptorMethodInfo { get; set; } public Dictionary<Type, MethodInfo> GenericHasDataInterceptorMethodInfo { get; set; } public Dictionary<Type, MethodInfo> GenericClearDataInterceptorMethodInfo { get; set; } public Dictionary<Type, MethodInfo> GenericGetDataFromTypeMethodInfo { get; set; } public Dictionary<Type, MethodInfo> GenericGetDataFromDataSourceIdMethodInfo { get; set; } public Dictionary<Type, MethodInfo> GenericGetDataFromTypeWithPredicateMethodInfo { get; set; } public Dictionary<Type, MethodInfo> GenericAddNewFromTypeMethodInfo { get; set; } public Dictionary<Type, MethodInfo> GenericMoveFromTypeMethodInfo { get; set; } public Dictionary<Type, MethodInfo> GenericExistsInAnyLocaleMethodInfo { get; set; } public Dictionary<Type, MethodInfo> GenericExistsInAnyLocaleWithParamMethodInfo { get; set; } public static void DoInitializeResources(Resources resources) { resources.GenericSetDataInterceptorMethodInfo = new Dictionary<Type, MethodInfo>(); resources.GenericHasDataInterceptorMethodInfo = new Dictionary<Type, MethodInfo>(); resources.GenericClearDataInterceptorMethodInfo = new Dictionary<Type, MethodInfo>(); resources.GenericGetDataFromTypeMethodInfo = new Dictionary<Type, MethodInfo>(); resources.GenericGetDataFromDataSourceIdMethodInfo = new Dictionary<Type, MethodInfo>(); resources.GenericGetDataFromTypeWithPredicateMethodInfo = new Dictionary<Type, MethodInfo>(); resources.GenericAddNewFromTypeMethodInfo = new Dictionary<Type, MethodInfo>(); resources.GenericMoveFromTypeMethodInfo = new Dictionary<Type, MethodInfo>(); resources.GenericExistsInAnyLocaleMethodInfo = new Dictionary<Type, MethodInfo>(); resources.GenericExistsInAnyLocaleWithParamMethodInfo = new Dictionary<Type, MethodInfo>(); } } } } ================================================ FILE: Composite/Data/DataFacadeImpl.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using Composite.C1Console.Security; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.Threading; using Composite.Core.Types; using Composite.Data.Caching; using Composite.Data.DynamicTypes; using Composite.Data.Foundation; using Composite.Data.Foundation.PluginFacades; using Composite.Data.Types; using Composite.Data.Validation; using Microsoft.Practices.EnterpriseLibrary.Validation; using Composite.Core; namespace Composite.Data { internal class DataFacadeImpl : IDataFacade { private static readonly string LogTitle = nameof(DataFacade); internal Dictionary<Type, DataInterceptor> GlobalDataInterceptors = new Dictionary<Type, DataInterceptor>(); static readonly Cache<string, IData> _dataBySourceIdCache = new Cache<string, IData>("Data by sourceId", 2000); private static readonly object _storeCreationLock = new object(); static DataFacadeImpl() { DataEventSystemFacade.SubscribeToDataAfterUpdate<IData>(OnDataChanged, true); DataEventSystemFacade.SubscribeToDataDeleted<IData>(OnDataChanged, true); DataEventSystemFacade.SubscribeToDataBeforeAdd<ICreationHistory>(SetCreationHistoryInformation, true); DataEventSystemFacade.SubscribeToDataBeforeAdd<IChangeHistory>(SetChangeHistoryInformation, true); DataEventSystemFacade.SubscribeToDataBeforeUpdate<IChangeHistory>(SetChangeHistoryInformation, true); } public IQueryable<T> GetData<T>(bool useCaching, IEnumerable<string> providerNames) where T : class, IData { IQueryable<T> resultQueryable; if (DataProviderRegistry.AllInterfaces.Contains(typeof (T))) { if (useCaching && providerNames == null && DataCachingFacade.IsDataAccessCacheEnabled(typeof (T))) { resultQueryable = DataCachingFacade.GetDataFromCache<T>( () => BuildQueryFromProviders<T>(null)); } else { resultQueryable = BuildQueryFromProviders<T>(providerNames); } } else { DataProviderRegistry.CheckInitializationErrors(typeof(T)); if (!typeof(T).GetCustomInterfaceAttributes<AutoUpdatebleAttribute>().Any()) { throw new ArgumentException($"The given interface type ({typeof (T)}) is not supported by any data providers"); } resultQueryable = new List<T>().AsQueryable(); } foreach (var dataInterceptor in GetDataInterceptors(typeof(T))) { try { resultQueryable = dataInterceptor.InterceptGetData<T>(resultQueryable); } catch (Exception ex) { Log.LogError(LogTitle, ex); } } return resultQueryable; } private IQueryable<T> BuildQueryFromProviders<T>(IEnumerable<string> providerNames) where T : class, IData { if (providerNames == null) { providerNames = DataProviderRegistry.GetDataProviderNamesByInterfaceType(typeof(T)); } var queries = new List<IQueryable<T>>(); foreach (string providerName in providerNames) { IQueryable<T> query = DataProviderPluginFacade.GetData<T>(providerName); queries.Add(query); } bool resultIsCached = queries.Count == 1 && queries[0] is ICachedQuery; if (resultIsCached) { return queries[0]; } return new DataFacadeQueryable<T>(queries); } public T GetDataFromDataSourceId<T>(DataSourceId dataSourceId, bool useCaching) where T : class, IData { Verify.ArgumentNotNull(dataSourceId, nameof(dataSourceId)); useCaching = useCaching && DataCachingFacade.IsTypeCacheable(typeof(T)); using (new DataScope(dataSourceId.DataScopeIdentifier, dataSourceId.LocaleScope)) { T resultData = null; string cacheKey = string.Empty; if (useCaching) { cacheKey = dataSourceId.ToString(); resultData = (T)_dataBySourceIdCache.Get(cacheKey); } if (resultData == null) { resultData = DataProviderPluginFacade.GetData<T>(dataSourceId.ProviderName, dataSourceId.DataId); if (useCaching && resultData != null && _dataBySourceIdCache.Enabled) { _dataBySourceIdCache.Add(cacheKey, resultData); } } if (useCaching && resultData != null) { resultData = DataWrappingFacade.Wrap(resultData); } foreach (var dataInterceptor in GetDataInterceptors(typeof(T))) { try { resultData = dataInterceptor.InterceptGetDataFromDataSourceId<T>(resultData); } catch (Exception ex) { Log.LogError(LogTitle, ex); } } return resultData; } } public IEnumerable<DataInterceptor> GetDataInterceptors(Type dataType) { DataInterceptor globalDataInterceptor = GlobalDataInterceptors .FirstOrDefault(kvp => kvp.Key.IsAssignableFrom(dataType)).Value; DataInterceptor threadedDataInterceptor = null; var threadData = ThreadDataManager.Current; if (threadData != null) { GetDataInterceptors(threadData).TryGetValue(dataType, out threadedDataInterceptor); } if (threadedDataInterceptor == null && globalDataInterceptor == null) { return Enumerable.Empty<DataInterceptor>(); } var dataInterceptors = new List<DataInterceptor> { threadedDataInterceptor, globalDataInterceptor }; return dataInterceptors.Where(d => d != null); } public void SetDataInterceptor<T>(DataInterceptor dataInterceptor) where T : class, IData { if (this.DataInterceptors.ContainsKey(typeof(T))) throw new InvalidOperationException("A data interceptor has already been set"); this.DataInterceptors.Add(typeof(T), dataInterceptor); Log.LogVerbose(LogTitle, $"Data interception added to the data type '{typeof (T)}' with interceptor type '{dataInterceptor.GetType()}'"); } public bool HasDataInterceptor<T>() where T : class, IData { return this.DataInterceptors.ContainsKey(typeof(T)); } public void ClearDataInterceptor<T>() where T : class, IData { if (this.DataInterceptors.ContainsKey(typeof(T))) { this.DataInterceptors.Remove(typeof(T)); Log.LogVerbose(LogTitle, $"Data interception cleared for the data type '{typeof (T)}'"); } } public void SetGlobalDataInterceptor<T>(DataInterceptor dataInterceptor) where T : class, IData { if (GlobalDataInterceptors.ContainsKey(typeof(T))) throw new InvalidOperationException("A data interceptor has already been set"); GlobalDataInterceptors.Add(typeof(T), dataInterceptor); Log.LogVerbose(LogTitle, $"Global Data interception added to the data type '{typeof (T)}' with interceptor type '{dataInterceptor.GetType()}'"); } public bool HasGlobalDataInterceptor<T>() where T : class, IData { return GlobalDataInterceptors.ContainsKey(typeof(T)); } public void ClearGlobalDataInterceptor<T>() where T : class, IData { if (GlobalDataInterceptors.ContainsKey(typeof(T))) { GlobalDataInterceptors.Remove(typeof(T)); Log.LogVerbose(LogTitle, $"Global Data interception cleared for the data type '{typeof (T)}'"); } } private Dictionary<Type, DataInterceptor> GetDataInterceptors(ThreadDataManagerData threadData) { Verify.ArgumentNotNull(threadData, nameof(threadData)); const string threadDataKey = "DataFacade:DataInterceptors"; var dataInterceptors = threadData.GetValue(threadDataKey) as Dictionary<Type, DataInterceptor>; if (dataInterceptors == null) { dataInterceptors = new Dictionary<Type, DataInterceptor>(); threadData.SetValue(threadDataKey, dataInterceptors); } return dataInterceptors; } private Dictionary<Type, DataInterceptor> DataInterceptors => GetDataInterceptors(ThreadDataManager.Current); public void Update(IEnumerable<IData> dataset, bool suppressEventing, bool performForeignKeyIntegrityCheck, bool performValidation) { Verify.ArgumentNotNull(dataset, "dataset"); var sortedDataset = dataset.ToDataProviderAndInterfaceTypeSortedDictionary(); if (!suppressEventing) { foreach (IData data in dataset) { DataEventSystemFacade.FireDataBeforeUpdateEvent(data.DataSourceId.InterfaceType, data); } } foreach (IData data in dataset) { if (performValidation) { CheckValidationResult(ValidationFacade.Validate(data), data.DataSourceId.InterfaceType); } if (performForeignKeyIntegrityCheck) { data.ValidateForeignKeyIntegrity(); } } foreach (KeyValuePair<string, Dictionary<Type, List<IData>>> providerPair in sortedDataset) { foreach (KeyValuePair<Type, List<IData>> interfaceTypePair in providerPair.Value) { List<IData> dataToUpdate = interfaceTypePair.Value; if (DataCachingFacade.IsTypeCacheable(interfaceTypePair.Key)) { var newDataToUpdate = new List<IData>(); foreach (IData d in interfaceTypePair.Value) { newDataToUpdate.Add(DataWrappingFacade.UnWrap(d)); } dataToUpdate = newDataToUpdate; } DataProviderPluginFacade.Update(providerPair.Key, dataToUpdate); if (DataCachingFacade.IsTypeCacheable(interfaceTypePair.Key)) { DataCachingFacade.UpdateCachedData(dataToUpdate); } } } if (!suppressEventing) { foreach (IData data in dataset) { DataEventSystemFacade.FireDataAfterUpdateEvent(data.DataSourceId.InterfaceType, data); } } } private List<string> GetWritableDataProviders(Type type) { var dataProviders = DataProviderRegistry.GetWriteableDataProviderNamesByInterfaceType(type); if (dataProviders.Count > 1 && dataProviders.Contains(DataProviderRegistry.DefaultDynamicTypeDataProviderName)) { dataProviders = new List<string> { DataProviderRegistry.DefaultDynamicTypeDataProviderName }; } return dataProviders; } public List<T> AddNew<T>(IEnumerable<T> datas, bool allowStoreCreation, bool suppressEventing, bool performForeignKeyIntegrityCheck, bool performValidation, List<string> writeableProviders) where T : class, IData { if (writeableProviders == null) { writeableProviders = GetWritableDataProviders(typeof (T)); } if (writeableProviders.Count == 0 && typeof(T).GetCustomInterfaceAttributes<AutoUpdatebleAttribute>().Any() && allowStoreCreation) { if (!DataTypeTypesManager.IsAllowedDataTypeAssembly(typeof(T))) { string message = $"The data interface '{typeof(T)}' is not located in an assembly in the website Bin folder. Please move it to that location"; Log.LogError(LogTitle, message); throw new InvalidOperationException(message); } lock (_storeCreationLock) { writeableProviders = GetWritableDataProviders(typeof (T)); if (writeableProviders.Count == 0) { Log.LogVerbose(LogTitle, $"Type data interface '{typeof(T)}' is marked auto updateble and is not supported by any providers. Adding it to the default dynamic type data provider"); DynamicTypeManager.EnsureCreateStore(typeof(T)); return AddNew<T>(datas, false, suppressEventing, performForeignKeyIntegrityCheck, performValidation, null); } } } if (writeableProviders.Count == 1) { return AddNew_AddingMethod<T>(writeableProviders[0], datas, suppressEventing, performForeignKeyIntegrityCheck, performValidation); } throw new InvalidOperationException($"{writeableProviders.Count} writeable data providers exists for data '{typeof(T)}'."); } private static List<T> AddNew_AddingMethod<T>(string providerName, IEnumerable<T> dataset, bool suppressEventing, bool performForeignKeyIntegrityCheck, bool performValidation) where T : class, IData { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); Verify.ArgumentNotNull(dataset, "dataset"); Verify.ArgumentCondition(!dataset.Contains(null), "dataset", "The enumeration may not contain null values"); List<string> writeableProviders = DataProviderRegistry.GetWriteableDataProviderNamesByInterfaceType(typeof(T)); if (!writeableProviders.Contains(providerName)) { Log.LogVerbose(LogTitle, $"Type data interface '{typeof(T)}' is marked auto updateable and is not supported by the provider '{providerName}', adding it"); DynamicTypeManager.EnsureCreateStore(typeof(T), providerName); } writeableProviders = DataProviderRegistry.GetWriteableDataProviderNamesByInterfaceType(typeof(T)); if (!writeableProviders.Contains(providerName)) { throw new InvalidOperationException($"The writeable data providers '{providerName}' does not support the interface '{typeof(T)}'."); } foreach (T data in dataset) { if (performValidation) { CheckValidationResult(ValidationFacade.Validate<T>(data), typeof (T)); } if (performForeignKeyIntegrityCheck) { data.ValidateForeignKeyIntegrity(); } } if (!suppressEventing) { foreach (T data in dataset) { DataEventSystemFacade.FireDataBeforeAddEvent<T>(data); } } List<T> addedDataset = DataProviderPluginFacade.AddNew<T>(providerName, dataset); DataCachingFacade.AddDataToCache(addedDataset); if (!suppressEventing) { foreach (T data in addedDataset) { DataEventSystemFacade.FireDataAfterAddEvent<T>(data); } } return addedDataset; } public void Delete<T>(IEnumerable<T> dataset, bool suppressEventing, CascadeDeleteType cascadeDeleteType, bool referencesFromAllScopes) where T : class, IData { Delete(dataset, suppressEventing, cascadeDeleteType, referencesFromAllScopes, new HashSet<DataSourceId>()); } 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 data in dataset) { Verify.ArgumentCondition(data != null, nameof(dataset), "dataset may not contain nulls"); Type interfaceType = data.DataSourceId.InterfaceType; // Not deleting references if the data is versioned and not all of the // versions of the element are to be deleted if (data is IVersioned && interfaceType.GetKeyProperties().Count == 1) { var key = data.GetUniqueKey(); var versions = DataFacade.TryGetDataVersionsByUniqueKey(interfaceType, key).ToList(); if (versions.Count > 1 && (dataset.Count() < versions.Count || !versions.All(v => dataPendingDeletion.Contains(v.DataSourceId)))) { continue; } } using (new DataScope(data.DataSourceId.DataScopeIdentifier)) { var allReferences = DataReferenceFacade.GetRefereesInt(data, referencesFromAllScopes, (a, b) => true); if (allReferences.Count == 0) continue; Verify.IsTrue(cascadeDeleteType != CascadeDeleteType.Disallow, "One of the given datas is referenced by one or more datas"); var optionalReferences = allReferences.Where(kvp => kvp.Item2.IsOptionalReference); var notOptionalReferences = allReferences.Where(kvp => !kvp.Item2.IsOptionalReference && !dataPendingDeletion.Contains(kvp.Item1.DataSourceId)).Evaluate(); foreach (var reference in optionalReferences) { var referee = reference.Item1; reference.Item2.SourcePropertyInfo.SetValue(referee, null, null); DataFacade.Update(referee, false, true, false); } foreach (var refereeInfo in notOptionalReferences) { if (!refereeInfo.Item2.AllowCascadeDeletes) { throw new InvalidOperationException("One of the given data items is referenced by one or more data items that do not allow cascade delete."); } } var toDelete = notOptionalReferences.Select(_ => _.Item1); Delete<IData>(toDelete, 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.RemoveDataFromCache(interfaceTypePair.Value); } } } if (!suppressEventing) { foreach (IData element in dataset) { DataEventSystemFacade.FireDataDeletedEvent(element.DataSourceId.InterfaceType, element); } } } public T BuildNew<T>(bool suppressEventing) where T : class, IData { ValidateBuildNewType(typeof(T)); Type generatedType = DataTypeTypesManager.GetDataTypeEmptyClass(typeof(T)); IData data = (IData)Activator.CreateInstance(generatedType, new object[] { }); SetNewInstanceFieldDefaultValues(data); if (suppressEventing == false) { DataEventSystemFacade.FireDataAfterBuildNewEvent<T>(data); } return (T)data; } public IData BuildNew(Type interfaceType, bool suppressEventling) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); ValidateBuildNewType(interfaceType); Type generatedType = DataTypeTypesManager.GetDataTypeEmptyClass(interfaceType); IData data = (IData)Activator.CreateInstance(generatedType, new object[] { }); SetNewInstanceFieldDefaultValues(data); if (!suppressEventling) { DataEventSystemFacade.FireDataAfterBuildNewEvent(generatedType, data); } return data; } private void ValidateBuildNewType(Type interfaceType) { string errorMessage; if(!DataTypeValidationRegistry.Validate(interfaceType, null, out errorMessage)) { Log.LogCritical(LogTitle, errorMessage); throw new InvalidOperationException(errorMessage); } } private void SetNewInstanceFieldDefaultValues(IData data) { Type interfaceType = data.DataSourceId.InterfaceType; List<PropertyInfo> properties = interfaceType.GetPropertiesRecursively(); foreach (PropertyInfo propertyInfo in properties) { try { var attribute = propertyInfo.GetCustomAttributesRecursively<NewInstanceDefaultFieldValueAttribute>().SingleOrDefault(); if (attribute == null || !attribute.HasValue) continue; if (!propertyInfo.CanWrite) { Log.LogError(LogTitle, string.Format("The property '{0}' on the interface '{1}' has defined a standard value, but no setter", propertyInfo.Name, interfaceType)); continue; } object value = attribute.GetValue(); value = ValueTypeConverter.Convert(value, propertyInfo.PropertyType); PropertyInfo targetPropertyInfo = data.GetType().GetProperties().Single(f => f.Name == propertyInfo.Name); targetPropertyInfo.SetValue(data, value, null); } catch (Exception ex) { Log.LogError(LogTitle, string.Format("Failed to set the standard value on the property '{0}' on the interface '{1}'", propertyInfo.Name, interfaceType)); Log.LogError(LogTitle, ex); } } } public bool ExistsInAnyLocale<T>(IEnumerable<CultureInfo> excludedCultureInfoes) where T : class, IData { foreach (CultureInfo cultureInfo in DataLocalizationFacade.ActiveLocalizationCultures.Except(excludedCultureInfoes)) { using (new DataScope(cultureInfo)) { bool exists = DataFacade.GetData<T>().Any(); if (exists) { return true; } } } return false; } public bool ValidatePath<TFile>(TFile file, string providerName, out string errorMessage) where TFile : IFile { return DataProviderPluginFacade.ValidatePath<TFile>(file, providerName, out errorMessage); } private static void CheckValidationResult(ValidationResults validationResults, Type interfaceType) { if (validationResults.IsValid) { return; } System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (ValidationResult result in validationResults) { sb.AppendLine("Field: '{0}' Error: {1}".FormatWith(result.Key, result.Message)); } string msg = "The data of type '{0}' did not validate, with the following errors:\r\n{1}".FormatWith(interfaceType, sb); throw new InvalidOperationException(msg); } private static void OnDataChanged(object sender, DataEventArgs dataEventArgs) { _dataBySourceIdCache.Remove(dataEventArgs.Data.DataSourceId.ToString()); } private static void SetChangeHistoryInformation(object sender, DataEventArgs dataEventArgs) { IChangeHistory data = dataEventArgs.Data as IChangeHistory; if (data != null) { data.ChangeDate = DateTime.Now; try { if (UserValidationFacade.IsLoggedIn()) { data.ChangedBy = UserValidationFacade.GetUsername(); } } catch { // silent } } } private static void SetCreationHistoryInformation(object sender, DataEventArgs dataEventArgs) { ICreationHistory data = dataEventArgs.Data as ICreationHistory; if (data != null) { if (data.CreationDate == DateTime.MinValue) { data.CreationDate = DateTime.Now; } try { if (string.IsNullOrEmpty(data.CreatedBy) && UserValidationFacade.IsLoggedIn()) { data.CreatedBy = UserValidationFacade.GetUsername(); } } catch { // silent } } } } } ================================================ FILE: Composite/Data/DataIconFacade.cs ================================================ using System; using System.Linq; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; using Composite.Data.ProcessControlled; using Composite.Core.ResourceSystem.Icons; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; namespace Composite.Data { internal static class DataIconFacade { public static ResourceHandle DataIcon = GetIconHandle("data"); public static ResourceHandle DataDraftIcon { get { return GetIconHandle("data-draft"); } } public static ResourceHandle DataAwaitingApprovalIcon { get { return GetIconHandle("data-awaiting-approval"); } } public static ResourceHandle DataAwaitingPublicationIcon { get { return GetIconHandle("data-awaiting-publication"); } } public static ResourceHandle DataPublishedIcon { get { return GetIconHandle("data-published"); } } public static ResourceHandle DataGhostedIcon { get { return GetIconHandle("data-ghosted"); } } public static ResourceHandle DataDisabledIcon { get { return GetIconHandle("data-disabled"); } } public static ResourceHandle GetIcon(this IData data) { IPublishControlled publishControlled = data as IPublishControlled; if (publishControlled == null) { return DataIcon; } switch (publishControlled.PublicationStatus) { case GenericPublishProcessController.Draft: return DataDraftIcon; case GenericPublishProcessController.AwaitingApproval: return DataAwaitingApprovalIcon; case GenericPublishProcessController.AwaitingPublication: return DataAwaitingPublicationIcon; case GenericPublishProcessController.Published: return DataPublishedIcon; default: var allowedPublicationStatuses = new[] { GenericPublishProcessController.Draft, GenericPublishProcessController.AwaitingApproval, GenericPublishProcessController.AwaitingPublication, GenericPublishProcessController.Published }; string allowedValues = string.Join(", ", allowedPublicationStatuses.Select(status => "'" + status + "'")); throw new InvalidOperationException("Unexpected publication status '{0}'. Allowed values: {1}" .FormatWith(publishControlled.PublicationStatus ?? "(null)", allowedValues)); } } public static ResourceHandle GetForeignIcon(this IData data) { return data.IsTranslatable() ? DataGhostedIcon : DataDisabledIcon; } [Obsolete("Use !data.IsTranslatable() instead")] public static bool IsLocaleDisabled(this IData data) { return !IsTranslatable(data); } /// <summary> /// Checks whether the specified data item can be translated. /// </summary> /// <param name="data"></param> /// <returns></returns> public static bool IsTranslatable(this IData data) { IPublishControlled publishControlled = data as IPublishControlled; if (!GlobalSettingsFacade.OnlyTranslateWhenApproved || publishControlled == null) { return true; } switch (publishControlled.PublicationStatus) { case GenericPublishProcessController.Draft: case GenericPublishProcessController.AwaitingApproval: using (new DataScope(data.DataSourceId.LocaleScope)) { return DataFacade.GetDataFromOtherScope(data, DataScopeIdentifier.Public).Any(); } case GenericPublishProcessController.AwaitingPublication: case GenericPublishProcessController.Published: return true; default: throw new InvalidOperationException("Unexpected publication status: " + (publishControlled.PublicationStatus ?? "(null)")); } } /// <summary> /// Returns the data item either from "Administrated" or from "Public" scope depending on, which has to be used as translation source. /// If onlyTranslateWhenApproved="true" or publication status is not "awaiting publishion" - item from the public scope will be returned. /// </summary> /// <param name="dataFromAdministratedScope">The data item</param> /// <returns></returns> public static T GetTranslationSource<T>(this T dataFromAdministratedScope) where T: class, IData { IPublishControlled publishControlled = dataFromAdministratedScope as IPublishControlled; if (!GlobalSettingsFacade.OnlyTranslateWhenApproved || publishControlled == null || publishControlled.PublicationStatus == GenericPublishProcessController.AwaitingPublication) { return dataFromAdministratedScope; } using (new DataScope(dataFromAdministratedScope.DataSourceId.LocaleScope)) { return (DataFacade.GetDataFromOtherScope(dataFromAdministratedScope as IData, DataScopeIdentifier.Public) .FirstOrDefault() ?? dataFromAdministratedScope) as T; } } private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } } } ================================================ FILE: Composite/Data/DataIdKeyFacade.cs ================================================ using System; using Composite.C1Console.Events; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DataIdKeyFacade { private static IDataIdKeyFacade _implementation = new DataIdKeyFacadeImpl(); /// <exclude /> static DataIdKeyFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } // Overload /// <exclude /> public static T GetKeyValue<T>(this DataSourceId dataSourceId, string keyName = null) { if (keyName == null) { keyName = dataSourceId.InterfaceType.GetSingleKeyProperty().Name; } return (T)_implementation.GetKeyValue(dataSourceId.DataId, keyName); } // Overload /// <exclude /> public static T GetKeyValue<T>(IDataId dataId, string keyName = null) { return (T)_implementation.GetKeyValue(dataId, keyName); } // Overload /// <exclude /> public static object GetKeyValue(this DataSourceId dataSourceId, string keyName = null) { Verify.ArgumentNotNull(dataSourceId, nameof(dataSourceId)); if (keyName == null) { keyName = dataSourceId.InterfaceType.GetSingleKeyProperty().Name; } return _implementation.GetKeyValue(dataSourceId.DataId, keyName); } /// <exclude /> public static object GetKeyValue(IDataId dataId, string keyName = null) { return _implementation.GetKeyValue(dataId, keyName); } // Overload /// <exclude /> public static string GetDefaultKeyName(IDataId dataId) { return _implementation.GetDefaultKeyName(dataId.GetType()); } /// <exclude /> public static string GetDefaultKeyName(Type dataIdType) { return _implementation.GetDefaultKeyName(dataIdType); } private static void Flush() { _implementation.OnFlush(); } } } ================================================ FILE: Composite/Data/DataIdKeyFacadeImpl.cs ================================================ using System; using System.Collections.Concurrent; using System.Reflection; namespace Composite.Data { internal class DataIdKeyFacadeImpl : IDataIdKeyFacade { private ConcurrentDictionary<Type, string> _defaultKeyNameCache = new ConcurrentDictionary<Type, string>(); private ConcurrentDictionary<Type, PropertyInfo> _keyPropertyInfoCache = new ConcurrentDictionary<Type, PropertyInfo>(); public object GetKeyValue(IDataId dataId, string keyName) { if (keyName == null) { keyName = this.GetDefaultKeyName(dataId.GetType()); if (keyName == null) throw new InvalidOperationException("Could not find default key for the type: " + dataId.GetType()); } Func<Type, PropertyInfo> valueFactory = f => f.GetProperty(keyName); PropertyInfo keyPropertyInfo = _keyPropertyInfoCache.GetOrAdd(dataId.GetType(), valueFactory); object keyValue = keyPropertyInfo.GetValue(dataId, null); return keyValue; } public string GetDefaultKeyName(Type dataIdType) { Func<Type, string> valueFactory = f => { PropertyInfo[] propertyInfoes = f.GetProperties(); if (propertyInfoes.Length != 1) return null; return propertyInfoes[0].Name; }; string defaultKeyName = _defaultKeyNameCache.GetOrAdd(dataIdType, valueFactory); return defaultKeyName; } public void OnFlush() { _defaultKeyNameCache = new ConcurrentDictionary<Type, string>(); _keyPropertyInfoCache = new ConcurrentDictionary<Type, PropertyInfo>(); } } } ================================================ FILE: Composite/Data/DataIdSerializer.cs ================================================ using System; using System.Collections.Generic; using Composite.Core.Serialization; using Composite.Core.Types; using static Composite.Core.Serialization.StringConversionServices; namespace Composite.Data { internal static class DataIdSerializer { public static string Serialize(this IDataId dataId, IEnumerable<string> propertyNames) { if (dataId == null) throw new ArgumentNullException(nameof(dataId)); return CompositeJsonSerializer.SerializePartial(dataId,propertyNames); } public static IDataId Deserialize(string serializedId, string serializedVersionId) { var serializedIdIsJson = CompositeJsonSerializer.IsJsonSerialized(serializedId); var serializedVersionIdIsJson = CompositeJsonSerializer.IsJsonSerialized(serializedVersionId); if (serializedIdIsJson) { if (string.IsNullOrWhiteSpace(serializedVersionId)) return CompositeJsonSerializer.Deserialize<IDataId>(serializedId); if (serializedVersionIdIsJson) return CompositeJsonSerializer.Deserialize<IDataId>(serializedId, serializedVersionId); } else if (!serializedVersionIdIsJson) { return DeserializeLegacy(serializedId, serializedVersionId); } throw new ArgumentException($"{nameof(IDataId)} is not serialized properly.", nameof(serializedId) + " and " + nameof(serializedVersionId)); } public static IDataId DeserializeLegacy(string serializedId, string serializedVersionId) { Dictionary<string, string> dataIdValues = ParseKeyValueCollection(serializedId); if (!dataIdValues.ContainsKey("_dataIdType_") || !dataIdValues.ContainsKey("_dataId_")) { throw new ArgumentException("The serializedId is not a serialized id", nameof(serializedId)); } string dataIdType = DeserializeValueString(dataIdValues["_dataIdType_"]); string serializedIdString = DeserializeValueString(dataIdValues["_dataId_"]); string serializedVersionIdString = ""; if (!string.IsNullOrEmpty(serializedVersionId)) { Dictionary<string, string> versionValues = ParseKeyValueCollection(serializedVersionId); if (!versionValues.ContainsKey("_dataIdType_") || !versionValues.ContainsKey("_dataId_")) { throw new ArgumentException("The serializedVersionId is not a serialized version id", nameof(serializedVersionId)); } if (dataIdValues["_dataIdType_"] != versionValues["_dataIdType_"]) { throw new ArgumentException("Serialized id and version id have different types", nameof(serializedId)); } serializedVersionIdString = DeserializeValueString(versionValues["_dataId_"]); } Type type = TypeManager.TryGetType(dataIdType); if (type == null) { throw new InvalidOperationException($"The type {dataIdType} could not be found"); } IDataId dataId = SerializationFacade.Deserialize<IDataId>(type, string.Join("", serializedIdString, serializedVersionIdString)); return dataId; } } } ================================================ FILE: Composite/Data/DataInterceptor.cs ================================================ using System.Collections.Generic; using System.Linq; namespace Composite.Data { /// <summary> /// Let you transform queries before data providers. Enable you to augment queries from alternate sources. /// </summary> public abstract class DataInterceptor { /// <summary> /// Let you transform queries before data providers. Enable you to augment queries from alternate sources. /// </summary> public virtual IQueryable<T> InterceptGetData<T>(IQueryable<T> dataset) where T : class, IData { return dataset; } /// <summary> /// Let you transform an in-memory result-set. /// This transformation should behave exactly as the IQueryable equivalent. /// </summary> public virtual IEnumerable<T> InterceptGetData<T>(IEnumerable<T> dataset) where T : class, IData { return InterceptGetData(dataset.AsQueryable()); } /// <summary> /// Enable you to intercept queries for a single data item. /// </summary> public virtual T InterceptGetDataFromDataSourceId<T>(T data) where T : class, IData { return data; } } } ================================================ FILE: Composite/Data/DataKeyPropertyCollection.cs ================================================ using System; using System.Collections.Generic; using System.Reflection; using System.Text; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DataKeyPropertyCollection { private readonly Dictionary<string, object> _keyProperties = new Dictionary<string, object>(); /// <exclude /> public void AddKeyProperty(PropertyInfo propertyInfo, object value) { if (propertyInfo == null) throw new ArgumentNullException("propertyInfo"); if (value == null) throw new ArgumentNullException("value"); AddKeyProperty(propertyInfo.Name, value); } /// <exclude /> public void AddKeyProperty(string keyPropertyName, object value) { if (keyPropertyName == null) throw new ArgumentNullException("keyPropertyName"); if (value == null) throw new ArgumentNullException("value"); if (_keyProperties.ContainsKey(keyPropertyName)) throw new ArgumentException(string.Format("The key property name '{0}' has already been added", keyPropertyName)); _keyProperties.Add(keyPropertyName, value); } /// <exclude /> public bool TryGetKeyValue(string keyPropertyName, out object value) { return _keyProperties.TryGetValue(keyPropertyName, out value); } /// <exclude /> public IEnumerable<KeyValuePair<string, object>> KeyProperties { get { return _keyProperties; } } /// <exclude /> public int Count { get { return _keyProperties.Count; } } /// <exclude /> public override bool Equals(object obj) { return Equals(obj as DataKeyPropertyCollection); } /// <exclude /> public bool Equals(DataKeyPropertyCollection dataKeyPropertyCollection) { if (dataKeyPropertyCollection == null || dataKeyPropertyCollection.Count != Count) return false; foreach (var kvp in this.KeyProperties) { object value; if (!dataKeyPropertyCollection.TryGetKeyValue(kvp.Key, out value) || !kvp.Value.Equals(value)) { return false; } } return true; } /// <exclude /> public override int GetHashCode() { int hashCode = 0; foreach (var kvp in _keyProperties) { hashCode ^= kvp.Key.GetHashCode(); hashCode ^= kvp.Value.GetHashCode(); } return hashCode; } /// <exclude /> public override string ToString() { var sb = new StringBuilder(); foreach (var kvp in _keyProperties) { if (sb.Length > 0) sb.Append(", "); sb.AppendFormat("{0} = '{1}'", kvp.Key, kvp.Value); } return sb.ToString(); } } } ================================================ FILE: Composite/Data/DataKeyPropertyCollectionExtensionMethods.cs ================================================ using System.Reflection; namespace Composite.Data { internal static class DataKeyPropertyCollectionExtensionMethods { public static DataKeyPropertyCollection CreateDataKeyPropertyCollection(this IData data) { Verify.ArgumentNotNull(data, "data"); var dataKeyPropertyCollection = new DataKeyPropertyCollection(); foreach (PropertyInfo propertyInfo in data.GetKeyProperties()) { object value = propertyInfo.GetValue(data, null); dataKeyPropertyCollection.AddKeyProperty(propertyInfo, value); } return dataKeyPropertyCollection; } } } ================================================ FILE: Composite/Data/DataLocalizationFacade.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using Composite.Core.ResourceSystem; using Composite.Data.ProcessControlled; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DataLocalizationFacade { private static IDataLocalizationFacade _dataLocalizationFacade = new DataLocalizationFacadeImpl(); internal static IDataLocalizationFacade Implementation { get { return _dataLocalizationFacade; } set { _dataLocalizationFacade = value; } } /// <exclude /> public static bool UseLocalization { get { return _dataLocalizationFacade.UseLocalization; } } /// <exclude /> public static IEnumerable<CultureInfo> WhiteListedLocales { get { return _dataLocalizationFacade.WhiteListedLocales; } } /// <exclude /> public static CultureInfo DefaultUrlMappingCulture { get { return _dataLocalizationFacade.DefaultUrlMappingCulture; } } /// <exclude /> public static CultureInfo DefaultLocalizationCulture { get { return _dataLocalizationFacade.DefaultLocalizationCulture; } internal set { _dataLocalizationFacade.DefaultLocalizationCulture = value; } } // Overload to ActiveLocalizationNames /// <exclude /> public static IEnumerable<CultureInfo> ActiveLocalizationCultures { get { foreach (string cultureName in _dataLocalizationFacade.ActiveLocalizationNames) { yield return CultureInfo.CreateSpecificCulture(cultureName); } } } /// <exclude /> public static IEnumerable<string> ActiveLocalizationNames { get { return _dataLocalizationFacade.ActiveLocalizationNames; } } /// <exclude /> public static string GetUrlMappingName(CultureInfo cultureInfo) { return _dataLocalizationFacade.GetUrlMappingName(cultureInfo); } /// <exclude /> public static CultureInfo GetCultureInfoByUrlMappingName(string urlMappingName) { return _dataLocalizationFacade.GetCultureInfoByUrlMappingName(urlMappingName); } /// <exclude /> public static IEnumerable<string> UrlMappingNames { get { return _dataLocalizationFacade.UrlMappingNames; } } // Overlaod /// <summary> /// Tells if a IData is currently localized or not /// </summary> /// <param name="data"></param> /// <returns></returns> public static bool IsLocalized(this IData data) { if (data == null) throw new ArgumentNullException("data"); return IsLocalized(data.DataSourceId.InterfaceType); } /// <summary> /// Tells if a IData is currently localized or not /// </summary> /// <param name="type"></param> /// <returns></returns> public static bool IsLocalized(Type type) { if (type == null) throw new ArgumentNullException("type"); return _dataLocalizationFacade.IsLocalized(type); } // Overload /// <summary> /// Tells if a type can be localized. Currently is dynamic types and IPage that /// can be localized. This does not tell if the given type IS currently localized. /// </summary> /// <param name="data"></param> /// <returns></returns> public static bool IsLocalizable(this IData data) { if (data == null) throw new ArgumentNullException("data"); return IsLocalizable(data.DataSourceId.InterfaceType); } /// <summary> /// Tells if a type can be localized. Currently is dynamic types and IPage that /// can be localized. This does not tell if the given type IS currently localized. /// </summary> /// <param name="type"></param> /// <returns></returns> public static bool IsLocalizable(Type type) { if (type == null) throw new ArgumentNullException("type"); return _dataLocalizationFacade.IsLocalizable(type); } /// <exclude /> public static IEnumerable<ReferenceFailingPropertyInfo> GetReferencingLocalizeFailingProperties(ILocalizedControlled data) { return _dataLocalizationFacade.GetReferencingLocalizeFailingProperties(data); } /// <exclude /> public static string GetCultureTitle(CultureInfo culture) { return _dataLocalizationFacade.GetCultureTitle(culture); } } } ================================================ FILE: Composite/Data/DataLocalizationFacadeImpl.cs ================================================ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using Composite.Core.ResourceSystem; using Composite.Core.Threading; using Composite.Data.Caching; using Composite.Data.ProcessControlled; using Composite.Data.Types; using Composite.Core.Logging; using Composite.Data.DynamicTypes; using Composite.Core.Extensions; using Composite.Core.Types; using System.Reflection; namespace Composite.Data { internal class DataLocalizationFacadeImpl : IDataLocalizationFacade { private static readonly string LogTitle = "LocalizationFacade"; private static readonly Cache<string, CultureInfo> _urlMappingCache = new Cache<string, CultureInfo>("UrlCultureMapping", 70); private static readonly Cache<string, string> _cultureUrlCache = new Cache<string, string>("CultureUrlMapping", 70); private static ReadOnlyCollection<string> _urlMappings; private static ReadOnlyCollection<string> _activeCultureNames; private static ExtendedNullable<CultureInfo> _defaultCulture; private static ExtendedNullable<CultureInfo> _defaultUrlMappingCulture; private static readonly object _syncRoot = new object(); static DataLocalizationFacadeImpl() { DataEventSystemFacade.SubscribeToDataAfterUpdate<ISystemActiveLocale>(OnSystemActiveLocaleChanged, true); DataEventSystemFacade.SubscribeToDataAfterAdd<ISystemActiveLocale>(OnSystemActiveLocaleChanged, true); DataEventSystemFacade.SubscribeToDataDeleted<ISystemActiveLocale>(OnSystemActiveLocaleChanged, true); DataEventSystemFacade.SubscribeToStoreChanged<ISystemActiveLocale>(OnSystemActiveLocaleStoreChanged, true); } private static void OnSystemActiveLocaleStoreChanged(object sender, StoreEventArgs storeEventArgs) { if (!storeEventArgs.DataEventsFired) { _urlMappingCache.Clear(); _cultureUrlCache.Clear(); lock (_syncRoot) { _urlMappings = null; _activeCultureNames = null; _defaultUrlMappingCulture = null; _defaultCulture = null; } } } private static void OnSystemActiveLocaleChanged(object sender, DataEventArgs dataEventArgs) { var locale = dataEventArgs.Data as ISystemActiveLocale; if (locale != null) { _urlMappingCache.Remove(locale.UrlMappingName); _cultureUrlCache.Remove(locale.CultureName); lock (_syncRoot) { _urlMappings = null; _activeCultureNames = null; _defaultUrlMappingCulture = null; _defaultCulture = null; } } } public bool UseLocalization { get { return DataFacade.GetData<ISystemActiveLocale>().Count() > 1; } } public IEnumerable<CultureInfo> WhiteListedLocales { get { return CultureInfo.GetCultures(CultureTypes.SpecificCultures); } } public CultureInfo DefaultUrlMappingCulture { get { ExtendedNullable<CultureInfo> result = _defaultUrlMappingCulture; if (result == null) { lock (_syncRoot) { if (_defaultUrlMappingCulture == null) { ISystemActiveLocale systemActiveLocale = (from data in DataFacade.GetData<ISystemActiveLocale>() where data.UrlMappingName == "" select data).FirstOrDefault(); CultureInfo cultureInfo = systemActiveLocale == null ? null : CultureInfo.CreateSpecificCulture(systemActiveLocale.CultureName); _defaultUrlMappingCulture = new ExtendedNullable<CultureInfo> {Value = cultureInfo}; } result = _defaultUrlMappingCulture; } } return result.Value; } } public CultureInfo DefaultLocalizationCulture { get { ExtendedNullable<CultureInfo> result = _defaultCulture; if (result == null) { lock (_syncRoot) { if (_defaultCulture == null) { List<string> culturesMarkedAsDefault; using (ThreadDataManager.EnsureInitialize()) { culturesMarkedAsDefault = (from data in DataFacade.GetData<ISystemActiveLocale>() where data.IsDefault select data.CultureName).ToList(); } CultureInfo cultureInfo = null; if (culturesMarkedAsDefault.Count > 0) { if (culturesMarkedAsDefault.Count > 1) { LoggingService.LogWarning(LogTitle, "There's more than one culture marked as 'default'"); } cultureInfo = CultureInfo.CreateSpecificCulture(culturesMarkedAsDefault[0]); } _defaultCulture = new ExtendedNullable<CultureInfo> { Value = cultureInfo }; } result = _defaultCulture; } } return result.Value; } set { Verify.ArgumentNotNull(value, "value"); string cultureName = value.Name; lock (_syncRoot) { using(var transactionScope = Data.Transactions.TransactionsFacade.CreateNewScope()) { List<ISystemActiveLocale> systemLocalesMarkedAsDefault = (from data in DataFacade.GetData<ISystemActiveLocale>() where data.IsDefault select data).ToList(); bool alreadyMarkedAsDefault = false; foreach(ISystemActiveLocale locale in systemLocalesMarkedAsDefault) { if(locale.CultureName == cultureName) { alreadyMarkedAsDefault = true; continue; } locale.IsDefault = false; DataFacade.Update(locale); } if(!alreadyMarkedAsDefault) { ISystemActiveLocale newDefaultCulture = (from data in DataFacade.GetData<ISystemActiveLocale>() where data.CultureName == cultureName select data).FirstOrDefault(); if (newDefaultCulture == null) { LoggingService.LogError(LogTitle, "Failed to get a locale by culture name '{0}'".FormatWith(cultureName)); return; } newDefaultCulture.IsDefault = true; DataFacade.Update(newDefaultCulture); } transactionScope.Complete(); } } LoggingService.LogVerbose(LogTitle, "Default localization culture changed to '{0}'".FormatWith(cultureName)); } } public IEnumerable<string> ActiveLocalizationNames { get { ReadOnlyCollection<string> _result = _activeCultureNames; if (_result == null) { lock (_syncRoot) { if (_activeCultureNames == null) { _activeCultureNames = new ReadOnlyCollection<string>( (from d in DataFacade.GetData<ISystemActiveLocale>() select d.CultureName).ToList()); } _result = _activeCultureNames; } } return _result; } } public string GetUrlMappingName(CultureInfo cultureInfo) { string urlMappingName = _cultureUrlCache.Get(cultureInfo.Name); if (urlMappingName == null) { urlMappingName = (from sal in DataFacade.GetData<ISystemActiveLocale>() as IEnumerable<ISystemActiveLocale> where sal.CultureName == cultureInfo.Name select sal.UrlMappingName).SingleOrDefault(); _cultureUrlCache.Add(cultureInfo.Name, urlMappingName); } return urlMappingName; } public CultureInfo GetCultureInfoByUrlMappingName(string urlMappingName) { CultureInfo cultureInfo = _urlMappingCache.Get(urlMappingName); if (cultureInfo == null) { string cultureName = (from sal in DataFacade.GetData<ISystemActiveLocale>() where string.Compare(sal.UrlMappingName, urlMappingName, StringComparison.OrdinalIgnoreCase) == 0 select sal.CultureName).Single(); cultureInfo = CultureInfo.CreateSpecificCulture(cultureName); _urlMappingCache.Add(urlMappingName, cultureInfo); } return cultureInfo; } public IEnumerable<string> UrlMappingNames { get { ReadOnlyCollection<string> _result = _urlMappings; if (_result == null) { lock (_syncRoot) { if (_urlMappings == null) { List<string> mappings = (from sal in DataFacade.GetData<ISystemActiveLocale>() select sal.UrlMappingName).ToList(); // Adding lower cased values for(int i=0; i<mappings.Count; i++) { string loweredValue = mappings[i].ToLowerInvariant(); if (mappings[i] != loweredValue) { mappings.Add(mappings[i].ToLowerInvariant()); } } _urlMappings = new ReadOnlyCollection<string>(mappings); } _result = _urlMappings; } } return _result; } } public bool IsLocalized(Type type) { if (type == null) throw new ArgumentNullException("type"); if (type == typeof(IPage)) return true; if (type == typeof(IPagePlaceholderContent)) return true; return typeof(ILocalizedControlled).IsAssignableFrom(type); } public bool IsLocalizable(Type type) { if (type == null) throw new ArgumentNullException("type"); if (type == typeof(IPage)) return true; if (type == typeof(IPagePlaceholderContent)) return true; if (type.IsGenerated()) return true; return typeof(ILocalizedControlled).IsAssignableFrom(type); } public IEnumerable<ReferenceFailingPropertyInfo> GetReferencingLocalizeFailingProperties(ILocalizedControlled data) { DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(data.DataSourceId.InterfaceType); IEnumerable<DataFieldDescriptor> requiredDataFieldDescriptors = dataTypeDescriptor.Fields.Where(f => f.ForeignKeyReferenceTypeName != null); foreach (DataFieldDescriptor dataFieldDescriptor in requiredDataFieldDescriptors) { Type referencedType = TypeManager.GetType(dataFieldDescriptor.ForeignKeyReferenceTypeName); if (!DataLocalizationFacade.IsLocalized(referencedType)) continue; // No special handling for not localized data. IData referencedData = data.GetReferenced(dataFieldDescriptor.Name); if (referencedData != null) continue; // Data has already been localized bool optionalReferenceWithValue = false; if (dataFieldDescriptor.IsNullable) { PropertyInfo propertyInfo = data.DataSourceId.InterfaceType.GetPropertiesRecursively().Single(f => f.Name == dataFieldDescriptor.Name); object value = propertyInfo.GetValue(data, null); if (value == null || object.Equals(value, dataFieldDescriptor.DefaultValue)) { continue; // Optional reference is null; } optionalReferenceWithValue = true; } CultureInfo locale = data.DataSourceId.LocaleScope; using (new DataScope(locale)) { referencedData = data.GetReferenced(dataFieldDescriptor.Name); } ReferenceFailingPropertyInfo referenceFailingPropertyInfo = new ReferenceFailingPropertyInfo ( dataFieldDescriptor, referencedType, referencedData, optionalReferenceWithValue ); yield return referenceFailingPropertyInfo; } } public string GetCultureTitle(CultureInfo culture) { return StringResourceSystemFacade.GetCultureTitle(culture); } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ReferenceFailingPropertyInfo { /// <exclude /> public ReferenceFailingPropertyInfo(DataFieldDescriptor dataFieldDescriptor, Type referencedType, IData originLocaleDataValue, bool optionalReferenceWithValue) { this.DataFieldDescriptor = dataFieldDescriptor; this.ReferencedType = referencedType; this.OriginLocaleDataValue = originLocaleDataValue; this.OptionalReferenceWithValue = optionalReferenceWithValue; } /// <summary> /// DataFieldDescriptor of the property that are the reference /// </summary> public DataFieldDescriptor DataFieldDescriptor { get; private set; } /// <summary> /// Data type that are refernced /// </summary> public Type ReferencedType { get; private set; } /// <summary> /// This holds the value of the reference in the same locale /// as the IData value given to the call to /// GetReferencingLocalizeFailingProperties /// This may be null in case of optional references /// </summary> public IData OriginLocaleDataValue { get; private set; } /// <summary> /// This is true if the reference is optional and /// if the referenced item is existing in the old locale. /// </summary> public bool OptionalReferenceWithValue { get; private set; } } } ================================================ FILE: Composite/Data/DataMetaDataFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Xml; using System.Xml.Linq; using Composite.C1Console.Events; using Composite.Core; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Linq; using Composite.Core.Types; using Composite.Core.Xml; using Composite.Data.DynamicTypes; using Composite.Data.DynamicTypes.Foundation; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DataMetaDataFacade { private static readonly string LogTitle = "DataMetaDataFacade"; private static Dictionary<Guid, DataTypeDescriptor> _dataTypeDescriptorCache; private static Dictionary<Guid, string> _dataTypeDescriptorFilesnamesCache; private static readonly object _lock = new object(); private static readonly string _metaDataPath; static DataMetaDataFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); _metaDataPath = PathUtil.Resolve(GlobalSettingsFacade.DataMetaDataDirectory); if (!C1Directory.Exists(_metaDataPath)) { C1Directory.CreateDirectory(_metaDataPath); } UpdateFilenames(); } private static void Initialize() { if (_dataTypeDescriptorCache != null) return; lock (_lock) { _dataTypeDescriptorCache = new Dictionary<Guid, DataTypeDescriptor>(); _dataTypeDescriptorFilesnamesCache = new Dictionary<Guid, string>(); string[] filepaths = C1Directory.GetFiles(_metaDataPath, "*.xml"); foreach (string filepath in filepaths) { var dataTypeDescriptor = LoadFromFile(filepath); Verify.That(!_dataTypeDescriptorCache.ContainsKey(dataTypeDescriptor.DataTypeId), "Data type with id '{0}' is already added. File: '{1}'", dataTypeDescriptor.DataTypeId, filepath); _dataTypeDescriptorCache.Add(dataTypeDescriptor.DataTypeId, dataTypeDescriptor); _dataTypeDescriptorFilesnamesCache.Add(dataTypeDescriptor.DataTypeId, filepath); } } } private static DataTypeDescriptor LoadFromFile(string filePath) { XDocument doc; try { doc = XDocumentUtils.Load(filePath, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo); } catch (XmlException e) { throw new ConfigurationErrorsException("Error loading meta data file '{0}': {1}".FormatWith(filePath, e.Message), e, filePath, e.LineNumber); } return DataTypeDescriptor.FromXml(doc.Root); } private static void UpdateFilenames() { List<string> filepaths = C1Directory.GetFiles(_metaDataPath, "*.xml").ToList(); var ids = new Dictionary<Guid, string>(); foreach (string filepath in filepaths) { Guid id = GetGuidFromFilename(filepath); if (!ids.ContainsKey(id)) { ids.Add(id, filepath); } else // This should never happen, but is here to be robust { if (!IsMetaDataFileName(Path.GetFileNameWithoutExtension(filepath))) // Old version of the file, delete it { FileUtils.Delete(filepath); } else // Old version is stored in ids, delete it and change the value to new version { FileUtils.Delete(ids[id]); ids[id] = filepath; } } } foreach (var kvp in ids) { string filepath = kvp.Value; if (!IsMetaDataFileName(Path.GetFileNameWithoutExtension(filepath))) { continue; } var dataTypeDescriptor = LoadFromFile(filepath); string newFilepath = CreateFilename(dataTypeDescriptor); FileUtils.RemoveReadOnly(filepath); Func<string, string> normalizeFileName = f => f.Replace('_', ' ').ToLowerInvariant(); if (normalizeFileName(filepath) != normalizeFileName(newFilepath)) { C1File.Move(filepath, newFilepath); } } } private static bool IsMetaDataFileName(string fileNameWithoutExtension) { return fileNameWithoutExtension.Contains("_") || fileNameWithoutExtension.Contains(" "); } /// <exclude /> public static IEnumerable<DataTypeDescriptor> AllDataTypeDescriptors { get { Initialize(); return _dataTypeDescriptorCache.Values.Evaluate(); } } /// <exclude /> public static IEnumerable<DataTypeDescriptor> GeneratedTypeDataTypeDescriptors { get { return AllDataTypeDescriptors.Where(d => d.IsCodeGenerated); } } /// <summary> /// This method will return the data type descriptor for the given data type id. /// If the data type descriptor has not yet been created (file not existing) and /// the <paramref name="allowTypeMetaDataCreation"/> is set to true, /// this method will try getting it through the <see cref="Composite.Data.DynamicTypes.Foundation.ReflectionBasedDescriptorBuilder"/> /// that will try locating the type from the data type id using reflection /// going through know assemblies. /// </summary> /// <param name="dataTypeId">The id of the data type.</param> /// <param name="allowTypeMetaDataCreation"> /// If this is <value>true</value> and the data type descriptor does not exists, the method will try to create it. /// </param> /// <returns></returns> public static DataTypeDescriptor GetDataTypeDescriptor(Guid dataTypeId, bool allowTypeMetaDataCreation = false) { Initialize(); DataTypeDescriptor dataTypeDescriptor; _dataTypeDescriptorCache.TryGetValue(dataTypeId, out dataTypeDescriptor); if (dataTypeDescriptor != null) return dataTypeDescriptor; if (!allowTypeMetaDataCreation) return null; foreach (Assembly assembly in AssemblyFacade.GetLoadedAssembliesFromBin()) { if (!AssemblyFacade.AssemblyPotentiallyUsesType(assembly, typeof(IData))) { // Ignoring assemblies that aren't referencing Composite.dll continue; } Type[] types; try { types = assembly.GetTypes(); } catch(ReflectionTypeLoadException ex) { if (assembly == typeof (IData).Assembly) { // It is critical to be able to load types from Composite.dll Log.LogError(LogTitle, ex.LoaderExceptions.FirstOrDefault()); throw new InvalidOperationException($"Failed to load '{typeof(IData).Assembly.FullName}', check log file for the details", ex); } Log.LogWarning($"Failed to get types from assembly '{assembly.FullName}'", ex); continue; } foreach (Type type in types) { if (type.GetInterfaces().Contains(typeof(IData))) { ImmutableTypeIdAttribute attribute = type.GetCustomAttributes(false).OfType<ImmutableTypeIdAttribute>().SingleOrDefault(); if (attribute == null || attribute.ImmutableTypeId != dataTypeId) continue; DataTypeDescriptor newDataTypeDescriptor = ReflectionBasedDescriptorBuilder.Build(type); PersistMetaData(newDataTypeDescriptor); return newDataTypeDescriptor; } } } Log.LogError(LogTitle, $"No data type found with the given data type id '{dataTypeId}'"); return null; } /// <summary> /// This method will return the data type descriptor for the given data type id. /// If the data type descriptor has not yet been created (file not existing) and /// the <paramref name="allowTypeMetaDataCreation"/> is set to true, /// this method will try getting it through the <see cref="Composite.Data.DynamicTypes.Foundation.ReflectionBasedDescriptorBuilder"/> /// based on <paramref name="interfaceType"/>. /// </summary> /// <param name="interfaceType">The data type.</param> /// <param name="allowTypeMetaDataCreation"> /// If this is true and the data type descriptor does not exists, it will be created. /// </param> /// <returns></returns> public static DataTypeDescriptor GetDataTypeDescriptor(Type interfaceType, bool allowTypeMetaDataCreation = false) { Verify.ArgumentNotNull(interfaceType, nameof(interfaceType)); Initialize(); DataTypeDescriptor dataTypeDescriptor; Guid dataTypeId = interfaceType.GetImmutableTypeId(); _dataTypeDescriptorCache.TryGetValue(dataTypeId, out dataTypeDescriptor); if (dataTypeDescriptor != null) return dataTypeDescriptor; if (!allowTypeMetaDataCreation) return null; var newDataTypeDescriptor = ReflectionBasedDescriptorBuilder.Build(interfaceType); PersistMetaData(newDataTypeDescriptor); return newDataTypeDescriptor; } /// <exclude /> public static void PersistMetaData(DataTypeDescriptor dataTypeDescriptor) { lock (_lock) { Initialize(); string filepath = CreateFilename(dataTypeDescriptor); XElement rootElement = dataTypeDescriptor.ToXml(); XDocument doc = new XDocument(rootElement); XDocumentUtils.Save(doc, filepath); _dataTypeDescriptorCache[dataTypeDescriptor.DataTypeId] = dataTypeDescriptor; if ((_dataTypeDescriptorFilesnamesCache.ContainsKey(dataTypeDescriptor.DataTypeId)) && (_dataTypeDescriptorFilesnamesCache[dataTypeDescriptor.DataTypeId] != filepath)) { FileUtils.Delete(_dataTypeDescriptorFilesnamesCache[dataTypeDescriptor.DataTypeId]); _dataTypeDescriptorFilesnamesCache[dataTypeDescriptor.DataTypeId] = filepath; } } } /// <exclude /> public static void DeleteMetaData(Guid dataTypeId) { lock (_lock) { Initialize(); if (_dataTypeDescriptorFilesnamesCache.ContainsKey(dataTypeId)) { FileUtils.Delete(_dataTypeDescriptorFilesnamesCache[dataTypeId]); _dataTypeDescriptorCache.Remove(dataTypeId); _dataTypeDescriptorFilesnamesCache.Remove(dataTypeId); } } } private static string CreateFilename(DataTypeDescriptor dataTypeDescriptor) { return Path.Combine(_metaDataPath, string.Format("{0} {1}.xml", dataTypeDescriptor.Name, dataTypeDescriptor.DataTypeId)); } private static Guid GetGuidFromFilename(string filepath) { string tmp = Path.GetFileNameWithoutExtension(filepath); int index = Math.Max(tmp.LastIndexOf('_'), tmp.LastIndexOf(' ')); if (index == -1) { return new Guid(tmp); } Guid result; string guidStr = tmp.Substring(index + 1); if (!Guid.TryParse(guidStr, out result)) { throw new InvalidOperationException("Failed to extract ID from file '{0}'".FormatWith(filepath)); } return result; } /// <summary> /// Used for processing xml/sql data providers configuration build by C1 vesrion older than 3.0 /// </summary> internal static Dictionary<string, Guid> GetTypeManagerTypeNameToTypeIdMap() { string metaDataFolderPath = PathUtil.Resolve(GlobalSettingsFacade.DataMetaDataDirectory); List<string> filepaths = C1Directory.GetFiles(metaDataFolderPath, "*.xml").ToList(); var result = new Dictionary<string, Guid>(); foreach (string filepath in filepaths) { try { XDocument doc = XDocumentUtils.Load(filepath); XAttribute dataTypeIdAttr = doc.Root.Attribute("dataTypeId"); XAttribute typeManagerTypeNameAttr = doc.Root.Attribute("typeManagerTypeName"); if (dataTypeIdAttr == null || typeManagerTypeNameAttr == null) continue; string typeManagerTypeName = typeManagerTypeNameAttr.Value; Guid dataTypeId = new Guid(dataTypeIdAttr.Value); const string redundantSuffix = ",Composite.Generated"; if (typeManagerTypeName.EndsWith(redundantSuffix, StringComparison.OrdinalIgnoreCase)) { typeManagerTypeName = typeManagerTypeName.Substring(0, typeManagerTypeName.Length - redundantSuffix.Length); } if (!result.ContainsKey(typeManagerTypeName)) { result.Add(typeManagerTypeName, dataTypeId); } if(!typeManagerTypeName.Contains(",") && !typeManagerTypeName.StartsWith("DynamicType:")) { string fixedTypeManagerTypeName = "DynamicType:" + typeManagerTypeName; if (!result.ContainsKey(fixedTypeManagerTypeName)) { result.Add(fixedTypeManagerTypeName, dataTypeId); } } } catch (Exception ex) { Log.LogWarning(LogTitle, "Error while parsing meta data file '{0}'".FormatWith(filepath)); Log.LogWarning(LogTitle, ex); } } // Backward compatibility for configuraiton files. (Breaking change C1 3.2 -> C1 4.0) result["Composite.Data.Types.IPageTemplate,Composite"] = new Guid("7b54d7d2-6be6-48a6-9ae1-2e0373073d1d"); return result; } private static void Flush() { _dataTypeDescriptorCache = null; _dataTypeDescriptorFilesnamesCache = null; } } } ================================================ FILE: Composite/Data/DataPropertyValueCollection.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DataPropertyValueCollection { private Dictionary<PropertyInfo, object> _propertyValues = new Dictionary<PropertyInfo, object>(); /// <exclude /> public void AddKeyProperty(PropertyInfo propertyInfo, object value) { if (propertyInfo == null) throw new ArgumentNullException("keyPropertyName"); if (value == null) throw new ArgumentNullException("value"); if (_propertyValues.ContainsKey(propertyInfo)) throw new ArgumentException(string.Format("The key property name '{0}' has already been added", propertyInfo.Name)); _propertyValues.Add(propertyInfo, value); } /// <exclude /> public IEnumerable<KeyValuePair<PropertyInfo, object>> PropertyValues { get { foreach (KeyValuePair<PropertyInfo, object> kvp in _propertyValues) { yield return kvp; } } } } } ================================================ FILE: Composite/Data/DataProviderCopier.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Transactions; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.Logging; using Composite.Core.Types; using Composite.Data.DynamicTypes; using Composite.Data.Foundation; using Composite.Data.Foundation.PluginFacades; using Composite.Data.Plugins.DataProvider; using Composite.Data.ProcessControlled; using Composite.Data.Transactions; namespace Composite.Data { /// <summary> /// Class used for copying data from one data provider to another /// </summary> public sealed class DataProviderCopier { private delegate void HandleSpecialTypeDelegate(List<IData> datas, string sourceProviderName, string targetProviderName); private static readonly string LogTitle = "Database copying"; private static readonly Dictionary<Type, HandleSpecialTypeDelegate> _specialHandleInterfaces = new Dictionary<Type, HandleSpecialTypeDelegate>(); /// <summary> /// Initializes a new instance of the <see cref="DataProviderCopier"/> class. /// </summary> /// <param name="sourceProviderName">Name of the source data provider.</param> /// <param name="targetProviderName">Name of the target data provider.</param> public DataProviderCopier(string sourceProviderName, string targetProviderName) { this.SourceProviderName = sourceProviderName; this.TargetProviderName = targetProviderName; UseTransaction = true; IgnorePrimaryKeyViolation = true; } /// <summary> /// Gets the name of the source data provider. /// </summary> /// <value> /// The name of the source data provider. /// </value> public string SourceProviderName { get; private set; } /// <summary> /// Gets the name of the target data provider. /// </summary> /// <value> /// The name of the target data provider. /// </value> public string TargetProviderName { get; private set; } /// <summary> /// Gets or sets a value indicating whether transaction should be used. /// Disabling transaction may help to ignore transaction timeout limitation which is limited to 20 minutes in machine.config /// </summary> /// <value> /// <c>true</c> if transaction should be used; otherwise, <c>false</c>. /// </value> public bool UseTransaction { get; set; } /// <summary> /// If set to <c>true</c>, records with already used primary keys will be skipped and the copying process will continue. /// </summary> /// <value> /// <c>true</c> if [ignore primary key violation]; otherwise, <c>false</c>. /// </value> public bool IgnorePrimaryKeyViolation { get; set; } /// <summary> /// Copies all the types that the query returns. /// </summary> public void Copy(IEnumerable<Type> queryToTypes) { using (GlobalInitializerFacade.CoreIsInitializedScope) { using (GlobalInitializerFacade.CoreLockScope) { TransactionScope transactionScope = null; try { if (UseTransaction) { transactionScope = TransactionsFacade.CreateNewScope(TimeSpan.FromHours(6.0)); } Log.LogVerbose(LogTitle, "Full copy started"); IEnumerable<Type> allInterfacesToEnsure = queryToTypes.ToList(); Log.LogVerbose(LogTitle, "Ensuring interfaces..."); EnsureInterfaces(allInterfacesToEnsure); Log.LogVerbose(LogTitle, "Done insuring interfaces!"); IEnumerable<Type> allInterfaces = queryToTypes.ToList(); List<Type> handleLastInterfaceTypes = new List<Type>(); foreach (Type interfaceType in allInterfaces) { if (_specialHandleInterfaces.ContainsKey(interfaceType) == false) { CopyData(interfaceType); } else { handleLastInterfaceTypes.Add(interfaceType); } } foreach (Type interfaceType in handleLastInterfaceTypes) { CopyData(interfaceType); } if (transactionScope != null) { transactionScope.Complete(); } } finally { if (transactionScope != null) { transactionScope.Dispose(); } } Log.LogVerbose(LogTitle, "Full copy done!"); } } } /// <summary> /// Copies all the data from the source data provider to the target data provider. /// </summary> public void FullCopy() { var allTypes = from type in DataFacade.GetAllInterfaces() where DataProviderRegistry.GetDataProviderNamesByInterfaceType(type).Contains(this.SourceProviderName) select type; Copy(allTypes); } private void EnsureInterfaces(IEnumerable<Type> allInterfaces) { var dataTypeDescriptors = new List<DataTypeDescriptor>(); foreach (Type interfaceType in allInterfaces) { if (!DataProviderRegistry.GetDataProviderNamesByInterfaceType(interfaceType).Contains(this.TargetProviderName)) { var dataTypeDescriptor = DynamicTypeManager.BuildNewDataTypeDescriptor(interfaceType); dataTypeDescriptor.Validate(); dataTypeDescriptors.Add(dataTypeDescriptor); } } DataProviderPluginFacade.CreateStores(this.TargetProviderName, dataTypeDescriptors); } private CultureInfo[] GetSupportedCultures(Type interfaceType) { if (DataLocalizationFacade.IsLocalized(interfaceType)) { return DataLocalizationFacade.ActiveLocalizationCultures.ToArray(); } return new[] { CultureInfo.InvariantCulture }; } private void CopyData(Type interfaceType) { IWritableDataProvider targetDataProvider = DataProviderPluginFacade.GetDataProvider(TargetProviderName) as IWritableDataProvider; Verify.IsNotNull(targetDataProvider, "Failed to get target data provider, probably it's not writeable."); foreach (DataScopeIdentifier dataScopeIdentifier in interfaceType.GetSupportedDataScopes()) { Log.LogVerbose(LogTitle, "Copying scope '{0}' data for type '{1}'".FormatWith(dataScopeIdentifier.Name, interfaceType.FullName)); foreach (CultureInfo cultureInfo in GetSupportedCultures(interfaceType)) { using (new DataScope(dataScopeIdentifier, cultureInfo)) { List<IData> dataset; try { dataset = DataFacade.GetData(interfaceType, SourceProviderName).ToDataList(); if (_specialHandleInterfaces.ContainsKey(interfaceType)) { _specialHandleInterfaces[interfaceType](dataset, this.SourceProviderName, this.TargetProviderName); } } catch (Exception) { Log.LogCritical(LogTitle,"Failed to read data from type '{0}'. See the log for the details." .FormatWith(interfaceType.FullName)); throw; } List<IData> filteredDataset = null; HashSet<string> dataIDs = null; if (IgnorePrimaryKeyViolation) { filteredDataset = new List<IData>(); dataIDs = new HashSet<string>(); } foreach (var data in dataset) { if (IgnorePrimaryKeyViolation) { string dataId = data.DataSourceId.ToString(); if (dataIDs.Contains(dataId)) { LoggingService.LogWarning(LogTitle, "Cannot insert a data row, since it's data ID is already used. DataID: '{0}'".FormatWith(dataId)); continue; } dataIDs.Add(dataId); filteredDataset.Add(data); } FixData(data); } if (IgnorePrimaryKeyViolation) { dataIDs = null; dataset = filteredDataset; } try { AddData(interfaceType, dataset, targetDataProvider); } catch (Exception e) { Log.LogError(LogTitle, $"Adding failed while adding {interfaceType.Namespace}.{interfaceType.Name} because {e.Message}"); Log.LogError(LogTitle,e.InnerException); throw; } } } } } private static void AddData(Type type, IEnumerable<IData> dataset, IWritableDataProvider dataProvider) { // TODO: check if adding in groups of ~1000 records may improve the performance MethodInfo genericMethod = StaticReflection.GetGenericMethodInfo((a) => AddData<IData>(null, null)); genericMethod.MakeGenericMethod(new[] { type }).Invoke(null, new object[] { dataset, dataProvider }); } private static void AddData<T>(IEnumerable<IData> dataset, IWritableDataProvider dataProvider) where T : class, IData { dataProvider.AddNew(dataset.Cast<T>()); } private static void FixData(IData data) { if (data is ILocalizedControlled) { var localizedData = data as ILocalizedControlled; if (localizedData.SourceCultureName == null) { localizedData.SourceCultureName = LocalizationScopeManager.CurrentLocalizationScope.Name; } } } } } ================================================ FILE: Composite/Data/DataReference.cs ================================================ using System; using System.Linq; using Composite.Core.Types; using System.Linq.Expressions; namespace Composite.Data { /// <summary> /// Represents a reference to a C1 CMS IData item. Unlike <see cref="DataReference{T}"/> this class signals /// that a data reference need not be set for this to be in a valid state. /// </summary> /// <typeparam name="T">The C1 Data Type (<see cref="IData"/>) being referenced</typeparam> [DataReferenceConverter] public class NullableDataReference<T> : DataReference<T> where T : class, IData { /// <exclude /> public NullableDataReference() { } /// <exclude /> public NullableDataReference(object keyValue) : base(keyValue) { } } /// <summary> /// Represents a reference to a C1 CMS IData item. /// </summary> /// <typeparam name="T">The C1 Data Type (<see cref="IData"/>) being referenced</typeparam> [DataReferenceConverter] public class DataReference<T> : IDataReference where T : class, IData { private readonly object _keyValue; private T _cachedValue; /// <summary> /// Constructs a 'empty' DataReference. /// </summary> public DataReference() { _keyValue = null; } /// <summary> /// Constructs a DataReference using a key value. /// </summary> /// <param name="keyValue">The key value, like the Guid for a page's Id.</param> public DataReference(object keyValue) { if (keyValue != null) { Type realKeyType = typeof(T).GetSingleKeyProperty().PropertyType; if (keyValue.GetType() != realKeyType) { _keyValue = ValueTypeConverter.Convert(keyValue, realKeyType); } else { _keyValue = keyValue; } } else { _keyValue = null; } } /// <summary> /// Constructs a DataReference using an instance of the data item. /// </summary> /// <param name="data">The data item to reference.</param> public DataReference(T data) { if (data != null) { _keyValue = data.GetUniqueKey(); _cachedValue = data; } } /// <summary> /// The type of the data item. This type inherits from IData. /// </summary> public Type ReferencedType => typeof(T); /// <summary> /// If the reference has not been set this is false. /// </summary> public bool IsSet { get { if (_keyValue is Guid) return (Guid)_keyValue != Guid.Empty; return _keyValue != null; } } /// <summary> /// The key value of the data item being referenced, like the Guid for a page id. /// </summary> public object KeyValue => _keyValue; /// <summary> /// The data item being referenced. /// </summary> IData IDataReference.Data => this.Data; /// <summary> /// The data item being referenced. /// </summary> public T Data { get { if (!IsSet) { return default(T); } if (_cachedValue != null) { return _cachedValue; } return _cachedValue = DataFacade.GetDataByUniqueKey<T>(_keyValue); } } /// <summary> /// A linq predicate that select the data item being referenced. You can use this when filtering data on the <see cref="DataConnection"/>. /// </summary> /// <returns>Predicate for referenced data.</returns> public Expression<Func<T, bool>> GetPredicateExpression() { if (!IsSet) { return f => false; } return DataFacade.GetPredicateExpressionByUniqueKey<T>(_keyValue); } /// <exclude /> public string Serialize() { if (_keyValue == null) return ""; return Composite.Core.Types.ValueTypeConverter.Convert<string>(_keyValue); } /// <exclude /> public override string ToString() { return this.Serialize(); } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DataReferenceConverterAttribute : ValueTypeConverterHelperAttribute { /// <exclude /> public override bool TryConvert(object value, Type targetType, out object targetValue) { Verify.ArgumentNotNull(value, "value"); IDataReference valueCasted = value as IDataReference; if (valueCasted != null) { if (!valueCasted.IsSet) { targetValue = null; return true; } if (targetType == typeof (string)) { targetValue = valueCasted.KeyValue.ToString(); return true; } if (targetType.IsInstanceOfType(valueCasted.KeyValue)) { targetValue = valueCasted.KeyValue; return true; } } if (typeof(IDataReference).IsAssignableFrom(targetType)) { if (value is string && string.IsNullOrEmpty((string) value)) { value = null; } object[] activationParameters = { value }; var dataReference = (IDataReference)Activator.CreateInstance(targetType, activationParameters); targetValue = dataReference; return true; } targetValue = null; return false; } } } ================================================ FILE: Composite/Data/DataReferenceFacade.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using Composite.Data.DynamicTypes.Foundation; using Composite.Data.Foundation; using Composite.Core.Extensions; using Composite.Core.Types; namespace Composite.Data { /// <summary> /// Referenced type: The type that is "pointed" to by another type /// Referee type: The type that is "pointing" to a nother type /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DataReferenceFacade { private static readonly Dictionary<PropertyInfo, Type> _propertyReferenceTargetTypeLookup = new Dictionary<PropertyInfo, Type>(); private static readonly object _lock = new object(); private static readonly MethodInfo HasReferenceMethodInfo = StaticReflection.GetGenericMethodInfo(() => HasReference<IData>(null, null, null)); private static readonly MethodInfo GetReferencesMethodInfo = StaticReflection.GetGenericMethodInfo(() => GetReferences<IData>(null, null, null, false)); /// <exclude /> public static List<Type> GetRefereeTypes(this Type referencedType) { Verify.ArgumentNotNull(referencedType, "referencedType"); return DataReferenceRegistry.GetRefereeTypes(referencedType).ToList(); } internal static bool TryValidateDeleteSuccess(this IData dataToDelete) { var foundDataset = new Dictionary<DataSourceId, Tuple<IData, ForeignPropertyInfo>>(); GetRefereesRecursively(dataToDelete, true, (type, foreignKey) => !foreignKey.IsOptionalReference && (!foreignKey.AllowCascadeDeletes || DataReferenceRegistry.GetRefereeTypes(type).Count > 0), foundDataset); return foundDataset.All(kvp => kvp.Value.Item2.AllowCascadeDeletes); } internal static void ValidateForeignKeyIntegrity(this IData refereeData) { Verify.ArgumentNotNull(refereeData, "refereeData"); var invalidForeignKeyPropertyNames = new List<string>(); if (!TryValidateForeignKeyIntegrity(refereeData, invalidForeignKeyPropertyNames)) { var sb = new StringBuilder(); sb.Append("The following foreign keys integrity did not validate: "); bool isFirst = true; foreach (string propertyName in invalidForeignKeyPropertyNames) { if (!isFirst) { sb.Append(", "); } else { isFirst = false; } sb.Append(propertyName); PropertyInfo invalidProperty = refereeData.GetType().GetAllProperties().FirstOrDefault(f => f.Name == propertyName); if (invalidProperty != null) { object propertyValue = invalidProperty.GetValue(refereeData, null); if (propertyValue != null) { string propertyStringValue = propertyValue.ToString(); if (propertyStringValue.Length > 50) propertyStringValue = propertyStringValue.Substring(0, 40) + "..."; sb.AppendFormat(" ['{0}']", propertyStringValue); } else { sb.Append(" [null]"); } } } sb.Append("; DataType: ").Append(refereeData.DataSourceId.InterfaceType.FullName); throw new InvalidOperationException(sb.ToString()); } } /// <exclude /> public static bool TryValidateForeignKeyIntegrity(this IData refereeData) { Verify.ArgumentNotNull(refereeData, "refereeData"); return TryValidateForeignKeyIntegrity(refereeData, null); } /// <exclude /> public static bool TryValidateForeignKeyIntegrity(this IData refereeData, List<string> invalidForeignKeyPropertyNames) { Verify.ArgumentNotNull(refereeData, "refereeData"); bool totalValidity = true; foreach (ForeignPropertyInfo foreignPropertyInfo in DataReferenceRegistry.GetForeignKeyProperties(refereeData.DataSourceId.InterfaceType)) { // If Nullable references are allowed, a check for SourcePropertyInfo.PropertyType.GetGenericDef == typeof(Nullable<?>) // If it is a nullable and has no value, then all is ok and continue // If it is a nullable and has a value, assign the value to refereeForeignKeyValue // Else change nothing /MRJ object refereeForeignKeyValue = foreignPropertyInfo.SourcePropertyInfo.GetValue(refereeData, null); // Handling Nullable<> if (refereeForeignKeyValue == null && (foreignPropertyInfo.SourcePropertyInfo.PropertyType.IsGenericType)) { Type type = foreignPropertyInfo.SourcePropertyInfo.PropertyType.GetGenericTypeDefinition(); if (type == typeof(Nullable<>)) { continue; } } // Handling null of type string where the reference should be handled as a non-reference if (refereeForeignKeyValue == null && foreignPropertyInfo.IsNullableString) { continue; } if (foreignPropertyInfo.IsNullReferenceValueSet) { object nullReferenceKeyValue = foreignPropertyInfo.NullReferenceValue; if (foreignPropertyInfo.NullReferenceValueType != null) { nullReferenceKeyValue = ValueTypeConverter.Convert(nullReferenceKeyValue, foreignPropertyInfo.NullReferenceValueType); } if (object.Equals(nullReferenceKeyValue, refereeForeignKeyValue)) { continue; // The foreign key is a null reference } } bool valid = false; if (refereeForeignKeyValue != null) { foreach (DataScopeIdentifier dataScopeIdentifier in DataFacade.GetSupportedDataScopes(foreignPropertyInfo.TargetType)) { using (new DataScope(dataScopeIdentifier)) { IQueryable scopeData = DataFacade.GetData(foreignPropertyInfo.TargetType); if (HasReference(scopeData, foreignPropertyInfo, refereeForeignKeyValue)) { valid = true; break; } } } } if (!valid) { totalValidity = false; if (invalidForeignKeyPropertyNames != null) { invalidForeignKeyPropertyNames.Add(foreignPropertyInfo.SourcePropertyName); } } } return totalValidity; } private static bool HasReference(IQueryable queryable, ForeignPropertyInfo foreignPropertyInfo, object propertyValue) { var targetType = foreignPropertyInfo.TargetType; var methodInfo = HasReferenceMethodInfo.MakeGenericMethod(new[] { targetType }); return (bool)methodInfo.Invoke(null, new[] { queryable, foreignPropertyInfo.TargetKeyPropertyInfo, propertyValue }); } private static IEnumerable GetReferences(IQueryable queryable, Type dataType, PropertyInfo propertyInfo, object keyValue, bool justOne) { var methodInfo = GetReferencesMethodInfo.MakeGenericMethod(new[] { dataType }); return (IEnumerable)methodInfo.Invoke(null, new[] { queryable, propertyInfo, keyValue, justOne }); } private static IEnumerable GetReferences(IQueryable queryable, ForeignPropertyInfo foreignPropertyInfo, object keyValue, bool justOne) { Type sourceType = foreignPropertyInfo.SourcePropertyInfo.DeclaringType; return GetReferences(queryable, sourceType, foreignPropertyInfo.SourcePropertyInfo, keyValue, justOne); } /// <summary> /// To be run through reflection /// </summary> /// <typeparam name="T"></typeparam> /// <param name="queryable"></param> /// <param name="propertyInfo"></param> /// <param name="keyValue"></param> /// <param name="justOne"></param> /// <returns></returns> private static IEnumerable GetReferences<T>(IQueryable<T> queryable, PropertyInfo propertyInfo, object keyValue, bool justOne) { Verify.ArgumentNotNull(queryable, "queryable"); Verify.ArgumentNotNull(propertyInfo, "propertyInfo"); Verify.ArgumentNotNull(keyValue, "keyValue"); // Building query: // select record from queryable // where record.'ForeingIdColumn' = 'keyValue' // [Take(1)] ParameterExpression parameter = Expression.Parameter(typeof(T), "record"); var propertyExpression = Expression.Property(parameter, propertyInfo); var constantExpression = GetConstantExpression(keyValue, propertyInfo); var equalExpression = Expression.Equal(propertyExpression, constantExpression); var lambdaFunc = Expression.Lambda<Func<T, bool>>(equalExpression, new[] { parameter }); IQueryable<T> resultQuery = queryable.Where(lambdaFunc); return justOne ? resultQuery.Take(1) : resultQuery; } private static ConstantExpression GetConstantExpression(object keyValue, PropertyInfo propertyInfo) { // Property foreingPropertyInfo could have type System.Nullable<T> when keyValue have type T. if(propertyInfo.PropertyType.FullName.StartsWith(typeof(System.Nullable<>).FullName)) { return Expression.Constant(keyValue, propertyInfo.PropertyType); } return Expression.Constant(keyValue); } /// <summary> /// To be run through reflection /// </summary> private static bool HasReference<T>(IQueryable queryable, PropertyInfo propertyInfo, object propertyValue) { Verify.ArgumentNotNull(queryable, "queryable"); Verify.ArgumentNotNull(propertyInfo, "propertyInfo"); Verify.ArgumentNotNull(propertyValue, "propertyValue"); // Building query: // select record from queryable // where record.'ForeingIdColumn' = 'propertyValue' // any; var typedQueryable = queryable as IQueryable<T>; Verify.ArgumentCondition(typedQueryable != null, "queryable", "The argument should implement '{0}' interface.".FormatWith(typeof(IQueryable<T>))); ParameterExpression parameter = Expression.Parameter(typeof(T), "record"); var propertyExpression = Expression.Property(parameter, propertyInfo); var constantExpression = GetConstantExpression(propertyValue, propertyInfo); var equalExpression = Expression.Equal(propertyExpression, constantExpression); var lambdaFunc = Expression.Lambda<Func<T, bool>>(equalExpression, new[] { parameter }); return typedQueryable.Where(lambdaFunc).Any(); } /// <exclude /> public static List<IData> GetNotOptionalReferences<T>(T data) where T : IData { return GetNotOptionalReferences(data, false); } /// <exclude /> public static List<IData> GetNotOptionalReferences<T>(T data, bool allScopes) where T : IData { return GetRefereesInt(data, allScopes, (type, fp) => !fp.IsOptionalReference) .Select(t => t.Item1).ToList(); } /// <exclude /> internal static List<IData> GetReferences(IData data, bool allScopes, Func<Type, ForeignPropertyInfo, bool> foreignKeyFilter) { return GetRefereesInt(data, allScopes, foreignKeyFilter) .Select(t => t.Item1).ToList(); } /// <exclude /> internal static IList<Tuple<IData, ForeignPropertyInfo>> GetRefereesInt( IData data, bool allScopes, Func<Type, ForeignPropertyInfo, bool> propertyFilter) { Verify.ArgumentNotNull(data, nameof(data)); var result = new List<Tuple<IData, ForeignPropertyInfo>>(); Type dataType = data.DataSourceId.InterfaceType; var referencedTypes = DataReferenceRegistry.GetRefereeTypes(dataType); foreach (var referencedType in referencedTypes) { foreach (var foreignKeyProperty in GetForeignKeyProperties(referencedType, dataType)) { if (!propertyFilter(referencedType, foreignKeyProperty)) { continue; } IEnumerable<IData> references = data.GetReferees(referencedType, new[] { foreignKeyProperty.SourcePropertyInfo }, allScopes); result.AddRange(references.Select(r => new Tuple<IData, ForeignPropertyInfo>(r, foreignKeyProperty))); } } // IData may contain a self-reference field, so we're removing references to original IData item from the result set result.RemoveAll(reference => reference.Item1.DataSourceId.Equals(data.DataSourceId)); return result; } /// <exclude /> public static bool TryGetReferenceType(this PropertyInfo propertyInfo, out Type typeBeingReferenced) { Verify.ArgumentNotNull(propertyInfo, "propertyInfo"); typeBeingReferenced = null; lock (_lock) { if (_propertyReferenceTargetTypeLookup.TryGetValue(propertyInfo, out typeBeingReferenced) == false) { IEnumerable<ForeignPropertyInfo> foreignKeysOnType = DataReferenceRegistry.GetForeignKeyProperties(propertyInfo.DeclaringType); ForeignPropertyInfo match = foreignKeysOnType.FirstOrDefault(f => f.SourcePropertyName == propertyInfo.Name); typeBeingReferenced = (match != null ? match.TargetType : null); _propertyReferenceTargetTypeLookup.Add(propertyInfo, typeBeingReferenced); } } return (typeBeingReferenced != null); } /// <exclude /> public static DataReference<T> BuildDataReference<T>(object keyValue) where T : class, IData { return new DataReference<T>(keyValue); } /// <exclude /> public static IDataReference BuildDataReference(Type referencedType, object keyValue) { Verify.ArgumentNotNull(keyValue, "keyValue"); Verify.ArgumentNotNull(referencedType, "referencedType"); Verify.ArgumentCondition(typeof(IData).IsAssignableFrom(referencedType), "referencedType", "The referenced type must implement IData"); Type genericReferenceType = typeof(DataReference<>).MakeGenericType(new Type[] { referencedType }); return (IDataReference)Activator.CreateInstance(genericReferenceType, new object[] { keyValue }); } internal static IEnumerable<ForeignPropertyInfo> GetForeignKeyProperties(Type refereeType) { Verify.ArgumentNotNull(refereeType, "refereeType"); return DataReferenceRegistry.GetForeignKeyProperties(refereeType); } internal static IEnumerable<ForeignPropertyInfo> GetForeignKeyProperties(Type refereeType, Type referencedType) { Verify.ArgumentNotNull(refereeType, "refereeType"); Verify.ArgumentNotNull(referencedType, "referencedType"); return from fk in DataReferenceRegistry.GetForeignKeyProperties(refereeType) where fk.TargetType == referencedType || referencedType.IsAssignableFrom(fk.TargetType) select fk; } internal static ForeignPropertyInfo GetForeignKeyPropertyInfo(Type refereeType, string refereePropertyName) { Verify.ArgumentNotNull(refereeType, "refereeType"); return DataReferenceRegistry.GetForeignKeyProperties(refereeType).Single(fk => fk.SourcePropertyName == refereePropertyName); } internal static IEnumerable<string> GetForeignKeyPropertyNames(Type refereeType, Type referencedType) { Verify.ArgumentNotNull(refereeType, "refereeType"); Verify.ArgumentNotNull(referencedType, "referencedType"); return from fk in DataReferenceRegistry.GetForeignKeyProperties(refereeType) where fk.TargetType == referencedType select fk.SourcePropertyName; } internal static bool CascadeDeleteAllowed(this IData data) { Verify.ArgumentNotNull(data, "data"); return DataReferenceRegistry.GetForeignKeyProperties(data.DataSourceId.InterfaceType) .All(_ => _.AllowCascadeDeletes); } internal static bool CascadeDeleteAllowed(this IData data, Type referencedType) { Verify.ArgumentNotNull(data, "data"); Verify.ArgumentNotNull(referencedType, "referencedType"); return GetForeignKeyProperties(data.DataSourceId.InterfaceType, referencedType) .All(_ => _.AllowCascadeDeletes); } /// <summary> /// Returns true if the refereeType has a foreign key to the referencedType /// </summary> /// <param name="refereeType"></param> /// <param name="referencedType"></param> /// <returns></returns> internal static bool ReferenceExists(Type refereeType, Type referencedType) { return DataReferenceRegistry.GetRefereeTypes(referencedType).Contains(refereeType); } internal static bool IsDataReferred(this IData referencedData) { Verify.ArgumentNotNull(referencedData, "referencedData"); return GetReferees(referencedData, true, null, null, true).Any(); } internal static bool IsDataReferred(this IData referencedData, Type refereeType, IEnumerable<PropertyInfo> foreignKeyProperties, bool allScopes) { Verify.ArgumentNotNull(referencedData, "referencedData"); return GetReferees(referencedData, true, refereeType, foreignKeyProperties, allScopes).Any(); } /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static List<IData> GetReferees(this IData referencedData) { Verify.ArgumentNotNull(referencedData, "referencedData"); return GetReferees(referencedData, false, null, null, true); } /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static List<IData> GetReferees(this IData referencedData, Type refereeType) { Verify.ArgumentNotNull(referencedData, "referencedData"); return GetReferees(referencedData, false, refereeType, null, true); } /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static List<IData> GetReferees(this IData referencedData, bool allScopes) { Verify.ArgumentNotNull(referencedData, "referencedData"); return GetReferees(referencedData, false, null, null, allScopes); } /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static List<IData> GetReferees(this IData referencedData, Type refereeType, IEnumerable<PropertyInfo> foreignKeyProperties, bool allScopes) { Verify.ArgumentNotNull(referencedData, "referencedData"); return GetReferees(referencedData, false, refereeType, foreignKeyProperties, allScopes); } internal static IEnumerable<Tuple<IData, ForeignPropertyInfo>> GetNotOptionalRefereesRecursively( this IData referencedData, bool allScopes = true) { Verify.ArgumentNotNull(referencedData, "referencedData"); var foundDataset = new Dictionary<DataSourceId, Tuple<IData, ForeignPropertyInfo>>(); GetRefereesRecursively(referencedData, allScopes, (t, f) => !f.IsOptionalReference, foundDataset); return foundDataset.Values; } /// <exclude /> public static IData GetReferenced(this IData refereeData, string foreignKeyPropertyName) { Verify.ArgumentNotNull(refereeData, "refereeData"); Verify.ArgumentNotNullOrEmpty(foreignKeyPropertyName, "foreignKeyPropertyName"); ForeignPropertyInfo foreignPropertyInfo = (from fkpi in DataReferenceRegistry.GetForeignKeyProperties(refereeData.DataSourceId.InterfaceType) where fkpi.SourcePropertyName == foreignKeyPropertyName select fkpi).Single(); object sourceKeyValue = foreignPropertyInfo.SourcePropertyInfo.GetValue(refereeData, null); // Handling of Nullable<> if (sourceKeyValue == null) { return null; } Type targetType = foreignPropertyInfo.TargetType; var dataset = DataFacade.GetData(targetType); IEnumerable queryResult = GetReferences(dataset, targetType, foreignPropertyInfo.TargetKeyPropertyInfo, sourceKeyValue, true); foreach(var result in queryResult) { Verify.That(result is IData, "Query result should implement '{0}' interface", typeof (IData).FullName); return result as IData; } return null; } private static void GetRefereesRecursively(IData referencedData, bool allScopes, Func<Type, ForeignPropertyInfo, bool> foreignKeyPredicate, Dictionary<DataSourceId, Tuple<IData, ForeignPropertyInfo>> foundDataset) { Verify.ArgumentNotNull(referencedData, nameof(foundDataset)); Verify.ArgumentNotNull(foundDataset, nameof(referencedData)); IList<Tuple<IData, ForeignPropertyInfo>> referees = GetRefereesInt(referencedData, allScopes, foreignKeyPredicate); foreach (var data in referees) { if (!foundDataset.ContainsKey(data.Item1.DataSourceId)) { foundDataset.Add(data.Item1.DataSourceId, data); GetRefereesRecursively(data.Item1, allScopes, foreignKeyPredicate, foundDataset); } } } private static List<IData> GetReferees(IData referencedData, IQueryable dataset, IEnumerable<ForeignPropertyInfo> foreignKeyProperyInfos, bool returnOnFirstFound) { List<IData> result = new List<IData>(); foreach (ForeignPropertyInfo foreignKeyPropertyInfo in foreignKeyProperyInfos) { if (!referencedData.DataSourceId.InterfaceType.IsAssignableFrom(foreignKeyPropertyInfo.TargetType)) { continue; } object sourceKeyValue = foreignKeyPropertyInfo.TargetKeyPropertyInfo.GetValue(referencedData, null); result.AddRange(GetReferences(dataset, foreignKeyPropertyInfo, sourceKeyValue, returnOnFirstFound).Cast<IData>()); if (returnOnFirstFound && result.Count > 0) { break; } } return result; } private static List<IData> GetReferees(IData referencedData, bool returnOnFirstFound, Type refereeType, IEnumerable<PropertyInfo> propertiesToSearchBy, bool allScopes) { Verify.ArgumentNotNull(referencedData, "referencedData"); IEnumerable<Type> refereeTypes; if (refereeType == null) { refereeTypes = DataReferenceRegistry.GetRefereeTypes(referencedData.DataSourceId.InterfaceType).Distinct(); } else { if (!DataReferenceRegistry.GetRefereeTypes(referencedData.DataSourceId.InterfaceType).Contains(refereeType)) { throw new ArgumentException($"The referencedData of type '{referencedData.DataSourceId.InterfaceType}' is not referenced by the given refereeType '{refereeType}'"); } refereeTypes = new List<Type> { refereeType }; } var referees = new List<IData>(); foreach (Type refType in refereeTypes) { var foreignKeyProperties = DataReferenceRegistry.GetForeignKeyProperties(refType); if (propertiesToSearchBy != null) { foreignKeyProperties = (from fkpi in foreignKeyProperties from pi in propertiesToSearchBy where fkpi.SourcePropertyInfo == pi select fkpi).ToList(); } if (allScopes) { foreach (DataScopeIdentifier dataScopeIdentifier in DataFacade.GetSupportedDataScopes(refType)) { using (new DataScope(dataScopeIdentifier)) { IQueryable dataset = DataFacade.GetData(refType); List<IData> refs = GetReferees(referencedData, dataset, foreignKeyProperties, returnOnFirstFound); referees.AddRange(refs.KeyDistinct()); // KeyDistinct is used here if a type has more than one reference to a nother time if (returnOnFirstFound && referees.Count > 0) { return referees; } } } } else { IQueryable dataset = DataFacade.GetData(refType); List<IData> refs = GetReferees(referencedData, dataset, foreignKeyProperties, returnOnFirstFound); referees.AddRange(refs.KeyDistinct()); // KeyDistinct is used here if a type has more than one reference to a nother time if (returnOnFirstFound && referees.Count > 0) { return referees; } } } return referees; } /// <exclude /> public static string GetBrokenReferencesReport(List<IData> brokenReferences) { var sb = new StringBuilder(); const int maximumLinesToShow = 6; int toDisplay = brokenReferences.Count > maximumLinesToShow ? maximumLinesToShow - 1 : brokenReferences.Count; for (int i = 0; i < toDisplay; i++) { IData brokenReference = brokenReferences[i]; Type type = brokenReference.DataSourceId.InterfaceType; string typeTitle = DynamicTypeReflectionFacade.GetTitle(type); if (string.IsNullOrEmpty(typeTitle)) { typeTitle = type.FullName; } string labelPropertyName = DynamicTypeReflectionFacade.GetLabelPropertyName(type); if (string.IsNullOrEmpty(labelPropertyName)) { labelPropertyName = "Id"; // This is a nasty fallback, but will work in most cases and all the time with generated types. } PropertyInfo labelPropertyInfo = brokenReference.GetType().GetProperty(labelPropertyName, BindingFlags.Instance | BindingFlags.Public); string dataLabel; if (labelPropertyInfo != null) { object propertyFieldValue = labelPropertyInfo.GetValue(brokenReference, null); dataLabel = (propertyFieldValue ?? "NULL").ToString(); } else { dataLabel = "'Failed to resolve ({0}) field'".FormatWith(labelPropertyName); } sb.Append("{0}, {1}".FormatWith(typeTitle, dataLabel)); sb.Append("\n\r"); } if (brokenReferences.Count > maximumLinesToShow) { sb.Append("..."); } return sb.ToString(); } } } ================================================ FILE: Composite/Data/DataScope.cs ================================================ using System; using System.Globalization; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DataScope : IDisposable { private readonly bool _dataScopePushed; private readonly bool _cultureInfoPushed; private bool _dataServicePushed; private bool _disposed; private bool _servicesDisabled; /// <exclude /> public void AddService(object service) { if (!_dataServicePushed) { DataServiceScopeManager.PushDataServiceScope(); _dataServicePushed = true; } DataServiceScopeManager.AddService(service); } /// <exclude /> public void AddDefaultService(object service) { DataServiceScopeManager.AddDefaultService(service); } /// <exclude /> public DataScope(DataScopeIdentifier dataScope) : this(dataScope, null) { } /// <exclude /> public DataScope(PublicationScope publicationScope) : this(DataScopeIdentifier.FromPublicationScope(publicationScope), null) { } /// <exclude /> public DataScope(CultureInfo cultureInfo) { if (cultureInfo != null) { LocalizationScopeManager.PushLocalizationScope(cultureInfo); _cultureInfoPushed = true; } } /// <summary> /// /// </summary> /// <param name="dataScope"></param> /// <param name="cultureInfo">null for default culture</param> public DataScope(DataScopeIdentifier dataScope, CultureInfo cultureInfo) { DataScopeManager.PushDataScope(dataScope); _dataScopePushed = true; if (cultureInfo != null) { LocalizationScopeManager.PushLocalizationScope(cultureInfo); _cultureInfoPushed = true; } else if (LocalizationScopeManager.IsEmpty) { LocalizationScopeManager.PushLocalizationScope(DataLocalizationFacade.DefaultLocalizationCulture); _cultureInfoPushed = true; } } /// <summary> /// /// </summary> /// <param name="publicationScope">Publication scope</param> /// <param name="cultureInfo">null for default culture</param> public DataScope(PublicationScope publicationScope, CultureInfo cultureInfo) : this(DataScopeIdentifier.FromPublicationScope(publicationScope), cultureInfo) { } #if LeakCheck private string stack = Environment.StackTrace; /// <exclude /> ~DataScope() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); Dispose(false); } #endif /// <exclude /> public void Dispose() { Dispose(true); #if LeakCheck GC.SuppressFinalize(this); #endif } void Dispose(bool disposing) { if (!disposing) { return; } if (_disposed) { throw new ObjectDisposedException(nameof(DataScope)); } if (_servicesDisabled) { EnableServices(); } if (_dataScopePushed) { DataScopeManager.PopDataScope(); } if (_cultureInfoPushed) { LocalizationScopeManager.PopLocalizationScope(); } if (_dataServicePushed) { DataServiceScopeManager.PopDataServiceScope(); } _disposed = true; } internal void DisableServices() { DataServiceScopeManager.DisableServices(); _servicesDisabled = true; } internal void EnableServices() { DataServiceScopeManager.EnableServices(); _servicesDisabled = false; } } } ================================================ FILE: Composite/Data/DataScopeAttribute.cs ================================================ using System; using System.Collections.Generic; namespace Composite.Data { /// <summary> /// Assigns data scopes to a data type. By default data types will live in the public data scope (only) and you use this /// attribute to specify aditional scopes. /// </summary> /// <example> This sample shows how to use the DataScope attribute along with related interfaces and attributes: /// <code> /// // (other IData attributes) /// [DataScope(DataScopeIdentifier.PublicName)] /// [DataScope(DataScopeIdentifier.AdministratedName)] /// [PublishProcessControllerType(typeof(GenericPublishProcessController))] /// interface IMyDataType : IData, IPublishControlled /// { /// // data type properties /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = true, Inherited = true)] public sealed class DataScopeAttribute : Attribute { /// <exclude /> public DataScopeAttribute(string dataScope) { this.Identifier = Composite.Data.DataScopeIdentifier.Deserialize(dataScope); } /// <exclude /> public DataScopeIdentifier Identifier { get; private set; } } } ================================================ FILE: Composite/Data/DataScopeIdentifier.cs ================================================ using System; using System.Diagnostics; using Newtonsoft.Json; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DebuggerDisplay("Name = {Name}")] public sealed class DataScopeIdentifier { /// <exclude /> public const string PublicName = "public"; /// <exclude /> public const string AdministratedName = "administrated"; /// <exclude /> public static DataScopeIdentifier Public { get; } = new DataScopeIdentifier(PublicName); /// <exclude /> public static DataScopeIdentifier Administrated { get; } = new DataScopeIdentifier(AdministratedName); /// <exclude /> public static DataScopeIdentifier GetDefault() { return DataScopeIdentifier.Public; } [JsonConstructor] private DataScopeIdentifier(string name) { this.Name = name; } /// <exclude /> public string Name { get; private set; } /// <exclude /> public string Serialize() { return this.Name; } /// <exclude /> public static DataScopeIdentifier Deserialize(string serializedData) { Verify.ArgumentNotNull(serializedData, nameof(serializedData)); switch (serializedData) { case PublicName: return DataScopeIdentifier.Public; case AdministratedName: return DataScopeIdentifier.Administrated; default: throw new InvalidOperationException("The serializedData argument was not a serialized DataScope"); } } /// <exclude /> public PublicationScope ToPublicationScope() { return Name == PublicName ? PublicationScope.Published : PublicationScope.Unpublished; } /// <exclude /> public static DataScopeIdentifier FromPublicationScope(PublicationScope publicationScope) { return publicationScope == PublicationScope.Published ? Public : Administrated; } /// <exclude /> public static bool IsLegasyDataScope(string name) { name = name.ToLowerInvariant(); return name == "deleted" || name == "versioned"; } /// <exclude /> public override bool Equals(object obj) { return obj != null && Equals(obj as DataScopeIdentifier); } /// <exclude /> public bool Equals(DataScopeIdentifier dataScope) { return !ReferenceEquals(dataScope, null) && this.Name == dataScope.Name; } /// <exclude /> public static bool operator==(DataScopeIdentifier a, DataScopeIdentifier b) { return (object)a == null ? (object)b == null : a.Equals(b); } /// <exclude /> public static bool operator!=(DataScopeIdentifier a, DataScopeIdentifier b) { return !(a == b); } /// <exclude /> public override int GetHashCode() { return this.Name.GetHashCode(); } /// <exclude /> public override string ToString() { return this.Serialize(); } } } ================================================ FILE: Composite/Data/DataScopeManager.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Core.Caching; using System.Threading; using System.Runtime.Remoting.Messaging; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DataScopeManager { /// <exclude /> public static DataScopeIdentifier CurrentDataScope { get { var stack = DataScopeStack; if (stack.Count != 0) { return stack.Peek(); } return DataScopeIdentifier.GetDefault(); } } /// <exclude /> public static DataScopeIdentifier MapByType(IData data) { if (data == null) throw new ArgumentNullException("data"); return MapByType(data.DataSourceId.InterfaceType); } /// <exclude /> public static DataScopeIdentifier MapByType(Type interfaceType) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); var currentScope = CurrentDataScope; if (DataFacade.GetSupportedDataScopes(interfaceType).Any(f => f.Equals(currentScope))) { return currentScope; } return DataScopeIdentifier.GetDefault(); } internal static void PushDataScope(DataScopeIdentifier dataScope) { DataScopeStack.Push(dataScope); } internal static void PopDataScope() { var stack = DataScopeStack; if (stack.Count > 0) { stack.Pop(); } } private const string _threadLocalCacheKey = "DataScopeManager:ThreadLocal"; /// <summary> /// Move the stack handling scope to a thread local store, enabling simultaneous threads to mutate (their own) scope. This will be in effect untill the thread has completed. /// </summary> public static void EnterThreadLocal() { if( CallContext.GetData(_threadLocalCacheKey) == null) { var threadLocalStack = new Stack<DataScopeIdentifier>( DataScopeStack ); CallContext.SetData( _threadLocalCacheKey, threadLocalStack ); } } /// <summary> /// Move the stack handling to request scope. /// </summary> public static void ExitThreadLocal() { if (CallContext.GetData(_threadLocalCacheKey) != null) { CallContext.SetData(_threadLocalCacheKey, null); } } private static Stack<DataScopeIdentifier> DataScopeStack { get { var threadLocalStack = CallContext.GetData(_threadLocalCacheKey) as Stack<DataScopeIdentifier>; if (threadLocalStack!=null) { return threadLocalStack; } return RequestLifetimeCache.GetCachedOrNew<Stack<DataScopeIdentifier>>("DataScopeManager:Stack"); } } } } ================================================ FILE: Composite/Data/DataScopeServicesFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Composite.Data { /// <summary> /// Facade for added services to data scope /// </summary> public static class DataScopeServicesFacade { /// <summary> /// Adds a default service to data scope manager. All DataScopes created after this point will include the service you provide. /// </summary> /// <param name="service"></param> public static void RegisterDefaultService(object service) { DataServiceScopeManager.AddDefaultService(service); } } } ================================================ FILE: Composite/Data/DataSerializerHandler.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Composite.Core.Serialization; using Composite.Core.Types; namespace Composite.Data { internal sealed class DataSerilizationException : Exception { public DataSerilizationException(string message) : base(message) { } } internal sealed class DataSerializerHandler : ISerializerHandler { public string Serialize(object objectToSerialize) { if (objectToSerialize == null) throw new ArgumentNullException("objectToSerialize"); IData data = objectToSerialize as IData; if (data == null) throw new ArgumentException("data"); StringBuilder sb = new StringBuilder(); if (data.DataSourceId.ExistsInStore == false) { StringConversionServices.SerializeKeyValuePair(sb, "_IsNew_", true); StringConversionServices.SerializeKeyValuePair(sb, "_Type_", TypeManager.SerializeType(data.DataSourceId.InterfaceType)); } else { StringConversionServices.SerializeKeyValuePair(sb, "_IsNew_", false); StringConversionServices.SerializeKeyValuePair(sb, "_DataSourceId_", data.DataSourceId.Serialize()); } Type dataType = data.DataSourceId.InterfaceType; SerializePropertiesFromInterface(data, data.DataSourceId.InterfaceType, false, sb); foreach(var inheritedInterface in dataType.GetInterfaces()) { if (inheritedInterface == typeof(IData)) continue; // DataSourceId is already serialized so we're skipping it here SerializePropertiesFromInterface(data, inheritedInterface, true, sb); } return sb.ToString(); } private static IEnumerable<PropertyInfo> GetSerializableProperties(Type @interface) { return from prop in @interface.GetProperties(BindingFlags.Public | BindingFlags.Instance) where prop.CanRead && prop.CanWrite select prop; } private static void SerializePropertiesFromInterface(object objectToSerialize, Type @interface, bool includeInterfaceName, StringBuilder stringBuilder) { string fieldPrefix = includeInterfaceName ? GetTypeSerializationPrefix(@interface) : string.Empty; foreach (PropertyInfo propertyInfo in GetSerializableProperties(@interface)) { MethodInfo methodInfo = (from mi in typeof(StringConversionServices).GetMethods(BindingFlags.Public | BindingFlags.Static) where mi.Name == "SerializeKeyValuePair" && mi.IsGenericMethodDefinition && mi.GetParameters().Length == 3 && mi.GetParameters()[2].ParameterType.IsGenericParameter select mi).SingleOrDefault(); methodInfo = methodInfo.MakeGenericMethod(new Type[] { propertyInfo.PropertyType }); object propertyValue = propertyInfo.GetValue(objectToSerialize, null); string fieldKey = fieldPrefix + propertyInfo.Name; methodInfo.Invoke(null, new object[] { stringBuilder, fieldKey, propertyValue }); } } private static void DeserializePropertiesFromInterface(Dictionary<string, string> serializedData, Type @interface, bool includeInterfaceName, object targetObject) { string fieldPrefix = includeInterfaceName ? GetTypeSerializationPrefix(@interface) : string.Empty; foreach (PropertyInfo propertyInfo in GetSerializableProperties(@interface)) { string fieldKey = fieldPrefix + propertyInfo.Name; if (serializedData.ContainsKey(fieldKey) == false) throw new DataSerilizationException(string.Format("The data type '{0}' does not contain a property named '{1}', type might have changed sinse this serialized data was created", @interface, propertyInfo.Name)); MethodInfo methodInfo = (from mi in typeof(StringConversionServices).GetMethods(BindingFlags.Public | BindingFlags.Static) where mi.Name == "DeserializeValue" && mi.IsGenericMethodDefinition && mi.GetParameters().Length == 2 && mi.GetParameters()[1].ParameterType.IsGenericParameter select mi).SingleOrDefault(); object defaultValue; if (propertyInfo.PropertyType == typeof(Guid)) defaultValue = default(Guid); else if (propertyInfo.PropertyType == typeof(string)) defaultValue = default(string); else if (propertyInfo.PropertyType == typeof(int)) defaultValue = default(int); else if (propertyInfo.PropertyType == typeof(DateTime)) defaultValue = default(DateTime); else if (propertyInfo.PropertyType == typeof(bool)) defaultValue = default(bool); else if (propertyInfo.PropertyType == typeof(decimal)) defaultValue = default(decimal); else if (propertyInfo.PropertyType == typeof(long)) defaultValue = default(long); else defaultValue = null; methodInfo = methodInfo.MakeGenericMethod(new Type[] { propertyInfo.PropertyType }); /* string methodName; if (propertyInfo.PropertyType == typeof(Guid)) methodName = "DeserializeValueGuid"; else if (propertyInfo.PropertyType == typeof(string)) methodName = "DeserializeValueString"; else if (propertyInfo.PropertyType == typeof(int)) methodName = "DeserializeValueInt"; else if (propertyInfo.PropertyType == typeof(DateTime)) methodName = "DeserializeValueDateTime"; else if (propertyInfo.PropertyType == typeof(DateTime?)) methodName = "DeserializeValueDateTimeNullable"; else if (propertyInfo.PropertyType == typeof(bool)) methodName = "DeserializeValueBool"; else if (propertyInfo.PropertyType == typeof(decimal)) methodName = "DeserializeValueDecimal"; else if (propertyInfo.PropertyType == typeof(long)) methodName = "DeserializeValueLong"; else methodName = null; if (methodName == null) throw new InvalidOperationException(string.Format("StringConversionServices does not support the type '{0}'", propertyInfo.PropertyType)); */ object propertyValue = methodInfo.Invoke(null, new object[] { serializedData[fieldKey], defaultValue }); propertyInfo.SetValue(targetObject, propertyValue, null); } } private static string GetTypeSerializationPrefix(Type type) { return type.FullName.Replace(".", "-") + "."; } public object Deserialize(string serializedObject) { Dictionary<string, string> serializationData = StringConversionServices.ParseKeyValueCollection(serializedObject); if (serializationData.ContainsKey("_IsNew_") == false) throw new ArgumentException("serializedObject is of wrong format"); IData data = null; bool isNew = StringConversionServices.DeserializeValueBool(serializationData["_IsNew_"]); if (isNew) { if (serializationData.ContainsKey("_Type_") == false) throw new ArgumentException("serializedObject is of wrong format"); string typeString = StringConversionServices.DeserializeValueString(serializationData["_Type_"]); Type interfaceType = TypeManager.GetType(typeString); data = DataFacade.BuildNew(interfaceType); } else { if (serializationData.ContainsKey("_DataSourceId_") == false) throw new ArgumentException("serializedObject is of wrong format"); string dataSourceIdString = StringConversionServices.DeserializeValueString(serializationData["_DataSourceId_"]); DataSourceId dataSourceId = DataSourceId.Deserialize(dataSourceIdString); data = DataFacade.GetDataFromDataSourceId(dataSourceId); if (data == null) throw new DataSerilizationException(string.Format("Failed to get the '{0}' with the given data source '{1}', data might have been deleted sinse this serialized data was created", dataSourceId.InterfaceType, dataSourceId)); } Type dataType = data.DataSourceId.InterfaceType; DeserializePropertiesFromInterface(serializationData, dataType, false, data); foreach (var inheritedInterface in dataType.GetInterfaces()) { if (inheritedInterface == typeof(IData)) continue; // DataSourceId is already deserialized so we're skipping it here DeserializePropertiesFromInterface(serializationData, inheritedInterface, true, data); } return data; } } } ================================================ FILE: Composite/Data/DataServiceScopeManager.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using Composite.Core.Caching; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DataServiceScopeManager { internal static void AddService(object service) { var serviceStack = DataServiceScopeStack?.Peek(); Verify.IsNotNull(serviceStack, "The data service stack was not pushed before use"); serviceStack.Add(service); } internal static void AddDefaultService(object service) { DataServiceDefaultList.Add(service); } internal static void DisableServices() { CallContext.SetData(DisableServicesCacheKey, true); } internal static void EnableServices() { CallContext.SetData(DisableServicesCacheKey,false); } internal static object GetService(Type t) { if (DisableServicesFlag.HasValue && DisableServicesFlag.Value) return null; foreach(var serviceList in DataServiceScopeStack) { var match = serviceList?.FindLast(f => f.GetType() == t); if (match != null) { return match; } } return DataServiceDefaultList.Last(f => f.GetType() == t); } private static readonly List<object> DataServiceDefaultList = new List<object>(); private static Stack<List<object>> DataServiceScopeStack { get { return CallContext.GetData(ServiceStackCacheKey) as Stack<List<object>> ?? RequestLifetimeCache.GetCachedOrNew<Stack<List<object>>>("DataServiceScopeManager:Stack"); } } private static bool? DisableServicesFlag { get { return CallContext.GetData(DisableServicesCacheKey) as bool? ?? RequestLifetimeCache.GetCachedOrNew<bool?>("DataServiceScopeManagerServiceDisabled:Bool"); } } /// <summary> /// Move the stack handling scope to a thread local store, enabling simultaneous threads to mutate (their own) scope. This will be in effect untill the thread has completed. /// </summary> public static void EnterThreadLocal() { if (CallContext.GetData(ServiceStackCacheKey) == null) { var threadLocalStack = new Stack<List<object>>(DataServiceScopeStack); CallContext.SetData(ServiceStackCacheKey, threadLocalStack); } if (CallContext.GetData(DisableServicesCacheKey) == null) { var threadLocalStackFlag = DisableServicesFlag; CallContext.SetData(DisableServicesCacheKey, threadLocalStackFlag); } } /// <summary> /// Move the stack handling to request scope. /// </summary> public static void ExitThreadLocal() { if (CallContext.GetData(ServiceStackCacheKey) != null) { CallContext.SetData(ServiceStackCacheKey, null); } if (CallContext.GetData(DisableServicesCacheKey) != null) { CallContext.SetData(DisableServicesCacheKey, null); } } private const string ServiceStackCacheKey = "DataServiceScopeManager:ThreadLocal"; private const string DisableServicesCacheKey = "DataServiceScopeManagerDisableServiceFlag:ThreadLocal"; internal static void PopDataServiceScope() { Verify.That(DataServiceScopeStack.Count > 0, nameof(DataServiceScopeStack) + " underflow"); DataServiceScopeStack.Pop().ForEach(f => (f as IDisposable)?.Dispose()); } internal static void PushDataServiceScope() { DataServiceScopeStack.Push(new List<object>()); } } } ================================================ FILE: Composite/Data/DataSourceId.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using Composite.Core.Serialization; using Composite.Core.Types; using Composite.Data.Foundation; using Composite.Data.Types; using Newtonsoft.Json; namespace Composite.Data { /// <summary> /// Uniquely identify a data element (table record in sql speak), its type and what provider it came from. /// </summary> public sealed class DataSourceId { private string _serializedData; private Dictionary<string, object> _tagInformation; /// <summary> /// This is for internal use only! /// </summary> public DataSourceId(IDataId dataId, string providerName, Type interfaceType) { if (string.IsNullOrEmpty(providerName)) throw new ArgumentNullException(nameof(providerName)); this.DataId = dataId ?? throw new ArgumentNullException(nameof(dataId)); ProviderName = providerName; InterfaceType = interfaceType ?? throw new ArgumentNullException(nameof(interfaceType)); DataScopeIdentifier = DataScopeManager.MapByType(interfaceType); LocaleScope = LocalizationScopeManager.MapByType(interfaceType); this.ExistsInStore = true; } /// <summary> /// This is for internal use only! /// </summary> public DataSourceId(IDataId dataId, string providerName, Type interfaceType, DataScopeIdentifier dataScopeIdentifier, CultureInfo localeScope) { // This constructor has to be extremely fast, we have up to 100.000 objects related while some requests if (string.IsNullOrEmpty(providerName)) throw new ArgumentNullException(nameof(providerName)); this.DataId = dataId ?? throw new ArgumentNullException(nameof(dataId)); ProviderName = providerName; InterfaceType = interfaceType ?? throw new ArgumentNullException(nameof(interfaceType)); DataScopeIdentifier = dataScopeIdentifier ?? throw new ArgumentNullException(nameof(dataScopeIdentifier)); LocaleScope = localeScope ?? throw new ArgumentNullException(nameof(localeScope)); this.ExistsInStore = true; } [JsonConstructor] private DataSourceId(IDataId dataId, string providerName, Type interfaceType, DataScopeIdentifier dataScopeIdentifier, string localeScope) { // This constructor has to be extremely fast, we have up to 100.000 objects related while some requests this.DataId = dataId ?? throw new ArgumentNullException(nameof(dataId)); ProviderName = providerName ?? DataProviderRegistry.DefaultDynamicTypeDataProviderName; InterfaceType = interfaceType ?? throw new ArgumentNullException(nameof(interfaceType)); DataScopeIdentifier = dataScopeIdentifier ?? throw new ArgumentNullException(nameof(dataScopeIdentifier)); LocaleScope = CultureInfo.CreateSpecificCulture(localeScope); this.ExistsInStore = true; } /// <summary> /// This is for internal use only! /// </summary> internal DataSourceId(Type interfaceType) { this.InterfaceType = interfaceType; this.ExistsInStore = false; } /// <summary> /// Object which the data provider can use to uniquely identify the 'table record' in its own store matching a data element. /// </summary> public IDataId DataId { get; } /// <summary> /// Name of the data provider responsible for the data element. /// </summary> public string ProviderName { get; } /// <exclude /> public bool ShouldSerializeProviderName() { // don't serialize ProviderName if it is default return ProviderName != DataProviderRegistry.DefaultDynamicTypeDataProviderName; } /// <summary> /// The interface used for the data element. This is expected to be implementing IData. /// </summary> public Type InterfaceType { get; } /// <summary> /// The data scope (language and published/unpublished) from which the data element originate. /// </summary> public DataScopeIdentifier DataScopeIdentifier { get; internal set; } /// <summary> /// The publication scope (published or unpublished) from which the data element originate. /// </summary> [JsonIgnore] public PublicationScope PublicationScope => DataScopeIdentifier.ToPublicationScope(); /// <summary> /// The language from which the data element originate. /// </summary> [JsonIgnore] public CultureInfo LocaleScope { get; internal set; } [JsonProperty(PropertyName = "localeScope")] private string LocalScopeName => (LocaleScope !=null ? LocaleScope.Name : null); /// <summary> /// True when the data element represents a physically stored element /// </summary> [JsonIgnore] public bool ExistsInStore { get; } /// <summary> /// Serialize to string /// </summary> /// <returns>Serialized as string</returns> public string Serialize() { return _serializedData ?? (_serializedData = CompositeJsonSerializer.Serialize(this)); } /// <summary> /// Recreate a DataSourceId based on a serialized string representation of it. /// </summary> /// <param name="serializedDataSourceId">A serialized DataSourceId</param> /// <returns>The DataSourceId deserialized</returns> public static DataSourceId Deserialize(string serializedDataSourceId) { DataSourceId dataSourceId; Deserialize(serializedDataSourceId, out dataSourceId, true); return dataSourceId; } /// <summary> /// Tries to deserialize a string as a DataSourceId. /// </summary> /// <param name="serializedDataSourceId">A serialized DataSourceId</param> /// <param name="dataSourceId">DataSourceId reference to set, if deserialization succeeded</param> /// <returns>True if the deserialization succeeded, otherwise false</returns> public static bool TryDeserialize(string serializedDataSourceId, out DataSourceId dataSourceId) { return Deserialize(serializedDataSourceId, out dataSourceId, false); } private static bool Deserialize(string serializedDataSourceId, out DataSourceId dataSourceId, bool throwException) { if(CompositeJsonSerializer.IsJsonSerialized(serializedDataSourceId)) { dataSourceId = CompositeJsonSerializer.Deserialize<DataSourceId>(serializedDataSourceId); return true; } return DeserializeLegacy(serializedDataSourceId, out dataSourceId, throwException); } private static bool DeserializeLegacy(string serializedDataSourceId, out DataSourceId dataSourceId, bool throwException) { dataSourceId = null; var dic = StringConversionServices.ParseKeyValueCollection(serializedDataSourceId); if (!dic.ContainsKey("_dataIdType_") || !dic.ContainsKey("_dataId_") || !dic.ContainsKey("_interfaceType_") || !dic.ContainsKey("_dataScope_") || !dic.ContainsKey("_localeScope_")) { if (throwException) { throw new ArgumentException("The argument is not a serialized " + nameof(DataSourceId), nameof(serializedDataSourceId)); } return false; } string serializedDataId = StringConversionServices.DeserializeValueString(dic["_dataId_"]); string dataIdTypeName = StringConversionServices.DeserializeValueString(dic["_dataIdType_"]); string providerName = dic.ContainsKey("_providerName_") ? StringConversionServices.DeserializeValueString(dic["_providerName_"]) : DataProviderRegistry.DefaultDynamicTypeDataProviderName; string interfaceTypeName = StringConversionServices.DeserializeValueString(dic["_interfaceType_"]); string dataScope = StringConversionServices.DeserializeValueString(dic["_dataScope_"]); string localeScope = StringConversionServices.DeserializeValueString(dic["_localeScope_"]); Type interfaceType = TypeManager.TryGetType(interfaceTypeName); if (interfaceType == null) { if (throwException) { throw new InvalidOperationException($"The type '{interfaceTypeName}' could not be found"); } return false; } Type dataIdType = TypeManager.TryGetType(dataIdTypeName); if (dataIdType == null) { if (throwException) { throw new InvalidOperationException($"The type '{dataIdTypeName}' could not be found"); } return false; } serializedDataId = FixSerializedDataId(serializedDataId, interfaceType); IDataId dataId = SerializationFacade.Deserialize<IDataId>(dataIdType, serializedDataId); CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture(localeScope); dataSourceId = new DataSourceId(dataId, providerName, interfaceType, DataScopeIdentifier.Deserialize(dataScope), cultureInfo); return true; } private static string FixSerializedDataId(string serializedDataId, Type interfaceType) { if (interfaceType == typeof(IPage) && !serializedDataId.Contains(nameof(IPage.VersionId))) { return serializedDataId + "," + serializedDataId.Replace(nameof(IPage.Id), nameof(IPage.VersionId)); } return serializedDataId; } /// <exclude /> public override string ToString() => Serialize(); /// <exclude /> public override bool Equals(object obj) { return obj is DataSourceId dataSourceId && Equals(dataSourceId); } /// <exclude /> public bool Equals(DataSourceId dataSourceId) { return dataSourceId != null && dataSourceId.ProviderName == ProviderName && dataSourceId.DataId.Equals(DataId) && dataSourceId.InterfaceType == InterfaceType && dataSourceId.DataScopeIdentifier.Equals(DataScopeIdentifier) && dataSourceId.LocaleScope.Name.Equals(LocaleScope.Name); } /// <exclude /> public override int GetHashCode() => DataId.GetHashCode() ^ InterfaceType.GetHashCode() ^ ProviderName.GetHashCode() ^ DataScopeIdentifier.GetHashCode() ^ LocaleScope.GetHashCode(); internal void SetTag(string id, object value) { InitializeTagInformation(); _tagInformation[id] = value; } internal void RemoveTag(string id) { if(_tagInformation == null) return; InitializeTagInformation(); _tagInformation.Remove(id); } internal bool TryGetTag(string id, out object value) { if(_tagInformation == null) { value = null; return false; } InitializeTagInformation(); return _tagInformation.TryGetValue(id, out value); } private void InitializeTagInformation() { if(_tagInformation == null) { _tagInformation = new Dictionary<string, object>(); } } } } ================================================ FILE: Composite/Data/DataTypeTypesManager.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Composite.Core; using Composite.Core.IO; using Composite.Core.Types; using Composite.Data.DynamicTypes; using Composite.Data.Foundation; using Composite.Data.GeneratedTypes; namespace Composite.Data { /// <summary> /// This class handles data type specific types: /// - Getting a data type from dataTypeId or data type descriptor /// - Getting a data type empty class from type or data type descriptor /// </summary> /// <exclude /> internal static class DataTypeTypesManager { private static readonly string LogTitle = typeof(DataTypeTypesManager).Name; private static List<Type> _LoadedDataTypes = new List<Type>(); /// <summary> /// Gets the runtime data type for the given data type id. /// In case of generated types, this call might result in a interface code compilation. /// </summary> /// <param name="dataTypeId">The id of the data type.</param> /// <returns>Returns the data type. Never null.</returns> public static Type GetDataType(Guid dataTypeId) { var dataTypeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(dataTypeId); if (dataTypeDescriptor == null) throw new InvalidOperationException("No data type exists with the given data type id: " + dataTypeId); return GetDataType(dataTypeDescriptor); } /// <summary> /// Gets the runtime data type for the given data type id. /// In case of generated types, this call might result in a interface code compilation. /// </summary> /// <param name="dataTypeDescriptor"> /// The DataTypeDescriptor for the data type. /// </param> /// <returns>Returns the data type. Never null.</returns> public static Type GetDataType(DataTypeDescriptor dataTypeDescriptor) { Verify.ArgumentNotNull(dataTypeDescriptor, "dataTypeDescriptor"); Type loadedDataType = _LoadedDataTypes.FirstOrDefault(f => f.FullName == dataTypeDescriptor.GetFullInterfaceName()); if (loadedDataType != null) return loadedDataType; Type type = InterfaceCodeManager.GetType(dataTypeDescriptor); return type; } /// <summary> /// Gets the runtime empty data type for the given data type. /// </summary> /// <param name="dataType"></param> /// <param name="forceReCompilation"> /// If this is true a new empty class will be /// compiled at runtime regardless if it exists or not. /// Use with caution! /// </param> /// <returns></returns> public static Type GetDataTypeEmptyClass(Type dataType, bool forceReCompilation = false) { return EmptyDataClassTypeManager.GetEmptyDataClassType(dataType, forceReCompilation); } /// <summary> /// Gets the runtime empty data type for the given data type descriptor. /// </summary> /// <param name="dataTypeDescriptor"></param> /// <returns></returns> public static Type GetDataTypeEmptyClass(DataTypeDescriptor dataTypeDescriptor) { return EmptyDataClassTypeManager.GetEmptyDataClassType(dataTypeDescriptor, false); } public static void AddNewAssembly(Assembly assembly) { AddNewAssembly(assembly, true); } /// <summary> /// Call this method whan a new assembly is load/added into the app domain. /// </summary> /// <param name="assembly"></param> /// <param name="logTypeLoadErrors"></param> public static void AddNewAssembly(Assembly assembly, bool logTypeLoadErrors) { if (!AssemblyFacade.AssemblyPotentiallyUsesType(assembly, typeof (IData))) { return; } try { var types = assembly.GetTypes(); _LoadedDataTypes.AddRange(types.Where(typeof(IData).IsAssignableFrom)); } catch (ReflectionTypeLoadException exception) { if (logTypeLoadErrors) { var exceptionToLog = exception.LoaderExceptions != null ? exception.LoaderExceptions.First() : exception; Log.LogError(LogTitle, new Exception($"Failed to load assembly '{assembly.FullName}'", exceptionToLog)); } } } internal static bool IsAllowedDataTypeAssembly(Type dataType) { string assemblyPath = dataType.Assembly.Location; if (assemblyPath.StartsWith(CodeGenerationManager.TempAssemblyFolderPath, StringComparison.InvariantCultureIgnoreCase)) return true; if (assemblyPath.StartsWith(CodeGenerationManager.BinFolder, StringComparison.InvariantCultureIgnoreCase)) return true; string assemblyFileName = Path.GetFileName(assemblyPath); bool locatedInBinFolder = C1Directory.GetFiles(CodeGenerationManager.BinFolder).Any(f => Path.GetFileName(f).Equals(assemblyFileName, StringComparison.InvariantCultureIgnoreCase)); if (locatedInBinFolder) return true; return false; } internal static Dictionary<Guid, Type> GetDataTypes(IReadOnlyCollection<DataTypeDescriptor> dataTypeDescriptors) { var result = new Dictionary<Guid, Type>(); var toCompile = new List<DataTypeDescriptor>(); foreach (var dataTypeDescriptor in dataTypeDescriptors) { string typeFullName = dataTypeDescriptor.GetFullInterfaceName(); Type type = _LoadedDataTypes.FirstOrDefault(f => f.FullName == typeFullName); if (type == null) { bool compilationNeeded; type = InterfaceCodeManager.TryGetType(dataTypeDescriptor, false, out compilationNeeded); if (compilationNeeded) { toCompile.Add(dataTypeDescriptor); } } if (type != null) { result[dataTypeDescriptor.DataTypeId] = type; } } if (toCompile.Any()) { var codeGenerationBuilder = new CodeGenerationBuilder("DataTypeTypesManager:compiling missing interfaces"); foreach (var dataTypeDescriptor in toCompile) { InterfaceCodeGenerator.AddAssemblyReferences(codeGenerationBuilder, dataTypeDescriptor); InterfaceCodeGenerator.AddInterfaceTypeCode(codeGenerationBuilder, dataTypeDescriptor); } var types = CodeGenerationManager.CompileRuntimeTempTypes(codeGenerationBuilder); var typesMap = types.ToDictionary(type => type.FullName); foreach (var dataTypeDescriptor in toCompile) { var type = typesMap[dataTypeDescriptor.GetFullInterfaceName()]; result[dataTypeDescriptor.DataTypeId] = type; } } return result; } } } ================================================ FILE: Composite/Data/DefaultFieldRandomStringValueAttribute.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.C1Console.Events; using Composite.Core.Linq; using Composite.Core.Types; using Composite.Core.WebClient; using Composite.Data.DynamicTypes; namespace Composite.Data { /// <summary> /// Sets the field's value to a random base64 string value of the specified length. /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class DefaultFieldRandomStringValueAttribute : DefaultFieldValueAttribute { private static readonly ConcurrentDictionary<Type, IEnumerable<RandomStringValueProperty>> ReflectionCache = new ConcurrentDictionary<Type, IEnumerable<RandomStringValueProperty>>(); internal int Length { get; private set; } internal bool CheckCollisions { get; private set; } private class RandomStringValueProperty { public PropertyInfo Property; public DefaultFieldRandomStringValueAttribute Attribute; public bool IsKey; } /// <summary> /// Sets the field's value to a random base64 string value of the specified length. /// </summary> /// <param name="length">The length of a generated random string. Allowed range is [3..22].</param> /// <param name="checkCollisions">When set to 2, the inserted value will be checked for a collision.</param> public DefaultFieldRandomStringValueAttribute(int length = 8, bool checkCollisions = false) { Verify.ArgumentCondition(length >= 3, "length", "Minimum allowed length is 3 characters"); Verify.ArgumentCondition(length <= 22, "length", "Maximum allowed length is 22 characters, which is an equivalent to a Guid value"); Length = length; CheckCollisions = checkCollisions; } static DefaultFieldRandomStringValueAttribute() { DataEvents<IData>.OnNew += (sender, arguments) => SetRandomStringFieldValues(arguments.Data, false); DataEvents<IData>.OnBeforeAdd += (sender, arguments) => SetRandomStringFieldValues(arguments.Data, true); GlobalEventSystemFacade.SubscribeToFlushEvent(a => ReflectionCache.Clear()); } private static void SetRandomStringFieldValues(IData data, bool checkCollisions) { var interfaceType = data.DataSourceId.InterfaceType; var fieldsToFill = GetRandomStringProperties(interfaceType); foreach (var field in fieldsToFill) { var value = field.Property.GetValue(data, null); if (value != null && (!(checkCollisions && field.Attribute.CheckCollisions) || !ValueIsInUse(interfaceType, field.Property, (string)value, field.IsKey))) continue; string randomString = GenerateNewUniqueValue(interfaceType, field); field.Property.SetValue(data, randomString); } } private static string GenerateNewUniqueValue(Type interfaceType, RandomStringValueProperty field) { string randomString = GenerateRandomString(field.Attribute.Length); if (field.Attribute.CheckCollisions) { bool uniqueValueFound = false; const int tries = 2; for (int i = 0; i < tries; i++) { if (!ValueIsInUse(interfaceType, field.Property, randomString, field.IsKey)) { uniqueValueFound = true; break; } randomString = GenerateRandomString(field.Attribute.Length); } if (!uniqueValueFound) { Verify.That(uniqueValueFound, "Failed to generate a unique random string value after {0} tries. Field name: {1}, random value length: {2}", tries, field.Property.Name, field.Attribute.Length); } } return randomString; } private static bool ValueIsInUse(Type interfaceType, PropertyInfo property, string value, bool isKeyField) { if (isKeyField) { var keyCollection = new DataKeyPropertyCollection(); keyCollection.AddKeyProperty(property, value); return DataFacade.TryGetDataByUniqueKey(interfaceType, keyCollection) != null; } var parameter = Expression.Parameter(interfaceType, "data"); var predicateExpression = ExpressionHelper.CreatePropertyPredicate(parameter, new[] { new Tuple<PropertyInfo, object>(property, value) }); Type delegateType = typeof(Func<,>).MakeGenericType(new [] { interfaceType, typeof(bool) }); LambdaExpression lambdaExpression = Expression.Lambda(delegateType, predicateExpression, new [] { parameter }); MethodInfo methodInfo = DataFacade.GetGetDataWithPredicatMethodInfo(interfaceType); var queryable = (IQueryable)methodInfo.Invoke(null, new object[] { lambdaExpression }); return queryable.OfType<IData>().Any(); } private static string GenerateRandomString(int length) { return UrlUtils.CompressGuid(Guid.NewGuid()).Substring(0, length); } private static IEnumerable<RandomStringValueProperty> GetRandomStringProperties(Type interfaceType) { return ReflectionCache.GetOrAdd(interfaceType, type => { List<RandomStringValueProperty> result = null; var stringProperties = type.GetPropertiesRecursively().Where(property => property.PropertyType == typeof(string)); foreach (var property in stringProperties) { var attribute = property.GetCustomAttribute<DefaultFieldRandomStringValueAttribute>(true); if (attribute == null) continue; result = result ?? new List<RandomStringValueProperty>(); var keyPropertyNames = type.GetKeyPropertyNames(); bool isKey = keyPropertyNames.Count == 1 && keyPropertyNames[0] == property.Name; result.Add(new RandomStringValueProperty { Attribute = attribute, Property = property, IsKey = isKey}); } return result ?? Enumerable.Empty<RandomStringValueProperty>(); }); } /// <exclude /> public override DefaultValue GetDefaultValue() { return DefaultValue.RandomString(Length, CheckCollisions); } } } ================================================ FILE: Composite/Data/DefaultFieldValueAttribute.cs ================================================ using System; using Composite.Data.DynamicTypes; namespace Composite.Data { /// <summary> /// This abstract class is used by data providers when a new column is added to a table. Extend this class to create your own. /// </summary> public abstract class DefaultFieldValueAttribute : Attribute { internal DefaultFieldValueAttribute() { } /// <exclude /> public abstract DefaultValue GetDefaultValue(); } /// <summary> /// Associate a static default value to a string property on a data type. /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class DefaultFieldStringValueAttribute : DefaultFieldValueAttribute { private readonly string _defaultValue; /// <summary> /// Associate a static default value to a string property on a data type. /// </summary> public DefaultFieldStringValueAttribute(string defaultValue) { if (defaultValue == null) throw new ArgumentNullException("defaultValue"); _defaultValue = defaultValue; } /// <exclude /> public override DefaultValue GetDefaultValue() { return DefaultValue.String(_defaultValue); } } /// <summary> /// Associate a static default value to an integer property on a data type. /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class DefaultFieldIntValueAttribute : DefaultFieldValueAttribute { private readonly int _defaultValue; /// <summary> /// Associate a static default value to an integer property on a data type. /// </summary> public DefaultFieldIntValueAttribute(int defaultValue) { _defaultValue = defaultValue; } /// <exclude /> public override DefaultValue GetDefaultValue() { return DefaultValue.Integer(_defaultValue); } } /// <summary> /// Associate a static default value to a decimal property on a data type. /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class DefaultFieldDecimalValueAttribute : DefaultFieldValueAttribute { private readonly decimal _defaultValue; /// <summary> /// Decimals are not allowed as attribute parameter values. They are structs. /// Use int value. /// </summary> /// <param name="defaultValue"></param> public DefaultFieldDecimalValueAttribute(int defaultValue) { _defaultValue = defaultValue; } /// <exclude /> public override DefaultValue GetDefaultValue() { return DefaultValue.Decimal(_defaultValue); } } /// <summary> /// Associate a static default value to a boolean property on a data type. /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class DefaultFieldBoolValueAttribute : DefaultFieldValueAttribute { private readonly bool _defaultValue; /// <summary> /// Associate a static default value to a boolean property on a data type. /// </summary> public DefaultFieldBoolValueAttribute(bool defaultValue) { _defaultValue = defaultValue; } /// <exclude /> public override DefaultValue GetDefaultValue() { return DefaultValue.Boolean(_defaultValue); } } /// <summary> /// Associate a static default value to a GUID property on a data type. /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class DefaultFieldGuidValueAttribute : DefaultFieldValueAttribute { private readonly Guid _defaultValue; /// <summary> /// Associate a static default value to a GUID property on a data type. /// </summary> public DefaultFieldGuidValueAttribute(string guidString) { _defaultValue = new Guid(guidString); } /// <exclude /> public override DefaultValue GetDefaultValue() { return DefaultValue.Guid(_defaultValue); } } /// <summary> /// Associate a random new GUID to a GUID property on a data type. /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class DefaultFieldNewGuidValueAttribute : DefaultFieldValueAttribute { /// <exclude /> public override DefaultValue GetDefaultValue() { return DefaultValue.NewGuid; } } /// <summary> /// Associate the current date and time to a DateTime property on a data type. /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class DefaultFieldNowDateTimeValueAttribute : DefaultFieldValueAttribute { /// <exclude /> public override DefaultValue GetDefaultValue() { return DefaultValue.Now; } } } ================================================ FILE: Composite/Data/DynamicTypes/Configuration/XmlConfigurationExtensionMethods.cs ================================================ using System; using System.Configuration; using System.Xml; using System.Xml.Linq; using Composite.Core.Extensions; namespace Composite.Data.DynamicTypes.Configuration { internal static class XmlConfigurationExtensionMethods { public static XAttribute GetRequiredAttribute(this XElement configurationElement, XName attributeName) { XAttribute result = configurationElement.Attribute(attributeName); if (result == null) { ThrowConfigurationError("Missing required attribute '{0}'".FormatWith(attributeName), configurationElement); } return result; } public static XElement GetRequiredElement(this XElement configurationElement, XName elementName) { var element = configurationElement.Element(elementName); if (element == null) { ThrowConfigurationError("Missing required element <{0}>".FormatWith(elementName), configurationElement); } return element; } public static string GetRequiredAttributeValue(this XElement configurationElement, XName attributeName) { string result = (string)configurationElement.Attribute(attributeName); if (string.IsNullOrEmpty(result)) { ThrowConfigurationError("Required attribute '{0}' is missing or empty".FormatWith(attributeName), configurationElement); } return result; } public static void ThrowConfigurationError(string message, XObject configurationXObject) { var document = configurationXObject.Document; if (document != null && !string.IsNullOrEmpty(document.BaseUri) && (configurationXObject as IXmlLineInfo).HasLineInfo()) { string fileName = GetFileName(document); int lineNumber = (configurationXObject as IXmlLineInfo).LineNumber; throw new ConfigurationErrorsException(message, fileName, lineNumber); } throw new InvalidOperationException(message); } public static Exception GetConfigurationException(string message, Exception innerException, XObject configurationXObject) { var document = configurationXObject.Document; if (document != null && !string.IsNullOrEmpty(document.BaseUri) && (configurationXObject as IXmlLineInfo).HasLineInfo()) { string fileName = GetFileName(document); int lineNumber = (configurationXObject as IXmlLineInfo).LineNumber; throw new ConfigurationErrorsException(message, innerException, fileName, lineNumber); } throw new InvalidOperationException(message, innerException); } private static string GetFileName(XDocument document) { const string fileUriPrefix = "file:///"; string baseUri = document.BaseUri; return baseUri.StartsWith(fileUriPrefix, StringComparison.Ordinal) ? baseUri.Substring(fileUriPrefix.Length) : baseUri; } } } ================================================ FILE: Composite/Data/DynamicTypes/DataAssociationDescriptor.cs ================================================ using System; using System.Xml.Linq; using Composite.Core.Types; namespace Composite.Data.DynamicTypes { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DataTypeAssociationDescriptor { /// <exclude /> public DataTypeAssociationDescriptor(Type associatedInterfaceType, string foreignKeyPropertyName, DataAssociationType dataAssociationType) { this.AssociatedInterfaceType = associatedInterfaceType; this.ForeignKeyPropertyName = foreignKeyPropertyName; this.AssociationType = dataAssociationType; } /// <exclude /> public Type AssociatedInterfaceType { get; private set; } /// <exclude /> public string ForeignKeyPropertyName { get; private set; } /// <exclude /> public DataAssociationType AssociationType { get; private set; } /// <exclude /> public XElement ToXml() { return new XElement("DataTypeAssociationDescriptor", new XAttribute("associatedInterfaceType", TypeManager.SerializeType(this.AssociatedInterfaceType)), new XAttribute("foreignKeyPropertyName", this.ForeignKeyPropertyName), new XAttribute("associationType", this.AssociationType)); } /// <exclude /> public static DataTypeAssociationDescriptor FromXml(XElement element) { if (element.Name != "DataTypeAssociationDescriptor") throw new ArgumentException("The xml is not correctly formattet"); XAttribute associatedInterfaceTypeAttribute = element.Attribute("associatedInterfaceType"); XAttribute foreignKeyPropertyNameAttribute = element.Attribute("foreignKeyPropertyName"); XAttribute associationTypeAttribute = element.Attribute("associationType"); if ((associatedInterfaceTypeAttribute == null) || (foreignKeyPropertyNameAttribute == null) || (associatedInterfaceTypeAttribute == null)) throw new ArgumentException("The xml is not correctly formattet"); Type associatedInterfaceType = TypeManager.GetType(associatedInterfaceTypeAttribute.Value); string foreignKeyPropertyName = foreignKeyPropertyNameAttribute.Value; DataAssociationType dataAssociationType = (DataAssociationType)Enum.Parse(typeof(DataAssociationType), associationTypeAttribute.Value); return new DataTypeAssociationDescriptor(associatedInterfaceType, foreignKeyPropertyName, dataAssociationType); } /// <exclude /> public override bool Equals(object obj) { return Equals(obj as DataTypeAssociationDescriptor); } /// <exclude /> public bool Equals(DataTypeAssociationDescriptor dataTypeAssociationDescriptor) { if (dataTypeAssociationDescriptor == null) return false; return this.AssociatedInterfaceType == dataTypeAssociationDescriptor.AssociatedInterfaceType && this.ForeignKeyPropertyName == dataTypeAssociationDescriptor.ForeignKeyPropertyName && this.AssociationType == dataTypeAssociationDescriptor.AssociationType; } /// <exclude /> public DataTypeAssociationDescriptor Clone() { return new DataTypeAssociationDescriptor(AssociatedInterfaceType, ForeignKeyPropertyName, AssociationType); } /// <exclude /> public override int GetHashCode() { return this.AssociatedInterfaceType.GetHashCode() ^ this.ForeignKeyPropertyName.GetHashCode() ^ this.AssociationType.GetHashCode(); } } } ================================================ FILE: Composite/Data/DynamicTypes/DataFieldDescriptor.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Xml.Linq; using Composite.Core.Types; using Composite.Data.DynamicTypes.Configuration; namespace Composite.Data.DynamicTypes { /// <summary> /// Describe a field on a <see cref="DataTypeDescriptor"/>. /// </summary> [Serializable] [DebuggerDisplay("Name = {Name}, Inherited = {Inherited}")] public sealed class DataFieldDescriptor { private bool _isNullable; private StoreFieldType _storeType; private DefaultValue _defaultValue; private string _name; private readonly Guid _id; /// <summary> /// Constructs a new instance. /// </summary> /// <param name="id">Permanent unique id for this field. This should never change.</param> /// <param name="name">Name (programmatic) of field.</param> /// <param name="storeType">Type to use when storing field.</param> /// <param name="instanceType">Type to use when field is exposed to .NET.</param> public DataFieldDescriptor(Guid id, string name, StoreFieldType storeType, Type instanceType) : this(id, name, storeType, instanceType, false) { _id = id; _name = NameValidation.ValidateName(name); this.StoreType = storeType; this.InstanceType = instanceType; this.FormRenderingProfile = new DataFieldFormRenderingProfile(); this.TreeOrderingProfile = new DataFieldTreeOrderingProfile(); this.IsReadOnly = false; } /// <summary> /// Constructs a new instance. /// </summary> /// <param name="id">Permanent unique id for this field. This should never change.</param> /// <param name="name">Name (programmatic) of field </param> /// <param name="storeType">Type to use when storing field</param> /// <param name="instanceType">Type to use when field is exposed to .NET</param> /// <param name="inherited">True when this field is inherited from a super interface.</param> public DataFieldDescriptor(Guid id, string name, StoreFieldType storeType, Type instanceType, bool inherited) { _id = id; _name = NameValidation.ValidateName(name); this.StoreType = storeType; this.InstanceType = instanceType; this.FormRenderingProfile = new DataFieldFormRenderingProfile(); this.TreeOrderingProfile = new DataFieldTreeOrderingProfile(); this.Inherited = inherited; this.IsReadOnly = false; } /// <summary> /// Position, relative to other fields. /// </summary> public int Position { get; set; } /// <summary> /// For grouping (ex. tree views), the priority of this field, relative to other fields. Lowest number gets grouped first. /// 0 means no grouping on this field. /// </summary> public int GroupByPriority { get; set; } /// <summary> /// Describe how this field should be edited in a form view /// </summary> public DataFieldFormRenderingProfile FormRenderingProfile { get; set; } /// <summary> /// Describe how this field should be part of a URL /// </summary> public DataUrlProfile DataUrlProfile { get; set; } /// <summary> /// Describe whether the field should be a part of search index. /// </summary> public SearchProfile SearchProfile { get; set; } /// <summary> /// Describe how this field should influence ordering of items in a tree view /// </summary> public DataFieldTreeOrderingProfile TreeOrderingProfile { get; set; } /// <summary> /// Specify the TypeManager type name for the type this field references. Null if this is not a reference field. /// </summary> public string ForeignKeyReferenceTypeName { get; set; } /// <summary> /// The CLR type of the field. /// </summary> public Type InstanceType { get; set; } /// <summary> /// Programmatic name of the field. /// </summary> public string Name { get { return _name; } set { _name = NameValidation.ValidateName(value); } } /// <summary> /// Permanent unique id for the field. This should never change. /// </summary> public Guid Id => _id; /// <summary> /// Describe how this field should be sored physically. /// </summary> public StoreFieldType StoreType { get { return _storeType; } set { _storeType = value; if (_defaultValue != null && !_defaultValue.IsAssignableTo(_storeType)) { _defaultValue = null; } } } /// <summary> /// Default value for the field, to be used for the physical store. See also <see cref="NewInstanceDefaultFieldValue"/> /// </summary> public DefaultValue DefaultValue { get { return _defaultValue; } set { if (value != null && !value.IsAssignableTo(_storeType)) { throw new InvalidOperationException("The DefaultValue must be assignable to the StoreType"); } _defaultValue = value; } } /// <summary> /// True when this field can be NULL /// </summary> public bool IsNullable { get { return _isNullable; } set { if (value) { var type = InstanceType; if (type.IsEnum) throw new InvalidOperationException("The associated instance type is an enum, which is not nullable"); if (type.IsValueType && (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(Nullable<>))) { throw new InvalidOperationException(string.Format("The associated instante type '{0}' is a value type, which is not nullable", type.Name)); } } _isNullable = value; } } /// <summary> /// True when this field is inherited from a super interface. /// </summary> public bool Inherited { get; private set; } /// <summary> /// True when data in this field can not be changed. /// </summary> public bool IsReadOnly { get; set; } /// <summary> /// Function markup that can deliver validators for this field. They will execute and validate if values set on this field is valid. /// </summary> public List<string> ValidationFunctionMarkup { get; set; } /// <summary> /// Default value to set on new instances of this field. /// </summary> public string NewInstanceDefaultFieldValue { get; set; } /// <summary> /// Create a clone of this field. /// </summary> /// <returns>The clone.</returns> public DataFieldDescriptor Clone() { return new DataFieldDescriptor(this.Id, this.Name, this.StoreType, this.InstanceType) { ForeignKeyReferenceTypeName = this.ForeignKeyReferenceTypeName, FormRenderingProfile = new DataFieldFormRenderingProfile { HelpText = this.FormRenderingProfile.HelpText, Label = this.FormRenderingProfile.Label, WidgetFunctionMarkup = this.FormRenderingProfile.WidgetFunctionMarkup }, TreeOrderingProfile = new DataFieldTreeOrderingProfile { OrderPriority = this.TreeOrderingProfile.OrderPriority, OrderDescending = this.TreeOrderingProfile.OrderDescending }, GroupByPriority = this.GroupByPriority, Inherited = this.Inherited, IsNullable = this.IsNullable, Position = this.Position, ValidationFunctionMarkup = this.ValidationFunctionMarkup != null ? new List<string>(this.ValidationFunctionMarkup) : null, NewInstanceDefaultFieldValue = this.NewInstanceDefaultFieldValue, DataUrlProfile = this.DataUrlProfile?.Clone(), SearchProfile = this.SearchProfile?.Clone(), DefaultValue = this.DefaultValue?.Clone() }; } /// <summary> /// Serialize this field description XML. /// </summary> /// <returns>Serialized field descriptor.</returns> public XElement ToXml() { var element = new XElement("DataFieldDescriptor", new XAttribute("id", this.Id), new XAttribute("name", this.Name), new XAttribute("isNullable", this.IsNullable), new XAttribute("position", this.Position), new XAttribute("groupByPriority", this.GroupByPriority), new XAttribute("inherited", this.Inherited), new XAttribute("instanceType", TypeManager.SerializeType(this.InstanceType)), new XAttribute("storeType", this.StoreType.Serialize()), new XAttribute("isReadOnly", this.IsReadOnly)); if (this.NewInstanceDefaultFieldValue != null) { element.Add(new XAttribute("newInstanceDefaultFieldValue", this.NewInstanceDefaultFieldValue)); } if (this.DefaultValue != null) { element.Add(new XAttribute("defaultValue", this.DefaultValue.Serialize())); } if (this.ForeignKeyReferenceTypeName != null) { element.Add(new XAttribute("foreignKeyReferenceTypeName", this.ForeignKeyReferenceTypeName)); } if (this.FormRenderingProfile != null) { XElement formRenderingProfileElement = new XElement("FormRenderingProfile"); if (this.FormRenderingProfile.Label != null) { formRenderingProfileElement.Add(new XAttribute("label", this.FormRenderingProfile.Label)); } if (this.FormRenderingProfile.HelpText != null) { formRenderingProfileElement.Add(new XAttribute("helpText", this.FormRenderingProfile.HelpText)); } if (this.FormRenderingProfile.WidgetFunctionMarkup != null) { formRenderingProfileElement.Add(new XAttribute("widgetFunctionMarkup", this.FormRenderingProfile.WidgetFunctionMarkup)); } element.Add(formRenderingProfileElement); } if (this.DataUrlProfile != null) { element.Add(new XElement("DataUrlProfile", new XAttribute("Order", this.DataUrlProfile.Order), this.DataUrlProfile.Format != null ? new XAttribute("Format", this.DataUrlProfile.Format) : null)); } if (this.SearchProfile != null) { element.Add(new XElement(nameof(SearchProfile), new XAttribute(CamelCase(nameof(SearchProfile.IndexText)), this.SearchProfile.IndexText), new XAttribute(CamelCase(nameof(SearchProfile.EnablePreview)), this.SearchProfile.EnablePreview), new XAttribute(CamelCase(nameof(SearchProfile.IsFacet)), this.SearchProfile.IsFacet))); } if (this.TreeOrderingProfile?.OrderPriority != null) { element.Add(new XElement("TreeOrderingProfile", new XAttribute("orderPriority", this.TreeOrderingProfile.OrderPriority), new XAttribute("orderDescending", this.TreeOrderingProfile.OrderDescending))); } if (this.ValidationFunctionMarkup != null) { XElement elementValidationFunctionMarkup = new XElement("ValidationFunctionMarkups"); foreach (string validationFunctionMarkup in this.ValidationFunctionMarkup) { elementValidationFunctionMarkup.Add(new XElement("ValidationFunctionMarkup", new XAttribute("markup", validationFunctionMarkup))); } element.Add(elementValidationFunctionMarkup); } return element; } private static string CamelCase(string str) { return char.ToLowerInvariant(str[0]) + str.Substring(1); } /// <summary> /// Deserialize a <see cref="DataFieldDescriptor"/>. /// </summary> /// <param name="element">Deserialized DataFieldDescriptor</param> /// <returns></returns> public static DataFieldDescriptor FromXml(XElement element) { if (element.Name != "DataFieldDescriptor") throw new ArgumentException("The xml is not correctly formatted"); Guid id = (Guid)element.GetRequiredAttribute("id"); string name = element.GetRequiredAttributeValue("name"); bool isNullable = (bool)element.GetRequiredAttribute("isNullable"); int position = (int)element.GetRequiredAttribute("position"); bool inherited = (bool)element.GetRequiredAttribute("inherited"); XAttribute groupByPriorityAttribute = element.Attribute("groupByPriority"); XAttribute instanceTypeAttribute = element.GetRequiredAttribute("instanceType"); XAttribute storeTypeAttribute = element.GetRequiredAttribute("storeType"); XAttribute isReadOnlyAttribute = element.Attribute("isReadOnly"); XAttribute newInstanceDefaultFieldValueAttribute = element.Attribute("newInstanceDefaultFieldValue"); bool isReadOnly = isReadOnlyAttribute != null && (bool) isReadOnlyAttribute; int groupByPriority = groupByPriorityAttribute != null ? (int)groupByPriorityAttribute : 0; XAttribute defaultValueAttribute = element.Attribute("defaultValue"); XAttribute foreignKeyReferenceTypeNameAttribute = element.Attribute("foreignKeyReferenceTypeName"); XElement formRenderingProfileElement = element.Element("FormRenderingProfile"); XElement treeOrderingProfileElement = element.Element("TreeOrderingProfile"); XElement validationFunctionMarkupsElement = element.Element("ValidationFunctionMarkups"); XElement dataUrlProfileElement = element.Element("DataUrlProfile"); XElement searchProfileElement = element.Element(nameof(SearchProfile)); Type instanceType = TypeManager.GetType(instanceTypeAttribute.Value); StoreFieldType storeType = StoreFieldType.Deserialize(storeTypeAttribute.Value); var dataFieldDescriptor = new DataFieldDescriptor(id, name, storeType, instanceType, inherited) { IsNullable = isNullable, Position = position, GroupByPriority = groupByPriority, IsReadOnly = isReadOnly }; if (newInstanceDefaultFieldValueAttribute != null) { dataFieldDescriptor.NewInstanceDefaultFieldValue = newInstanceDefaultFieldValueAttribute.Value; } if (defaultValueAttribute != null) { DefaultValue defaultValue = DefaultValue.Deserialize(defaultValueAttribute.Value); dataFieldDescriptor.DefaultValue = defaultValue; } if (foreignKeyReferenceTypeNameAttribute != null) { string typeName = foreignKeyReferenceTypeNameAttribute.Value; typeName = TypeManager.FixLegasyTypeName(typeName); dataFieldDescriptor.ForeignKeyReferenceTypeName = typeName; } if (formRenderingProfileElement != null) { XAttribute labelAttribute = formRenderingProfileElement.Attribute("label"); XAttribute helpTextAttribute = formRenderingProfileElement.Attribute("helpText"); XAttribute widgetFunctionMarkupAttribute = formRenderingProfileElement.Attribute("widgetFunctionMarkup"); var dataFieldFormRenderingProfile = new DataFieldFormRenderingProfile(); if (labelAttribute != null) { dataFieldFormRenderingProfile.Label = labelAttribute.Value; } if (helpTextAttribute != null) { dataFieldFormRenderingProfile.HelpText = helpTextAttribute.Value; } if (widgetFunctionMarkupAttribute != null) { dataFieldFormRenderingProfile.WidgetFunctionMarkup = widgetFunctionMarkupAttribute.Value; } dataFieldDescriptor.FormRenderingProfile = dataFieldFormRenderingProfile; } if (dataUrlProfileElement != null) { int order = (int)dataUrlProfileElement.GetRequiredAttribute("Order"); var formatStr = (string)dataUrlProfileElement.Attribute("Format"); DataUrlSegmentFormat? format = null; if (formatStr != null) { format = (DataUrlSegmentFormat) Enum.Parse(typeof(DataUrlSegmentFormat), formatStr); } dataFieldDescriptor.DataUrlProfile = new DataUrlProfile {Order = order, Format = format}; } if (searchProfileElement != null) { Func<string, bool> getAttr = fieldName => (bool)searchProfileElement.GetRequiredAttribute(CamelCase(fieldName)); dataFieldDescriptor.SearchProfile = new SearchProfile { IndexText = getAttr(nameof(DynamicTypes.SearchProfile.IndexText)), EnablePreview = getAttr(nameof(DynamicTypes.SearchProfile.EnablePreview)), IsFacet = getAttr(nameof(DynamicTypes.SearchProfile.IsFacet)) }; } if (treeOrderingProfileElement != null) { int? orderPriority = (int?)treeOrderingProfileElement.Attribute("orderPriority"); bool orderDescending = (bool)treeOrderingProfileElement.Attribute("orderDescending"); dataFieldDescriptor.TreeOrderingProfile = new DataFieldTreeOrderingProfile { OrderPriority = orderPriority, OrderDescending = orderDescending }; } dataFieldDescriptor.ValidationFunctionMarkup = new List<string>(); if (validationFunctionMarkupsElement != null) { foreach (XElement validationFunctionMarkupElement in validationFunctionMarkupsElement.Elements("ValidationFunctionMarkup")) { string markup = validationFunctionMarkupElement.GetRequiredAttributeValue("markup"); dataFieldDescriptor.ValidationFunctionMarkup.Add(markup); } } return dataFieldDescriptor; } /// <exclude /> public override bool Equals(object obj) { return Equals(obj as DataFieldDescriptor); } /// <exclude /> public bool Equals(DataFieldDescriptor dataFieldDescriptor) { return dataFieldDescriptor != null && dataFieldDescriptor.Id == Id; } /// <exclude /> public override int GetHashCode() { return this.Id.GetHashCode(); } } } ================================================ FILE: Composite/Data/DynamicTypes/DataFieldDescriptorCollection.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Composite.Core.Extensions; namespace Composite.Data.DynamicTypes { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DataFieldDescriptorCollection : IEnumerable<DataFieldDescriptor> { private readonly DataTypeDescriptor _parent; private readonly List<DataFieldDescriptor> _descriptors = new List<DataFieldDescriptor>(); internal DataFieldDescriptorCollection(DataTypeDescriptor parent) { _parent = parent; } /// <exclude /> public int Count { get { return _descriptors.Count; } } /// <exclude /> public void Add(DataFieldDescriptor descriptor) { Verify.ArgumentNotNull(descriptor, "descriptor"); if (_descriptors.Contains(descriptor)) { throw new ArgumentException("The specifed DataFieldDescriptor with ID '{0}' has already been added. ".FormatWith(descriptor.Id) + "Developers should ensure that the Immutable Field Id is unique on all fields."); } if (this[descriptor.Name] != null) { throw new InvalidOperationException("The specified field name '{0}' is in use by another DataFieldDescriptor".FormatWith(descriptor.Name)); } if (this[descriptor.Id] != null) { throw new InvalidOperationException("The specified field Id '{0}' is in use by another DataFieldDescriptor".FormatWith(descriptor.Id)); } _descriptors.Add(descriptor); } /// <exclude /> public void Insert(int index, DataFieldDescriptor descriptor) { Verify.ArgumentNotNull(descriptor, "descriptor"); if (_descriptors.Contains(descriptor)) throw new ArgumentException("The specified DataFieldDescriptor with ID '{0}' has already been added".FormatWith(descriptor.Id)); if (this[descriptor.Name] != null) { throw new InvalidOperationException("The specified field name '{0}' is in use by another DataFieldDescriptor".FormatWith(descriptor.Name)); } if (this[descriptor.Id] != null) { throw new InvalidOperationException("The specified field Id '{0}' is in use by another DataFieldDescriptor".FormatWith(descriptor.Id)); } _descriptors.Insert(index, descriptor); } /// <exclude /> public void Remove(DataFieldDescriptor descriptor) { Verify.ArgumentNotNull(descriptor, "descriptor"); if (!_descriptors.Contains(descriptor)) throw new ArgumentException("The specified DataFieldDescriptor was not found"); if (_parent.KeyPropertyNames.Contains(descriptor.Name)) throw new ArgumentException("The DataFieldDescriptor can not be removed while it is a member of the key field list."); if (_parent.StoreSortOrderFieldNames.Contains(descriptor.Name)) throw new ArgumentException("The DataFieldDescriptor can not be removed while it is a member of the physical sort order field list."); _descriptors.Remove(descriptor); } /// <exclude /> public bool Contains(DataFieldDescriptor descriptor) { Verify.ArgumentNotNull(descriptor, "descriptor"); return _descriptors.Contains(descriptor); } /// <exclude /> public DataFieldDescriptor this[string name] { get { return _descriptors.SingleOrDefault(d => d.Name == name); } } /// <exclude /> public DataFieldDescriptor this[Guid id] { get { return _descriptors.SingleOrDefault(d => d.Id == id); } } /// <exclude /> public IEnumerator<DataFieldDescriptor> GetEnumerator() { return _descriptors.OrderBy(f => f.Position).GetEnumerator(); } /// <exclude /> IEnumerator IEnumerable.GetEnumerator() { return _descriptors.OrderBy(f => f.Position).GetEnumerator(); } } } ================================================ FILE: Composite/Data/DynamicTypes/DataFieldDescriptorValueXmlSerializer.cs ================================================ using System; using System.Linq; using Composite.Core.Serialization; using System.Xml.Linq; namespace Composite.Data.DynamicTypes { internal sealed class DataFieldDescriptorValueXmlSerializer : IValueXmlSerializer { public bool TrySerialize(Type objectToSerializeType, object objectToSerialize, IXmlSerializer xmlSerializer, out XElement serializedObject) { if (objectToSerializeType == null) throw new ArgumentNullException("objectToSerializeType"); serializedObject = null; if (objectToSerializeType != typeof(DataFieldDescriptor)) return false; if (objectToSerialize == null) { serializedObject = new XElement("DataFieldDescriptor"); } else { DataFieldDescriptor dataFieldDescriptor = (DataFieldDescriptor)objectToSerialize; serializedObject = dataFieldDescriptor.ToXml(); } return true; } public bool TryDeserialize(XElement serializedObject, IXmlSerializer xmlSerializer, out object deserializedObject) { if (serializedObject == null) throw new ArgumentNullException("serializedObject"); deserializedObject = null; if (serializedObject.Name.LocalName != "DataFieldDescriptor") return false; if (!serializedObject.Elements().Any()) { deserializedObject = null; } else { deserializedObject = DataFieldDescriptor.FromXml(serializedObject); } return true; } } } ================================================ FILE: Composite/Data/DynamicTypes/DataFieldFormRenderingProfile.cs ================================================ using System; namespace Composite.Data.DynamicTypes { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable()] public class DataFieldFormRenderingProfile { /// <exclude /> public virtual string Label { get; set; } /// <exclude /> public virtual string HelpText { get; set; } /// <exclude /> public virtual string WidgetFunctionMarkup { get; set; } } [Serializable()] internal class LazyDataFieldFormRenderingProfile : DataFieldFormRenderingProfile { [NonSerialized] private string _widgetFunctionMarkup = null; [NonSerialized] private Func<string> _widgetFunctionMarkupFunc; public Func<string> WidgetFunctionMarkupFunc { get { return _widgetFunctionMarkupFunc; } set { _widgetFunctionMarkupFunc = value; } } public override string WidgetFunctionMarkup { get { if (_widgetFunctionMarkup == null) { _widgetFunctionMarkup = WidgetFunctionMarkupFunc(); } return _widgetFunctionMarkup; } set { _widgetFunctionMarkup = value; } } } } ================================================ FILE: Composite/Data/DynamicTypes/DataFieldIdEqualityComparer.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Text; namespace Composite.Data.DynamicTypes { internal sealed class DataFieldIdEqualityComparer : EqualityComparer<DataFieldDescriptor> { public override bool Equals(DataFieldDescriptor x, DataFieldDescriptor y) { return x.Id.Equals(y.Id); } public override int GetHashCode(DataFieldDescriptor obj) { return obj.Id.GetHashCode(); } } } ================================================ FILE: Composite/Data/DynamicTypes/DataFieldNameCollection.cs ================================================ using System; using System.Collections.Generic; namespace Composite.Data.DynamicTypes { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DataFieldNameCollection : IEnumerable<string> { private readonly List<string> _dataFieldNames = new List<string>(); private readonly DataFieldDescriptorCollection _validDataFieldDescriptions; private readonly bool _allowNullableFields; private readonly bool _allowListFields; private readonly bool _allowLargeStringFields; internal DataFieldNameCollection(DataFieldDescriptorCollection validDataFieldDescriptions, bool allowNullableFields, bool allowListFields, bool allowLargeStringFields) { _validDataFieldDescriptions = validDataFieldDescriptions; _allowNullableFields = allowNullableFields; _allowListFields = allowListFields; _allowLargeStringFields = allowLargeStringFields; } /// <exclude /> public void Add(string dataFieldName) { Add(dataFieldName, true); } /// <exclude /> public void Add(string dataFieldName, bool validateFieldMemberShip) { if (validateFieldMemberShip) { ValidateFieldMembership(dataFieldName); } _dataFieldNames.Add(dataFieldName); } /// <exclude /> public void Remove(string dataFieldName) { _dataFieldNames.Remove(dataFieldName); } /// <exclude /> public void Clear() { _dataFieldNames.Clear(); } /// <exclude /> public bool Contains(string fieldName) { return _dataFieldNames.Contains(fieldName); } /// <exclude /> public int Count { get { return _dataFieldNames.Count; } } /// <exclude /> public string this[int index] { get { return _dataFieldNames[index]; } } /// <exclude /> public IEnumerator<string> GetEnumerator() { return _dataFieldNames.GetEnumerator(); } /// <exclude /> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _dataFieldNames.GetEnumerator(); } internal void ValidateMembers() { foreach (string fieldName in _dataFieldNames) { ValidateFieldMembership(fieldName); } } private void ValidateFieldMembership(string dataFieldName) { DataFieldDescriptor dataFieldDescriptor = _validDataFieldDescriptions[dataFieldName]; if (dataFieldDescriptor == null) throw new ArgumentException(string.Format("Unknown data field name '{0}'", dataFieldName)); if (_allowNullableFields == false && dataFieldDescriptor.IsNullable) throw new ArgumentException("Can not add nullable fields to this list"); if (dataFieldDescriptor.StoreType.PhysicalStoreType == PhysicalStoreFieldType.LargeString && _allowLargeStringFields == false) throw new ArgumentException("Can not add large string fields to this list"); } } } ================================================ FILE: Composite/Data/DynamicTypes/DataFieldTreeOrderingProfile.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Composite.Data.DynamicTypes { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable()] public class DataFieldTreeOrderingProfile { /// <exclude /> public DataFieldTreeOrderingProfile() { OrderPriority = null; OrderDescending = false; } /// <exclude /> public virtual int? OrderPriority { get; set; } /// <exclude /> public virtual bool OrderDescending { get; set; } /// <exclude /> public override string ToString() { return String.Format("{0},{1}", OrderPriority, OrderDescending); } /// <exclude /> public static DataFieldTreeOrderingProfile FromString(string str) { var parts = str.Split(','); int priority; bool order; DataFieldTreeOrderingProfile treeOrderingProfile = new DataFieldTreeOrderingProfile(); if (int.TryParse(parts[0], out priority)) treeOrderingProfile.OrderPriority = priority; if (parts.Length > 1 && bool.TryParse(parts[1], out order)) treeOrderingProfile.OrderDescending = order; return treeOrderingProfile; } } } ================================================ FILE: Composite/Data/DynamicTypes/DataTypeChangeDescriptor.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using Composite.Core.Linq; namespace Composite.Data.DynamicTypes { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DataTypeChangeDescriptor { private readonly DataTypeDescriptor _original; private readonly DataTypeDescriptor _altered; private readonly bool _originalTypeDataExists; /// <exclude /> public DataTypeChangeDescriptor(DataTypeDescriptor originalTypeDescriptor, DataTypeDescriptor alteredTypeDescriptor) : this(originalTypeDescriptor, alteredTypeDescriptor, true) { } internal DataTypeChangeDescriptor(DataTypeDescriptor originalTypeDescriptor, DataTypeDescriptor alteredTypeDescriptor, bool originalTypeDataExists) { if (originalTypeDescriptor.DataTypeId != alteredTypeDescriptor.DataTypeId) throw new ArgumentException("The original and current data type descriptors must have the same data type id"); _original = originalTypeDescriptor; _altered = alteredTypeDescriptor; _originalTypeDataExists = originalTypeDataExists; ValidateTypeChanges(); } /// <exclude /> public bool AlteredTypeHasChanges { get { bool alteredTypeHasChanges = false; alteredTypeHasChanges |= this.AlteredType.IsCodeGenerated != this.OriginalType.IsCodeGenerated; alteredTypeHasChanges |= this.AlteredType.Name != this.OriginalType.Name; alteredTypeHasChanges |= this.AlteredType.Namespace != this.OriginalType.Namespace; // Do we really need to regenerated the type if it has a new type manager type name? //alteredTypeHasChanges |= (this.AlteredType.TypeManagerTypeName != this.OriginalType.TypeManagerTypeName); alteredTypeHasChanges |= this.AddedFields.Any(); alteredTypeHasChanges |= this.DeletedFields.Any(); alteredTypeHasChanges |= this.AddedKeyFields.Any(); alteredTypeHasChanges |= this.DeletedKeyFields.Any(); alteredTypeHasChanges |= this.KeyFieldsOrderChanged; alteredTypeHasChanges |= this.ExistingFields.Any(f => f.AlteredFieldHasChanges); alteredTypeHasChanges |= this.AddedDataScopes.Any(); alteredTypeHasChanges |= this.DeletedDataScopes.Any(); alteredTypeHasChanges |= IndexesChanged; alteredTypeHasChanges |= VersionKeyFieldsChanged; return alteredTypeHasChanges; } } /// <summary> /// Indicates if type's metadata should be updated. /// </summary> internal bool TypeHasMetaDataChanges => !OriginalType.IsCodeGenerated && (OriginalType.Title != AlteredType.Title || OriginalType.LabelFieldName != AlteredType.LabelFieldName || OriginalType.Cachable != AlteredType.Cachable || OriginalType.Searchable != AlteredType.Searchable || OriginalType.InternalUrlPrefix != AlteredType.InternalUrlPrefix); /// <exclude /> public DataTypeDescriptor OriginalType => _original; /// <exclude /> public DataTypeDescriptor AlteredType => _altered; /// <summary> /// True when the system contains data of the original type. Allowable schema changes can be limited when data exists. /// </summary> public bool OriginalTypeDataExists => _originalTypeDataExists; /// <summary> /// Returns original fields that are no longer part of the altered type. /// </summary> public IEnumerable<DataFieldDescriptor> DeletedFields { get { return _original.Fields.Except(_altered.Fields, new DataFieldIdEqualityComparer()); } } /// <summary> /// Returns added fields that were not part of the original type. /// </summary> public IEnumerable<DataFieldDescriptor> AddedFields { get { return _altered.Fields.Except(_original.Fields, new DataFieldIdEqualityComparer()); } } /// <summary> /// Returns fields that exists in both the original and altered type. Fields may have changed name or type. /// </summary> public IEnumerable<ExistingFieldInfo> ExistingFields { get { var existingFields = from altered in _altered.Fields join original in _original.Fields on altered.Id equals original.Id select new ExistingFieldInfo(original, altered); return existingFields; } } /// <summary> /// Returns original DataScopes that are no longer part of the altered type. /// </summary> public IEnumerable<DataScopeIdentifier> DeletedDataScopes { get { return _original.DataScopes.Where(f => _altered.DataScopes.Count(g => g.Name == f.Name) == 0); } } /// <summary> /// Returns new DataScopes that was not part of the original type. /// </summary> public IEnumerable<DataScopeIdentifier> AddedDataScopes { get { return _altered.DataScopes.Where(f => _original.DataScopes.Count(g => g.Name == f.Name) == 0); } } /// <summary> /// Returns new DataScopes that was not part of the original type. /// </summary> public IEnumerable<DataScopeIdentifier> ExistingDataScopes { get { return _altered.DataScopes.Where(f => _original.DataScopes.Count(g => g.Name == f.Name) == 1); } } IEnumerable<DataFieldDescriptor> GetKeyProperties_Original() { return _original.KeyPropertyNames .Select(name => _original.Fields.Where(fld => fld.Name == name) .FirstOrException("Key property name {0} is not defined in the <Fields> section", name)).ToList(); } IEnumerable<DataFieldDescriptor> GetKeyProperties_Altered() { return _altered.KeyPropertyNames.Select(name => _altered.Fields.Where(fld => fld.Name == name) .FirstOrException("Key property name {0} is not defined in the <Fields> section", name)).ToList(); } /// <summary> /// Returns original key fields that are not part of the altered types key. Fields may have been deleted or demoted to normal fields. /// </summary> public IEnumerable<DataFieldDescriptor> DeletedKeyFields { get { return GetKeyProperties_Original().Except(GetKeyProperties_Altered(), new DataFieldIdEqualityComparer()); } } /// <summary> /// Returns added key fields that were not part of the original types key. Fields may be new or promoted from normal fields. /// </summary> public IEnumerable<DataFieldDescriptor> AddedKeyFields { get { return GetKeyProperties_Altered().Except(GetKeyProperties_Original(), new DataFieldIdEqualityComparer()); } } /// <summary> /// Returns true if order of key properties have been changed /// </summary> public bool KeyFieldsOrderChanged { get { return !GetKeyProperties_Original().SequenceEqual(GetKeyProperties_Altered(), new DataFieldIdEqualityComparer()); } } /// <summary> /// Returns <value>true</value> if indexes have changed /// </summary> public bool IndexesChanged { get { var originalIndexes = OriginalType.Indexes; var newIndexes = AlteredType.Indexes; Func<IReadOnlyCollection<DataTypeIndex>, string> serializeIndexes = indexes => string.Join("|", indexes.Select(i => i.ToString()).OrderBy(a => a)); return serializeIndexes(originalIndexes) != serializeIndexes(newIndexes); } } /// <summary> /// Returns <value>true</value> if version key fields have changed /// </summary> public bool VersionKeyFieldsChanged => !_original.VersionKeyPropertyNames.SequenceEqual(_altered.VersionKeyPropertyNames); /// <summary> /// Returns key fields that exists in both the original and altered type. Fields may have changed name or type. /// </summary> public IEnumerable<ExistingFieldInfo> ExistingKeyFields { get { var existingFields = from altered in _altered.Fields join original in _original.Fields on altered.Id equals original.Id where _altered.KeyPropertyNames.Contains(altered.Name) && _original.KeyPropertyNames.Contains(original.Name) select new ExistingFieldInfo(original, altered); return existingFields; } } private void ValidateTypeChanges() { if (this.OriginalTypeDataExists) { foreach (var existingField in this.ExistingFields) { if (existingField.OriginalField.StoreType.IsConvertibleTo(existingField.AlteredField.StoreType) == false) { throw new InvalidOperationException(string.Format("Data type change description is invalid. Requested convertion for field {0} is not allowed.", existingField.AlteredField.Name)); } } } foreach (string keyFieldName in this.AlteredType.KeyPropertyNames) { if (this.AlteredType.Fields[keyFieldName] == null) { throw new InvalidOperationException("Data type change description is invalid. Key field list contains an unknown field name."); } } foreach (string sortOrderFieldName in this.AlteredType.StoreSortOrderFieldNames) { if (this.AlteredType.Fields[sortOrderFieldName] == null) { throw new InvalidOperationException("Data type change description is invalid. Sort order field list contains an unknown field name."); } } } /// <exclude /> public class ExistingFieldInfo { private readonly DataFieldDescriptor _originalField; private DataFieldDescriptor _alteredField; internal ExistingFieldInfo(DataFieldDescriptor originalField, DataFieldDescriptor alteredField) { _originalField = originalField; _alteredField = alteredField; } /// <exclude /> public DataFieldDescriptor OriginalField => _originalField; /// <exclude /> public DataFieldDescriptor AlteredField { get { return _alteredField; } set { _alteredField = value; } } /// <exclude /> public bool AlteredFieldHasChanges { get { bool hasChanged = false; hasChanged |= ((_originalField.DefaultValue == null) != (_alteredField.DefaultValue == null)); if (_originalField.DefaultValue != null && _alteredField.DefaultValue != null) { hasChanged |= (_originalField.DefaultValue.CompareTo(_alteredField.DefaultValue) != 0); } hasChanged |= (_originalField.InstanceType != _alteredField.InstanceType); hasChanged |= (_originalField.IsNullable != _alteredField.IsNullable); hasChanged |= (_originalField.Name != _alteredField.Name); hasChanged |= (_originalField.StoreType.Serialize() != _alteredField.StoreType.Serialize()); return hasChanged; } } } } } ================================================ FILE: Composite/Data/DynamicTypes/DataTypeDescriptor.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Xml.Linq; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.Types; using Composite.Data.DynamicTypes.Configuration; using Composite.Data.DynamicTypes.Foundation; using Composite.Data.ProcessControlled; using Composite.Data.Types; namespace Composite.Data.DynamicTypes { /// <summary> /// Describes a data type in C1 CMS /// </summary> [DebuggerDisplay("Type name = {Namespace + '.' + Name}")] public class DataTypeDescriptor { private const string LogTitle = nameof(DataTypeDescriptor); private string _name; private Guid _dataTypeId; private string _namespace; private List<Type> _superInterfaces = new List<Type>(); private List<DataTypeAssociationDescriptor> _dataTypeAssociationDescriptors = new List<DataTypeAssociationDescriptor>(); private IReadOnlyCollection<DataTypeIndex> _indexes = new DataTypeIndex[0]; /// <summary> /// Instantiates an instance of <see cref="DataTypeDescriptor"/> with default settings. /// </summary> public DataTypeDescriptor() { this.Fields = new DataFieldDescriptorCollection(this); this.KeyPropertyNames = new DataFieldNameCollection(this.Fields, false, false, false); this.VersionKeyPropertyNames = new DataFieldNameCollection(this.Fields, false, false, false); this.StoreSortOrderFieldNames = new DataFieldNameCollection(this.Fields, true, false, false); this.IsCodeGenerated = false; this.DataScopes = new List<DataScopeIdentifier>(); } /// <summary> /// Instantiates an instance of <see cref="DataTypeDescriptor"/>. /// </summary> /// <param name="dataTypeId">The permanent Guid which should represent this data type.</param> /// <param name="dataTypeNamespace">Namespace of the type.</param> /// <param name="dataTypeName">Name of the type.</param> /// <param name="isCodeGenerated">True if this type is dynamically compiled.</param> public DataTypeDescriptor(Guid dataTypeId, string dataTypeNamespace, string dataTypeName, bool isCodeGenerated) : this() { this.DataTypeId = dataTypeId; this.Namespace = dataTypeNamespace; this.Name = dataTypeName; this.IsCodeGenerated = isCodeGenerated; } /// <summary> /// Instantiates an instance of <see cref="DataTypeDescriptor"/> with a custom Type Manager. /// </summary> /// <param name="dataTypeId">The permanent Guid which should represent this data type.</param> /// <param name="dataTypeNamespace">Namespace of the type.</param> /// <param name="dataTypeName">Name of the type.</param> /// <param name="typeManagerTypeName">If this data type has a custom type manager</param> public DataTypeDescriptor(Guid dataTypeId, string dataTypeNamespace, string dataTypeName, string typeManagerTypeName) : this() { this.DataTypeId = dataTypeId; this.Namespace = dataTypeNamespace; this.Name = dataTypeName; this.TypeManagerTypeName = typeManagerTypeName; this.IsCodeGenerated = false; } /// <summary> /// Instantiates an instance of <see cref="DataTypeDescriptor"/> with a custom Type Manager. /// </summary> /// <param name="dataTypeId">The permanent Guid which should represent this data type.</param> /// <param name="dataTypeNamespace">Namespace of the type.</param> /// <param name="dataTypeName">Name of the type.</param> /// <param name="typeManagerTypeName">If this data type has a custom type manager</param> /// <param name="isCodeGenerated">True if this type is dynamically compiled.</param> public DataTypeDescriptor(Guid dataTypeId, string dataTypeNamespace, string dataTypeName, string typeManagerTypeName, bool isCodeGenerated) : this() { this.DataTypeId = dataTypeId; this.Namespace = dataTypeNamespace; this.Name = dataTypeName; this.TypeManagerTypeName = typeManagerTypeName; this.IsCodeGenerated = isCodeGenerated; } /// <summary> /// The data types permant id. /// </summary> public Guid DataTypeId { get { return _dataTypeId; } set { if (value == Guid.Empty) throw new ArgumentException("DataTypeId must be a non-empty Guid"); _dataTypeId = value; } } /// <summary> /// Primary keys. /// </summary> public DataFieldNameCollection KeyPropertyNames { get; set; } /// <summary> /// Version keys, appear in the physical order but not included in data references. /// </summary> public DataFieldNameCollection VersionKeyPropertyNames { get; set; } /// <summary> /// Version keys, appear in the physical order but not included in data references. /// </summary> internal IEnumerable<string> PhysicalKeyPropertyNames => KeyPropertyNames.Concat(VersionKeyPropertyNames); /// <summary> /// Returns the CLT Type for this data type description. /// </summary> /// <returns></returns> public Type GetInterfaceType() { if (this.TypeManagerTypeName == null) { throw new InvalidOperationException("The TypeManagerTypeName has not been set"); } return DataTypeTypesManager.GetDataType(this); } /// <summary> /// Type name of the Type Manager responsible for this data type. /// </summary> public string TypeManagerTypeName { get; set; } /// <summary> /// A list of field names that the provider should use when physically storing data. /// Select ordering is not (necessarily) influenced by this setting. /// </summary> public DataFieldNameCollection StoreSortOrderFieldNames { get; set; } /// <summary>The fields (aka properties or columns) of the type.</summary> public DataFieldDescriptorCollection Fields { get; set; } /// <summary> /// Physical key fields. Note that the order of the fields is important. /// The physical key ensure that storage identity is unique across different versions of data with shared id. /// </summary> internal IEnumerable<DataFieldDescriptor> PhysicalKeyFields { get { Func<string, DataFieldDescriptor> getField = fieldName => this.Fields.Where(field => field.Name == fieldName) .SingleOrException("Missing a field '{0}'", "Multiple fields with name '{0}'", fieldName); return PhysicalKeyPropertyNames.Select(getField); } } /// <summary> /// Indexes. /// </summary> public IReadOnlyCollection<DataTypeIndex> Indexes { get { return _indexes; } set { Verify.That(value.Count(idx => idx.Clustered) < 2, "It is not allowed to have more than one clustered index"); _indexes = value; } } internal bool PrimaryKeyIsClusteredIndex { get { return !HasCustomPhysicalSortOrder && !Indexes.Any(i => i.Clustered); } } /// <summary>The short name of the type, without namespace and assembly info</summary> public string Name { get { return _name; } set { _name = NameValidation.ValidateName(value); } } /// <summary> /// The data types namespace /// </summary> public string Namespace { get { return _namespace; } set { _namespace = NameValidation.ValidateNamespace(value); } } /// <summary> /// The data types title /// </summary> public string Title { get; set; } /// <summary> /// The name of field to use when labeling data of this type. /// </summary> public string LabelFieldName { get; set; } /// <summary> /// The internal url name /// </summary> public string InternalUrlPrefix { get; set; } /// <summary> /// True if the interface code for this type is created via code generation. False for statically compiled types. /// </summary> public bool IsCodeGenerated { get; private set; } /// <summary> /// When <value>true</value> data of this type may be cached. /// </summary> public bool Cachable { get; internal set; } /// <summary> /// When <value>true</value> the data of this type is searchable. /// </summary> public bool Searchable { get; internal set; } /// <summary> /// When true this type has a physical sortorder specified. /// </summary> public bool HasCustomPhysicalSortOrder { get { if (this.StoreSortOrderFieldNames.Count == 0) return false; if (this.StoreSortOrderFieldNames.Count != this.KeyPropertyNames.Count) return true; for (int i = 0; i < this.StoreSortOrderFieldNames.Count; i++) { if (this.StoreSortOrderFieldNames[i] != this.KeyPropertyNames[i]) return true; } return false; } } /// <summary> /// The data scopes this data type exist in. Typically always "public". Also "administrated" if this type supports publishing. /// </summary> public List<DataScopeIdentifier> DataScopes { get; set; } /// <summary> /// When true data can be localized. /// </summary> public bool Localizeable => SuperInterfaces.Contains(typeof(ILocalizedControlled)); /// <summary> /// Type name for custom handler to use when building new instances of the data type. /// </summary> public string BuildNewHandlerTypeName { get; set; } /// <summary> /// Adds an interface the data type should inherit from /// </summary> /// <param name="interfaceType"></param> public void AddSuperInterface(Type interfaceType) { AddSuperInterface(interfaceType, true); } /// <summary> /// Adds an interface the data type should inherit from /// </summary> /// <param name="interfaceType"></param> /// <param name="addInheritedFields"></param> internal void AddSuperInterface(Type interfaceType, bool addInheritedFields) { if (_superInterfaces.Contains(interfaceType) || interfaceType == typeof (IData)) { return; } _superInterfaces.Add(interfaceType); if (addInheritedFields) { foreach (PropertyInfo propertyInfo in interfaceType.GetProperties()) { if (propertyInfo.Name == nameof(IPageData.PageId) && interfaceType == typeof (IPageData)) { continue; } DataFieldDescriptor dataFieldDescriptor = ReflectionBasedDescriptorBuilder.BuildFieldDescriptor(propertyInfo, true); this.Fields.Add(dataFieldDescriptor); } } foreach (string propertyName in interfaceType.GetKeyPropertyNames()) { if (KeyPropertyNames.Contains(propertyName)) continue; PropertyInfo property = ReflectionBasedDescriptorBuilder.FindProperty(interfaceType, propertyName); if (DynamicTypeReflectionFacade.IsKeyField(property)) { this.KeyPropertyNames.Add(propertyName, false); } } foreach (var dataScopeIdentifier in DynamicTypeReflectionFacade.GetDataScopes(interfaceType)) { if (!this.DataScopes.Contains(dataScopeIdentifier)) { this.DataScopes.Add(dataScopeIdentifier); } } var superInterfaces = interfaceType.GetInterfaces().Where(t => typeof (IData).IsAssignableFrom(t)); foreach (Type superSuperInterfaceType in superInterfaces) { AddSuperInterface(superSuperInterfaceType, addInheritedFields); } } /// <summary> /// Removes a super interface /// </summary> /// <param name="interfaceType">Type to remove</param> public void RemoveSuperInterface(Type interfaceType) { if (interfaceType == typeof(IData)) { return; } if (_superInterfaces.Contains(interfaceType)) { _superInterfaces.Remove(interfaceType); } foreach (PropertyInfo propertyInfo in interfaceType.GetProperties()) { var dataFieldDescriptor = ReflectionBasedDescriptorBuilder.BuildFieldDescriptor(propertyInfo, true); if (this.Fields.Contains(dataFieldDescriptor)) { this.Fields.Remove(dataFieldDescriptor); } if (DynamicTypeReflectionFacade.IsKeyField(propertyInfo) && this.KeyPropertyNames.Contains(propertyInfo.Name)) { this.KeyPropertyNames.Remove(propertyInfo.Name); } } foreach (var dataScopeIdentifier in DynamicTypeReflectionFacade.GetDataScopes(interfaceType)) { if (this.DataScopes.Contains(dataScopeIdentifier)) { this.DataScopes.Remove(dataScopeIdentifier); } } var superInterfaces = interfaceType.GetInterfaces().Where(t => typeof (IData).IsAssignableFrom(t)); foreach (Type superInterfaceType in superInterfaces) { RemoveSuperInterface(superInterfaceType); } } /// <summary> /// All interfaces this data type inherit from /// </summary> public IEnumerable<Type> SuperInterfaces => _superInterfaces; /// <summary> /// Attached a associated to another data type, like page meta data or page folder data. /// </summary> public List<DataTypeAssociationDescriptor> DataAssociations { get { return _dataTypeAssociationDescriptors; } set { if (value == null) throw new ArgumentNullException(); _dataTypeAssociationDescriptors = value; } } /// <summary> /// True when the data type is associated to C1 CMS pages as an agregation /// </summary> public bool IsPageFolderDataType { get { return this.DataAssociations.Any(f => f.AssociatedInterfaceType == typeof(IPage) && f.AssociationType == DataAssociationType.Aggregation); } } /// <summary> /// True when the data type is associated to C1 CMS pages as an composition /// </summary> public bool IsPageMetaDataType { get { return this.DataAssociations.Any(f => f.AssociatedInterfaceType == typeof(IPage) && f.AssociationType == DataAssociationType.Composition); } } /// <summary> /// Resets the list of interfaces this data type inherit from /// </summary> /// <param name="superInterfaces"></param> internal void SetSuperInterfaces(List<Type> superInterfaces) { _superInterfaces = superInterfaces; } /// <summary> /// Validate the data type description or throw an exception. /// </summary> public void Validate() { try { if (this.DataTypeId == Guid.Empty) throw new InvalidOperationException("The type descriptor property DataTypeId can not be empty"); if (string.IsNullOrEmpty(this.Namespace)) throw new InvalidOperationException("The type descriptor property Namespace can not be empty"); if (string.IsNullOrEmpty(this.Name)) throw new InvalidOperationException("The type descriptor property Name can not be empty"); if (string.IsNullOrEmpty(this.TypeManagerTypeName)) throw new InvalidOperationException("The type descriptor property TypeManagerTypeName can not be empty"); if (this.Fields.Count == 0) throw new InvalidOperationException("The type descriptors Fields collection may not be empty"); if (this.KeyPropertyNames.Count == 0) throw new InvalidOperationException("The type descriptors KeyFieldNames collection may not be empty"); if (this.DataScopes.Count == 0) throw new InvalidOperationException("The DataScopes list containing the list of data scopes this type must support can not be empty. Please provide at least one data scopes."); if (this.DataScopes.Select(f => f.Name).Distinct().Count() != this.DataScopes.Count) throw new InvalidOperationException("The DataScopes list contains redundant data scopes"); this.KeyPropertyNames.ValidateMembers(); this.StoreSortOrderFieldNames.ValidateMembers(); if (this.LabelFieldName != null) { if (!this.Fields.Any(f => f.Name == this.LabelFieldName)) { throw new InvalidOperationException($"The label field name '{this.LabelFieldName}' is not an existing field"); } } int distinctForeignKeyPropertyNames = (from assDec in this.DataAssociations select assDec.ForeignKeyPropertyName).Distinct().Count(); if (distinctForeignKeyPropertyNames != this.DataAssociations.Count) { throw new InvalidOperationException("Two or more data associations are using the same foreign key field"); } int distinctAssociatedInterfaceType = (from assDec in this.DataAssociations select assDec.AssociatedInterfaceType).Distinct().Count(); if (distinctAssociatedInterfaceType != this.DataAssociations.Count) { throw new InvalidOperationException("Two or more data associations are associated to the same interface type"); } } catch (Exception ex) { string typeName = string.IsNullOrEmpty(this.TypeManagerTypeName) ? this.Name : this.TypeManagerTypeName; throw new InvalidOperationException($"Failed to validate data type description for '{typeName}'.", ex); } } /// <summary> /// Clones the data type description. /// </summary> /// <returns>A clone</returns> public DataTypeDescriptor Clone() { var dataTypeDescriptor = new DataTypeDescriptor(this.DataTypeId, this.Namespace, this.Name, this.TypeManagerTypeName, this.IsCodeGenerated) { Title = this.Title, BuildNewHandlerTypeName = this.BuildNewHandlerTypeName, LabelFieldName = this.LabelFieldName, InternalUrlPrefix = this.InternalUrlPrefix, Cachable = this.Cachable, Searchable = this.Searchable }; foreach (DataTypeAssociationDescriptor dataTypeAssociationDescriptor in this.DataAssociations) { dataTypeDescriptor.DataAssociations.Add(dataTypeAssociationDescriptor.Clone()); } dataTypeDescriptor.DataScopes = new List<DataScopeIdentifier>(this.DataScopes); foreach (DataFieldDescriptor dataFieldDescriptor in this.Fields) { if (!dataFieldDescriptor.Inherited) { dataTypeDescriptor.Fields.Add(dataFieldDescriptor.Clone()); } } foreach (string keyPropertyName in this.KeyPropertyNames) { dataTypeDescriptor.KeyPropertyNames.Add(keyPropertyName, false); } foreach (string storeSortOrderFieldNames in this.StoreSortOrderFieldNames) { dataTypeDescriptor.StoreSortOrderFieldNames.Add(storeSortOrderFieldNames, false); } foreach (Type superInterface in this.SuperInterfaces) { dataTypeDescriptor.AddSuperInterface(superInterface); } return dataTypeDescriptor; } /// <summary> /// Serialize the data type description to XML /// </summary> /// <returns>Serialized data type descriptor</returns> public XElement ToXml() { var element = new XElement("DataTypeDescriptor", new XAttribute("dataTypeId", this.DataTypeId), new XAttribute("name", this.Name), new XAttribute("namespace", this.Namespace), this.Title != null ? new XAttribute("title", this.Title) : null, new XAttribute("isCodeGenerated", this.IsCodeGenerated), new XAttribute("cachable", this.Cachable), new XAttribute("searchable", this.Searchable), this.LabelFieldName != null ? new XAttribute("labelFieldName", this.LabelFieldName) : null, !string.IsNullOrEmpty(this.InternalUrlPrefix) ? new XAttribute("internalUrlPrefix", this.InternalUrlPrefix) : null, this.TypeManagerTypeName != null ? new XAttribute("typeManagerTypeName", this.TypeManagerTypeName) : null, !string.IsNullOrEmpty(this.BuildNewHandlerTypeName) ? new XAttribute("buildNewHandlerTypeName", this.BuildNewHandlerTypeName) : null); element.Add(new[] { new XElement("DataAssociations", DataAssociations.Select(da => da.ToXml())), new XElement("DataScopes", DataScopes.Select(dsi => new XElement("DataScopeIdentifier", new XAttribute("name", dsi)))), new XElement("KeyPropertyNames", KeyPropertyNames.Select(name => new XElement("KeyPropertyName", new XAttribute("name", name)))), VersionKeyPropertyNames.Any() ? new XElement("VersionKeyPropertyNames", VersionKeyPropertyNames.Select(name => new XElement("VersionKeyPropertyName", new XAttribute("name", name)))) : null, new XElement("SuperInterfaces", SuperInterfaces.Select(su => new XElement("SuperInterface", new XAttribute("type", TypeManager.SerializeType(su))))), new XElement("Fields", Fields.Select(f => f.ToXml())) }); if (Indexes.Any()) { element.Add(new XElement("Indexes", Indexes.Select(i => i.ToXml()))); } return element; } /// <summary> /// Deserializes a data type descriptor /// </summary> /// <param name="element">A serialized (XML) data type descriptor</param> /// <returns>De-serialized data type descriptor</returns> public static DataTypeDescriptor FromXml(XElement element) { return FromXml(element, true); } internal static DataTypeDescriptor FromXml(XElement element, bool inheritedFieldsIncluded) { Verify.ArgumentNotNull(element, "element"); if (element.Name != "DataTypeDescriptor") throw new ArgumentException("The xml is not correctly formatted."); Guid dataTypeId = (Guid) element.GetRequiredAttribute("dataTypeId"); string name = element.GetRequiredAttributeValue("name"); string @namespace = element.GetRequiredAttributeValue("namespace"); bool isCodeGenerated = (bool) element.GetRequiredAttribute("isCodeGenerated"); XAttribute cachableAttribute = element.Attribute("cachable"); XAttribute searchableAttribute = element.Attribute("searchable"); XAttribute buildNewHandlerTypeNameAttribute = element.Attribute("buildNewHandlerTypeName"); XElement dataAssociationsElement = element.GetRequiredElement("DataAssociations"); XElement dataScopesElement = element.GetRequiredElement("DataScopes"); XElement keyPropertyNamesElement = element.GetRequiredElement("KeyPropertyNames"); XElement versionKeyPropertyNamesElement = element.Element("VersionKeyPropertyNames"); XElement superInterfacesElement = element.GetRequiredElement("SuperInterfaces"); XElement fieldsElement = element.GetRequiredElement("Fields"); XElement indexesElement = element.Element("Indexes"); XAttribute titleAttribute = element.Attribute("title"); XAttribute labelFieldNameAttribute = element.Attribute("labelFieldName"); XAttribute internalUrlPrefixAttribute = element.Attribute("internalUrlPrefix"); string typeManagerTypeName = (string) element.Attribute("typeManagerTypeName"); bool cachable = cachableAttribute != null && (bool)cachableAttribute; bool searchable = searchableAttribute != null && (bool)searchableAttribute; var dataTypeDescriptor = new DataTypeDescriptor(dataTypeId, @namespace, name, isCodeGenerated) { Cachable = cachable, Searchable = searchable }; if (titleAttribute != null) dataTypeDescriptor.Title = titleAttribute.Value; if (labelFieldNameAttribute != null) dataTypeDescriptor.LabelFieldName = labelFieldNameAttribute.Value; if (internalUrlPrefixAttribute != null) dataTypeDescriptor.InternalUrlPrefix = internalUrlPrefixAttribute.Value; if (typeManagerTypeName != null) { typeManagerTypeName = TypeManager.FixLegasyTypeName(typeManagerTypeName); dataTypeDescriptor.TypeManagerTypeName = typeManagerTypeName; } if (buildNewHandlerTypeNameAttribute != null) dataTypeDescriptor.BuildNewHandlerTypeName = buildNewHandlerTypeNameAttribute.Value; foreach (XElement elm in dataAssociationsElement.Elements()) { var dataTypeAssociationDescriptor = DataTypeAssociationDescriptor.FromXml(elm); dataTypeDescriptor.DataAssociations.Add(dataTypeAssociationDescriptor); } foreach (XElement elm in dataScopesElement.Elements("DataScopeIdentifier")) { string dataScopeName = elm.GetRequiredAttributeValue("name"); if (DataScopeIdentifier.IsLegasyDataScope(dataScopeName)) { Log.LogWarning(LogTitle, "Ignored legacy data scope '{0}' on type '{1}.{2}' while deserializing DataTypeDescriptor. The '{0}' data scope is no longer supported.".FormatWith(dataScopeName, @namespace, name)); continue; } DataScopeIdentifier dataScopeIdentifier = DataScopeIdentifier.Deserialize(dataScopeName); dataTypeDescriptor.DataScopes.Add(dataScopeIdentifier); } foreach (XElement elm in superInterfacesElement.Elements("SuperInterface")) { string superInterfaceTypeName = elm.GetRequiredAttributeValue("type"); if (superInterfaceTypeName.StartsWith("Composite.Data.ProcessControlled.IDeleteControlled")) { Log.LogWarning(LogTitle, $"Ignored legacy super interface '{superInterfaceTypeName}' on type '{@namespace}.{name}' while deserializing DataTypeDescriptor. This super interface is no longer supported."); continue; } Type superInterface; try { superInterface = TypeManager.GetType(superInterfaceTypeName); } catch (Exception ex) { throw XmlConfigurationExtensionMethods.GetConfigurationException($"Failed to load super interface '{superInterfaceTypeName}'", ex, elm); } dataTypeDescriptor.AddSuperInterface(superInterface, !inheritedFieldsIncluded); } foreach (XElement elm in fieldsElement.Elements()) { var dataFieldDescriptor = DataFieldDescriptor.FromXml(elm); try { dataTypeDescriptor.Fields.Add(dataFieldDescriptor); } catch (Exception ex) { throw XmlConfigurationExtensionMethods.GetConfigurationException("Failed to add a data field: " + ex.Message, ex, elm); } } foreach (XElement elm in keyPropertyNamesElement.Elements("KeyPropertyName")) { var propertyName = elm.GetRequiredAttributeValue("name"); bool isDefinedOnSuperInterface = dataTypeDescriptor.SuperInterfaces.Any(f => f.GetProperty(propertyName) != null); if (!isDefinedOnSuperInterface) { dataTypeDescriptor.KeyPropertyNames.Add(propertyName); } } if (versionKeyPropertyNamesElement != null) { foreach (XElement elm in versionKeyPropertyNamesElement.Elements("VersionKeyPropertyName")) { var propertyName = elm.GetRequiredAttributeValue("name"); dataTypeDescriptor.VersionKeyPropertyNames.Add(propertyName); } } if (indexesElement != null) { dataTypeDescriptor.Indexes = indexesElement.Elements("Index").Select(DataTypeIndex.FromXml).ToList(); } // Loading field rendering profiles for static data types if (!isCodeGenerated && typeManagerTypeName != null) { Type type = Type.GetType(typeManagerTypeName); if (type != null) { foreach (var fieldDescriptor in dataTypeDescriptor.Fields) { var property = type.GetProperty(fieldDescriptor.Name); if (property != null) { var formRenderingProfile = DynamicTypeReflectionFacade.GetFormRenderingProfile(property); if (formRenderingProfile != null) { fieldDescriptor.FormRenderingProfile = formRenderingProfile; } } } } } return dataTypeDescriptor; } /// <exclude /> public override int GetHashCode() { return this.DataTypeId.GetHashCode(); } /// <exclude /> public override bool Equals(object obj) { return Equals(obj as DataTypeDescriptor); } /// <exclude /> public bool Equals(DataTypeDescriptor dataTypeDescriptor) { return dataTypeDescriptor != null && dataTypeDescriptor.DataTypeId == this.DataTypeId; } /// <exclude /> public override string ToString() { if (this.Namespace == "") { return this.Name; } return this.Namespace + "." + this.Name; } } /// <summary> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] public static class DataTypeDescriptorExtensions { /// <summary> /// This method returns the full interface name. F.e. "Composite.Data.Types.IPage" /// </summary> /// <param name="dataTypeDescriptor"></param> /// <returns></returns> public static string GetFullInterfaceName(this DataTypeDescriptor dataTypeDescriptor) { return dataTypeDescriptor.Namespace + "." + dataTypeDescriptor.Name; } /// <summary> /// This method will return false if the type is not code generated and does exists /// </summary> /// <param name="dataTypeDescriptor"></param> /// <returns></returns> public static bool ValidateRuntimeType(this DataTypeDescriptor dataTypeDescriptor) { Verify.ArgumentNotNull(dataTypeDescriptor, "dataTypeDescriptor"); if (dataTypeDescriptor.IsCodeGenerated) return true; Type dataType = TypeManager.TryGetType(dataTypeDescriptor.TypeManagerTypeName); return dataType != null; } } } ================================================ FILE: Composite/Data/DynamicTypes/DataTypeDescriptorFormsHelper.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Xml.Linq; using Composite.C1Console.Forms; using Composite.C1Console.Security; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; using Composite.Core.Types; using Composite.Core.Xml; using Composite.Data.DynamicTypes.Foundation; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.PublishScheduling; using Composite.Data.Types; using Composite.Data.Validation; using Composite.Data.Validation.ClientValidationRules; using Composite.Functions; using Composite.Functions.Foundation; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Plugins_GeneratedDataTypesElementProvider; namespace Composite.Data.DynamicTypes { /// <summary> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] public sealed class DataTypeDescriptorFormsHelper { private readonly DataTypeDescriptor _dataTypeDescriptor; private readonly List<string> _readOnlyFields = new List<string>(); private readonly bool _showPublicationStatusSelector; private readonly string _bindingNamesPrefix; private XDocument _customFormDefinition; private bool _customFormDefinitionInitialized; private string _generatedForm; private XElement _bindingsXml; private XElement _panelXml; private const string PublicationStatusPostFixBindingName = "PublicationStatus"; private const string PublicationStatusOptionsPostFixBindingName = "PublicationStatusOptions"; private static readonly XElement CmsFormElementTemplate; private static readonly XElement CmsBindingsElementTemplate; private static readonly XElement CmsLayoutElementTemplate; /// <exclude /> static DataTypeDescriptorFormsHelper() { CmsFormElementTemplate = XElement.Parse(string.Format(@"<cms:{0} xmlns:cms=""{1}"" xmlns=""{2}"" xmlns:ff=""{3}"" xmlns:f=""{4}"" />", FormKeyTagNames.FormDefinition, Namespaces.BindingForms10, Namespaces.BindingFormsStdUiControls10, Namespaces.BindingFormsStdFuncLib10, FunctionTreeConfigurationNames.NamespaceName)); CmsBindingsElementTemplate = new XElement(Namespaces.BindingForms10 + FormKeyTagNames.Bindings); CmsLayoutElementTemplate = new XElement(Namespaces.BindingForms10 + FormKeyTagNames.Layout); } /// <summary> /// Creates an instance of <see cref="DataTypeDescriptorFormsHelper"/> /// </summary> /// <param name="dataTypeDescriptor"></param> /// <param name="showPublicationStatusSelector"></param> /// <param name="entityToken">EntityToken is used for resolving to which publication states, current user has access to.</param> public DataTypeDescriptorFormsHelper(DataTypeDescriptor dataTypeDescriptor, bool showPublicationStatusSelector, EntityToken entityToken) : this(dataTypeDescriptor, null, showPublicationStatusSelector, entityToken) { } /// <exclude /> public DataTypeDescriptorFormsHelper(DataTypeDescriptor dataTypeDescriptor) : this(dataTypeDescriptor, null, false, null) { } /// <exclude /> public DataTypeDescriptorFormsHelper(DataTypeDescriptor dataTypeDescriptor, string bindingNamesPrefix) : this(dataTypeDescriptor, bindingNamesPrefix, false, null) { } /// <exclude /> public DataTypeDescriptorFormsHelper(DataTypeDescriptor dataTypeDescriptor, string bindingNamesPrefix, bool showPublicationStatusSelector, EntityToken entityToken) { if (dataTypeDescriptor == null) throw new ArgumentNullException("dataTypeDescriptor"); _dataTypeDescriptor = dataTypeDescriptor; _bindingNamesPrefix = bindingNamesPrefix; _showPublicationStatusSelector = showPublicationStatusSelector; EntityToken = entityToken; LayoutIconHandle = null; } /// <exclude /> public DataTypeDescriptor DataTypeDescriptor { get { return _dataTypeDescriptor; } } /// <exclude /> public XDocument CustomFormDefinition { get { if (!_customFormDefinitionInitialized) { _customFormDefinition = DynamicTypesCustomFormFacade.GetCustomFormMarkup(_dataTypeDescriptor); _customFormDefinitionInitialized = true; } return _customFormDefinition; } set { _customFormDefinition = value; _customFormDefinitionInitialized = true; } } /// <exclude /> public void AddReadOnlyField(string fieldName) { _readOnlyFields.Add(fieldName); } /// <exclude /> public void AddReadOnlyFields(IEnumerable<string> fieldNames) { _readOnlyFields.AddRange(fieldNames); } /// <exclude /> public string GetForm() { if (_generatedForm == null) { GenerateForm(); } return _generatedForm; } /// <exclude /> public XElement BindingXml { get { if (_bindingsXml == null) { GenerateForm(); } return _bindingsXml; } } /// <exclude /> public XElement PanelXml { get { if (_panelXml == null) { GenerateForm(); } return _panelXml; } } /// <exclude /> public string BindingNamesPrefix { get { return _bindingNamesPrefix; } } /// <exclude /> public void UpdateWithNewBindings(Dictionary<string, object> bindings) { var newBindings = GetNewBindings(); foreach (var kvp in newBindings) { bindings[kvp.Key] = kvp.Value; } } private static object GetDefaultValue(Type type) { if (type == typeof(int)) return 0; if (type == typeof(decimal)) return (decimal)0.0; if (type == typeof(DateTime)) return DateTime.Now; if (type == typeof(bool)) return false; if (type == typeof(Guid)) return Guid.Empty; return null; } /// <exclude /> public Dictionary<string, object> GetNewBindings() { var newBindings = new Dictionary<string, object>(); foreach (var fieldDescriptor in _dataTypeDescriptor.Fields) { var fieldType = fieldDescriptor.InstanceType; object value; if (fieldDescriptor.IsNullable || (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Nullable<>))) { value = null; } else { if (fieldType == typeof(string) && fieldDescriptor.ForeignKeyReferenceTypeName == null) { value = ""; } else { value = GetDefaultValue(fieldType); } } newBindings.Add(GetBindingName(fieldDescriptor), value); } if (_showPublicationStatusSelector && _dataTypeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled))) { newBindings[PublicationStatusBindingName] = GenericPublishProcessController.Draft; newBindings.Add(PublicationStatusOptionsBindingName, GetAvailablePublishingFlowTransitions(EntityToken)); } return newBindings; } private static Dictionary<string, string> GetAvailablePublishingFlowTransitions(EntityToken entityToken) { if(UserValidationFacade.IsLoggedIn()) { var transitionNames = new Dictionary<string, string> { {GenericPublishProcessController.Draft, LocalizationFiles.Composite_Management.PublishingStatus_draft}, {GenericPublishProcessController.AwaitingApproval, LocalizationFiles.Composite_Management.PublishingStatus_awaitingApproval} }; var username = UserValidationFacade.GetUsername(); var userPermissionDefinitions = PermissionTypeFacade.GetUserPermissionDefinitions(username); var userGroupPermissionDefinition = PermissionTypeFacade.GetUserGroupPermissionDefinitions(username); var currentPermissionTypes = PermissionTypeFacade.GetCurrentPermissionTypes(UserValidationFacade.GetUserToken(), entityToken, userPermissionDefinitions, userGroupPermissionDefinition); foreach (var permissionType in currentPermissionTypes) { if (GenericPublishProcessController.AwaitingPublicationActionPermissionType.Contains(permissionType)) { transitionNames.Add(GenericPublishProcessController.AwaitingPublication, LocalizationFiles.Composite_Management.PublishingStatus_awaitingPublication); break; } } return transitionNames; } else { return new Dictionary<string, string>(); } } /// <exclude /> public void UpdateWithBindings(IData dataObject, Dictionary<string, object> bindings) { var newBindings = GetBindings(dataObject); foreach (var kvp in newBindings) { bindings[kvp.Key] = kvp.Value; } } /// <exclude /> public Dictionary<string, object> GetBindings(IData dataObject) { return GetBindings(dataObject, false); } /// <exclude /> public Dictionary<string, object> GetBindings(IData dataObject, bool allowMandatoryNonDefaultingProperties) { if (dataObject == null) throw new ArgumentNullException("dataObject"); var bindings = new Dictionary<string, object>(); foreach (var fieldDescriptor in _dataTypeDescriptor.Fields) { var propertyInfo = dataObject.GetType().GetProperty(fieldDescriptor.Name); if (propertyInfo.CanRead) { var value = propertyInfo.GetGetMethod().Invoke(dataObject, null); if (value == null && !fieldDescriptor.IsNullable) { if (fieldDescriptor.IsNullable) { // Ignore, null is allowed } else if (fieldDescriptor.InstanceType.IsGenericType && fieldDescriptor.InstanceType.GetGenericTypeDefinition() == typeof(Nullable<>)) { // Ignore, null is allowed } else if (allowMandatoryNonDefaultingProperties) { if (propertyInfo.PropertyType == typeof(string) && fieldDescriptor.ForeignKeyReferenceTypeName == null) //FK fields stay NULL { value = ""; } else { value = GetDefaultValue(propertyInfo.PropertyType); } } else { throw new InvalidOperationException(string.Format("Field '{0}' on type '{1}' is null, does not allow null and does not have a default value", fieldDescriptor.Name, _dataTypeDescriptor.TypeManagerTypeName)); } } bindings.Add(GetBindingName(fieldDescriptor), value); } } if (_showPublicationStatusSelector && _dataTypeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled))) { bindings[PublicationStatusBindingName] = ((IPublishControlled)dataObject).PublicationStatus; bindings.Add(PublicationStatusOptionsBindingName, GetAvailablePublishingFlowTransitions(EntityToken)); var interfaceType = dataObject.DataSourceId.InterfaceType; var stringKey = dataObject.GetUniqueKey().ToString(); var locale = dataObject.DataSourceId.LocaleScope.Name; var existingPublishSchedule = PublishScheduleHelper.GetPublishSchedule(interfaceType, stringKey, locale); bindings.Add("PublishDate", existingPublishSchedule?.PublishDate); var existingUnpublishSchedule = PublishScheduleHelper.GetUnpublishSchedule(interfaceType, stringKey, locale); bindings.Add("UnpublishDate", existingUnpublishSchedule?.UnpublishDate); } return bindings; } /// <exclude /> public Dictionary<string, List<ClientValidationRule>> GetBindingsValidationRules(IData data) { Verify.ArgumentNotNull(data, "data"); var result = new Dictionary<string, List<ClientValidationRule>>(); foreach (var fieldDescriptor in _dataTypeDescriptor.Fields) { var rules = ClientValidationRuleFacade.GetClientValidationRules(data, fieldDescriptor.Name); result.Add(GetBindingName(fieldDescriptor), rules); } return result; } /// <exclude /> public Dictionary<string, string> BindingsToObject(Dictionary<string, object> bindings, IData dataObject) { var errorMessages = new Dictionary<string, string>(); foreach (var fieldDescriptor in _dataTypeDescriptor.Fields) { if (_readOnlyFields.Contains(fieldDescriptor.Name)) { continue; } var bindingName = GetBindingName(fieldDescriptor); if (!bindings.ContainsKey(bindingName)) { Verify.That(fieldDescriptor.IsNullable, "Missing value for field '{0}'", fieldDescriptor.Name); continue; } var propertyInfo = dataObject.GetType().GetProperty(fieldDescriptor.Name); if (propertyInfo.CanWrite) { var newValue = bindings[bindingName]; if (newValue is string && (newValue as string) == "" && IsNullableStringReference(propertyInfo)) { newValue = null; } try { newValue = ValueTypeConverter.Convert(newValue, propertyInfo.PropertyType); propertyInfo.GetSetMethod().Invoke(dataObject, new[] { newValue }); } catch (Exception ex) { errorMessages.Add(bindingName, ex.Message); } } } if (_showPublicationStatusSelector && _dataTypeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled))) { var publishControlled = dataObject as IPublishControlled; publishControlled.PublicationStatus = (string)bindings[PublicationStatusBindingName]; } if (errorMessages.Count > 0) { return errorMessages; } return null; } private static bool IsNullableStringReference(PropertyInfo propertyInfo) { var dataType = propertyInfo.DeclaringType; return DataAttributeFacade.GetDataReferenceProperties(dataType) .Any(foreignKey => foreignKey.SourcePropertyName == propertyInfo.Name && foreignKey.IsNullableString); } /// <exclude /> public Dictionary<string, string> ObjectToBindings(IData dataObject, Dictionary<string, object> bindings) { var errorMessages = new Dictionary<string, string>(); foreach (var fieldDescriptor in _dataTypeDescriptor.Fields) { var bindingName = GetBindingName(fieldDescriptor); if (bindings.ContainsKey(bindingName)) { var propertyInfo = dataObject.GetType().GetProperty(fieldDescriptor.Name); Verify.IsNotNull(propertyInfo, "Missing property type '{0}' does not contain property '{1}'", dataObject.GetType(), fieldDescriptor.Name); if (propertyInfo.CanRead) { var newValue = propertyInfo.GetValue(dataObject, null); if (newValue == null && !fieldDescriptor.IsNullable) { var fieldType = fieldDescriptor.InstanceType; if (fieldType == typeof(string) && fieldDescriptor.ForeignKeyReferenceTypeName == null) { newValue = ""; } else { newValue = GetDefaultValue(fieldType); } } try { bindings[bindingName] = newValue; } catch (Exception ex) { errorMessages.Add(bindingName, ex.Message); } } } } if (_showPublicationStatusSelector && _dataTypeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled))) { var publishControlled = dataObject as IPublishControlled; bindings[PublicationStatusBindingName] = publishControlled.PublicationStatus; } return errorMessages.Count > 0 ? errorMessages : null; } /// <exclude /> public string LayoutIconHandle { get; set; } /// <exclude /> public static XNamespace MainNamespace => Namespaces.BindingFormsStdUiControls10; /// <exclude /> public static XNamespace CmsNamespace => Namespaces.BindingForms10; /// <exclude /> public static XNamespace FunctionNamespace => Namespaces.BindingFormsStdFuncLib10; /// <exclude /> public string FieldGroupLabel { get; set; } /// <exclude /> public string LayoutLabel { get; set; } private Type GetFieldBindingType(DataFieldDescriptor fieldDescriptor) { var bindingType = fieldDescriptor.InstanceType; // Nullable<T> handling. Allowed types: Nullable<Guid>, Nullable<int>, Nullable<decimal> if (bindingType != typeof(Guid?) && bindingType != typeof(int?) && bindingType != typeof(decimal?) && bindingType.IsGenericType && bindingType.GetGenericTypeDefinition() == typeof(Nullable<>)) { return bindingType.GetGenericArguments()[0]; } return bindingType; } private EntityToken EntityToken { get; set; } private void GenerateForm() { var fieldNameToBindingNameMapper = new Dictionary<string, string>(); _bindingsXml = new XElement(CmsBindingsElementTemplate); var layout = new XElement(CmsLayoutElementTemplate); if (!string.IsNullOrEmpty(LayoutIconHandle)) { layout.Add(new XAttribute("iconhandle", LayoutIconHandle)); } // Add a read binding as the layout label if (!string.IsNullOrEmpty(LayoutLabel)) { var labelAttribute = new XAttribute("label", LayoutLabel); layout.Add(labelAttribute); } else if (!string.IsNullOrEmpty(_dataTypeDescriptor.LabelFieldName)) { layout.Add((new XElement(CmsNamespace + "layout.label", new XElement(CmsNamespace + "read", new XAttribute("source", _dataTypeDescriptor.LabelFieldName))))); } _panelXml = new XElement(MainNamespace + "FieldGroup"); string formLabel = !string.IsNullOrEmpty(FieldGroupLabel) ? FieldGroupLabel : _dataTypeDescriptor.Title; if (!string.IsNullOrEmpty(formLabel)) { _panelXml.Add(new XAttribute("Label", formLabel)); } layout.Add(_panelXml); foreach (var fieldDescriptor in _dataTypeDescriptor.Fields) { var bindingType = GetFieldBindingType(fieldDescriptor); var bindingName = GetBindingName(fieldDescriptor); fieldNameToBindingNameMapper.Add(fieldDescriptor.Name, bindingName); var binding = new XElement(CmsNamespace + FormKeyTagNames.Binding, new XAttribute("name", bindingName), new XAttribute("type", bindingType)); if (fieldDescriptor.IsNullable) { binding.Add(new XAttribute("optional", "true")); } _bindingsXml.Add(binding); if (!_readOnlyFields.Contains(fieldDescriptor.Name)) { XElement widgetFunctionMarkup; var label = fieldDescriptor.FormRenderingProfile.Label; if (label.IsNullOrEmpty()) { label = fieldDescriptor.Name; } var helptext = fieldDescriptor.FormRenderingProfile.HelpText ?? ""; if (!string.IsNullOrEmpty(fieldDescriptor.FormRenderingProfile.WidgetFunctionMarkup)) { widgetFunctionMarkup = XElement.Parse(fieldDescriptor.FormRenderingProfile.WidgetFunctionMarkup); } else if (!DataTypeDescriptor.IsCodeGenerated && fieldDescriptor.FormRenderingProfile.WidgetFunctionMarkup == null) { // Auto generating a widget for not code generated data types Type fieldType; if (!fieldDescriptor.ForeignKeyReferenceTypeName.IsNullOrEmpty()) { Type foreignKeyType; try { foreignKeyType = Type.GetType(fieldDescriptor.ForeignKeyReferenceTypeName, true); } catch (Exception ex) { throw new InvalidOperationException("Failed to get referenced foreign key type '{0}'".FormatWith(fieldDescriptor.ForeignKeyReferenceTypeName), ex); } var referenceTemplateType = fieldDescriptor.IsNullable ? typeof(NullableDataReference<>) : typeof(DataReference<>); fieldType = referenceTemplateType.MakeGenericType(foreignKeyType); } else { fieldType = fieldDescriptor.InstanceType; } var widgetFunctionProvider = StandardWidgetFunctions.GetDefaultWidgetFunctionProviderByType(fieldType); if (widgetFunctionProvider != null) { widgetFunctionMarkup = widgetFunctionProvider.SerializedWidgetFunction; } else { continue; } } else { continue; } var widgetRuntimeTreeNode = (WidgetFunctionRuntimeTreeNode)FunctionTreeBuilder.Build(widgetFunctionMarkup); widgetRuntimeTreeNode.Label = label; widgetRuntimeTreeNode.HelpDefinition = new HelpDefinition(helptext); widgetRuntimeTreeNode.BindingSourceName = bindingName; var element = (XElement)widgetRuntimeTreeNode.GetValue(); _panelXml.Add(element); } } if (_showPublicationStatusSelector && _dataTypeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled))) { var placeholder = new XElement(MainNamespace + "PlaceHolder"); _panelXml.Remove(); placeholder.Add(_panelXml); layout.Add(placeholder); var publishFieldsXml = new XElement(MainNamespace + "FieldGroup", new XAttribute("Label", Texts.PublicationSettings_FieldGroupLabel)); placeholder.Add(publishFieldsXml); var publicationStatusOptionsBinding = new XElement(CmsNamespace + FormKeyTagNames.Binding, new XAttribute("name", PublicationStatusOptionsBindingName), new XAttribute("type", typeof(object))); _bindingsXml.Add(publicationStatusOptionsBinding); var element = new XElement(MainNamespace + "KeySelector", new XAttribute("OptionsKeyField", "Key"), new XAttribute("OptionsLabelField", "Value"), new XAttribute("Label", Texts.PublicationStatus_Label), new XAttribute("Help", Texts.PublicationStatus_Help), new XElement(MainNamespace + "KeySelector.Selected", new XElement(CmsNamespace + "bind", new XAttribute("source", PublicationStatusBindingName))), new XElement(MainNamespace + "KeySelector.Options", new XElement(CmsNamespace + "read", new XAttribute("source", PublicationStatusOptionsBindingName))) ); publishFieldsXml.Add(element); var publishDateBinding = new XElement(CmsNamespace + FormKeyTagNames.Binding, new XAttribute("name", "PublishDate"), new XAttribute("type", typeof(DateTime)), new XAttribute("optional", "true")); _bindingsXml.Add(publishDateBinding); publishFieldsXml.Add( new XElement(MainNamespace + "DateTimeSelector", new XAttribute("Label", Texts.PublishDate_Label), new XAttribute("Help", Texts.PublishDate_Help), new XElement(CmsNamespace + "bind", new XAttribute("source", "PublishDate")))); var unpublishDateBinding = new XElement(CmsNamespace + FormKeyTagNames.Binding, new XAttribute("name", "UnpublishDate"), new XAttribute("type", typeof(DateTime)), new XAttribute("optional", "true")); _bindingsXml.Add(unpublishDateBinding); publishFieldsXml.Add( new XElement(MainNamespace + "DateTimeSelector", new XAttribute("Label", Texts.UnpublishDate_Label), new XAttribute("Help", Texts.UnpublishDate_Help), new XElement(CmsNamespace + "bind", new XAttribute("source", "UnpublishDate")))); } var formDefinition = new XElement(CmsFormElementTemplate); formDefinition.Add(_bindingsXml); formDefinition.Add(layout); if (CustomFormDefinition == null) { _generatedForm = formDefinition.ToString(); } else { if (_showPublicationStatusSelector && _dataTypeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled))) { fieldNameToBindingNameMapper.Add(nameof(IPublishSchedule.PublishDate), nameof(IPublishSchedule.PublishDate)); fieldNameToBindingNameMapper.Add(nameof(IUnpublishSchedule.UnpublishDate), nameof(IUnpublishSchedule.UnpublishDate)); } Func<XElement, IEnumerable<XAttribute>> getBindingsFunc = doc => doc.Descendants(CmsNamespace + "binding").Attributes("name") .Concat(doc.Descendants(CmsNamespace + "bind").Attributes("source")) .Concat(doc.Descendants(CmsNamespace + "read").Attributes("source")); // Validation foreach (var bindingNameAttribute in getBindingsFunc(CustomFormDefinition.Root)) { var bindingName = bindingNameAttribute.Value; if (!IsNotFieldBinding(bindingName) && !fieldNameToBindingNameMapper.ContainsKey(bindingName)) { throw new ParseDefinitionFileException("Invalid binding name '{0}'".FormatWith(bindingName), bindingNameAttribute); } } var formDefinitionElement = new XElement(CustomFormDefinition.Root); foreach (var bindingNameAttribute in getBindingsFunc(formDefinitionElement).Where(attr => !IsNotFieldBinding(attr.Value))) { bindingNameAttribute.Value = fieldNameToBindingNameMapper[bindingNameAttribute.Value]; } if (!string.IsNullOrEmpty(FieldGroupLabel)) { foreach (var fieldGroupElement in formDefinitionElement.Descendants(MainNamespace + "FieldGroup")) { if (fieldGroupElement.Attribute("Label") == null) { fieldGroupElement.Add(new XAttribute("Label", FieldGroupLabel)); } } } _generatedForm = formDefinitionElement.ToString(); _panelXml = formDefinitionElement.Elements().Last().Elements().LastOrDefault(); } } private bool IsNotFieldBinding(string bindingName) { return bindingName == PublicationStatusOptionsBindingName; } /// <exclude /> public static string GetBindingName(string prefix, string bindingName) { return string.Format("{0}{1}", prefix, bindingName).Replace('.', '_'); } private string GetBindingName(DataFieldDescriptor dataFieldDescriptor) { if (string.IsNullOrEmpty(_bindingNamesPrefix)) { return dataFieldDescriptor.Name; } return GetBindingName(_bindingNamesPrefix, dataFieldDescriptor.Name); } private string PublicationStatusBindingName { get { return GetBindingName(_bindingNamesPrefix, PublicationStatusPostFixBindingName); } } private string PublicationStatusOptionsBindingName { get { return GetBindingName(_bindingNamesPrefix, PublicationStatusOptionsPostFixBindingName); } } internal bool BindingIsOptional(string bindingName) { var customFormDefinition = CustomFormDefinition; XElement bindingsXml; if (customFormDefinition?.Root != null) { bindingsXml = customFormDefinition.Root; } else if (!_generatedForm.IsNullOrEmpty()) { bindingsXml = XElement.Parse(_generatedForm); } else { bindingsXml = BindingXml; } var binding = bindingsXml .Descendants(CmsNamespace + "binding") .FirstOrDefault(e => (string)e.Attribute("name") == bindingName); return binding != null && string.Equals((string)binding.Attribute("optional"), "true", StringComparison.OrdinalIgnoreCase); } } } ================================================ FILE: Composite/Data/DynamicTypes/DataTypeDescriptorValueXmlSerializer.cs ================================================ using System; using System.Linq; using System.Xml.Linq; using Composite.Core.Serialization; namespace Composite.Data.DynamicTypes { internal sealed class DataTypeDescriptorValueXmlSerializer : IValueXmlSerializer { public bool TrySerialize(Type objectToSerializeType, object objectToSerialize, IXmlSerializer xmlSerializer, out XElement serializedObject) { if (objectToSerializeType == null) throw new ArgumentNullException("objectToSerializeType"); serializedObject = null; if (objectToSerializeType != typeof(DataTypeDescriptor)) return false; if (objectToSerialize == null) { serializedObject = new XElement("DataTypeDescriptor"); } else { DataTypeDescriptor dataTypeDescriptor = (DataTypeDescriptor)objectToSerialize; serializedObject = dataTypeDescriptor.ToXml(); } return true; } public bool TryDeserialize(XElement serializedObject, IXmlSerializer xmlSerializer, out object deserializedObject) { if (serializedObject == null) throw new ArgumentNullException("serializedObject"); deserializedObject = null; if (serializedObject.Name.LocalName != "DataTypeDescriptor") return false; if (serializedObject.Elements().Count() == 0) { deserializedObject = null; } else { deserializedObject = DataTypeDescriptor.FromXml(serializedObject); } return true; } } } ================================================ FILE: Composite/Data/DynamicTypes/DataTypeIndex.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using Composite.Data.DynamicTypes.Configuration; namespace Composite.Data.DynamicTypes { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class DataTypeIndex { private string _toString; /// <exclude /> public DataTypeIndex(IReadOnlyCollection<Tuple<string, IndexDirection>> fields) { Fields = fields; } /// <summary> /// Gets the list of fields /// </summary> public IReadOnlyCollection<Tuple<string, IndexDirection>> Fields { get; private set; } /// <summary> /// Defines whether current index is clustered. Only one index per data type can be choosen as clustered. /// </summary> public bool Clustered { get; set; } /// <exclude /> public override string ToString() { if (_toString == null) { var sb = new StringBuilder().Append("Index"); if (Clustered) { sb.Append(", Clustered"); } sb.Append(": "); bool first = true; foreach (var field in Fields) { if (!first) { sb.Append(", "); } sb.Append("{").Append(field.Item1).Append(", ").Append(field.Item2).Append("}"); first = false; } _toString = sb.ToString(); } return _toString; } /// <summary> /// Serializes data type index into an XElement /// </summary> /// <returns></returns> public XElement ToXml() { return new XElement("Index", Clustered ? new XAttribute("clustered", true) : null, new XElement("Fields", Fields.Select(f => new XElement("Field", new XAttribute("name", f.Item1), new XAttribute("direction", f.Item2))))); } /// <summary> /// Deserializes a <see cref="DataTypeIndex"/> /// </summary> /// <param name="element"></param> /// <returns></returns> public static DataTypeIndex FromXml(XElement element) { var clusteredAttribute = element.Attribute("clustered"); bool isClustered = clusteredAttribute != null && (bool) clusteredAttribute; var fieldsElement = element.Element("Fields"); Verify.IsNotNull(fieldsElement, "'Fields' element is missing"); var fields = new List<Tuple<string, IndexDirection>>(); foreach (var field in fieldsElement.Elements("Field")) { string fieldName = field.GetRequiredAttributeValue("name"); var direction = (IndexDirection)Enum.Parse(typeof(IndexDirection), field.GetRequiredAttributeValue("direction")); fields.Add(new Tuple<string, IndexDirection>(fieldName, direction)); } return new DataTypeIndex(fields) { Clustered = isClustered }; } } } ================================================ FILE: Composite/Data/DynamicTypes/DataTypeValidationRegistry.cs ================================================ using System; using System.Collections.Concurrent; using System.ComponentModel; using System.Text; using Composite.C1Console.Events; namespace Composite.Data.DynamicTypes { /// <summary> /// Used to keep information about the validation state of data types. /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] internal static class DataTypeValidationRegistry { private static readonly ConcurrentDictionary<Type, string> _typeSpecificValidations = new ConcurrentDictionary<Type, string>(); private static readonly ConcurrentDictionary<string, ConcurrentDictionary<Type, string>> _providerSpecificValidations = new ConcurrentDictionary<string, ConcurrentDictionary<Type, string>>(); static DataTypeValidationRegistry() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } /// <summary> /// /// </summary> /// <param name="interfaceType"></param> /// <param name="existingDataTypeDescriptor">Use null to get existing data type descriptor</param> /// <returns></returns> public static bool Validate(Type interfaceType, DataTypeDescriptor existingDataTypeDescriptor) { string errorMessage; return Validate(interfaceType, existingDataTypeDescriptor, out errorMessage); } /// <summary> /// /// </summary> /// <param name="interfaceType"></param> /// <param name="existingDataTypeDescriptor">Use null to get existing data type descriptor</param> /// <param name="errorMessage"></param> /// <returns></returns> public static bool Validate(Type interfaceType, DataTypeDescriptor existingDataTypeDescriptor, out string errorMessage) { if (existingDataTypeDescriptor == null) { existingDataTypeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(interfaceType.GetImmutableTypeId()); if (existingDataTypeDescriptor == null) { errorMessage = null; return true; } } errorMessage = _typeSpecificValidations.GetOrAdd( interfaceType, f => { string message; bool isValid = DataTypeValidator.Validate(interfaceType, existingDataTypeDescriptor, out message); if (isValid) return null; var sb = new StringBuilder(); sb.AppendLine(string.Format("The data type interface '{0}' did not validate and can't be used at the moment.", interfaceType)); sb.AppendLine(message); return sb.ToString(); } ); return errorMessage == null; } public static bool IsValidForProvider(Type interfaceType, string providerName) { string errorMessage; return IsValidForProvider(interfaceType, providerName, out errorMessage); } public static bool IsValidForProvider(Type interfaceType, string providerName, out string errorMessage) { return !_providerSpecificValidations .GetOrAdd(providerName, s => new ConcurrentDictionary<Type, string>()) .TryGetValue(interfaceType, out errorMessage); } public static void ClearValidationError(Type interfaceType, string providerName) { ConcurrentDictionary<Type, string> cd; if (!_providerSpecificValidations.TryGetValue(providerName, out cd)) { return; } string error; cd.TryRemove(interfaceType, out error); } public static void AddValidationError(Type interfaceType, string providerName, string errorMessage) { var providerErrors = _providerSpecificValidations .GetOrAdd(providerName, s => new ConcurrentDictionary<Type, string>()); providerErrors.AddOrUpdate(interfaceType, t => errorMessage, (type, s) => s + errorMessage); } private static void Flush() { _typeSpecificValidations.Clear(); _providerSpecificValidations.Clear(); } } } ================================================ FILE: Composite/Data/DynamicTypes/DataTypeValidator.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using Composite.Core; using Composite.Data; namespace Composite.Data.DynamicTypes { /// <summary> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] internal static class DataTypeValidator { /// <summary> /// This method validates if the existing .NET runtime type match the recorded meta data (DataTypeDescriptor). /// In case there is a mismatch, changes might have been done to the runtime type and an update on /// the existing store(s)could not be performed. /// </summary> /// <param name="interfaceType"></param> /// <param name="existingDataTypeDescriptor"></param> /// <param name="errorMessage"></param> /// <returns></returns> public static bool Validate(Type interfaceType, DataTypeDescriptor existingDataTypeDescriptor, out string errorMessage) { DataTypeDescriptor newDataTypeDescriptor; try { newDataTypeDescriptor = DynamicTypeManager.BuildNewDataTypeDescriptor(interfaceType); } catch (Exception) { errorMessage = null; return true; } try { new DataTypeChangeDescriptor(existingDataTypeDescriptor, newDataTypeDescriptor); } catch (Exception ex) { errorMessage = ex.Message; return false; } errorMessage = null; return true; } } } ================================================ FILE: Composite/Data/DynamicTypes/DataUrlProfile.cs ================================================ using System; using System.CodeDom; using Composite.Core.Extensions; namespace Composite.Data.DynamicTypes { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public class DataUrlProfile { /// <exclude /> public int Order { get; set; } /// <exclude /> public DataUrlSegmentFormat? Format { get; set; } /// <exclude /> public DataUrlProfile Clone() { return new DataUrlProfile {Order = Order, Format = Format}; } /// <exclude /> internal CodeAttributeDeclaration GetCodeAttributeDeclaration() { if (Format == null || Format.Value == DataUrlSegmentFormat.Undefined) { return new CodeAttributeDeclaration( typeof(RouteSegmentAttribute).FullName, new CodeAttributeArgument( new CodePrimitiveExpression(Order))); } var dateSegment = GetDateSegmentFormat(); return new CodeAttributeDeclaration(typeof (RouteDateSegmentAttribute).FullName, new CodeAttributeArgument(new CodePrimitiveExpression(Order)), new CodeAttributeArgument(new CodeFieldReferenceExpression( // Referencing an enum value new CodeTypeReferenceExpression(typeof(DateSegmentFormat)), dateSegment.ToString()))); } private DateSegmentFormat GetDateSegmentFormat() { switch (Format.Value) { case DataUrlSegmentFormat.DateTime_Year: return DateSegmentFormat.Year; case DataUrlSegmentFormat.DateTime_YearMonth: return DateSegmentFormat.YearMonth; case DataUrlSegmentFormat.DateTime_YearMonthDay: return DateSegmentFormat.YearMonthDay; } throw new InvalidOperationException("Failed to convert '{0}' to DateSegmentFormat".FormatWith(Format.Value)); } } /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum DataUrlSegmentFormat { /// <exclude /> Undefined = 0, /// <exclude /> DateTime_Year = 1, /// <exclude /> DateTime_YearMonth = 2, /// <exclude /> DateTime_YearMonthDay = 3 } } ================================================ FILE: Composite/Data/DynamicTypes/Debug/DynamicTempTypeCreator.cs ================================================ #define USE_TEMPTYPECREATOR using System; using System.Collections.Generic; using System.Linq; using Composite.Data.DynamicTypes; namespace Composite.Data.ExtendedDataType.Debug { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DynamicTempTypeCreator { private readonly string _namePrefix; private List<DataFieldDescriptor> _dataFieldDescriptors; /// <exclude /> public DynamicTempTypeCreator(string namePrefix) { _namePrefix = namePrefix; Initialize(); } /// <exclude /> public static bool UseTempTypeCreator { get { #if USE_TEMPTYPECREATOR return true; #else return false; #endif } } /// <exclude /> public string TypeName { get; private set; } /// <exclude /> public string TypeTitle { get; private set; } /// <exclude /> public List<DataFieldDescriptor> DataFieldDescriptors => _dataFieldDescriptors; private void Initialize() { int counter = 1; while (true) { string typeName = $"{_namePrefix}{counter++}"; if (!DataMetaDataFacade.GeneratedTypeDataTypeDescriptors.Any(d => d.Name == typeName)) { TypeName = TypeTitle = typeName; break; } } _dataFieldDescriptors = new List<DataFieldDescriptor> { new DataFieldDescriptor(Guid.NewGuid(), "MyStringField", StoreFieldType.String(64), typeof(string)) { Position = 10, IsNullable = true, DataUrlProfile = new DataUrlProfile { Format = DataUrlSegmentFormat.DateTime_Year, Order = 1 }, FormRenderingProfile = new DataFieldFormRenderingProfile { Label = "MyStringField", HelpText = "This is an auto-generated field.", WidgetFunctionMarkup = GetWidgetFunctionMarkup("Composite.Widgets.String.TextBox") }, TreeOrderingProfile = new DataFieldTreeOrderingProfile { OrderPriority = 1, OrderDescending = false, }, SearchProfile = new SearchProfile { IndexText = true } }, new DataFieldDescriptor(Guid.NewGuid(), "MyIntField", StoreFieldType.Integer, typeof(int)) { Position = 11, FormRenderingProfile = new DataFieldFormRenderingProfile { Label = "MyIntField", HelpText = "This is an auto-generated field.", WidgetFunctionMarkup = GetWidgetFunctionMarkup("Composite.Widgets.String.TextBox") }, TreeOrderingProfile = new DataFieldTreeOrderingProfile { OrderPriority = 2, OrderDescending = true, } }, new DataFieldDescriptor(Guid.NewGuid(), "MyDateTimeField", StoreFieldType.DateTime, typeof(DateTime?)) { IsNullable = true, Position = 12, FormRenderingProfile = new DataFieldFormRenderingProfile { Label = "MyDateTimeField", HelpText = "This is an auto-generated field.", WidgetFunctionMarkup = GetWidgetFunctionMarkup("Composite.Widgets.Date.DateSelector") }, TreeOrderingProfile = new DataFieldTreeOrderingProfile { OrderPriority = null, } } }; } private static string GetWidgetFunctionMarkup(string widgetFunctionName) { return @"<f:widgetfunction xmlns:f=""http://www.composite.net/ns/function/1.0"" name=""{Name}"" label="""" bindingsourcename=""""> <f:helpdefinition xmlns:f=""http://www.composite.net/ns/function/1.0"" helptext="""" /> </f:widgetfunction>".Replace("{Name}", widgetFunctionName); } } } ================================================ FILE: Composite/Data/DynamicTypes/DefaultValue.cs ================================================ using System; using System.CodeDom; using System.Collections.Generic; using System.Globalization; using System.Text; using Composite.Core.Instrumentation; using Composite.Core.Serialization; namespace Composite.Data.DynamicTypes { /// <summary> /// Represents a default value for a data type field /// </summary> [Serializable] public sealed class DefaultValue : IComparable { private readonly object _value; private readonly DefaultValueType _valueType; private readonly RandomStringSettings _randomStringSettings; /// <summary> /// String default value /// </summary> /// <param name="defaultValue">value</param> /// <returns></returns> public static DefaultValue String(string defaultValue) { return new DefaultValue(defaultValue); } /// <summary> /// Int default value /// </summary> /// <param name="defaultValue">value</param> /// <returns></returns> public static DefaultValue Integer(int defaultValue) { return new DefaultValue(defaultValue); } /// <summary> /// Decimal default value /// </summary> /// <param name="defaultValue">value</param> /// <returns></returns> public static DefaultValue Decimal(decimal defaultValue) { return new DefaultValue(defaultValue); } /// <summary> /// Bool default value /// </summary> /// <param name="defaultValue">value</param> /// <returns></returns> public static DefaultValue Boolean(bool defaultValue) { return new DefaultValue(defaultValue); } /// <summary> /// DateTime default value /// </summary> /// <param name="defaultValue">value</param> /// <returns></returns> public static DefaultValue DateTime(DateTime defaultValue) { return new DefaultValue(defaultValue); } /// <summary> /// Guid default value /// </summary> /// <param name="defaultValue">value</param> /// <returns></returns> public static DefaultValue Guid(Guid defaultValue) { return new DefaultValue(defaultValue); } /// <summary> /// 'Now' as a default value (time stamp) /// </summary> /// <returns></returns> public static DefaultValue Now { get { return new DefaultValue(DefaultValueType.DateTimeNow); } } /// <summary> /// New Guid as default value. Generate a new unique Guid. /// </summary> /// <returns></returns> public static DefaultValue NewGuid { get { return new DefaultValue(DefaultValueType.NewGuid); } } /// <summary> /// A new value is a new random string /// </summary> /// <returns></returns> public static DefaultValue RandomString(int length, bool checkCollisions) { return new DefaultValue(new RandomStringSettings(length, checkCollisions)); } /// <summary> /// The default value. /// </summary> public object Value { get { switch (_valueType) { case DefaultValueType.DateTimeNow: return System.DateTime.Now; case DefaultValueType.NewGuid: return System.Guid.NewGuid(); case DefaultValueType.RandomString: return null; // A new value is generated and set in an "OnBeforeAdd" event handler. default: return _value; } } } /// <summary> /// Type of the default value /// </summary> public DefaultValueType ValueType { get { return _valueType; } } /// <exclude /> public DefaultValue Clone() { switch (_valueType) { case DefaultValueType.Boolean: return DefaultValue.Boolean((bool)_value); case DefaultValueType.DateTime: return DefaultValue.DateTime((DateTime)_value); case DefaultValueType.DateTimeNow: return DefaultValue.Now; case DefaultValueType.Decimal: return DefaultValue.Decimal((decimal)_value); case DefaultValueType.Guid: return DefaultValue.Guid((Guid)_value); case DefaultValueType.Integer: return DefaultValue.Integer((int)_value); case DefaultValueType.NewGuid: return DefaultValue.NewGuid; case DefaultValueType.String: return DefaultValue.String((string)_value); case DefaultValueType.RandomString: return new DefaultValue(_randomStringSettings); default: throw new NotImplementedException(); } } /// <exclude /> public string Serialize() { var sb = new StringBuilder(); StringConversionServices.SerializeKeyValuePair(sb, "ValueType", this.ValueType.ToString()); if (!IsDynamicValue && this.Value != null) { StringConversionServices.SerializeKeyValuePair(sb, "Value", SerializeDefaultValue(ValueType, this.Value)); } if (_randomStringSettings != null) { _randomStringSettings.Serialize(sb); } return sb.ToString(); } private static string SerializeDefaultValue(DefaultValueType type, object value) { Verify.ArgumentNotNull(value, "value"); switch (type) { case DefaultValueType.Boolean: return ((bool)value).ToString(CultureInfo.InvariantCulture); case DefaultValueType.DateTime: return ((DateTime)value).ToString(CultureInfo.InvariantCulture); case DefaultValueType.Decimal: return ((Decimal)value).ToString(CultureInfo.InvariantCulture); case DefaultValueType.Guid: return value.ToString(); case DefaultValueType.Integer: return ((Int32)value).ToString(CultureInfo.InvariantCulture); case DefaultValueType.String: return (string)value; case DefaultValueType.RandomString: case DefaultValueType.NewGuid: case DefaultValueType.DateTimeNow: return string.Empty; default: throw new NotImplementedException("DefaultValueType = " + type); } } /// <exclude /> public static DefaultValue Deserialize(string serializedData) { Verify.ArgumentNotNullOrEmpty(serializedData, "serializedData"); using (TimerProfilerFacade.CreateTimerProfiler()) { Dictionary<string, string> dic = StringConversionServices.ParseKeyValueCollection(serializedData); Verify.That(dic.ContainsKey("ValueType"), "Wrong serialized format"); string valueTypeString = StringConversionServices.DeserializeValue<string>(dic["ValueType"]); var valueType = (DefaultValueType)Enum.Parse(typeof(DefaultValueType), valueTypeString); bool hasValue = dic.ContainsKey("Value"); switch (valueType) { case DefaultValueType.Boolean: Verify.That(hasValue, "Wrong serialized format"); bool boolValue = StringConversionServices.DeserializeValueBool(dic["Value"]); return DefaultValue.Boolean(boolValue); case DefaultValueType.DateTime: Verify.That(hasValue, "Wrong serialized format"); DateTime dateTimeValue = StringConversionServices.DeserializeValueDateTime(dic["Value"]); return DefaultValue.DateTime(dateTimeValue); case DefaultValueType.DateTimeNow: return DefaultValue.Now; case DefaultValueType.Decimal: Verify.That(hasValue, "Wrong serialized format"); decimal decimalValue = StringConversionServices.DeserializeValueDecimal(dic["Value"]); return DefaultValue.Decimal(decimalValue); case DefaultValueType.Guid: Verify.That(hasValue, "Wrong serialized format"); Guid guidValue = StringConversionServices.DeserializeValueGuid(dic["Value"]); return DefaultValue.Guid(guidValue); case DefaultValueType.Integer: Verify.That(hasValue, "Wrong serialized format"); int intValue = StringConversionServices.DeserializeValueInt(dic["Value"]); return DefaultValue.Integer(intValue); case DefaultValueType.NewGuid: return DefaultValue.NewGuid; case DefaultValueType.String: string stringValue = null; if (hasValue) { stringValue = StringConversionServices.DeserializeValueString(dic["Value"]); } return DefaultValue.String(stringValue); case DefaultValueType.RandomString: var settings = RandomStringSettings.Deserialize(dic); return new DefaultValue(settings); default: throw new NotImplementedException("DefaultValueType = " + valueType); } } } /// <exclude /> public override string ToString() { return Serialize(); } internal CodeAttributeDeclaration GetCodeAttributeDeclaration() { CodeAttributeDeclaration codeAttributeDeclaration; switch (this.ValueType) { case DefaultValueType.DateTimeNow: codeAttributeDeclaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(DefaultFieldNowDateTimeValueAttribute))); break; case DefaultValueType.Guid: codeAttributeDeclaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(DefaultFieldGuidValueAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression(this.Value.ToString()))); break; case DefaultValueType.Integer : codeAttributeDeclaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(DefaultFieldIntValueAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression(this.Value))); break; case DefaultValueType.Decimal: codeAttributeDeclaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(DefaultFieldDecimalValueAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression(decimal.ToInt32((decimal)this.Value)))); break; case DefaultValueType.NewGuid: codeAttributeDeclaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(DefaultFieldNewGuidValueAttribute))); break; case DefaultValueType.String: codeAttributeDeclaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(DefaultFieldStringValueAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression(this.Value))); break; case DefaultValueType.RandomString: codeAttributeDeclaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(DefaultFieldRandomStringValueAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression(_randomStringSettings.Length)), new CodeAttributeArgument(new CodePrimitiveExpression(_randomStringSettings.CheckCollisions))); break; case DefaultValueType.Boolean: codeAttributeDeclaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(DefaultFieldBoolValueAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression(this.Value))); break; default: throw new NotImplementedException(); } return codeAttributeDeclaration; } internal bool IsAssignableTo(StoreFieldType storeType) { switch (this.ValueType) { case DefaultValueType.DateTime: case DefaultValueType.DateTimeNow: return storeType.IsDateTime || storeType.IsString; case DefaultValueType.String: if (!storeType.IsString) return false; return this.Value == null || storeType.MaximumLength >= this.Value.ToString().Length; case DefaultValueType.RandomString: return storeType.IsString && storeType.MaximumLength >= _randomStringSettings.Length; case DefaultValueType.Integer: return storeType.IsNumeric || storeType.IsString; case DefaultValueType.Decimal: return storeType.IsDecimal; case DefaultValueType.Boolean: return storeType.IsBoolean || storeType.IsString; case DefaultValueType.Guid: case DefaultValueType.NewGuid: return storeType.IsGuid || storeType.IsString; } throw new ArgumentException("Unknown store type"); } private DefaultValue(RandomStringSettings randomStringSettings) { _valueType = DefaultValueType.RandomString; _randomStringSettings = randomStringSettings; } private DefaultValue(string defaultValue) { _valueType = DefaultValueType.String; _value = defaultValue; } private DefaultValue(int defaultValue) { _valueType = DefaultValueType.Integer; _value = defaultValue; } private DefaultValue(decimal defaultValue) { _valueType = DefaultValueType.Decimal; _value = defaultValue; } private DefaultValue(bool defaultValue) { _valueType = DefaultValueType.Boolean; _value = defaultValue; } private DefaultValue(DateTime defaultValue) { _valueType = DefaultValueType.DateTime; _value = defaultValue; } private DefaultValue(Guid defaultValue) { _valueType = DefaultValueType.Guid; _value = defaultValue; } private DefaultValue(DefaultValueType defaultValueType) { switch (defaultValueType) { case DefaultValueType.DateTimeNow: case DefaultValueType.NewGuid: _valueType = defaultValueType; return; } throw new ArgumentException("Provided value type can not be constructed using this constructor. Use other constructor."); } private bool IsDynamicValue { get { return ValueType == DefaultValueType.DateTimeNow || ValueType == DefaultValueType.NewGuid || ValueType == DefaultValueType.RandomString; } } /// <exclude /> public int CompareTo(object obj) { if (obj == null) throw new ArgumentNullException(); if (obj.GetType() != typeof(DefaultValue)) throw new ArithmeticException(string.Format("Expected object of type {0}", typeof(DefaultValue))); var compareTo = (DefaultValue)obj; if (this.ValueType != compareTo.ValueType) return -1; switch (_valueType) { case DefaultValueType.DateTimeNow: case DefaultValueType.NewGuid: return 0; case DefaultValueType.String: if (this.Value == null) { return compareTo.Value == null ? 0 : -1; } return string.Compare(this.Value.ToString(), compareTo.Value.ToString(), StringComparison.Ordinal); case DefaultValueType.Integer: return ((int)this.Value).CompareTo((int)compareTo.Value); case DefaultValueType.Decimal: return ((Decimal)this.Value).CompareTo((Decimal)compareTo.Value); case DefaultValueType.Boolean: return ((bool)this.Value).CompareTo((bool)compareTo.Value); case DefaultValueType.DateTime: return ((DateTime)this.Value).CompareTo((DateTime)compareTo.Value); case DefaultValueType.Guid: return string.Compare(this.Value.ToString(), compareTo.Value.ToString(), StringComparison.OrdinalIgnoreCase); case DefaultValueType.RandomString: return string.Compare(_randomStringSettings.ToString(), compareTo._randomStringSettings.ToString(), StringComparison.OrdinalIgnoreCase); default: throw new NotImplementedException("Unable to compare DefaultValue objects - unknown case of DefaultValueType"); } } /// <exclude /> public override bool Equals(object obj) { return obj is DefaultValue && CompareTo(obj) == 0; } /// <exclude /> public override int GetHashCode() { return ToString().GetHashCode(); } [Serializable] private class RandomStringSettings { public RandomStringSettings(int length, bool checkCollisions) { Length = length; CheckCollisions = checkCollisions; } public void Serialize(StringBuilder sb) { StringConversionServices.SerializeKeyValuePair(sb, "Length", Length); StringConversionServices.SerializeKeyValuePair(sb, "CheckCollisions", CheckCollisions); } public static RandomStringSettings Deserialize(Dictionary<string, string> values) { return new RandomStringSettings( StringConversionServices.DeserializeValueInt(values["Length"]), StringConversionServices.DeserializeValueBool(values["CheckCollisions"])); } public int Length { get; private set; } public bool CheckCollisions { get; private set; } public override string ToString() { return string.Format("{0},{1}", Length, CheckCollisions); } } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum DefaultValueType { /// <exclude /> DateTimeNow = 0, /// <exclude /> String = 1, /// <exclude /> Integer = 2, /// <exclude /> Decimal = 3, /// <exclude /> Boolean = 4, /// <exclude /> DateTime = 5, /// <exclude /> Guid = 6, /// <exclude /> NewGuid = 7, /// <exclude /> RandomString = 8, } } ================================================ FILE: Composite/Data/DynamicTypes/DynamicTypeManager.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using Composite.Core; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.Instrumentation; using Composite.Data.Foundation; using Composite.Data.Foundation.PluginFacades; using Composite.Data.Plugins.DataProvider; using Composite.Core.Types; namespace Composite.Data.DynamicTypes { /// <summary> /// This class is used for handling DataTypeDescriptors for all C1 data types. /// Building new from reflection and getting already stored. /// /// This class is also used for handling stores for a given data type. /// Including creating/altering/dropping and locales. So through this class /// you can create/alter/drop stores in a specific data provider for a given /// data type. /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] public static class DynamicTypeManager { private static IDynamicTypeManager _dynamicTypeManager = new DynamicTypeManagerImpl(); /// <exclude /> public static IDynamicTypeManager Implementation { get { return _dynamicTypeManager; } set { _dynamicTypeManager = value; } } internal delegate void DataStoreEventHandler(DataTypeDescriptor dataTypeDescriptor); internal delegate void DataStoreChangedEventHandler(UpdateDataTypeDescriptor updateDataTypeDescriptor); internal delegate void LocalizationEventHandler(CultureInfo culture); /// <summary> /// Raised after data stores are created for a data type. /// </summary> internal static event DataStoreEventHandler OnStoreCreated; /// <summary> /// Raised after a data type is removed from the system. /// </summary> internal static event DataStoreEventHandler OnStoreDropped; /// <summary> /// Raised after a data type is updated. /// </summary> internal static event DataStoreChangedEventHandler OnStoreUpdated; /// <summary> /// Raised after the data stores created for a new locale. /// </summary> internal static event LocalizationEventHandler OnLocaleAdded; /// <summary> /// Raised after the data stores related to a locale are removed. /// </summary> internal static event LocalizationEventHandler OnLocaleRemoved; /// <exclude /> public static DataTypeDescriptor BuildNewDataTypeDescriptor(Type typeToDescript) { return _dynamicTypeManager.BuildNewDataTypeDescriptor(typeToDescript); } // Overload /// <exclude /> public static DataTypeDescriptor GetDataTypeDescriptor(Type typeToDescript) { DataTypeDescriptor dataTypeDescriptor; if (!TryGetDataTypeDescriptor(typeToDescript.GetImmutableTypeId(), out dataTypeDescriptor)) { dataTypeDescriptor = BuildNewDataTypeDescriptor(typeToDescript); } return dataTypeDescriptor; } // Overload /// <exclude /> public static DataTypeDescriptor GetDataTypeDescriptor(Guid immutableTypeId) { DataTypeDescriptor dataTypeDescriptor; TryGetDataTypeDescriptor(immutableTypeId, out dataTypeDescriptor); return dataTypeDescriptor; } // Overload /// <exclude /> public static bool TryGetDataTypeDescriptor(Type interfaceType, out DataTypeDescriptor dataTypeDescriptor) { return _dynamicTypeManager.TryGetDataTypeDescriptor(interfaceType.GetImmutableTypeId(), out dataTypeDescriptor); } /// <exclude /> public static bool TryGetDataTypeDescriptor(Guid immutableTypeId, out DataTypeDescriptor dataTypeDescriptor) { return _dynamicTypeManager.TryGetDataTypeDescriptor(immutableTypeId, out dataTypeDescriptor); } // Overload /// <exclude /> public static void UpdateDataTypeDescriptor(DataTypeDescriptor dataTypeDescriptor) { UpdateDataTypeDescriptor(dataTypeDescriptor, true); } /// <exclude /> public static void UpdateDataTypeDescriptor(DataTypeDescriptor dataTypeDescriptor, bool flushTheSystem) { _dynamicTypeManager.UpdateDataTypeDescriptor(dataTypeDescriptor, flushTheSystem); } // Overload /// <exclude /> public static void CreateStore(DataTypeDescriptor typeDescriptor) { CreateStore(DataProviderRegistry.DefaultDynamicTypeDataProviderName, typeDescriptor, true); } // Overload /// <exclude /> public static void CreateStore(DataTypeDescriptor typeDescriptor, bool doFlush) { CreateStore(DataProviderRegistry.DefaultDynamicTypeDataProviderName, typeDescriptor, doFlush); } /// <exclude /> public static void CreateStores(IReadOnlyCollection<DataTypeDescriptor> typeDescriptors, bool doFlush) { CreateStores(DataProviderRegistry.DefaultDynamicTypeDataProviderName, typeDescriptors, doFlush); } // Overload /// <exclude /> public static void CreateStore(string providerName, DataTypeDescriptor typeDescriptor) { CreateStore(providerName, typeDescriptor, true); } /// <exclude /> public static void CreateStore(string providerName, DataTypeDescriptor typeDescriptor, bool doFlush) { _dynamicTypeManager.CreateStores(providerName, new[] { typeDescriptor }, doFlush); OnStoreCreated?.Invoke(typeDescriptor); } /// <exclude /> public static void CreateStores(string providerName, IReadOnlyCollection<DataTypeDescriptor> typeDescriptors, bool doFlush) { _dynamicTypeManager.CreateStores(providerName, typeDescriptors, doFlush); typeDescriptors.ForEach(td => OnStoreCreated?.Invoke(td)); } // Overload /// <exclude /> public static void AlterStore(UpdateDataTypeDescriptor updateDataTypeDescriptor) { AlterStore(updateDataTypeDescriptor, false); } /// <exclude /> public static void AlterStore(UpdateDataTypeDescriptor updateDataTypeDescriptor, bool forceRecompile) { _dynamicTypeManager.AlterStore(updateDataTypeDescriptor, forceRecompile); OnStoreUpdated?.Invoke(updateDataTypeDescriptor); } // Overload /// <exclude /> public static void DropStore(DataTypeDescriptor typeDescriptor) { DropStore(null, typeDescriptor, true); } // Overload /// <exclude /> public static void DropStore(string providerName, DataTypeDescriptor typeDescriptor) { DropStore(providerName, typeDescriptor, true); } internal static void DropStore(string providerName, DataTypeDescriptor typeDescriptor, bool makeAFlush) { if (providerName == null) { providerName = DataProviderRegistry.DefaultDynamicTypeDataProviderName; } _dynamicTypeManager.DropStore(providerName, typeDescriptor, makeAFlush); var interfaceType = typeDescriptor.GetInterfaceType(); if (interfaceType != null) { DataProviderRegistry.UnregisterDataType(interfaceType, providerName); } OnStoreDropped?.Invoke(typeDescriptor); } // Overload /// <exclude /> public static void AddLocale(CultureInfo cultureInfo) { AddLocale(DataProviderRegistry.DefaultDynamicTypeDataProviderName, cultureInfo); } /// <exclude /> public static void AddLocale(string providerName, CultureInfo cultureInfo) { _dynamicTypeManager.AddLocale(providerName, cultureInfo); OnLocaleAdded?.Invoke(cultureInfo); } // Overload /// <exclude /> public static void RemoveLocale(CultureInfo cultureInfo) { RemoveLocale(DataProviderRegistry.DefaultDynamicTypeDataProviderName, cultureInfo); } /// <exclude /> public static void RemoveLocale(string providerName, CultureInfo cultureInfo) { _dynamicTypeManager.RemoveLocale(providerName, cultureInfo); OnLocaleRemoved?.Invoke(cultureInfo); } /// <summary> /// For internal use only!!! /// This method will create the store if the interfaceType has not been configured. /// </summary> /// <param name="interfaceType"></param> public static void EnsureCreateStore(Type interfaceType) { EnsureCreateStore(interfaceType, null); } /// <summary> /// For internal use only!!! /// This method will create the store if the interfaceType has not been configured. /// </summary> /// <param name="interfaceType"></param> /// <param name="providerName"></param> // Helper public static void EnsureCreateStore(Type interfaceType, string providerName) { IEnumerable<string> dynamicProviderNames; if (providerName == null) { // Checking if any of existing dynamic data providers already has a store for the specified interface type providerName = DataProviderRegistry.DefaultDynamicTypeDataProviderName; dynamicProviderNames = DataProviderRegistry.DynamicDataProviderNames; } else { dynamicProviderNames = new[] {providerName}; } var possibleMatches = dynamicProviderNames .Select(DataProviderPluginFacade.GetDataProvider) .Cast<IDynamicDataProvider>() .SelectMany(dynamicDataProvider => dynamicDataProvider.GetKnownInterfaces()) .Where(i => i.FullName == interfaceType.FullName); foreach(var match in possibleMatches) { if(match == interfaceType) return; if (match.GetImmutableTypeId() == interfaceType.GetImmutableTypeId()) { throw new InvalidOperationException($"The same type '{match.FullName}' is loaded in memory twice. Location 1: '{match.Assembly.Location}', location 2: {interfaceType.Assembly.Location}"); } } var dataTypeDescriptor = BuildNewDataTypeDescriptor(interfaceType); CreateStore(providerName, dataTypeDescriptor, true); if (!SystemSetupFacade.SetupIsRunning) { CodeGenerationManager.GenerateCompositeGeneratedAssembly(true); } } // Helper internal static bool IsEnsureUpdateStoreNeeded(Type interfaceType) { using (TimerProfilerFacade.CreateTimerProfiler()) { DataTypeDescriptor newDataTypeDescriptor; if (!TryGetDataTypeDescriptor(interfaceType, out newDataTypeDescriptor)) { newDataTypeDescriptor = BuildNewDataTypeDescriptor(interfaceType); } var oldDataTypeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(newDataTypeDescriptor.DataTypeId); if (oldDataTypeDescriptor == null) { DataMetaDataFacade.PersistMetaData(newDataTypeDescriptor); return false; } var dataTypeChangeDescriptor = new DataTypeChangeDescriptor(oldDataTypeDescriptor, newDataTypeDescriptor); if (!dataTypeChangeDescriptor.AlteredTypeHasChanges) { return false; } return dataTypeChangeDescriptor.AlteredTypeHasChanges; } } // Helper internal static bool EnsureUpdateStore(Type interfaceType, string providerName, bool makeAFlush) { using (TimerProfilerFacade.CreateTimerProfiler(interfaceType.ToString())) { var newDataTypeDescriptor = BuildNewDataTypeDescriptor(interfaceType); var oldDataTypeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(newDataTypeDescriptor.DataTypeId); if (interfaceType.IsGenerated()) { var customFields = oldDataTypeDescriptor.Fields.Where(f => !f.Inherited && !oldDataTypeDescriptor.KeyPropertyNames .Contains(f.Name)); foreach (var field in customFields) { var fieldDescriptor = newDataTypeDescriptor.Fields[field.Name]; if (fieldDescriptor != null) { newDataTypeDescriptor.Fields.Remove(fieldDescriptor); } else { Log.LogWarning(nameof(DynamicTypeManager), $"Property '{field.Name}' was missing in the generated interface type '{interfaceType.FullName}'"); } newDataTypeDescriptor.Fields.Add(field); } } if (oldDataTypeDescriptor == null) { DataMetaDataFacade.PersistMetaData(newDataTypeDescriptor); return false; } var dataTypeChangeDescriptor = new DataTypeChangeDescriptor(oldDataTypeDescriptor, newDataTypeDescriptor); if (!dataTypeChangeDescriptor.AlteredTypeHasChanges) { if (dataTypeChangeDescriptor.TypeHasMetaDataChanges) { Log.LogInformation(nameof(DynamicTypeManager), $"Updating data type descriptor for type '{newDataTypeDescriptor.GetFullInterfaceName()}'"); DataMetaDataFacade.PersistMetaData(newDataTypeDescriptor); } return false; } Log.LogVerbose(nameof(DynamicTypeManager), "Updating the store for interface type '{0}' on the '{1}' data provider", interfaceType, providerName); var updateDataTypeDescriptor = new UpdateDataTypeDescriptor(oldDataTypeDescriptor, newDataTypeDescriptor, providerName); AlterStore(updateDataTypeDescriptor, makeAFlush); return true; } } } } ================================================ FILE: Composite/Data/DynamicTypes/DynamicTypeManagerImpl.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using Composite.Core.Extensions; using Composite.Data.DynamicTypes.Foundation; using Composite.Data.Foundation.PluginFacades; using Composite.C1Console.Events; using Composite.Core.Configuration; using Composite.Data.Transactions; using Composite.Core.Types; namespace Composite.Data.DynamicTypes { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DynamicTypeManagerImpl : IDynamicTypeManager { /// <exclude /> public DataTypeDescriptor BuildNewDataTypeDescriptor(Type typeToDescript) { if (typeToDescript == null) throw new ArgumentNullException("typeToDescript"); return ReflectionBasedDescriptorBuilder.Build(typeToDescript); } /// <exclude /> public bool TryGetDataTypeDescriptor(Guid immutableTypeId, out DataTypeDescriptor dataTypeDescriptor) { dataTypeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(immutableTypeId); return dataTypeDescriptor != null; } /// <exclude /> public void UpdateDataTypeDescriptor(DataTypeDescriptor dataTypeDescriptor, bool flushTheSystem) { dataTypeDescriptor.Validate(); DataMetaDataFacade.PersistMetaData(dataTypeDescriptor); if (flushTheSystem) { GlobalEventSystemFacade.FlushTheSystem(); } } /// <exclude /> public void CreateStores(string providerName, IReadOnlyCollection<DataTypeDescriptor> typeDescriptors, bool doFlush) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); Verify.ArgumentNotNull(typeDescriptors, "typeDescriptors"); typeDescriptors.ForEach(d => d.Validate()); using (var transactionScope = TransactionsFacade.CreateNewScope()) { foreach (var typeDescriptor in typeDescriptors) { DataMetaDataFacade.PersistMetaData(typeDescriptor); } DataProviderPluginFacade.CreateStores(providerName, typeDescriptors); transactionScope.Complete(); } if (doFlush) { GlobalEventSystemFacade.FlushTheSystem(); } } /// <exclude /> public void AlterStore(UpdateDataTypeDescriptor updateDataTypeDescriptor, bool forceCompile) { DataTypeChangeDescriptor dataTypeChangeDescriptor = updateDataTypeDescriptor.CreateDataTypeChangeDescriptor(); dataTypeChangeDescriptor.AlteredType.Validate(); using (var transactionScope = TransactionsFacade.CreateNewScope()) { DataMetaDataFacade.PersistMetaData(dataTypeChangeDescriptor.AlteredType); if (dataTypeChangeDescriptor.AlteredTypeHasChanges) { DataProviderPluginFacade.AlterStore(updateDataTypeDescriptor, forceCompile); } transactionScope.Complete(); } } /// <exclude /> public void DropStore(string providerName, DataTypeDescriptor typeDescriptor, bool makeAFlush) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); Verify.ArgumentNotNull(typeDescriptor, "typeDescriptor"); typeDescriptor.Validate(); using (var transactionScope = TransactionsFacade.CreateNewScope()) { DataProviderPluginFacade.DropStore(providerName, typeDescriptor); DataMetaDataFacade.DeleteMetaData(typeDescriptor.DataTypeId); transactionScope.Complete(); } if (makeAFlush) { GlobalEventSystemFacade.FlushTheSystem(); } } /// <exclude /> public void AddLocale(string providerName, CultureInfo cultureInfo) { Verify.ArgumentNotNullOrEmpty(providerName, nameof(providerName)); Verify.ArgumentNotNull(cultureInfo, nameof(cultureInfo)); using (var transactionScope = TransactionsFacade.CreateNewScope()) { DataProviderPluginFacade.AddLocale(providerName, cultureInfo); transactionScope.Complete(); } if (!SystemSetupFacade.SetupIsRunning) { CodeGenerationManager.GenerateCompositeGeneratedAssembly(true); } } /// <exclude /> public void RemoveLocale(string providerName, CultureInfo cultureInfo) { if (string.IsNullOrEmpty(providerName)) throw new ArgumentNullException("providerName"); if (cultureInfo == null) throw new ArgumentNullException("cultureInfo"); using (var transactionScope = TransactionsFacade.CreateNewScope()) { DataProviderPluginFacade.RemoveLocale(providerName, cultureInfo); transactionScope.Complete(); } CodeGenerationManager.GenerateCompositeGeneratedAssembly(true); } } } ================================================ FILE: Composite/Data/DynamicTypes/DynamicTypeMarkupServices.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.Core.Types; using Composite.Core.Xml; namespace Composite.Data.DynamicTypes { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DynamicTypeMarkupServices { private static readonly XName _fieldReferenceElementName = Namespaces.DynamicData10 + "fieldreference"; private static readonly XName _fieldReferenceTypeAttributeName = "typemanagername"; private static readonly XName _fieldReferenceFieldAttributeName = "fieldname"; /// <exclude /> public static XElement GetReferenceElement(this DataFieldDescriptor fieldToReference, DataTypeDescriptor ownerTypeDescriptor) { return GetReferenceElement(fieldToReference.Name,ownerTypeDescriptor.TypeManagerTypeName); } /// <exclude /> public static XElement GetReferenceElement(string fieldName, string typeManagerName) { // ensure "data:" prefix in markup: XElement element = XElement.Parse(string.Format("<data:{0} xmlns:data='{1}' />", _fieldReferenceElementName.LocalName, _fieldReferenceElementName.NamespaceName)); element.Add( new XAttribute(_fieldReferenceFieldAttributeName, fieldName), new XAttribute(_fieldReferenceTypeAttributeName, typeManagerName)); return element; } /// <exclude /> public static bool TryGetDescriptors(XElement fieldReferenceElement, out DataTypeDescriptor typeDescriptor, out DataFieldDescriptor fieldDescriptor) { typeDescriptor = null; fieldDescriptor = null; if (fieldReferenceElement.Name != _fieldReferenceElementName) { throw new InvalidOperationException(string.Format("Unexpected element name '{0}'. Expected '{1}'", fieldReferenceElement.Name, _fieldReferenceElementName)); } string typeManagerName = fieldReferenceElement.Attribute(_fieldReferenceTypeAttributeName).Value; string fieldName = fieldReferenceElement.Attribute(_fieldReferenceFieldAttributeName).Value; Type t = TypeManager.TryGetType(typeManagerName); if (t == null) { return false; } typeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(t.GetImmutableTypeId()); if (typeDescriptor == null) { return false; } if(fieldName == "DataSourceId") { fieldDescriptor = new DataFieldDescriptor(Guid.Empty, "DataSourceId", StoreFieldType.LargeString, typeof (string)); return true; } fieldDescriptor = typeDescriptor.Fields.Where(f => f.Name == fieldName).FirstOrDefault(); if (fieldDescriptor == null) { return false; } return true; } /// <exclude /> public static IEnumerable<FieldReferenceDefinition> GetFieldReferenceDefinitions(XContainer container, string typeManagerName) { Type type = null; foreach (XElement referenceElement in container.Descendants(_fieldReferenceElementName)) { string referencedTypeName = referenceElement.Attribute(_fieldReferenceTypeAttributeName).Value; if(referencedTypeName != typeManagerName) { type = type ?? TypeManager.TryGetType(typeManagerName); if(type == null) continue; Type referencedType = TypeManager.TryGetType(referencedTypeName); if(referencedType == null || !referencedType.Equals(type)) { continue; } } string fieldName = referenceElement.Attribute(_fieldReferenceFieldAttributeName).Value; yield return new FieldReferenceDefinition { FieldName = fieldName, FieldReferenceElement = referenceElement }; } } /// <exclude /> public class FieldReferenceDefinition { /// <exclude /> public string FieldName { get; set; } /// <exclude /> public XElement FieldReferenceElement { get; set; } } } } ================================================ FILE: Composite/Data/DynamicTypes/Foundation/DynamicTypeReflectionFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.Core.Linq; using Composite.Core.Types; namespace Composite.Data.DynamicTypes.Foundation { internal static class DynamicTypeReflectionFacade { public static Guid GetImmutableTypeId(Type type) { List<ImmutableTypeIdAttribute> immutableTypeIdAttributes = type.GetCustomInterfaceAttributes<ImmutableTypeIdAttribute>().ToList(); if (immutableTypeIdAttributes.Count == 0) throw new InvalidOperationException(string.Format("{0} is missing the {1} definition.", type, typeof(ImmutableTypeIdAttribute))); Guid immutableTypeId = immutableTypeIdAttributes[0].ImmutableTypeId; if (immutableTypeId.Equals(Guid.Empty)) throw new InvalidOperationException(string.Format("{0} has an invalid {1} definition. A unique Guid is expected.", type, typeof(ImmutableTypeIdAttribute).Name)); return immutableTypeId; } public static Guid GetImmutableFieldId(PropertyInfo propertyInfo) { object[] immutableFieldIdAttributes = propertyInfo.GetCustomAttributes(typeof(ImmutableFieldIdAttribute), true); if (immutableFieldIdAttributes.Length == 0) throw new InvalidOperationException(string.Format("The {0} property of type {1} is missing its {2} definition.", propertyInfo.Name, propertyInfo.DeclaringType.FullName, typeof(ImmutableFieldIdAttribute))); Guid immutableFieldId = ((ImmutableFieldIdAttribute)immutableFieldIdAttributes[0]).ImmutableFieldId; if (immutableFieldId.Equals(Guid.Empty)) throw new InvalidOperationException(string.Format("{0} has an invalid {1} definition. A unique Guid is expected.", propertyInfo.DeclaringType, typeof(ImmutableFieldIdAttribute).Name)); return immutableFieldId; } public static StoreFieldType GetStoreFieldType(PropertyInfo fieldInfo) { var storeFieldTypeAttribute = GetCustomAttribute<StoreFieldTypeAttribute>(fieldInfo); Verify.IsNotNull(storeFieldTypeAttribute, "Missing [{0}] on field '{1}.{2}'", typeof(StoreFieldTypeAttribute), fieldInfo.DeclaringType.FullName, fieldInfo.Name); return storeFieldTypeAttribute.StoreFieldType; } public static bool TryGetFieldPosition(PropertyInfo fieldInfo, out int position) { var fieldPositionAttribute = GetCustomAttribute<FieldPositionAttribute>(fieldInfo); if (fieldPositionAttribute == null) { position = 0; return false; } position = fieldPositionAttribute.Position; return true; } public static int GetGroupByPriority(PropertyInfo fieldInfo) { var groupByPriorityAttribute = GetCustomAttribute<GroupByPriorityAttribute>(fieldInfo); return groupByPriorityAttribute != null ? groupByPriorityAttribute.Priority : 0; } public static DataFieldTreeOrderingProfile GetTreeOrderingProfile(PropertyInfo fieldInfo) { var attribute = GetCustomAttribute<TreeOrderingAttribute>(fieldInfo); if (attribute == null) { return new DataFieldTreeOrderingProfile { OrderPriority = null }; } return new DataFieldTreeOrderingProfile { OrderPriority = attribute.Priority, OrderDescending = attribute.Descending }; } public static DataFieldFormRenderingProfile GetFormRenderingProfile(PropertyInfo propertyInfo) { var attr = GetCustomAttribute<FormRenderingProfileAttribute>(propertyInfo); return attr != null ? new DataFieldFormRenderingProfile { Label = attr.Label, HelpText = attr.HelpText, WidgetFunctionMarkup = attr.WidgetFunctionMarkup } : null; } private static T GetCustomAttribute<T>(PropertyInfo propertyInfo) where T: Attribute { object[] attributes = propertyInfo.GetCustomAttributes(typeof(T), true); Verify.That(attributes.Length < 2, "Multiple [{0}] attributes defined on field {1}.{2}", typeof(T).Name, propertyInfo.DeclaringType.FullName, propertyInfo.Name); return attributes.Length > 0 ? (T)attributes[0] : null; } public static string GetTitle(Type type) { List<TitleAttribute> titleAttributes = type.GetCustomInterfaceAttributes<TitleAttribute>().ToList(); if (titleAttributes.Count > 0) { return titleAttributes[0].Title; } return null; } public static string GetLabelPropertyName(Type type) { List<LabelPropertyNameAttribute> labelPropertyNameAttributes = type.GetCustomInterfaceAttributes<LabelPropertyNameAttribute>().ToList(); if (labelPropertyNameAttributes.Count > 0) { return labelPropertyNameAttributes[0].PropertyName; } return null; } public static string GetInternalUrlPrefix(Type type) { var internalUrlAttributes = type.GetCustomInterfaceAttributes<InternalUrlAttribute>().Evaluate(); return internalUrlAttributes.Count > 0 ? internalUrlAttributes.First().InternalUrlPrefix : null; } public static IEnumerable<DataScopeIdentifier> GetDataScopes(Type interfaceType) { List<DataScopeAttribute> attributes = interfaceType.GetCustomInterfaceAttributes<DataScopeAttribute>().ToList(); var dataScopeIdentifiers = new List<DataScopeIdentifier>(); foreach (DataScopeAttribute attribute in attributes) { if (dataScopeIdentifiers.Contains(attribute.Identifier) == false) { dataScopeIdentifiers.Add(attribute.Identifier); } } return dataScopeIdentifiers; } public static DefaultValue GetDefaultValue(PropertyInfo propertyInfo) { List<DefaultFieldValueAttribute> defaultValueAttributes = propertyInfo.GetCustomAttributesRecursively<DefaultFieldValueAttribute>().ToList(); if (defaultValueAttributes.Count > 1) throw new InvalidOperationException(string.Format("The field '{0}' on the interface '{1}' may only have zero or one default value attribute", propertyInfo.Name, propertyInfo.DeclaringType)); if (defaultValueAttributes.Count == 0) return null; return defaultValueAttributes[0].GetDefaultValue(); } public static string[] GetSortOrder(Type interfaceType) { List<StoreSortOrderAttribute> attributes = interfaceType.GetCustomInterfaceAttributes<StoreSortOrderAttribute>().ToList(); if (attributes.Count == 0) return null; return attributes[0].SortOrder; } public static bool IsNullable(PropertyInfo fieldInfo) { object[] storeFieldTypeAttributes = fieldInfo.GetCustomAttributes(typeof(StoreFieldTypeAttribute), false); if (storeFieldTypeAttributes.Length == 0) throw new InvalidOperationException("Missing PhysicalStoreFieldTypeAttribute on field " + fieldInfo.Name); var storeAttribute = (StoreFieldTypeAttribute)storeFieldTypeAttributes[0]; return storeAttribute.IsNullable; } public static bool IsKeyField(PropertyInfo fieldInfo) { List<KeyPropertyNameAttribute> typeKeys = fieldInfo.DeclaringType.GetCustomInterfaceAttributes<KeyPropertyNameAttribute>().ToList(); int thisPropertyMatchCount = typeKeys.Count(f => f.KeyPropertyName == fieldInfo.Name); Verify.That(thisPropertyMatchCount < 2, "{0} contains multiple {1} declarations with the property name '{2}'", fieldInfo.MemberType, typeof(KeyPropertyNameAttribute), fieldInfo.Name); return thisPropertyMatchCount == 1; } public static string ForeignKeyReferenceTypeName(PropertyInfo propertyInfo) { object[] attributes = propertyInfo.GetCustomAttributes(typeof(ForeignKeyAttribute), false); if (attributes.Length == 0) return null; return TypeManager.SerializeType(((ForeignKeyAttribute)attributes[0]).InterfaceType); } public static string NewInstanceDefaultFieldValue(PropertyInfo propertyInfo) { var attribute = GetCustomAttribute<FunctionBasedNewInstanceDefaultFieldValueAttribute>(propertyInfo); return attribute != null ? attribute.FunctionDescription : null; } public static List<DataTypeAssociationDescriptor> GetDataTypeAssociationDescriptors(Type interfaceType) { var result = new List<DataTypeAssociationDescriptor>(); var attributes = interfaceType.GetCustomAttributes(typeof(DataAssociationAttribute), false).OfType<DataAssociationAttribute>().ToList(); foreach (DataAssociationAttribute attribute in attributes) { var dataTypeAssociationDescriptor = new DataTypeAssociationDescriptor(attribute.AssociatedInterfaceType, attribute.ForeignKeyPropertyName, attribute.AssociationType); if (!result.Contains(dataTypeAssociationDescriptor)) { result.Add(dataTypeAssociationDescriptor); } } return result; } public static List<DataTypeAssociationDescriptor> GetDataTypeAssociationDescriptorsRecursively(Type interfaceType) { var result = new List<DataTypeAssociationDescriptor>(); List<DataAssociationAttribute> attributes = interfaceType.GetCustomAttributesRecursively<DataAssociationAttribute>().ToList(); foreach (DataAssociationAttribute attribute in attributes) { var dataTypeAssociationDescriptor = new DataTypeAssociationDescriptor(attribute.AssociatedInterfaceType, attribute.ForeignKeyPropertyName, attribute.AssociationType); if (!result.Contains(dataTypeAssociationDescriptor)) { result.Add(dataTypeAssociationDescriptor); } } return result; } /// <summary> /// If no BuildNewHandlerAttribute is used on the data type interface /// null is returned. /// </summary> /// <returns></returns> public static Type GetBuildNewHandlerType(Type interfaceType) { var attributes = interfaceType.GetCustomAttributesRecursively<BuildNewHandlerAttribute>().Evaluate(); if (!attributes.Any()) return null; if (attributes.Count() > 1) throw new InvalidOperationException(string.Format("Only one '{0}' allowed on the interface '{1}'", typeof(BuildNewHandlerAttribute).FullName, interfaceType.FullName)); return attributes.Single().BuildNewHandlerType; } } } ================================================ FILE: Composite/Data/DynamicTypes/Foundation/DynamicTypesAlternateFormFacade.cs ================================================ using System; using System.Linq; using System.Xml.Linq; using Composite.Data.Types; namespace Composite.Data.DynamicTypes.Foundation { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("User DynamicTypesCustomFormFacade instead")] public static class DynamicTypesAlternateFormFacade { /// <summary> /// Returns null if no alternate form exists. /// </summary> /// <exclude /> public static string GetAlternateFormMarkup(DataTypeDescriptor dataTypeDescriptor) { var file = GetAlternateFormMarkupFile(dataTypeDescriptor.Namespace, dataTypeDescriptor.Name); return file != null ? file.ReadAllText() : null; } internal static IFile GetAlternateFormMarkupFile(string @namespace, string typeName) { string dynamicDataFormFolderPath = GetFolderPath(@namespace); string dynamicDataFormFileName = GetFilename(typeName); IDynamicTypeFormDefinitionFile formOverride = DataFacade.GetData<IDynamicTypeFormDefinitionFile>() .FirstOrDefault(f => f.FolderPath.Equals(dynamicDataFormFolderPath, StringComparison.OrdinalIgnoreCase) && f.FileName.Equals(dynamicDataFormFileName, StringComparison.OrdinalIgnoreCase)); return formOverride; } /// <exclude /> public static void SetAlternateForm(DataTypeDescriptor dataTypeDescriptor, string newFormMarkup) { string dynamicDataFormFolderPath = GetFolderPath(dataTypeDescriptor.Namespace); string dynamicDataFormFileName = GetFilename(dataTypeDescriptor.Name); // Parsing for assertion XDocument.Parse(newFormMarkup); IDynamicTypeFormDefinitionFile formDefinitionFile = DataFacade.GetData<IDynamicTypeFormDefinitionFile>() .FirstOrDefault(f => f.FolderPath.Equals(dynamicDataFormFolderPath, StringComparison.OrdinalIgnoreCase) && f.FileName.Equals(dynamicDataFormFileName, StringComparison.OrdinalIgnoreCase)); if (formDefinitionFile == null) { var newFile = DataFacade.BuildNew<IDynamicTypeFormDefinitionFile>(); newFile.FolderPath = dynamicDataFormFolderPath; newFile.FileName = dynamicDataFormFileName; newFile.SetNewContent(newFormMarkup); formDefinitionFile = DataFacade.AddNew<IDynamicTypeFormDefinitionFile>(newFile); } else { formDefinitionFile.SetNewContent(newFormMarkup); DataFacade.Update(formDefinitionFile); } } private static string GetFilename(string typeName) { return string.Format("{0}.xml", typeName); } private static string GetFolderPath(string @namespace) { return "\\" + @namespace.Replace('.', '\\'); } } } ================================================ FILE: Composite/Data/DynamicTypes/Foundation/DynamicTypesCustomFormFacade.cs ================================================ using System; using System.Linq; using System.Xml.Linq; using Composite.Core.Xml; using Composite.Data.Types; using Composite.Plugins.Data.DataProviders.FileSystemDataProvider.Foundation; namespace Composite.Data.DynamicTypes.Foundation { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DynamicTypesCustomFormFacade { /// <summary> /// Returns custom form markup. /// </summary> /// <param name="dataTypeDescriptor">A data type descriptor</param> /// <returns></returns> public static XDocument GetCustomFormMarkup(DataTypeDescriptor dataTypeDescriptor) { var file = GetCustomFormMarkupFile(dataTypeDescriptor.Namespace, dataTypeDescriptor.Name); if (file == null) { return null; } var markupFilePath = (file as FileSystemFile).SystemPath; return XDocumentUtils.Load(markupFilePath, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo); } internal static IFile GetCustomFormMarkupFile(string @namespace, string typeName) { string dynamicDataFormFolderPath = GetFolderPath(@namespace); string dynamicDataFormFileName = GetFilename(typeName); IDynamicTypeFormDefinitionFile formOverride = DataFacade.GetData<IDynamicTypeFormDefinitionFile>() .FirstOrDefault(f => f.FolderPath.Equals(dynamicDataFormFolderPath, StringComparison.OrdinalIgnoreCase) && f.FileName.Equals(dynamicDataFormFileName, StringComparison.OrdinalIgnoreCase)); return formOverride; } /// <exclude /> public static void SetCustomForm(DataTypeDescriptor dataTypeDescriptor, string newFormMarkup) { string dynamicDataFormFolderPath = GetFolderPath(dataTypeDescriptor.Namespace); string dynamicDataFormFileName = GetFilename(dataTypeDescriptor.Name); // Parsing for assertion XDocument.Parse(newFormMarkup); IDynamicTypeFormDefinitionFile formDefinitionFile = DataFacade.GetData<IDynamicTypeFormDefinitionFile>() .FirstOrDefault(f => f.FolderPath.Equals(dynamicDataFormFolderPath, StringComparison.OrdinalIgnoreCase) && f.FileName.Equals(dynamicDataFormFileName, StringComparison.OrdinalIgnoreCase)); if (formDefinitionFile == null) { var newFile = DataFacade.BuildNew<IDynamicTypeFormDefinitionFile>(); newFile.FolderPath = dynamicDataFormFolderPath; newFile.FileName = dynamicDataFormFileName; newFile.SetNewContent(newFormMarkup); formDefinitionFile = DataFacade.AddNew<IDynamicTypeFormDefinitionFile>(newFile); } else { formDefinitionFile.SetNewContent(newFormMarkup); DataFacade.Update(formDefinitionFile); } } private static string GetFilename(string typeName) { return string.Format("{0}.xml", typeName); } private static string GetFolderPath(string @namespace) { return "\\" + @namespace.Replace('.', '\\'); } } } ================================================ FILE: Composite/Data/DynamicTypes/Foundation/ReflectionBasedDataTypeDescriptorBuilder.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.Core.Extensions; using Composite.Core.Types; namespace Composite.Data.DynamicTypes.Foundation { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ReflectionBasedDescriptorBuilder { /// <exclude /> public static DataTypeDescriptor Build(Type type) { Verify.ArgumentNotNull(type, "type"); Verify.ArgumentCondition(typeof(IData).IsAssignableFrom(type), "type", "{0} does not implement {1}".FormatWith(type.FullName, typeof(IData).FullName)); Guid dataTypeId = DynamicTypeReflectionFacade.GetImmutableTypeId(type); bool isCodeGenerated = type.GetCustomInterfaceAttributes<CodeGeneratedAttribute>().Any(); var typeDescriptor = new DataTypeDescriptor(dataTypeId, type.Namespace, type.Name, TypeManager.SerializeType(type), isCodeGenerated) { Title = DynamicTypeReflectionFacade.GetTitle(type), LabelFieldName = DynamicTypeReflectionFacade.GetLabelPropertyName(type), InternalUrlPrefix = DynamicTypeReflectionFacade.GetInternalUrlPrefix(type), DataAssociations = DynamicTypeReflectionFacade.GetDataTypeAssociationDescriptors(type) }; List<Type> superInterfaces = type.GetInterfacesRecursively(t => typeof(IData).IsAssignableFrom(t) && t != typeof(IData)); typeDescriptor.SetSuperInterfaces(superInterfaces); Type buildNewHandlerType = DynamicTypeReflectionFacade.GetBuildNewHandlerType(type); if (buildNewHandlerType != null) typeDescriptor.BuildNewHandlerTypeName = TypeManager.SerializeType(buildNewHandlerType); foreach (PropertyInfo propertyInfo in type.GetProperties()) { DataFieldDescriptor fieldDescriptor = BuildFieldDescriptor(propertyInfo, false); typeDescriptor.Fields.Add(fieldDescriptor); } foreach (Type superInterfaceType in superInterfaces) { foreach (PropertyInfo propertyInfo in superInterfaceType.GetProperties()) { if (propertyInfo.Name == nameof(IPageData.PageId) && propertyInfo.DeclaringType == typeof(IPageData)) { continue; } DataFieldDescriptor fieldDescriptor = BuildFieldDescriptor(propertyInfo, true); typeDescriptor.Fields.Add(fieldDescriptor); } } ValidateAndAddKeyProperties(typeDescriptor.KeyPropertyNames, typeDescriptor.VersionKeyPropertyNames, type); string[] storeSortOrder = DynamicTypeReflectionFacade.GetSortOrder(type); if (storeSortOrder != null) { foreach (string name in storeSortOrder) { typeDescriptor.StoreSortOrderFieldNames.Add(name); } } CheckSortOrder(typeDescriptor); foreach (var dataScopeIdentifier in DynamicTypeReflectionFacade.GetDataScopes(type)) { if (!typeDescriptor.DataScopes.Contains(dataScopeIdentifier)) { typeDescriptor.DataScopes.Add(dataScopeIdentifier); } } foreach (string keyPropertyName in type.GetKeyPropertyNames()) { if (typeDescriptor.Fields[keyPropertyName] == null) { throw new InvalidOperationException( $"The type '{type}' has a non existing key property specified by the attribute '{typeof (KeyPropertyNameAttribute)}'"); } } var indexes = new List<DataTypeIndex>(); foreach (var indexAttribute in type.GetCustomAttributesRecursively<IndexAttribute>()) { foreach (var field in indexAttribute.Fields) { if (typeDescriptor.Fields[field.Item1] == null) { throw new InvalidOperationException($"Index field '{field.Item1}' is not defined"); } } indexes.Add(new DataTypeIndex(indexAttribute.Fields) { Clustered = indexAttribute.Clustered }); } indexes.Sort((a,b) => string.Compare(a.ToString(), b.ToString(), StringComparison.Ordinal)); typeDescriptor.Indexes = indexes; return typeDescriptor; } static void ValidateAndAddKeyProperties( DataFieldNameCollection keyProperties, DataFieldNameCollection versionKeyProperties, Type interfaceType) { foreach (string propertyName in interfaceType.GetKeyPropertyNames()) { PropertyInfo property = FindProperty(interfaceType, propertyName); if (DynamicTypeReflectionFacade.IsKeyField(property)) { keyProperties.Add(propertyName, false); } } foreach (string propertyName in interfaceType.GetVersionKeyPropertyNames()) { FindProperty(interfaceType, propertyName); versionKeyProperties.Add(propertyName, false); } } internal static PropertyInfo FindProperty(Type interfaceType, string propertyName) { PropertyInfo property = interfaceType.GetProperty(propertyName); if (property == null) { List<Type> superInterfaces = interfaceType.GetInterfacesRecursively(t => typeof(IData).IsAssignableFrom(t) && t != typeof(IData)); foreach (Type superInterface in superInterfaces) { property = superInterface.GetProperty(propertyName); if (property != null) break; } } Verify.IsNotNull(property, $"Missing property '{propertyName}' on type '{interfaceType}' or one of its interfaces"); return property; } internal static DataFieldDescriptor BuildFieldDescriptor(PropertyInfo propertyInfo, bool inherited) { string fieldName = propertyInfo.Name; Type fieldType = propertyInfo.PropertyType; Guid fieldId = DynamicTypeReflectionFacade.GetImmutableFieldId(propertyInfo); StoreFieldType storeFieldType = DynamicTypeReflectionFacade.GetStoreFieldType(propertyInfo); var fieldDescriptor = new DataFieldDescriptor(fieldId, fieldName, storeFieldType, fieldType, inherited) { DefaultValue = DynamicTypeReflectionFacade.GetDefaultValue(propertyInfo), IsNullable = DynamicTypeReflectionFacade.IsNullable(propertyInfo), ForeignKeyReferenceTypeName = DynamicTypeReflectionFacade.ForeignKeyReferenceTypeName(propertyInfo), GroupByPriority = DynamicTypeReflectionFacade.GetGroupByPriority(propertyInfo), TreeOrderingProfile = DynamicTypeReflectionFacade.GetTreeOrderingProfile(propertyInfo), NewInstanceDefaultFieldValue = DynamicTypeReflectionFacade.NewInstanceDefaultFieldValue(propertyInfo), IsReadOnly = !propertyInfo.CanWrite }; var formRenderingProfile = DynamicTypeReflectionFacade.GetFormRenderingProfile(propertyInfo); if (formRenderingProfile != null) { fieldDescriptor.FormRenderingProfile = formRenderingProfile; } // These auto added widget functions does not work on a empty system. // This code could have added widgets for data types that does not have any widgets attached to them //WidgetFunctionProvider widgetFunctionProvider = GetWidgetFunctionMarkup(propertyInfo.PropertyType); //if (widgetFunctionProvider != null) //{ // LazyDataFieldFormRenderingProfile lazyDataFieldFormRenderingProfile = new LazyDataFieldFormRenderingProfile(); // lazyDataFieldFormRenderingProfile.Label = propertyInfo.Name; // lazyDataFieldFormRenderingProfile.HelpText = propertyInfo.Name; // lazyDataFieldFormRenderingProfile.WidgetFunctionMarkupFunc = () => widgetFunctionProvider.SerializedWidgetFunction.ToString(); // fieldDescriptor.FormRenderingProfile = lazyDataFieldFormRenderingProfile; //} int position; fieldDescriptor.Position = DynamicTypeReflectionFacade.TryGetFieldPosition(propertyInfo, out position) ? position : 1000; return fieldDescriptor; } //private static WidgetFunctionProvider GetWidgetFunctionMarkup(Type propertyType) //{ // if (propertyType == typeof(string)) // { // return StandardWidgetFunctions.TextBoxWidget; // } // if (propertyType == typeof(Guid)) // { // return StandardWidgetFunctions.GuidTextBoxWidget; // } // if (propertyType == typeof(int)) // { // return StandardWidgetFunctions.IntegerTextBoxWidget; // } // if (propertyType == typeof(DateTime)) // { // return StandardWidgetFunctions.DateTimeSelectorWidget; // } // if (propertyType == typeof(decimal)) // { // return StandardWidgetFunctions.DecimalTextBoxWidget; // } // return null; //} private static void CheckSortOrder(DataTypeDescriptor typeDescriptor) { if (typeDescriptor.StoreSortOrderFieldNames.Count == 0) return; if (typeDescriptor.StoreSortOrderFieldNames.Count != typeDescriptor.Fields.Count) { throw new InvalidOperationException("The store sort order attribute should list all the fields of the interface"); } } } } ================================================ FILE: Composite/Data/DynamicTypes/IDynamicTypeManager.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; namespace Composite.Data.DynamicTypes { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IDynamicTypeManager { /// <exclude /> DataTypeDescriptor BuildNewDataTypeDescriptor(Type typeToDescript); /// <exclude /> bool TryGetDataTypeDescriptor(Guid immutableTypeId, out DataTypeDescriptor dataTypeDescriptor); /// <exclude /> void UpdateDataTypeDescriptor(DataTypeDescriptor dataTypeDescriptor, bool flushTheSystem); /// <exclude /> void CreateStores(string providerName, IReadOnlyCollection<DataTypeDescriptor> typeDescriptor, bool doFlush); /// <exclude /> void AlterStore(UpdateDataTypeDescriptor updateDataTypeDescriptor, bool makeAFlush); /// <exclude /> void DropStore(string providerName, DataTypeDescriptor typeDescriptor, bool makeAFlush); /// <exclude /> void AddLocale(string providerName, CultureInfo cultureInfo); /// <exclude /> void RemoveLocale(string providerName, CultureInfo cultureInfo); } } ================================================ FILE: Composite/Data/DynamicTypes/NameValidation.cs ================================================ using System; using System.Globalization; using System.Linq; using Composite.Core.ResourceSystem; namespace Composite.Data.DynamicTypes { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class NameValidation { /// <exclude /> public static string ValidateNamespace(string namespaceString) { string errorMessage; if (TryValidateNamespace(namespaceString, out errorMessage) == false) { throw new ArgumentException(errorMessage); } return namespaceString; } /// <exclude /> public static bool TryValidateNamespace(string namespaceString) { string errorMessage; return TryValidateNamespace(namespaceString, out errorMessage); } /// <exclude /> public static bool TryValidateNamespace(string namespaceString, out string errorMessage) { errorMessage = ""; if (string.IsNullOrEmpty(namespaceString)) { errorMessage = StringResourceSystemFacade.GetString("Composite.NameValidation", "EmptyNamespace"); return false; } string[] namespaceElements = namespaceString.Split('.'); foreach (string namespaceElement in namespaceElements) { if (NameValidation.TryValidateName(namespaceElement, out errorMessage) == false) { return false; } } if (namespaceElements.Distinct().Count() < namespaceElements.Count()) { errorMessage = StringResourceSystemFacade.GetString("Composite.NameValidation", "DuplicateElementNamespace"); return false; } return true; } /// <summary> /// Returns the name if all characters are valid in a type and field name. Invalid characters generate an exception. /// </summary> /// <param name="name">The name to validate</param> /// <returns>The name that was validated</returns> public static string ValidateName(string name) { string errorMessage; if (TryValidateName(name, out errorMessage) == false) { throw new ArgumentException(errorMessage); } return name; } /// <exclude /> public static bool TryValidateName(string name) { string errorMessage; return TryValidateName(name, out errorMessage); } /// <exclude /> public static bool TryValidateName(string name, out string errorMessage) { errorMessage = ""; if (string.IsNullOrEmpty(name)) { errorMessage = StringResourceSystemFacade.GetString("Composite.NameValidation", "EmptyName"); return false; } for (int i = 0; i < name.Length; i++) { char ch = name[i]; UnicodeCategory uc = Char.GetUnicodeCategory(ch); if (ch > 127) { errorMessage = string.Format(StringResourceSystemFacade.GetString("Composite.NameValidation", "InvalidIdentifier"), name); return false; } if (i == 0 && uc == UnicodeCategory.DecimalDigitNumber) { errorMessage = string.Format(StringResourceSystemFacade.GetString("Composite.NameValidation", "InvalidIdentifierDigit"), name); return false; } switch (uc) { case UnicodeCategory.UppercaseLetter: case UnicodeCategory.LowercaseLetter: case UnicodeCategory.TitlecaseLetter: case UnicodeCategory.DecimalDigitNumber: break; default: if (ch == 95) break; errorMessage = string.Format(StringResourceSystemFacade.GetString("Composite.NameValidation", "InvalidIdentifier"), name); return false; } } return true; } } } ================================================ FILE: Composite/Data/DynamicTypes/ParseDefinitionFileException.cs ================================================ using System; using System.Xml; using System.Xml.Linq; namespace Composite.Data.DynamicTypes { [Serializable] internal class ParseDefinitionFileException : Exception { private readonly XObject _source; public ParseDefinitionFileException(string message, XObject source) : base(GetMessage(message, source)) { _source = source; Line = (source as IXmlLineInfo).LineNumber; Position = (source as IXmlLineInfo).LinePosition; } public override string Source { get { return _source.BaseUri; } } public int Line { get; private set; } public int Position { get; private set; } private static string GetMessage(string message, XObject source) { var lineInfo = source as IXmlLineInfo; return string.Format("{0} ({1}:{2}): {3}", source.BaseUri, lineInfo.LineNumber, lineInfo.LinePosition, message); } } } ================================================ FILE: Composite/Data/DynamicTypes/SearchProfile.cs ================================================ using System; using System.CodeDom; namespace Composite.Data.DynamicTypes { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public class SearchProfile { /// <exclude /> public bool IndexText { get; set; } /// <exclude /> public bool EnablePreview { get; set; } /// <exclude /> public bool IsFacet { get; set; } /// <exclude /> public SearchProfile Clone() { return new SearchProfile { IndexText = IndexText, EnablePreview = EnablePreview, IsFacet = IsFacet }; } /// <exclude /> internal CodeAttributeDeclaration GetCodeAttributeDeclaration() { if (!IndexText && !EnablePreview && !IsFacet) { return null; } return new CodeAttributeDeclaration( typeof(SearchableFieldAttribute).FullName, new CodeAttributeArgument(new CodePrimitiveExpression(IndexText)), new CodeAttributeArgument(new CodePrimitiveExpression(EnablePreview)), new CodeAttributeArgument(new CodePrimitiveExpression(IsFacet))); } } } ================================================ FILE: Composite/Data/DynamicTypes/StoreFieldType.cs ================================================ using System; using System.Collections.Generic; using System.Text; using Composite.Core.Instrumentation; using Composite.Core.Serialization; namespace Composite.Data.DynamicTypes { /// <summary> /// Describe a field on a C1 CMS data type, see <see cref="DataTypeDescriptor"/>. /// </summary> [Serializable()] public sealed class StoreFieldType { private int? _maximumLength; private int? _numericPrecision; private int? _numericScale; /// <summary>The maximum number of characters allowed in a string (2048). For larger strings use the LargeString type.</summary> public static int StringMaximumLength { get { return 2048; } } /// <summary>The maximum number of digits a decimal may contain (28).</summary> public static int NumericPrecisionMaximum { get { return 28; } } /// <summary> /// Builds a <see cref="StoreFieldType"/> describing a string. /// </summary> /// <param name="maximumLength">String maximum length</param> /// <returns></returns> public static StoreFieldType String(int maximumLength) { return new StoreFieldType(PhysicalStoreFieldType.String, maximumLength); } /// <summary> /// Builds a <see cref="StoreFieldType"/> describing a int. /// </summary> public static StoreFieldType Integer { get { return new StoreFieldType(PhysicalStoreFieldType.Integer); } } /// <summary> /// Builds a <see cref="StoreFieldType"/> describing a long. /// </summary> public static StoreFieldType Long { get { return new StoreFieldType(PhysicalStoreFieldType.Long); } } /// <summary> /// Builds a <see cref="StoreFieldType"/> describing a decimal. /// </summary> /// <param name="precision">precision</param> /// <param name="scale">scale</param> /// <returns></returns> public static StoreFieldType Decimal(int precision, int scale) { return new StoreFieldType(PhysicalStoreFieldType.Decimal, precision, scale); } /// <summary> /// Builds a <see cref="StoreFieldType"/> describing a DateTime. /// </summary> public static StoreFieldType DateTime { get { return new StoreFieldType(PhysicalStoreFieldType.DateTime); } } /// <summary> /// Builds a <see cref="StoreFieldType"/> describing a string with unlimited length. /// </summary> public static StoreFieldType LargeString { get { return new StoreFieldType(PhysicalStoreFieldType.LargeString); } } /// <summary> /// Builds a <see cref="StoreFieldType"/> describing a bool. /// </summary> public static StoreFieldType Boolean { get { return new StoreFieldType(PhysicalStoreFieldType.Boolean); } } /// <summary> /// Builds a <see cref="StoreFieldType"/> describing a Guid. /// </summary> public static StoreFieldType Guid { get { return new StoreFieldType(PhysicalStoreFieldType.Guid); } } /// <summary> /// The type of physical store for this field /// </summary> public PhysicalStoreFieldType PhysicalStoreType { get; private set; } /// <summary> /// True when this field is a string. /// </summary> public bool IsString { get { return this.PhysicalStoreType == PhysicalStoreFieldType.String || this.PhysicalStoreType == PhysicalStoreFieldType.LargeString; } } /// <summary> /// True when this field is a string of unlimited length. /// </summary> public bool IsLargeString { get { return this.PhysicalStoreType == PhysicalStoreFieldType.LargeString; } } /// <summary> /// True when this field is a decimal. /// </summary> public bool IsDecimal { get { return this.PhysicalStoreType == PhysicalStoreFieldType.Decimal; } } /// <summary> /// True when this field is a DateTime. /// </summary> public bool IsDateTime { get { return this.PhysicalStoreType == PhysicalStoreFieldType.DateTime; } } /// <summary> /// True when this field is a Guid. /// </summary> public bool IsGuid { get { return this.PhysicalStoreType == PhysicalStoreFieldType.Guid; } } /// <exclude /> public bool IsNumeric { get { return this.PhysicalStoreType == PhysicalStoreFieldType.Decimal || this.PhysicalStoreType == PhysicalStoreFieldType.Long || this.PhysicalStoreType == PhysicalStoreFieldType.Integer; } } /// <summary> /// True when this field is a boolean. /// </summary> public bool IsBoolean { get { return this.PhysicalStoreType == PhysicalStoreFieldType.Boolean; } } /// <summary> /// Maximum length of string. This field is only used for string. /// </summary> public int MaximumLength { get { if (_maximumLength.HasValue) { return _maximumLength.Value; } else { throw new InvalidOperationException("The maximum length is not valid for this store field type"); } } private set { _maximumLength = value; } } /// <summary> /// Numeric precision of decimal. This field is only used for decimal. /// </summary> public int NumericPrecision { get { if (_numericPrecision.HasValue) { return _numericPrecision.Value; } else { throw new InvalidOperationException("The numeric precision is not valid for this store field type"); } } private set { _numericPrecision = value; } } /// <summary> /// Numeric scale of decimal. This field is only used for decimal. /// </summary> public int NumericScale { get { if (_numericScale.HasValue) { return _numericScale.Value; } else { throw new InvalidOperationException("The numeric scale is not valid for this store field type"); } } private set { _numericScale = value; } } /// <summary> /// Evaluate if one field type can safely change to another type. /// </summary> /// <param name="newStoreFieldType">New store field type</param> /// <returns>True is conversion is allowed.</returns> public bool IsConvertibleTo(StoreFieldType newStoreFieldType) { if (this.PhysicalStoreType == newStoreFieldType.PhysicalStoreType) return true; if (this.IsNumeric && newStoreFieldType.IsDecimal) return true; // String and LargeString are convertable to each other if ((PhysicalStoreType == PhysicalStoreFieldType.String && newStoreFieldType.PhysicalStoreType == PhysicalStoreFieldType.LargeString) || (newStoreFieldType.PhysicalStoreType == PhysicalStoreFieldType.String && PhysicalStoreType == PhysicalStoreFieldType.LargeString)) { return true; } return false; } /// <exclude /> public override string ToString() { switch (this.PhysicalStoreType) { case PhysicalStoreFieldType.Integer: case PhysicalStoreFieldType.Long: case PhysicalStoreFieldType.LargeString: case PhysicalStoreFieldType.DateTime: case PhysicalStoreFieldType.Guid: case PhysicalStoreFieldType.Boolean: return this.PhysicalStoreType.ToString(); case PhysicalStoreFieldType.String: return string.Format("{0}({1})", this.PhysicalStoreType, this.MaximumLength); case PhysicalStoreFieldType.Decimal: return string.Format("{0}({1},{2})", this.PhysicalStoreType, this.NumericPrecision, this.NumericScale); } throw new NotImplementedException(); } /// <exclude /> public string Serialize() { StringBuilder sb = new StringBuilder(); StringConversionServices.SerializeKeyValuePair(sb, "PhysicalStoreType", this.PhysicalStoreType.ToString()); switch (this.PhysicalStoreType) { case PhysicalStoreFieldType.String: StringConversionServices.SerializeKeyValuePair(sb, "Length", this.MaximumLength); break; case PhysicalStoreFieldType.Decimal: StringConversionServices.SerializeKeyValuePair(sb, "Precision", this.NumericPrecision); StringConversionServices.SerializeKeyValuePair(sb, "Scale", this.NumericScale); break; } return sb.ToString(); } /// <exclude /> public static StoreFieldType Deserialize(string serializedData) { using (TimerProfiler timerProfiler = TimerProfilerFacade.CreateTimerProfiler()) { if (string.IsNullOrEmpty(serializedData)) throw new ArgumentNullException("serializedData"); Dictionary<string, string> dic = StringConversionServices.ParseKeyValueCollection(serializedData); if (dic.ContainsKey("PhysicalStoreType") == false) throw new ArgumentException("Wrong serialized format"); string physicalStoreFieldTypeString = StringConversionServices.DeserializeValue<string>(dic["PhysicalStoreType"]); PhysicalStoreFieldType physicalStoreFieldType = (PhysicalStoreFieldType)Enum.Parse(typeof(PhysicalStoreFieldType), physicalStoreFieldTypeString); switch (physicalStoreFieldType) { case PhysicalStoreFieldType.String: if (dic.ContainsKey("Length") == false) throw new ArgumentException("Wrong serialized format"); int length = StringConversionServices.DeserializeValueInt(dic["Length"]); return new StoreFieldType(physicalStoreFieldType, length); case PhysicalStoreFieldType.Decimal: if (dic.ContainsKey("Precision") == false) throw new ArgumentException("Wrong serialized format"); if (dic.ContainsKey("Scale") == false) throw new ArgumentException("Wrong serialized format"); int precision = StringConversionServices.DeserializeValueInt(dic["Precision"]); int scale = StringConversionServices.DeserializeValueInt(dic["Scale"]); return new StoreFieldType(physicalStoreFieldType, precision, scale); case PhysicalStoreFieldType.Boolean: case PhysicalStoreFieldType.DateTime: case PhysicalStoreFieldType.Guid: case PhysicalStoreFieldType.Integer: case PhysicalStoreFieldType.LargeString: case PhysicalStoreFieldType.Long: return new StoreFieldType(physicalStoreFieldType); } throw new NotImplementedException(); } } private StoreFieldType(PhysicalStoreFieldType storeType) { this.PhysicalStoreType = storeType; if (storeType == PhysicalStoreFieldType.LargeString) this.MaximumLength = int.MaxValue; } private StoreFieldType(PhysicalStoreFieldType storeType, int precision, int scale) { switch (storeType) { case PhysicalStoreFieldType.Decimal: if (precision < 1) throw new ArgumentException("Precision must be 1 or greater"); if (precision > NumericPrecisionMaximum) throw new ArgumentException("Precision may not be greater than " + NumericPrecisionMaximum.ToString()); if (scale < 0) throw new ArgumentException("Scale must be 0 or greater"); if (scale > precision) throw new ArgumentException("Scale can not be larger than precision"); this.PhysicalStoreType = storeType; this.NumericPrecision = precision; this.NumericScale = scale; return; } throw new ArgumentException("Specified PhysicalStoreType is not associated with a presision and scale"); } private StoreFieldType(PhysicalStoreFieldType storeType, int maxLength) { switch (storeType) { case PhysicalStoreFieldType.String: if (maxLength < 1) throw new ArgumentException("Maximum lenght must be 1 or greater", "maxLength"); if (maxLength > StringMaximumLength) throw new ArgumentException("Maximum lenght must be 2048 or less", "maxLength"); this.PhysicalStoreType = storeType; this.MaximumLength = maxLength; return; } throw new ArgumentException("Specified PhysicalStoreType is not associated with a maximum length"); } } } ================================================ FILE: Composite/Data/DynamicTypes/TypeUpdateVersionException.cs ================================================ using System; namespace Composite.Data.DynamicTypes { internal sealed class TypeUpdateVersionException : Exception { public TypeUpdateVersionException(string message) : base(message) { } } } ================================================ FILE: Composite/Data/DynamicTypes/UpdateDataTypeDescriptor.cs ================================================ using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using Composite.Data.Foundation; using Composite.Data.ProcessControlled; using Composite.Core.Linq; namespace Composite.Data.DynamicTypes { /// <summary> /// This is a helper class to use when making changes to a data type descriptor. /// It is mainly used by data providers when they have to update the under laying stores. /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] public class UpdateDataTypeDescriptor { /// <summary> /// </summary> /// <param name="oldDataTypeDescriptor"></param> /// <param name="newDataTypeDescriptor"></param> /// <param name="originalTypeHasData"></param> public UpdateDataTypeDescriptor(DataTypeDescriptor oldDataTypeDescriptor, DataTypeDescriptor newDataTypeDescriptor, bool originalTypeHasData = true) { OldDataTypeDescriptor = oldDataTypeDescriptor; NewDataTypeDescriptor = newDataTypeDescriptor; var interfaceType = oldDataTypeDescriptor.GetInterfaceType(); ProviderName = interfaceType != null ? DataProviderRegistry.GetWriteableDataProviderNamesByInterfaceType(interfaceType) .SingleOrException("Failed to get data provider by type '{0}'", "Multiple data providers for type '{0}'", interfaceType.FullName) : DataProviderRegistry.DefaultDynamicTypeDataProviderName; } internal UpdateDataTypeDescriptor(DataTypeDescriptor oldDataTypeDescriptor, DataTypeDescriptor newDataTypeDescriptor, string providerName) { OldDataTypeDescriptor = oldDataTypeDescriptor; NewDataTypeDescriptor = newDataTypeDescriptor; ProviderName = providerName; } /// <summary> /// </summary> public DataTypeDescriptor OldDataTypeDescriptor { get; private set; } /// <summary> /// </summary> public DataTypeDescriptor NewDataTypeDescriptor { get; private set; } /// <summary> /// </summary> public DataTypeChangeDescriptor CreateDataTypeChangeDescriptor() { return new DataTypeChangeDescriptor(OldDataTypeDescriptor, NewDataTypeDescriptor, OriginalTypeHasData); } /// <summary> /// If this is true, extra validation on what things are changed on /// the data type. Some operation are not allowed if data exists. /// </summary> public bool OriginalTypeHasData { get; set; } /// <summary> /// </summary> public string ProviderName { get; set; } /// <summary> /// This is only used when enabling localization for the data type in question /// If this empty or contains any cultues, data from existing locale(s) (published/unpublished) /// will be copied to these locales. /// </summary> public IEnumerable<CultureInfo> LocalesToCopyTo { get; set; } /// <summary> /// This is only used when disabling localization for the data type in question /// Data from this locale (published/unpublished) will be copied to the non-localized store(s). /// </summary> public CultureInfo LocaleToCopyFrom { get; set; } /// <summary> /// </summary> public IEnumerable<DataScopeIdentifier> OldSupportedDataScopeIdentifiers { get { yield return DataScopeIdentifier.Administrated; if (OldDataTypeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled))) yield return DataScopeIdentifier.Public; } } /// <summary> /// This is true if publication is added from the data type (IPublishControlled added). /// </summary> public bool PublicationAdded { get { return (OldDataTypeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled)) == false) && (NewDataTypeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled))); } } /// <summary> /// This is true if publication is removed from the data type (IPublishControlled removed). /// </summary> public bool PublicationRemoved { get { return (OldDataTypeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled))) && (NewDataTypeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled)) == false); } } /// <summary> /// This is true if the new data type description has publication. /// </summary> public bool NewHasPublication { get { return NewDataTypeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled)); } } } } ================================================ FILE: Composite/Data/FieldPositionAttribute.cs ================================================ using System; namespace Composite.Data { /// <summary> /// Specify the posution of a field as they should be listed by default /// </summary> /// <example> This sample shows how to use the FieldPosition attribute. /// <code> /// // data interface attributes ... /// interface IMyDataType : IData /// { /// [StoreFieldType(PhysicalStoreFieldType.String, 64)] /// [ImmutableFieldId("{D75EA67F-AD14-4BAB-8547-6D87002709F3}")] /// [FieldPosition(1)] /// string Title { get; set; } /// /// // more data properties ... /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class FieldPositionAttribute : Attribute { /// <exclude /> public FieldPositionAttribute(int position) { this.Position = position; } /// <exclude /> public int Position { get; private set; } } } ================================================ FILE: Composite/Data/ForeignKeyAttribute.cs ================================================ using System; using Composite.Core.Types; namespace Composite.Data { /// <summary> /// The attribute will tell the system that a data property is a reference (foreign key) to another IData. /// </summary> /// <example> This sample shows how to use the ForeignKey attribute. /// <code> /// // data interface attributes ... /// interface IMyDataType : IData /// { /// [StoreFieldType(PhysicalStoreFieldType.Guid)] /// [ImmutableFieldId("{D75EA67F-AD14-4BAB-8547-6D87002809F2}")] /// [ForeignKey(typeof(IPage), "Id", AllowCascadeDeletes = true)] /// Guid PageId { get; set; } /// /// // more data properties ... /// /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class ForeignKeyAttribute : Attribute { private string _interfaceTypeManagerName; private Type _interfaceType; private string _keyPropertyName; private object _nullReferenceValue; private bool _isNullReferenceValueSet; private readonly object _lock = new object(); /// <summary> /// Tell the system that this data property is a reference (foreign key) to another IData. /// </summary> /// <param name="interfaceType">The type being referenced</param> /// <param name="keyPropertyName">The field being referenced</param> public ForeignKeyAttribute(Type interfaceType, string keyPropertyName) { _interfaceType = interfaceType; _keyPropertyName = keyPropertyName; } /// <summary> /// Only use this constructor for types that are registred with the DynamicTypeManager. Primary key field is infered. /// </summary> /// <param name="interfaceTypeManagerName">A string that will yield a type from the TypeManager.</param> public ForeignKeyAttribute(string interfaceTypeManagerName) { Verify.ArgumentNotNullOrEmpty(interfaceTypeManagerName, nameof(interfaceTypeManagerName)); _interfaceTypeManagerName = interfaceTypeManagerName; } /// <summary> /// If the "parent" data is deleted and this is set to true, then the data that /// refer to the parent is also deleted. /// </summary> public bool AllowCascadeDeletes { get; set; } /// <summary> /// This value is used when foreign key integrity is performed. /// If this is not set, the data that the foreign key is pointing to must always exists. /// </summary> public object NullReferenceValue { get { return _nullReferenceValue; } set { _nullReferenceValue = value; _isNullReferenceValueSet = true; } } /// <summary> /// The NullReferenceValue will be converted to the the type specifed with the property /// </summary> public Type NullReferenceValueType { get; set; } /// <summary> /// Use this if non-reference is allowed with strings foreign keys /// </summary> public bool NullableString { get; set; } /// <exclude /> public bool IsNullReferenceValueSet => _isNullReferenceValueSet; /// <exclude /> public Type InterfaceType { get { lock (_lock) { if (_interfaceType == null) { _interfaceType = TypeManager.GetType(_interfaceTypeManagerName); } } return _interfaceType; } } /// <exclude /> public bool IsValid { get { lock (_lock) { if (_interfaceType == null) { _interfaceType = TypeManager.TryGetType(_interfaceTypeManagerName); } } return _interfaceType != null; } } /// <exclude /> public string TypeManagerName { get { lock (_lock) { if (string.IsNullOrEmpty(_interfaceTypeManagerName)) { _interfaceTypeManagerName = TypeManager.TrySerializeType(_interfaceType); } } return _interfaceTypeManagerName; } } /// <exclude /> public string KeyPropertyName { get { if (_keyPropertyName == null) { lock (_lock) { if (_keyPropertyName == null) { _keyPropertyName = InterfaceType.GetSingleKeyProperty().Name; } } } return _keyPropertyName; } } } } ================================================ FILE: Composite/Data/ForeignPropertyInfo.cs ================================================ using Composite.Core.Types; using System; using System.Reflection; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ForeignPropertyInfo { internal ForeignPropertyInfo(PropertyInfo sourcePropertyInfo, Type targetType, string targetKeyPropertyName, bool allowCascadeDeletes, object nullReferenceValue, Type nullReferenceValueType, bool isNullableString) : this(sourcePropertyInfo, targetType, targetKeyPropertyName, allowCascadeDeletes, isNullableString) { this.NullReferenceValue = ValueTypeConverter.Convert( nullReferenceValue, sourcePropertyInfo.PropertyType); this.NullReferenceValueType = nullReferenceValueType; this.IsNullReferenceValueSet = true; } internal ForeignPropertyInfo(PropertyInfo sourcePropertyInfo, Type targetType, string targetKeyPropertyName, bool allowCascadeDeletes, bool isNullableString) { this.SourcePropertyName = sourcePropertyInfo.Name; this.SourcePropertyInfo = sourcePropertyInfo; this.TargetType = targetType; this.TargetKeyPropertyName = targetKeyPropertyName; this.AllowCascadeDeletes = allowCascadeDeletes; this.IsNullableString = isNullableString; } /// <exclude /> public string SourcePropertyName { get; private set; } internal PropertyInfo SourcePropertyInfo { get; private set; } /// <exclude /> public Type TargetType { get; private set; } /// <exclude /> public string TargetKeyPropertyName { get; private set; } /// <exclude /> public bool AllowCascadeDeletes { get; private set; } /// <exclude /> public object NullReferenceValue { get; private set; } /// <exclude /> public Type NullReferenceValueType { get; private set; } /// <exclude /> public bool IsNullReferenceValueSet { get; private set; } /// <exclude /> public bool IsNullableString { get; private set; } /// <exclude /> public bool IsOptionalReference { get { return IsNullableString || SourcePropertyInfo.PropertyType == typeof (Guid?); } } internal PropertyInfo TargetKeyPropertyInfo { get; set; } } } ================================================ FILE: Composite/Data/FormRenderingProfileAttribute.cs ================================================ using System; namespace Composite.Data { /// <summary> /// Assign this to properties on your IData interfaces to control how a data field whould be viewed and edited in a form view. /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public sealed class FormRenderingProfileAttribute : Attribute { /// <summary> /// Defines the field's label /// </summary> public string Label { get; set; } /// <summary> /// Defines the field's help text. /// </summary> public string HelpText { get; set; } /// <summary> /// Defines the widget function markup /// </summary> public string WidgetFunctionMarkup { get; set; } } } ================================================ FILE: Composite/Data/Foundation/CodeGeneratedAttribute.cs ================================================ using System; namespace Composite.Data.Foundation { [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = true)] internal sealed class CodeGeneratedAttribute : Attribute { public CodeGeneratedAttribute() { } } } ================================================ FILE: Composite/Data/Foundation/CodeGeneration/DataWrapperClassCodeProvider.cs ================================================ using Composite.Core; using Composite.Core.Types; using Composite.Data.DynamicTypes; namespace Composite.Data.Foundation.CodeGeneration { internal class DataWrapperClassCodeProvider : ICodeProvider { public void GetCodeToCompile(CodeGenerationBuilder builder) { foreach (DataTypeDescriptor dataTypeDescriptor in DataMetaDataFacade.AllDataTypeDescriptors) { if (!dataTypeDescriptor.ValidateRuntimeType()) { Log.LogError("DataWrapperClassCodeProvider", string.Format("The non code generated interface type '{0}' was not found, skipping code generation for that type", dataTypeDescriptor)); continue; } DataWrapperCodeGenerator.AddDataWrapperClassCode(builder, dataTypeDescriptor); } } } } ================================================ FILE: Composite/Data/Foundation/CodeGeneration/DataWrapperCodeGenerator.cs ================================================ using System; using System.CodeDom; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; using Composite.Core.Types; using Composite.Data.DynamicTypes; using Composite.Data.DynamicTypes.Foundation; namespace Composite.Data.Foundation.CodeGeneration { /// <summary> /// This class genereated code for data wrapper classes. /// </summary> internal static class DataWrapperCodeGenerator { private const string NamespaceName = "CompositeGenerated.DataWrappers"; private const string WrappedObjectName = "_wrappedData"; internal static void AddDataWrapperClassCode(CodeGenerationBuilder codeGenerationBuilder, Type interfaceType) { codeGenerationBuilder.AddReference(interfaceType.Assembly); DataTypeDescriptor dataTypeDescriptor = ReflectionBasedDescriptorBuilder.Build(interfaceType); AddDataWrapperClassCode(codeGenerationBuilder, dataTypeDescriptor); } internal static void AddDataWrapperClassCode(CodeGenerationBuilder codeGenerationBuilder, DataTypeDescriptor dataTypeDescriptor) { Type interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor); if (interfaceType == null) return; codeGenerationBuilder.AddReference(typeof(IDataWrapper).Assembly); codeGenerationBuilder.AddReference(typeof(EditorBrowsableAttribute).Assembly); CodeTypeDeclaration codeTypeDeclaration = CreateCodeTypeDeclaration(dataTypeDescriptor); codeGenerationBuilder.AddType(NamespaceName, codeTypeDeclaration); } internal static string CreateWrapperClassFullName(string interfaceTypeFullName) { return NamespaceName + "." + CreateWrapperClassName(interfaceTypeFullName); } private static string CreateWrapperClassName(string interfaceTypeFullName) { return string.Format("{0}Wrapper", interfaceTypeFullName.Replace('.', '_').Replace('+', '_')); } private static CodeTypeDeclaration CreateCodeTypeDeclaration(DataTypeDescriptor dataTypeDescriptor) { string interfaceTypeFullName = dataTypeDescriptor.GetFullInterfaceName(); var debugDisplayText = $"Data wrapper for '{interfaceTypeFullName}'"; foreach (var keyPropertyName in dataTypeDescriptor.KeyPropertyNames) { debugDisplayText += $", {keyPropertyName} = {{{keyPropertyName}}}"; } var labelFieldName = dataTypeDescriptor.LabelFieldName; if (!string.IsNullOrEmpty(labelFieldName) && !dataTypeDescriptor.KeyPropertyNames.Contains(labelFieldName)) { debugDisplayText += $", {labelFieldName} = {{{labelFieldName}}}"; } IEnumerable<Tuple<string, Type, bool>> properties = dataTypeDescriptor.Fields. Select(f => new Tuple<string, Type, bool>(f.Name, f.InstanceType, f.IsReadOnly)). Concat(new[] { new Tuple<string, Type, bool>("DataSourceId", typeof(DataSourceId), true) }); var declaration = new CodeTypeDeclaration { Name = CreateWrapperClassName(interfaceTypeFullName), IsClass = true, TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed }; declaration.BaseTypes.Add(interfaceTypeFullName); declaration.BaseTypes.Add(typeof(IDataWrapper)); declaration.CustomAttributes.AddRange(new[] { new CodeAttributeDeclaration( new CodeTypeReference(typeof(EditorBrowsableAttribute)), new CodeAttributeArgument( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(EditorBrowsableState)), EditorBrowsableState.Never.ToString() ) ) ), new CodeAttributeDeclaration( new CodeTypeReference(typeof(DebuggerDisplayAttribute)), new CodeAttributeArgument( new CodePrimitiveExpression(debugDisplayText) ) ) }); declaration.Members.Add(new CodeMemberField(interfaceTypeFullName, WrappedObjectName)); AddConstructor(declaration, interfaceTypeFullName); AddInterfaceProperties(declaration, properties); AddMethods(declaration, properties); return declaration; } private static void AddConstructor(CodeTypeDeclaration declaration, string interfaceTypeFullName) { const string parameterName = "data"; CodeConstructor codeConstructor = new CodeConstructor(); codeConstructor.Attributes = MemberAttributes.Public; codeConstructor.Parameters.Add(new CodeParameterDeclarationExpression(interfaceTypeFullName, parameterName)); codeConstructor.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), WrappedObjectName), new CodeVariableReferenceExpression(parameterName) )); declaration.Members.Add(codeConstructor); } /// <summary> /// /// </summary> /// <param name="declaration"></param> /// <param name="properties">Tuple(string propertyName, Type propertyType, bool readOnly)</param> private static void AddInterfaceProperties(CodeTypeDeclaration declaration, IEnumerable<Tuple<string, Type, bool>> properties) { foreach (var property in properties) { string propertyName = property.Item1; Type propertyType = property.Item2; bool readOnly = property.Item3; string fieldName = CreateFieldName(propertyName); CodeTypeReference nullableType = new CodeTypeReference( typeof(ExtendedNullable<>).FullName, new [] { new CodeTypeReference(propertyType) } ); CodeMemberField codeField = new CodeMemberField(); codeField.Name = fieldName; codeField.Type = nullableType; declaration.Members.Add(codeField); CodeMemberProperty codeProperty = new CodeMemberProperty(); codeProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final; codeProperty.Name = propertyName; codeProperty.HasGet = true; codeProperty.HasSet = !readOnly; codeProperty.Type = new CodeTypeReference(propertyType); codeProperty.GetStatements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), fieldName ), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null) ), new CodeStatement[] { new CodeMethodReturnStatement( new CodePropertyReferenceExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), fieldName ), "Value" ) ) }, new CodeStatement[] { new CodeMethodReturnStatement( new CodePropertyReferenceExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), WrappedObjectName ), propertyName ) ) } )); if (!readOnly) { // CODEGEN: // if(this.[fieldName] == null) { // this.[fieldName] = new ExtendedNullable<...>(); // } codeProperty.SetStatements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), fieldName ), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null) ), new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), fieldName ), new CodeObjectCreateExpression(nullableType, new CodeExpression[] {})))); // CODEGEN: // this.[fieldName] = value; codeProperty.SetStatements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), fieldName ), "Value" ), new CodePropertySetValueReferenceExpression() )); } declaration.Members.Add(codeProperty); } } /// <summary> /// /// </summary> /// <param name="declaration"></param> /// <param name="properties">Tuple(string propertyName, Type propertyType, bool readOnly)</param> private static void AddMethods(CodeTypeDeclaration declaration, IEnumerable<Tuple<string, Type, bool>> properties) { CodeMemberProperty codeMemberProperty = new CodeMemberProperty(); codeMemberProperty.Name = "WrappedData"; codeMemberProperty.HasGet = true; codeMemberProperty.HasSet = false; codeMemberProperty.Type = new CodeTypeReference(typeof(IData)); codeMemberProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final; codeMemberProperty.GetStatements.Add( new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), WrappedObjectName ) )); declaration.Members.Add(codeMemberProperty); CodeMemberMethod codeMemberMethod = new CodeMemberMethod(); codeMemberMethod.Name = "CommitData"; codeMemberMethod.ReturnType = new CodeTypeReference(typeof(void)); codeMemberMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; foreach (var property in properties) { string propertyName = property.Item1; bool readOnly = property.Item3; if (readOnly) continue; string fieldName = CreateFieldName(propertyName); List<CodeStatement> statements = new List<CodeStatement>(); statements.Add(new CodeAssignStatement( new CodePropertyReferenceExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), WrappedObjectName ), propertyName ), new CodePropertyReferenceExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), fieldName ), "Value" ) )); codeMemberMethod.Statements.Add(new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), fieldName ), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null) ), statements.ToArray() )); } declaration.Members.Add(codeMemberMethod); } private static string CreateFieldName(string propertyName) { return string.Format("_{0}Nullable", propertyName.ToLowerInvariant()); } } } ================================================ FILE: Composite/Data/Foundation/CodeGeneration/DataWrapperGenerator.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Composite.Core.Types; using Composite.Data.DynamicTypes; namespace Composite.Data.Foundation.CodeGeneration { /// <summary> /// This class handles data wrapper types and cashing. /// It will through <see cref="DataWrapperCodeGenerator"/> generated /// data wrapper class types if needed. /// </summary> internal static class DataWrapperTypeManager { private static readonly object _compilationLock = new object(); private static readonly ConcurrentDictionary<Type, Type> _dataWrappersCache = new ConcurrentDictionary<Type, Type>(); delegate T ObjectActivator<T>(T param); private static readonly ConcurrentDictionary<Type, object> _dataWrappersActivatorCache = new ConcurrentDictionary<Type, object>(); public static Func<T, T> GetWrapperConstructor<T>() { return (Func < T, T >)_dataWrappersActivatorCache.GetOrAdd(typeof (T), type => { var wrapperType = GetDataWrapperType(typeof (T)); var param = Expression.Parameter(typeof (T)); var constructor = wrapperType.GetConstructors().Single(); var ctrExpression = Expression.New(constructor, param); var lambda = Expression.Lambda(typeof (ObjectActivator<T>), ctrExpression, param); var activator = (ObjectActivator<T>) lambda.Compile(); Func<T, T> func = obj => activator(obj); return func; }); } public static Type GetDataWrapperType(Type interfaceType) { return _dataWrappersCache.GetOrAdd(interfaceType, type => { Type wrapperType = TryGetWrapperType(type.FullName); if (wrapperType != null) return wrapperType; lock (_compilationLock) { wrapperType = TryGetWrapperType(type.FullName); if (wrapperType != null) return wrapperType; var codeGenerationBuilder = new CodeGenerationBuilder("DataWrapper:" + type.FullName); DataWrapperCodeGenerator.AddDataWrapperClassCode(codeGenerationBuilder, type); IEnumerable<Type> types = CodeGenerationManager.CompileRuntimeTempTypes(codeGenerationBuilder); return types.Single(); } }); } public static Type GetDataWrapperType(DataTypeDescriptor dataTypeDescriptor) { Type wrapperType = TryGetWrapperType(dataTypeDescriptor.GetFullInterfaceName()); if (wrapperType != null) return wrapperType; lock (_compilationLock) { wrapperType = TryGetWrapperType(dataTypeDescriptor.GetFullInterfaceName()); if (wrapperType != null) return wrapperType; var codeGenerationBuilder = new CodeGenerationBuilder("DataWrapper:" + dataTypeDescriptor.GetFullInterfaceName()); DataWrapperCodeGenerator.AddDataWrapperClassCode(codeGenerationBuilder, dataTypeDescriptor); IEnumerable<Type> types = CodeGenerationManager.CompileRuntimeTempTypes(codeGenerationBuilder); return types.Single(); } } /// <summary> /// Returns a wrapper type, if it already exists. /// </summary> public static Type TryGetWrapperType(string fullName) { string dataWrapperFullName = DataWrapperCodeGenerator.CreateWrapperClassFullName(fullName); Type wrapperType = TypeManager.TryGetType(dataWrapperFullName); return wrapperType; } } } ================================================ FILE: Composite/Data/Foundation/CodeGeneration/EmptyDataClassBase.cs ================================================ using System; namespace Composite.Data.Foundation.CodeGeneration { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public abstract class EmptyDataClassBase : IData { [NonSerialized] private DataSourceId _dataSourceId = null; /// <exclude /> public DataSourceId DataSourceId { get { if (_dataSourceId == null) { _dataSourceId = new DataSourceId(this._InterfaceType); } return _dataSourceId; } internal set { _dataSourceId = value; } } /// <exclude /> protected abstract Type _InterfaceType { get; } } } ================================================ FILE: Composite/Data/Foundation/CodeGeneration/EmptyDataClassCodeGenerator.cs ================================================ using System; using System.CodeDom; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using Composite.Core.Types; using Composite.Data.DynamicTypes; namespace Composite.Data.Foundation.CodeGeneration { internal static class EmptyDataClassCodeGenerator { public static readonly string NamespaceName = "Composite.Data.GeneratedTypes"; internal static void AddEmptyDataClassTypeCode(CodeGenerationBuilder codeGenerationBuilder, DataTypeDescriptor dataTypeDescriptor, Type baseClassType = null, CodeAttributeDeclaration codeAttributeDeclaration = null) { Type interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor); if (interfaceType == null) return; if (baseClassType == null) baseClassType = typeof(EmptyDataClassBase); CodeTypeDeclaration codeTypeDeclaration = CreateCodeTypeDeclaration(dataTypeDescriptor, baseClassType, codeAttributeDeclaration); codeGenerationBuilder.AddType(NamespaceName, codeTypeDeclaration); } internal static void AddAssemblyReferences(CodeGenerationBuilder codeGenerationBuilder, DataTypeDescriptor dataTypeDescriptor) { Type interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor); if (interfaceType == null) return; codeGenerationBuilder.AddReference(typeof(EmptyDataClassBase).Assembly); codeGenerationBuilder.AddReference(typeof(EditorBrowsableAttribute).Assembly); codeGenerationBuilder.AddReference(interfaceType.Assembly); if (!string.IsNullOrEmpty(dataTypeDescriptor.BuildNewHandlerTypeName)) { Type buildeNewHandlerType = TypeManager.GetType(dataTypeDescriptor.BuildNewHandlerTypeName); codeGenerationBuilder.AddReference(buildeNewHandlerType.Assembly); } } internal static CodeTypeDeclaration CreateCodeTypeDeclaration(DataTypeDescriptor dataTypeDescriptor, Type baseClass, CodeAttributeDeclaration codeAttributeDeclaration) { Type interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor); string interfaceTypeFullName = interfaceType.FullName; CodeTypeDeclaration declaration = new CodeTypeDeclaration(); declaration.Name = CreateClassName(interfaceTypeFullName); declaration.IsClass = true; declaration.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed; declaration.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(SerializableAttribute)))); declaration.CustomAttributes.Add( new CodeAttributeDeclaration( new CodeTypeReference(typeof(EditorBrowsableAttribute)), new CodeAttributeArgument( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(EditorBrowsableState)), EditorBrowsableState.Never.ToString() ) ) ) ); if (baseClass != null) { declaration.BaseTypes.Add(baseClass); } declaration.BaseTypes.Add(new CodeTypeReference(interfaceType, CodeTypeReferenceOptions.GlobalReference)); if (codeAttributeDeclaration != null) { declaration.CustomAttributes.Add(codeAttributeDeclaration); } AddConstructor(declaration); AddInterfaceProperties(declaration, dataTypeDescriptor.Fields); AddInterfaceTypeProperty(declaration, interfaceTypeFullName); return declaration; } private static void AddConstructor(CodeTypeDeclaration declaration) { CodeConstructor codeConstructor = new CodeConstructor(); codeConstructor.Attributes = MemberAttributes.Public; declaration.Members.Add(codeConstructor); } private static void AddInterfaceProperties(CodeTypeDeclaration declaration, IEnumerable<DataFieldDescriptor> dataFieldDescriptors) { foreach (DataFieldDescriptor dataFieldDescriptor in dataFieldDescriptors) { string fieldName = CreateFieldName(dataFieldDescriptor); CodeMemberField codeField = new CodeMemberField(new CodeTypeReference(dataFieldDescriptor.InstanceType), fieldName); declaration.Members.Add(codeField); CodeMemberProperty property = new CodeMemberProperty(); property.Attributes = MemberAttributes.Public | MemberAttributes.Final; property.Name = dataFieldDescriptor.Name; property.HasGet = true; property.HasSet = !dataFieldDescriptor.IsReadOnly; property.Type = new CodeTypeReference(dataFieldDescriptor.InstanceType); property.GetStatements.Add( new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), fieldName ) ) ); if (!dataFieldDescriptor.IsReadOnly) { property.SetStatements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), fieldName ), new CodePropertySetValueReferenceExpression() )); } declaration.Members.Add(property); } } private static void AddInterfaceTypeProperty(CodeTypeDeclaration declaration, string interfaceTypeFullName) { CodeMemberProperty codeMemberProperty = new CodeMemberProperty(); codeMemberProperty.Name = "_InterfaceType"; codeMemberProperty.Type = new CodeTypeReference(typeof(Type)); codeMemberProperty.Attributes = MemberAttributes.Family | MemberAttributes.Override; codeMemberProperty.HasSet = false; codeMemberProperty.HasGet = true; codeMemberProperty.GetStatements.Add( new CodeMethodReturnStatement( new CodeTypeOfExpression(new CodeTypeReference(interfaceTypeFullName, CodeTypeReferenceOptions.GlobalReference)) ) ); declaration.Members.Add(codeMemberProperty); } internal static string GetEmptyClassTypeFullName(DataTypeDescriptor dataTypeDescriptor) { return NamespaceName + "." + CreateClassName(dataTypeDescriptor.GetFullInterfaceName()); } private static string CreateClassName(string fullname) { return string.Format("{0}EmptyClass", fullname.Replace('.', '_').Replace('+', '_')); } private static string CreateFieldName(DataFieldDescriptor dataFieldDescriptor) { return string.Format("_{0}", dataFieldDescriptor.Name.ToLowerInvariant()); } } } ================================================ FILE: Composite/Data/Foundation/CodeGeneration/EmptyDataClassCodeProvider.cs ================================================ using Composite.Core; using Composite.Core.Types; using Composite.Data.DynamicTypes; namespace Composite.Data.Foundation.CodeGeneration { internal class EmptyDataClassCodeProvider : ICodeProvider { public void GetCodeToCompile(CodeGenerationBuilder builder) { foreach (DataTypeDescriptor dataTypeDescriptor in DataMetaDataFacade.AllDataTypeDescriptors) { if (!dataTypeDescriptor.ValidateRuntimeType()) { Log.LogError("EmptyDataClassCodeProvider", "The non code generated interface type '{0}' was not found, skipping code generation for that type", dataTypeDescriptor); continue; } if (string.IsNullOrEmpty(dataTypeDescriptor.BuildNewHandlerTypeName)) { EmptyDataClassCodeGenerator.AddAssemblyReferences(builder, dataTypeDescriptor); EmptyDataClassCodeGenerator.AddEmptyDataClassTypeCode(builder, dataTypeDescriptor); } } } } } ================================================ FILE: Composite/Data/Foundation/DataAssociationRegistry.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using Composite.Core.Extensions; using Composite.Data.ProcessControlled; using Composite.C1Console.Events; using Composite.Core.Linq; using Composite.Core.Types; using Composite.Data.Types; using Composite.Core; namespace Composite.Data.Foundation { /// <summary> /// Associated type: The type that is "pointed" to by another type /// Association type: The type that is "pointing" to a nother type /// </summary> internal static class DataAssociationRegistry { // Associated type -> Association type private static Dictionary<Type, List<Type>> _associatedTypes; // Association type -> Associated type -> DataAssociationInfo // As long as only one association is allowed for a given type, this dictionary is over kill /MRJ private static Dictionary<Type, Dictionary<Type, DataAssociationInfo>> _dataAssociations; static DataAssociationRegistry() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } public static bool IsAssociationType(Type associationType) { Verify.ArgumentNotNull(associationType, "associationType"); using (GlobalInitializerFacade.CoreIsInitializedScope) { return _dataAssociations.ContainsKey(associationType); } } public static DataAssociationType GetAssociationType(Type associationType) { Verify.ArgumentNotNull(associationType, "associationType"); using (GlobalInitializerFacade.CoreIsInitializedScope) { Dictionary<Type, DataAssociationInfo> dataAssociationInfo; if (!_dataAssociations.TryGetValue(associationType, out dataAssociationInfo)) { return DataAssociationType.None; } return dataAssociationInfo.Single().Value.AssociationType; } } public static IEnumerable<string> GetForeignKeyPropertyNames(this Type associationType, DataAssociationType dataAssociationType) { Verify.ArgumentNotNull(associationType, "associationType"); using (GlobalInitializerFacade.CoreIsInitializedScope) { Dictionary<Type, DataAssociationInfo> dataAssociationInfos; if (!_dataAssociations.TryGetValue(associationType, out dataAssociationInfos)) { return Enumerable.Empty<string>(); } return from info in dataAssociationInfos.Values where info.AssociationType == dataAssociationType select info.ForeignKeyPropertyName; } } public static List<Type> GetAssociationTypes(Type associatedType, DataAssociationType dataAssociationType) { if (associatedType == null) throw new ArgumentNullException("associatedType"); if (dataAssociationType == DataAssociationType.None) throw new ArgumentException(string.Format("dataAssociationType may not be '{0}", DataAssociationType.None)); using (GlobalInitializerFacade.CoreIsInitializedScope) { List<Type> associationTypes; if (!_associatedTypes.TryGetValue(associatedType, out associationTypes)) { return new List<Type>(); } return (from t1 in associationTypes from info in _dataAssociations[t1].Values where info.AssociationType == dataAssociationType select t1).ToList(); } } public static List<Type> GetAssociatedTypes(Type associationType, DataAssociationType dataAssociationType) { Verify.ArgumentNotNull(associationType, "associationType"); if (dataAssociationType == DataAssociationType.None) throw new ArgumentException(string.Format("dataAssociationType may not be '{0}", DataAssociationType.None)); using (GlobalInitializerFacade.CoreIsInitializedScope) { Dictionary<Type, DataAssociationInfo> dataAssociations; if (!_dataAssociations.TryGetValue(associationType, out dataAssociations)) { throw new InvalidOperationException(string.Format("Type type '{0}' is not an association type", associationType)); } return (from info in dataAssociations where info.Value.AssociationType == dataAssociationType select info.Key).ToList(); } } public static string GetForeignKeyPropertyName(Type associatedType, Type associationType) { if (associatedType == null) throw new ArgumentNullException("associatedType"); if (associationType == null) throw new ArgumentNullException("associationType"); using (GlobalInitializerFacade.CoreIsInitializedScope) { Dictionary<Type, DataAssociationInfo> dataAssociationInfos; if (!_dataAssociations.TryGetValue(associationType, out dataAssociationInfos)) throw new ArgumentException(string.Format("The type '{0}' is not associated to any types", associationType)); DataAssociationInfo dataAssociationInfo; if (!dataAssociationInfos.TryGetValue(associatedType, out dataAssociationInfo)) throw new ArgumentException(string.Format("The type '{0}' is not associated to the type '{1}'", associationType, associatedType)); return dataAssociationInfo.ForeignKeyPropertyName; } } public static PropertyInfo GetForeignKeyPropertyInfo(Type associatedType, Type associationType) { if (associatedType == null) throw new ArgumentNullException("associatedType"); if (associationType == null) throw new ArgumentNullException("associationType"); using (GlobalInitializerFacade.CoreIsInitializedScope) { Dictionary<Type, DataAssociationInfo> dataAssociationInfos; if (!_dataAssociations.TryGetValue(associationType, out dataAssociationInfos)) throw new ArgumentException(string.Format("The type '{0}' is not associated to any types", associationType)); DataAssociationInfo dataAssociationInfo; if (!dataAssociationInfos.TryGetValue(associatedType, out dataAssociationInfo)) throw new ArgumentException(string.Format("The type '{0}' is not associated to the type '{1}'", associationType, associatedType)); return dataAssociationInfo.ForeignKeyPropertyInfo; } } internal static void Initialize_PostDataTypes() { if (RuntimeInformation.IsDebugBuild) { GlobalInitializerFacade.ValidateIsOnlyCalledFromGlobalInitializerFacade(new StackTrace()); } _associatedTypes = new Dictionary<Type, List<Type>>(); _dataAssociations = new Dictionary<Type, Dictionary<Type, DataAssociationInfo>>(); foreach (Type type in DataProviderRegistry.AllInterfaces) { AddNewType(type); } } private static void AddNewType(Type interfaceType) { List<DataAssociationAttribute> attributes = interfaceType.GetCustomAttributesRecursively<DataAssociationAttribute>().ToList(); if (attributes.Count == 0) { return; } var dataAssociationInfos = new Dictionary<Type, DataAssociationInfo>(); foreach (DataAssociationAttribute attribute in attributes) { if (attribute.AssociationType == DataAssociationType.None) throw new ArgumentException(string.Format("The associationType on the attribute '{0}' on the interface type '{1}' may not be '{2}'", typeof(DataAssociationAttribute), interfaceType, DataAssociationType.None)); if (attribute.AssociatedInterfaceType == null) throw new ArgumentNullException(string.Format("The associatedInterfaceType on the attribute '{0}' on the interface type '{1}' is null", typeof(DataAssociationAttribute), interfaceType)); List<Type> associatedTypes; Type associatedInterface = attribute.AssociatedInterfaceType; if (_associatedTypes.TryGetValue(associatedInterface, out associatedTypes) == false) { associatedTypes = new List<Type>(); _associatedTypes.Add(associatedInterface, associatedTypes); DataEventSystemFacade.SubscribeToDataAfterUpdate(associatedInterface, OnAfterDataUpdated, false); } associatedTypes.Add(interfaceType); PropertyInfo propertyInfo = (from pi in interfaceType.GetAllProperties() where pi.Name == attribute.ForeignKeyPropertyName select pi).FirstOrDefault(); if (propertyInfo == null) throw new ArgumentException(string.Format("The foreign key property name '{0}' set on the attribute '{1}' does not exist on the interface '{2}'", attribute.ForeignKeyPropertyName, typeof(DataAssociationAttribute), interfaceType)); var dataAssociationInfo = new DataAssociationInfo { AssociatedInterfaceType = associatedInterface, ForeignKeyPropertyName = attribute.ForeignKeyPropertyName, ForeignKeyPropertyInfo = propertyInfo, AssociationType = attribute.AssociationType, }; Verify.IsFalse(dataAssociationInfos.ContainsKey(associatedInterface), "Failed to register interface '{0}'. Data association already exist, type: '{1}'".FormatWith(interfaceType, associatedInterface)); dataAssociationInfos.Add(associatedInterface, dataAssociationInfo); if (!DataProviderRegistry.AllInterfaces.Contains(associatedInterface)) { Log.LogCritical("DataReferenceRegistry", string.Format("The one type '{0}' is associated to the non supported data type '{1}'", interfaceType, associatedInterface)); } } _dataAssociations.Add(interfaceType, dataAssociationInfos); } private static void OnAfterDataUpdated(object sender, DataEventArgs dataEventArgs) { IPublishControlled publishControlled = dataEventArgs.Data as IPublishControlled; if (publishControlled == null) return; IPage page = dataEventArgs.Data as IPage; if (page == null) return; var metaDataToBeUpdated = page.GetMetaData().Evaluate(); foreach (IData data in metaDataToBeUpdated) { IPublishControlled pc = data as IPublishControlled; if (pc.PublicationStatus != publishControlled.PublicationStatus) { pc.PublicationStatus = publishControlled.PublicationStatus; // THIS UPDATE WAS ALWAYS EXECUTED - OUTSIDE THE versionControlled CHECK - WAS THIS NEEDED? DataFacade.Update(data, false, false, false); } } } private static void Flush() { _associatedTypes = null; _dataAssociations = null; } private sealed class DataAssociationInfo { public Type AssociatedInterfaceType { get; set; } public string ForeignKeyPropertyName { get; set; } public PropertyInfo ForeignKeyPropertyInfo { get; set; } public DataAssociationType AssociationType { get; set; } } } } ================================================ FILE: Composite/Data/Foundation/DataExpressionBuilder.cs ================================================ using System.Linq.Expressions; using System.Linq; using System.Reflection; using System.Collections.Generic; using System; using Composite.Core.Linq; using Composite.C1Console.Events; using Composite.Data.ProcessControlled; namespace Composite.Data.Foundation { internal static class DataExpressionBuilder { private static object _lock = new object(); static DataExpressionBuilder() { } /// <summary> /// This method returns a queryable containing data with the same keys /// </summary> /// <param name="data"></param> /// <returns></returns> public static IQueryable GetQueryableByData(IData data) { return GetQueryableByData(data, null); } public static IQueryable GetQueryableByData(IData data, IQueryable sourceQueryable) { LambdaExpression whereLambdaExpression = GetWhereLambdaExpression(data); if (sourceQueryable == null) { sourceQueryable = DataFacade.GetData(data.DataSourceId.InterfaceType); } Expression whereExpression = ExpressionCreator.Where(sourceQueryable.Expression, whereLambdaExpression); IQueryable newQueryable = sourceQueryable.Provider.CreateQuery(whereExpression); return newQueryable; } public static IQueryable<T> GetQueryableByData<T>(T data) where T : class, IData { LambdaExpression whereLambdaExpression = GetWhereLambdaExpression(data); IQueryable queryable = DataFacade.GetData(data.DataSourceId.InterfaceType); Expression whereExpression = ExpressionCreator.Where(queryable.Expression, whereLambdaExpression); MethodInfo methodInfo = DataFacadeReflectionCache.GetCreateQueryMethodInfo(data.DataSourceId.InterfaceType); return (IQueryable<T>)methodInfo.Invoke(queryable.Provider, new object[] { whereExpression }); } public static Delegate GetWherePredicateDelegate(IData data) { LambdaExpression whereLambdaExpression = GetWhereLambdaExpression(data); Delegate resultDelegate = whereLambdaExpression.Compile(); return resultDelegate; } private static LambdaExpression GetWhereLambdaExpression(IData data) { var propertyInfoes = data.DataSourceId.InterfaceType.GetPhysicalKeyProperties(); if (propertyInfoes.Count == 0) { throw new InvalidOperationException(string.Format("The data type '{0}' does not have any keys specified", data.DataSourceId.InterfaceType)); } ParameterExpression parameterExpression = Expression.Parameter(data.DataSourceId.InterfaceType, "parameter"); Expression whereBodyExpression = null; foreach (PropertyInfo propertyInfo in propertyInfoes) { object value = propertyInfo.GetGetMethod().Invoke(data, new object[] { }); Expression expression = Expression.Equal( Expression.Property(parameterExpression, propertyInfo), Expression.Constant(value) ); if (whereBodyExpression == null) { whereBodyExpression = expression; } else { whereBodyExpression = Expression.And(whereBodyExpression, expression); } } LambdaExpression whereLambdaExpression = Expression.Lambda(whereBodyExpression, new ParameterExpression[] { parameterExpression }); return whereLambdaExpression; } } } ================================================ FILE: Composite/Data/Foundation/DataFacadeQueryable.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Data.Linq; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Data.Caching; using Composite.Core.Extensions; using Composite.Core.Linq; namespace Composite.Data.Foundation { internal sealed class DataFacadeQueryable<T> : IQueryable<T>, IOrderedQueryable<T>, IDataFacadeQueryable, IQueryProvider { private readonly List<IQueryable> _sources; private readonly Expression _currentExpression; private readonly Expression _initialExpression; public DataFacadeQueryable(IEnumerable<IQueryable<T>> sources) { Verify.ArgumentNotNull(sources, "sources"); _sources = new List<IQueryable>(); foreach (IQueryable<T> source in sources) { _sources.Add(source); } _initialExpression = Expression.Constant(this); _currentExpression = _initialExpression; } /// <summary> /// Invoked via reflection /// </summary> public DataFacadeQueryable(List<IQueryable> sources, Expression currentExpression) { _sources = sources; _currentExpression = currentExpression; } public IQueryable<S> CreateQuery<S>(Expression expression) { Verify.ArgumentNotNull(expression, "expression"); Verify.ArgumentCondition(typeof(IQueryable<S>).IsAssignableFrom(expression.Type), "expression", "Incorrect expression type"); return new DataFacadeQueryable<S>(_sources, expression); } public S Execute<S>(Expression expression) { IQueryable source; var newExpression = BuildSqlCompatibleExpression(expression, out source); return (S)source.Provider.Execute(newExpression); } public IEnumerator<T> GetEnumerator() { if(object.Equals(_currentExpression, _initialExpression)) { if(_sources.Count == 1 && _sources[0] is IEnumerable<T>) { return (_sources[0] as IEnumerable<T>).GetEnumerator(); } if (_sources.Count == 0) { return new List<T>().GetEnumerator(); } } IQueryable source; var newExpression = BuildSqlCompatibleExpression(_currentExpression, out source); IQueryable<T> queryable = (IQueryable<T>)source.Provider.CreateQuery(newExpression); return queryable.GetEnumerator(); } private static Expression BuildSqlCompatibleExpression(Expression expression, out IQueryable source) { bool pullIntoMemory = ShouldBePulledIntoMemory(expression); var handleInProviderVisitor = new DataFacadeQueryableExpressionVisitor(pullIntoMemory); var newExpression = handleInProviderVisitor.Visit(expression); // Checking if the source contains queries both from SQL and Composite.Data.Caching.CachingQueryable in-memory queries. // In this case, we can replace CachingQueryable instances with sql queries which allows building correct sql statements. var analyzer = new QueryableAnalyzerVisitor(); analyzer.Visit(newExpression); if (analyzer.CachedSqlQueries > 1 || (analyzer.SqlQueries > 0 && analyzer.CachedSqlQueries > 0)) { newExpression = new CachedQueryExtractorVisitor().Visit(newExpression); newExpression = handleInProviderVisitor.Visit(newExpression); } source = handleInProviderVisitor.Queryable; return newExpression; } IEnumerator IEnumerable.GetEnumerator() { MethodInfo methodInfo = DataFacadeReflectionCache.GetDataFacadeQueryableGetEnumeratorMethodInfo(typeof(T)); return (IEnumerator)methodInfo.Invoke(this, null); } public IQueryable CreateQuery(Expression expression) { if (_currentExpression == expression) return this; Type elementType = TypeHelpers.FindElementType(expression); Type multipleSourceQueryableType = typeof(DataFacadeQueryable<>).MakeGenericType(new Type[] { elementType }); return Activator.CreateInstance( multipleSourceQueryableType, new object[] { _sources, expression }) as IQueryable; } public Type ElementType => typeof(T); public object Execute(Expression expression) { MethodInfo methodInfo = DataFacadeReflectionCache.GetDataFacadeQueryableExecuteMethodInfo(typeof(T), expression.Type); return methodInfo.Invoke(this, new object[] { expression }); } public Expression Expression => _currentExpression ?? Expression.Constant(this); public ICollection<IQueryable> Sources => _sources; public Type InterfaceType => typeof (T); private static bool ShouldBePulledIntoMemory(Expression expression) { var analyzer = new QueryableAnalyzerVisitor(); analyzer.Visit(expression); return analyzer.MethodsNotSupportedBySql > 0; } public bool IsEnumerableQuery { get { return _sources.All(source => (source as IQueryable<T>).IsEnumerableQuery()); } } public IQueryProvider Provider => this; private class QueryableAnalyzerVisitor : ExpressionVisitor { public int SqlQueries { get; private set; } public int CachedSqlQueries { get; private set; } public int InMemoryQueries { get; private set; } public int MethodsNotSupportedBySql { get; private set; } public int Other { get; private set; } protected override Expression VisitConstant(ConstantExpression node) { var value = node.Value; if (value is IQueryable) { if (value is ITable) { SqlQueries++; } else if (value is ICachedQuery) { CachedSqlQueries++; } else if (value is EnumerableQuery) { InMemoryQueries++; } else { Other++; } } return base.VisitConstant(node); } protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression) { // Checking for C# anonymous functions if(methodCallExpression.Method.ReflectedType.FullName.Contains("+<>")) { MethodsNotSupportedBySql++; } return base.VisitMethodCall(methodCallExpression); } } private class CachedQueryExtractorVisitor : ExpressionVisitor { protected override Expression VisitConstant(ConstantExpression node) { object value = node.Value; if(value is ICachedQuery) { IQueryable originalQuery = (value as ICachedQuery).GetOriginalQuery(); return Expression.Constant(originalQuery); } return base.VisitConstant(node); } } } } ================================================ FILE: Composite/Data/Foundation/DataFacadeQueryableExpressionVisitor.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Data.Linq; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.Types; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration; namespace Composite.Data.Foundation { /// <summary> /// Pulls queries into the memory if needed. Handles multiple source IQueryable-s /// </summary> internal sealed class DataFacadeQueryableExpressionVisitor : ExpressionVisitor { private static readonly MethodInfo _dataFacadeGetDataMethodInfo = typeof(DataFacade).GetMethods().First(x => x.Name == "GetData" && x.IsGenericMethod); private static readonly MethodInfo _dataConnectionGetDataMethodInfo = typeof(DataConnection).GetMethods().First(x => x.Name == "Get" && x.IsGenericMethod); private static readonly MethodInfo Queryable_Where = StaticReflection.GetGenericMethodInfo(() => System.Linq.Queryable.Where(null, (Expression<Func<int, bool>>)null)); private static readonly MethodInfo Queryable_Any = typeof(Queryable).GetMethods().Single(x => x.Name == "Any" && x.IsGenericMethod && x.GetParameters().Count() == 1); private static readonly MethodInfo Queryable_All = typeof(Queryable).GetMethods().Single(x => x.Name == "All" && x.IsGenericMethod && x.GetParameters().Count() == 2); private static readonly MethodInfo Queryable_Count = typeof(Queryable).GetMethods().Single(x => x.Name == "Count" && x.IsGenericMethod && x.GetParameters().Count() == 1); private static readonly MethodInfo Queryable_FirstOrDefault = typeof(Queryable).GetMethods().Single(x => x.Name == "FirstOrDefault" && x.IsGenericMethod && x.GetParameters().Count() == 1); private static readonly MethodInfo Queryable_SingleOrDefault = typeof(Queryable).GetMethods().Single(x => x.Name == "SingleOrDefault" && x.IsGenericMethod && x.GetParameters().Count() == 1); private static readonly MethodInfo Queryable_Take = typeof(Queryable).GetMethods().Single(x => x.Name == "Take" && x.IsGenericMethod && x.GetParameters().Count() == 2); private readonly bool _pullAllToMemory; private IQueryable _queryable; public DataFacadeQueryableExpressionVisitor(bool pullAllToMemeory) { _pullAllToMemory = pullAllToMemeory; } protected override Expression VisitConstant(ConstantExpression c) { if (c.Value is IDataFacadeQueryable) { IQueryable queryable = HandleMultipleSourceQueryable(c.Value); return queryable.Expression; } return base.VisitConstant(c); } protected override Expression VisitMember(MemberExpression m) { if (m.Member.DeclaringType.IsCompilerGeneratedType()) { if (m.Member.MemberType == MemberTypes.Field) { Type fieldType = ((FieldInfo)m.Member).FieldType; if ((fieldType.IsGenericType) && (fieldType.GetGenericTypeDefinition() == typeof(IQueryable<>)) && (m.Expression.NodeType == ExpressionType.Constant)) { // Container for holding a IQueryable<TARGET_TYPE> ConstantExpression constatntExpression = (ConstantExpression)m.Expression; FieldInfo fieldInfo = (FieldInfo)m.Member; object value = fieldInfo.GetValue(constatntExpression.Value); IQueryable queryable = HandleMultipleSourceQueryable(value); if (queryable != null) { fieldInfo.SetValue(constatntExpression.Value, queryable); } } } } return base.VisitMember(m); } protected override Expression VisitMethodCall(MethodCallExpression m) { if (m.Method.DeclaringType == typeof (DataFacade)) { if (m.Method.IsGenericMethod && m.Method.GetGenericMethodDefinition() == _dataFacadeGetDataMethodInfo) { object result = m.Method.Invoke(null, null); return Expression.Constant(result is IDataFacadeQueryable ? HandleMultipleSourceQueryable(result) : result); } // Handling some of the overloads of GetData() if (m.Method.Name == _dataFacadeGetDataMethodInfo.Name && m.Arguments.All(arg => (arg as ConstantExpression) != null)) { object[] parameters = m.Arguments.Select(arg => (arg as ConstantExpression).Value).ToArray(); object result = m.Method.Invoke(null, parameters); return Expression.Constant(result is IDataFacadeQueryable ? HandleMultipleSourceQueryable(result) : result); } throw new NotSupportedException("Supporing for DataFacade method '{0}' or one of it's overloads not yet implemented".FormatWith(m.Method.Name)); } if (m.Method.DeclaringType == typeof (DataConnection)) { if (m.Method.IsGenericMethod && m.Method.GetGenericMethodDefinition() == _dataConnectionGetDataMethodInfo) { var dataConnection = EvaluateExpression<DataConnection>(m.Object); object result = m.Method.Invoke(dataConnection, null); return Expression.Constant(result is IDataFacadeQueryable ? HandleMultipleSourceQueryable(result) : result); } throw new NotSupportedException("Supporing for DataConnection method '{0}' or one of it's overloads not yet implemented".FormatWith(m.Method.Name)); } // Replacing Guid.NewGuid() call with "newid()" sql statement if (m.Method.IsStatic && m.Method.DeclaringType == typeof(Guid) && m.Method.Name == "NewGuid" && _queryable != null) { var dataContext = GetContext(_queryable) as DataContextBase; if(dataContext != null) { return Expression.Call(Expression.Constant(dataContext), DataContextBase.GetNewIdMethodInfo()); } } // Processing queries that have multiple IQueryable sources // Processing queries like // // multipleSourceQueryable.METHOD() // multipleSourceQueryable.METHOD(predicate) // multipleSourceQueryable(.Where(predicate))*.METHOD() // multipleSourceQueryable(.Where(predicate))*.METHOD(predicate) // // Where the supported METHOD options are: "Where", "Any", "Count", "First" and "FirstOrDefault" IQueryable[] sources = null; List<Expression> predicates = null; if (m.Method.IsStatic && (m.Method.Name == "Where" || m.Method.Name == "Any" || m.Method.Name == "All" || m.Method.Name == "Count" || m.Method.Name == "First" || m.Method.Name == "FirstOrDefault" || m.Method.Name == "Single" || m.Method.Name == "SingleOrDefault") && (m.Arguments.Count == 1 || (m.Arguments.Count == 2 && m.Arguments[1] is UnaryExpression)) && ExtractMultipleSourceQueryable(m.Arguments[0], ref sources, ref predicates)) { Expression operationPredicate = m.Arguments.Count == 2 ? (m.Arguments[1] as UnaryExpression).Operand : null; if (m.Method.Name == "All") { _queryable = _queryable ?? new bool[0].AsQueryable(); return Expression.Constant(All(sources, predicates, operationPredicate)); } if (operationPredicate != null) { predicates.Add(operationPredicate); } if (m.Method.Name == "Where") { IQueryable loadedSet = LoadToMemory(sources, predicates); _queryable = _queryable ?? loadedSet; return Expression.Constant(loadedSet); } _queryable = _queryable ?? new bool[0].AsQueryable(); if (m.Method.Name == "Any") { return Expression.Constant(Any(sources, predicates)); } if (m.Method.Name == "Count") { return Expression.Constant(Count(sources, predicates)); } if (m.Method.Name == "First") { return Expression.Constant(First(sources, predicates)); } if (m.Method.Name == "FirstOrDefault") { return Expression.Constant(FirstOrDefault(sources, predicates)); } if (m.Method.Name == "Single") { return Expression.Constant(Single(sources, predicates)); } if (m.Method.Name == "SingleOrDefault") { return Expression.Constant(SingleOrDefault(sources, predicates)); } throw new InvalidOperationException("This code should not be reachable. Current expression: " + m); } // Processing queries like // // multipleSourceQueryable(.Where(predicate))*.Take(N) if (m.Method.IsStatic && m.Method.Name == "Take" && (m.Arguments.Count == 2 && m.Arguments[1] is ConstantExpression && (m.Arguments[1] as ConstantExpression).Value is int) && ExtractMultipleSourceQueryable(m.Arguments[0], ref sources, ref predicates)) { int count = (int) (m.Arguments[1] as ConstantExpression).Value; var result = Take(sources, count, predicates); _queryable = _queryable ?? result; return Expression.Constant(result); } return base.VisitMethodCall(m); } private static DataContext GetContext(IQueryable q) { string typeName = q.GetType().FullName; if (!typeName.StartsWith("System.Data.Linq.DataQuery`1", StringComparison.Ordinal) && !typeName.StartsWith("System.Data.Linq.Table`1", StringComparison.Ordinal)) { return null; } var field = q.GetType().GetField("context", BindingFlags.NonPublic | BindingFlags.Instance); return field == null ? null : field.GetValue(q) as DataContext; } private TResultType EvaluateExpression<TResultType>(Expression expression) { return Expression.Lambda<Func<TResultType>>(expression).Compile().Invoke(); } public IQueryable Queryable { get { return _queryable; } } private static Type GetElementType(IQueryable[] sources) { // Choosing element type which is the "highest" in hierarhy. F.e. if we have IQueryable<IPage> and IQueryable<IData>, // the "highest" element type would be IData Type elementType = sources[0].ElementType; for(int i=1; i<sources.Length; i++) { if(elementType != sources[i].ElementType && sources[i].ElementType.IsAssignableFrom(elementType)) { elementType = sources[i].ElementType; } } return elementType; } private static bool Any(IQueryable[] sources, IEnumerable<Expression> predicates = null) { Type elementType = GetElementType(sources); foreach (IQueryable query in sources) { IQueryable filteredQuery = ApplyPredicates(query, elementType, predicates); bool any = (bool) Queryable_Any.MakeGenericMethod(elementType).Invoke(null, new object[] { filteredQuery }); if (any) return true; } return false; } private static bool All(IQueryable[] sources, IEnumerable<Expression> predicates, Expression operationPredicate) { Type elementType = GetElementType(sources); foreach (IQueryable query in sources) { IQueryable filteredQuery = ApplyPredicates(query, elementType, predicates); bool all = (bool)Queryable_All.MakeGenericMethod(elementType).Invoke(null, new object[] { filteredQuery, operationPredicate }); if (!all) return false; } return true; } private static int Count(IQueryable[] sources, IEnumerable<Expression> predicates = null) { Type elementType = GetElementType(sources); int result = 0; foreach (IQueryable query in sources) { IQueryable filteredQuery = ApplyPredicates(query, elementType, predicates); int count = (int) Queryable_Count.MakeGenericMethod(elementType).Invoke(null, new object[] { filteredQuery }); result += count; } return result; } private static object First(IQueryable[] sources, IEnumerable<Expression> predicates = null) { var result = FirstOrDefault(sources, predicates); if (result == null) { string predicateInfo = predicates != null ? string.Join(" ANDALSO ", predicates.Select(p => p.ToString())) : ""; throw new InvalidOperationException("Sequence contains no elements. " + predicateInfo); } return result; } private static object FirstOrDefault(IQueryable[] sources, IEnumerable<Expression> predicates = null) { Type elementType = GetElementType(sources); foreach (IQueryable query in sources) { IQueryable filteredQuery = ApplyPredicates(query, elementType, predicates); object result = Queryable_FirstOrDefault.MakeGenericMethod(elementType).Invoke(null, new object[] { filteredQuery }); // Result can't be value type, so null is always the default value if (result != null) { return result; } } return null; } private static object Single(IQueryable[] sources, IEnumerable<Expression> predicates = null) { var result = SingleOrDefault(sources, predicates); if (result == null) { string predicateInfo = predicates != null ? string.Join(" ANDALSO ", predicates.Select(p => p.ToString())) : ""; throw new InvalidOperationException("Sequence contains no elements. " + predicateInfo); } return result; } private static object SingleOrDefault(IQueryable[] sources, IEnumerable<Expression> predicates = null) { Type elementType = GetElementType(sources); object result = null; foreach (IQueryable query in sources) { IQueryable filteredQuery = ApplyPredicates(query, elementType, predicates); object subqueryResult = Queryable_SingleOrDefault.MakeGenericMethod(elementType).Invoke(null, new object[] { filteredQuery }); if (subqueryResult != null) { if (result != null) { string predicateInfo = predicates != null ? string.Join(" ANDALSO ", predicates.Select(p => p.ToString())) : ""; throw new InvalidOperationException("More than one value returned. " + predicateInfo); } result = subqueryResult; } } return result; } private static IQueryable Take(IQueryable[] sources, int count, IEnumerable<Expression> predicates = null) { Type elementType = GetElementType(sources); MethodInfo addRangeToListMethodInfo = DataFacadeReflectionCache.List_AddRangeMethodInfo(elementType); Type listType = typeof(List<>).MakeGenericType(elementType); var List_Count = listType.GetProperty("Count"); var list = Activator.CreateInstance(listType); int taken = 0; foreach (IQueryable query in sources) { IQueryable filteredQuery = ApplyPredicates(query, elementType, predicates); int elementsToTake = count - taken; var subList = Queryable_Take.MakeGenericMethod(elementType).Invoke(null, new object[] { filteredQuery, elementsToTake }); addRangeToListMethodInfo.Invoke(list, new object[] { subList }); taken = (int) List_Count.GetValue(list, null); if(taken == count) break; } MethodInfo asQueryableMethodInfo = DataFacadeReflectionCache.Queryable_AsQueryableMethodInfo(elementType); object listedDataAsQueryable = asQueryableMethodInfo.Invoke(null, new [] { list }); return (IQueryable)listedDataAsQueryable; } private static IQueryable LoadToMemory(IQueryable[] sources, IEnumerable<Expression> predicates = null) { Type elementType = GetElementType(sources); return LoadToMemory(elementType, sources, predicates); } private static IQueryable LoadToMemory(Type elementType, IQueryable[] sources, IEnumerable<Expression> predicates = null) { MethodInfo addRangeToListMethodInfo = DataFacadeReflectionCache.List_AddRangeMethodInfo(elementType); MethodInfo toListMethodInfo = DataFacadeReflectionCache.Enumerable_ToList(elementType); IList list = DataFacadeReflectionCache.List_New(elementType); foreach (IQueryable query in sources) { IQueryable filteredQuery = ApplyPredicates(query, elementType, predicates); var subList = toListMethodInfo.Invoke(null, new object[] { filteredQuery }); addRangeToListMethodInfo.Invoke(list, new object[] { subList }); } MethodInfo asQueryableMethodInfo = DataFacadeReflectionCache.Queryable_AsQueryableMethodInfo(elementType); object listedDataAsQueryable = asQueryableMethodInfo.Invoke(null, new object[] { list }); if (RuntimeInformation.IsDebugBuild) { if (list.Count > 500) { Log.LogInformation("DataFacadeQuery", list.Count + " rows in a single query. Element type:" + elementType.FullName); } } return (IQueryable)listedDataAsQueryable; } private static IQueryable ApplyPredicates(IQueryable queryable, Type elementType, IEnumerable<Expression> predicates) { if (predicates != null) { foreach (var predicate in predicates) { queryable = (IQueryable) Queryable_Where.MakeGenericMethod(elementType).Invoke(null, new object[] {queryable, predicate}); } } return queryable; } /// <summary> /// Extracts multiple source queryable with predicates defined in WHERE statements /// </summary> private static bool ExtractMultipleSourceQueryable(Expression expression, ref IQueryable[] sources, ref List<Expression> predicates) { if (expression is ConstantExpression) { var constantExpression = expression as ConstantExpression; if (constantExpression.Value is IDataFacadeQueryable && (constantExpression.Value as IDataFacadeQueryable).Sources.Count() > 1) { predicates = new List<Expression>(); sources = (constantExpression.Value as IDataFacadeQueryable).Sources.ToArray(); return true; } return false; } if (expression is MethodCallExpression) { var methodCallExpression = (expression as MethodCallExpression); if (methodCallExpression.Method.Name == "Where" && methodCallExpression.Arguments[1] is UnaryExpression && ExtractMultipleSourceQueryable(methodCallExpression.Arguments[0], ref sources, ref predicates)) { predicates.Add((methodCallExpression.Arguments[1] as UnaryExpression).Operand); return true; } } return false; } private IQueryable HandleMultipleSourceQueryable(object multipleSourceQueryableCandidate) { IDataFacadeQueryable multipleSourceQueryable = multipleSourceQueryableCandidate as IDataFacadeQueryable; if (multipleSourceQueryable == null) return null; IQueryable queryable; if (!_pullAllToMemory && multipleSourceQueryable.Sources.Count == 1) { queryable = multipleSourceQueryable.Sources.First(); } else { IQueryable[] sources = multipleSourceQueryable.Sources.ToArray(); queryable = LoadToMemory(multipleSourceQueryable.InterfaceType, sources); } if (_queryable == null) { _queryable = queryable; } return queryable; } } } ================================================ FILE: Composite/Data/Foundation/DataFacadeQueryableGathererExpressionVisitor.cs ================================================ using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace Composite.Data.Foundation { internal sealed class DataFacadeQueryableGathererExpressionVisitor : ExpressionVisitor { private List<IDataFacadeQueryable> _multibleSourceQueryables = new List<IDataFacadeQueryable>(); private int _sourceCount = 0; protected override Expression VisitConstant(ConstantExpression c) { if (c.Value is IDataFacadeQueryable) { IDataFacadeQueryable multibleSourceQueryable = (IDataFacadeQueryable)c.Value; _sourceCount += multibleSourceQueryable.Sources.Count(); IDataFacadeQueryable found = _multibleSourceQueryables.Find(delegate(IDataFacadeQueryable queryable) { return object.ReferenceEquals(multibleSourceQueryable, queryable); }); if (found == null) { _multibleSourceQueryables.Add(multibleSourceQueryable); } } return base.VisitConstant(c); } public List<IDataFacadeQueryable> MultibleSourceQueryables { get { return _multibleSourceQueryables; } } public int SourceCount { get { return _sourceCount; } } } } ================================================ FILE: Composite/Data/Foundation/DataFacadeReflectionCache.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.C1Console.Events; using Composite.Core.Collections.Generic; namespace Composite.Data.Foundation { internal static class DataFacadeReflectionCache { private static Hashtable<Type, Type> _listTypeCache = new Hashtable<Type, Type>(); private static Hashtable<Type, MethodInfo> _addRangeToListMethodInfoCache = new Hashtable<Type, MethodInfo>(); private static Hashtable<Type, MethodInfo> _toListMethodInfo = new Hashtable<Type, MethodInfo>(); private static Hashtable<Type, MethodInfo> _asQueryableMethodInfo = new Hashtable<Type, MethodInfo>(); private static Hashtable<Type, Hashtable<Type, MethodInfo>> _dataFacadeQueryableExecuteMethodInfoCache = new Hashtable<Type, Hashtable<Type, MethodInfo>>(); private static Hashtable<Type, MethodInfo> _dataFacadeQueryableGetEnumeratorMethodInfoCache = new Hashtable<Type, MethodInfo>(); private static Hashtable<Type, MethodInfo> _createQueryMethodInfo = new Hashtable<Type, MethodInfo>(); private static readonly MethodInfo IQueryProvider_CreateQuery; private static readonly MethodInfo Queryable_AsQueryable; private static readonly object _lock = new object(); static DataFacadeReflectionCache() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); IQueryProvider_CreateQuery = typeof (IQueryProvider).GetMethods().First(m => m.Name == "CreateQuery" && m.IsGenericMethod); Queryable_AsQueryable = typeof (Queryable).GetMethods().First(m => m.Name == "AsQueryable" && m.IsGenericMethod); } private static Type List_GetType(Type type) { Type listType; if (!_listTypeCache.TryGetValue(type, out listType)) { lock (_lock) { if (!_listTypeCache.TryGetValue(type, out listType)) { listType = typeof(List<>); listType = listType.MakeGenericType(new Type[] { type }); _listTypeCache.Add(type, listType); } } } return listType; } /// <summary> /// Creates a new instance of List <<paramref name="type"/>> /// </summary> public static IList List_New(Type type) { var listType = List_GetType(type); return Activator.CreateInstance(listType) as IList; } public static MethodInfo List_AddRangeMethodInfo(Type type) { MethodInfo addRangeToListMethodInfo; if (!_addRangeToListMethodInfoCache.TryGetValue(type, out addRangeToListMethodInfo)) { lock (_lock) { if (!_addRangeToListMethodInfoCache.TryGetValue(type, out addRangeToListMethodInfo)) { Type listType = List_GetType(type); addRangeToListMethodInfo = listType.GetMethod("AddRange"); _addRangeToListMethodInfoCache.Add(type, addRangeToListMethodInfo); } } } return addRangeToListMethodInfo; } public static MethodInfo Enumerable_ToList(Type type) { MethodInfo toListMethodInfo; if (!_toListMethodInfo.TryGetValue(type, out toListMethodInfo)) { lock (_lock) { if (!_toListMethodInfo.TryGetValue(type, out toListMethodInfo)) { toListMethodInfo = typeof (Enumerable).GetMethod("ToList"); toListMethodInfo = toListMethodInfo.MakeGenericMethod(new Type[] {type}); _toListMethodInfo.Add(type, toListMethodInfo); } } } return toListMethodInfo; } public static MethodInfo Queryable_AsQueryableMethodInfo(Type type) { MethodInfo asQueryableMethodInfo; if (!_asQueryableMethodInfo.TryGetValue(type, out asQueryableMethodInfo)) { lock (_lock) { if (!_asQueryableMethodInfo.TryGetValue(type, out asQueryableMethodInfo)) { asQueryableMethodInfo = Queryable_AsQueryable.MakeGenericMethod(new[] { type }); _asQueryableMethodInfo.Add(type, asQueryableMethodInfo); } } } return asQueryableMethodInfo; } public static MethodInfo GetDataFacadeQueryableExecuteMethodInfo(Type genericType, Type expressionType) { MethodInfo methodInfo; Hashtable<Type, MethodInfo> methodInfoes; if (!_dataFacadeQueryableExecuteMethodInfoCache.TryGetValue(genericType, out methodInfoes) || !methodInfoes.TryGetValue(expressionType, out methodInfo)) { lock (_lock) { if (!_dataFacadeQueryableExecuteMethodInfoCache.TryGetValue(genericType, out methodInfoes)) { methodInfoes = new Hashtable<Type, MethodInfo>(); _dataFacadeQueryableExecuteMethodInfoCache.Add(genericType, methodInfoes); } if (!methodInfoes.TryGetValue(expressionType, out methodInfo)) { Type type = typeof (DataFacadeQueryable<>).MakeGenericType(new Type[] {genericType}); methodInfo = type.GetMethods().First(m => m.Name == "Execute" && m.IsGenericMethod); methodInfo = methodInfo.MakeGenericMethod(new Type[] {expressionType}); methodInfoes.Add(expressionType, methodInfo); } } } return methodInfo; } public static MethodInfo GetDataFacadeQueryableGetEnumeratorMethodInfo(Type genericType) { MethodInfo methodInfo; if (!_dataFacadeQueryableGetEnumeratorMethodInfoCache.TryGetValue(genericType, out methodInfo)) { lock (_lock) { if (!_dataFacadeQueryableGetEnumeratorMethodInfoCache.TryGetValue(genericType, out methodInfo)) { Type type = typeof (DataFacadeQueryable<>).MakeGenericType(new Type[] {genericType}); methodInfo = type.GetMethods().First(m => m.Name == "GetEnumerator"); _dataFacadeQueryableGetEnumeratorMethodInfoCache.Add(genericType, methodInfo); } } } return methodInfo; } public static MethodInfo GetCreateQueryMethodInfo(Type genericType) { MethodInfo methodInfo; if (!_createQueryMethodInfo.TryGetValue(genericType, out methodInfo)) { lock (_lock) { if (!_createQueryMethodInfo.TryGetValue(genericType, out methodInfo)) { methodInfo = IQueryProvider_CreateQuery.MakeGenericMethod(genericType); _createQueryMethodInfo.Add(genericType, methodInfo); } } } return methodInfo; } private static void Flush() { lock (_lock) { _listTypeCache = new Hashtable<Type, Type>(); _addRangeToListMethodInfoCache = new Hashtable<Type, MethodInfo>(); _toListMethodInfo = new Hashtable<Type, MethodInfo>(); _asQueryableMethodInfo = new Hashtable<Type, MethodInfo>(); _dataFacadeQueryableExecuteMethodInfoCache = new Hashtable<Type, Hashtable<Type, MethodInfo>>(); _dataFacadeQueryableGetEnumeratorMethodInfoCache = new Hashtable<Type, MethodInfo>(); _createQueryMethodInfo = new Hashtable<Type, MethodInfo>(); } } } } ================================================ FILE: Composite/Data/Foundation/DataInterfaceAutoUpdater.cs ================================================ using System; using System.Linq; using Composite.Core; using Composite.Core.Application; using Composite.Data.DynamicTypes; using Composite.Core.Instrumentation; namespace Composite.Data.Foundation { internal static class DataInterfaceAutoUpdater { private static readonly string LogTitle = typeof (DataInterfaceAutoUpdater).Name; internal static bool EnsureUpdateAllInterfaces() { using (AppDomainLocker.NewLock()) using (TimerProfilerFacade.CreateTimerProfiler()) { bool doFlush = false; var knownInterfaces = DataProviderRegistry.AllKnownInterfaces.ToList(); foreach (Type interfaceType in knownInterfaces) { if (!interfaceType.IsAutoUpdateble()) { continue; } foreach (string providerName in DataProviderRegistry.GetDataProviderNamesByInterfaceType(interfaceType)) { try { if (DynamicTypeManager.EnsureUpdateStore(interfaceType, providerName, true)) { doFlush = true; } } catch (TypeUpdateVersionException) { throw; } catch (TypeInitializationException tiex) { throw new InvalidOperationException("The data type meta stored did not initialize. Check configuration", tiex); } catch (Exception ex) { Log.LogCritical(LogTitle, "Update failed for the interface '{0}' on the '{1}' data provider", interfaceType, providerName); Log.LogCritical(LogTitle, ex); } } } return doFlush; } } internal static void TestEnsureUpdateAllInterfaces() { using (TimerProfilerFacade.CreateTimerProfiler()) { foreach (Type interfaceType in DataProviderRegistry.AllInterfaces) { if (!interfaceType.IsAutoUpdateble() || interfaceType.IsGenerated()) { continue; } foreach (string providerName in DataProviderRegistry.GetDataProviderNamesByInterfaceType(interfaceType)) { try { if (DynamicTypeManager.IsEnsureUpdateStoreNeeded(interfaceType)) { Log.LogError(LogTitle, "Autoupdating the data interface '{0}' on the '{1}' data provider failed!", interfaceType, providerName); } } catch (Exception ex) { Log.LogCritical(LogTitle, "Update failed for the interface '{0}' on the '{1}' data provider", interfaceType, providerName); Log.LogCritical(LogTitle, ex); } } } } } } } ================================================ FILE: Composite/Data/Foundation/DataProviderRegistry.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using Composite.C1Console.Events; namespace Composite.Data.Foundation { /// <summary> /// This should only be used intern in the Composite.Data namespace! /// </summary> internal sealed class DataProviderRegistry { private static IDataProviderRegistry _dataProviderRegistry = new DataProviderRegistryImpl(); static DataProviderRegistry() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } internal static IDataProviderRegistry Implementation { get { return _dataProviderRegistry; } set { _dataProviderRegistry = value; } } public static string DefaultDynamicTypeDataProviderName { get { using (GlobalInitializerFacade.CoreIsInitializedScope) { return _dataProviderRegistry.DefaultDynamicTypeDataProviderName; } } } public static IEnumerable<Type> AllInterfaces { get { using (GlobalInitializerFacade.CoreIsInitializedScope) { return _dataProviderRegistry.AllInterfaces; } } } /// <summary> /// This will include currently non-supported interfaces. /// That is, interfaces that exists, but for some reason /// does nok work as a data type. /// </summary> public static IEnumerable<Type> AllKnownInterfaces { get { using (GlobalInitializerFacade.CoreIsInitializedScope) { return _dataProviderRegistry.AllKnownInterfaces; } } } public static IEnumerable<Type> GeneratedInterfaces { get { using (GlobalInitializerFacade.CoreIsInitializedScope) { return _dataProviderRegistry.GeneratedInterfaces; } } } public static IEnumerable<string> DataProviderNames { get { using (GlobalInitializerFacade.CoreIsInitializedScope) { return _dataProviderRegistry.DataProviderNames; } } } public static IEnumerable<string> DynamicDataProviderNames { get { using (GlobalInitializerFacade.CoreIsInitializedScope) { return _dataProviderRegistry.DynamicDataProviderNames; } } } public static List<string> GetDataProviderNamesByInterfaceType(Type interfaceType) { using (GlobalInitializerFacade.CoreIsInitializedScope) { return _dataProviderRegistry.GetDataProviderNamesByInterfaceType(interfaceType); } } public static List<string> GetWriteableDataProviderNamesByInterfaceType(Type interfaceType) { using (GlobalInitializerFacade.CoreIsInitializedScope) { return _dataProviderRegistry.GetWriteableDataProviderNamesByInterfaceType(interfaceType); } } /// <summary> /// This method adds a new supported data type to the registry. /// This should be used if a data provider has extended the /// number of supported interfaces at runtime. /// </summary> /// <param name="interaceType"></param> /// <param name="providerName"></param> /// <param name="isWritableProvider"></param> public static void AddNewDataType(Type interaceType, string providerName, bool isWritableProvider = true) { using (GlobalInitializerFacade.CoreIsInitializedScope) { _dataProviderRegistry.AddNewDataType(interaceType, providerName); } } public static void AddKnownDataType(Type interaceType, string providerName) { _dataProviderRegistry.AddKnownDataType(interaceType, providerName); } public static void UnregisterDataType(Type interfaceType, string providerName) { _dataProviderRegistry.UnregisterDataType(interfaceType, providerName); } public static void RegisterDataTypeInitializationError(Type interfaceType, Exception exception) { _dataProviderRegistry.RegisterDataTypeInitializationError(interfaceType, exception); } /// <summary> /// Checks whether the data store for the specified data type was created without errors. /// If any errors occurred, an exception will be thrown. /// </summary> /// <param name="interfaceType">The interface type</param> public static void CheckInitializationErrors(Type interfaceType) { _dataProviderRegistry.CheckInitializationErrors(interfaceType); } internal static void InitializeDataTypes() { if (RuntimeInformation.IsDebugBuild) { GlobalInitializerFacade.ValidateIsOnlyCalledFromGlobalInitializerFacade(new StackTrace()); } _dataProviderRegistry.InitializeDataTypes(); } public static void Flush() { _dataProviderRegistry.Flush(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } } } ================================================ FILE: Composite/Data/Foundation/DataProviderRegistryImpl.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.Core; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Data.Foundation.PluginFacades; using Composite.Data.Plugins.DataProvider; using Composite.Data.Plugins.DataProvider.Runtime; using Composite.Core.Instrumentation; using Composite.Core.Types; namespace Composite.Data.Foundation { internal sealed class DataProviderRegistryImpl : IDataProviderRegistry { private string _defaultDynamicTypeDataProviderName; private List<string> _dataProviderNames; private Dictionary<Type, List<string>> _interfaceTypeToReadableProviderNames; private Dictionary<Type, List<string>> _interfaceTypeToWriteableProviderNames; private Dictionary<Type, List<string>> _knownInterfaceTypeToDynamicProviderNames; private List<Type> _generatedInterfaceTypes; private Hashtable<Type, Exception> _initializationErrors; public string DefaultDynamicTypeDataProviderName { get { if (_defaultDynamicTypeDataProviderName == null || !_dataProviderNames.Contains(_defaultDynamicTypeDataProviderName)) { throw new InvalidOperationException("Failed to locate the default provider name for dynamic types. Please check the configuration."); } return _defaultDynamicTypeDataProviderName; } } public IEnumerable<Type> AllInterfaces { get { return _interfaceTypeToReadableProviderNames.Keys.ToList(); } } public IEnumerable<Type> AllKnownInterfaces { get { return _interfaceTypeToReadableProviderNames.Keys. Concat(_knownInterfaceTypeToDynamicProviderNames.Keys). ToList(); } } public IEnumerable<Type> GeneratedInterfaces { get { return _generatedInterfaceTypes; } } public IEnumerable<string> DataProviderNames { get { return _dataProviderNames; } } public IEnumerable<string> DynamicDataProviderNames { get { return DataProviderRegistry.DataProviderNames.Where(DataProviderPluginFacade.IsDynamicProvider); } } public List<string> GetDataProviderNamesByInterfaceType(Type interfaceType) { List<string> providerNames = new List<string>(); if (_interfaceTypeToReadableProviderNames.ContainsKey(interfaceType)) { providerNames.AddRange(_interfaceTypeToReadableProviderNames[interfaceType]); } else if (_knownInterfaceTypeToDynamicProviderNames.ContainsKey(interfaceType)) { providerNames.AddRange(_knownInterfaceTypeToDynamicProviderNames[interfaceType]); } return providerNames; } public List<string> GetWriteableDataProviderNamesByInterfaceType(Type interfaceType) { if (!_interfaceTypeToWriteableProviderNames.ContainsKey(interfaceType)) { return new List<string>(); } return _interfaceTypeToWriteableProviderNames[interfaceType]; } public void AddNewDataType(Type interaceType, string providerName, bool isWritableProvider = true) { AddType(interaceType, providerName, isWritableProvider); } public void AddKnownDataType(Type interaceType, string providerName) { List<string> providers; if (!_knownInterfaceTypeToDynamicProviderNames.TryGetValue(interaceType, out providers)) { providers = new List<string>(); _knownInterfaceTypeToDynamicProviderNames.Add(interaceType, providers); } providers.Add(providerName); } public void UnregisterDataType(Type interfaceType, string providerName) { List<string> providerNames; if (!_interfaceTypeToReadableProviderNames.TryGetValue(interfaceType, out providerNames)) { return; } providerNames.Remove(providerName); } public void RegisterDataTypeInitializationError(Type interfaceType, Exception exception) { _initializationErrors[interfaceType] = exception; } public void CheckInitializationErrors(Type interfaceType) { if (_initializationErrors.ContainsKey(interfaceType)) { var ex = _initializationErrors[interfaceType]; throw new InvalidOperationException("Failed to initialize data type '{0}'".FormatWith(interfaceType.FullName), ex); } } public void InitializeDataTypes() { using (TimerProfilerFacade.CreateTimerProfiler()) { _dataProviderNames = new List<string>(); _interfaceTypeToReadableProviderNames = new Dictionary<Type, List<string>>(); _interfaceTypeToWriteableProviderNames = new Dictionary<Type, List<string>>(); _knownInterfaceTypeToDynamicProviderNames = new Dictionary<Type, List<string>>(); _initializationErrors = new Hashtable<Type, Exception>(); _generatedInterfaceTypes = new List<Type>(); if (DataProviderPluginFacade.HasConfiguration()) { BuildDataProviderNames(); BuildDictionaries(); } else if (RuntimeInformation.IsDebugBuild) { Log.LogError("DataProviderRegistry", string.Format("Failed to load the configuration section '{0}' from the configuration", DataProviderSettings.SectionName)); } } } public void Flush() { _defaultDynamicTypeDataProviderName = null; _dataProviderNames = null; _interfaceTypeToReadableProviderNames = null; _interfaceTypeToWriteableProviderNames = null; _knownInterfaceTypeToDynamicProviderNames = null; _generatedInterfaceTypes = null; } private void AddType(Type typeToAdd, string providerName, bool writeableProvider) { Verify.That(typeToAdd.IsInterface, "The data provider {0} returned an non-interface ({1})", providerName, typeToAdd); Verify.That(typeof(IData).IsAssignableFrom(typeToAdd), "The data provider {0} returned an non IData interface ({1})", providerName, typeToAdd); using (TimerProfilerFacade.CreateTimerProfiler()) { List<DataScopeIdentifier> supportedDataScopes = typeToAdd.GetSupportedDataScopes().ToList(); if (supportedDataScopes.Count == 0) { throw new InvalidOperationException(string.Format("The data provider {0} returned an IData interface ({1}) with no data scopes defined. Use the {2} attribute to define scopes.", providerName, typeToAdd, typeof(DataScopeAttribute))); } foreach (PropertyInfo propertyInfo in typeToAdd.GetPropertiesRecursively()) { bool containsBadAttribute = propertyInfo.GetCustomAttributesRecursively<Microsoft.Practices.EnterpriseLibrary.Validation.Validators.StringLengthValidatorAttribute>().Any(); if (!containsBadAttribute) continue; #pragma warning disable 0612 Log.LogWarning("DataProviderRegistry", string.Format("The property named '{0}' on the type '{1}' has an attribute of type '{2}' wich is not supported, use '{3}'", typeToAdd, propertyInfo.Name, typeof(Microsoft.Practices.EnterpriseLibrary.Validation.Validators.StringLengthValidatorAttribute), typeof(Composite.Data.Validation.Validators.StringLengthValidatorAttribute))); #pragma warning restore 0612 } var readableList = _interfaceTypeToReadableProviderNames.GetOrAdd(typeToAdd, () => new List<string>()); if (!readableList.Contains(providerName)) { readableList.Add(providerName); } if (writeableProvider) { var writableList = _interfaceTypeToWriteableProviderNames.GetOrAdd(typeToAdd, () => new List<string>()); if (!writableList.Contains(providerName)) { writableList.Add(providerName); } } } } private void BuildDataProviderNames() { using (TimerProfilerFacade.CreateTimerProfiler()) { var dataProviderSettings = ConfigurationServices.ConfigurationSource.GetSection(DataProviderSettings.SectionName) as DataProviderSettings; _defaultDynamicTypeDataProviderName = dataProviderSettings.DefaultDynamicTypeDataProviderName; foreach (DataProviderData data in dataProviderSettings.DataProviderPlugins) { _dataProviderNames.Add(data.Name); } } } private void BuildDictionaries() { using (TimerProfilerFacade.CreateTimerProfiler("Adding supported types")) { foreach (string providerName in _dataProviderNames) { IEnumerable<Type> types = DataProviderPluginFacade.GetSupportedInterfaces(providerName); bool writeableProvider = DataProviderPluginFacade.IsWriteableProvider(providerName); foreach (Type type in types) { AddType(type, providerName, writeableProvider); } if (DataProviderPluginFacade.IsGeneratedTypesProvider(providerName)) { IEnumerable<Type> generatedTypes = DataProviderPluginFacade.GetGeneratedInterfaces(providerName); foreach (Type type in generatedTypes) { AddType(type, providerName, writeableProvider); if (!_generatedInterfaceTypes.Contains(type)) { _generatedInterfaceTypes.Add(type); } } } } } using (TimerProfilerFacade.CreateTimerProfiler("Adding known interfaces")) { foreach (string providerName in _dataProviderNames) { if (DataProviderPluginFacade.IsDynamicProvider(providerName)) { IEnumerable<Type> knownTypes = DataProviderPluginFacade.GetKnownInterfaces(providerName); foreach (Type knownType in knownTypes) { if (!_interfaceTypeToReadableProviderNames.Keys.Contains(knownType)) { List<string> providerNames; if (!_knownInterfaceTypeToDynamicProviderNames.TryGetValue(knownType, out providerNames)) { providerNames = new List<string>(); _knownInterfaceTypeToDynamicProviderNames.Add(knownType, providerNames); if (RuntimeInformation.IsDebugBuild) { Log.LogVerbose("DataProviderRegistry", "Adding known IData interface: {0}", knownType); } } providerNames.Add(providerName); } } } } } } } } ================================================ FILE: Composite/Data/Foundation/DataReferenceRegistry.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using Composite.C1Console.Events; using Composite.Core; namespace Composite.Data.Foundation { internal static class DataReferenceRegistry { private static readonly string LogTitle = "DataReferenceRegistry"; private static Dictionary<Type, List<Type>> _referencedToReferees = new Dictionary<Type, List<Type>>(); private static Dictionary<Type, IReadOnlyList<ForeignPropertyInfo>> _foreignKeyProperties = new Dictionary<Type, IReadOnlyList<ForeignPropertyInfo>>(); static DataReferenceRegistry() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } public static IReadOnlyCollection<Type> GetRefereeTypes(Type referencedType) { Verify.ArgumentNotNull(referencedType, "referencedType"); List<Type> refereeTypes = new List<Type>(); // TODO: rewrite using concurrent dictionaries using (GlobalInitializerFacade.CoreIsInitializedScope) { foreach (var key in _referencedToReferees.Keys) { if (referencedType.IsAssignableFrom(key)) { _referencedToReferees[key].ForEach(refereeTypes.Add); } } } return refereeTypes; } [Obsolete("Use 'GetForeignKeyProperties' instead")] public static List<ForeignPropertyInfo> GetForeignKeyPropertyInfos(Type refereeType) { return GetForeignKeyProperties(refereeType).ToList(); } public static IReadOnlyCollection<ForeignPropertyInfo> GetForeignKeyProperties(Type refereeType) { Verify.ArgumentNotNull(refereeType, "refereeType"); IReadOnlyList<ForeignPropertyInfo> foreignKeyProperties; using (GlobalInitializerFacade.CoreIsInitializedScope) { if (!_foreignKeyProperties.TryGetValue(refereeType, out foreignKeyProperties)) { return Array.Empty<ForeignPropertyInfo>(); } } return foreignKeyProperties; } internal static void Initialize_PostDataTypes() { if (RuntimeInformation.IsDebugBuild) { GlobalInitializerFacade.ValidateIsOnlyCalledFromGlobalInitializerFacade(new StackTrace()); } _referencedToReferees = new Dictionary<Type, List<Type>>(); _foreignKeyProperties = new Dictionary<Type, IReadOnlyList<ForeignPropertyInfo>>(); foreach (Type type in DataProviderRegistry.AllInterfaces) { AddNewType(type); } } private static void AddNewType(Type interfaceType) { var foreignKeyProperties = DataAttributeFacade.GetDataReferenceProperties(interfaceType); foreach (ForeignPropertyInfo foreignKeyPropertyInfo in foreignKeyProperties) { if (!foreignKeyPropertyInfo.SourcePropertyInfo.CanRead) throw new InvalidOperationException( $"The property '{foreignKeyPropertyInfo.SourcePropertyInfo}' shoud have a getter"); if (foreignKeyPropertyInfo.TargetType.IsNotReferenceable()) throw new InvalidOperationException( $"The referenced type '{foreignKeyPropertyInfo.TargetType}' is marked NotReferenceable and can not be referenced by the interfaceType '{interfaceType}'"); PropertyInfo propertyInfo = foreignKeyPropertyInfo.TargetType.GetDataPropertyRecursively(foreignKeyPropertyInfo.TargetKeyPropertyName); Verify.IsNotNull(propertyInfo, "The data type '{0}' does not contain a property named '{1}' as specified by the '{2}' attribute on the data type '{3}'", foreignKeyPropertyInfo.TargetType, foreignKeyPropertyInfo.TargetKeyPropertyName, typeof(ForeignKeyAttribute), foreignKeyPropertyInfo.SourcePropertyInfo.DeclaringType); Verify.That(propertyInfo.CanRead, "The property '{0}' should have a getter", propertyInfo); if (foreignKeyPropertyInfo.IsNullableString && (propertyInfo.PropertyType != typeof(string))) throw new InvalidOperationException("NullableString can only be used when the foreign key is of type string"); Type sourcePropertyType = foreignKeyPropertyInfo.SourcePropertyInfo.PropertyType; if (sourcePropertyType.IsGenericType && (sourcePropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))) { // Handling og Nullable<> sourcePropertyType = sourcePropertyType.GetGenericArguments()[0]; } if (propertyInfo.PropertyType != sourcePropertyType) throw new InvalidOperationException( $"Type mismatch '{propertyInfo.PropertyType}' and '{foreignKeyPropertyInfo.SourcePropertyInfo.PropertyType}' does not match from the two properties '{propertyInfo}' and '{foreignKeyPropertyInfo.SourcePropertyInfo}'"); foreignKeyPropertyInfo.TargetKeyPropertyInfo = propertyInfo; } _foreignKeyProperties.Add(interfaceType, foreignKeyProperties); foreach (ForeignPropertyInfo foreignKeyPropertyInfo in foreignKeyProperties) { List<Type> referees; if (!_referencedToReferees.TryGetValue(foreignKeyPropertyInfo.TargetType, out referees)) { referees = new List<Type>(); _referencedToReferees.Add(foreignKeyPropertyInfo.TargetType, referees); } else { if(referees.Contains(interfaceType)) { continue; } } referees.Add(interfaceType); if (!DataProviderRegistry.AllInterfaces.Contains(foreignKeyPropertyInfo.TargetType)) { Log.LogCritical(LogTitle, $"The one type '{interfaceType}' is referring the non supported data type '{foreignKeyPropertyInfo.TargetType}'"); } } } private static void Flush() { _referencedToReferees = new Dictionary<Type, List<Type>>(); _foreignKeyProperties = new Dictionary<Type, IReadOnlyList<ForeignPropertyInfo>>(); } } } ================================================ FILE: Composite/Data/Foundation/DataStoreExistenceVerifier.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; namespace Composite.Data.Foundation { internal static class DataStoreExistenceVerifier { private static IDataStoreExistenceVerifier _dataStoreExistenceVerifier = new DataStoreExistenceVerifierImpl(); internal static IDataStoreExistenceVerifier Implementation { get { return _dataStoreExistenceVerifier; } set { _dataStoreExistenceVerifier = value; } } public static IEnumerable<Type> InterfaceTypes { get { return _dataStoreExistenceVerifier.InterfaceTypes; } } public static bool EnsureDataStores() { if (RuntimeInformation.IsDebugBuild) { GlobalInitializerFacade.ValidateIsOnlyCalledFromGlobalInitializerFacade(new StackTrace()); } return _dataStoreExistenceVerifier.EnsureDataStores(); } } } ================================================ FILE: Composite/Data/Foundation/DataStoreExistenceVerifierImpl.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Core; using Composite.Data.DynamicTypes; using Composite.Data.Foundation.PluginFacades; using Composite.Data.Plugins.DataProvider.Runtime; using Composite.Data.Types; using Composite.Plugins.WebClient.SessionStateProviders.DefaultSessionStateProvider; namespace Composite.Data.Foundation { internal sealed class DataStoreExistenceVerifierImpl : IDataStoreExistenceVerifier { private const string LogTitle = "DataStoreExistenceVerifier"; // Interfaces in this list will have a store created on system start if they do not exists private static readonly List<Type> _interfaceTypes = new List<Type> { typeof(ICompositionContainer), typeof(ICustomFunctionCallEditorMapping), typeof(IDataItemTreeAttachmentPoint), typeof(IFlowInformation), typeof(IFolderWhiteList), typeof(IGeneratedTypeWhiteList), typeof(IHostnameBinding), typeof(IInlineFunction), typeof(IInlineFunctionAssemblyReference), typeof(ILockingInformation), typeof(IMediaFile), typeof(IMediaFileData), typeof(IMediaFileFolder), typeof(IMediaFolderData), typeof(IMethodBasedFunctionInfo), typeof(INamedFunctionCall), typeof(IPackageServerSource), typeof(IPage), typeof(IPageFolderDefinition), typeof(IPageMetaDataDefinition), typeof(IPagePlaceholderContent), typeof(IPageStructure), typeof(IXmlPageTemplate), typeof(IPageType), typeof(IPageTypeDataFolderTypeLink), typeof(IPageTypeDefaultPageContent), typeof(IPageTypeMetaDataTypeLink), typeof(IPageTypePageTemplateRestriction), typeof(IPageTypeParentRestriction), typeof(IPageTypeTreeLink), typeof(IPublishSchedule), typeof(IUnpublishSchedule), typeof(IParameter), typeof(ISearchEngineOptimizationKeyword), typeof(ISessionStateEntry), typeof(ISqlConnection), typeof(ISqlFunctionInfo), typeof(ISystemActiveLocale), typeof(ITaskItem), typeof(IUrlConfiguration), typeof(IUser), typeof(IUserPasswordHistory), typeof(IUserActiveLocale), typeof(IUserActivePerspective), typeof(IUserConsoleInformation), typeof(IUserDeveloperSettings), typeof(IUserFormLogin), typeof(IUserGroup), typeof(IUserGroupActiveLocale), typeof(IUserGroupActivePerspective), typeof(IUserGroupPermissionDefinition), typeof(IUserGroupPermissionDefinitionPermissionType), typeof(IUserPermissionDefinition), typeof(IUserPermissionDefinitionPermissionType), typeof(IUserSettings), typeof(IUserUserGroupRelation), typeof(IVisualFunction), typeof(IXsltFunction) }; public IEnumerable<Type> InterfaceTypes { get { return _interfaceTypes; } } public bool EnsureDataStores() { if (!DataProviderPluginFacade.HasConfiguration()) { Log.LogError(LogTitle, "Failed to load the configuration section '{0}' from the configuration", DataProviderSettings.SectionName); return false; } var typeDescriptors = new List<DataTypeDescriptor>(); foreach (Type type in _interfaceTypes) { try { if (!DataProviderRegistry.AllKnownInterfaces.Contains(type)) { var dataTypeDescriptor = DynamicTypeManager.BuildNewDataTypeDescriptor(type); dataTypeDescriptor.Validate(); typeDescriptors.Add(dataTypeDescriptor); } } catch (Exception ex) { throw new InvalidOperationException(string.Format("Failed to validate type '{0}'", type), ex); } } if (typeDescriptors.Any()) { DataProviderPluginFacade.CreateStores(DataProviderRegistry.DefaultDynamicTypeDataProviderName, typeDescriptors); string typeNames = string.Join(", ", typeDescriptors.Select(t => t.GetFullInterfaceName())); Log.LogVerbose(LogTitle, "Stores for the following data types were created: " + typeNames); } return typeDescriptors.Count > 0; } } } ================================================ FILE: Composite/Data/Foundation/DataWrappingFacade.cs ================================================ using System; using Composite.Data.Foundation.CodeGeneration; namespace Composite.Data.Foundation { /// <summary> /// Wraps data object, so changes to the original object won't be applied until the object is saved. Used for wrapping cached data. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DataWrappingFacade { /// <exclude /> public static T Wrap<T>(T value) where T: class, IData { if (value is IDataWrapper) return value; Type wrapperType = WrapperSingleton<T>.WrapperType; return (T)Activator.CreateInstance(wrapperType, new object[] { value }); } /// <exclude /> public static T UnWrap<T>(T value) where T: class, IData { while (value is IDataWrapper) { var wrappedItem = value as IDataWrapper; wrappedItem.CommitData(); value = (T)wrappedItem.WrappedData; } return value; } private static class WrapperSingleton<T> { private static readonly Type _wrapperType; static WrapperSingleton() { _wrapperType = DataWrapperTypeManager.GetDataWrapperType(typeof(T)); } public static Type WrapperType { get { return _wrapperType; } } } } } ================================================ FILE: Composite/Data/Foundation/EmptyDataClassTypeManager.cs ================================================ using System; using System.CodeDom; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Events; using Composite.Core; using Composite.Core.Collections.Generic; using Composite.Core.Types; using Composite.Data.DynamicTypes; using Composite.Data.Foundation.CodeGeneration; namespace Composite.Data.Foundation { /// <summary> /// This class caches and if needed creates data empty classes runtime. /// </summary> internal static class EmptyDataClassTypeManager { private static readonly object _lock = new object(); private static readonly ResourceLocker<Resources> ResourceLocker = new ResourceLocker<Resources>(new Resources(), Resources.Initialize); static EmptyDataClassTypeManager() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } /// <summary> /// This method will return the type of the empty data class type. /// If the type does not exist, one will be runtime code generated /// using the type to get a data type descriptor. /// </summary> /// <param name="interfaceType">The data interface type to get the empty class type for.</param> /// <param name="forceReCompilation"> /// If this is true a new empty class will be /// compiled at runtime regardless if it exists or not. /// Use with caution! /// </param> /// <returns>The empty class type for the given data interface type.</returns> public static Type GetEmptyDataClassType(Type interfaceType, bool forceReCompilation = false) { VerifyAssemblyLocation(interfaceType); var dataTypeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(interfaceType, true); return GetEmptyDataClassType(dataTypeDescriptor, forceReCompilation); } /// <summary> /// This method will return the type of the empty data class type. /// If the type does not exist, one will be runtime code generated /// using the <paramref name="dataTypeDescriptor"/>. /// </summary> /// <param name="dataTypeDescriptor"> /// The data type descriptor for the data type to get /// the empty class type for. /// </param> /// <param name="forceReCompilation"> /// If this is true a new empty class will be /// compiled at runtime regardless if it exists or not. /// Use with caution! /// </param> /// <returns>The empty class type for the given data interface type.</returns> public static Type GetEmptyDataClassType(DataTypeDescriptor dataTypeDescriptor, bool forceReCompilation = false) { if (!string.IsNullOrEmpty(dataTypeDescriptor.BuildNewHandlerTypeName)) { return GetEmptyClassFromBuildNewHandler(dataTypeDescriptor); } if (forceReCompilation) { return CreateEmptyDataClassType(dataTypeDescriptor); } Type interfaceType = TypeManager.TryGetType(dataTypeDescriptor.TypeManagerTypeName); string emptyClassFullName = EmptyDataClassCodeGenerator.GetEmptyClassTypeFullName(dataTypeDescriptor); Type emptyClassType = TypeManager.TryGetType(emptyClassFullName); bool isRecompileNeeded = true; if (interfaceType != null) { isRecompileNeeded = CodeGenerationManager.IsRecompileNeeded(interfaceType, new[] { emptyClassType }); } if (isRecompileNeeded) { lock (_lock) { interfaceType = TypeManager.TryGetType(dataTypeDescriptor.GetFullInterfaceName()); emptyClassType = TypeManager.TryGetType(emptyClassFullName); if (interfaceType != null) { isRecompileNeeded = CodeGenerationManager.IsRecompileNeeded(interfaceType, new[] { emptyClassType }); } if (isRecompileNeeded) { emptyClassType = CreateEmptyDataClassType(dataTypeDescriptor); } } } return emptyClassType; } private static Type GetEmptyClassFromBuildNewHandler(DataTypeDescriptor dataTypeDescriptor) { Type buildNewHandlerType = TypeManager.GetType(dataTypeDescriptor.BuildNewHandlerTypeName); IBuildNewHandler buildNewHandler = (IBuildNewHandler)Activator.CreateInstance(buildNewHandlerType); Type dataType = DataTypeTypesManager.GetDataType(dataTypeDescriptor); VerifyAssemblyLocation(dataType); return buildNewHandler.GetTypeToBuild(dataType); } private static void VerifyAssemblyLocation(Type interfaceType) { if (!DataTypeTypesManager.IsAllowedDataTypeAssembly(interfaceType)) { string message = $"The data interface '{interfaceType}' is not located in an assembly in the website Bin folder. Please move it to that location"; Log.LogError(nameof(EmptyDataClassTypeManager), message); throw new InvalidOperationException(message); } } internal static Type CreateEmptyDataClassType(DataTypeDescriptor dataTypeDescriptor, Type baseClassType = null, CodeAttributeDeclaration codeAttributeDeclaration = null) { var codeGenerationBuilder = new CodeGenerationBuilder("EmptyDataClass: " + dataTypeDescriptor.Name); EmptyDataClassCodeGenerator.AddAssemblyReferences(codeGenerationBuilder, dataTypeDescriptor); EmptyDataClassCodeGenerator.AddEmptyDataClassTypeCode(codeGenerationBuilder, dataTypeDescriptor, baseClassType, codeAttributeDeclaration); IEnumerable<Type> types = CodeGenerationManager.CompileRuntimeTempTypes(codeGenerationBuilder); return types.Single(); } private static void Flush() { ResourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private sealed class Resources { internal Dictionary<Guid, Type> DataEmptyClassTypes { get; set; } public static void Initialize(Resources resources) { resources.DataEmptyClassTypes = new Dictionary<Guid, Type>(); } } } } ================================================ FILE: Composite/Data/Foundation/IDataFacadeQueryable.cs ================================================ using System; using System.Linq; using System.Collections.Generic; namespace Composite.Data.Foundation { internal interface IDataFacadeQueryable { ICollection<IQueryable> Sources { get; } Type InterfaceType { get; } } } ================================================ FILE: Composite/Data/Foundation/IDataProviderRegistry.cs ================================================ using System; using System.Collections.Generic; namespace Composite.Data.Foundation { internal interface IDataProviderRegistry { string DefaultDynamicTypeDataProviderName { get; } IEnumerable<Type> AllInterfaces { get; } IEnumerable<Type> AllKnownInterfaces { get; } IEnumerable<Type> GeneratedInterfaces { get; } IEnumerable<string> DataProviderNames { get; } IEnumerable<string> DynamicDataProviderNames { get; } List<string> GetDataProviderNamesByInterfaceType(Type interfaceType); List<string> GetWriteableDataProviderNamesByInterfaceType(Type interfaceType); void AddNewDataType(Type interaceType, string providerName, bool isWritableProvider = true); void AddKnownDataType(Type interaceType, string providerName); void UnregisterDataType(Type interfaceType, string providerName); void RegisterDataTypeInitializationError(Type interfaceType, Exception exception); void CheckInitializationErrors(Type interfaceType); void InitializeDataTypes(); void Flush(); } } ================================================ FILE: Composite/Data/Foundation/IDataStoreExistenceVerifier.cs ================================================ using System.Collections.Generic; using System; namespace Composite.Data.Foundation { internal interface IDataStoreExistenceVerifier { IEnumerable<Type> InterfaceTypes { get; } /// <summary> /// Return true if any types was "created" /// </summary> /// <returns></returns> bool EnsureDataStores(); } } ================================================ FILE: Composite/Data/Foundation/PluginFacades/DataProviderPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using Composite.Core; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.Data.DynamicTypes; using Composite.Data.Plugins.DataProvider; using Composite.Data.Plugins.DataProvider.Runtime; using Composite.Data.Types; using Composite.C1Console.Events; using Composite.Core.Instrumentation; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider; namespace Composite.Data.Foundation.PluginFacades { internal static class DataProviderPluginFacade { private static readonly ResourceLocker<Resources> _resourceLocker = new ResourceLocker<Resources>(new Resources(), Resources.Initialize); internal static Func<IDataProviderFactory> DataProviderFactoryCreationDelegate = () => new ConfigurationDataProviderFactory(); static DataProviderPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } public static bool HasConfiguration() { return ConfigurationServices.ConfigurationSource?.GetSection(DataProviderSettings.SectionName) != null; } public static IEnumerable<Type> GetSupportedInterfaces(string providerName) { using (TimerProfilerFacade.CreateTimerProfiler(providerName)) { using (_resourceLocker.Locker) { IDataProvider provider = GetDataProvider(providerName); return provider.GetSupportedInterfaces(); } } } public static IEnumerable<Type> GetKnownInterfaces(string providerName) { using (TimerProfilerFacade.CreateTimerProfiler()) { using (_resourceLocker.Locker) { var provider = GetDataProvider<IDynamicDataProvider>(providerName); List<Type> knownInterfaces = provider.GetKnownInterfaces().ToList(); if (knownInterfaces.Contains(null)) { Log.LogWarning(nameof(DataProviderPluginFacade), $"Data Provider '{providerName}' returned (null) as a known interface type. Value is ignored."); knownInterfaces.RemoveAll(f => f == null); } return knownInterfaces; } } } public static IEnumerable<Type> GetGeneratedInterfaces(string providerName) { using (TimerProfilerFacade.CreateTimerProfiler()) { using (_resourceLocker.Locker) { var provider = GetDataProvider<IGeneratedTypesDataProvider>(providerName); return provider.GetGeneratedInterfaces(); } } } public static IQueryable<T> GetData<T>(string providerName) where T : class, IData { using (TimerProfilerFacade.CreateTimerProfiler()) { return Call<IDataProvider, IQueryable<T>>(providerName, provider => provider.GetData<T>()); } } public static T GetData<T>(string providerName, IDataId dataId) where T : class, IData { Verify.ArgumentNotNull(dataId, "dataId"); using (TimerProfilerFacade.CreateTimerProfiler()) { return Call<IDataProvider, T>(providerName, provider => provider.GetData<T>(dataId)); } } public static void Update(string providerName, IEnumerable<IData> dataset) { Verify.ArgumentNotNull(dataset, "dataset"); using (TimerProfilerFacade.CreateTimerProfiler()) { SyncronizedCall<IWritableDataProvider>(providerName, provider => provider.Update(dataset)); } } public static List<T> AddNew<T>(string providerName, IEnumerable<T> dataset) where T : class, IData { Verify.ArgumentNotNull(dataset, "dataset"); using (TimerProfilerFacade.CreateTimerProfiler()) { return SyncronizedCall<IWritableDataProvider, List<T>>(providerName, provider => provider.AddNew<T>(dataset)); } } public static void Delete(string providerName, IEnumerable<DataSourceId> dataSourceIds) { Verify.ArgumentNotNull(dataSourceIds, "dataSourceIds"); using (TimerProfilerFacade.CreateTimerProfiler()) { SyncronizedCall<IWritableDataProvider>(providerName, provider => provider.Delete(dataSourceIds)); } } public static bool ValidatePath<TFile>(TFile file, string providerName, out string errorMessage) where TFile : IFile { Verify.ArgumentNotNull(file, "dataSourceIds"); string message = null; bool result = false; SyncronizedCall<IFileSystemDataProvider>(providerName, provider => result = provider.ValidatePath<TFile>(file, out message)); errorMessage = message; return result; } public static void CreateStore(string providerName, DataTypeDescriptor typeDescriptor) { CreateStores(providerName, new[] { typeDescriptor }); } public static void CreateStores(string providerName, IReadOnlyCollection<DataTypeDescriptor> typeDescriptors) { Verify.ArgumentNotNull(typeDescriptors, "typeDescriptors"); using (TimerProfilerFacade.CreateTimerProfiler()) { using (_resourceLocker.Locker) { var provider = GetDataProvider<IDynamicDataProvider>(providerName); provider.CreateStores(typeDescriptors); } } } public static void AlterStore(UpdateDataTypeDescriptor updateDataTypeDescriptor, bool forceCompile) { using (TimerProfilerFacade.CreateTimerProfiler()) { using (_resourceLocker.Locker) { var provider = GetDataProvider<IDynamicDataProvider>(updateDataTypeDescriptor.ProviderName); provider.AlterStore(updateDataTypeDescriptor, forceCompile); } } } public static void DropStore(string providerName, DataTypeDescriptor typeDescriptor) { Verify.ArgumentNotNull(typeDescriptor, "typeDescriptor"); using (TimerProfilerFacade.CreateTimerProfiler()) { using (_resourceLocker.Locker) { var provider = GetDataProvider<IDynamicDataProvider>(providerName); provider.DropStore(typeDescriptor); } } } public static void AddLocale(string providerName, CultureInfo cultureInfo) { Verify.ArgumentNotNull(cultureInfo, "cultureInfo"); using (_resourceLocker.Locker) { var provider = GetDataProvider<ILocalizedDataProvider>(providerName); provider.AddLocale(cultureInfo); } } public static void RemoveLocale(string providerName, CultureInfo cultureInfo) { Verify.ArgumentNotNull(cultureInfo, "cultureInfo"); using (_resourceLocker.Locker) { var provider = GetDataProvider<ILocalizedDataProvider>(providerName); provider.RemoveLocale(cultureInfo); } } private static TResult Call<TProvider, TResult>(string providerName, Func<TProvider, TResult> func) where TProvider : class, IDataProvider where TResult : class { var provider = GetDataProvider(providerName) as TProvider ?? throw new InvalidOperationException($"The data provider '{providerName}' does not implement the interface '{typeof(TProvider).FullName}'"); return func(provider); } private static void SyncronizedCall<TProvider>(string providerName, Action<TProvider> func) where TProvider : class, IDataProvider { SyncronizedCall<TProvider, object>(providerName, provider => { func(provider); return null; }); } private static TResult SyncronizedCall<TProvider, TResult>(string providerName, Func<TProvider, TResult> func) where TProvider : class, IDataProvider where TResult : class { var provider = GetDataProvider(providerName) as TProvider ?? throw new InvalidOperationException($"The data provider '{providerName}' does not implement the interface '{typeof(TProvider).FullName}'"); // DDZ: hardcoded for now, to be fixed bool syncDisabled = provider is SqlDataProvider; IDisposable scope = null; try { if (!syncDisabled) { scope = _resourceLocker.Locker; } return func(provider); } finally { scope?.Dispose(); } } public static bool IsWriteableProvider(string providerName) { return GetDataProvider(providerName) is IWritableDataProvider; } public static bool IsDynamicProvider(string providerName) { return GetDataProvider(providerName) is IDynamicDataProvider; } public static bool IsGeneratedTypesProvider(string providerName) { return GetDataProvider(providerName) is IGeneratedTypesDataProvider; } public static bool IsLocalizedDataProvider(string providerName) { return GetDataProvider(providerName) is ILocalizedDataProvider; } /// <summary> /// Indicates whether it has sense to cache the query results. /// </summary> /// <returns></returns> public static bool AllowsResultsWrapping(string providerName) { var dataProvider = GetDataProvider(providerName); return (dataProvider as ISupportCachingDataProvider)?.AllowResultsWrapping ?? true; } private static T GetDataProvider<T>(string providerName) where T : class, IDataProvider { var provider = GetDataProvider(providerName) as T; return provider ?? throw new InvalidOperationException($"The data provider '{providerName}' does not implement the interface '{typeof(T)}'"); ; } internal static IDataProvider GetDataProvider(string providerName) { IDataProvider dataProvider = _resourceLocker.Resources.ProviderCache[providerName]; if (dataProvider != null) { return dataProvider; } using (_resourceLocker.Locker) { dataProvider = _resourceLocker.Resources.ProviderCache[providerName]; if (dataProvider != null) { return dataProvider; } try { dataProvider = _resourceLocker.Resources.Factory.Create(providerName); dataProvider.Context = new DataProviderContext(providerName); _resourceLocker.Resources.ProviderCache.Add(providerName, dataProvider); } catch (Exception ex) when (ex is ArgumentException || ex is ConfigurationErrorsException) { HandleConfigurationError(ex); } } return dataProvider; } internal static void Flush() { _resourceLocker.ResetInitialization(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException($"Failed to load the configuration section '{DataProviderSettings.SectionName}' from the configuration.", ex); } private sealed class Resources { public IDataProviderFactory Factory { get; private set; } public Hashtable<string, IDataProvider> ProviderCache { get; private set; } public static void Initialize(Resources resources) { try { resources.Factory = DataProviderFactoryCreationDelegate(); } catch (Exception ex) when (ex is NullReferenceException || ex is ConfigurationErrorsException) { HandleConfigurationError(ex); } resources.ProviderCache = new Hashtable<string, IDataProvider>(); } } } } ================================================ FILE: Composite/Data/Foundation/ProcessControllerRegistry.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using Composite.C1Console.Events; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.Core.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Data.Foundation { internal static class ProcessControllerRegistry { private static readonly ResourceLocker<Resources> _resourceLocker = new ResourceLocker<Resources>(new Resources(), Resources.Initialize); static ProcessControllerRegistry() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static IEnumerable<Type> ProcessControllerTypes { get { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.ProcessControllerTypes.ToList(); } } } public static IEnumerable<Type> DataTypesWithProcessControllers { get { using (_resourceLocker.Locker) { return _resourceLocker.Resources.TypeToProcessControllerTypes.GetKeys().ToList(); } } } public static Dictionary<Type, Type> GetProcessControllerTypes(Type interfaceType) { Verify.ArgumentNotNull(interfaceType, "interfaceType"); var resourceLocker = _resourceLocker; var resources = _resourceLocker.Resources; Dictionary<Type, Type> processControllerTypes; if (!resources.TypeToProcessControllerTypes.TryGetValue(interfaceType, out processControllerTypes)) { using (resourceLocker.Locker) { if (!resources.TypeToProcessControllerTypes.TryGetValue(interfaceType, out processControllerTypes)) { processControllerTypes = resources.ProcessInterfaceType(_resourceLocker.Resources, interfaceType); } } } return processControllerTypes; } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private sealed class Resources { public List<Type> ProcessControllerTypes { get; set; } public List<Type> ProcessedInterfaceTypes { get; set; } // interfaceType -> IProcessController subinterface -> process controller type public Hashtable<Type, Dictionary<Type, Type>> TypeToProcessControllerTypes { get; set; } private ProcessControllerSettings _settings; public static void Initialize(Resources resources) { var configurationSource = GetConfiguration(); ProcessControllerSettings settings = configurationSource.GetSection(ProcessControllerSettings.SectionName) as ProcessControllerSettings; if (settings == null) { throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration", ProcessControllerSettings.SectionName)); } resources._settings = settings; resources.ProcessControllerTypes = new List<Type>(); resources.ProcessedInterfaceTypes = new List<Type>(); resources.TypeToProcessControllerTypes = new Hashtable<Type, Dictionary<Type, Type>>(); foreach (Type interfaceType in DataFacade.GetAllInterfaces()) { resources.ProcessInterfaceType(resources, interfaceType); } } internal Dictionary<Type, Type> ProcessInterfaceType(Resources resources, Type interfaceType) { Dictionary<Type, Type> processControllerTypes = new Dictionary<Type, Type>(); foreach (var controllerData in _settings.ProcessControllers) { AddProcessController(resources, interfaceType, controllerData.InterfaceType, controllerData.AttributeType, processControllerTypes); } resources.TypeToProcessControllerTypes.Add(interfaceType, processControllerTypes); return processControllerTypes; } private static IConfigurationSource GetConfiguration() { IConfigurationSource source = ConfigurationServices.ConfigurationSource; if (null == source) { throw new ConfigurationErrorsException(string.Format("No configuration source specified")); } return source; } private static void AddProcessController(Resources resources, Type interfaceType, Type superProcessControllerInterfaceType, Type attributeType, Dictionary<Type, Type> processControllerTypes) { var publishAttributes = interfaceType.GetCustomAttributesRecursively(attributeType).Cast<ProcessControllerTypeAttribute>().ToList(); if (publishAttributes.Count == 0) return; Type processControllerType = publishAttributes[0].ProcessControllerType; foreach (ProcessControllerTypeAttribute attribute in publishAttributes.Skip(1)) { Verify.That(attribute.ProcessControllerType != processControllerType, "Only one '{0}' is allowed on the data type '{1}' or all attributes should have same process controller type", processControllerType, interfaceType); } processControllerTypes.Add(superProcessControllerInterfaceType, processControllerType); if (!resources.ProcessControllerTypes.Contains(processControllerType)) { resources.ProcessControllerTypes.Add(processControllerType); } } } } } ================================================ FILE: Composite/Data/Foundation/ProcessControllerSettings.cs ================================================ using System; using System.ComponentModel; using System.Configuration; using Composite.Core.Configuration; using Composite.Data.ProcessControlled; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Data.Foundation { internal class ProcessControllerSettings : SerializableConfigurationSection { public const string SectionName = "Composite.Data.Foundation.ProcessControllerConfiguration"; private const string ProcessControllersPropertyName = "ProcessControllers"; [ConfigurationProperty(ProcessControllersPropertyName)] public NamedElementCollection<ProcessControllerData> ProcessControllers { get { return (NamedElementCollection<ProcessControllerData>)base[ProcessControllersPropertyName]; } } } internal class ProcessControllerData : NamedConfigurationElement { private const string InterfaceTypePropertyName = "interfaceType"; private const string AttributeTypePropertyName = "attributeType"; /// <summary> /// The interface type for the <see cref="IProcessController"/> that will /// do the processing /// </summary> [ConfigurationProperty(InterfaceTypePropertyName, IsRequired = true)] [TypeConverter(typeof(TypeManagerTypeNameConverter))] public Type InterfaceType { get { return (Type)this[InterfaceTypePropertyName]; } set { this[InterfaceTypePropertyName] = value; } } /// <summary> /// The <see cref="ProcessControllerTypeAttribute"/> attached to the IData /// object /// </summary> [ConfigurationProperty(AttributeTypePropertyName, IsRequired = true)] [TypeConverter(typeof(TypeManagerTypeNameConverter))] public Type AttributeType { get { return (Type)this[AttributeTypePropertyName]; } set { this[AttributeTypePropertyName] = value; } } } } ================================================ FILE: Composite/Data/Foundation/SelectMethodInfoCache.cs ================================================ using System; using System.Linq; using System.Reflection; using System.Collections.Generic; namespace Composite.Data.Foundation { internal sealed class SelectMethodInfoCache { private static Dictionary<CacheEntry, MethodInfo> _methodInfoCache = new Dictionary<CacheEntry, MethodInfo>(); public static MethodInfo GetSelectMethod(Type sourceType, Type targetType) { CacheEntry entry = new CacheEntry(sourceType, targetType); if ( false == _methodInfoCache.ContainsKey(entry)) { MethodInfo genericSelectMethod = (from method in typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public) where method.Name == "Select" && method.IsGenericMethod && method.GetGenericArguments().Length == 2 select method).First(); MethodInfo selectMethod = genericSelectMethod.MakeGenericMethod(new Type[] { sourceType, targetType }); _methodInfoCache.Add(entry, selectMethod); } return _methodInfoCache[entry]; } private sealed class CacheEntry { private Type _sourceType; private Type _targetType; public CacheEntry(Type sourceType, Type targetType) { _sourceType = sourceType; _targetType = targetType; } public override bool Equals(object obj) { CacheEntry entry = obj as CacheEntry; if (null == entry) return false; return entry._sourceType == _sourceType && entry._targetType == _targetType; } public override int GetHashCode() { return _sourceType.GetHashCode() ^ _targetType.GetHashCode(); } } } } ================================================ FILE: Composite/Data/GeneratedTypes/GeneratedTypesFacade.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using Composite.Data.DynamicTypes; using Composite.Data.Foundation; namespace Composite.Data.GeneratedTypes { /// <summary> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] public class GenerateNewTypeEventArgs : EventArgs { } /// <summary> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] public class UpdateTypeEventArgs : EventArgs { } /// <summary> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] public class DeleteTypeEventArgs : EventArgs { } /// <summary> /// This class is used to create/update/delete generated types. That is, types /// that is not defined in code, but designed through the UI and is dynamicly /// compiled. /// When a data type is created/updated/deleted the interface is (re)code-generated/deleted /// and the store is created/updated/deleted through <see cref="Composite.Data.DynamicTypes.DynamicTypeManager"/> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] public static class GeneratedTypesFacade { /// <exclude /> public delegate void GenerateNewTypeDelegate(GenerateNewTypeEventArgs args); /// <exclude /> public delegate void UpdateTypeDelegate(UpdateTypeEventArgs args); /// <exclude /> public delegate void DeleteTypeDelegate(DeleteTypeEventArgs args); private static event GenerateNewTypeDelegate _generateNewTypeDelegate; private static event UpdateTypeDelegate _updateTypeDelegate; private static event DeleteTypeDelegate _deleteTypeDelegate; private static IGeneratedTypesFacade _generatedTypesFacade = new GeneratedTypesFacadeImpl(); internal static IGeneratedTypesFacade Implementation { get { return _generatedTypesFacade; } set { _generatedTypesFacade = value; } } // Overload /// <exclude /> public static void GenerateNewType(DataTypeDescriptor dataTypeDescriptor) { GenerateNewType(DataProviderRegistry.DefaultDynamicTypeDataProviderName, dataTypeDescriptor, true); } // Overload /// <exclude /> public static void GenerateNewType(DataTypeDescriptor dataTypeDescriptor, bool makeAFlush) { GenerateNewType(DataProviderRegistry.DefaultDynamicTypeDataProviderName, dataTypeDescriptor, makeAFlush); } // Overload /// <exclude /> public static void GenerateNewTypes(IReadOnlyCollection<DataTypeDescriptor> dataTypeDescriptor, bool makeAFlush) { GenerateNewTypes(DataProviderRegistry.DefaultDynamicTypeDataProviderName, dataTypeDescriptor, makeAFlush); } /// <exclude /> public static void GenerateNewType(string providerName, DataTypeDescriptor dataTypeDescriptor, bool makeAFlush) { GenerateNewTypes(providerName, new[] {dataTypeDescriptor}, makeAFlush); } /// <exclude /> public static void GenerateNewTypes(string providerName, IReadOnlyCollection<DataTypeDescriptor> dataTypeDescriptors, bool makeAFlush) { using (GlobalInitializerFacade.CoreLockScope) { _generatedTypesFacade.GenerateNewTypes(providerName, dataTypeDescriptors, makeAFlush); if (_generateNewTypeDelegate != null) { GenerateNewTypeDelegate generateNewTypeDelegate = _generateNewTypeDelegate; generateNewTypeDelegate(new GenerateNewTypeEventArgs()); } } } /// <exclude /> public static bool CanDeleteType(DataTypeDescriptor dataTypeDescriptor, out string errorMessage) { return _generatedTypesFacade.CanDeleteType(dataTypeDescriptor, out errorMessage); } /// <exclude /> public static void DeleteType(DataTypeDescriptor dataTypeDescriptor) { DeleteType(DataProviderRegistry.DefaultDynamicTypeDataProviderName, dataTypeDescriptor, true); } internal static void DeleteType(DataTypeDescriptor dataTypeDescriptor, bool makeAFlush) { DeleteType(DataProviderRegistry.DefaultDynamicTypeDataProviderName, dataTypeDescriptor, makeAFlush); } /// <exclude /> public static void DeleteType(string providerName, DataTypeDescriptor dataTypeDescriptor) { DeleteType(providerName, dataTypeDescriptor, true); } internal static void DeleteType(string providerName, DataTypeDescriptor dataTypeDescriptor, bool makeAFlush) { using (GlobalInitializerFacade.CoreLockScope) { PageFolderFacade.RemoveAllFolderDefinitions(dataTypeDescriptor.DataTypeId, false); PageMetaDataFacade.RemoveAllDefinitions(dataTypeDescriptor.DataTypeId, false); _generatedTypesFacade.DeleteType(providerName, dataTypeDescriptor, makeAFlush); if (_deleteTypeDelegate != null) { DeleteTypeDelegate deleteDelegate = _deleteTypeDelegate; deleteDelegate(new DeleteTypeEventArgs()); } } } ///// <exclude /> //public static void UpdateType(DataTypeDescriptor oldDataTypeDescriptor, DataTypeDescriptor newDataTypeDescriptor, bool originalTypeHasData) //{ // UpdateType(DataProviderRegistry.DefaultDynamicTypeDataProviderName, oldDataTypeDescriptor, newDataTypeDescriptor, originalTypeHasData); //} ///// <exclude /> //public static void UpdateType(DataTypeDescriptor oldDataTypeDescriptor, DataTypeDescriptor newDataTypeDescriptor) //{ // UpdateType(DataProviderRegistry.DefaultDynamicTypeDataProviderName, oldDataTypeDescriptor, newDataTypeDescriptor, true); //} /// <exclude /> public static void UpdateType(UpdateDataTypeDescriptor updateDataTypeDescriptor) { using (GlobalInitializerFacade.CoreLockScope) { _generatedTypesFacade.UpdateType(updateDataTypeDescriptor); if (_updateTypeDelegate != null) { UpdateTypeDelegate updateDelegate = _updateTypeDelegate; updateDelegate(new UpdateTypeEventArgs()); } } } /// <exclude /> public static void SubscribeToGenerateNewTypeEvent(GenerateNewTypeDelegate eventDelegate) { _generateNewTypeDelegate += eventDelegate; } /// <exclude /> public static void SubscribeToUpdateTypeEvent(UpdateTypeDelegate eventDelegate) { _updateTypeDelegate += eventDelegate; } /// <exclude /> public static void SubscribeToDeleteTypeEvent(DeleteTypeDelegate eventDelegate) { _deleteTypeDelegate += eventDelegate; } /// <exclude /> public static void UnsubscribeToGenerateNewTypeEvent(GenerateNewTypeDelegate eventDelegate) { _generateNewTypeDelegate -= eventDelegate; } /// <exclude /> public static void UnsubscribeToUpdateTypeEvent(UpdateTypeDelegate eventDelegate) { _updateTypeDelegate -= eventDelegate; } /// <exclude /> public static void UnsubscribeToDeleteTypeEvent(DeleteTypeDelegate eventDelegate) { _deleteTypeDelegate -= eventDelegate; } } } ================================================ FILE: Composite/Data/GeneratedTypes/GeneratedTypesFacadeImpl.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Transactions; using Composite.Core; using Composite.Data.DynamicTypes; using Composite.Data.Transactions; using Composite.Core.Types; namespace Composite.Data.GeneratedTypes { internal sealed class GeneratedTypesFacadeImpl : IGeneratedTypesFacade { public void GenerateNewTypes(string providerName, IReadOnlyCollection<DataTypeDescriptor> dataTypeDescriptors, bool makeAFlush) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); Verify.ArgumentNotNull(dataTypeDescriptors, "dataTypeDescriptors"); foreach (var dataTypeDescriptor in dataTypeDescriptors) { UpdateWithNewMetaDataForeignKeySystem(dataTypeDescriptor); UpdateWithNewPageFolderForeignKeySystem(dataTypeDescriptor, false); } var types = DataTypeTypesManager.GetDataTypes(dataTypeDescriptors); foreach (var dataTypeDescriptor in dataTypeDescriptors) { dataTypeDescriptor.TypeManagerTypeName = TypeManager.SerializeType(types[dataTypeDescriptor.DataTypeId]); } DynamicTypeManager.CreateStores(providerName, dataTypeDescriptors, makeAFlush); if (makeAFlush && dataTypeDescriptors.Any(d => d.IsCodeGenerated)) { CodeGenerationManager.GenerateCompositeGeneratedAssembly(true); } } public void DeleteType(string providerName, DataTypeDescriptor dataTypeDescriptor, bool makeAFlush) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); Verify.ArgumentNotNull(dataTypeDescriptor, "dataTypeDescriptor"); using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { DynamicTypeManager.DropStore(providerName, dataTypeDescriptor, makeAFlush); transactionScope.Complete(); } if (makeAFlush && dataTypeDescriptor.IsCodeGenerated) { CodeGenerationManager.GenerateCompositeGeneratedAssembly(true); } } public bool CanDeleteType(DataTypeDescriptor dataTypeDescriptor, out string errorMessage) { CompatibilityCheckResult compatibilityCheckResult = CodeCompatibilityChecker.CheckIfAppCodeDependsOnInterface(dataTypeDescriptor); if (!compatibilityCheckResult.Successful) { errorMessage = "Cannot delete the type since it will cause a build error for App_Code files. " + compatibilityCheckResult.ErrorMessage; return false; } errorMessage = string.Empty; return true; } public void UpdateType(UpdateDataTypeDescriptor updateDataTypeDescriptor) { Verify.ArgumentNotNullOrEmpty(updateDataTypeDescriptor.ProviderName, "providerName"); Verify.ArgumentNotNull(updateDataTypeDescriptor.OldDataTypeDescriptor, "oldDataTypeDescriptor"); Verify.ArgumentNotNull(updateDataTypeDescriptor.NewDataTypeDescriptor, "newDataTypeDescriptor"); Type interfaceType = null; if (updateDataTypeDescriptor.OldDataTypeDescriptor.IsCodeGenerated) { interfaceType = InterfaceCodeManager.GetType(updateDataTypeDescriptor.NewDataTypeDescriptor, true); } else { interfaceType = DataTypeTypesManager.GetDataType(updateDataTypeDescriptor.NewDataTypeDescriptor); } updateDataTypeDescriptor.NewDataTypeDescriptor.TypeManagerTypeName = TypeManager.SerializeType(interfaceType); DynamicTypeManager.AlterStore(updateDataTypeDescriptor, false); CodeGenerationManager.GenerateCompositeGeneratedAssembly(true); } /// <summary> /// This method will remove a foreign key (if any exists) that is no longer possible with the /// new meta data system (IPageMetaDataDefinition) /// </summary> /// <param name="dataTypeDescriptor"></param> /// <param name="dataStoreExists"></param> private void UpdateWithNewPageFolderForeignKeySystem(DataTypeDescriptor dataTypeDescriptor, bool dataStoreExists) { if (dataTypeDescriptor.IsPageFolderDataType == false) { return; } DataFieldDescriptor dataFieldDescriptor = dataTypeDescriptor.Fields["IAggregationDescriptionIdForeignKey"]; if (dataFieldDescriptor == null) { return; } Log.LogVerbose("GeneratedTypesFacade", string.Format("Removing the property {0} on the type {1}.{2}", dataFieldDescriptor.Name, dataTypeDescriptor.Namespace, dataTypeDescriptor.Name)); if(!dataStoreExists) { dataTypeDescriptor.Fields.Remove(dataFieldDescriptor); DynamicTypeManager.UpdateDataTypeDescriptor(dataTypeDescriptor, false); return; } DataTypeDescriptor oldDataTypeDescriptor = dataTypeDescriptor.Clone(); dataTypeDescriptor.Fields.Remove(dataFieldDescriptor); var dataTypeChangeDescriptor = new DataTypeChangeDescriptor(oldDataTypeDescriptor, dataTypeDescriptor); var updateDataTypeDescriptor = new UpdateDataTypeDescriptor(oldDataTypeDescriptor, dataTypeDescriptor); DynamicTypeManager.AlterStore(updateDataTypeDescriptor, false); } /// <summary> /// This method will remove a foreign key (if any exists) that is no longer possible with the /// new meta data system (IPageMetaDataDefinition) /// </summary> /// <param name="dataTypeDescriptor"></param> private void UpdateWithNewMetaDataForeignKeySystem(DataTypeDescriptor dataTypeDescriptor) { if (dataTypeDescriptor.IsPageMetaDataType) { var dataFieldDescriptor = dataTypeDescriptor.Fields[nameof(IPageMetaData.FieldName)]; if (dataFieldDescriptor?.ForeignKeyReferenceTypeName != null) // This should never fail, but want to be sure { dataFieldDescriptor.ForeignKeyReferenceTypeName = null; DynamicTypeManager.UpdateDataTypeDescriptor(dataTypeDescriptor, false); Log.LogVerbose("GeneratedTypesFacade", string.Format("Removing foreign on the property {0} on the type {1}.{2}", dataFieldDescriptor.Name, dataTypeDescriptor.Namespace, dataTypeDescriptor.Name)); } } } } } ================================================ FILE: Composite/Data/GeneratedTypes/GeneratedTypesHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Xml.Linq; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.Types; using Composite.Data.DynamicTypes; using Composite.Data.ProcessControlled; using Composite.Data.Types; using Composite.Functions; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_GeneratedTypes; namespace Composite.Data.GeneratedTypes { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class GeneratedTypesHelper { /// <exclude /> public enum KeyFieldType { /// <exclude /> Undefined = 0, /// <exclude /> Guid = 1, /// <exclude /> RandomString4 = 2, /// <exclude /> RandomString8 = 3 } private static readonly string[] ReservedNamespaces = { "System", "Composite.Data.GeneratedTypes", "GeneratedTypes" }; private const string CompositeNamespace = "Composite"; private Type _associatedType; private readonly Type _oldType; private readonly DataTypeDescriptor _oldDataTypeDescriptor; private DataTypeDescriptor _newDataTypeDescriptor; private string _newTypeName; private string _newTypeNamespace; private string _newTypeTitle; private bool _cacheable; private bool _searchable; private bool _publishControlled; private bool _localizedControlled; private IEnumerable<DataFieldDescriptor> _newDataFieldDescriptors; private string _newKeyFieldName; private string _newLabelFieldName; private string _newInternalUrlPrefix; private DataAssociationType _dataAssociationType = DataAssociationType.None; private DataFieldDescriptor _foreignKeyDataFieldDescriptor; private DataFieldDescriptor _pageMetaDataDescriptionForeignKeyDataFieldDescriptor; private DataTypeAssociationDescriptor _dataTypeAssociationDescriptor; private bool _typeCreated; private const string IdFieldName = "Id"; private const string PageReferenceFieldName = "PageId"; private const string CompositionDescriptionFieldName = "FieldName"; //private KeyFieldType _keyFieldType = KeyFieldType.Guid; /// <exclude /> public GeneratedTypesHelper() { } /// <exclude /> public GeneratedTypesHelper(Type oldType) { Verify.ArgumentNotNull(oldType, "oldType"); _oldType = oldType; _oldDataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(oldType); Initialize(); } /// <exclude /> public GeneratedTypesHelper(DataTypeDescriptor oldDataTypeDescriptor) { Verify.ArgumentNotNull(oldDataTypeDescriptor, "oldDataTypeDescriptor"); _oldType = oldDataTypeDescriptor.GetInterfaceType(); _oldDataTypeDescriptor = oldDataTypeDescriptor; Initialize(); } /// <exclude /> public bool AllowForeignKeyEditing { get; set; } /// <exclude /> [Obsolete("Use EditableOwnDataFieldDescriptors which does not return inherited fields", true)] public IEnumerable<DataFieldDescriptor> EditableDataFieldDescriptors { get { Verify.IsNotNull(_oldDataTypeDescriptor, "No old data type specified"); var fields = _oldDataTypeDescriptor.Fields; return fields.Where(field => IsDataFieldBindable(_oldDataTypeDescriptor, field)); } } /// <exclude /> public IEnumerable<DataFieldDescriptor> EditableInDesignerOwnDataFields { get { Verify.IsNotNull(_oldDataTypeDescriptor, "No old data type specified"); var fields = _oldDataTypeDescriptor.Fields; return fields.Where(field => IsDataFieldBindable(_oldDataTypeDescriptor, field) && !field.Inherited); } } /// <exclude /> public IEnumerable<string> NotEditableDataFieldDescriptorNames { get { Verify.IsNotNull(_oldDataTypeDescriptor, "No old data type specified"); return from field in _oldDataTypeDescriptor.Fields where !IsDataFieldBindable(_oldDataTypeDescriptor, field) || _oldDataTypeDescriptor.KeyPropertyNames.FirstOrDefault() == field.Name select field.Name; } } /// <exclude /> [Obsolete("Use IsCacheable")] public bool IsCachable => IsCacheable; /// <exclude /> public bool IsCacheable { get { Verify.IsNotNull(_oldDataTypeDescriptor, "No old data type specified"); return _oldDataTypeDescriptor.Cachable; } } /// <exclude /> public bool IsSearchable { get { Verify.IsNotNull(_oldDataTypeDescriptor, "No old data type specified"); return _oldDataTypeDescriptor.Searchable; } } /// <exclude /> public bool IsPublishControlled { get { Verify.IsNotNull(_oldDataTypeDescriptor, "No old data type specified"); return _oldDataTypeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled)); } } /// <exclude /> public bool IsLocalizedControlled { get { Verify.IsNotNull(_oldDataTypeDescriptor, "No old data type specified"); return _oldDataTypeDescriptor.SuperInterfaces.Contains(typeof(ILocalizedControlled)); } } /// <summary> /// Returns <value>true</value> if the date type is a page meta data type. /// </summary> public bool IsEditProcessControlledAllowed => _pageMetaDataDescriptionForeignKeyDataFieldDescriptor == null; /// <exclude /> public bool ValidateNewTypeName(string typeName, out string message) { Verify.ArgumentNotNullOrEmpty(typeName, "typeName"); return NameValidation.TryValidateName(typeName, out message); } /// <exclude /> public bool ValidateNewTypeNamespace(string typeNamespace, out string message) { Verify.ArgumentNotNullOrEmpty(typeNamespace, "typeNamespace"); return NameValidation.TryValidateNamespace(typeNamespace, out message); } /// <exclude /> public bool ValidateNewTypeFullName(string typeName, string typeNamespace, out string message) { Verify.ArgumentNotNullOrEmpty(typeName, "typeName"); Verify.ArgumentNotNullOrEmpty(typeNamespace, "typeNamespace"); message = null; if (typeNamespace.Split('.').Contains(typeName)) { message = Texts.TypeNameInNamespace(typeName, typeNamespace); return false; } if (_oldDataTypeDescriptor != null) { if (_oldDataTypeDescriptor.Name == typeName && _oldDataTypeDescriptor.Namespace == typeNamespace) { return true; } var interfaceType = _oldDataTypeDescriptor.GetInterfaceType(); if (interfaceType.GetRefereeTypes().Count > 0) { message = Texts.TypesAreReferencing; return false; } } var typeFullname = StringExtensionMethods.CreateNamespace(typeNamespace, typeName, '.'); foreach (var dtd in DataMetaDataFacade.GeneratedTypeDataTypeDescriptors) { var fullname = StringExtensionMethods.CreateNamespace(dtd.Namespace, dtd.Name, '.'); if (typeFullname == fullname) { message = Texts.TypesNameClash; return false; } } var partNames = typeFullname.Split('.'); var sb = new StringBuilder(partNames[0]); for (var i = 1; i < partNames.Length; i++) { var exists = TypeManager.HasTypeWithName(sb.ToString()); if (exists) { message = Texts.NameSpaceIsTypeTypeName(sb.ToString()); return false; } sb.Append("."); sb.Append(partNames[i]); } return true; } /// <exclude /> public bool ValidateByCompile(out string errorMessage) { var dataTypeDescriptor = _oldDataTypeDescriptor == null ? CreateNewDataTypeDescriptor() : CreateUpdatedDataTypeDescriptor(); var classFullName = (dataTypeDescriptor.Namespace + "." + dataTypeDescriptor.Name).Replace(" ", string.Empty); var classFullNameWithDot = classFullName + "."; foreach (var reservedNamespace in ReservedNamespaces) { if (classFullNameWithDot.StartsWith(reservedNamespace + ".", StringComparison.InvariantCultureIgnoreCase)) { errorMessage = Texts.NamespaceIsReserved; return false; } } foreach (var namePart in classFullName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries)) { if (!IsCSharpValidIdentifier(namePart)) { errorMessage = Texts.TypeNameIsInvalidIdentifier(classFullName); return false; } } foreach (var dataField in dataTypeDescriptor.Fields) { if (!IsCSharpValidIdentifier(dataField.Name)) { errorMessage = Texts.FieldNameCannotBeUsed(dataField.Name); return false; } } // Checking for name collisions with Composite.dll if (classFullName.StartsWith(CompositeNamespace + ".", StringComparison.InvariantCultureIgnoreCase)) { foreach (var type in typeof(IData).Assembly.GetTypes()) { var typeNameWithDot = type.FullName + "."; if (classFullNameWithDot.StartsWith(typeNameWithDot, StringComparison.InvariantCultureIgnoreCase) || typeNameWithDot.StartsWith(classFullNameWithDot, StringComparison.InvariantCultureIgnoreCase)) { errorMessage = Texts.CompileErrorWhileAddingType; return false; } } } var compatibilityCheckResult = CodeCompatibilityChecker.CheckCompatibilityWithAppCodeFolder(dataTypeDescriptor); if (!compatibilityCheckResult.Successful) { errorMessage = _oldDataTypeDescriptor == null ? Texts.CompileErrorWhileAddingType : Texts.CompileErrorWhileChangingType; errorMessage += compatibilityCheckResult.ErrorMessage; return false; } errorMessage = string.Empty; return true; } /// <exclude /> public bool ValidateNewFieldDescriptors(IEnumerable<DataFieldDescriptor> newDataFieldDescriptors, string keyFieldName, out string message) { Verify.ArgumentNotNull(newDataFieldDescriptors, "newDataFieldDescriptors"); newDataFieldDescriptors = newDataFieldDescriptors.Evaluate(); message = null; if (newDataFieldDescriptors.All(f => f.Name == keyFieldName)) { message = Texts.MissingFields; return false; } if (keyFieldName != IdFieldName && newDataFieldDescriptors.Any(dfd => dfd.Name == IdFieldName)) { message = Texts.FieldNameCannotBeUsed(IdFieldName); return false; } return true; } /// <exclude /> public static string GetCompositionDescriptionPropertyName(Type compositionType) { return CompositionDescriptionFieldName; } /// <exclude /> public static PropertyInfo GetCompositionDescriptionPropertyInfo(Type compositionType) { return compositionType.GetPropertiesRecursively().Single(f => f.Name == CompositionDescriptionFieldName); } /// <exclude /> public static PropertyInfo GetPageReferencePropertyInfo(Type compositionType) { return compositionType.GetPropertiesRecursively().Single(f => f.Name == PageReferenceFieldName); } /// <exclude /> public void SetNewTypeFullName(string typeName, string typeNamespace) { Verify.ArgumentNotNullOrEmpty(typeName, "typeName"); Verify.ArgumentNotNullOrEmpty(typeNamespace, "typeNamespace"); _newTypeName = typeName; _newTypeNamespace = typeNamespace; } /// <exclude /> public void SetNewTypeTitle(string typeTitle) { Verify.ArgumentNotNullOrEmpty(typeTitle, "typeTitle"); _newTypeTitle = typeTitle; } /// <exclude /> public void SetNewInternalUrlPrefix(string internalUrlPrefix) { _newInternalUrlPrefix = internalUrlPrefix; } /// <exclude /> [Obsolete("SetCacheable")] public void SetCachable(bool cacheable) { SetCacheable(cacheable); } /// <exclude /> public void SetCacheable(bool cacheable) { _cacheable = cacheable; } /// <exclude /> public void SetSearchable(bool searchable) { _searchable = searchable; } /// <exclude /> public void SetPublishControlled(bool isPublishControlled) { Verify.That(IsEditProcessControlledAllowed, "Not allowed to change this value"); _publishControlled = isPublishControlled; } /// <exclude /> public void SetLocalizedControlled(bool isLocalizedControlled) { Verify.That(IsEditProcessControlledAllowed, "Not allowed to change this value"); _localizedControlled = isLocalizedControlled; } /// <exclude /> [Obsolete("Left for backward compatibility")] public void SetNewFieldDescriptors(IEnumerable<DataFieldDescriptor> newDataFieldDescriptors, string labelFieldName) { var idField = BuildIdField(); var fields = new[] { idField }; SetNewFieldDescriptors(fields.Concat(newDataFieldDescriptors), IdFieldName, labelFieldName); } /// <exclude /> public void SetNewFieldDescriptors(IEnumerable<DataFieldDescriptor> newDataFieldDescriptors, string keyFieldName, string labelFieldName) { Verify.ArgumentNotNull(newDataFieldDescriptors, "newDataFieldDescriptors"); _newDataFieldDescriptors = newDataFieldDescriptors; _newKeyFieldName = keyFieldName; _newLabelFieldName = labelFieldName; if (_newLabelFieldName == "") { _newLabelFieldName = null; } } /// <exclude /> public void SetForeignKeyReference(Type targetDataType, DataAssociationType dataAssociationType) { if (dataAssociationType == DataAssociationType.None) { throw new ArgumentException("dataAssociationType"); } var targetDataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(targetDataType); SetForeignKeyReference(targetDataTypeDescriptor, dataAssociationType); } /// <exclude /> public void SetForeignKeyReference(DataTypeDescriptor targetDataTypeDescriptor, DataAssociationType dataAssociationType) { if (dataAssociationType == DataAssociationType.None) { throw new ArgumentException("dataAssociationType"); } if ((dataAssociationType == DataAssociationType.Aggregation || dataAssociationType == DataAssociationType.Composition) && _pageMetaDataDescriptionForeignKeyDataFieldDescriptor != null) { throw new InvalidOperationException("The type already has a foreign key reference"); } string fieldName = null; var targetType = TypeManager.GetType(targetDataTypeDescriptor.TypeManagerTypeName); if (targetType == typeof(IPage)) { fieldName = PageReferenceFieldName; _dataAssociationType = dataAssociationType; } _foreignKeyDataFieldDescriptor = CreateReferenceDataFieldDescriptor(targetDataTypeDescriptor, out var foreignKeyFieldName, fieldName); if (dataAssociationType != DataAssociationType.None) { _dataTypeAssociationDescriptor = new DataTypeAssociationDescriptor(targetType, foreignKeyFieldName, dataAssociationType); } if (dataAssociationType == DataAssociationType.Composition) { var compositionRuleDataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(typeof(IPageMetaDataDefinition)); _pageMetaDataDescriptionForeignKeyDataFieldDescriptor = CreateWeakReferenceDataFieldDescriptor(compositionRuleDataTypeDescriptor, compositionRuleDataTypeDescriptor.Fields["Name"], CompositionDescriptionFieldName); } } /// <exclude /> public bool TryValidateUpdate(bool originalTypeDataExists, out string errorMessage) { if (_oldDataTypeDescriptor != null) { if (_newLabelFieldName == null) { _newLabelFieldName = KeyFieldName; } if (_newTypeTitle == null) { _newTypeTitle = _newTypeName; } if (!UpdateOldType(true, originalTypeDataExists, out errorMessage)) { return false; } } return ValidateByCompile(out errorMessage); } /// <exclude /> public void CreateType(bool originalTypeHasData) { if (_typeCreated) { throw new InvalidOperationException("The type can only be created once"); } try { if (_newLabelFieldName == null) { _newLabelFieldName = KeyFieldName; } if (_newTypeTitle == null) { _newTypeTitle = _newTypeName; } if (_oldDataTypeDescriptor == null) { Verify.IsNotNull(_newTypeName, "Type name not set"); Verify.IsNotNull(_newTypeNamespace, "Type namespace not set"); Verify.IsNotNull(_newDataFieldDescriptors, "Type field descriptors not set"); CreateNewType(); } else { UpdateOldType(false, originalTypeHasData, out _); } } finally { _typeCreated = true; } } /// <exclude /> public Type InterfaceType { get { Verify.That(_typeCreated, "The type has to be created first"); return _newDataTypeDescriptor.GetInterfaceType(); } } /// <exclude /> public static void SetNewIdFieldValue(IData data) { Verify.ArgumentNotNull(data, "data"); var keyProperties = data.GetType().GetKeyProperties(); foreach (var keyProperty in keyProperties) { var hasDefaultFieldValueAttribute = keyProperty.GetCustomAttributesRecursively<DefaultFieldValueAttribute>().Any(); var hasNewInstanceDefaultFieldValueAttribute = keyProperty.GetCustomAttributesRecursively<NewInstanceDefaultFieldValueAttribute>().Any(); if (!hasDefaultFieldValueAttribute && !hasNewInstanceDefaultFieldValueAttribute) { if (keyProperty.PropertyType == typeof(Guid)) { // Assigning a guid key a value because its not part of the generated UI keyProperty.SetValue(data, Guid.NewGuid(), null); } else { // For now, do nothing. This would fix auto increment issue for int key properties // throw new InvalidOperationException(string.Format("The property '{0}' on the data interface '{1}' does not a DefaultFieldValueAttribute or NewInstanceDefaultFieldValueAttribute and no default value could be created", propertyInfo.Name, data.GetType()); } } } } private void Initialize() { if (_oldDataTypeDescriptor.DataAssociations.Count > 0) { var dataTypeAssociationDescriptor = _oldDataTypeDescriptor.DataAssociations.Single(); _associatedType = dataTypeAssociationDescriptor.AssociatedInterfaceType; } foreach (var dataFieldDescriptor in _oldDataTypeDescriptor.Fields) { if (dataFieldDescriptor.ForeignKeyReferenceTypeName != null) { if (_associatedType != null) { var associatedTypeTypeName = TypeManager.SerializeType(_associatedType); if (dataFieldDescriptor.ForeignKeyReferenceTypeName == associatedTypeTypeName) { _foreignKeyDataFieldDescriptor = dataFieldDescriptor; } } } if (dataFieldDescriptor.Name == CompositionDescriptionFieldName) { _pageMetaDataDescriptionForeignKeyDataFieldDescriptor = dataFieldDescriptor; } } _publishControlled = IsPublishControlled; _localizedControlled = IsLocalizedControlled; } private void CreateNewType() { _newDataTypeDescriptor = CreateNewDataTypeDescriptor(); GeneratedTypesFacade.GenerateNewType(_newDataTypeDescriptor); } private static bool IsCSharpValidIdentifier(string name) { return CSharpCodeProviderFactory.CreateCompiler().IsValidIdentifier(name); } private bool UpdateOldType(bool validateOnly, bool originalTypeDataExists, out string errorMessage) { errorMessage = ""; _newDataTypeDescriptor = CreateUpdatedDataTypeDescriptor(); try { new DataTypeChangeDescriptor(_oldDataTypeDescriptor, _newDataTypeDescriptor, originalTypeDataExists); } catch (Exception ex) { errorMessage = ex.Message; return false; } if (validateOnly) { return true; } GeneratedTypesFacade.UpdateType(new UpdateDataTypeDescriptor(_oldDataTypeDescriptor, _newDataTypeDescriptor, originalTypeDataExists)); return true; } private DataTypeDescriptor CreateNewDataTypeDescriptor() { return CreateNewDataTypeDescriptor( _newTypeNamespace, _newTypeName, _newTypeTitle, _newLabelFieldName, _newInternalUrlPrefix, _cacheable, _searchable, _publishControlled, _localizedControlled, _newDataFieldDescriptors, _foreignKeyDataFieldDescriptor, _dataTypeAssociationDescriptor, _pageMetaDataDescriptionForeignKeyDataFieldDescriptor); } private DataTypeDescriptor CreateNewDataTypeDescriptor( string typeNamespace, string typeName, string typeTitle, string labelFieldName, string internalUrlPrefix, bool cachable, bool searchable, bool publishControlled, bool localizedControlled, IEnumerable<DataFieldDescriptor> dataFieldDescriptors, DataFieldDescriptor foreignKeyDataFieldDescriptor, DataTypeAssociationDescriptor dataTypeAssociationDescriptor, DataFieldDescriptor compositionRuleForeignKeyDataFieldDescriptor) { var id = Guid.NewGuid(); var dataTypeDescriptor = new DataTypeDescriptor(id, typeNamespace, typeName, true) { Cachable = cachable, Searchable = searchable, Title = typeTitle, LabelFieldName = labelFieldName, InternalUrlPrefix = internalUrlPrefix }; dataTypeDescriptor.DataScopes.Add(DataScopeIdentifier.Public); if (publishControlled && _dataAssociationType != DataAssociationType.Composition) { dataTypeDescriptor.AddSuperInterface(typeof(IPublishControlled)); } if (localizedControlled) { dataTypeDescriptor.AddSuperInterface(typeof(ILocalizedControlled)); } //bool addKeyField = true; if (_dataAssociationType == DataAssociationType.Aggregation) { dataTypeDescriptor.AddSuperInterface(typeof(IPageDataFolder)); } else if (_dataAssociationType == DataAssociationType.Composition) { //addKeyField = false; dataTypeDescriptor.AddSuperInterface(typeof(IPageData)); dataTypeDescriptor.AddSuperInterface(typeof(IPageRelatedData)); dataTypeDescriptor.AddSuperInterface(typeof(IPageMetaData)); } //if (addKeyField) //{ // var idDataFieldDescriptor = BuildKeyFieldDescriptor(); // dataTypeDescriptor.Fields.Add(idDataFieldDescriptor); // dataTypeDescriptor.KeyPropertyNames.Add(IdFieldName); //} foreach (var dataFieldDescriptor in dataFieldDescriptors) { dataTypeDescriptor.Fields.Add(dataFieldDescriptor); } if (_newKeyFieldName != null) { dataTypeDescriptor.KeyPropertyNames.Add(_newKeyFieldName); } var position = 100; if (_foreignKeyDataFieldDescriptor != null) { _foreignKeyDataFieldDescriptor.Position = position++; if (foreignKeyDataFieldDescriptor.Name != PageReferenceFieldName) { dataTypeDescriptor.Fields.Add(foreignKeyDataFieldDescriptor); dataTypeDescriptor.DataAssociations.Add(dataTypeAssociationDescriptor); } } return dataTypeDescriptor; } /// <summary> /// Builds a default "Id" field. /// </summary> /// <returns></returns> public static DataFieldDescriptor BuildIdField() { var idFieldDescriptor = new DataFieldDescriptor(Guid.NewGuid(), IdFieldName, StoreFieldType.Guid, typeof(Guid)) { DataUrlProfile = new DataUrlProfile { Order = 0 } }; return idFieldDescriptor; } private string KeyFieldName => _newKeyFieldName ?? IdFieldName; //private DataFieldDescriptor BuildKeyFieldDescriptor() //{ // DataFieldDescriptor result; // switch (_keyFieldType) // { // case KeyFieldType.Guid: // result = BuildIdField(); // break; // case KeyFieldType.RandomString4: // result = new DataFieldDescriptor(Guid.NewGuid(), IdFieldName, StoreFieldType.String(22), typeof (string)) // { // DefaultValue = DefaultValue.RandomString(4, true) // }; // break; // case KeyFieldType.RandomString8: // result = new DataFieldDescriptor(Guid.NewGuid(), IdFieldName, StoreFieldType.String(22), typeof (string)) // { // DefaultValue = DefaultValue.RandomString(8, false) // }; // break; // default: throw new InvalidOperationException("Not supported key field type value"); // } // result.Position = -1; // return result; //} private DataTypeDescriptor CreateUpdatedDataTypeDescriptor() { var dataTypeDescriptor = new DataTypeDescriptor(_oldDataTypeDescriptor.DataTypeId, _newTypeNamespace, _newTypeName, true) { Cachable = _cacheable, Searchable = _searchable }; dataTypeDescriptor.DataScopes.Add(DataScopeIdentifier.Public); Type[] indirectlyInheritedInterfaces = { typeof(IPublishControlled), typeof(ILocalizedControlled), typeof(IPageData), typeof(IPageFolderData), typeof(IPageMetaData) }; // Foreign interfaces should stay inherited foreach (var superInterface in _oldDataTypeDescriptor.SuperInterfaces) { if (!indirectlyInheritedInterfaces.Contains(superInterface)) { dataTypeDescriptor.AddSuperInterface(superInterface); } } if (_publishControlled && _dataAssociationType != DataAssociationType.Composition) { dataTypeDescriptor.AddSuperInterface(typeof(IPublishControlled)); } if (_localizedControlled && _dataAssociationType != DataAssociationType.Composition) { dataTypeDescriptor.AddSuperInterface(typeof(ILocalizedControlled)); } if (_oldDataTypeDescriptor.SuperInterfaces.Contains(typeof(IPageFolderData))) { dataTypeDescriptor.AddSuperInterface(typeof(IPageData)); dataTypeDescriptor.AddSuperInterface(typeof(IPageFolderData)); } else if (_oldDataTypeDescriptor.SuperInterfaces.Contains(typeof(IPageMetaData))) { dataTypeDescriptor.AddSuperInterface(typeof(IPageData)); dataTypeDescriptor.AddSuperInterface(typeof(IPageMetaData)); } else { //DataFieldDescriptor idDataFieldDescriptor = // (from dfd in _oldDataTypeDescriptor.Fields // where dfd.Name == KeyFieldName // select dfd).Single(); //dataTypeDescriptor.Fields.Add(idDataFieldDescriptor); //dataTypeDescriptor.KeyPropertyNames.Add(KeyFieldName); } dataTypeDescriptor.Title = _newTypeTitle; foreach (var dataFieldDescriptor in _newDataFieldDescriptors) { dataTypeDescriptor.Fields.Add(dataFieldDescriptor); } if (KeyFieldName != null && !dataTypeDescriptor.KeyPropertyNames.Contains(KeyFieldName)) { dataTypeDescriptor.KeyPropertyNames.Add(KeyFieldName); } dataTypeDescriptor.LabelFieldName = _newLabelFieldName; dataTypeDescriptor.InternalUrlPrefix = _newInternalUrlPrefix; dataTypeDescriptor.DataAssociations.AddRange(_oldDataTypeDescriptor.DataAssociations); var position = 100; if (_foreignKeyDataFieldDescriptor != null) { _foreignKeyDataFieldDescriptor.Position = position++; if (_foreignKeyDataFieldDescriptor.Name != PageReferenceFieldName) { dataTypeDescriptor.Fields.Add(_foreignKeyDataFieldDescriptor); } } return dataTypeDescriptor; } private static DataFieldDescriptor CreateWeakReferenceDataFieldDescriptor(DataTypeDescriptor targetDataTypeDescriptor, DataFieldDescriptor targetDataFieldDescriptor, string fieldName) { TypeManager.GetType(targetDataTypeDescriptor.TypeManagerTypeName); var widgetFunctionProvider = StandardWidgetFunctions.TextBoxWidget; return new DataFieldDescriptor(Guid.NewGuid(), fieldName, targetDataFieldDescriptor.StoreType, targetDataFieldDescriptor.InstanceType) { IsNullable = targetDataFieldDescriptor.IsNullable, DefaultValue = targetDataFieldDescriptor.DefaultValue, ValidationFunctionMarkup = targetDataFieldDescriptor.ValidationFunctionMarkup, FormRenderingProfile = new DataFieldFormRenderingProfile { Label = fieldName, HelpText = fieldName, WidgetFunctionMarkup = widgetFunctionProvider.SerializedWidgetFunction.ToString(SaveOptions.DisableFormatting) } }; } private static DataFieldDescriptor CreateReferenceDataFieldDescriptor(DataTypeDescriptor targetDataTypeDescriptor, out string foreignKeyFieldName, string fieldName = null) { var targetType = TypeManager.GetType(targetDataTypeDescriptor.TypeManagerTypeName); var targetKeyFieldName = targetDataTypeDescriptor.KeyPropertyNames.First(); var targetKeyDataFieldDescriptor = targetDataTypeDescriptor.Fields[targetKeyFieldName]; foreignKeyFieldName = fieldName ?? $"{targetDataTypeDescriptor.Name}{targetKeyFieldName}ForeignKey"; var widgetFunctionProvider = StandardWidgetFunctions.GetDataReferenceWidget(targetType); return new DataFieldDescriptor(Guid.NewGuid(), foreignKeyFieldName, targetKeyDataFieldDescriptor.StoreType, targetKeyDataFieldDescriptor.InstanceType) { IsNullable = targetKeyDataFieldDescriptor.IsNullable, DefaultValue = targetKeyDataFieldDescriptor.DefaultValue, ValidationFunctionMarkup = targetKeyDataFieldDescriptor.ValidationFunctionMarkup, ForeignKeyReferenceTypeName = targetDataTypeDescriptor.TypeManagerTypeName, FormRenderingProfile = new DataFieldFormRenderingProfile { Label = foreignKeyFieldName, HelpText = foreignKeyFieldName, WidgetFunctionMarkup = widgetFunctionProvider.SerializedWidgetFunction.ToString(SaveOptions.DisableFormatting) } }; } private bool IsDataFieldBindable(DataTypeDescriptor dataTypeDescriptor, DataFieldDescriptor dataFieldDescriptor) { if (dataFieldDescriptor.Inherited) { var superInterface = dataTypeDescriptor.SuperInterfaces.FirstOrDefault(type => type.GetProperty(dataFieldDescriptor.Name) != null); if (superInterface != null && superInterface.Assembly == typeof(IData).Assembly) { return false; } } if ((dataFieldDescriptor.Name == IdFieldName || dataFieldDescriptor.Name == CompositionDescriptionFieldName) && dataTypeDescriptor.IsPageMetaDataType) { return false; } if (PageFolderFacade.GetAllFolderTypes().Contains(_oldType) && dataFieldDescriptor.Name == PageReferenceFieldName) { return false; } if (dataFieldDescriptor.ForeignKeyReferenceTypeName != null) { var dataTypeAssociationDescriptor = dataTypeDescriptor.DataAssociations.FirstOrDefault(); if (dataTypeAssociationDescriptor != null) { if (!AllowForeignKeyEditing && dataFieldDescriptor.Name == dataTypeAssociationDescriptor.ForeignKeyPropertyName) { return false; } if (dataFieldDescriptor.Name == CompositionDescriptionFieldName && dataTypeDescriptor.IsPageMetaDataType) { return false; } } } return true; } } } ================================================ FILE: Composite/Data/GeneratedTypes/IGeneratedTypesFacade.cs ================================================ using System.Collections.Generic; using Composite.Data.DynamicTypes; namespace Composite.Data.GeneratedTypes { internal interface IGeneratedTypesFacade { void GenerateNewTypes(string providerName, IReadOnlyCollection<DataTypeDescriptor> dataTypeDescriptors, bool makeAFlush); bool CanDeleteType(DataTypeDescriptor dataTypeDescriptor, out string errorMessage); void DeleteType(string providerName, DataTypeDescriptor dataTypeDescriptor, bool makeAFlush); void UpdateType(UpdateDataTypeDescriptor updateDataTypeDescriptor); } } ================================================ FILE: Composite/Data/GeneratedTypes/InterfaceCodeGenerator.cs ================================================ using System; using System.CodeDom; using System.Collections.Generic; using System.Linq; using Composite.Core.Types; using Composite.Core.WebClient.Renderings.Data; using Composite.Data.DynamicTypes; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.Validation.Validators; using System.Reflection; namespace Composite.Data.GeneratedTypes { /// <summary> /// Will generate data interfaces given <see cref="DataTypeDescriptor"/>. /// </summary> public static class InterfaceCodeGenerator { /// <summary> /// Adds the assembly references required by the supplied <see cref="DataTypeDescriptor"/> to the supplied <see cref="CodeGenerationBuilder"/> /// </summary> /// <param name="codeGenerationBuilder">Assembly refences is added to this builder</param> /// <param name="dataTypeDescriptor">Data type descriptor which may contain references to assemblies</param> public static void AddAssemblyReferences(CodeGenerationBuilder codeGenerationBuilder, DataTypeDescriptor dataTypeDescriptor) { foreach (Assembly assembly in GetReferencedAssemblies(dataTypeDescriptor)) { codeGenerationBuilder.AddReference(assembly); } } /// <summary> /// Adds the source code defined by <see cref="DataTypeDescriptor"/> to the supplied <see cref="CodeGenerationBuilder"/> /// </summary> /// <param name="codeGenerationBuilder">Source code is added to this builder</param> /// <param name="dataTypeDescriptor">Data type descriptor to convert into source code</param> public static void AddInterfaceTypeCode(CodeGenerationBuilder codeGenerationBuilder, DataTypeDescriptor dataTypeDescriptor) { var codeTypeDeclaration = CreateCodeTypeDeclaration(dataTypeDescriptor); var codeNamespace = new CodeNamespace(dataTypeDescriptor.Namespace); codeNamespace.Types.Add(codeTypeDeclaration); codeGenerationBuilder.AddNamespace(codeNamespace); } internal static IEnumerable<Assembly> GetReferencedAssemblies(DataTypeDescriptor dataTypeDescriptor) { yield return typeof(ImmutableTypeIdAttribute).Assembly; yield return typeof(Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidatorAttribute).Assembly; } /// <summary> /// Given a <see cref="DataTypeDescriptor"/> creates a interface declaration inheriting from IData, a valid C1 Datatype. /// </summary> /// <param name="dataTypeDescriptor">A description of the data type to generate interface for</param> /// <returns>The generated interface</returns> public static CodeTypeDeclaration CreateCodeTypeDeclaration(DataTypeDescriptor dataTypeDescriptor) { try { var codeTypeDeclaration = new CodeTypeDeclaration(dataTypeDescriptor.Name) { IsInterface = true }; codeTypeDeclaration.BaseTypes.Add(new CodeTypeReference(typeof(IData))); var propertyNamesToSkip = new List<string>(); foreach (Type superInterface in dataTypeDescriptor.SuperInterfaces) { codeTypeDeclaration.BaseTypes.Add(new CodeTypeReference(superInterface)); propertyNamesToSkip.AddRange(superInterface.GetAllProperties().Select(p => p.Name)); } AddInterfaceAttributes(codeTypeDeclaration.CustomAttributes, dataTypeDescriptor); AddInterfaceProperties(codeTypeDeclaration, dataTypeDescriptor, propertyNamesToSkip); return codeTypeDeclaration; } catch (Exception ex) { throw new InvalidOperationException($"Failed to generate interface for type '{dataTypeDescriptor.TypeManagerTypeName}'", ex); } } private static void AddInterfaceAttributes(CodeAttributeDeclarationCollection attributes, DataTypeDescriptor dataTypeDescriptor) { attributes.Add( new CodeAttributeDeclaration( typeof(AutoUpdatebleAttribute).FullName, new CodeAttributeArgument[] { } )); attributes.Add( new CodeAttributeDeclaration( typeof(DataScopeAttribute).FullName, new [] { new CodeAttributeArgument( new CodePrimitiveExpression( DataScopeIdentifier.GetDefault().Name )) } )); attributes.Add( new CodeAttributeDeclaration( typeof(RelevantToUserTypeAttribute).FullName, new [] { new CodeAttributeArgument( new CodePrimitiveExpression( nameof(UserType.Developer) )) } )); attributes.Add( new CodeAttributeDeclaration( typeof(CodeGeneratedAttribute).FullName, new CodeAttributeArgument[] { } )); attributes.Add( new CodeAttributeDeclaration( typeof(DataAncestorProviderAttribute).FullName, new [] { new CodeAttributeArgument( new CodeTypeOfExpression(typeof(NoAncestorDataAncestorProvider)) ) } )); attributes.Add( new CodeAttributeDeclaration( typeof(ImmutableTypeIdAttribute).FullName, new [] { new CodeAttributeArgument(new CodePrimitiveExpression(dataTypeDescriptor.DataTypeId.ToString())) } )); var xhtmlEmbedableEnumRef = new CodeFieldReferenceExpression( new CodeTypeReferenceExpression( typeof(XhtmlRenderingType) ), XhtmlRenderingType.Embedable.ToString()); attributes.Add( new CodeAttributeDeclaration( typeof(KeyTemplatedXhtmlRendererAttribute).FullName, new [] { new CodeAttributeArgument(xhtmlEmbedableEnumRef), new CodeAttributeArgument(new CodePrimitiveExpression("<span>{label}</span>")) } )); foreach (string keyFieldName in dataTypeDescriptor.KeyPropertyNames) { bool isDefinedOnSuperInterface = dataTypeDescriptor.SuperInterfaces.Any(f => f.GetProperty(keyFieldName) != null); if (!isDefinedOnSuperInterface) { attributes.Add( new CodeAttributeDeclaration( typeof(KeyPropertyNameAttribute).FullName, new [] { new CodeAttributeArgument(new CodePrimitiveExpression(keyFieldName)) } )); } } if (dataTypeDescriptor.StoreSortOrderFieldNames.Count > 0) { attributes.Add( new CodeAttributeDeclaration( typeof(StoreSortOrderAttribute).FullName, dataTypeDescriptor.StoreSortOrderFieldNames.Select(name => new CodeAttributeArgument(new CodePrimitiveExpression(name))).ToArray() )); } if (!string.IsNullOrEmpty(dataTypeDescriptor.Title)) { attributes.Add( new CodeAttributeDeclaration( typeof(TitleAttribute).FullName, new CodeAttributeArgument( new CodePrimitiveExpression(dataTypeDescriptor.Title) ) )); } if (!string.IsNullOrEmpty(dataTypeDescriptor.LabelFieldName)) { attributes.Add( new CodeAttributeDeclaration( typeof(LabelPropertyNameAttribute).FullName, new CodeAttributeArgument( new CodePrimitiveExpression(dataTypeDescriptor.LabelFieldName) ) )); } if (!string.IsNullOrEmpty(dataTypeDescriptor.InternalUrlPrefix)) { attributes.Add( new CodeAttributeDeclaration( typeof (InternalUrlAttribute).FullName, new CodeAttributeArgument( new CodePrimitiveExpression(dataTypeDescriptor.InternalUrlPrefix) ) )); } foreach (var dataTypeAssociationDescriptor in dataTypeDescriptor.DataAssociations) { attributes.Add( new CodeAttributeDeclaration( typeof(DataAssociationAttribute).FullName, new CodeAttributeArgument(new CodeTypeOfExpression(dataTypeAssociationDescriptor.AssociatedInterfaceType)), new CodeAttributeArgument(new CodePrimitiveExpression(dataTypeAssociationDescriptor.ForeignKeyPropertyName)), new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(DataAssociationType)),dataTypeAssociationDescriptor.AssociationType.ToString())) )); } if (!dataTypeDescriptor.SuperInterfaces.Contains(typeof(IPageMetaData))) { if (dataTypeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled))) { attributes.Add( new CodeAttributeDeclaration( typeof(PublishProcessControllerTypeAttribute).FullName, new CodeAttributeArgument(new CodeTypeOfExpression(typeof(GenericPublishProcessController))))); } } if (dataTypeDescriptor.Cachable) { // [CachingAttribute(CachingType.Full)] attributes.Add( new CodeAttributeDeclaration( typeof(CachingAttribute).FullName, new CodeAttributeArgument( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(CachingType)), nameof(CachingType.Full) ) ))); } if (dataTypeDescriptor.Searchable) { // [SearchableTypeAttribute] attributes.Add( new CodeAttributeDeclaration( typeof(SearchableTypeAttribute).FullName )); } } private static void AddInterfaceProperties(CodeTypeDeclaration codeTypeDeclaration, DataTypeDescriptor dataTypeDescriptor, List<string> propertyNamesToSkip) { foreach (var dataFieldDescriptor in dataTypeDescriptor.Fields.Where(dfd => !dfd.Inherited)) { if (propertyNamesToSkip.Contains(dataFieldDescriptor.Name)) continue; var codeMemberProperty = new CodeMemberProperty { Name = dataFieldDescriptor.Name, Type = new CodeTypeReference(dataFieldDescriptor.InstanceType), HasGet = true, HasSet = true }; AddPropertyAttributes(codeMemberProperty.CustomAttributes, dataFieldDescriptor, dataTypeDescriptor.KeyPropertyNames.Contains(dataFieldDescriptor.Name)); codeTypeDeclaration.Members.Add(codeMemberProperty); } } private static void AddPropertyAttributes(CodeAttributeDeclarationCollection customAttributes, DataFieldDescriptor dataFieldDescriptor, bool isKeyField) { customAttributes.Add( new CodeAttributeDeclaration( typeof(ImmutableFieldIdAttribute).FullName, new CodeAttributeArgument(new CodePrimitiveExpression(dataFieldDescriptor.Id.ToString())))); if (isKeyField && dataFieldDescriptor.InstanceType == typeof(Guid) && dataFieldDescriptor.NewInstanceDefaultFieldValue == null) { customAttributes.Add( new CodeAttributeDeclaration( typeof(FunctionBasedNewInstanceDefaultFieldValueAttribute).FullName, new CodeAttributeArgument(new CodePrimitiveExpression(@"<f:function name=""Composite.Utils.Guid.NewGuid"" xmlns:f=""http://www.composite.net/ns/function/1.0"" />")))); } else if (dataFieldDescriptor.NewInstanceDefaultFieldValue != null) { customAttributes.Add( new CodeAttributeDeclaration( typeof(FunctionBasedNewInstanceDefaultFieldValueAttribute).FullName, new CodeAttributeArgument(new CodePrimitiveExpression(dataFieldDescriptor.NewInstanceDefaultFieldValue)))); } var arguments = new List<CodeAttributeArgument> { new CodeAttributeArgument( new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(typeof (PhysicalStoreFieldType)), dataFieldDescriptor.StoreType.PhysicalStoreType.ToString() )) }; switch (dataFieldDescriptor.StoreType.PhysicalStoreType) { case PhysicalStoreFieldType.String: arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(dataFieldDescriptor.StoreType.MaximumLength))); break; case PhysicalStoreFieldType.Decimal: arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(dataFieldDescriptor.StoreType.NumericPrecision))); arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(dataFieldDescriptor.StoreType.NumericScale))); break; } if (dataFieldDescriptor.IsNullable) { arguments.Add(new CodeAttributeArgument(nameof(StoreFieldTypeAttribute.IsNullable), new CodePrimitiveExpression(true))); } customAttributes.Add( new CodeAttributeDeclaration( typeof(StoreFieldTypeAttribute).FullName, arguments.ToArray() )); if (dataFieldDescriptor.ValidationFunctionMarkup != null) { foreach (string functionMarkup in dataFieldDescriptor.ValidationFunctionMarkup) { var codeAttributeDeclaration = new CodeAttributeDeclaration( new CodeTypeReference(typeof(LazyFunctionProviedPropertyAttribute)), new CodeAttributeArgument( new CodePrimitiveExpression(functionMarkup) ) ); customAttributes.Add(codeAttributeDeclaration); } } if (!dataFieldDescriptor.IsNullable) { if (!dataFieldDescriptor.InstanceType.IsValueType) { var notNullAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidatorAttribute))); customAttributes.Add(notNullAttribute); } if (dataFieldDescriptor.StoreType.IsDateTime) { var dateRangeAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(Microsoft.Practices.EnterpriseLibrary.Validation.Validators.DateTimeRangeValidatorAttribute))); // 1753 is what sql server has as minimum date... dateRangeAttribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("1753-01-01T00:00:00"))); dateRangeAttribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("9999-12-31T23:59:59"))); customAttributes.Add(dateRangeAttribute); } else if (dataFieldDescriptor.ForeignKeyReferenceTypeName != null && dataFieldDescriptor.InstanceType == typeof(Guid)) { customAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(GuidNotEmptyAttribute)))); } } if (dataFieldDescriptor.Position < 1000) // Hmm, 1000 is kinda random { var fieldPositionAttribute = new CodeAttributeDeclaration( new CodeTypeReference(typeof(FieldPositionAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression(dataFieldDescriptor.Position)) ); customAttributes.Add(fieldPositionAttribute); } if (dataFieldDescriptor.StoreType.IsString && !dataFieldDescriptor.StoreType.IsLargeString) { var attributeType = dataFieldDescriptor.IsNullable ? typeof (NullStringLengthValidatorAttribute) : typeof (StringSizeValidatorAttribute); int max = dataFieldDescriptor.StoreType.MaximumLength; var stringLengthAttribute = new CodeAttributeDeclaration(new CodeTypeReference(attributeType), new CodeAttributeArgument(new CodePrimitiveExpression(0)), new CodeAttributeArgument(new CodePrimitiveExpression(max))); customAttributes.Add(stringLengthAttribute); } if (dataFieldDescriptor.StoreType.PhysicalStoreType == PhysicalStoreFieldType.Integer) { Type validatorAttributeType = dataFieldDescriptor.IsNullable ? typeof(NullIntegerRangeValidatorAttribute) : typeof(IntegerRangeValidatorAttribute); var integerRangeValidatorAttribute = new CodeAttributeDeclaration(new CodeTypeReference(validatorAttributeType), new CodeAttributeArgument(new CodePrimitiveExpression(Int32.MinValue)), new CodeAttributeArgument(new CodePrimitiveExpression(Int32.MaxValue))); customAttributes.Add(integerRangeValidatorAttribute); } if (dataFieldDescriptor.StoreType.IsDecimal) { var decimalPrecisionAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(DecimalPrecisionValidatorAttribute))); int precision = dataFieldDescriptor.StoreType.NumericScale; decimalPrecisionAttribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(precision))); customAttributes.Add(decimalPrecisionAttribute); } if (dataFieldDescriptor.DefaultValue != null) { CodeAttributeDeclaration codeAttributeDeclaration = dataFieldDescriptor.DefaultValue.GetCodeAttributeDeclaration(); if (codeAttributeDeclaration != null) { customAttributes.Add(codeAttributeDeclaration); } } if (dataFieldDescriptor.ForeignKeyReferenceTypeName != null) { var codeAttributeArgument = new List<CodeAttributeArgument> { new CodeAttributeArgument(new CodePrimitiveExpression(dataFieldDescriptor.ForeignKeyReferenceTypeName)), new CodeAttributeArgument(nameof(ForeignKeyAttribute.AllowCascadeDeletes), new CodePrimitiveExpression(true)) }; if (!dataFieldDescriptor.IsNullable) { CodeExpression defaultValue; if (dataFieldDescriptor.InstanceType == typeof(Guid)) { defaultValue = new CodePrimitiveExpression("{00000000-0000-0000-0000-000000000000}"); } else if (dataFieldDescriptor.InstanceType == typeof(string)) { defaultValue = new CodePrimitiveExpression(null); } else if (dataFieldDescriptor.InstanceType == typeof(int)) { defaultValue = new CodePrimitiveExpression(0); } else { throw new NotImplementedException(); } codeAttributeArgument.Add(new CodeAttributeArgument(nameof(ForeignKeyAttribute.NullReferenceValue), defaultValue)); } else if (dataFieldDescriptor.InstanceType == typeof(string)) { codeAttributeArgument.Add(new CodeAttributeArgument(nameof(ForeignKeyAttribute.NullableString), new CodePrimitiveExpression(true))); } customAttributes.Add( new CodeAttributeDeclaration( typeof(ForeignKeyAttribute).FullName, codeAttributeArgument.ToArray() )); } if (dataFieldDescriptor.TreeOrderingProfile.OrderPriority.HasValue) { var args = new List<CodeAttributeArgument> { new CodeAttributeArgument(new CodePrimitiveExpression(dataFieldDescriptor.TreeOrderingProfile.OrderPriority)) }; if (dataFieldDescriptor.TreeOrderingProfile.OrderDescending) { args.Add( new CodeAttributeArgument(new CodePrimitiveExpression(dataFieldDescriptor.TreeOrderingProfile.OrderDescending))); } customAttributes.Add( new CodeAttributeDeclaration( typeof(TreeOrderingAttribute).FullName, args.ToArray() )); } if (dataFieldDescriptor.DataUrlProfile != null) { customAttributes.Add(dataFieldDescriptor.DataUrlProfile.GetCodeAttributeDeclaration()); } var attribute = dataFieldDescriptor.SearchProfile?.GetCodeAttributeDeclaration(); if (attribute != null) { customAttributes.Add(attribute); } if (dataFieldDescriptor.GroupByPriority != 0) { customAttributes.Add( new CodeAttributeDeclaration( typeof(GroupByPriorityAttribute).FullName, new CodeAttributeArgument( new CodePrimitiveExpression( dataFieldDescriptor.GroupByPriority ) ) )); } } } } ================================================ FILE: Composite/Data/GeneratedTypes/InterfaceCodeManager.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Core.Types; using Composite.Data.DynamicTypes; namespace Composite.Data.GeneratedTypes { /// <summary> /// This class handles the caching of code generated data interface. /// It also through <see cref="InterfaceCodeGenerator"/> generated data interfaces, /// that does not exist. /// </summary> internal static class InterfaceCodeManager { private static readonly object _lock = new object(); /// <summary> /// This method will return type given by the dataTypeDescriptor. /// If the data type does not exist, one will be dynamically /// runtime code generated. /// </summary> /// <param name="dataTypeDescriptor"></param> /// <param name="forceReCompilation">If this is true a new type will be compiled regardless if one already exists.</param> /// <returns></returns> public static Type GetType(DataTypeDescriptor dataTypeDescriptor, bool forceReCompilation = false) { bool codeGenerationNeeded; Type type = TryGetType(dataTypeDescriptor, forceReCompilation, out codeGenerationNeeded); if (type != null) { return type; } if (codeGenerationNeeded) { lock (_lock) { type = TypeManager.TryGetType(dataTypeDescriptor.GetFullInterfaceName()); if (type != null) return type; var codeGenerationBuilder = new CodeGenerationBuilder("DataInterface: " + dataTypeDescriptor.Name); InterfaceCodeGenerator.AddAssemblyReferences(codeGenerationBuilder, dataTypeDescriptor); InterfaceCodeGenerator.AddInterfaceTypeCode(codeGenerationBuilder, dataTypeDescriptor); IEnumerable<Type> types = CodeGenerationManager.CompileRuntimeTempTypes(codeGenerationBuilder); return types.Single(); } } return null; } internal static Type TryGetType(DataTypeDescriptor dataTypeDescriptor, bool forceReCompilation, out bool codeGenerationNeeded) { Verify.ArgumentNotNull(dataTypeDescriptor, "dataTypeDescriptor"); codeGenerationNeeded = false; Type type; if (!forceReCompilation) { type = TypeManager.TryGetType(dataTypeDescriptor.GetFullInterfaceName()); if (type != null) return type; if (!dataTypeDescriptor.IsCodeGenerated) { type = TypeManager.TryGetType(dataTypeDescriptor.TypeManagerTypeName); if (type != null) return type; } } if (!dataTypeDescriptor.IsCodeGenerated) { return null; } if (forceReCompilation) { type = TypeManager.TryGetType(dataTypeDescriptor.GetFullInterfaceName()); if (type != null) return type; } codeGenerationNeeded = true; return null; } } } ================================================ FILE: Composite/Data/GeneratedTypes/InterfaceCodeProvider.cs ================================================ using System.Reflection; using Composite.Core.Types; using Composite.Data.DynamicTypes; namespace Composite.Data.GeneratedTypes { internal class InterfaceCodeProvider : ICodeProvider { public void GetCodeToCompile(CodeGenerationBuilder builder) { foreach (DataTypeDescriptor dataTypeDescriptor in DataMetaDataFacade.GeneratedTypeDataTypeDescriptors) { InterfaceCodeGenerator.AddAssemblyReferences(builder, dataTypeDescriptor); InterfaceCodeGenerator.AddInterfaceTypeCode(builder, dataTypeDescriptor); } } } } ================================================ FILE: Composite/Data/GlobalDataTypeFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; namespace Composite.Data { /// <summary> /// This facade is used for handlign genereted/dynamic global data types /// </summary> internal static class GlobalDataTypeFacade { public static IEnumerable<Type> GetAllGlobalDataTypes() { return DataFacade.GetGeneratedInterfaces(). Except(PageFolderFacade.GetAllFolderTypes()). Except(PageMetaDataFacade.GetAllMetaDataTypes()); } } } ================================================ FILE: Composite/Data/GroupByPriorityAttribute.cs ================================================ using System; namespace Composite.Data { /// <summary> /// Assign this to properties on your IData interfaces to control default page foldering of tree items. /// </summary> public sealed class GroupByPriorityAttribute : Attribute { /// <summary> /// Specify that this field should be used for default tree foldering. /// Multiple fields on a data type may create foldering. In that case the priority has importance. /// </summary> /// <param name="priority">Priority controls which fields are used first when foldering. Low number win.</param> public GroupByPriorityAttribute(int priority) { this.Priority = priority; } /// <summary> /// Priority for foldering. /// </summary> public int Priority { get; set; } } } ================================================ FILE: Composite/Data/Hierarchy/DataAncestorFacade.cs ================================================ using System; using Composite.Data.Hierarchy.Foundation; namespace Composite.Data.Hierarchy { internal static class DataAncestorFacade { public static IData GetParent(this IData data) { if (data == null) throw new ArgumentNullException("data"); IDataAncestorProvider provider = DataAncestorProviderCache.GetDataAncestorProvider(data); return provider.GetParent(data);; } } } ================================================ FILE: Composite/Data/Hierarchy/DataAncestorProviderAttribute.cs ================================================ using System; namespace Composite.Data.Hierarchy { /// <summary> /// This attribute is requried if data items of this type is used as elements in a tree view. /// This attribute points to a type that can resolve parent relations. /// See <see cref="Composite.Data.Hierarchy.IDataAncestorProvider"/> for more information on parent relations. /// In case that the data items do not have natural parents, use the default implementaion <see cref="Composite.Data.Hierarchy.DataAncestorProviders.NoAncestorDataAncestorProvider"/> /// </summary> [AttributeUsageAttribute(AttributeTargets.Interface, Inherited = true, AllowMultiple = false)] public sealed class DataAncestorProviderAttribute : Attribute { private Type _dataAncestorProviderType; /// <summary> /// Create a instance of <see cref="DataAncestorProviderAttribute"/> given the <paramref name="dataAncestorProviderType"/> type. /// </summary> /// <param name="dataAncestorProviderType">The type that can resolve parent relations. See <see cref="Composite.Data.Hierarchy.IDataAncestorProvider"/>.</param> public DataAncestorProviderAttribute(Type dataAncestorProviderType) { _dataAncestorProviderType = dataAncestorProviderType; } /// <summary> /// The type that can resolve parent relations. See <see cref="Composite.Data.Hierarchy.IDataAncestorProvider"/>. /// </summary> public Type DataAncestorProviderType { get { return _dataAncestorProviderType; } } } } ================================================ FILE: Composite/Data/Hierarchy/DataAncestorProviders/NoAncestorDataAncestorProvider.cs ================================================ namespace Composite.Data.Hierarchy.DataAncestorProviders { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class NoAncestorDataAncestorProvider : IDataAncestorProvider { /// <exclude /> public IData GetParent(IData data) { Verify.ArgumentNotNull(data, "data"); return null; } } } ================================================ FILE: Composite/Data/Hierarchy/DataAncestorProviders/PageDataAncestorProvider.cs ================================================ using System; using Composite.Core.Configuration; using Composite.Data.Types; using Composite.Core.Extensions; namespace Composite.Data.Hierarchy.DataAncestorProviders { internal sealed class PageDataAncestorProvider : IDataAncestorProvider { public IData GetParent(IData data) { Verify.ArgumentNotNull(data, "data"); IPage page = data as IPage; Verify.IsNotNull(page, "Only '{0}' type is supported.".FormatWith(typeof(IPage).FullName)); Guid parentId = PageManager.GetParentId(page.Id); if (parentId == Guid.Empty) { return null; } using (new DataScope(data.DataSourceId.LocaleScope)) { return PageManager.GetPageById(parentId); } } } } ================================================ FILE: Composite/Data/Hierarchy/DataAncestorProviders/PropertyDataAncestorProvider.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Core.Linq; using Composite.Core.Types; namespace Composite.Data.Hierarchy.DataAncestorProviders { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class PropertyDataAncestorProviderAttribute : Attribute { private string _idPropertyName; private string _parentIdPropertyName; private Type _parentDataType; private object _nullValue; /// <summary> /// /// </summary> /// <param name="idPropertyName">The name of the property that contains the value of the parent id property</param> /// <param name="parentDataType">The type of the parent</param> /// <param name="parentIdPropertyName">The name of the id property on the parent</param> /// <param name="nullValue"></param> public PropertyDataAncestorProviderAttribute(string idPropertyName, Type parentDataType, string parentIdPropertyName, object nullValue) { _idPropertyName = idPropertyName; _parentDataType = parentDataType; _parentIdPropertyName = parentIdPropertyName; _nullValue = nullValue; } /// <exclude /> public string IdPropertyName { get { return _idPropertyName; } } /// <exclude /> public string ParentIdPropertyName { get { return _parentIdPropertyName; } } /// <exclude /> public Type ParentDataType { get { return _parentDataType; } } /// <exclude /> public object NullValue { get { return _nullValue; } } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class PropertyDataAncestorProvider : IDataAncestorProvider { private Dictionary<Type, Entry> _methodInfoCache = new Dictionary<Type, Entry>(); /// <exclude /> public IData GetParent(IData data) { if (data == null) throw new ArgumentNullException("data"); Entry entry = GetEntry(data.GetType()); object propertyValue = entry.PropertyValueMethodInfo.Invoke(data, null); if (entry.PropertyValueMethodInfo.ReturnType == typeof(Guid)) { if (Equals(propertyValue, Guid.Empty)) return null; } else { if (Equals(propertyValue, entry.NullValue)) return null; } using (DataScope dataScope = new DataScope(data.DataSourceId.DataScopeIdentifier)) { List<object> queryResult = GetQueryResult(entry.ParentDataType, entry.ParentIdPropertyName, propertyValue); if (queryResult.Count == 0) throw new InvalidOperationException(string.Format("The parent of the type {0} with the id ({1}) value of {2} was not found", entry.ParentDataType, entry.ParentIdPropertyName, propertyValue)); if (queryResult.Count > 1) throw new InvalidOperationException(string.Format("More than one parent of the type {0} with the id ({1}) value of {2} was found", entry.ParentDataType, entry.ParentIdPropertyName, propertyValue)); return (IData)queryResult[0]; } } private Entry GetEntry(Type dataType) { Entry entry; if (_methodInfoCache.TryGetValue(dataType, out entry) == false) { List<PropertyDataAncestorProviderAttribute> attributes = dataType.GetCustomInterfaceAttributes<PropertyDataAncestorProviderAttribute>().ToList(); if (attributes.Count == 0) throw new InvalidOperationException(string.Format("Missing {0} attribute on the data type {1}", typeof(PropertyDataAncestorProviderAttribute), dataType)); if (attributes.Count > 1) throw new InvalidOperationException(string.Format("Only one {0} attribute is allowed on the data type {1}", typeof(PropertyDataAncestorProviderAttribute), dataType)); PropertyDataAncestorProviderAttribute attribute = attributes[0]; PropertyInfo propertyInfo = dataType.GetProperty(attribute.IdPropertyName); if (propertyInfo == null) throw new InvalidOperationException(string.Format("No property named {0} (as specified on the PropertyDataAncestorProivder) on the type {1}", attribute.IdPropertyName, dataType)); MethodInfo methodInfo = propertyInfo.GetGetMethod(); if (methodInfo == null) throw new InvalidOperationException(string.Format("Missing get property named {0} (as specified on the PropertyDataAncestorProivder) on the type {1}", attribute.IdPropertyName, dataType)); if (typeof(IData).IsAssignableFrom(attribute.ParentDataType) == false) throw new InvalidOperationException(string.Format("The parent type ({0}) should be of type {1}", attribute.ParentDataType, typeof(IData))); if (attribute.ParentDataType.GetProperty(attribute.ParentIdPropertyName) == null) throw new InvalidOperationException(string.Format("The id property named {0} is missing from the parent type {1}", attribute.IdPropertyName, attribute.ParentDataType)); entry = new Entry { PropertyValueMethodInfo = methodInfo, ParentDataType = attribute.ParentDataType, ParentIdPropertyName = attribute.ParentIdPropertyName, NullValue = attribute.NullValue, }; _methodInfoCache.Add(dataType, entry); } return entry; } private List<object> GetQueryResult(Type dataType, string idPropertyName, object value) { ParameterExpression parameter = Expression.Parameter(dataType, "parameter"); Expression body = Expression.Equal(Expression.Property(parameter, idPropertyName), Expression.Constant(value)); LambdaExpression lambda = Expression.Lambda(body, parameter); MethodInfo getDataMethod = DataFacade.GetGetDataMethodInfo(dataType); IQueryable queryable = (IQueryable)getDataMethod.Invoke(null, new object[] { true, null }); Expression whereExpression = ExpressionCreator.Where(queryable.Expression, lambda); IEnumerable enumerable = (IEnumerable)queryable.Provider.CreateQuery(whereExpression); return enumerable.ToListOfObjects(); } private sealed class Entry { public MethodInfo PropertyValueMethodInfo { get; set; } public Type ParentDataType { get; set; } public string ParentIdPropertyName { get; set; } public object NullValue { get; set; } } } } ================================================ FILE: Composite/Data/Hierarchy/Foundation/DataAncestorProviderCache.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using Composite.Core.Collections.Generic; using Composite.Core.Types; using Composite.C1Console.Events; namespace Composite.Data.Hierarchy.Foundation { internal static class DataAncestorProviderCache { private static Hashtable<Type, IDataAncestorProvider> _dataAncestorProviderCache = new Hashtable<Type, IDataAncestorProvider>(); private static readonly object _syncRoot = new object(); static DataAncestorProviderCache() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } public static IDataAncestorProvider GetDataAncestorProvider(IData data) { if (data == null) throw new ArgumentNullException("data"); Type dataType = data.GetType(); var cache = _dataAncestorProviderCache; IDataAncestorProvider dataAncestorProvider = cache[dataType]; if (dataAncestorProvider != null) { return dataAncestorProvider; } lock (_syncRoot) { dataAncestorProvider = cache[dataType]; if (dataAncestorProvider != null) { return dataAncestorProvider; } List<DataAncestorProviderAttribute> attributes = dataType.GetCustomInterfaceAttributes<DataAncestorProviderAttribute>().ToList(); if (attributes.Count == 0) throw new InvalidOperationException(string.Format("Missing {0} attribute on the data type {1}", typeof(DataAncestorProviderAttribute), dataType)); if (attributes.Count > 1) throw new InvalidOperationException(string.Format("Only one {0} attribute is allowed on the data type {1}", typeof(DataAncestorProviderAttribute), dataType)); DataAncestorProviderAttribute attribute = attributes[0]; if (attribute.DataAncestorProviderType == null) throw new InvalidOperationException(string.Format("Data ancestor provider type can not be null on the data type {0}", data)); if (typeof(IDataAncestorProvider).IsAssignableFrom(attribute.DataAncestorProviderType) == false) throw new InvalidOperationException(string.Format("Data ancestor provider {0} should implement the interface {1}", attribute.DataAncestorProviderType, typeof(IDataAncestorProvider))); dataAncestorProvider = (IDataAncestorProvider)Activator.CreateInstance(attribute.DataAncestorProviderType); cache.Add(dataType, dataAncestorProvider); return dataAncestorProvider; } } private static void Flush() { _dataAncestorProviderCache = new Hashtable<Type, IDataAncestorProvider>(); } } } ================================================ FILE: Composite/Data/Hierarchy/IDataAncestorProvider.cs ================================================ using Composite.Data; namespace Composite.Data.Hierarchy { /// <summary> /// Implementations of this interface is used for determining hierarchy when /// data items are used as elements in trees. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IDataAncestorProvider { /// <exclude /> IData GetParent(IData data); } } ================================================ FILE: Composite/Data/IBuildNewHandler.cs ================================================ using System; using System.CodeDom; namespace Composite.Data { /// <summary> /// This interface is used togehter with the attribute <see cref="BuildNewHandlerAttribute"/>. /// It is possible to overwrite the default behavior when a new data item is created through the method <see cref="DataConnection.New"/> /// To do this, you have to implement this interface and attach it to your <see cref="IData"/> type by using the attribute <see cref="BuildNewHandlerAttribute"/> /// <example> /// <code> /// [BuildNewHandlerAttribute(typeof(MyBuildNewHandler)) /// [AutoUpdateble] /// [KeyPropertyName("Id")] /// [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] /// [ImmutableTypeId("{10D6CA29-5B01-45EE-9405-9B027F4C949C}")] /// interface IMyDataType : IData /// { /// [StoreFieldType(PhysicalStoreFieldType.Guid)] /// [ImmutableFieldId("{B99F4AF2-859D-4235-887B-E5A06BBB9892}")] /// Guid Id { get; set; } /// /// [StoreFieldType(PhysicalStoreFieldType.String, 256)] /// [ImmutableFieldId("{A8127C77-5083-4409-9EA6-1E3BB696310D}")] /// string Name { get; set; } /// } /// /// class MyBuildNewHandler : IBuildNewHandler /// { /// public Type GetTypeToBuild(Type dataType) /// { /// /* dataType will always be typeof(IMyDataType) */ /// /// return typeof(MyDataType); /// } /// } /// /// /// class MyDataType : IMyDataType /// { /// puglic MyDataType() /// { /// /* All new instances of IMyDataType will becrated through this constructor */ /// this.Id = Guid.NewGuid(); /// this.Name = "RandomName"; /// } /// /// public Id { get; set; } /// /// public Name { get; set; } /// } /// </code> /// </example> /// </summary> public interface IBuildNewHandler { /// <summary> /// The method should return a type with parameterless constructor that will be used to create a new <see cref="IData"/> instance. /// The returned type is used by C1 to construct a new object when <see cref="DataConnection.New"/> is called. /// </summary> /// <param name="dataType"> /// The data interface type in question. This interface type is inheriting <see cref="IData"/>. /// And the interface type is also decorated with the attribute <see cref="BuildNewHandlerAttribute"/>. /// </param> /// <returns>Should return a type that will be used to create an object that implements the given <paramref name="dataType"/> interface.</returns> Type GetTypeToBuild(Type dataType); } } ================================================ FILE: Composite/Data/IChangeHistory.cs ================================================ using System; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IChangeHistory: IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.DateTime)] [ImmutableFieldId("{59E10FE8-EC55-4b10-B17A-FDE3EB4690F0}")] [DefaultFieldNowDateTimeValue] [FieldPosition(502)] [SearchableField(false, true, true)] DateTime ChangeDate { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 64, IsNullable = true)] [ImmutableFieldId("{617E34B5-E035-4107-9109-DB0B33078B2A}")] [DefaultFieldStringValue("")] [FieldPosition(503)] [SearchableField(false, true, true)] string ChangedBy { get; set; } } } ================================================ FILE: Composite/Data/ICreationHistory.cs ================================================ using System; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface ICreationHistory: IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.DateTime)] [ImmutableFieldId("{59E10FE8-EC55-4b10-B17A-FDE3EB4690F1}")] [DefaultFieldNowDateTimeValue()] [FunctionBasedNewInstanceDefaultFieldValue("<f:function xmlns:f=\"http://www.composite.net/ns/function/1.0\" name=\"Composite.Utils.Date.Now\" />")] [FieldPosition(502)] DateTime CreationDate { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 64, IsNullable = true)] [ImmutableFieldId("{617E34B5-E035-4107-9109-DB0B33078B2B}")] [DefaultFieldStringValue("")] [FieldPosition(503)] string CreatedBy { get; set; } } } ================================================ FILE: Composite/Data/IData.cs ================================================ using Composite.Core.Serialization; namespace Composite.Data { /// <summary> /// Base interface for data types in C1 CMS. /// </summary> [SerializerHandler(typeof(DataSerializerHandler))] public interface IData { /// <summary> /// Uniquely identify this data element, its type and what provider it came from. /// </summary> DataSourceId DataSourceId { get; } } } ================================================ FILE: Composite/Data/IDataExtensions.cs ================================================ using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.Data.DynamicTypes; using Composite.Data.DynamicTypes.Foundation; using Composite.Data.Hierarchy; using Composite.Core.Types; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class IDataExtensions { private static ConcurrentDictionary<Type, IReadOnlyCollection<DataScopeIdentifier>> _supportedDataScopes = new ConcurrentDictionary<Type, IReadOnlyCollection<DataScopeIdentifier>>(); private static MethodInfo ToDataReferenceMethodInfo = StaticReflection.GetGenericMethodInfo(() => ToDataReference<IData>(null)); /// <summary> /// Copies all changed properties from sourceData to targetData. /// </summary> /// <param name="sourceData"></param> /// <param name="targetData"></param> public static void FullCopyChangedTo(this IData sourceData, IData targetData) { FullCopyChangedTo(sourceData, targetData, null); } /// <summary> /// Copies all changed properties from sourceData to targetData. /// </summary> /// <param name="sourceData"></param> /// <param name="targetData"></param> /// <param name="propertyNamesToIgnore"></param> public static void FullCopyChangedTo(this IData sourceData, IData targetData, IEnumerable<string> propertyNamesToIgnore) { foreach (PropertyInfo targetPropertyInfo in targetData.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (targetPropertyInfo.Name == "DataSourceId") continue; if ((propertyNamesToIgnore != null) && (propertyNamesToIgnore.Contains(targetPropertyInfo.Name))) continue; if (targetPropertyInfo.CanWrite) { PropertyInfo sourcePropertyInfo = sourceData.GetType().GetProperty(targetPropertyInfo.Name, BindingFlags.Public | BindingFlags.Instance); if (sourcePropertyInfo == null) throw new InvalidOperationException(string.Format("Missing source property '{0}' on the data type '{1}'", targetPropertyInfo.Name, sourceData.DataSourceId.InterfaceType)); object newValue = sourcePropertyInfo.GetValue(sourceData, null); object oldValue = targetPropertyInfo.GetValue(targetData, null); if (Equals(newValue, oldValue) == false) { targetPropertyInfo.SetValue(targetData, newValue, null); } } } } /// <summary> /// Copies all properties that exists on the targetData from the sourceData except the DataSourceId /// If the targetData has a property that does not exist on the sourceData, the default value is used. /// </summary> /// <param name="sourceData"></param> /// <param name="targetData"></param> public static void ProjectedCopyTo(this IData sourceData, IData targetData) { ProjectedCopyTo(sourceData, targetData, true); } /// <summary> /// Copies all properties that exists on the targetData from the sourceData except the DataSourceId /// </summary> /// <param name="sourceData"></param> /// <param name="targetData"></param> /// <param name="useDefaultValues"></param> public static void ProjectedCopyTo(this IData sourceData, IData targetData, bool useDefaultValues) { foreach (PropertyInfo targetPropertyInfo in targetData.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (targetPropertyInfo.Name == "DataSourceId") continue; if (targetPropertyInfo.CanWrite) { PropertyInfo sourcePropertyInfo = sourceData.GetType().GetProperty(targetPropertyInfo.Name, BindingFlags.Public | BindingFlags.Instance); if (sourcePropertyInfo != null) { object value = sourcePropertyInfo.GetValue(sourceData, null); targetPropertyInfo.SetValue(targetData, value, null); } else if (useDefaultValues) { object oldValue = targetPropertyInfo.GetValue(targetData, null); if (oldValue == null) { DefaultValue defaultValue = DynamicTypeReflectionFacade.GetDefaultValue(targetPropertyInfo); if (defaultValue != null) { targetPropertyInfo.SetValue(targetData, defaultValue.Value, null); } else { // Do something here ?? /MRJ } } } } } } /// <summary> /// Compares the value of the key properties of leftData and rightData /// and if all the values are equals then it returns true. Otherwise false. /// </summary> /// <param name="leftData"></param> /// <param name="rightData"></param> /// <returns></returns> internal static bool KeyEquals(this IData leftData, IData rightData) { Verify.ArgumentNotNull(leftData, "leftData"); Verify.ArgumentNotNull(rightData, "rightData"); if (leftData.DataSourceId.InterfaceType != rightData.DataSourceId.InterfaceType) return false; foreach (PropertyInfo propertyInfo in DataAttributeFacade.GetKeyProperties(leftData.DataSourceId.InterfaceType)) { object leftValue = propertyInfo.GetValue(leftData, null); object rightValue = propertyInfo.GetValue(rightData, null); if (!leftValue.Equals(rightValue)) return false; } return true; } /// <summary> /// This returns an enumerable where no two data elements has the same key value. /// </summary> /// <param name="datas"></param> /// <returns></returns> internal static List<IData> KeyDistinct(this IEnumerable<IData> datas) { var result = new List<IData>(); foreach (IData data in datas) { if (!result.Any(f => f.KeyEquals(data))) { result.Add(data); } } return result; } /// <summary> /// Returns the data item's key field's value. If the key is compound, an exeption will be thrown. /// </summary> /// <param name="data"></param> /// <returns></returns> /// <exclude /> // Made public for Base site in App_Code/Composite/BasicSearch.cs [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static object GetUniqueKey(this IData data) { Verify.ArgumentNotNull(data, "data"); return data.DataSourceId.InterfaceType.GetSingleKeyProperty().GetValue(data, null); } /// <summary> /// Returns the data item's key field's value. If the key is compound, an exception will be thrown. /// </summary> /// <param name="data"></param> /// <returns></returns> public static T GetUniqueKey<T>(this IData data) { Verify.ArgumentNotNull(data, "data"); return (T)data.GetUniqueKey(); } /// <summary> /// Converts a data item into a data reference /// </summary> /// <param name="data">The data item</param> /// <returns></returns> public static IDataReference ToDataReference(this IData data) { Verify.ArgumentNotNull(data, "data"); var interfaceType = data.DataSourceId.InterfaceType; return (IDataReference) ToDataReferenceMethodInfo .MakeGenericMethod(new[] {interfaceType}).Invoke(null, new object[] {data}); } /// <summary> /// Converts a data item into a data reference /// </summary> /// <param name="data">The data item</param> /// <returns></returns> public static DataReference<T> ToDataReference<T>(T data) where T : class, IData { return new DataReference<T>(data); } /// <summary> /// Returns true if the child has ancestor as one of its ancestors /// </summary> /// <param name="child"></param> /// <param name="parent"></param> /// <returns></returns> internal static bool HasAncestor(this IData child, IData parent) { return HasAncestor(child, parent, int.MaxValue); } /// <summary> /// Returns true if the child has ancestor as one of its ancestors /// in max maxLevels ancestors /// </summary> /// <param name="child"></param> /// <param name="parent"></param> /// <param name="maxLevels"></param> /// <returns></returns> internal static bool HasAncestor(this IData child, IData parent, int maxLevels) { Verify.ArgumentNotNull(child, "child"); Verify.ArgumentNotNull(parent, "parent"); if (maxLevels < 0) return false; if (child.KeyEquals(parent)) { return true; } IData childParent = child.GetParent(); if (childParent == null) return false; return HasAncestor(childParent, parent, maxLevels - 1); } internal static IReadOnlyCollection<DataScopeIdentifier> GetSupportedDataScopes(this Type interfaceType) { Verify.ArgumentNotNull(interfaceType, "interfaceType"); if (!typeof(IData).IsAssignableFrom(interfaceType)) throw new ArgumentException(string.Format("The specified type must inherit from '{0}'", typeof(IData)), "interfaceType"); return _supportedDataScopes.GetOrAdd(interfaceType, GetSupportedDataScopesInt); } private static IReadOnlyCollection<DataScopeIdentifier> GetSupportedDataScopesInt(Type interfaceType) { IEnumerable<DataScopeAttribute> attributes = interfaceType.GetCustomInterfaceAttributes<DataScopeAttribute>(); return attributes.Select(attribute => attribute.Identifier).Distinct().ToList(); } /// <summary> /// </summary> /// <exclude /> // Made public for Base site in App_Code/Composite/BasicSearch.cs [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static List<IData> ToDataList(this IQueryable queryable) { Verify.ArgumentNotNull(queryable, "queryable"); return Enumerable.Cast<IData>(queryable).ToList(); } /// <exclude /> public static IEnumerable<IData> ToDataEnumerable(this IQueryable queryable) { Verify.ArgumentNotNull(queryable, "queryable"); return Enumerable.Cast<IData>(queryable); } internal static IEnumerable ToCastedDataEnumerable(this IEnumerable<IData> datas, Type interfaceType) { MethodInfo methodInfo = typeof(Enumerable).GetMethods().Single(f => f.Name == "Cast"); methodInfo = methodInfo.MakeGenericMethod(interfaceType); return (IEnumerable)methodInfo.Invoke(null, new object[] { datas }); } internal static IDictionary<string, List<T>> ToDataProviderSortedDictionary<T>(this IEnumerable<T> datas) where T : class, IData { if (datas == null) throw new ArgumentNullException("datas"); var result = new Dictionary<string, List<T>>(); foreach (T data in datas) { List<T> dataList; if (result.TryGetValue(data.DataSourceId.ProviderName, out dataList) == false) { dataList = new List<T>(); result.Add(data.DataSourceId.ProviderName, dataList); } dataList.Add(data); } return result; } internal static Dictionary<string, Dictionary<Type, List<IData>>> ToDataProviderAndInterfaceTypeSortedDictionary<T>(this IEnumerable<T> datas) where T : class, IData { if (datas == null) throw new ArgumentNullException("datas"); var result = new Dictionary<string, Dictionary<Type, List<IData>>>(); foreach (IData data in datas) { Dictionary<Type, List<IData>> dictionary; if (!result.TryGetValue(data.DataSourceId.ProviderName, out dictionary)) { dictionary = new Dictionary<Type, List<IData>>(); result.Add(data.DataSourceId.ProviderName, dictionary); } List<IData> dataList; if (!dictionary.TryGetValue(data.DataSourceId.InterfaceType, out dataList)) { dataList = new List<IData>(); dictionary.Add(data.DataSourceId.InterfaceType, dataList); } dataList.Add(data); } return result; } /// <exclude /> [Obsolete("Use GetDataPropertyRecursively instead")] public static PropertyInfo GetDataPropertyRecursivly(this Type dataType, string propertyName) { return GetDataPropertyRecursively(dataType, propertyName); } /// <exclude /> public static PropertyInfo GetDataPropertyRecursively(this Type dataType, string propertyName) { Verify.ArgumentNotNull(dataType, "dataType"); PropertyInfo propertyInfo = dataType.GetProperty(propertyName); if (propertyInfo != null) return propertyInfo; foreach (Type superInterface in dataType.GetInterfaces()) { if (superInterface != typeof(IData) && typeof(IData).IsAssignableFrom(superInterface)) { PropertyInfo propInfo = superInterface.GetDataPropertyRecursivly(propertyName); if (propInfo != null) { return propInfo; } } } return null; } internal static List<PropertyInfo> GetAllProperties(this Type dataType) { Verify.ArgumentNotNull(dataType, "dataType"); var result = new List<PropertyInfo>(); result.AddRange(dataType.GetProperties()); foreach (Type superInterface in dataType.GetInterfacesRecursively()) { if (superInterface != typeof(IData) && typeof(IData).IsAssignableFrom(superInterface)) { result.AddRange(superInterface.GetProperties()); } } // A compatibility fix, returning the same "PageId" property twice usually leads to an error if (typeof(IPageData).IsAssignableFrom(dataType)) { result.RemoveAll(p => p.Name == "PageId" && p.DeclaringType == typeof(IPageData)); } return result; } /// <exclude /> public static void SetValues(this IData data, Dictionary<string, string> values) { Verify.ArgumentNotNull(data, "data"); Verify.ArgumentNotNull(values, "values"); List<PropertyInfo> properties = data.DataSourceId.InterfaceType.GetPropertiesRecursively(); foreach (var kvp in values) { PropertyInfo propertyInfo = properties.Single(f => f.Name == kvp.Key); object convertedValue = ValueTypeConverter.Convert(kvp.Value, propertyInfo.PropertyType); propertyInfo.SetValue(data, convertedValue, null); } } } } ================================================ FILE: Composite/Data/IDataFacade.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Composite.Data.Types; namespace Composite.Data { internal interface IDataFacade { void SetDataInterceptor<T>(DataInterceptor dataInterceptor) where T : class, IData; bool HasDataInterceptor<T>() where T : class, IData; void ClearDataInterceptor<T>() where T : class, IData; IEnumerable<DataInterceptor> GetDataInterceptors(Type interfaceType); IQueryable<T> GetData<T>(bool useCaching, IEnumerable<string> providerNames) where T : class, IData; T GetDataFromDataSourceId<T>(DataSourceId dataSourceId, bool useCaching) where T : class, IData; void Update(IEnumerable<IData> datas, bool suppressEventing, bool performForeignKeyIntegrityCheck, bool performeValidation); /// <summary> /// This method will add the given data. /// This method will also create a store if no data provider supports the given data interface T /// and allowStoreCreation is true. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="datas"></param> /// <param name="allowStoreCreation"></param> /// <param name="suppressEventing"></param> /// <param name="performForeignKeyIntegrityCheck"></param> /// <param name="performeValidation"></param> /// <param name="writeableProviders">null is allowed</param> /// <returns></returns> List<T> AddNew<T>(IEnumerable<T> datas, bool allowStoreCreation, bool suppressEventing, bool performForeignKeyIntegrityCheck, bool performeValidation, List<string> writeableProviders) where T : class, IData; void Delete<T>(IEnumerable<T> datas, bool suppressEventing, CascadeDeleteType cascadeDeleteType, bool referencesFromAllScopes) where T : class, IData; T BuildNew<T>(bool suppressEventing) where T : class, IData; IData BuildNew(Type interfaceType, bool suppressEventling); bool ExistsInAnyLocale<T>(IEnumerable<CultureInfo> excludedCultureInfoes) where T : class, IData; /// <summary> /// See <see cref="Composite.Data.Plugins.DataProvider.IFileSystemDataProvider"/> /// </summary> /// <typeparam name="TFile"></typeparam> /// <param name="file"></param> /// <param name="providerName"></param> /// <param name="errorMessage"></param> /// <returns></returns> bool ValidatePath<TFile>(TFile file, string providerName, out string errorMessage) where TFile : IFile; void SetGlobalDataInterceptor<T>(DataInterceptor dataInterceptor) where T : class, IData; bool HasGlobalDataInterceptor<T>() where T : class, IData; void ClearGlobalDataInterceptor<T>() where T : class, IData; } } ================================================ FILE: Composite/Data/IDataId.cs ================================================ namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IDataId { } } ================================================ FILE: Composite/Data/IDataIdExtensions.cs ================================================ using System.Reflection; using System; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class IDataIdExtensions { /// <exclude /> public static void FullCopyTo(this IDataId sourceDataId, IDataId targetDataId) { if (sourceDataId == null) throw new ArgumentNullException("sourceDataId"); if (targetDataId == null) throw new ArgumentNullException("targetDataId"); foreach (PropertyInfo sourcePropertyInfo in sourceDataId.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { PropertyInfo targetPropertyInfo = targetDataId.GetType().GetProperty(sourcePropertyInfo.Name, BindingFlags.Public | BindingFlags.Instance); object value = sourcePropertyInfo.GetValue(sourceDataId, null); targetPropertyInfo.SetValue(targetDataId, value, null); } } /// <exclude /> public static bool CompareTo(this IDataId sourceDataId, IDataId targetDataId) { return CompareTo(sourceDataId, targetDataId, false); } /// <exclude /> public static bool CompareTo(this IDataId sourceDataId, IDataId targetDataId, bool throwExceptionOnTypeMismathc) { if (sourceDataId == null) throw new ArgumentNullException("sourceDataId"); if (targetDataId == null) throw new ArgumentNullException("targetDataId"); if (sourceDataId.GetType() != targetDataId.GetType()) { if (throwExceptionOnTypeMismathc) throw new ArgumentException(string.Format("Type mismatch {0} and {1}", sourceDataId.GetType(), targetDataId.GetType())); return false; } bool equal = true; foreach (PropertyInfo sourcePropertyInfo in sourceDataId.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { PropertyInfo targetPropertyInfo = targetDataId.GetType().GetProperty(sourcePropertyInfo.Name, BindingFlags.Public | BindingFlags.Instance); object sourceValue = sourcePropertyInfo.GetValue(sourceDataId, null); object targetValue = targetPropertyInfo.GetValue(targetDataId, null); if (object.Equals(sourceValue, targetValue) == false) { equal = false; break; } } return equal; } } } ================================================ FILE: Composite/Data/IDataIdKeyFacade.cs ================================================ using System; namespace Composite.Data { internal interface IDataIdKeyFacade { object GetKeyValue(IDataId dataId, string keyName); string GetDefaultKeyName(Type dataIdType); void OnFlush(); } } ================================================ FILE: Composite/Data/IDataLocalizationFacade.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using Composite.Data.ProcessControlled; namespace Composite.Data { internal interface IDataLocalizationFacade { /// <summary> /// This method return true if the system should use localization functionallity. /// In ohter words, if there are two or more languages added then localization functionallity /// should be used. /// </summary> bool UseLocalization { get; } IEnumerable<CultureInfo> WhiteListedLocales { get; } CultureInfo DefaultLocalizationCulture { get; set; } CultureInfo DefaultUrlMappingCulture { get; } IEnumerable<string> ActiveLocalizationNames { get; } string GetUrlMappingName(CultureInfo cultureInfo); CultureInfo GetCultureInfoByUrlMappingName(string urlMappingName); IEnumerable<string> UrlMappingNames { get; } bool IsLocalized(Type type); bool IsLocalizable(Type type); IEnumerable<ReferenceFailingPropertyInfo> GetReferencingLocalizeFailingProperties(ILocalizedControlled data); string GetCultureTitle(CultureInfo culture); } } ================================================ FILE: Composite/Data/IDataReference.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Composite.Data { /// <summary> /// Represents a reference to a C1 CMS IData item. See <see cref="DataReference{T}"/>. /// </summary> public interface IDataReference { /// <summary> /// The type of the data item. This type inherits from IData. /// </summary> Type ReferencedType { get; } /// <summary> /// If the reference has not been set this is false. /// </summary> bool IsSet { get; } /// <summary> /// The key value of the data item being referenced, like the Guid for a page id. /// </summary> object KeyValue { get; } /// <summary> /// The data item being referenced. /// </summary> IData Data { get; } /// <exclude /> string Serialize(); } } ================================================ FILE: Composite/Data/IDataWrapper.cs ================================================ namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IDataWrapper { /// <exclude /> IData WrappedData { get; } /// <exclude /> void CommitData(); } } ================================================ FILE: Composite/Data/IPageData.cs ================================================ using System; using Composite.Core.Serialization; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [SerializerHandler(typeof(DataSerializerHandler))] [KeyPropertyName("Id")] public interface IPageData : IPageRelatedData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{F6DF85E4-C577-49E5-ACD9-8BE8958736D6}")] Guid Id { get; set; } /// <exclude /> new Guid PageId { get; set; } // Field is left in this interface for backward compatibility } /// <exclude /> public interface IPageRelatedData : IData { /// <exclude /> [ForeignKey(typeof(Composite.Data.Types.IPage), "Id", AllowCascadeDeletes = true)] [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{F641EC01-75BB-49EC-B02A-969D6BE59A5F}")] Guid PageId { get; set; } } } ================================================ FILE: Composite/Data/IPageFolderData.cs ================================================  using System; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [Obsolete("Use IPageDataFolder instead and remember to define key fields")] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IPageFolderData : IPageDataFolder, IPageData { } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DataAssociationAttribute(typeof(Composite.Data.Types.IPage), "PageId", DataAssociationType.Aggregation)] public interface IPageDataFolder : IPageRelatedData { } } ================================================ FILE: Composite/Data/IPageMetaData.cs ================================================ using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.ProcessControlled; using Composite.Data.Types; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DataScope(DataScopeIdentifier.PublicName)] [DataScope(DataScopeIdentifier.AdministratedName)] [PublishProcessControllerType(typeof(GenericPublishProcessController))] [DataAssociationAttribute(typeof(Composite.Data.Types.IPage), "PageId", DataAssociationType.Composition)] public interface IPageMetaData : IPageData, IPublishControlled, IVersioned { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 128)] [ImmutableFieldId("{B2A5EE23-848D-4D0B-A801-FDF68F9F899E}")] string FieldName { get; set; } } } ================================================ FILE: Composite/Data/ImmutableFieldIdAttribute.cs ================================================ using System; namespace Composite.Data { /// <summary> /// Assigns an immutable id to this property. The id must be unique and is used to identify the property even if /// the name should change. The Dynamic Type system uses this value to detect data schema changes. /// </summary> /// <example> This sample shows how to use the ImmutableFieldId attribute: /// <code> /// // (IData attributes) /// interface IMyDataType : IData /// { /// [ImmutableFieldId("b3bada55-0e7e-4195-86e6-92770c381df4")] /// string Title { get; set; } /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class ImmutableFieldIdAttribute : Attribute { /// <summary> /// Specify the immutable id of this data type. This value must be unique among types and should not change. /// </summary> /// <param name="immutableFieldId">Unique GUID string</param> public ImmutableFieldIdAttribute(string immutableFieldId) { this.ImmutableFieldId = new Guid(immutableFieldId); } /// <exclude /> public Guid ImmutableFieldId { get; set; } } } ================================================ FILE: Composite/Data/ImmutableTypeIdAttribute.cs ================================================ using System; namespace Composite.Data { /// <summary> /// Assigns an immutable id to this type. The id must be unique and is used to identify the type even if /// the type name, namespace or version should change. The Dynamic Type system uses this value to detect data schema changes. /// </summary> /// <example> This sample shows how to use the ImmutableTypeId attribute: /// <code> /// [ImmutableTypeId("b3bada55-0e7e-4195-86e6-92770c381df3")] /// // (other IData attributes) /// interface IMyDataType : IData /// { /// // data type properties /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = true)] public class ImmutableTypeIdAttribute : Attribute { /// <summary> /// Specify the immutable id of this data type. This value must be unique among types and should not change. /// </summary> /// <param name="immutableTypeId">Unique GUID string</param> public ImmutableTypeIdAttribute(string immutableTypeId) { this.ImmutableTypeId = new Guid(immutableTypeId); } /// <exclude /> public Guid ImmutableTypeId { get; set; } } } ================================================ FILE: Composite/Data/IndexAttribute.cs ================================================ using System; using System.Collections.Generic; namespace Composite.Data { /// <summary> /// Add this attribute to define an additional index to a tables representing the data type. /// </summary> /// <example> This sample shows how to use the KeyPropertyName attribute: /// <code> /// [KeyPropertyName("Id")] /// [Index("FolderName", IndexDirection.Ascending, "FileName", IndexDirection.Descending)] /// interface IMyDataType : IData /// { /// Guid Id { get; set; } /// string FolderName { get; set; } /// string FileName { get; set; } /// /// // other data type properties /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = true, Inherited = true)] public sealed class IndexAttribute: Attribute { private readonly IReadOnlyCollection<Tuple<string, IndexDirection>> _fields; /// <exclude /> public IndexAttribute(string fieldName, IndexDirection indexDirection) { _fields = new List<Tuple<string, IndexDirection>> { new Tuple<string, IndexDirection>(fieldName, indexDirection) }; } /// <exclude /> public IndexAttribute(string field1Name, IndexDirection indexDirection1, string field2Name, IndexDirection indexDirection2) { _fields = new List<Tuple<string, IndexDirection>> { new Tuple<string, IndexDirection>(field1Name, indexDirection1), new Tuple<string, IndexDirection>(field2Name, indexDirection2) }; } /// <exclude /> public IndexAttribute(string field1Name, IndexDirection indexDirection1, string field2Name, IndexDirection indexDirection2, string field3Name, IndexDirection indexDirection3) { _fields = new List<Tuple<string, IndexDirection>> { new Tuple<string, IndexDirection>(field1Name, indexDirection1), new Tuple<string, IndexDirection>(field2Name, indexDirection2), new Tuple<string, IndexDirection>(field3Name, indexDirection3) }; } /// <exclude /> public IndexAttribute(string field1Name, IndexDirection indexDirection1, string field2Name, IndexDirection indexDirection2, string field3Name, IndexDirection indexDirection3, string field4Name, IndexDirection indexDirection4) { _fields = new List<Tuple<string, IndexDirection>> { new Tuple<string, IndexDirection>(field1Name, indexDirection1), new Tuple<string, IndexDirection>(field2Name, indexDirection2), new Tuple<string, IndexDirection>(field3Name, indexDirection3), new Tuple<string, IndexDirection>(field4Name, indexDirection4) }; } /// <exclude /> public IndexAttribute(string field1Name, IndexDirection indexDirection1, string field2Name, IndexDirection indexDirection2, string field3Name, IndexDirection indexDirection3, string field4Name, IndexDirection indexDirection4, string field5Name, IndexDirection indexDirection5) { _fields = new List<Tuple<string, IndexDirection>> { new Tuple<string, IndexDirection>(field1Name, indexDirection1), new Tuple<string, IndexDirection>(field2Name, indexDirection2), new Tuple<string, IndexDirection>(field3Name, indexDirection3), new Tuple<string, IndexDirection>(field4Name, indexDirection4), new Tuple<string, IndexDirection>(field5Name, indexDirection5) }; } /// <summary> /// Gets the list of fields /// </summary> public IReadOnlyCollection<Tuple<string, IndexDirection>> Fields { get { return _fields; } } /// <summary> /// Defines whether current index is clustered. Only one index per data type can be choosen as clustered. /// </summary> public bool Clustered { get; set; } } } ================================================ FILE: Composite/Data/IndexDirection.cs ================================================ namespace Composite.Data { /// <summary> /// Index direction /// </summary> public enum IndexDirection { /// <summary> /// Arranged from smallest to largest. /// </summary> Ascending = 0, /// <summary> /// Arranged from largest to smallest. /// </summary> Descending = 1 } } ================================================ FILE: Composite/Data/InternalUrlAttribute.cs ================================================ using System; namespace Composite.Data { /// <summary> /// When specified, defines a short type name for generating internal urls. /// F.e.: [InternalUrl("news")] for "~/news(id)" internal links. /// </summary> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = false)] public class InternalUrlAttribute : Attribute { /// <summary> /// Specify a short type name, to be used in internal urls. /// </summary> /// <param name="internalUrlPrefix">The internal url prefix.</param> public InternalUrlAttribute(string internalUrlPrefix) { Verify.ArgumentNotNullOrEmpty(internalUrlPrefix, "InternalUrlPrefix"); InternalUrlPrefix = internalUrlPrefix; } /// <exclude /> public string InternalUrlPrefix { get; set; } } } ================================================ FILE: Composite/Data/KeyPropertyNameAttribute.cs ================================================ using System; namespace Composite.Data { /// <summary> /// Add this attribute to your data interface to specify one or more primary key fields. /// </summary> /// <example> This sample shows how to use the KeyPropertyName attribute: /// <code> /// [KeyPropertyName("Id")] /// // (other IData attributes) /// interface IMyDataType : IData /// { /// Guid Id { get; set; } /// /// // other data type properties /// } /// </code> /// /// This example shows how to specify a compound key. : /// <code> /// [KeyPropertyName(0, "FolderName")] /// [KeyPropertyName(1, "FileName")] /// // (other IData attributes) /// interface IMyDataType : IData /// { /// string FolderName { get; set; } /// string FileName { get; set; } /// /// // other data type properties /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = true, Inherited = true)] public sealed class KeyPropertyNameAttribute : Attribute { /// <summary> /// Specify the name of a data property to be used as primary key. /// </summary> /// <param name="compoundKeyIndex">The index of the field in a multi part key.</param> /// <param name="propertyName">Name of data property</param> public KeyPropertyNameAttribute(int compoundKeyIndex, string propertyName) { Index = compoundKeyIndex; KeyPropertyName = propertyName; } /// <summary> /// Specify the name of a data property to be used as primary key. /// </summary> /// <param name="propertyName">Name of data property</param> public KeyPropertyNameAttribute(string propertyName) { this.KeyPropertyName = propertyName; } /// <summary> /// Gets the name of the key property. /// </summary> /// <value> /// The name of the key property. /// </value> /// <exclude /> public string KeyPropertyName { get; private set; } /// <summary> /// An index of the field in a multi part primary key. /// </summary> public int Index { get; private set; } // TODO: implement support for sort order ///// <summary> ///// A sort order for indexing. ///// </summary> //public SortOrder SortOrder { get; set; } } } ================================================ FILE: Composite/Data/LabelPropertyNameAttribute.cs ================================================ using System; namespace Composite.Data { /// <summary> /// Add this attribute to your data interface to select what property should be used as label when enumerating data. /// </summary> /// <example> This sample shows how to use the LabelPropertyName attribute. /// <code> /// [LabelPropertyName("Title")] /// // (other IData attributes) /// interface IMyDataType : IData /// { /// string Title { get; set; } /// /// // other data type properties /// } /// </code> /// </example> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = true)] public sealed class LabelPropertyNameAttribute : Attribute { /// <exclude /> public LabelPropertyNameAttribute(string propertyName) { this.PropertyName = propertyName; } /// <exclude /> public string PropertyName { get; private set; } } } ================================================ FILE: Composite/Data/LocalizationScopeManager.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using Composite.Core.Caching; using System.Runtime.Remoting.Messaging; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class LocalizationScopeManager { /// <exclude /> public static CultureInfo CurrentLocalizationScope { get { var stack = LocalizationScopeStack; if (stack.Count != 0) { return stack.Peek(); } return CultureInfo.InvariantCulture; } } /// <exclude /> public static CultureInfo MapByType(Type type) { if (DataLocalizationFacade.IsLocalized(type)) { return CurrentLocalizationScope; } return CultureInfo.InvariantCulture; } internal static void PushLocalizationScope(CultureInfo cultureInfo) { LocalizationScopeStack.Push(cultureInfo); } internal static void PopLocalizationScope() { var stack = LocalizationScopeStack; if (stack.Count > 0) { stack.Pop(); } } internal static bool IsEmpty { get { return (LocalizationScopeStack.Count == 0); } } private const string _threadLocalCacheKey = "LocalizationScopeManager:ThreadLocal"; /// <summary> /// Move the stack handling scope to a thread local store, enabling simultaneous threads to mutate (their own) scope. This will be in effect untill the thread has completed. /// </summary> public static void EnterThreadLocal() { if( CallContext.GetData(_threadLocalCacheKey) == null) { var threadLocalStack = new Stack<CultureInfo>(LocalizationScopeStack); CallContext.SetData( _threadLocalCacheKey, threadLocalStack ); } } /// <summary> /// Move the stack handling to request scope. /// </summary> public static void ExitThreadLocal() { if (CallContext.GetData(_threadLocalCacheKey) != null) { CallContext.SetData(_threadLocalCacheKey, null); } } private static Stack<CultureInfo> LocalizationScopeStack { get { var threadLocalStack = CallContext.GetData(_threadLocalCacheKey) as Stack<CultureInfo>; if (threadLocalStack != null) { return threadLocalStack; } return RequestLifetimeCache.GetCachedOrNew<Stack<CultureInfo>>("LocalizationScopeManager:Stack"); } } } } ================================================ FILE: Composite/Data/NewInstanceDefaultFieldValueAttribute.cs ================================================ using System; using System.Xml.Linq; using Composite.Functions; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public abstract class NewInstanceDefaultFieldValueAttribute : Attribute { /// <exclude /> public abstract bool HasValue { get; } /// <exclude /> public abstract object GetValue(); } /// <summary> /// Assign this attribute to a data type property to enforce a default value for the property on newly created instanced of your data type. /// You specify a serialized C1 Function - this C1 Function will be executed and the result will be written to this property. /// </summary> /// <example> This sample shows how to use the FunctionBasedNewInstanceDefaultFieldValue attribute. /// Here the current date and time is set on the Created property through the use of the C1 Function Composite.Utils.Date.Now. /// <code> /// // data interface attributes ... /// interface IMyDataType : IData /// { /// [FunctionBasedNewInstanceDefaultFieldValue(@"<f:function name='Composite.Utils.Date.Now' xmlns:f='http://www.composite.net/ns/function/1.0' />")] /// [StoreFieldType(PhysicalStoreFieldType.DateTime)] /// [ImmutableFieldId("{D75EA67F-AD14-4BAB-8547-6D87002809F1}")] /// DateTime Created { get; set; } /// /// // more data properties ... /// /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class FunctionBasedNewInstanceDefaultFieldValueAttribute : NewInstanceDefaultFieldValueAttribute { /// <summary> /// Specify a C1 Function call that will provide a default value for this field. The function call is expressed as XML. /// Example: <f:function name='Composite.Utils.Date.Now' xmlns:f='http://www.composite.net/ns/function/1.0' /> /// </summary> /// <param name="functionDescription">Serialized C1 Function call</param> public FunctionBasedNewInstanceDefaultFieldValueAttribute(string functionDescription) { this.FunctionDescription = functionDescription; } /// <exclude /> public string FunctionDescription { get; private set; } /// <exclude /> public override bool HasValue { get { return (string.IsNullOrEmpty(this.FunctionDescription) == false); } } /// <summary> /// Execute the C1 Function defined for this attribute and return the result. /// </summary> /// <returns>Result of C1 Function call</returns> public override object GetValue() { BaseRuntimeTreeNode node = FunctionFacade.BuildTree(XElement.Parse(this.FunctionDescription)); return node.GetValue(); } } } ================================================ FILE: Composite/Data/NotReferenceable.cs ================================================ using System; namespace Composite.Data { /// <summary> /// Add this attribute to your data interface to prevent it from being referenced by other data types /// </summary> /// <example> This sample shows how to use the NotReferenceable attribute. /// <code> /// [NotReferenceable()] /// // (other IData attributes) /// interface IMyDataType : IData /// { /// // data type properties /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = true)] public sealed class NotReferenceableAttribute : Attribute { } } ================================================ FILE: Composite/Data/PageDataConnection.cs ================================================ using System; using System.Globalization; using System.Linq; using Composite.Core.Implementation; namespace Composite.Data { ///// <summary> ///// </summary> ///// <exclude /> //[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] //public class PageDataConnection : ImplementationContainer<PageDataConnectionImplementation>, IDisposable //{ // ImplementationContainer<DataConnection> _dataConnection; // ImplementationContainer<SitemapNavigator> _sitemapNavigator; // public PageDataConnection() // : base(() => ImplementationFactory.CurrentFactory.CreatePageDataConnection(null, null)) // { // _dataConnection = new ImplementationContainer<DataConnection>(() => new DataConnection()); // _sitemapNavigator = new ImplementationContainer<SitemapNavigator>(() => new SitemapNavigator(this.DataConnection)); // } // public PageDataConnection(PublicationScope scope) // : base(() => ImplementationFactory.CurrentFactory.CreatePageDataConnection(scope, null)) // { // if ((scope < PublicationScope.Unpublished) || (scope > PublicationScope.Published)) throw new ArgumentOutOfRangeException("scope"); // _dataConnection = new ImplementationContainer<DataConnection>(() => new DataConnection(scope)); // _sitemapNavigator = new ImplementationContainer<SitemapNavigator>(() => new SitemapNavigator(this.DataConnection)); // } // public PageDataConnection(CultureInfo locale) // : base(() => ImplementationFactory.CurrentFactory.CreatePageDataConnection(null, locale)) // { // _dataConnection = new ImplementationContainer<DataConnection>(() => new DataConnection(locale)); // _sitemapNavigator = new ImplementationContainer<SitemapNavigator>(() => new SitemapNavigator(this.DataConnection)); // } // public PageDataConnection(PublicationScope scope, CultureInfo locale) // : base(() => ImplementationFactory.CurrentFactory.CreatePageDataConnection(scope, locale)) // { // if ((scope < PublicationScope.Unpublished) || (scope > PublicationScope.Published)) throw new ArgumentOutOfRangeException("scope"); // _dataConnection = new ImplementationContainer<DataConnection>(() => new DataConnection(scope, locale)); // _sitemapNavigator = new ImplementationContainer<SitemapNavigator>(() => new SitemapNavigator(this.DataConnection)); // } // public TData GetPageMetaData<TData>(string fieldName) // where TData : IPageMetaData // { // if (string.IsNullOrWhiteSpace(fieldName)) throw new ArgumentNullException("fieldName"); // return this.Implementation.GetPageMetaData<TData>(fieldName); // } // public TData GetPageMetaData<TData>(string fieldName, Guid pageId) // where TData : IPageMetaData // { // if (string.IsNullOrWhiteSpace(fieldName)) throw new ArgumentNullException("fieldName"); // return this.Implementation.GetPageMetaData<TData>(fieldName, pageId); // } // public IQueryable<TData> GetPageMetaData<TData>(string fieldName, SitemapScope scope) // where TData : IPageMetaData // { // if (string.IsNullOrWhiteSpace(fieldName)) throw new ArgumentNullException("fieldName"); // if ((scope < SitemapScope.Current) || (scope > SitemapScope.SiblingsAndSelf)) throw new ArgumentOutOfRangeException("scope"); // return this.Implementation.GetPageMetaData<TData>(fieldName, scope); // } // public IQueryable<TData> GetPageMetaData<TData>(string fieldName, SitemapScope scope, Guid pageId) // where TData : IPageMetaData // { // if (string.IsNullOrWhiteSpace(fieldName)) throw new ArgumentNullException("fieldName"); // if ((scope < SitemapScope.Current) || (scope > SitemapScope.SiblingsAndSelf)) throw new ArgumentOutOfRangeException("scope"); // return this.Implementation.GetPageMetaData<TData>(fieldName, scope, pageId); // } // public IQueryable<TData> GetPageData<TData>() // where TData : IPageData // { // return this.Implementation.GetPageData<TData>(); // } // public IQueryable<TData> GetPageData<TData>(SitemapScope scope) // where TData : IPageData // { // if ((scope < SitemapScope.Current) || (scope > SitemapScope.SiblingsAndSelf)) throw new ArgumentOutOfRangeException("scope"); // return this.Implementation.GetPageData<TData>(scope); // } // public IQueryable<TData> GetPageData<TData>(SitemapScope scope, Guid sourcePageId) // where TData : IPageData // { // if ((scope < SitemapScope.Current) || (scope > SitemapScope.SiblingsAndSelf)) throw new ArgumentOutOfRangeException("scope"); // return this.Implementation.GetPageData<TData>(scope, sourcePageId); // } // public SitemapNavigator SitemapNavigator // { // get // { // return _sitemapNavigator.Implementation; // } // } // public DataConnection DataConnection // { // get // { // return _dataConnection.Implementation; // } // } // public void Dispose() // { // Dispose(true); // GC.SuppressFinalize(this); // } // ~PageDataConnection() // { // Dispose(false); // } // protected virtual void Dispose(bool disposing) // { // if (disposing) // { // if (_dataConnection != null) // { // _dataConnection.DisposeImplementation(); // _sitemapNavigator.DisposeImplementation(); // } // } // } //} } ================================================ FILE: Composite/Data/PageFolderFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Transactions; using Composite.Core.Extensions; using Composite.Data.DynamicTypes; using Composite.Data.Foundation; using Composite.Data.Types; using Composite.Core.Linq; using Composite.Data.Transactions; using Composite.Core.Types; namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PageFolderFacade { private static readonly string PageFolderType_PageIdFieldName = "PageId"; private static readonly string PageFolderType_IdFieldName = "Id"; /// <summary> /// Returns all possible page folder types. This is NOT all types that only have been defined on any pages /// </summary> /// <returns></returns> public static IEnumerable<Type> GetAllFolderTypes() { return DataAssociationRegistry.GetAssociationTypes(typeof(IPage), DataAssociationType.Aggregation); } /// <summary> /// Returns true if the given page has any folder definitions defined on it /// </summary> /// <param name="page"></param> /// <returns></returns> public static bool HasFolderDefinitions(this IPage page) { Verify.ArgumentNotNull(page, nameof(page)); Guid pageId = page.Id; var definitions = DataFacade.GetData<IPageFolderDefinition>(); return definitions.IsEnumerableQuery() ? definitions.AsEnumerable().Any(f => f.PageId == pageId) : definitions.Any(f => f.PageId == pageId); } /// <summary> /// Returns (if any) folder types that are defined on the given page /// </summary> /// <param name="page"></param> /// <returns></returns> public static IEnumerable<Type> GetDefinedFolderTypes(this IPage page) { Verify.ArgumentNotNull(page, nameof(page)); var folderDefinitions = DataFacade.GetData<IPageFolderDefinition>(); IEnumerable<Guid> typeIds; if (folderDefinitions.IsEnumerableQuery()) { typeIds = folderDefinitions .Evaluate() .Where(f => f.PageId == page.Id) .Select(f => f.FolderTypeId); } else { typeIds = folderDefinitions .Where(f => f.PageId == page.Id) .Select(f => f.FolderTypeId) .Evaluate(); } foreach (Guid typeId in typeIds) { var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(typeId); Verify.IsNotNull(dataTypeDescriptor, "Missing a page data folder type with id '{0}', referenced by a IPageFolderDefinition record", typeId); yield return TypeManager.GetType(dataTypeDescriptor.TypeManagerTypeName); } } /// <summary> /// Returns the id of a folder definition given the page and folder type /// </summary> /// <param name="page"></param> /// <param name="folderType"></param> /// <returns></returns> public static Guid GetFolderDefinitionId(this IPage page, Type folderType) { Verify.ArgumentNotNull(page, "page"); return GetFolderDefinitionId(page, folderType.GetImmutableTypeId()); } /// <summary> /// Returns the id (or empty guid if non exists) of a folder definition given the page and folder type id /// </summary> /// <param name="page"></param> /// <param name="folderTypeId"></param> /// <returns></returns> public static Guid GetFolderDefinitionId(this IPage page, Guid folderTypeId) { Verify.ArgumentNotNull(page, "page"); return DataFacade.GetData<IPageFolderDefinition>(). Where(f => f.PageId == page.Id && f.FolderTypeId == folderTypeId). Select(f => f.Id). SingleOrDefault(); } /// <exclude /> public static bool HasFolderData(this IPage page, Type pageFolderType) { Verify.ArgumentNotNull(page, "page"); //TODO: Consider caching here ParameterExpression parameterExpression = Expression.Parameter(pageFolderType); LambdaExpression lambdaExpression = Expression.Lambda( Expression.Equal( Expression.Property( parameterExpression, PageMetaDataFacade.GetDefinitionPageReferencePropertyInfo(pageFolderType) ), Expression.Constant( page.Id, typeof(Guid) ) ), parameterExpression ); Expression whereExpression = ExpressionCreator.Where(DataFacade.GetData(pageFolderType).Expression, lambdaExpression); //TODO: Possible optimization here return DataFacade.GetData(pageFolderType).Provider.CreateQuery(whereExpression).ToEnumerableOfObjects().Any(); } /// <summary> /// Returns all folder data given the page and folder data type /// </summary> /// <param name="page"></param> /// <param name="pageFolderType"></param> /// <returns></returns> public static IEnumerable<IData> GetFolderData(this IPage page, Type pageFolderType) { Verify.ArgumentNotNull(page, "page"); return GetFolderData(page.Id, pageFolderType); } /// <summary> /// Returns all folder data given the page id and folder data type /// </summary> /// <param name="pageId"></param> /// <param name="pageFolderType"></param> /// <returns></returns> public static IEnumerable<IData> GetFolderData(Guid pageId, Type pageFolderType) { //TODO: Consider caching here ParameterExpression parameterExpression = Expression.Parameter(pageFolderType); LambdaExpression lambdaExpression = Expression.Lambda( Expression.Equal( Expression.Property( parameterExpression, PageMetaDataFacade.GetDefinitionPageReferencePropertyInfo(pageFolderType) ), Expression.Constant( pageId, typeof(Guid) ) ), parameterExpression ); Expression whereExpression = ExpressionCreator.Where(DataFacade.GetData(pageFolderType).Expression, lambdaExpression); IEnumerable<IData> dataset = ExpressionHelper.GetCastedObjects<IData>(pageFolderType, whereExpression); return dataset; } /// <summary> /// Returns all folder data for all defined folder types for the given page /// </summary> /// <param name="page"></param> /// <returns></returns> public static IEnumerable<IData> GetFolderData(this IPage page) { foreach (Type folderType in page.GetDefinedFolderTypes()) { foreach (IData data in page.GetFolderData(folderType)) { yield return data; } } } /// <summary> /// Returns the referenced page /// </summary> /// <param name="folderData"></param> /// <returns></returns> public static IPage GetReferencedPage(IData folderData) { Guid pageId = (Guid)GetDefinitionPageReferencePropertyInfo(folderData.DataSourceId.InterfaceType).GetValue(folderData, null); return Composite.Data.PageManager.GetPageById(pageId); } /// <summary> /// Adds a data folder type to the given page /// </summary> /// <param name="page"></param> /// <param name="dataFolderType"></param> // Overload public static void AddFolderDefinition(this IPage page, Type dataFolderType) { AddFolderDefinition(page, dataFolderType.GetImmutableTypeId()); } /// <summary> /// Adds a data folder type to the given page /// </summary> /// <param name="page"></param> /// <param name="dataFolderTypeId"></param> public static void AddFolderDefinition(this IPage page, Guid dataFolderTypeId) { var pageFolderDefinition = DataFacade.BuildNew<IPageFolderDefinition>(); pageFolderDefinition.Id = Guid.NewGuid(); pageFolderDefinition.PageId = page.Id; pageFolderDefinition.FolderTypeId = dataFolderTypeId; DataFacade.AddNew<IPageFolderDefinition>(pageFolderDefinition); } /// <summary> /// Removes a data folder type for the given page /// </summary> /// <param name="page"></param> /// <param name="dataFolderType"></param> /// <param name="deleteExistingFolderData"></param> public static void RemoveFolderDefinition(this IPage page, Type dataFolderType, bool deleteExistingFolderData = true) { Guid dataFolderTypeId = dataFolderType.GetImmutableTypeId(); if (!deleteExistingFolderData) { RemoveFolderDefinitionInternal(page.Id, dataFolderTypeId); return; } using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { DataFacade.ForEachDataScope(dataFolderType, () => { IEnumerable<IData> dataset = page.GetFolderData(dataFolderType); DataFacade.Delete(dataset); }); RemoveFolderDefinitionInternal(page.Id, dataFolderTypeId); transactionScope.Complete(); } } /// <summary> /// Removes a data folder type for the given page /// </summary> /// <param name="page"></param> /// <param name="dataFolderTypeId"></param> /// <param name="deleteExistingFolderData"></param> public static void RemoveFolderDefinition(this IPage page, Guid dataFolderTypeId, bool deleteExistingFolderData = true) { var interfaceType = DynamicTypeManager.GetDataTypeDescriptor(dataFolderTypeId).GetInterfaceType(); RemoveFolderDefinition(page, interfaceType, deleteExistingFolderData); } private static void RemoveFolderDefinitionInternal(Guid pageId, Guid dataFolderTypeId) { IPageFolderDefinition pageFolderDefinition = DataFacade.GetData<IPageFolderDefinition>() .FirstOrDefault(f => f.PageId == pageId && f.FolderTypeId == dataFolderTypeId); Verify.IsNotNull(pageFolderDefinition, "Page folder definition does not exist"); DataFacade.Delete<IPageFolderDefinition>(pageFolderDefinition); } /// <summary> /// Removes all data folder definitions given the folder type id /// </summary> /// <param name="dataFolderTypeId"></param> /// <param name="deleteExistingFolderData"></param> public static void RemoveAllFolderDefinitions(Guid dataFolderTypeId, bool deleteExistingFolderData = true) { if (deleteExistingFolderData) { IEnumerable<IPageFolderDefinition> pageFolderDefinitions = DataFacade.GetData<IPageFolderDefinition>(). Where(f => f.FolderTypeId == dataFolderTypeId); foreach (IPageFolderDefinition pageFolderDefinition in pageFolderDefinitions) { IPage page = Composite.Data.PageManager.GetPageById(pageFolderDefinition.Id); page.RemoveFolderDefinition(pageFolderDefinition.FolderTypeId); } DataFacade.Delete<IPageFolderDefinition>(pageFolderDefinitions); } else { IEnumerable<IPageFolderDefinition> pageFolderDefinitions = DataFacade.GetData<IPageFolderDefinition>(). Where(f => f.FolderTypeId == dataFolderTypeId); DataFacade.Delete<IPageFolderDefinition>(pageFolderDefinitions); } } /// <summary> /// Updates the given page folder item with new Id and setting the page folder definition id and defining item id /// </summary> /// <param name="pageFolderData"></param> /// <param name="definingPage"></param> [Obsolete("Use an overload accepting a page Id")] public static void AssignFolderDataSpecificValues(IData pageFolderData, IPage definingPage) { AssignFolderDataSpecificValues(pageFolderData, definingPage.Id); } /// <summary> /// Updates the given page folder item with new Id and setting the page folder definition id and defining item id /// </summary> /// <param name="pageFolderData"></param> /// <param name="pageId"></param> public static void AssignFolderDataSpecificValues(IData pageFolderData, Guid pageId) { var pageRelatedData = pageFolderData as IPageRelatedData; if (pageRelatedData != null) { pageRelatedData.PageId = pageId; } else { // Backward compatibility Type interfaceType = pageFolderData.DataSourceId.InterfaceType; PropertyInfo pageReferencePropertyInfo = GetDefinitionPageReferencePropertyInfo(interfaceType); pageReferencePropertyInfo.SetValue(pageFolderData, pageId, null); } var pageData = pageFolderData as IPageData; if (pageData != null) { pageData.Id = Guid.NewGuid(); } else { // Backward compatibility Type interfaceType = pageFolderData.DataSourceId.InterfaceType; PropertyInfo idPropertyInfo = interfaceType.GetPropertiesRecursively() .FirstOrDefault(f => f.Name == PageFolderType_IdFieldName); if (idPropertyInfo != null && idPropertyInfo.PropertyType == typeof(Guid)) { idPropertyInfo.SetValue(pageFolderData, Guid.NewGuid(), null); } } } /// <exclude /> public static PropertyInfo GetDefinitionPageReferencePropertyInfo(Type pageFolderType) { return pageFolderType.GetPropertiesRecursively().Last(f => f.Name == PageFolderType_PageIdFieldName); } } } ================================================ FILE: Composite/Data/PageManager.cs ================================================ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using Composite.Core; using Composite.Core.Linq; using Composite.Data.Caching; using Composite.Data.Foundation; using Composite.Core.Types; using Composite.Data.Types; namespace Composite.Data { /// <summary> /// Provides basic data access to IPage and IPageStructure data /// </summary> /// <exclude /> // Made public for Base site in App_Code/Composite/BasicSearch.cs [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PageManager { private static readonly string LogTitle = "PageManager"; private class PageStructureRecord { public PageStructureRecord() { } public PageStructureRecord(IPageStructure ps) { ParentId = ps.ParentId; LocalOrdering = ps.LocalOrdering; } public Guid ParentId { get; set; } public int LocalOrdering { get; set; } } private static readonly int PageCacheSize = 5000; private static readonly int PageStructureCacheSize = 3000; private static readonly int ChildrenCacheSize = 2000; private static readonly int PagePlaceholderCacheSize = 10000; private static readonly Cache<string, IReadOnlyCollection<IPage>> _pageCache = new Cache<string, IReadOnlyCollection<IPage>>("Pages", PageCacheSize); private static readonly Cache<string, ReadOnlyCollection<IPagePlaceholderContent>> _placeholderCache = new Cache<string, ReadOnlyCollection<IPagePlaceholderContent>>("Page placeholders", PagePlaceholderCacheSize); private static readonly Cache<Guid, ExtendedNullable<PageStructureRecord>> _pageStructureCache = new Cache<Guid, ExtendedNullable<PageStructureRecord>>("Page structure", PageStructureCacheSize); private static readonly Cache<Guid, ReadOnlyCollection<Guid>> _childrenCache = new Cache<Guid, ReadOnlyCollection<Guid>>("Child pages", ChildrenCacheSize); private static readonly object _preloadingSyncRoot = new object(); private static bool _pageStructurePreloaded; private static readonly HashSet<string> _preloadedPageDataScopes = new HashSet<string>(); static PageManager() { SubscribeToEvents(); } #region Public methods /// <exclude /> public static IPage GetPageById(Guid id) { return GetPageById(id, false); } /// <exclude /> public static IPage GetPageById(Guid id, bool readonlyValue) { var versions = GetAllPageVersions(id); if (versions == null || versions.Count == 0) { return null; } IEnumerable<IPage> filteredVersions = versions; foreach (var dataInterceptor in DataFacade.GetDataInterceptors(typeof(IPage))) { filteredVersions = dataInterceptor.InterceptGetData(filteredVersions); } var result = filteredVersions.FirstOrDefault(); if (result == null) { return null; } return readonlyValue ? result : CreateWrapper(result); } /// <exclude /> public static IPage GetPageById(Guid id, Guid versionId, bool readonlyValue = false) { var versions = GetAllPageVersions(id); if (versions == null || versions.Count == 0) { return null; } var result = versions.FirstOrDefault(v => v.VersionId == versionId); if (result == null) { return null; } return readonlyValue ? result : CreateWrapper(result); } private static IReadOnlyCollection<IPage> GetAllPageVersions(Guid pageId) { string cacheKey = GetCacheKey<IPage>(pageId, Guid.Empty); IReadOnlyCollection<IPage> allPageVersions = _pageCache.Get(cacheKey); if (allPageVersions == null) { using (var conn = new DataConnection()) { conn.DisableServices(); allPageVersions = new ReadOnlyCollection<IPage>( conn.Get<IPage>().Where(p => p.Id == pageId).ToList() ); } _pageCache.Add(cacheKey, allPageVersions); } return allPageVersions; } /// <exclude /> [Obsolete("Use GetParentId(..)", true)] public static Guid GetParentID(Guid pageId) { return GetParentId(pageId); } /// <exclude /> public static Guid GetParentId(Guid pageId) { PageStructureRecord pageStructure = GetPageStructureRecord(pageId); return pageStructure?.ParentId ?? Guid.Empty; } /// <exclude /> public static int GetLocalOrdering(Guid pageId) { PageStructureRecord pageStructure = GetPageStructureRecord(pageId); return pageStructure?.LocalOrdering ?? 0; } /// <summary> /// /// </summary> /// <param name="parentPageId">Empty guild will yield all root pages</param> /// <returns></returns> public static ReadOnlyCollection<Guid> GetChildrenIDs(Guid parentPageId) { var cacheKey = parentPageId; var cachedValue = _childrenCache.Get(cacheKey); if (cachedValue != null) { return cachedValue; } // TODO: put children's page structure records into cache List<Guid> children = (from ps in DataFacade.GetData<IPageStructure>() where ps.ParentId == parentPageId orderby ps.LocalOrdering select ps.Id).ToList(); var readonlyList = new ReadOnlyCollection<Guid>(children); _childrenCache.Add(cacheKey, readonlyList); return readonlyList; } /// <exclude /> [Obsolete("Use an overload also accepting a version id")] public static ReadOnlyCollection<IPagePlaceholderContent> GetPlaceholderContent(Guid pageId) { IPage page = GetPageById(pageId); return GetPlaceholderContent(pageId, page.VersionId); } /// <exclude /> public static ReadOnlyCollection<IPagePlaceholderContent> GetPlaceholderContent(Guid pageId, Guid versionId) { string cacheKey = GetCacheKey<IPagePlaceholderContent>(pageId, versionId); var result = _placeholderCache.Get(cacheKey); if (result == null) { using (var conn = new DataConnection()) { conn.DisableServices(); var list = DataFacade.GetData<IPagePlaceholderContent>(false) .Where(f => f.PageId == pageId && f.VersionId == versionId).ToList(); result = new ReadOnlyCollection<IPagePlaceholderContent>(list); } _placeholderCache.Add(cacheKey, result); } return result; } #endregion Public internal static void PreloadPageCaching() { string key = DataScopeManager.CurrentDataScope.ToString() + LocalizationScopeManager.CurrentLocalizationScope; if (!_preloadedPageDataScopes.Contains(key)) { lock (_preloadingSyncRoot) { if (!_preloadedPageDataScopes.Contains(key)) { using (var conn = new DataConnection()) { conn.DisableServices(); var pages = DataFacade.GetData<IPage>().GroupBy(p => p.Id).Evaluate(); if (pages.Count > 0) { var dataSourceId = pages.First().First().DataSourceId; foreach (var pageVersionsGroup in pages) { string pageKey = GetCacheKey(pageVersionsGroup.Key, dataSourceId); _pageCache.Add(pageKey, new ReadOnlyCollection<IPage>(pageVersionsGroup.ToList())); } } } _preloadedPageDataScopes.Add(key); } } } if (!_pageStructurePreloaded) { lock (_preloadingSyncRoot) { if (!_pageStructurePreloaded) { var pageStructures = DataFacade.GetData<IPageStructure>().Evaluate(); foreach (var str in pageStructures) { _pageStructureCache.Add(str.Id, new ExtendedNullable<PageStructureRecord> {Value = new PageStructureRecord(str)}); } foreach (var pair in pageStructures.GroupBy(ps => ps.ParentId)) { _childrenCache.Add(pair.Key, new ReadOnlyCollection<Guid>( pair .OrderBy(p => p.LocalOrdering) .Select(v => v.Id).ToList())); } _pageStructurePreloaded = true; } } } } #region Private private static PageStructureRecord GetPageStructureRecord(Guid pageId) { var cacheKey = pageId; ExtendedNullable<PageStructureRecord> cachedValue = _pageStructureCache.Get(cacheKey); if (cachedValue != null) { Verify.That(cachedValue.HasValue, "Incorrect usage of cache."); return cachedValue.Value; } PageStructureRecord result = (from ps in DataFacade.GetData<IPageStructure>(false) where ps.Id == pageId select new PageStructureRecord { ParentId = ps.ParentId, LocalOrdering = ps.LocalOrdering }).FirstOrDefault(); if (result == null) { Log.LogWarning(LogTitle, $"No IPageStructure entries found for Page with Id '{pageId}'"); } _pageStructureCache.Add(cacheKey, result); return result; } private static string GetCacheKey<T>(Guid id, Guid versionId) { var cultureInfo = LocalizationScopeManager.MapByType(typeof (T)); Verify.IsNotNull(cultureInfo, "Localization culture is not set"); var dataScope = DataScopeManager.MapByType(typeof (T)); Verify.IsNotNull(dataScope, "Publication scope is not set"); return id + dataScope.Name + cultureInfo + (versionId != Guid.Empty ? versionId.ToString() : ""); } private static string GetCacheKey(Guid id, DataSourceId dataSourceId) { return GetCacheKey(id, Guid.Empty, dataSourceId); } private static string GetCacheKey(Guid id, Guid versionId, DataSourceId dataSourceId) { string localizationInfo = dataSourceId.LocaleScope.ToString(); string dataScope = dataSourceId.DataScopeIdentifier.Name; string versionIdStr = versionId != Guid.Empty ? versionId.ToString() : ""; return id + dataScope + localizationInfo + versionIdStr; } private static void OnPageStoreChanged(object sender, StoreEventArgs storeEventArgs) { if (!storeEventArgs.DataEventsFired) { _pageCache.Clear(); lock (_preloadingSyncRoot) { _preloadedPageDataScopes.Clear(); } } } private static void OnPageChanged(object sender, DataEventArgs args) { if (args.Data is IPage page) { _pageCache.Remove(GetCacheKey(page.Id, page.DataSourceId)); } } private static void OnPagePlaceholderStoreChanged(object sender, StoreEventArgs storeEventArgs) { if (!storeEventArgs.DataEventsFired) { _placeholderCache.Clear(); } } private static void OnPagePlaceholderChanged(object sender, DataEventArgs args) { if (args.Data is IPagePlaceholderContent placeHolder) { _placeholderCache.Remove(GetCacheKey(placeHolder.PageId, placeHolder.VersionId, placeHolder.DataSourceId)); } } private static void OnPageStructureStoreChanged(object sender, StoreEventArgs storeEventArgs) { if (!storeEventArgs.DataEventsFired) { _pageStructureCache.Clear(); _childrenCache.Clear(); _pageStructurePreloaded = false; } } private static void OnPageStructureChanged(object sender, DataEventArgs args) { if (args.Data is IPageStructure pageStructure) { _pageStructureCache.Remove(pageStructure.Id); _childrenCache.Remove(pageStructure.ParentId); } } private static IPage CreateWrapper(IPage page) { return DataWrappingFacade.Wrap(page); } private static void SubscribeToEvents() { DataEventSystemFacade.SubscribeToDataDeleted<IPagePlaceholderContent>(OnPagePlaceholderChanged, true); DataEventSystemFacade.SubscribeToDataAfterUpdate<IPagePlaceholderContent>(OnPagePlaceholderChanged, true); DataEventSystemFacade.SubscribeToDataAfterAdd<IPagePlaceholderContent>(OnPagePlaceholderChanged, true); DataEventSystemFacade.SubscribeToStoreChanged<IPagePlaceholderContent>(OnPagePlaceholderStoreChanged, true); DataEventSystemFacade.SubscribeToDataAfterUpdate<IPage>(OnPageChanged, true); DataEventSystemFacade.SubscribeToDataAfterAdd<IPage>(OnPageChanged, true); DataEventSystemFacade.SubscribeToDataDeleted<IPage>(OnPageChanged, true); DataEventSystemFacade.SubscribeToStoreChanged<IPage>(OnPageStoreChanged, true); DataEventSystemFacade.SubscribeToDataAfterAdd<IPageStructure>(OnPageStructureChanged, true); DataEventSystemFacade.SubscribeToDataAfterUpdate<IPageStructure>(OnPageStructureChanged, true); DataEventSystemFacade.SubscribeToDataDeleted<IPageStructure>(OnPageStructureChanged, true); DataEventSystemFacade.SubscribeToStoreChanged<IPageStructure>(OnPageStructureStoreChanged, true); } #endregion Private } } ================================================ FILE: Composite/Data/PageMetaDataDescription.cs ================================================ using System; using System.Collections.Generic; using System.Text; using Composite.Core.Serialization; namespace Composite.Data { internal sealed class PageMetaDataDescriptionSerializerHandler : ISerializerHandler { public string Serialize(object objectToSerialize) { PageMetaDataDescription dataAssociationVisabilityRule = (PageMetaDataDescription)objectToSerialize; return dataAssociationVisabilityRule.Serialize(); } public object Deserialize(string serializedObject) { return PageMetaDataDescription.Deserialize(serializedObject); } } /// <summary> /// This class is used when adding a new page metadata type to a given page. In other words, in workflow only. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SerializerHandler(typeof(PageMetaDataDescriptionSerializerHandler))] public sealed class PageMetaDataDescription { /// <exclude /> public static PageMetaDataDescription OneToOne() { return new PageMetaDataDescription(PageMetaDataDescriptionType.OneToOne); } /// <exclude /> public static PageMetaDataDescription Branch() { return new PageMetaDataDescription(PageMetaDataDescriptionType.Branch, 0, 100000); } /// <exclude /> public static PageMetaDataDescription Branch(int startLevel) { return new PageMetaDataDescription(PageMetaDataDescriptionType.Branch, startLevel, int.MaxValue); } /// <exclude /> public static PageMetaDataDescription Branch(int startLevel, int levels) { return new PageMetaDataDescription(PageMetaDataDescriptionType.Branch, startLevel, levels); } internal PageMetaDataDescription(PageMetaDataDescriptionType dataAssociationVisabilityRuleType) : this(dataAssociationVisabilityRuleType, 0, 0) { } internal PageMetaDataDescription(PageMetaDataDescriptionType dataAssociationVisabilityRuleType, int startLevel, int levels) { this.PageMetaDataDescriptionType = dataAssociationVisabilityRuleType; this.StartLevel = startLevel; this.Levels = levels; } /// <exclude /> public PageMetaDataDescriptionType PageMetaDataDescriptionType { get; private set; } /// <exclude /> public int StartLevel { get; private set; } /// <exclude /> public int Levels { get; private set; } /// <exclude /> public string Serialize() { StringBuilder sb = new StringBuilder(); StringConversionServices.SerializeKeyValuePair(sb, "_PageMetaDataDescriptionType_", this.PageMetaDataDescriptionType.ToString()); StringConversionServices.SerializeKeyValuePair(sb, "_StartLevel_", this.StartLevel.ToString()); StringConversionServices.SerializeKeyValuePair(sb, "_Levels_", this.Levels.ToString()); return sb.ToString(); } internal static PageMetaDataDescription Deserialize(string serializedData) { // DataAssociationVisabilityRuleType is here for backwards compatibility - after 1.3 its not used any more Dictionary<string, string> dic = StringConversionServices.ParseKeyValueCollection(serializedData); if (((dic.ContainsKey("DataAssociationVisabilityRuleType") == false) && (dic.ContainsKey("_PageMetaDataDescriptionType_") == false)) || (dic.ContainsKey("_StartLevel_") == false) || (dic.ContainsKey("_Levels_") == false)) { throw new ArgumentException(string.Format("The serializedData is not a serialized '{0}'", typeof(PageMetaDataDescription)), "serializedData"); } string serializedDataAssociationVisabilityRuleType; if (dic.ContainsKey("_PageMetaDataDescriptionType_")) { serializedDataAssociationVisabilityRuleType = StringConversionServices.DeserializeValueString(dic["_PageMetaDataDescriptionType_"]); } else { serializedDataAssociationVisabilityRuleType = StringConversionServices.DeserializeValueString(dic["DataAssociationVisabilityRuleType"]); } PageMetaDataDescriptionType type = (PageMetaDataDescriptionType)Enum.Parse(typeof(PageMetaDataDescriptionType), serializedDataAssociationVisabilityRuleType); string serializedStartLevel = StringConversionServices.DeserializeValueString(dic["_StartLevel_"]); string serializedLevels = StringConversionServices.DeserializeValueString(dic["_Levels_"]); int startLevel = int.Parse(serializedStartLevel); int levels = int.Parse(serializedLevels); return new PageMetaDataDescription(type, startLevel, levels); } /// <exclude /> public override bool Equals(object obj) { return Equals(obj as PageMetaDataDescription); } /// <exclude /> public bool Equals(PageMetaDataDescription dataAssociationVisabilityRule) { if (dataAssociationVisabilityRule == null) return false; return this.PageMetaDataDescriptionType == dataAssociationVisabilityRule.PageMetaDataDescriptionType && this.StartLevel == dataAssociationVisabilityRule.StartLevel && this.Levels == dataAssociationVisabilityRule.Levels; } /// <exclude /> public override int GetHashCode() { return this.PageMetaDataDescriptionType.GetHashCode() ^ this.StartLevel.GetHashCode() ^ this.Levels.GetHashCode(); } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum PageMetaDataDescriptionType { /// <exclude /> OneToOne = 0, /// <exclude /> Branch = 1, /// <exclude /> PageType = 2 } } ================================================ FILE: Composite/Data/PageMetaDataFacade.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Transactions; using Composite.Data.DynamicTypes; using Composite.Data.Foundation; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.Types; using Composite.Data.Transactions; using Composite.Core.Linq; using Composite.Core.Types; using Composite.C1Console.Users; namespace Composite.Data { /// <summary> /// Using the same name for a metadata definition is allowed iff metadata type and label are the same /// on all instances. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PageMetaDataFacade { private static readonly Guid DefaultCompositionContainerId = new Guid("eb210a75-be25-401f-b0d4-b3787bce36fa"); /// <summary> /// Returns all possible meta data types. This is NOT types that only have been defined on any pages or page type /// </summary> /// <returns></returns> public static IEnumerable<Type> GetAllMetaDataTypes() { return DataAssociationRegistry.GetAssociationTypes(typeof(IPage), DataAssociationType.Composition); } /// <summary> /// Returns all meta data types that are defined on the given page. /// </summary> /// <param name="page">If this is null, Guid.Empty is assumed as defining item id</param> /// <returns></returns> public static IEnumerable<Type> GetDefinedMetaDataTypes(this IPage page) { Guid pageId = page.GetPageIdOrNull(); IEnumerable<Guid> metaDataTypeIds = DataFacade.GetData<IPageMetaDataDefinition>(). Where(f => f.DefiningItemId == pageId). Select(f => f.MetaDataTypeId). Distinct(); foreach (Guid metaDataTypeId in metaDataTypeIds) { var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(metaDataTypeId); yield return TypeManager.GetType(dataTypeDescriptor.TypeManagerTypeName); } } /// <exclude /> public static IEnumerable<Tuple<Type, string>> GetDefinedMetaDataTypeAndNames(this IPage page) { Guid pageId = page.GetPageIdOrNull(); IEnumerable<Tuple<Guid, string>> metaDataTypeIdAndNames = DataFacade.GetData<IPageMetaDataDefinition>(). Where(f => f.DefiningItemId == pageId). Select(f => new Tuple<Guid, string>(f.MetaDataTypeId, f.Name)). Distinct(); foreach (Tuple<Guid, string> metaDataTypeIdAndName in metaDataTypeIdAndNames) { var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(metaDataTypeIdAndName.Item1); yield return new Tuple<Type, string>(TypeManager.GetType(dataTypeDescriptor.TypeManagerTypeName), metaDataTypeIdAndName.Item2); } } /// <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); } /// <summary> /// Returns the composition container given the page metadata definition name /// </summary> /// <param name="name"></param> /// <returns></returns> [Obsolete()] public static ICompositionContainer GetMetaDataContainerByDefinitionName(string name) { return DataFacade.GetData<IPageMetaDataDefinition>() .Join(DataFacade.GetData<ICompositionContainer>(), o => o.MetaDataContainerId, i => i.Id, (def, con) => new { def, con }) .Where(f => f.def.Name == name) .Select(f => f.con) .Distinct() .SingleOrDefaultOrException("Multiple metadata containers with the same name '{0}'", name); } /// <summary> /// Gets all meta data containers ordered. If none exists in the system, a default is created /// </summary> /// <returns></returns> public static List<KeyValuePair<Guid, string>> GetAllMetaDataContainers() { List<KeyValuePair<Guid, string>> containers; using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { bool anyExists = DataFacade.GetData<ICompositionContainer>().Any(); if (!anyExists) { ICompositionContainer defaultContainer = DataFacade.BuildNew<ICompositionContainer>(); defaultContainer.Id = DefaultCompositionContainerId; defaultContainer.Label = "${Composite.Management, DataCompositionVisabilityFacade.DefaultContainerLabel}"; DataFacade.AddNew<ICompositionContainer>(defaultContainer); } containers = DataFacade.GetData<ICompositionContainer>(). OrderBy(f => f.Label). Select(f => new KeyValuePair<Guid, string>(f.Id, f.Label)). ToList(); transactionScope.Complete(); } return containers; } /// <summary> /// Returns all allowed metadata containers on the given page /// </summary> /// <param name="page">If null, empty guid is used (whole website)</param> /// <returns></returns> public static IEnumerable<ICompositionContainer> GetAllowedMetaDataContainers(this IPage page) { foreach (Guid metaDataContainerId in GetAllowedMetaDataDefinitions(page).Select(f => f.MetaDataContainerId).Distinct()) { Guid containerId = metaDataContainerId; // moving Guid to a local variable to build a correct linq expression yield return DataFacade.GetData<ICompositionContainer>(). Where(f => f.Id == containerId). SingleOrException("Cannot find ICompositionContainer by ID: '{0}'", "More than one ICompositionContainer object for the same ID: '{0}'", containerId); } } /// <summary> /// Return all allowed metadata types on the given page /// </summary> /// <param name="page"></param> /// <returns></returns> public static IEnumerable<Type> GetAllowedMetaDataTypes(this IPage page) { foreach (Guid metaDataTypeId in GetAllowedMetaDataDefinitions(page).Select(f => f.MetaDataTypeId).Distinct()) { var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(metaDataTypeId); yield return TypeManager.GetType(dataTypeDescriptor.TypeManagerTypeName); } } /// <summary> /// Returns all allowed metadata definitions on the given page /// </summary> /// <param name="page">If null, empty guid is used (whole website)</param> /// <returns></returns> public static List<IPageMetaDataDefinition> GetAllowedMetaDataDefinitions(this IPage page) { IEnumerable<IPageMetaDataDefinition> pageMetaDataDefinitions = DataFacade. GetData<IPageMetaDataDefinition>().OrderBy(f => f.Label). Evaluate(); List<IPageMetaDataDefinition> resultPageMetaDataDefinitions = new List<IPageMetaDataDefinition>(); foreach (IPageMetaDataDefinition pageMetaDataDefinition in pageMetaDataDefinitions) { if (IsDefinitionAllowed(pageMetaDataDefinition, page)) { if (!resultPageMetaDataDefinitions.Any(f => f.Name == pageMetaDataDefinition.Name)) { resultPageMetaDataDefinitions.Add(pageMetaDataDefinition); } } } return resultPageMetaDataDefinitions; } /// <summary> /// Returns true if the given page metadata definition is allowed for the given page /// </summary> /// <param name="pageMetaDataDefinition"></param> /// <param name="page">If null, empty guid is used (whole website)</param> /// <returns></returns> public static bool IsDefinitionAllowed(IPageMetaDataDefinition pageMetaDataDefinition, IPage page) { if (page != null && pageMetaDataDefinition.DefiningItemId == page.PageTypeId) return true; Guid pageId = page.GetPageIdOrNull(); // Its not a pagetype attached meta data definitions, check page attacked int levelsToParent = CountLevelsToParent(pageMetaDataDefinition.DefiningItemId, pageId); if (pageMetaDataDefinition.StartLevel > levelsToParent) return false; if (pageMetaDataDefinition.StartLevel + pageMetaDataDefinition.Levels < levelsToParent) return false; return true; } private static int CountLevelsToParent(Guid definingPageId, Guid pageId) { int count = 0; while (definingPageId != pageId) { Guid parentPageId = Composite.Data.PageManager.GetParentId(pageId); if (definingPageId != Guid.Empty && parentPageId == Guid.Empty) return -1; // Page is not a (sub)child of _pageId pageId = parentPageId; count++; } return count; } /// <exclude /> public static IEnumerable<IData> GetMetaData(string definitionName, Type metaDataType) { Verify.ArgumentNotNull(definitionName, nameof(definitionName)); Verify.ArgumentNotNull(metaDataType, nameof(metaDataType)); var parameterExpression = Expression.Parameter(metaDataType); var lambdaExpression = Expression.Lambda( Expression.Equal( Expression.Property( parameterExpression, PageMetaDataFacade.GetDefinitionNamePropertyInfo(metaDataType) ), Expression.Constant( definitionName, typeof(string) ) ), parameterExpression ); var whereExpression = ExpressionCreator.Where(DataFacade.GetData(metaDataType).Expression, lambdaExpression); IEnumerable<IData> datas = ExpressionHelper.GetCastedObjects<IData>(metaDataType, whereExpression); return datas; } /// <exclude /> public static IEnumerable<IData> GetMetaData(this IPage page) { Verify.ArgumentNotNull(page, nameof(page)); return GetMetaData(page, DataScopeManager.CurrentDataScope); } /// <exclude /> public static IEnumerable<IData> GetMetaData(this IPage page, DataScopeIdentifier dataScopeIdentifier) { Verify.ArgumentNotNull(page, nameof(page)); using (new DataScope(dataScopeIdentifier)) { foreach (IPageMetaDataDefinition pageMetaDataDefinition in page.GetAllowedMetaDataDefinitions()) { IData data = page.GetMetaData(pageMetaDataDefinition.Name, pageMetaDataDefinition.MetaDataTypeId); if (data != null) { yield return data; } } } } /// <exclude /> public static IData GetMetaData(this IPage page, string definitionName, Guid metaDataTypeId) { DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(metaDataTypeId); Type metaDataType = TypeManager.GetType(dataTypeDescriptor.TypeManagerTypeName); return GetMetaData(page, definitionName, metaDataType); } /// <exclude /> public static IData GetMetaData(this IPage page, string definitionName, Type metaDataType) { Verify.ArgumentNotNull(page, nameof(page)); return GetMetaData(page.Id, page.VersionId, definitionName, metaDataType); } /// <exclude /> public static IData GetMetaData(Guid pageId, Guid pageVersionId, string definitionName, Type metaDataType) { Verify.ArgumentNotNull(definitionName, nameof(definitionName)); Verify.ArgumentNotNull(metaDataType, nameof(metaDataType)); //TODO: Consider caching here var parameterExpression = Expression.Parameter(metaDataType); var lambdaExpression = Expression.Lambda( Expression.And( Expression.And( Expression.Equal( Expression.Property( parameterExpression, GetDefinitionPageReferencePropertyInfo(metaDataType) ), Expression.Constant(pageId, typeof(Guid)) ), Expression.Equal( Expression.Property( parameterExpression, GetDefinitionPageReferencePropertyVersionInfo(metaDataType) ), Expression.Constant(pageVersionId, typeof(Guid)) ) ), Expression.Equal( Expression.Property( parameterExpression, GetDefinitionNamePropertyInfo(metaDataType) ), Expression.Constant(definitionName, typeof(string)) )), parameterExpression ); using (var conn = new DataConnection()) { conn.DisableServices(); var whereExpression = ExpressionCreator.Where(DataFacade.GetData(metaDataType).Expression, lambdaExpression); IEnumerable<IData> dataset = ExpressionHelper.GetCastedObjects<IData>(metaDataType, whereExpression); return dataset.SingleOrDefaultOrException("There're multiple meta data on a page. Page '{0}', definition name '{1}', meta type '{2}'", pageId, definitionName, metaDataType.FullName); } } /// <summary> /// Gets all existing pages that are affected by the given meta data definition /// </summary> /// <param name="definingPage">If null, empty guid is used</param> /// <param name="definitionName"></param> /// <returns></returns> public static IEnumerable<IPage> GetMetaDataAffectedPages(this IPage definingPage, string definitionName) { Guid pageId = definingPage.GetPageIdOrNull(); IPageMetaDataDefinition pageMetaDataDefinition = GetMetaDataDefinition(pageId, definitionName); return GetMetaDataAffectedPages(definingPage, pageMetaDataDefinition.StartLevel, pageMetaDataDefinition.Levels); } /// <summary> /// Gets all existing pages that are affected by the given meta data definition /// </summary> /// <param name="definingPage"></param> /// <param name="startLevel"></param> /// <param name="levels"></param> /// <returns></returns> public static IEnumerable<IPage> GetMetaDataAffectedPages(this IPage definingPage, int startLevel, int levels) { List<IPage> pages; if (definingPage != null) { pages = new List<IPage> { definingPage }; } else { pages = new List<IPage>(); foreach (Guid pageId in Composite.Data.PageManager.GetChildrenIDs(Guid.Empty)) { pages.Add(Composite.Data.PageManager.GetPageById(pageId)); } startLevel--; // We have just taken one level } for (int i = 0; i < startLevel; i++) { pages = pages.SelectMany(page => page.GetChildren()).ToList(); } for (int i = 0; i <= levels; i++) { if (pages.Count == 0) yield break; foreach (IPage p in pages) { yield return p; } pages = pages.SelectMany(page => page.GetChildren()).ToList(); } } /// <exclude /> public static IEnumerable<IPage> GetMetaDataAffectedPagesByPageTypeId(Guid definingPageTypeId) { return DataFacade.GetData<IPage>().Where(f => f.PageTypeId == definingPageTypeId); } //public static bool IsDefinitionAllowed(string name, string label, Guid metaDataTypeId) //{ // return // DataFacade.GetData<IPageMetaDataDefinition>(). // Where(f => (f.Name == name) && ((f.Label != label) || (f.MetaDataTypeId != metaDataTypeId))). // Any() == false; //} /// <exclude /> public static bool IsDefinitionAllowed(Guid definingItemId, string name, string label, Guid metaDataTypeId) { var pageMetaDataDefinitions = DataFacade.GetData<IPageMetaDataDefinition>().Where(f => f.Name == name).Evaluate(); foreach (IPageMetaDataDefinition pageMetaDataDefinition in pageMetaDataDefinitions) { if (pageMetaDataDefinition.DefiningItemId == definingItemId && pageMetaDataDefinition.MetaDataTypeId == metaDataTypeId && pageMetaDataDefinition.Label != label && pageMetaDataDefinitions.Count == 1) { return true; // Allow renaming of label } if (pageMetaDataDefinition.Label != label || pageMetaDataDefinition.MetaDataTypeId != metaDataTypeId || pageMetaDataDefinition.DefiningItemId == definingItemId) { return false; } } return true; } /// <exclude /> public static bool IsNewContainerIdAllowed(Guid definingItemId, string name, Guid newMetaDataContainerName) { var pageMetaDataDefinitions = DataFacade.GetData<IPageMetaDataDefinition>().Where(f => f.Name == name).Evaluate(); var pageMetaDataDefinition = pageMetaDataDefinitions.SingleOrDefault(f => f.DefiningItemId == definingItemId); if (pageMetaDataDefinition != null && pageMetaDataDefinition.MetaDataContainerId == newMetaDataContainerName) { return true; // Return true if no changes are made } return pageMetaDataDefinitions.Count <= 1; } /// <summary> /// Adds a new metadata definition to the given page /// </summary> /// <param name="definingPage"></param> /// <param name="name"></param> /// <param name="label"></param> /// <param name="metaDataTypeId"></param> /// <param name="metaDataContainerId"></param> /// <param name="startLevel"></param> /// <param name="levels"></param> public static void AddMetaDataDefinition(this IPage definingPage, string name, string label, Guid metaDataTypeId, Guid metaDataContainerId, int startLevel = 0, int levels = 100000) { AddDefinition(definingPage.GetPageIdOrNull(), name, label, metaDataTypeId, metaDataContainerId, startLevel, levels); } /// <summary> /// Adds a new metadata definition to the given pagetype /// </summary> /// <param name="definingPageType"></param> /// <param name="name"></param> /// <param name="label"></param> /// <param name="metaDataTypeId"></param> /// <param name="metaDataContainerId"></param> public static void AddMetaDataDefinition(this IPageType definingPageType, string name, string label, Guid metaDataTypeId, Guid metaDataContainerId) { Verify.ArgumentNotNull(definingPageType, nameof(definingPageType)); AddDefinition(definingPageType.Id, name, label, metaDataTypeId, metaDataContainerId, 0, 0); } /// <summary> /// Adds a new metadata definition to the given definingItemId. Guid.Empty is the whole website /// </summary> /// <param name="definingItemId"></param> /// <param name="name"></param> /// <param name="label"></param> /// <param name="metaDataTypeId"></param> /// <param name="metaDataContainerId"></param> /// <param name="startLevel"></param> /// <param name="levels"></param> public static void AddDefinition(Guid definingItemId, string name, string label, Guid metaDataTypeId, Guid metaDataContainerId, int startLevel = 0, int levels = 100000) { IPageMetaDataDefinition pageMetaDataDefinition = DataFacade.BuildNew<IPageMetaDataDefinition>(); pageMetaDataDefinition.Id = Guid.NewGuid(); pageMetaDataDefinition.DefiningItemId = definingItemId; pageMetaDataDefinition.Name = name; pageMetaDataDefinition.Label = label; pageMetaDataDefinition.MetaDataContainerId = metaDataContainerId; pageMetaDataDefinition.MetaDataTypeId = metaDataTypeId; pageMetaDataDefinition.StartLevel = startLevel; pageMetaDataDefinition.Levels = levels; DataFacade.AddNew<IPageMetaDataDefinition>(pageMetaDataDefinition); } /// <summary> /// Using the given page this methods adds meta data instances that are missing /// </summary> /// <param name="definingPage">If null, empty guid is used</param> /// <param name="metaDataDefinitionName"></param> /// <param name="newDataTemplate"></param> public static void AddNewMetaDataToExistingPages(this IPage definingPage, string metaDataDefinitionName, IData newDataTemplate) { Guid pageId = definingPage.GetPageIdOrNull(); IPageMetaDataDefinition pageMetaDataDefinition = GetMetaDataDefinition(pageId, metaDataDefinitionName); DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(pageMetaDataDefinition.MetaDataTypeId); Type metaDataType = TypeManager.GetType(dataTypeDescriptor.TypeManagerTypeName); IEnumerable<IPage> affectedPages = definingPage.GetMetaDataAffectedPages(metaDataDefinitionName); foreach (IPage affectedPage in affectedPages) { AddNewMetaDataToExistingPage(affectedPage, metaDataDefinitionName, metaDataType, newDataTemplate); } } /// <exclude /> public static void AddNewMetaDataToExistingPage(this IPage page, string metaDataDefinitionName, Type metaDataType, IData newDataTemplate) { IData data = page.GetMetaData(metaDataDefinitionName, metaDataType); if (data != null) return; var newData = (IPublishControlled) DataFacade.BuildNew(metaDataType); newDataTemplate.FullCopyChangedTo(newData); newData.PublicationStatus = GenericPublishProcessController.Draft; AssignMetaDataSpecificValues(newData, metaDataDefinitionName, page); if (newData is ILocalizedControlled localizedData) { localizedData.SourceCultureName = page.SourceCultureName; } newData = (IPublishControlled)DataFacade.AddNew((IData)newData); // Cast is needed for the DataFacade to work correctly if (newData.PublicationStatus != page.PublicationStatus) { newData.PublicationStatus = page.PublicationStatus; DataFacade.Update(newData); } } /// <summary> /// Using the given pageType this methods adds meta data instances that are missing /// </summary> /// <param name="definingPageType"></param> /// <param name="metaDataDefinitionName"></param> /// <param name="newDataTemplate"></param> public static void AddNewMetaDataToExistingPages(this IPageType definingPageType, string metaDataDefinitionName, IData newDataTemplate) { IPageMetaDataDefinition pageMetaDataDefinition = GetMetaDataDefinition(definingPageType.Id, metaDataDefinitionName); var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(pageMetaDataDefinition.MetaDataTypeId); Type metaDataType = TypeManager.GetType(dataTypeDescriptor.TypeManagerTypeName); IEnumerable<IPage> affectedPages = PageMetaDataFacade.GetMetaDataAffectedPagesByPageTypeId(definingPageType.Id); AddNewMetaDataToExistingPages(affectedPages, metaDataDefinitionName, metaDataType, newDataTemplate); } private static void AddNewMetaDataToExistingPages(IEnumerable<IPage> affectedPages, string metaDataDefinitionName, Type metaDataType, IData newDataTemplate) { foreach (IPage affectedPage in affectedPages) { IData data = affectedPage.GetMetaData(metaDataDefinitionName, metaDataType); if (data != null) continue; var newData = (IPublishControlled) DataFacade.BuildNew(metaDataType); newDataTemplate.FullCopyChangedTo(newData); newData.PublicationStatus = GenericPublishProcessController.Draft; PageMetaDataFacade.AssignMetaDataSpecificValues(newData, metaDataDefinitionName, affectedPage); if(newData is ILocalizedControlled localizedData) { localizedData.SourceCultureName = UserSettings.ActiveLocaleCultureInfo.Name; } newData = (IPublishControlled) DataFacade.AddNew((IData) newData); if (newData.PublicationStatus != affectedPage.PublicationStatus) { newData.PublicationStatus = affectedPage.PublicationStatus; DataFacade.Update(newData); } } } /// <summary> /// Update an existing metadata definition with possible new label and container id /// </summary> /// <param name="definingItemId"></param> /// <param name="definitionName"></param> /// <param name="newLabel"></param> /// <param name="newMetaDataContainerId"></param> public static void UpdateDefinition(Guid definingItemId, string definitionName, string newLabel, Guid newMetaDataContainerId) { using (var transactionScope = TransactionsFacade.CreateNewScope()) { IPageMetaDataDefinition pageMetaDataDefinition = GetMetaDataDefinition(definingItemId, definitionName); pageMetaDataDefinition.Label = newLabel; pageMetaDataDefinition.MetaDataContainerId = newMetaDataContainerId; // Update all data // PageDataAssociationVisabilityWrapper wrapper = new PageDataAssociationVisabilityWrapper(pageAssociationVisability); // Make join expression tree with compositionType and IPage on compositionType ref to IPage // and test those pages against the PageDataAssociationVisabilityWrapper (IsAllowed) and // Change compositionType composition description name to new name DataFacade.Update(pageMetaDataDefinition); transactionScope.Complete(); } } /// <summary> /// Update an existing metadata definition with possible new label and container id /// </summary> /// <param name="definingItemId"></param> /// <param name="definitionName"></param> /// <param name="newLabel"></param> /// <param name="newLevels"></param> /// <param name="newStartLevel"></param> /// <param name="newMetaDataContainerId"></param> public static void UpdateDefinition(Guid definingItemId, string definitionName, string newLabel, int newStartLevel, int newLevels, Guid newMetaDataContainerId) { using (var transactionScope = TransactionsFacade.CreateNewScope()) { IPageMetaDataDefinition pageMetaDataDefinition = GetMetaDataDefinition(definingItemId, definitionName); pageMetaDataDefinition.Label = newLabel; pageMetaDataDefinition.MetaDataContainerId = newMetaDataContainerId; pageMetaDataDefinition.StartLevel = newStartLevel; pageMetaDataDefinition.Levels = newLevels; // Update all data // PageDataAssociationVisabilityWrapper wrapper = new PageDataAssociationVisabilityWrapper(pageAssociationVisability); // Make join expression tree with compositionType and IPage on compositionType ref to IPage // and test those pages against the PageDataAssociationVisabilityWrapper (IsAllowed) and // Change compositionType composition description name to new name DataFacade.Update(pageMetaDataDefinition); transactionScope.Complete(); } } /// <summary> /// Removes a metadata definition and possibly deletes all data items that are defined by it /// </summary> /// <param name="definingPage"></param> /// <param name="definitionName"></param> /// <param name="deleteExistingMetaData"></param> public static void RemoveMetaDataDefinition(this IPage definingPage, string definitionName, bool deleteExistingMetaData = true) { RemoveDefinition(definingPage.GetPageIdOrNull(), definitionName, deleteExistingMetaData); } /// <summary> /// Removes a metadata definition and possibly deletes all data items that are defined by it /// </summary> /// <param name="definingPageType"></param> /// <param name="definitionName"></param> /// <param name="deleteExistingMetaData"></param> public static void RemoveMetaDataDefinition(this IPageType definingPageType, string definitionName, bool deleteExistingMetaData = true) { RemoveDefinition(definingPageType.Id, definitionName, deleteExistingMetaData); } /// <summary> /// Removes a metadata definition and possibly deletes all data items that are defined by it /// </summary> /// <param name="definingItemId"></param> /// <param name="definitionName"></param> /// <param name="deleteExistingMetaData"></param> public static void RemoveDefinition(Guid definingItemId, string definitionName, bool deleteExistingMetaData = true) { IPageMetaDataDefinition pageMetaDataDefinition = GetMetaDataDefinition(definingItemId, definitionName); IEnumerable<IPageMetaDataDefinition> otherPageMetaDataDefinitions = DataFacade.GetData<IPageMetaDataDefinition>(). Where(f => f.Name == definitionName && f.Id != pageMetaDataDefinition.Id). Evaluate(); DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(pageMetaDataDefinition.MetaDataTypeId); Type metaDataType = TypeManager.GetType(dataTypeDescriptor.TypeManagerTypeName); if (deleteExistingMetaData) { using (var transactionScope = TransactionsFacade.CreateNewScope()) { foreach (CultureInfo localeCultureInfo in DataLocalizationFacade.ActiveLocalizationCultures) { using (new DataScope(localeCultureInfo)) { using (new DataScope(DataScopeIdentifier.Public)) { RemoveDefinitionDeleteData(definitionName, metaDataType, otherPageMetaDataDefinitions); } using (new DataScope(DataScopeIdentifier.Administrated)) { RemoveDefinitionDeleteData(definitionName, metaDataType, otherPageMetaDataDefinitions); } } } DataFacade.Delete(pageMetaDataDefinition); transactionScope.Complete(); } } else { DataFacade.Delete(pageMetaDataDefinition); } } private static void RemoveDefinitionDeleteData(string definitionName, Type metaDataType, IEnumerable<IPageMetaDataDefinition> otherPageMetaDataDefinitions) { IEnumerable<IData> dataToDelete = PageMetaDataFacade.GetMetaData(definitionName, metaDataType).Evaluate(); List<IData> datasNotToDelete = new List<IData>(); foreach (IData data in dataToDelete) { IPage page = data.GetMetaDataReferencedPage(); if(page == null) { continue; } bool existsInOtherScope = ExistInOtherScope(page, otherPageMetaDataDefinitions); if (existsInOtherScope) { datasNotToDelete.Add(data); } } dataToDelete = dataToDelete.Except(datasNotToDelete); DataFacade.Delete(dataToDelete); } private static bool ExistInOtherScope(IPage page, IEnumerable<IPageMetaDataDefinition> otherPageMetaDataDefinitions) { return otherPageMetaDataDefinitions.Any( definition => IsDefinitionAllowed(definition, page)); } /// <exclude /> public static void RemoveAllDefinitions(Guid metaDataTypeId, bool deleteExistingMetaData = true) { IEnumerable<IPageMetaDataDefinition> pageMetaDataDefinitions = DataFacade.GetData<IPageMetaDataDefinition>(). Where(f => f.MetaDataTypeId == metaDataTypeId). Evaluate(); foreach (IPageMetaDataDefinition pageMetaDataDefinition in pageMetaDataDefinitions) { RemoveDefinition(pageMetaDataDefinition.DefiningItemId, pageMetaDataDefinition.Name, deleteExistingMetaData); } } /// <summary> /// Updates the given metadata item with new Id and setting the metadata definition name and defining item id /// </summary> /// <param name="metaData"></param> /// <param name="metaDataDefinitionName"></param> /// <param name="definingPage"></param> public static void AssignMetaDataSpecificValues(IData metaData, string metaDataDefinitionName, IPage definingPage) { Type interfaceType = metaData.DataSourceId.InterfaceType; PropertyInfo idPropertyInfo = interfaceType.GetPropertiesRecursively().SingleOrDefault(f => f.Name == nameof(IPageMetaData.Id)); idPropertyInfo.SetValue(metaData, Guid.NewGuid(), null); PropertyInfo namePropertyInfo = GetDefinitionNamePropertyInfo(interfaceType); namePropertyInfo.SetValue(metaData, metaDataDefinitionName, null); PropertyInfo pageReferencePropertyInfo = GetDefinitionPageReferencePropertyInfo(interfaceType); pageReferencePropertyInfo.SetValue(metaData, definingPage.Id, null); PropertyInfo pageReferencePropertyVersionInfo = GetDefinitionPageReferencePropertyVersionInfo(interfaceType); pageReferencePropertyVersionInfo.SetValue(metaData, definingPage.VersionId, null); } /// <exclude /> public static PropertyInfo GetDefinitionNamePropertyInfo(Type metaDataType) { return typeof (IPageMetaData).GetProperty(nameof(IPageMetaData.FieldName)); } /// <exclude /> public static PropertyInfo GetDefinitionPageReferencePropertyInfo(Type metaDataType) { return typeof(IPageRelatedData).GetProperty(nameof(IPageRelatedData.PageId)); } /// <exclude /> public static PropertyInfo GetDefinitionPageReferencePropertyVersionInfo(Type metaDataType) { return typeof(IVersioned).GetProperty(nameof(IVersioned.VersionId)); } /// <exclude /> public static Guid GetMetaDataReferencedPageId(IData metaData) { PropertyInfo propertyInfo = PageMetaDataFacade.GetDefinitionPageReferencePropertyInfo(metaData.DataSourceId.InterfaceType); Guid pageId = (Guid)propertyInfo.GetValue(metaData, null); return pageId; } /// <exclude /> public static IPage GetMetaDataReferencedPage(this IData metaData) { Guid pageId = GetMetaDataReferencedPageId(metaData); return Composite.Data.PageManager.GetPageById(pageId); } private static Guid GetPageIdOrNull(this IPage page) => page?.Id ?? Guid.Empty; } } ================================================ FILE: Composite/Data/PageNode.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Xml.Linq; using Composite.Core.Implementation; using Composite.Core.Routing; using Composite.Core.WebClient.Renderings.Page; using Composite.Data.Types; namespace Composite.Data { /// <summary> /// Represents a page in the C1 CMS sitemap hierarchy. /// </summary> public class PageNode { private readonly IPage _page; private readonly SitemapNavigatorImplementation _sitemapNavigator; private XElement _pageElement; private int? _level; /// <summary> /// Initializes a new instance of <see cref="PageNode"/>. /// </summary> /// <param name="page">The page.</param> /// <param name="sitemapNavigator">The site map navigator.</param> public PageNode(IPage page, SitemapNavigatorImplementation sitemapNavigator) { Verify.ArgumentNotNull(page, "page"); _page = page; _sitemapNavigator = sitemapNavigator; } /// <summary> /// The Id of the page /// </summary> public virtual Guid Id => _page.Id; /// <summary> /// The Title of the page /// </summary> public virtual string Title => _page.Title; /// <summary> /// The Menu Title of the page /// </summary> public virtual string MenuTitle => string.IsNullOrEmpty(_page.MenuTitle) ? null : _page.MenuTitle; /// <summary> /// The time the page was changed last /// </summary> public virtual DateTime ChangedDate => _page.ChangeDate; /// <summary> /// The Description of the page /// </summary> public virtual string Description => _page.Description; /// <summary> /// Url to this page. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] public virtual string Url => PageUrls.BuildUrl(_page); /// <summary> /// The level this page is placed at in the sitemap. Level 1 is a homepage, level 2 are children of the homepage and so on. /// </summary> public virtual int Level { get { if (_level == null) { PageNode parent = ParentPage; _level = parent?.Level + 1 ?? 1; } return _level.Value; } } /// <summary> /// Returns the parent <see cref="PageNode"/>. /// </summary> public virtual PageNode ParentPage { get { var parentPageId = PageManager.GetParentId(_page.Id); if (parentPageId == Guid.Empty) return null; var page = PageManager.GetPageById(parentPageId); return page != null ? new PageNode(page, _sitemapNavigator) : null; } } /// <summary> /// Returns <see cref="PageNode"/> elements that represent the immediate children of this page. /// </summary> public virtual IEnumerable<PageNode> ChildPages { get { foreach (Guid childId in PageManager.GetChildrenIDs(_page.Id)) { var page = PageManager.GetPageById(childId); if (page != null) { yield return new PageNode(page, _sitemapNavigator); } } } } /// <summary> /// Returns <see cref="PageNode"/> elements that is with the <see cref="SitemapScope"/> of this page- /// </summary> /// <param name="scope">The scope.</param> /// <returns></returns> public virtual IEnumerable<PageNode> GetPageNodes(SitemapScope scope) { if (scope < SitemapScope.Current || scope > SitemapScope.SiblingsAndSelf) throw new ArgumentOutOfRangeException("scope"); foreach (Guid pageId in GetPageIds(scope)) { var page = PageManager.GetPageById(pageId); if (page != null) { yield return new PageNode(page, _sitemapNavigator); } } } /// <summary> /// Return the Page Id's that is with the <see cref="SitemapScope"/> of this page- /// </summary> /// <param name="scope">The scope.</param> /// <returns></returns> public virtual IEnumerable<Guid> GetPageIds(SitemapScope scope) { if (scope < SitemapScope.Current || scope > SitemapScope.SiblingsAndSelf) throw new ArgumentOutOfRangeException("scope"); return PageStructureInfo.GetAssociatedPageIds(_page.Id, scope); } /// <summary> /// XML representing the page and it's decendants. Do NOT modify this structure. To do modifications, clone this first. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Sitemap")] public virtual XElement SitemapXml { get { if (_pageElement == null) { _pageElement = _sitemapNavigator.GetElementByPageId(_page.Id); } return _pageElement; } } /// <summary> /// Gets the page. /// </summary> /// <returns>The page</returns> public virtual IPage Page => _page; /// <summary> /// Serialize the page specific state to a string for reading. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "PageNode(Id:'{0}', Title:'{1}', Description:'{2}', MenuTitle:'{3}', Url:'{4}', Level:'{5}')", this.Id, this.Title, this.Description, this.MenuTitle, this.Url, this.Level); } } } ================================================ FILE: Composite/Data/PageRenderingHistory.cs ================================================ using System; using System.Collections.Concurrent; using System.IO; using System.Net; using System.Threading; using System.Web; using Composite.C1Console.Events; using Composite.Core; using Composite.Core.Routing; using Composite.Core.WebClient; using Composite.Core.WebClient.Renderings.Page; using Composite.Data.Types; namespace Composite.Data { /// <summary> /// Preserves list of pages that has been rendered since last content/function change /// </summary> public static class PageRenderingHistory { private static readonly string LogTitle = nameof(PageRenderingHistory); private const int MaxRenderErrorsToLog = 10; private const int PageRenderingTimeout = 7000; private const int PageRenderingQueueWaitingTimeout = 15000; private static readonly ConcurrentDictionary<string, object> _renderedPages = new ConcurrentDictionary<string, object>(); private static int _errorCounter; private static readonly object _pageRenderingLock = new object(); static PageRenderingHistory() { GlobalEventSystemFacade.OnDesignChange += () => _renderedPages.Clear(); DataEvents<IPage>.OnAfterUpdate += (sender, args) => PageUpdated((IPage) args.Data); DataEvents<IPage>.OnDeleted += (sender, args) => PageUpdated((IPage)args.Data); DataEvents<IPage>.OnStoreChanged += (sender, args) => { if (!args.DataEventsFired) { _renderedPages.Clear(); } }; } private static string GetCacheKey(IPage page) { var dataSourceId = page.DataSourceId; string localizationInfo = dataSourceId.LocaleScope.ToString(); string dataScope = dataSourceId.DataScopeIdentifier.Name; return page.Id + dataScope + localizationInfo; } /// <summary> /// Indicates whether the page was rendered since the last /// </summary> /// <param name="page"></param> /// <returns></returns> public static bool IsPageRendered(IPage page) { var key = GetCacheKey(page); return _renderedPages.ContainsKey(key); } /// <summary> /// Marks page as rendered. /// </summary> /// <param name="page">The pages.</param> public static void MarkPageAsRendered(IPage page) { var key = GetCacheKey(page); _renderedPages[key] = null; } private static void PageUpdated(IPage page) { object temp; _renderedPages.TryRemove(GetCacheKey(page), out temp); } /// <exclude /> public static void RenderPageIfNotRendered(IPage page) { if (IsPageRendered(page) || PageRenderer.CurrentPageId == page.Id) return; bool lockTaken = false; try { Monitor.TryEnter(_pageRenderingLock, PageRenderingQueueWaitingTimeout, ref lockTaken); if (IsPageRendered(page)) return; try { RenderPage(page); } catch (Exception ex) { string pageUrl = PageUrls.BuildUrl(page) ?? "(no url)"; Log.LogError(LogTitle, "Failed to render page '{0}', Id: {1}", pageUrl, page.Id); Log.LogError(LogTitle, ex); } } finally { if (lockTaken) { Monitor.Exit(_pageRenderingLock); } if (!lockTaken) { if (!IsPageRendered(page)) { Log.LogWarning("DataUrls", "Timeout on page rendering waiting queue"); } } MarkPageAsRendered(page); } } private static void RenderPage(IPage page) { var context = HttpContext.Current; if (context == null) { return; } var urlSpace = new UrlSpace(context) { ForceRelativeUrls = false }; var url = PageUrls.BuildUrl(page, UrlKind.Public, urlSpace) ?? PageUrls.BuildUrl(page, UrlKind.Renderer, urlSpace); if (string.IsNullOrEmpty(url)) { return; } var requestUrl = context.Request.Url; string hostName = requestUrl.Host; if (!url.StartsWith("http", StringComparison.InvariantCultureIgnoreCase)) { string serverUrl = new UrlBuilder(requestUrl.ToString()).ServerUrl; url = UrlUtils.Combine(serverUrl, url); } string cookies = context.Request.Headers["Cookie"]; string responseBody, errorMessage; var result = RenderPage(hostName, url, cookies, out responseBody, out errorMessage); if (result != PageRenderingResult.Successful && Interlocked.Increment(ref _errorCounter) <= MaxRenderErrorsToLog) { Log.LogWarning(LogTitle, $"Failed to render page '{url}' with the goal of collecting dymanic url providers. Result: {result}; Error: {errorMessage}"); } } enum PageRenderingResult { Failed = 0, Successful = 1, Redirect = 2, NotFound = 3 } private static PageRenderingResult RenderPage(string hostname, string url, string cookies, out string responseBody, out string errorMessage) { try { var request = WebRequest.Create(url) as HttpWebRequest; request.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5"; request.Timeout = PageRenderingTimeout; request.AllowAutoRedirect = false; // Some pages may contain redirects to other pages/different websites request.Method = "GET"; request.Headers.Add("Cookie", cookies); request.Host = hostname; int statusCode; using (var response = request.GetResponse() as HttpWebResponse) { statusCode = (int)response.StatusCode; if (statusCode == 200) { using (var responseStream = response.GetResponseStream()) { responseBody = new StreamReader(responseStream).ReadToEnd(); } errorMessage = null; return PageRenderingResult.Successful; } if (statusCode == 301 || statusCode == 302) { responseBody = null; errorMessage = null; return PageRenderingResult.Redirect; } } errorMessage = "Http status: " + statusCode; } catch (WebException ex) { var webResponse = ex.Response as HttpWebResponse; if (webResponse != null && webResponse.StatusCode != HttpStatusCode.OK) { if (webResponse.StatusCode == HttpStatusCode.NotFound) { errorMessage = responseBody = null; return PageRenderingResult.NotFound; } errorMessage = "Http status: " + ((int)webResponse.StatusCode + " " + webResponse.StatusCode); } else { errorMessage = ex.ToString(); } } responseBody = null; return PageRenderingResult.Failed; } } } ================================================ FILE: Composite/Data/PageUrl.cs ================================================ using System; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using Composite.Core.Routing; using Composite.Data.Types; using Composite.Core.WebClient; using Composite.Core.Extensions; using Composite.Core; namespace Composite.Data { /// <summary> /// Page url type /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Use Composite.Core.Routing.PageUrls", true)] public enum PageUrlType { /// <exclude /> Undefined = 0, /// <summary> /// A main url by with a C1 page is accessed. F.e. "/Home/About.aspx" /// </summary> Public = 1, /// <summary> /// A main url by with a C1 page is accessed. F.e. "/Home/About.aspx" /// </summary> [Obsolete("Use 'Public' instead")] Published = 1, /// <summary> /// Unpublihed reference to a page. F.e. "/Renderers/Page.aspx?id=7446ceda-df90-49f0-a183-4e02ed6f6eec" /// </summary> Internal = 2, /// <summary> /// Unpublihed reference to a page. F.e. "/Renderers/Page.aspx?id=7446ceda-df90-49f0-a183-4e02ed6f6eec" /// </summary> [Obsolete("Use 'Internal' instead")] Unpublished = 2, /// <summary> /// Friendly url. A short url, by accessing which C1 will make a redirect to related "public" url /// </summary> Friendly = 3 } /// <summary> /// Represents a page url /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Use Composite.Core.Routing.PageUrls")] public sealed class PageUrl { /// <exclude /> public PageUrl(PublicationScope publicationScope, CultureInfo locale, Guid pageId) : this(publicationScope, locale, pageId, PageUrlType.Undefined) { } /// <exclude /> public PageUrl(PublicationScope publicationScope, CultureInfo locale, Guid pageId, PageUrlType urlType) { Verify.ArgumentNotNull(locale, "locale"); Verify.ArgumentCondition(pageId != Guid.Empty, "pageId", "PageId should not be an empty guid."); this.PublicationScope = publicationScope; Locale = locale; PageId = pageId; UrlType = urlType; } /// <summary> /// Gets the type of the URL. /// </summary> /// <value>The type of the URL.</value> public PageUrlType UrlType { get; private set; } /// <summary> /// Gets the publication scope. /// </summary> /// <value>The publication scope.</value> public PublicationScope PublicationScope { get; private set; } /// <summary> /// Gets the locale. /// </summary> /// <value>The locale.</value> public CultureInfo Locale { get; private set; } /// <summary> /// Gets the page id. /// </summary> /// <value>The page id.</value> public Guid PageId { get; private set; } /// <summary> /// Gets the page. /// </summary> /// <returns></returns> public IPage GetPage() { using(new DataConnection(PublicationScope, Locale)) { return Data.PageManager.GetPageById(PageId); } } /// <summary> /// Builds a url. /// </summary> /// <returns></returns> public UrlBuilder Build() { Verify.That(UrlType != PageUrlType.Undefined, "Url type is undefined"); return Build(UrlType); } /// <summary> /// Builds a url of the the specified URL type. /// </summary> /// <param name="urlType">Type of the URL.</param> /// <returns></returns> public UrlBuilder Build(PageUrlType urlType) { IPage page = GetPage(); if(page == null) { return null; } PageUrlData pageUrlData = new PageUrlData(page); string url = PageUrls.BuildUrl(pageUrlData, ToUrlKind(urlType), new UrlSpace()); return url != null ? new UrlBuilder(url) : null; } private static UrlKind ToUrlKind(PageUrlType pageUrlType) { switch (pageUrlType) { case PageUrlType.Public: return UrlKind.Public; case PageUrlType.Internal: return UrlKind.Internal; case PageUrlType.Friendly: return UrlKind.Friendly; } return UrlKind.Undefined; } /// <summary> /// Parses the specified URL. /// </summary> /// <param name="url">The URL.</param> public static PageUrl Parse(string url) { NameValueCollection queryParameters; return Parse(url, out queryParameters); } /// <summary> /// Parses the specified URL. /// </summary> /// <param name="url">The URL.</param> /// <param name="queryParameters">The query parameters that weren't used to define which page was accessed.</param> /// <returns></returns> [SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.String.Compare(System.String,System.String,System.Boolean)")] [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#")] public static PageUrl Parse(string url, out NameValueCollection queryParameters) { Verify.ArgumentNotNull(url, "url"); var urlBuilder = new UrlBuilder(url); return IsInternalUrl(urlBuilder) ? ParseInternalUrl(urlBuilder, out queryParameters) : ParsePublicUrl(urlBuilder, out queryParameters); } internal static PageUrl ParsePublicUrl(UrlBuilder urlBuilder, out NameValueCollection notUsedQueryParameters) { UrlKind urlKind; PageUrlData pageUrlData = PageUrls.ParseUrl(urlBuilder.ToString(), out urlKind); if (pageUrlData == null || urlKind != UrlKind.Public) { notUsedQueryParameters = null; return null; } notUsedQueryParameters = pageUrlData.QueryParameters; return new PageUrl(pageUrlData.PublicationScope, pageUrlData.LocalizationScope, pageUrlData.PageId, PageUrlType.Public); } internal static CultureInfo GetCultureInfo(string requestPath, out string requestPathWithoutUrlMappingName) { requestPathWithoutUrlMappingName = requestPath; int startIndex = requestPath.IndexOf('/', UrlUtils.PublicRootPath.Length) + 1; if (startIndex >= 0 && requestPath.Length > startIndex) { int endIndex = requestPath.IndexOf('/', startIndex + 1) - 1; if (endIndex >= 0) { string urlMappingName = requestPath.Substring(startIndex, endIndex - startIndex + 1); if (DataLocalizationFacade.UrlMappingNames.Contains(urlMappingName)) { CultureInfo cultureInfo = DataLocalizationFacade.GetCultureInfoByUrlMappingName(urlMappingName); bool exists = DataLocalizationFacade.ActiveLocalizationNames.Contains(cultureInfo.Name); if (exists) { requestPathWithoutUrlMappingName = requestPath.Remove(startIndex - 1, endIndex - startIndex + 2); return cultureInfo; } return null; } } } return DataLocalizationFacade.DefaultUrlMappingCulture; } internal static PageUrl ParseInternalUrl(UrlBuilder urlBuilder, out NameValueCollection notUsedQueryStringParameters) { return ParseQueryString(urlBuilder.GetQueryParameters(), out notUsedQueryStringParameters); } /// <summary> /// To be used for handling 'internal' links. /// </summary> /// <param name="queryString">Query string.</param> /// <param name="notUsedQueryParameters">Query string parameters that were not used.</param> /// <returns></returns> internal static PageUrl ParseQueryString(NameValueCollection queryString, out NameValueCollection notUsedQueryParameters) { if (string.IsNullOrEmpty(queryString["pageId"])) throw new InvalidOperationException("Invalid query string. The 'pageId' parameter of the GUID type is expected."); string dataScopeName = queryString["dataScope"]; PublicationScope publicationScope = PublicationScope.Published; if(dataScopeName != null && string.Compare(dataScopeName, DataScopeIdentifier.AdministratedName, StringComparison.OrdinalIgnoreCase) == 0) { publicationScope = PublicationScope.Unpublished; } string cultureInfoStr = queryString["cultureInfo"]; if (cultureInfoStr.IsNullOrEmpty()) { cultureInfoStr = queryString["CultureInfo"]; } CultureInfo cultureInfo; if (!cultureInfoStr.IsNullOrEmpty()) { cultureInfo = new CultureInfo(cultureInfoStr); } else { cultureInfo = LocalizationScopeManager.CurrentLocalizationScope; if (cultureInfo == CultureInfo.InvariantCulture) { cultureInfo = DataLocalizationFacade.DefaultLocalizationCulture; } } Guid pageId = new Guid(queryString["pageId"]); notUsedQueryParameters = new NameValueCollection(); var queryKeys = new[] { "pageId", "dataScope", "cultureInfo", "CultureInfo" }; var notUsedKeys = queryString.AllKeys.Where(key => !queryKeys.Contains(key, StringComparer.OrdinalIgnoreCase)); foreach (string key in notUsedKeys) { notUsedQueryParameters.Add(key, queryString[key]); } return new PageUrl(publicationScope, cultureInfo, pageId, PageUrlType.Internal); } /// <summary> /// Looks for a friendly URL and set pageUrl if found. /// </summary> /// <param name="relativeUrl">The string to match to a friendly URL</param> /// <param name="pageUrl">The matching page, if a match was found. Otherwise null.</param> /// <returns>True if a friendly URL match was found</returns> public static bool TryParseFriendlyUrl(string relativeUrl, out PageUrl pageUrl) { UrlKind urlKind; PageUrlData pageUrlData = PageUrls.ParseUrl(relativeUrl, new UrlSpace(), out urlKind); if (pageUrlData == null || urlKind != UrlKind.Friendly) { pageUrl = null; return false; } pageUrl = new PageUrl(pageUrlData.PublicationScope, pageUrlData.LocalizationScope, pageUrlData.PageId, PageUrlType.Friendly); return true; } internal static bool IsInternalUrl(string url) { return IsInternalUrl(new UrlBuilder(url)); } internal static bool IsInternalUrl(UrlBuilder url) { return url.FilePath.EndsWith("Renderers/Page.aspx", true); } } } ================================================ FILE: Composite/Data/PhysicalStoreFieldType.cs ================================================  namespace Composite.Data { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum PhysicalStoreFieldType { /// <exclude /> Integer = 1, /// <exclude /> Long = 2, /// <exclude /> String = 3, /// <exclude /> LargeString = 4, /// <exclude /> DateTime = 5, /// <exclude /> Decimal = 6, /// <exclude /> Guid = 7, /// <exclude /> Boolean = 8 } } ================================================ FILE: Composite/Data/Plugins/DataProvider/DataInterfaceValidator.cs ================================================ using System; using System.Text; using System.Reflection; using System.Collections.Generic; using Composite.Core.Types; using Composite.Core.ResourceSystem; namespace Composite.Data.Plugins.DataProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class DataInterfaceValidator { /// <exclude /> public static bool TryValidate(Type interfaceType, out IEnumerable<string> errorMessages) { List<string> errors = new List<string>(); errorMessages = errors; if (interfaceType.IsInterface == false) { string errorMessage = StringResourceSystemFacade.GetString("Composite.Management", "DataInterfaceValidator.TypeNotAnInterface"); errors.Add(string.Format(errorMessage, interfaceType)); } if (typeof(IData).IsAssignableFrom(interfaceType) == false) { string errorMessage = StringResourceSystemFacade.GetString("Composite.Management", "DataInterfaceValidator.TypeDoesNotImplementInterface"); errors.Add(string.Format(errorMessage, interfaceType, typeof(IData))); } PropertyInfo[] properties = interfaceType.GetProperties(); foreach (PropertyInfo propertyInfo in properties) { bool acceptedType = PrimitiveTypes.IsPrimitiveOrNullableType(propertyInfo.PropertyType); if (acceptedType == false) { string errorMessage = StringResourceSystemFacade.GetString("Composite.Management", "DataInterfaceValidator.NotAcceptedType"); errors.Add(string.Format(errorMessage, propertyInfo.PropertyType, interfaceType)); } } return errors.Count == 0; } /// <exclude /> public static bool TryValidate(Type interfaceType) { IEnumerable<string> errorMessages; return TryValidate(interfaceType, out errorMessages); } /// <exclude /> public static bool TryValidate<T>(out IEnumerable<string> errorMessages) where T : class, IData { return TryValidate(typeof(T), out errorMessages); } /// <exclude /> public static bool TryValidate<T>() where T : class, IData { IEnumerable<string> errors; return TryValidate(typeof(T), out errors); } /// <exclude /> public static void Validate(Type interfaceType) { IEnumerable<string> errors; bool res = TryValidate(interfaceType, out errors); if (res == false) { StringBuilder sb = new StringBuilder(); string errorMessage = StringResourceSystemFacade.GetString("Composite.Management", "DataInterfaceValidator.NotValidIDataInterface"); sb.AppendLine(string.Format(errorMessage, interfaceType)); foreach (string error in errors) { sb.AppendLine(error); } throw new ArgumentException(sb.ToString()); } } /// <exclude /> public static void Validate<T>() where T : class, IData { Validate(typeof(T)); } } } ================================================ FILE: Composite/Data/Plugins/DataProvider/DataProviderConfigurationServices.cs ================================================ using System; using System.Linq; using Composite.Core.Configuration; using Composite.Data.Plugins.DataProvider.Runtime; namespace Composite.Data.Plugins.DataProvider { internal static class DataProviderConfigurationServices { public static DataProviderData GetDataProviderConfiguration(string providerName) { DataProviderSettings settings = (DataProviderSettings)ConfigurationServices.ConfigurationSource.GetSection(DataProviderSettings.SectionName); if (settings.DataProviderPlugins.Contains(providerName) == false) throw new ArgumentException("Unknown provider name", "providerName"); return settings.DataProviderPlugins.Get(providerName); } } } ================================================ FILE: Composite/Data/Plugins/DataProvider/DataProviderContext.cs ================================================ using System; using System.Globalization; using Composite.Core.Extensions; using Composite.Data.Foundation.CodeGeneration; namespace Composite.Data.Plugins.DataProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DataProviderContext { private readonly string _providerName; /// <exclude /> public DataProviderContext(string providerName) { Verify.ArgumentNotNullOrEmpty(providerName, "providerName"); _providerName = providerName; } /// <exclude /> public string ProviderName { get { return _providerName; } } /// <exclude /> public DataSourceId CreateDataSourceId(IDataId dataId, Type interfaceType) { Verify.ArgumentNotNull(dataId, "dataId"); Verify.ArgumentNotNull(interfaceType, "interfaceType"); Verify.ArgumentCondition(typeof(IData).IsAssignableFrom(interfaceType), "interfaceType", "The interface type '{0}' does not inherit the interface '{1}'".FormatWith(interfaceType, typeof(IData))); return new DataSourceId(dataId, _providerName, interfaceType, DataScopeManager.MapByType(interfaceType), LocalizationScopeManager.MapByType(interfaceType)); } /// <exclude /> public DataSourceId CreateDataSourceId(IDataId dataId, Type interfaceType, DataScopeIdentifier dataScopeIdentifier, CultureInfo cultureInfo) { Verify.ArgumentNotNull(dataId, "dataId"); Verify.ArgumentNotNull(interfaceType, "interfaceType"); Verify.ArgumentNotNull(dataScopeIdentifier, "dataScopeIdentifier"); Verify.ArgumentNotNull(cultureInfo, "cultureInfo"); Verify.ArgumentCondition(typeof(IData).IsAssignableFrom(interfaceType), "interfaceType", "The interface type '{0}' does not inherit the interface '{1}'".FormatWith(interfaceType, typeof(IData))); return new DataSourceId(dataId, _providerName, interfaceType, dataScopeIdentifier, cultureInfo); } /// <exclude /> public void UpdateDataSourceId(IData data, IDataId dataId, Type interfaceType) { Verify.ArgumentNotNull(data, "data"); Verify.ArgumentNotNull(dataId, "dataId"); Verify.ArgumentNotNull(interfaceType, "interfaceType"); Verify.ArgumentCondition(typeof(IData).IsAssignableFrom(interfaceType), "interfaceType", "The interface type '{0}' does not inherit the interface '{1}'".FormatWith(interfaceType, typeof(IData))); var emptyDataClassBase = data as EmptyDataClassBase; if (emptyDataClassBase == null) { throw new InvalidOperationException("Updates on DataSourceIds can only be done on objects that are returned by the DataFacade.BuildNew<T>() method"); } if (emptyDataClassBase.DataSourceId.ExistsInStore) { throw new InvalidOperationException("Updates on DataSourceIds can only be done once"); } emptyDataClassBase.DataSourceId = CreateDataSourceId(dataId, interfaceType); } /// <exclude /> public void UpdateDataSourceIdDataScope(IData data) { Verify.ArgumentNotNull(data, "data"); data.DataSourceId.DataScopeIdentifier = DataScopeManager.MapByType(data); } } } ================================================ FILE: Composite/Data/Plugins/DataProvider/DataProviderData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Data.Plugins.DataProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ConfigurationElementType(typeof(NonConfigurableDataProvider))] public class DataProviderData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/Data/Plugins/DataProvider/IDataProvider.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Data.Plugins.DataProvider.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Data.Plugins.DataProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [CustomFactory(typeof(DataProviderCustomFactory))] [ConfigurationNameMapper(typeof(DataProviderDefaultNameRetriever))] public interface IDataProvider { /// <summary> /// This is set by the system and is used to create DataSourceId's /// </summary> DataProviderContext Context { set; } /// <summary> /// This method should return all supported data interfaces. /// That is, all data interfaces that this provider is currently handling. /// </summary> /// <returns></returns> IEnumerable<Type> GetSupportedInterfaces(); /// <exclude /> IQueryable<T> GetData<T>() where T : class, IData; /// <summary> /// This method should return null if the given dataId does not correspond to an IData /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dataId"></param> /// <returns></returns> T GetData<T>(IDataId dataId) where T : class, IData; } } ================================================ FILE: Composite/Data/Plugins/DataProvider/IDynamicDataProvider.cs ================================================ using System; using System.Collections.Generic; using Composite.Data.DynamicTypes; namespace Composite.Data.Plugins.DataProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IDynamicDataProvider : IDataProvider { /// <summary> /// This method should return ALL data interface that the provider knows. Including /// currently not supported interface due to configuratoion and/or store errors. /// </summary> /// <returns></returns> IEnumerable<Type> GetKnownInterfaces(); /// <exclude /> void CreateStores(IReadOnlyCollection<DataTypeDescriptor> typeDescriptor); /// <summary> /// /// </summary> /// <param name="updateDataTypeDescriptor"></param> /// <param name="forceCompile">If this is true and the provider uses dynamic compilations. It should compile its helper regardless.</param> void AlterStore(UpdateDataTypeDescriptor updateDataTypeDescriptor, bool forceCompile); /// <exclude /> void DropStore(DataTypeDescriptor typeDescriptor); } } ================================================ FILE: Composite/Data/Plugins/DataProvider/IFileSystemDataProvider.cs ================================================ using Composite.Data.Types; namespace Composite.Data.Plugins.DataProvider { /// <summary> /// This should be implemented by DataProviders that provies IFile data items. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IFileSystemDataProvider : IDataProvider { /// <summary> /// This method is called when the absolute file path needs validation. /// Only the data provider knows the base path, so its responsible for /// creating the full absolute path from an IFile. /// </summary> /// <typeparam name="TFile">An IFile or an sub interface</typeparam> /// <param name="file">The IFile instance</param> /// <param name="errorMessage">Will contain the error message, if any</param> /// <returns>Returns false if something is wrong with the path and <paramref name="errorMessage"/> will contain the error message. Otherwice true.</returns> bool ValidatePath<TFile>(TFile file, out string errorMessage) where TFile : IFile; } } ================================================ FILE: Composite/Data/Plugins/DataProvider/IGeneratedTypesDataProvider.cs ================================================ using System; using System.Collections.Generic; namespace Composite.Data.Plugins.DataProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IGeneratedTypesDataProvider : IDataProvider, IDynamicDataProvider, IWritableDataProvider { /// <summary> /// This method should return all genereted data interface types that the provider supports, /// and nothing more. /// </summary> /// <returns></returns> IEnumerable<Type> GetGeneratedInterfaces(); } } ================================================ FILE: Composite/Data/Plugins/DataProvider/ILocalizedDataProvider.cs ================================================ using System.Globalization; namespace Composite.Data.Plugins.DataProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface ILocalizedDataProvider : IDataProvider { /// <exclude /> void AddLocale(CultureInfo cultureInfo); /// <exclude /> void RemoveLocale(CultureInfo cultureInfo); } } ================================================ FILE: Composite/Data/Plugins/DataProvider/ISupportCaching.cs ================================================ namespace Composite.Data.Plugins.DataProvider { internal interface ISupportCachingDataProvider: IDataProvider { bool AllowResultsWrapping { get; } } } ================================================ FILE: Composite/Data/Plugins/DataProvider/IWritableDataProvider.cs ================================================ using System.Collections.Generic; namespace Composite.Data.Plugins.DataProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IWritableDataProvider : IDataProvider { /// <exclude /> void Update(IEnumerable<IData> datas); /// <exclude /> List<T> AddNew<T>(IEnumerable<T> datas) where T : class, IData; /// <exclude /> void Delete(IEnumerable<DataSourceId> dataSourceIds); } } ================================================ FILE: Composite/Data/Plugins/DataProvider/NonConfigurableDataProvider.cs ================================================ using System; using Microsoft.Practices.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Data.Plugins.DataProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Assembler(typeof(NonConfigurableDataProviderAssembler))] public sealed class NonConfigurableDataProvider : DataProviderData { } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class NonConfigurableDataProviderAssembler : IAssembler<IDataProvider, DataProviderData> { /// <exclude /> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IDataProvider Assemble(IBuilderContext context, DataProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IDataProvider)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/Data/Plugins/DataProvider/Runtime/DataProviderCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Data.Plugins.DataProvider.Runtime { internal sealed class DataProviderCustomFactory : AssemblerBasedCustomFactory<IDataProvider, DataProviderData> { protected override DataProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { DataProviderSettings settings = configurationSource.GetSection(DataProviderSettings.SectionName) as DataProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", DataProviderSettings.SectionName)); } return settings.DataProviderPlugins.Get(name); } } } ================================================ FILE: Composite/Data/Plugins/DataProvider/Runtime/DataProviderDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Data.Plugins.DataProvider.Runtime { internal sealed class DataProviderDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/Data/Plugins/DataProvider/Runtime/DataProviderFactory.cs ================================================ using System; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Data.Plugins.DataProvider.Runtime { internal interface IDataProviderFactory { IDataProvider Create(string dataProviderName); } internal sealed class ConfigurationDataProviderFactory : NameTypeFactoryBase<IDataProvider>, IDataProviderFactory { public ConfigurationDataProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } IDataProvider IDataProviderFactory.Create(string dataProviderName) { return base.Create(dataProviderName); } } } ================================================ FILE: Composite/Data/Plugins/DataProvider/Runtime/DataProviderSettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Data.Plugins.DataProvider.Runtime { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DataProviderSettings : SerializableConfigurationSection { /// <exclude /> public const string SectionName = "Composite.Data.Plugins.DataProviderConfiguration"; private const string _defaultDynamicTypeDataProviderNameProperty = "defaultDynamicTypeDataProviderName"; /// <exclude /> [ConfigurationProperty(_defaultDynamicTypeDataProviderNameProperty, IsRequired = true)] public string DefaultDynamicTypeDataProviderName { get { return (string)base[_defaultDynamicTypeDataProviderNameProperty]; } set { base[_defaultDynamicTypeDataProviderNameProperty] = value; } } private const string _dataProviderPluginsProperty = "DataProviderPlugins"; /// <exclude /> [ConfigurationProperty(_dataProviderPluginsProperty)] public NameTypeManagerTypeConfigurationElementCollection<DataProviderData> DataProviderPlugins { get { return (NameTypeManagerTypeConfigurationElementCollection<DataProviderData>)base[_dataProviderPluginsProperty]; } } } } ================================================ FILE: Composite/Data/Plugins/DataProvider/Streams/FileChangeNotificator.cs ================================================ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Threading; using Composite.Core.Collections.Generic; using Composite.Core.IO; using Composite.Core.Types; using Composite.Data.Streams; using System.IO; using Composite.Core; namespace Composite.Data.Plugins.DataProvider.Streams { internal static class FileChangeNotificator { private static readonly object _syncRoot = new object(); private static C1FileSystemWatcher _fileWatcher; private static int _counter; // We're holding only weak reference to subscriber objects, in order to avoid memory leaks private static readonly Hashtable<string, ReadOnlyCollection<Pair<MethodInfo, WeakReference>>> _subscribers = new Hashtable<string, ReadOnlyCollection<Pair<MethodInfo, WeakReference>>>(); private static void EnsureInitialization() { if (_fileWatcher != null) { return; } lock (_syncRoot) { if (_fileWatcher != null) { return; } _fileWatcher = new C1FileSystemWatcher(AppDomain.CurrentDomain.BaseDirectory) { IncludeSubdirectories = true, NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite, InternalBufferSize = 32768 }; // _fileWatcher.Created += FileWatcher_Created; _fileWatcher.Changed += FileWatcher_Changed; _fileWatcher.Deleted += FileWatcher_Deleted; _fileWatcher.EnableRaisingEvents = true; } } static void FileWatcher_Deleted(object sender, FileSystemEventArgs e) { FireFileChangedEvent(e.FullPath, FileChangeType.Deleted); } static void FileWatcher_Changed(object sender, FileSystemEventArgs e) { FileChangeType changeType = e.ChangeType == WatcherChangeTypes.Renamed ? FileChangeType.Renamed : FileChangeType.Modified; FireFileChangedEvent(e.FullPath, changeType); } //static void FileWatcher_Created(object sender, FileSystemEventArgs e) //{ // // Do nothing... //} private static void FireFileChangedEvent(string filePath, FileChangeType changeType) { filePath = filePath.ToLowerInvariant(); ReadOnlyCollection<Pair<MethodInfo, WeakReference>> weakInvocationList; if (!_subscribers.TryGetValue(filePath.ToLowerInvariant(), out weakInvocationList)) { return; } var parameters = new object[] { filePath, changeType }; foreach (var callInfo in weakInvocationList) { try { if (callInfo.Second == null) // Call to a static method { callInfo.First.Invoke(null, parameters); } else { object target = callInfo.Second.Target; if (target != null) // Checking if object is alive { callInfo.First.Invoke(target, parameters); } } } catch (Exception ex) { Log.LogError(nameof(FileChangeNotificator), ex); } } } public static void Subscribe(FileSystemFileBase file, OnFileChangedDelegate handler) { Verify.ArgumentNotNull(file, "file"); Subscribe(file.SystemPath, handler); } public static void Subscribe(string filePath, OnFileChangedDelegate handler) { Verify.ArgumentNotNullOrEmpty(filePath, "filePath"); Verify.ArgumentNotNull(handler, "handler"); EnsureInitialization(); int counterValue = Interlocked.Increment(ref _counter); if (counterValue % 100 == 0) { ClearDeadReferences(); } var weakInvocationList = new List<Pair<MethodInfo, WeakReference>>(); foreach (Delegate func in handler.GetInvocationList()) { var targetObject = func.Target; if (targetObject == null) { weakInvocationList.Add(new Pair<MethodInfo, WeakReference>(func.Method, null)); } else { weakInvocationList.Add(new Pair<MethodInfo, WeakReference>(func.Method, new WeakReference(handler.Target))); } } string key = filePath.ToLowerInvariant(); lock (_syncRoot) { if (_subscribers.ContainsKey(key)) { ReadOnlyCollection<Pair<MethodInfo, WeakReference>> oldList = _subscribers[key]; var newList = new ReadOnlyCollection<Pair<MethodInfo, WeakReference>>( new List<Pair<MethodInfo, WeakReference>>(oldList.Concat(weakInvocationList))); _subscribers[key] = newList; } else { _subscribers.Add(key, new ReadOnlyCollection<Pair<MethodInfo, WeakReference>>(weakInvocationList)); } } } private static void ClearDeadReferences() { lock(_syncRoot) { ICollection<string> keys = _subscribers.GetKeys(); foreach(string key in keys) { ReadOnlyCollection<Pair<MethodInfo, WeakReference>> currentList = _subscribers[key]; int countOfAlive = currentList.Count(pair => pair.Second == null || pair.Second.IsAlive); if(countOfAlive == 0) { _subscribers.Remove(key); continue; } if (countOfAlive == currentList.Count) { continue; } var newList = new List<Pair<MethodInfo, WeakReference>>( currentList.Where(pair => pair.Second == null || pair.Second.IsAlive)); _subscribers[key] = new ReadOnlyCollection<Pair<MethodInfo, WeakReference>>(newList); } } } } } ================================================ FILE: Composite/Data/Plugins/DataProvider/Streams/FileSystemFileBase.cs ================================================ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.IO; namespace Composite.Data.Plugins.DataProvider.Streams { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class FileSystemFileBase { /// <exclude /> [SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] protected FileStream TemporaryFileStream { get; set; } /// <exclude /> protected string TemporaryFilePath { get; set; } /// <exclude /> public virtual string SystemPath { get; set; } /// <exclude /> [SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] [SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public FileStream GetNewWriteStream() { if (TemporaryFileStream != null) { Verify.That(!TemporaryFileStream.CanWrite, "Stream for writing has not been closed."); TemporaryFileStream = null; File.Delete(TemporaryFilePath); } string tempFile = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.TempDirectory), "upload" + Path.GetRandomFileName()); this.TemporaryFilePath = tempFile; this.TemporaryFileStream = File.Open(tempFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None); return TemporaryFileStream; } /// <exclude /> [SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] public Stream GetReadStream() { string filePath; if (this.TemporaryFileStream != null) { Verify.That(!TemporaryFileStream.CanWrite, "Stream for writing has not been closed."); filePath = this.TemporaryFilePath; } else { filePath = this.SystemPath; } return new FileStream(filePath, FileMode.Open, FileAccess.Read); } /// <exclude /> [SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void CommitChanges() { if (this.TemporaryFileStream == null) return; Verify.That(!TemporaryFileStream.CanWrite, "Stream for writing has not been closed."); DirectoryUtils.EnsurePath(this.SystemPath); if (!this.SystemPath.IsNullOrEmpty()) { File.Delete(this.SystemPath); } File.Move(this.TemporaryFilePath, this.SystemPath); this.TemporaryFileStream = null; this.TemporaryFilePath = null; } } } ================================================ FILE: Composite/Data/Plugins/DataProvider/Streams/FileSystemFileStreamManager.cs ================================================ using System; using System.IO; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Data.Streams; using Composite.Data.Types; namespace Composite.Data.Plugins.DataProvider.Streams { internal sealed class FileSystemFileStreamManager : IFileStreamManager { public Stream GetReadStream(IFile file) { Verify.ArgumentNotNull(file, "file"); Verify.ArgumentCondition(file is FileSystemFileBase, "file", "The type '{0}' does not inherit the class '{1}'".FormatWith(file.GetType(), typeof(FileSystemFileBase))); var baseFile = file as FileSystemFileBase; return baseFile.GetReadStream(); } public Stream GetNewWriteStream(IFile file) { Verify.ArgumentNotNull(file, "file"); Verify.ArgumentCondition(file is FileSystemFileBase, "file", "The type '{0}' does not inherit the class '{1}'".FormatWith(file.GetType(), typeof(FileSystemFileBase))); var baseFile = file as FileSystemFileBase; return baseFile.GetNewWriteStream(); } internal static void DeleteFile(string filename) { Verify.ArgumentNotNullOrEmpty(filename, "filename"); DirectoryUtils.DeleteFile(filename, true); } internal static void DeleteFile(IFile file) { Verify.ArgumentNotNull(file, "file"); Verify.ArgumentCondition(file is FileSystemFileBase, "file", "The type '{0}' does not inherit the class '{1}'".FormatWith(file.GetType(), typeof(FileSystemFileBase))); var baseFile = file as FileSystemFileBase; DeleteFile(baseFile.SystemPath); } internal static void WriteFileToDisk(IFile file) { Verify.ArgumentNotNull(file, "file"); Verify.ArgumentCondition(file is FileSystemFileBase, "file", "The type '{0}' does not inherit the class '{1}'".FormatWith(file.GetType(), typeof(FileSystemFileBase))); var baseFile = file as FileSystemFileBase; baseFile.CommitChanges(); } public void SubscribeOnFileChanged(IFile file, OnFileChangedDelegate handler) { FileChangeNotificator.Subscribe(file as FileSystemFileBase, handler); } } } ================================================ FILE: Composite/Data/Plugins/DataProvider/Streams/TransactionFileSystemFileStreamManager.cs ================================================ using System; using System.IO; using System.Transactions; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Data.Streams; using Composite.Data.Types; namespace Composite.Data.Plugins.DataProvider.Streams { internal sealed class TransactionFileSystemFileStreamManager : IFileStreamManager { public Stream GetReadStream(IFile file) { Verify.ArgumentNotNull(file, "file"); Verify.ArgumentCondition(file is FileSystemFileBase, "file", "The type '{0}' does not inherit the class '{1}'".FormatWith(file.GetType(), typeof(FileSystemFileBase))); var baseFile = file as FileSystemFileBase; return baseFile.GetReadStream(); } public Stream GetNewWriteStream(IFile file) { Verify.ArgumentNotNull(file, "file"); Verify.ArgumentCondition(file is FileSystemFileBase, "file", "The type '{0}' does not inherit the class '{1}'".FormatWith(file.GetType(), typeof(FileSystemFileBase))); var baseFile = file as FileSystemFileBase; return baseFile.GetNewWriteStream(); } internal static void DeleteFile(string filename) { Verify.ArgumentNotNullOrEmpty(filename, "filename"); DirectoryUtils.DeleteFile(filename, true); } internal static void DeleteFile(IFile file) { Verify.ArgumentNotNull(file, "file"); FileSystemFileBase baseFile = file as FileSystemFileBase; Verify.ArgumentCondition(baseFile != null, "file", "The type '{0}' does not inherit the class '{1}'" .FormatWith(file.GetType(), typeof(FileSystemFileBase))); if (Transaction.Current == null) { LogNoTransaction(); DeleteFile(baseFile.SystemPath); } else { Transaction.Current.EnlistVolatile(new DeleteEnlistment(baseFile), EnlistmentOptions.None); } } internal static void WriteFileToDisk(IFile file) { Verify.ArgumentNotNull(file, "file"); FileSystemFileBase baseFile = file as FileSystemFileBase; Verify.ArgumentCondition(baseFile != null, "file", "The type '{0}' does not inherit the class '{1}'" .FormatWith(file.GetType(), typeof(FileSystemFileBase))); if (Transaction.Current == null) { LogNoTransaction(); baseFile.CommitChanges(); } else { Transaction.Current.EnlistVolatile(new WriteToDiskEnlistment(file, baseFile), EnlistmentOptions.None); } } private static void LogNoTransaction() { if (RuntimeInformation.IsDebugBuild) { Log.LogWarning("Transaction not active", "There is no current transaction that the File System File Stream manager can attach to."); } } public void SubscribeOnFileChanged(IFile file, OnFileChangedDelegate handler) { FileChangeNotificator.Subscribe(file as FileSystemFileBase, handler); } private class WriteToDiskEnlistment : IEnlistmentNotification { private IFile file; private FileSystemFileBase baseFile; public WriteToDiskEnlistment(IFile file, FileSystemFileBase baseFile) { this.file = file; this.baseFile = baseFile; } public void Commit(Enlistment enlistment) { baseFile.CommitChanges(); enlistment.Done(); } public void InDoubt(Enlistment enlistment) { enlistment.Done(); } public void Prepare(PreparingEnlistment preparingEnlistment) { preparingEnlistment.Prepared(); } public void Rollback(Enlistment enlistment) { enlistment.Done(); } } private class DeleteEnlistment : IEnlistmentNotification { private FileSystemFileBase baseFile; public DeleteEnlistment(FileSystemFileBase baseFile) { this.baseFile = baseFile; } public void Commit(Enlistment enlistment) { DeleteFile(baseFile.SystemPath); enlistment.Done(); } public void InDoubt(Enlistment enlistment) { enlistment.Done(); } public void Prepare(PreparingEnlistment preparingEnlistment) { preparingEnlistment.Prepared(); } public void Rollback(Enlistment enlistment) { enlistment.Done(); } } } } ================================================ FILE: Composite/Data/Plugins/DataProvider/TransformQueryable/TransformQueryable.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Data.Plugins.DataProvider.TransformQueryable.Foundation; using Composite.Linq; namespace Composite.Data.Plugins.DataProvider.TransformQueryable { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class TransformQueryable<T> : IOrderedQueryable<T>, ITransformQueryable, IQueryProvider { private IQueryable _source; private TypeMappings _typeMappings; private PropertyMappings _propertyMappings; private SelectParameterMappings _selectParameterMappings; private ContainerClassMappings _containerClassMappings; private Expression _currentExpression; public TransformQueryable(IQueryable source, TypeMappings typeMappings, PropertyMappings propertyMappings, SelectParameterMappings selectParameterMappings, ContainerClassMappings containerClassMappings) { if (source == null) throw new ArgumentNullException("source"); if (typeMappings == null) throw new ArgumentNullException("typeMappings"); if (propertyMappings == null) throw new ArgumentNullException("propertyMappings"); if (selectParameterMappings == null) throw new ArgumentNullException("selectParameterMappings"); if (containerClassMappings == null) throw new ArgumentNullException("containerClassFieldMappings"); _source = source; _typeMappings = typeMappings; _propertyMappings = propertyMappings; _selectParameterMappings = selectParameterMappings; _containerClassMappings = containerClassMappings; _currentExpression = Expression.Constant(this); } public TransformQueryable(IQueryable source, TypeMappings typeMappings, PropertyMappings propertyMappings, SelectParameterMappings selectParameterMappings, ContainerClassMappings containerClassMappings, Expression currentExpression) { if (source == null) throw new ArgumentNullException("source"); if (typeMappings == null) throw new ArgumentNullException("typeMappings"); if (propertyMappings == null) throw new ArgumentNullException("propertyMappings"); if (selectParameterMappings == null) throw new ArgumentNullException("selectParameterMappings"); if (containerClassMappings == null) throw new ArgumentNullException("containerClassFieldMappings"); if (currentExpression == null) throw new ArgumentNullException("currentExpression"); _source = source; _typeMappings = typeMappings; _propertyMappings = propertyMappings; _selectParameterMappings = selectParameterMappings; _containerClassMappings = containerClassMappings; _currentExpression = currentExpression; } public IQueryable<S> CreateQuery<S>(Expression expression) { return new TransformQueryable<S>(_source, _typeMappings, _propertyMappings, _selectParameterMappings, _containerClassMappings, expression); } public S Execute<S>(Expression expression) { TransformMappingsMergerExpressionVisitor mergerVisitor = new TransformMappingsMergerExpressionVisitor(); mergerVisitor.Visit(expression); TransformSelectInserterExpressionVisitor selectInserterVisitor = new TransformSelectInserterExpressionVisitor(mergerVisitor.TypeMappings); expression = selectInserterVisitor.Visit(expression); TransformExpressionVisitor visitor = new TransformExpressionVisitor( _source, mergerVisitor.TypeMappings, mergerVisitor.PropertyMappings, mergerVisitor.SelectParameterMappings, mergerVisitor.ContainerClassMappings); Expression newExpression = visitor.Visit(expression); return (S)_source.Provider.Execute(newExpression); } public IEnumerator<T> GetEnumerator() { TransformMappingsMergerExpressionVisitor mergerVisitor = new TransformMappingsMergerExpressionVisitor(); mergerVisitor.Visit(_currentExpression); TransformSelectInserterExpressionVisitor selectInserterVisitor = new TransformSelectInserterExpressionVisitor(mergerVisitor.TypeMappings); Expression newExpression = selectInserterVisitor.Visit(_currentExpression); TransformExpressionVisitor visitor = new TransformExpressionVisitor( _source, mergerVisitor.TypeMappings, mergerVisitor.PropertyMappings, mergerVisitor.SelectParameterMappings, mergerVisitor.ContainerClassMappings); newExpression = visitor.Visit(newExpression); IQueryable<T> queryable = (IQueryable<T>)_source.Provider.CreateQuery(newExpression); return queryable.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { MethodInfo methodInfo = TransformQueryableCache.GetTransformQueryableGetEnumeratorMethodInfo(typeof(T)); return (IEnumerator)methodInfo.Invoke(this, null); } public IQueryable CreateQuery(Expression expression) { if (_currentExpression == expression) return this; Type elementType = TypeHelpers.FindElementType(expression); Type queryableType = TransformQueryableCache.GetTransformQueryableType(elementType); return (IQueryable)Activator.CreateInstance( queryableType, new object[] { _source, _typeMappings, _propertyMappings, _selectParameterMappings, _containerClassMappings, expression }); } public Type ElementType { get { return typeof(T); } } public object Execute(Expression expression) { MethodInfo methodInfo = TransformQueryableCache.GetTransformQueryableExecuteMethodInfo(typeof(T), expression.Type); return methodInfo.Invoke(this, new object[] { expression }); } public Expression Expression { get { return _currentExpression; } } IQueryable ITransformQueryable.Source { get { return _source; } } TypeMappings ITransformQueryable.TypeMappings { get { return _typeMappings; } } PropertyMappings ITransformQueryable.PropertyMappings { get { return _propertyMappings; } } SelectParameterMappings ITransformQueryable.SelectParameterMappings { get { return _selectParameterMappings; } } ContainerClassMappings ITransformQueryable.ContainerClassMappings { get { return _containerClassMappings; } } public IQueryProvider Provider { get { return this; } } } } ================================================ FILE: Composite/Data/ProcessControlled/ActionIconResourceHandleAttribute.cs ================================================ using System; using Composite.Core.ResourceSystem; namespace Composite.Data.ProcessControlled { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] internal sealed class ActionResourceHandleAttribute : Attribute { public ActionResourceHandleAttribute(string actionTypeName, string resourceNamespace, string resourceName) { this.ActionTypeName = actionTypeName; this.ActionResourceHandle = new ResourceHandle(resourceNamespace, resourceName); } public string ActionTypeName { get; private set; } public ResourceHandle ActionResourceHandle { get; private set; } } } ================================================ FILE: Composite/Data/ProcessControlled/ActionRoleProviderAttribute.cs ================================================ using System; namespace Composite.Data.ProcessControlled { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] internal sealed class ActionPermissionTypeProviderAttribute : Attribute { public ActionPermissionTypeProviderAttribute(string actionTypeName, Type actionPermissionTypeProviderType) { this.ActionTypeName = actionTypeName; this.ActionPermissionTypeProviderType = actionPermissionTypeProviderType; } public string ActionTypeName { get; private set; } public Type ActionPermissionTypeProviderType { get; private set; } } } ================================================ FILE: Composite/Data/ProcessControlled/ActionTokenProviderAttribute.cs ================================================ using System; namespace Composite.Data.ProcessControlled { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] internal sealed class ActionTokenProviderAttribute : Attribute { public ActionTokenProviderAttribute(string actionTypeName, Type actionTokenProviderType) { this.ActionTypeName = actionTypeName; this.ActionTokenProviderType = actionTokenProviderType; } public string ActionTypeName { get; private set; } public Type ActionTokenProviderType { get; private set; } } } ================================================ FILE: Composite/Data/ProcessControlled/IActionRoleProvider.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Security; namespace Composite.Data.ProcessControlled { internal interface IActionPermissionTypeProvider { IEnumerable<PermissionType> GetActionPermissionTypes(string actionTypeName, IData data); } } ================================================ FILE: Composite/Data/ProcessControlled/IActionTokenProvider.cs ================================================ using Composite.C1Console.Security; namespace Composite.Data.ProcessControlled { internal interface IActionTokenProvider { ActionToken GetActionToken(string actionTypeName, IData data); } } ================================================ FILE: Composite/Data/ProcessControlled/ILocalizeProcessController.cs ================================================ using Composite.Data.ProcessControlled.ProcessControllers.GenericLocalizeProcessController; namespace Composite.Data.ProcessControlled { internal interface ILocalizeProcessController : IProcessController { bool OnAfterBuildNew(IData data); } } ================================================ FILE: Composite/Data/ProcessControlled/ILocalizedControlled.cs ================================================ using Composite.Data.ProcessControlled.ProcessControllers.GenericLocalizeProcessController; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.ProcessControlled { /// <summary> /// Implement this interface to allow your data type to exist in multiple language scopes (i.e. enable localizing of data). /// </summary> [LocalizeProcessControllerType(typeof(GenericLocalizeProcessController))] public interface ILocalizedControlled : IProcessControlled { /// <summary> /// The locale data originaled from. This field is automatically maintaned, do not set it unless implementing localization logic. /// </summary> [StoreFieldType(PhysicalStoreFieldType.String, 16)] [ImmutableFieldId("{0456EBB0-7FB1-46cd-9A23-4AE9AA3337FA}")] [NotNullValidator] [DefaultFieldStringValue("")] // Invariant string SourceCultureName { get; set; } } } ================================================ FILE: Composite/Data/ProcessControlled/IProcessControlled.cs ================================================ namespace Composite.Data.ProcessControlled { /// <summary> /// This interface is for internal use. DO NOT INHERIT /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IProcessControlled : IData { } } ================================================ FILE: Composite/Data/ProcessControlled/IProcessController.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Elements; namespace Composite.Data.ProcessControlled { /// <summary> /// Providers element actions for data types that have attributes inherited from <see cref="Composite.Data.ProcessControllerTypeAttribute"/> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IProcessController { /// <exclude /> List<ElementAction> GetActions(IData data, Type elementProviderType); } } ================================================ FILE: Composite/Data/ProcessControlled/IPublishControlled.cs ================================================ namespace Composite.Data.ProcessControlled { /// <summary> /// Add this interface to your data type to support publication workflow. /// </summary> [DataScope(DataScopeIdentifier.PublicName)] [DataScope(DataScopeIdentifier.AdministratedName)] public interface IPublishControlled : IProcessControlled { /// <summary> /// The workflow status of data. /// </summary> [StoreFieldType(PhysicalStoreFieldType.String, 64, IsNullable = false)] [ImmutableFieldId("{FAB1CF0C-66B0-11DC-A47E-CF6356D89593}")] [DefaultFieldStringValue("")] [FieldPosition(50)] [SearchableField(false, true, true)] string PublicationStatus { get; set; } } } ================================================ FILE: Composite/Data/ProcessControlled/IPublishControlledAuxiliary.cs ================================================  namespace Composite.Data.ProcessControlled { internal interface IPublishControlledAuxiliary { /// <summary> /// This method will be called after the IPublishProcessController.OnAfterDataUpdated has been called /// </summary> /// <param name="data"></param> void OnAfterDataUpdated(IData data); /// <summary> /// This method will be called after the IPublishProcessController.OnAfterBuildNew has been called /// </summary> /// <param name="data"></param> void OnAfterBuildNew(IData data); } } ================================================ FILE: Composite/Data/ProcessControlled/IPublishProcessController.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Elements; namespace Composite.Data.ProcessControlled { internal interface IPublishProcessController : IProcessController { void SetStartStatus(IData data); IDictionary<string, string> GetValidTransitions(IData data); /// <summary> /// Returns true if auxilaries should be called, false if they should not be called /// </summary> /// <param name="data"></param> /// <returns></returns> bool OnAfterDataUpdated(IData data); /// <summary> /// Returns true if auxilaries should be called, false if they should not be called /// </summary> /// <param name="data"></param> /// <returns></returns> bool OnAfterBuildNew(IData data); void ValidateTransition(IData data, string status); } } ================================================ FILE: Composite/Data/ProcessControlled/IgnoreActionAttribute.cs ================================================ using System; namespace Composite.Data.ProcessControlled { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] internal sealed class IgnoreActionAttribute : Attribute { public IgnoreActionAttribute(string actionTypeName) { this.ActionTypeName = actionTypeName; } public string ActionTypeName { get; private set; } } } ================================================ FILE: Composite/Data/ProcessControlled/ProcessControllerAttributesFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Core.Collections.Generic; using Composite.C1Console.Events; using Composite.Core.Types; using Composite.Core.ResourceSystem; using Composite.Core.Logging; namespace Composite.Data.ProcessControlled { internal static class ProcessControllerAttributesFacade { private static ResourceLocker<Resources> _resourceLocker = new ResourceLocker<Resources>(new Resources(), Resources.DoInitialize); static ProcessControllerAttributesFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static bool IsActionIgnored(Type elementProviderType, string actionTypeName) { List<string> ignoredActionTypes; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.IgnoreActionCache.TryGetValue(elementProviderType, out ignoredActionTypes) == false) { ignoredActionTypes = (from t in elementProviderType.GetCustomAttributesRecursively<IgnoreActionAttribute>() select t.ActionTypeName).Distinct().ToList(); _resourceLocker.Resources.IgnoreActionCache.Add(elementProviderType, ignoredActionTypes); } } return ignoredActionTypes.Contains(actionTypeName); } public static IActionTokenProvider GetActionTokenProvider(Type elementProviderType, string actionTypeName) { Dictionary<string, IActionTokenProvider> actionTokenProviders; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.ActionTokenProviderCache.TryGetValue(elementProviderType, out actionTokenProviders) == false) { actionTokenProviders = new Dictionary<string, IActionTokenProvider>(); var pairs = (from t in elementProviderType.GetCustomAttributesRecursively<ActionTokenProviderAttribute>() select new { ActionTypeName = t.ActionTypeName, ActionTokenProviderType = t.ActionTokenProviderType }); foreach (var pair in pairs) { if (actionTokenProviders.ContainsKey(pair.ActionTypeName) == false) { IActionTokenProvider newActionTokenProvider = (IActionTokenProvider)Activator.CreateInstance(pair.ActionTokenProviderType); actionTokenProviders.Add(pair.ActionTypeName, newActionTokenProvider); } } _resourceLocker.Resources.ActionTokenProviderCache.Add(elementProviderType, actionTokenProviders); } IActionTokenProvider actionTokenProvider; actionTokenProviders.TryGetValue(actionTypeName, out actionTokenProvider); return actionTokenProvider; } } public static ResourceHandle GetActionResourceHandle(Type elementProviderType, string actionTypeName) { Dictionary<string, ResourceHandle> actionResourceHandles; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.ActionResourceHandleCache.TryGetValue(elementProviderType, out actionResourceHandles) == false) { actionResourceHandles = new Dictionary<string, ResourceHandle>(); var pairs = (from t in elementProviderType.GetCustomAttributesRecursively<ActionResourceHandleAttribute>() select new { ActionTypeName = t.ActionTypeName, ActionResourceHandle = t.ActionResourceHandle }); foreach (var pair in pairs) { if (actionResourceHandles.ContainsKey(pair.ActionTypeName) == false) { actionResourceHandles.Add(pair.ActionTypeName, pair.ActionResourceHandle); } } _resourceLocker.Resources.ActionResourceHandleCache.Add(elementProviderType, actionResourceHandles); } ResourceHandle actionResourceHandle; actionResourceHandles.TryGetValue(actionTypeName, out actionResourceHandle); return actionResourceHandle; } } public static IActionPermissionTypeProvider GetActionPermissionTypeProvider(Type elementProviderType, string actionTypeName) { Dictionary<string, IActionPermissionTypeProvider> actionPermissionTypeProviders; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.ActionPermissionTypeProviderCache.TryGetValue(elementProviderType, out actionPermissionTypeProviders) == false) { actionPermissionTypeProviders = new Dictionary<string, IActionPermissionTypeProvider>(); var pairs = (from t in elementProviderType.GetCustomAttributesRecursively<ActionPermissionTypeProviderAttribute>() select new { ActionTypeName = t.ActionTypeName, ActionPermissionProviderType = t.ActionPermissionTypeProviderType }); foreach (var pair in pairs) { if (actionPermissionTypeProviders.ContainsKey(pair.ActionTypeName) == false) { IActionPermissionTypeProvider newActionPermissionTypeProvider = (IActionPermissionTypeProvider)Activator.CreateInstance(pair.ActionPermissionProviderType); actionPermissionTypeProviders.Add(pair.ActionTypeName, newActionPermissionTypeProvider); } } _resourceLocker.Resources.ActionPermissionTypeProviderCache.Add(elementProviderType, actionPermissionTypeProviders); } IActionPermissionTypeProvider actionPermissionTypeProvider; actionPermissionTypeProviders.TryGetValue(actionTypeName, out actionPermissionTypeProvider); return actionPermissionTypeProvider; } } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private sealed class Resources { public Dictionary<Type, List<string>> IgnoreActionCache; public Dictionary<Type, Dictionary<string, IActionTokenProvider>> ActionTokenProviderCache; public Dictionary<Type, Dictionary<string, IActionPermissionTypeProvider>> ActionPermissionTypeProviderCache; public Dictionary<Type, Dictionary<string, ResourceHandle>> ActionResourceHandleCache; public static void DoInitialize(Resources resources) { resources.IgnoreActionCache = new Dictionary<Type, List<string>>(); resources.ActionTokenProviderCache = new Dictionary<Type, Dictionary<string, IActionTokenProvider>>(); resources.ActionPermissionTypeProviderCache = new Dictionary<Type, Dictionary<string, IActionPermissionTypeProvider>>(); resources.ActionResourceHandleCache = new Dictionary<Type, Dictionary<string, ResourceHandle>>(); } } } } ================================================ FILE: Composite/Data/ProcessControlled/ProcessControllerFacade.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using Composite.Core.Caching; using Composite.Core.Collections.Generic; using Composite.Data.Foundation; using Composite.C1Console.Elements; using Composite.C1Console.Events; using Composite.Data.Transactions; using Composite.Core.Types; using Composite.Core.Linq; namespace Composite.Data.ProcessControlled { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ProcessControllerFacade { private static readonly Dictionary<Type, Type> _controlledTypes = new Dictionary<Type, Type>(); private static Dictionary<Type, IProcessController> _processControllers; private static Hashtable<Type, List<IPublishControlledAuxiliary>> _publishControlledAuxiliaries = new Hashtable<Type, List<IPublishControlledAuxiliary>>(); static ProcessControllerFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); _controlledTypes.Add(typeof(IPublishControlled), typeof(IPublishProcessController)); _controlledTypes.Add(typeof(ILocalizedControlled), typeof(ILocalizeProcessController)); } /// <summary> /// This method will delete the data, and its if the exists its versions and publications /// </summary> /// <param name="data"></param> public static void FullDelete(IData data) { FullDelete(new[] {data}); } internal static void FullDelete(IEnumerable<IData> dataset) { using (var transactionScope = TransactionsFacade.CreateNewScope()) { foreach (var data in dataset) { if (data is IPublishControlled) { using (new DataScope(DataScopeIdentifier.Public)) { IEnumerable<IData> datasDelete = DataFacade.GetDataFromOtherScope(data, DataScopeIdentifier.Public).Evaluate(); DataFacade.Delete(datasDelete, CascadeDeleteType.Disable); } } using (new DataScope(DataScopeIdentifier.Administrated)) { DataFacade.Delete(data); } } transactionScope.Complete(); } } /// <summary> /// This method return the types that implements the same IProcessControlled interfaces as /// the targetType. /// </summary> /// <param name="targetType"></param> /// <param name="types"></param> /// <returns></returns> public static IEnumerable<Type> GetProcessControlledTypes(Type targetType, IEnumerable<Type> types) { if (targetType == null) throw new ArgumentNullException("targetType"); if (types == null) throw new ArgumentNullException("types"); List<Type> compatibleTypes = new List<Type>(); foreach (Type type in types) { foreach (Type processControledType in _controlledTypes.Keys) { if (!compatibleTypes.Contains(type) && processControledType.IsAssignableFrom(targetType) && processControledType.IsAssignableFrom(type)) { compatibleTypes.Add(type); } } } return compatibleTypes; } /// <exclude /> public static List<ElementAction> GetActions(IData data, Type elementProviderType) { if (data == null) throw new ArgumentNullException("data"); if (elementProviderType == null) throw new ArgumentNullException("elementProviderType"); var actions = new List<ElementAction>(); Dictionary<Type, Type> processControllerTypes = ProcessControllerRegistry.GetProcessControllerTypes(data.DataSourceId.InterfaceType); foreach (Type processControllerType in processControllerTypes.Values) { IProcessController processController = _processControllers[processControllerType]; List<ElementAction> acts = processController.GetActions(data, elementProviderType); if (acts != null) { actions.AddRange(acts); } } return actions; } #region IPublishControlled methods /// <exclude /> public static void SetStartStatus(IData data) { if (data == null) throw new ArgumentNullException("data"); IPublishProcessController controller = GetProcessController<IPublishProcessController>(data.DataSourceId.InterfaceType); if (controller == null) throw new ArgumentException(string.Format("The type '{0}' is not registred process controller", data.DataSourceId.InterfaceType)); controller.SetStartStatus(data); } /// <exclude /> public static IDictionary<string, string> GetValidTransitions(IData data) { if (data == null) throw new ArgumentNullException("data"); IPublishProcessController controller = GetProcessController<IPublishProcessController>(data.DataSourceId.InterfaceType); if (controller == null) throw new ArgumentException(string.Format("The type '{0}' is not registred process controller", data.DataSourceId.InterfaceType)); return controller.GetValidTransitions(data); } /// <exclude /> public static void ValidateTransition(IData data, string status) { if (data == null) throw new ArgumentNullException("data"); IPublishProcessController controller = GetProcessController<IPublishProcessController>(data.DataSourceId.InterfaceType); if (controller == null) throw new ArgumentException(string.Format("The type '{0}' is not registred process controller", data.DataSourceId.InterfaceType)); controller.ValidateTransition(data, status); } #endregion /// <exclude /> public static Type GetProcessControllerType<T>(IData data) where T : class, IProcessController { if (data == null) throw new ArgumentNullException("data"); T controller = GetProcessController<T>(data.DataSourceId.InterfaceType); if (controller == null) throw new ArgumentException(string.Format("The type '{0}' is not registred process controller", data.DataSourceId.InterfaceType)); return controller.GetType(); } /// <exclude /> public static IDisposable NoProcessControllers { get { return new NoProcessControllersDisposable(); } } private static void OnAfterDataUpdated(object sender, DataEventArgs dataEventArgs) { if (GetProcessControllersCounter() > 0) return; if (dataEventArgs.Data is IPublishControlled) { IPublishProcessController controller = GetProcessController<IPublishProcessController>(dataEventArgs.Data.DataSourceId.InterfaceType); if (controller != null) { bool callAuxilaries = controller.OnAfterDataUpdated(dataEventArgs.Data); if (callAuxilaries) { IEnumerable<IPublishControlledAuxiliary> publishControlledAuxiliaries = GetPublishControlledAuxiliaries(dataEventArgs.DataType); foreach (IPublishControlledAuxiliary publishControlledAuxiliary in publishControlledAuxiliaries) { publishControlledAuxiliary.OnAfterDataUpdated(dataEventArgs.Data); } } } } } private static void OnDataBuildNew(object sender, DataEventArgs dataEventArgs) { if (GetProcessControllersCounter() > 0) return; if (dataEventArgs.Data is IPublishControlled) { IPublishProcessController controller = GetProcessController<IPublishProcessController>(dataEventArgs.Data.DataSourceId.InterfaceType); if (controller != null) { bool callAuxilaries = controller.OnAfterBuildNew(dataEventArgs.Data); if (callAuxilaries) { IEnumerable<IPublishControlledAuxiliary> publishControlledAuxiliaries = GetPublishControlledAuxiliaries(dataEventArgs.DataType); foreach (IPublishControlledAuxiliary publishControlledAuxiliary in publishControlledAuxiliaries) { publishControlledAuxiliary.OnAfterBuildNew(dataEventArgs.Data); } } } } if (dataEventArgs.Data is ILocalizedControlled) { ILocalizeProcessController controller = GetProcessController<ILocalizeProcessController>(dataEventArgs.Data.DataSourceId.InterfaceType); if (controller != null) { controller.OnAfterBuildNew(dataEventArgs.Data); } } } private static T GetProcessController<T>(Type dataType) where T : class, IProcessController { Dictionary<Type, Type> processControllerTypes = ProcessControllerRegistry.GetProcessControllerTypes(dataType); Type type; if (processControllerTypes.TryGetValue(typeof(T), out type) == false) { return null; } return (T)_processControllers[type]; } private static IEnumerable<IPublishControlledAuxiliary> GetPublishControlledAuxiliaries(Type dataType) { List<IPublishControlledAuxiliary> publishControlledAuxiliaries; if (!_publishControlledAuxiliaries.TryGetValue(dataType, out publishControlledAuxiliaries)) { lock (_publishControlledAuxiliaries) { if (!_publishControlledAuxiliaries.TryGetValue(dataType, out publishControlledAuxiliaries)) { List<PublishControlledAuxiliaryAttribute> attributes = dataType.GetCustomAttributesRecursively<PublishControlledAuxiliaryAttribute>().ToList(); publishControlledAuxiliaries = new List<IPublishControlledAuxiliary>(); foreach (PublishControlledAuxiliaryAttribute attribute in attributes) { if (attribute.PublishControlledAuxiliaryType == null) throw new InvalidOperationException(string.Format("The PublishControlledAuxiliaryType may not be null on the {0}", typeof(PublishControlledAuxiliaryAttribute))); if (typeof(IPublishControlledAuxiliary).IsAssignableFrom(attribute.PublishControlledAuxiliaryType) == false) throw new InvalidOperationException(string.Format("The {0} does not inheret the interface {1} the {2}", attribute.PublishControlledAuxiliaryType, typeof(IPublishControlledAuxiliary), typeof(PublishControlledAuxiliaryAttribute))); ConstructorInfo constructorInfo = attribute.PublishControlledAuxiliaryType.GetConstructor(new Type[] { }); if (constructorInfo == null) throw new InvalidOperationException(string.Format("The type {0} used by the {1} does not have a default contructor", attribute.PublishControlledAuxiliaryType, typeof(PublishControlledAuxiliaryAttribute))); IPublishControlledAuxiliary publishControlledAuxiliary = (IPublishControlledAuxiliary)Activator.CreateInstance(attribute.PublishControlledAuxiliaryType, new object[] { }); publishControlledAuxiliaries.Add(publishControlledAuxiliary); } _publishControlledAuxiliaries.Add(dataType, publishControlledAuxiliaries); } } } foreach (IPublishControlledAuxiliary publishControlledAuxiliary in publishControlledAuxiliaries) { yield return publishControlledAuxiliary; } } internal static void Initialize_PostDataTypes() { if (RuntimeInformation.IsDebugBuild) { GlobalInitializerFacade.ValidateIsOnlyCalledFromGlobalInitializerFacade(new StackTrace()); } DoInitialize(); } private static void DoInitialize() { _processControllers = new Dictionary<Type, IProcessController>(); foreach (Type processControllerType in ProcessControllerRegistry.ProcessControllerTypes) { IProcessController processController = (IProcessController)Activator.CreateInstance(processControllerType); _processControllers.Add(processControllerType, processController); } if (!RuntimeInformation.IsUnittest) { foreach (Type dataType in DataFacade.GetAllInterfaces()) { Dictionary<Type, Type> processControllerTypes = ProcessControllerRegistry.GetProcessControllerTypes(dataType); foreach (var kvp in _controlledTypes) { if (kvp.Key.IsAssignableFrom(dataType)) { if (!processControllerTypes.ContainsKey(kvp.Value)) { throw new InvalidOperationException(string.Format("The data type {0} is inheriting the interface {1} but has not been assigned a {2} process controller", dataType, kvp.Key, kvp.Value)); } } } } } DataEventSystemFacade.SubscribeToDataAfterUpdate<IProcessControlled>(OnAfterDataUpdated, false); DataEventSystemFacade.SubscribeToDataAfterBuildNew<IProcessControlled>(OnDataBuildNew, false); } private static void Flush() { _processControllers = null; _publishControlledAuxiliaries = new Hashtable<Type, List<IPublishControlledAuxiliary>>(); } private static int GetProcessControllersCounter() { return ProcessControllersCounter.Counter; } private sealed class NoProcessControllersDisposable : IDisposable { public NoProcessControllersDisposable() { ProcessControllersCounter.Counter++; } public void Dispose() { ProcessControllersCounter.Counter--; #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// <exclude /> ~NoProcessControllersDisposable() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } private sealed class CounterContainer { public CounterContainer() { this.Counter = 0; } public int Counter { get; set; } } private static CounterContainer ProcessControllersCounter { get { return RequestLifetimeCache.GetCachedOrNew<CounterContainer>("ProcessControllerFacade:ProcessControllersCounter"); } } } } ================================================ FILE: Composite/Data/ProcessControlled/ProcessControllers/DummyProcessControllers/PublishDummyProcessController.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Elements; namespace Composite.Data.ProcessControlled.ProcessControllers.DummyProcessControllers { internal sealed class PublishDummyProcessController : IPublishProcessController { public void SetStartStatus(IData data) { } public IDictionary<string, string> GetValidTransitions(IData data) { return new Dictionary<string, string>(); } public bool OnAfterDataUpdated(IData data) { return true; } public bool OnAfterBuildNew(IData data) { return true; } public void ValidateTransition(IData data, string status) { } public List<ElementAction> GetActions(IData data, Type elementProviderType) { return new List<ElementAction>(); } } } ================================================ FILE: Composite/Data/ProcessControlled/ProcessControllers/GenericLocalizeProcessController/GenericLocalizeProcessController.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Elements; using Composite.C1Console.Users; using System.Globalization; using Composite.C1Console.Security; namespace Composite.Data.ProcessControlled.ProcessControllers.GenericLocalizeProcessController { internal sealed class GenericLocalizeProcessController : ILocalizeProcessController { public bool OnAfterBuildNew(IData data) { ILocalizedControlled localizedData = data as ILocalizedControlled; if (localizedData != null) { if (!LocalizationScopeManager.IsEmpty) { localizedData.SourceCultureName = LocalizationScopeManager.CurrentLocalizationScope.Name; } else { CultureInfo cultureInfo = null; if (UserValidationFacade.IsLoggedIn()) { cultureInfo = UserSettings.ActiveLocaleCultureInfo; } if (cultureInfo == null) { cultureInfo = DataLocalizationFacade.DefaultLocalizationCulture; } if (cultureInfo != null) { localizedData.SourceCultureName = cultureInfo.Name; } } } return false; } public List<ElementAction> GetActions(IData data, Type elementProviderType) { // TODO: Add Localize action here????? return new List<ElementAction>(); } } } ================================================ FILE: Composite/Data/ProcessControlled/ProcessControllers/GenericPublishProcessController/GenericPublishProcessController.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Transactions; using Composite.C1Console.Actions; using Composite.C1Console.Actions.Data; using Composite.C1Console.Events; using Composite.C1Console.Elements; using Composite.Core.Linq; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.C1Console.Security; using Composite.Data.Transactions; using Composite.C1Console.Users; using Composite.Data.Validation; using Microsoft.Practices.EnterpriseLibrary.Validation; using Composite.Data.Types; using ManagementStrings = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Management; namespace Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class GenericPublishProcessController : IPublishProcessController { private static readonly string _oldPublishedStatusTag = "OldPublishedStatus"; /// <exclude /> public const string Draft = "draft"; /// <exclude /> public const string AwaitingApproval = "awaitingApproval"; /// <exclude /> public const string AwaitingPublication = "awaitingPublication"; /// <exclude /> public const string Published = "published"; /// <exclude /> public static string BulkPublishingCommandsTag { get; } = "BulkPublishingCommands"; private static readonly string _backToAwaitingApproval = "awaitingApprovalBack"; private static readonly string _forwardToAwaitingApproval = "awaitingApprovalForward"; private static readonly string _backToAwaitingPublication = "awaitingPublicationBack"; private static readonly string _forwardToAwaitingPublication = "awaitingPublicationForward"; private static readonly string _draftDisabled = "draftDisabled"; private static readonly string _awaitingApprovalDisabled = "awaitingApprovalDisabled"; private static readonly string _awaitingPublicationDisabled = "awaitingPublicationDisabled"; private static readonly string _publishedDisabled = "publishedDisabled"; private readonly IDictionary<string, IList<string>> _transitions; private readonly IDictionary<string, IList<string>> _visualTransitions; private readonly IDictionary<string, string> _transitionNames; private readonly IDictionary<string, Func<ElementAction>> _visualTransitionsActions; // Using visual transition names as keys /// <exclude /> public static ResourceHandle SendForwardForApproval { get { return GetIconHandle("item-send-forward-for-approval"); } } /// <exclude /> public static ResourceHandle SendForwardForPublication { get { return GetIconHandle("item-send-forward-for-publication"); } } /// <exclude /> public static ResourceHandle Publish { get { return GetIconHandle("item-publish"); } } /// <exclude /> public static ResourceHandle Unpublish { get { return GetIconHandle("item-unpublish"); } } /// <exclude /> public static ResourceHandle UndoUnpublishedChanges { get { return GetIconHandle("item-undo-unpublished-changes"); } } /// <exclude /> public static ResourceHandle SendBackToDraft { get { return GetIconHandle("item-send-back-to-draft"); } } /// <exclude /> public static ResourceHandle SendBackForApproval { get { return GetIconHandle("item-send-back-for-approval"); } } /// <exclude /> public static ResourceHandle SendBackForPublication { get { return GetIconHandle("item-send-back-for-publication"); } } /// <exclude /> public static readonly ActionGroup WorkflowActionGroup = new ActionGroup("Workflow", ActionGroupPriority.PrimaryMedium); /// <exclude /> public static readonly IEnumerable<PermissionType> AwaitingPublicationActionPermissionType = new PermissionType[] { PermissionType.Approve }; /// <exclude /> public GenericPublishProcessController() { _transitions = new Dictionary<string, IList<string>> { {Draft, new List<string> {AwaitingApproval, AwaitingPublication, Published}}, {AwaitingApproval, new List<string> {Draft, AwaitingPublication, Published}}, {AwaitingPublication, new List<string> {Draft, AwaitingApproval, Published}}, {Published, new List<string> {Draft, AwaitingApproval, AwaitingPublication}} }; _visualTransitions = new Dictionary<string, IList<string>> { {Draft, new List<string> { _draftDisabled, _forwardToAwaitingApproval, _forwardToAwaitingPublication, Published }}, {AwaitingApproval, new List<string> { Draft, _awaitingApprovalDisabled, _forwardToAwaitingPublication, Published }}, {AwaitingPublication, new List<string> { Draft, _backToAwaitingApproval, _awaitingPublicationDisabled, Published }}, {Published, new List<string>()} // when public, no "send to" available. }; _transitionNames = new Dictionary<string, string> { {Draft, ManagementStrings.PublishingStatus_draft}, {AwaitingApproval, ManagementStrings.PublishingStatus_awaitingApproval}, {AwaitingPublication, ManagementStrings.PublishingStatus_awaitingPublication}, {Published, ManagementStrings.PublishingStatus_published} }; Func<ElementAction> sendBackToDraftAction = () => new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.SendToDraft) { DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "SendToDraft"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "SendToDraftToolTip"), Icon = GenericPublishProcessController.SendBackToDraft, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = true, ActionGroup = WorkflowActionGroup } }, TagValue = BulkPublishingCommandsTag }; Func<ElementAction> sendForwardToAwaitingApprovalAction = () => new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.SendForApproval) { DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "SendForApproval"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "SendForApprovalToolTip"), Icon = GenericPublishProcessController.SendForwardForApproval, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = true, ActionGroup = WorkflowActionGroup } }, TagValue = BulkPublishingCommandsTag }; Func<ElementAction> sendForwardToAwaitingPublicationAction = () => new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.SendForPublication) { DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "SendForPublication"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "SendForPublicationToolTip"), Icon = GenericPublishProcessController.SendForwardForPublication, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = true, ActionGroup = WorkflowActionGroup } }, TagValue = BulkPublishingCommandsTag }; Func<ElementAction> publishAction = () => new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.Publish) {DoIgnoreEntityTokenLocking = true})) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "Publish"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "PublishToolTip"), Icon = GenericPublishProcessController.Publish, Disabled = false, BulkExecutionDialog = new DialogStrings { Title = LocalizationFiles.Composite_Plugins_PageElementProvider.ViewUnpublishedItems_PublishConfirmTitle, Text = LocalizationFiles.Composite_Plugins_PageElementProvider.ViewUnpublishedItems_PublishConfirmText }, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = true, ActionGroup = WorkflowActionGroup, ActionBundle = "Publish" } }, TagValue = BulkPublishingCommandsTag }; // "arrow pointing left when state change is going backwards" actions Func<ElementAction> sendBackToAwaitingApprovalAction = () => new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.SendForApproval) { DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "SendForApproval"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "SendForApprovalToolTip"), Icon = GenericPublishProcessController.SendForwardForApproval, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = true, ActionGroup = WorkflowActionGroup } }, TagValue = BulkPublishingCommandsTag }; Func<ElementAction> sendBackToAwaitingPublicationAction = () => new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.SendForPublication) { DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "SendForPublication"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "SendForPublicationToolTip"), Icon = GenericPublishProcessController.SendForwardForApproval, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = true, ActionGroup = WorkflowActionGroup } }, TagValue = BulkPublishingCommandsTag, }; // disabled actions Func<ElementAction> draftActionDisabled = () => new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.SendToDraft) { DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "SendToDraft"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "SendToDraftToolTip"), Icon = GenericPublishProcessController.SendBackToDraft, Disabled = true, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = true, ActionGroup = WorkflowActionGroup } }, TagValue = BulkPublishingCommandsTag }; Func<ElementAction> awaitingApprovalActionDisabled = () => new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.SendForApproval) { DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "SendForApproval"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "SendForApprovalToolTip"), Icon = GenericPublishProcessController.SendForwardForApproval, Disabled = true, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = true, ActionGroup = WorkflowActionGroup } }, TagValue = BulkPublishingCommandsTag }; Func<ElementAction> awaitingPublicationActionDisabled = () => new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.SendForPublication) { DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "SendForPublication"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "SendForPublicationToolTip"), Icon = GenericPublishProcessController.SendBackForPublication, Disabled = true, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = true, ActionGroup = WorkflowActionGroup } }, TagValue = BulkPublishingCommandsTag }; Func<ElementAction> publishActionDisabled = () => new ElementAction(new ActionHandle(new DisabledActionToken())) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "Publish"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "PublishToolTip"), Icon = GenericPublishProcessController.Publish, Disabled = true, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = true, ActionGroup = WorkflowActionGroup } }, TagValue = BulkPublishingCommandsTag }; _visualTransitionsActions = new Dictionary<string, Func<ElementAction>> { {Draft, sendBackToDraftAction}, {_backToAwaitingApproval, sendBackToAwaitingApprovalAction}, {_backToAwaitingPublication, sendBackToAwaitingPublicationAction}, {_forwardToAwaitingApproval, sendForwardToAwaitingApprovalAction}, {_forwardToAwaitingPublication, sendForwardToAwaitingPublicationAction}, {Published, publishAction}, {_draftDisabled, draftActionDisabled}, {_awaitingApprovalDisabled, awaitingApprovalActionDisabled}, {_awaitingPublicationDisabled, awaitingPublicationActionDisabled}, {_publishedDisabled, publishActionDisabled} }; } /// <exclude /> public List<ElementAction> GetActions(IData data, Type elementProviderType) { if (!(data is IPublishControlled) || !data.DataSourceId.DataScopeIdentifier.Equals(DataScopeIdentifier.Administrated)) { return new List<ElementAction>(); } if (UserSettings.ActiveLocaleCultureInfo == null || 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).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; } /// <exclude /> public void SetStartStatus(IData data) { if (!(data is IPublishControlled) || !data.DataSourceId.DataScopeIdentifier.Equals(DataScopeIdentifier.Administrated)) { return; } var publishControlled = (IPublishControlled)data; publishControlled.PublicationStatus = Draft; } /// <exclude /> public IDictionary<string, string> GetValidTransitions(IData data) { if (!(data is IPublishControlled) || !data.DataSourceId.DataScopeIdentifier.Equals(DataScopeIdentifier.Administrated)) { return new Dictionary<string, string>(); } return _transitionNames; } /// <exclude /> public bool OnAfterBuildNew(IData data) { var publishControlled = (IPublishControlled)data; publishControlled.PublicationStatus = Draft; return true; } /// <exclude /> public bool OnAfterDataUpdated(IData data) { DataFacade.RemoveDataTag(data, _oldPublishedStatusTag); if (!data.DataSourceId.DataScopeIdentifier.Equals(DataScopeIdentifier.Administrated)) return false; var publishControlled = (IPublishControlled)data; if (publishControlled.PublicationStatus == Published) { using (new DataScope(DataScopeIdentifier.Public)) { var existing = DataFacade.GetDataFromOtherScope((IData)publishControlled, DataScopeIdentifier.Public).Evaluate(); if (existing.Any()) { DataFacade.Delete(existing, CascadeDeleteType.Disable); } DataFacade.AddNew(data); } return true; } // Check when do we have this situation return false; } /// <exclude /> public void ValidateTransition(IData data, string status) { var publishControlled = (IPublishControlled)data; string oldTag; if (DataFacade.TryGetDataTag<string>(publishControlled, _oldPublishedStatusTag, out oldTag)) { if (status != oldTag) { if (!_transitions[oldTag].Contains(status)) { throw new ArgumentException("Invalid transition"); } } } else { if (!String.IsNullOrEmpty(publishControlled.PublicationStatus) && status != publishControlled.PublicationStatus) { if (_transitions[publishControlled.PublicationStatus].Contains(status) == false) { throw new ArgumentException("Invalid transition"); } } } DataFacade.SetDataTag(data, _oldPublishedStatusTag, status); } private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } internal sealed class PublishActionExecutor : IActionExecutor { 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; } } internal sealed class DisabledActionToken : ActionToken { public override IEnumerable<PermissionType> PermissionTypes { get { yield break; } } public override string Serialize() { return ""; } public static ActionToken Deserialize(string serializedData) { return new DisabledActionToken(); } } [ActionExecutor(typeof(PublishActionExecutor))] internal sealed class PublishActionToken : ActionToken { private static IEnumerable<PermissionType> _permissionTypes = new [] { PermissionType.Publish }; public override IEnumerable<PermissionType> PermissionTypes { get { return _permissionTypes; } } public override bool IgnoreEntityTokenLocking => true; public override string Serialize() { return Published; } public static ActionToken Deserialize(string serializedData) { return new PublishActionToken(); } } [ActionExecutor(typeof(PublishActionExecutor))] internal sealed class UnpublishActionToken : ActionToken { private static IEnumerable<PermissionType> _permissionTypes = new PermissionType[] { PermissionType.Publish }; public override IEnumerable<PermissionType> PermissionTypes { get { return _permissionTypes; } } public override bool IgnoreEntityTokenLocking => true; public override string Serialize() { return Published; } public static ActionToken Deserialize(string serializedData) { return new ProxyDataActionToken(ActionIdentifier.Unpublish); } } [ActionExecutor(typeof(PublishActionExecutor))] internal sealed class UndoPublishedChangesActionToken : ActionToken { private static IEnumerable<PermissionType> _permissionTypes = new [] { PermissionType.Edit, PermissionType.Publish }; public override IEnumerable<PermissionType> PermissionTypes { get { return _permissionTypes; } } public override bool IgnoreEntityTokenLocking => true; public override string Serialize() { return ""; } public static ActionToken Deserialize(string serializedData) { return new UndoPublishedChangesActionToken(); } } [ActionExecutor(typeof(PublishActionExecutor))] internal sealed class DraftActionToken : ActionToken { private static IEnumerable<PermissionType> _permissionTypes = new [] { PermissionType.Edit, PermissionType.Approve, PermissionType.Publish }; public override IEnumerable<PermissionType> PermissionTypes { get { return _permissionTypes; } } public override bool IgnoreEntityTokenLocking => true; public override string Serialize() { return Draft; } public static ActionToken Deserialize(string serializedData) { return new DraftActionToken(); } } [ActionExecutor(typeof(PublishActionExecutor))] internal sealed class AwaitingApprovalActionToken : ActionToken { private static IEnumerable<PermissionType> _permissionTypes = new [] { PermissionType.Edit }; public override IEnumerable<PermissionType> PermissionTypes { get { return _permissionTypes; } } public override bool IgnoreEntityTokenLocking => true; public override string Serialize() { return _forwardToAwaitingApproval; } public static Composite.C1Console.Security.ActionToken Deserialize(string serializedData) { return new AwaitingApprovalActionToken(); } } [ActionExecutor(typeof(PublishActionExecutor))] internal sealed class AwaitingPublicationActionToken : ActionToken { private static IEnumerable<PermissionType> _permissionTypes = new [] { PermissionType.Approve }; public override IEnumerable<PermissionType> PermissionTypes { get { return _permissionTypes; } } public override bool IgnoreEntityTokenLocking => true; public override string Serialize() { return _forwardToAwaitingApproval; } public static Composite.C1Console.Security.ActionToken Deserialize(string serializedData) { return new AwaitingPublicationActionToken(); } } } } ================================================ FILE: Composite/Data/ProcessControlled/ProcessControllers/GenericPublishProcessController/GenericPublishProcessControllerActionType.cs ================================================ namespace Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController { internal static class GenericPublishProcessControllerActionTypeNames { public const string UndoUnpublishedChanges = "UndoUnpublishedChanges"; } } ================================================ FILE: Composite/Data/ProcessControlled/ProcessControllers/GenericPublishProcessController/GenericPublishProcessDynamicActionTokens.cs ================================================ using Composite.C1Console.Actions.Data; using Composite.Core.Application; namespace Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController { [ApplicationStartup] class GenericPublishProcessDynamicActionTokens { public static void OnBeforeInitialize() { } public static void OnInitialized(DataActionTokenResolver resolver) { resolver.RegisterDefault<IData>(ActionIdentifier.SendForPublication, f => new GenericPublishProcessController.AwaitingPublicationActionToken()); resolver.RegisterDefault<IData>(ActionIdentifier.Publish, f => new GenericPublishProcessController.PublishActionToken()); resolver.RegisterDefault<IData>(ActionIdentifier.SendForApproval, f => new GenericPublishProcessController.AwaitingApprovalActionToken()); resolver.RegisterDefault<IData>(ActionIdentifier.SendToDraft, f => new GenericPublishProcessController.DraftActionToken()); resolver.RegisterDefault<IData>(ActionIdentifier.Unpublish, f => new GenericPublishProcessController.UnpublishActionToken()); } } } ================================================ FILE: Composite/Data/ProcessControlled/PublishControlledAuxiliaryAttribute.cs ================================================ using System; namespace Composite.Data.ProcessControlled { internal class PublishControlledAuxiliaryAttribute : Attribute { public PublishControlledAuxiliaryAttribute(Type publishControlledAuxiliaryType) { this.PublishControlledAuxiliaryType = publishControlledAuxiliaryType; } public Type PublishControlledAuxiliaryType { get; private set; } } } ================================================ FILE: Composite/Data/ProcessControllerTypeAttribute.cs ================================================ using System; using Composite.Data.ProcessControlled; namespace Composite.Data { /// <summary> /// Binds imlementations of <see cref="IProcessController"/> to data types /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class ProcessControllerTypeAttribute : Attribute { /// <exclude /> protected ProcessControllerTypeAttribute(Type processControllerType) { this.ProcessControllerType = processControllerType; } /// <exclude /> public Type ProcessControllerType { get; private set; } } /// <summary> /// Add this attribute to your data interface to specify what controller to use for publishing. /// Your data type is expected to implement <see cref="Composite.Data.ProcessControlled.IPublishControlled"/> when this attribute is used. /// The type you specify is expected to implement <see cref="Composite.Data.ProcessControlled.IPublishProcessController"/>. /// For default publishing behaviour use the type <see cref="Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController.GenericPublishProcessController"/> /// </summary> /// <example> This sample shows how to use the PublishProcessControllerType attribute. /// <code> /// [PublishProcessControllerType(typeof(GenericPublishProcessController))] /// // (other IData attributes) /// interface IMyDataType : IData, IPublishControlled /// { /// // data type properties /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = true, Inherited = true)] public sealed class PublishProcessControllerTypeAttribute : ProcessControllerTypeAttribute { /// <summary> /// Specify what controller to use for publishing. /// For default publishing behaviour use the type <see cref="Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController.GenericPublishProcessController"/> /// </summary> /// <param name="processControllerType">Controller to use in publishing flow</param> public PublishProcessControllerTypeAttribute(Type processControllerType) : base(processControllerType) { } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Interface, AllowMultiple = true, Inherited = true)] public sealed class LocalizeProcessControllerTypeAttribute : ProcessControllerTypeAttribute { /// <exclude /> public LocalizeProcessControllerTypeAttribute(Type processControllerType) : base(processControllerType) { } } } ================================================ FILE: Composite/Data/PublicationScope.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Composite.Data { /// <summary> /// Define the scope of data in relation to publication status. Data which support publication should always be maintained /// in the “Unpublihed” scope, while reading data on the public website should always be done in the “Published” scope. /// Correct setting of the PublicationScope is typically handled by C1 CMS and should in general not be changed by developers. /// Setting an explicit PublicationScope is typically only needed on new service end-points or /// if specific features relating to data updating / publication is desired. /// See <see cref="Composite.Data.DataConnection"/> /// </summary> ///// <seealso cref="Composite.Data.PageDataConnection"/> public enum PublicationScope { /// <summary> /// Only show data that has been published. /// </summary> Published = 1, /// <summary> /// Show / update unpublished data. /// </summary> Unpublished = 0 } } ================================================ FILE: Composite/Data/PublishScheduling/PublishScheduleHelper.cs ================================================ using System; using System.Linq; using System.Workflow.Runtime; using Composite.Data.Types; namespace Composite.Data.PublishScheduling { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PublishScheduleHelper { /// <exclude /> public static void CreatePublishSchedule(Type dataType, string id, string cultureName, DateTime date, WorkflowInstance workflow) { var publishSchedule = DataFacade.BuildNew<IPublishSchedule>(); publishSchedule.Id = Guid.NewGuid(); publishSchedule.DataTypeId = dataType.GetImmutableTypeId(); publishSchedule.DataId = id; publishSchedule.PublishDate = date; publishSchedule.WorkflowInstanceId = workflow.InstanceId; publishSchedule.LocaleCultureName = DataLocalizationFacade.IsLocalized(dataType) ? cultureName : ""; DataFacade.AddNew(publishSchedule); } /// <exclude /> public static void CreateUnpublishSchedule(Type dataType, string id, string cultureName, DateTime date, WorkflowInstance workflow) { var unpublishSchedule = DataFacade.BuildNew<IUnpublishSchedule>(); unpublishSchedule.Id = Guid.NewGuid(); unpublishSchedule.DataTypeId = dataType.GetImmutableTypeId(); unpublishSchedule.DataId = id; unpublishSchedule.UnpublishDate = date; unpublishSchedule.WorkflowInstanceId = workflow.InstanceId; unpublishSchedule.LocaleCultureName = DataLocalizationFacade.IsLocalized(dataType) ? cultureName : ""; DataFacade.AddNew(unpublishSchedule); } /// <exclude /> public static IPublishSchedule GetPublishSchedule(Type dataType, string id, string cultureName) { Guid dataTypeId = dataType.GetImmutableTypeId(); var query = DataFacade.GetData<IPublishSchedule>().Where(ps => ps.DataId == id && ps.DataTypeId == dataTypeId); if (DataLocalizationFacade.IsLocalized(dataType)) { query = query.Where(ps => ps.LocaleCultureName == cultureName); } return query.FirstOrDefault(); } /// <exclude /> public static IUnpublishSchedule GetUnpublishSchedule(Type dataType, string id, string cultureName) { Guid dataTypeId = dataType.GetImmutableTypeId(); var query = DataFacade.GetData<IUnpublishSchedule>().Where(ps => ps.DataId == id && ps.DataTypeId == dataTypeId); if (DataLocalizationFacade.IsLocalized(dataType)) { query = query.Where(ps => ps.LocaleCultureName == cultureName); } return query.FirstOrDefault(); } } } ================================================ FILE: Composite/Data/RelevantToUserTypeAttribute.cs ================================================ using System; using System.Collections.Generic; namespace Composite.Data { /// <summary> /// Add this attribute to your data interface to make it visible in the C1 Console developer UI. /// </summary> /// <example> This sample shows how to use the RelevantToUserType attribute. /// <code> /// [RelevantToUserType(UserType.Developer)] /// // (other IData attributes) /// interface IMyDataType : IData /// { /// // data type properties /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = true, Inherited = true)] public sealed class RelevantToUserTypeAttribute : Attribute { /// <summary> /// Make your data interface visible in the C1 Console developer UI. /// </summary> /// <param name="relevantToUserType">The <see cref="Composite.Data.UserType"/> this data type is relevant to. Only 'Developer' is available.</param> public RelevantToUserTypeAttribute(UserType relevantToUserType) { this.UserType = relevantToUserType; } /// <exclude /> public RelevantToUserTypeAttribute(string relevantToUserTypeString) { this.UserType = (UserType)Enum.Parse( typeof(UserType), relevantToUserTypeString ); } /// <exclude /> public UserType UserType { get; private set; } } } ================================================ FILE: Composite/Data/RouteDateSegmentAttribute.cs ================================================ using System; using System.Linq.Expressions; using System.Reflection; using Composite.Core.Routing; namespace Composite.Data { /// <summary> /// Describes which data format should be used while building a data url segment /// </summary> public enum DateSegmentFormat { /// <exclude /> Undefined = 0, /// <summary> /// Date url segment: '/Year' /// </summary> Year = 1, /// <summary> /// Date url segments: '/Year/Month' /// </summary> YearMonth = 2, /// <summary> /// Date url segments: '/Year/Month/Day' /// </summary> YearMonthDay = 3 } /// <summary> /// Makes the data type property of type <see cref="DateTime"/> field appear in data url. /// </summary> public sealed class RouteDateSegmentAttribute : RouteSegmentAttribute { private readonly DateSegmentFormat _format; /// <summary> /// Makes the data type property of type <see cref="DateTime"/> field appear in data url. /// </summary> public RouteDateSegmentAttribute(int order, DateSegmentFormat format = DateSegmentFormat.YearMonthDay) : base(order) { if (format == DateSegmentFormat.Undefined) { format = DateSegmentFormat.YearMonthDay; } _format = format; } /// <exclude /> public override IRelativeRouteToPredicateMapper BuildMapper(PropertyInfo propertyInfo) { Verify.That(propertyInfo.PropertyType == typeof(DateTime), "Property '{0}' of type '{1}' has attribute [{2}] with is applicable only for properties of type System.DateTime", propertyInfo.Name, propertyInfo.DeclaringType.FullName, typeof(RouteDateSegmentAttribute).Name); return new DateUrlSegmentMapper(_format); } internal class DateUrlSegmentMapper : IRelativeRouteToPredicateMapper<DateTime> { private readonly DateSegmentFormat _format; public DateUrlSegmentMapper(DateSegmentFormat format) { _format = format; } public int PathSegmentsCount { get { switch (_format) { case DateSegmentFormat.Year: return 1; case DateSegmentFormat.YearMonth: return 2; case DateSegmentFormat.YearMonthDay: return 3; } throw new InvalidOperationException("Not supported DateSegmentFormat value: " + _format); } } public Expression<Func<DateTime, bool>> GetPredicate(Guid pageId, RelativeRoute route) { int year, month, day; if (!int.TryParse(route.PathSegments[0], out year) || year < 0 || year > 10000) { return null; } if (_format == DateSegmentFormat.Year) { return date => date.Year == year; } if (!int.TryParse(route.PathSegments[1], out month) || month < 1 || month > 12) { return null; } if (_format == DateSegmentFormat.YearMonth) { return date => date.Year == year && date.Month == month; } if (!int.TryParse(route.PathSegments[2], out day) || day < 1 || day > DateTime.DaysInMonth(year, month)) { return null; } return date => date.Year == year && date.Month == month && date.Day == day; } public RelativeRoute GetRoute(DateTime fieldValue, bool searchSignificant) { switch (_format) { case DateSegmentFormat.Year: return new RelativeRoute { PathSegments = new[] { fieldValue.Year.ToString(), } }; case DateSegmentFormat.YearMonth: return new RelativeRoute { PathSegments = new[] { fieldValue.Year.ToString(), fieldValue.Month.ToString(), } }; case DateSegmentFormat.YearMonthDay: return new RelativeRoute { PathSegments = new[] { fieldValue.Year.ToString(), fieldValue.Month.ToString(), fieldValue.Day.ToString() } }; } throw new InvalidOperationException("Not supported DateSegmentFormat value: " + _format); } } } } ================================================ FILE: Composite/Data/RouteSegmentAttribute.cs ================================================ using System; using System.Linq; using System.Reflection; using Composite.Core.Routing; namespace Composite.Data { /// <summary> /// Indicates that the current property has to be used for building data url. /// </summary> [AttributeUsage(AttributeTargets.Property)] public class RouteSegmentAttribute : Attribute { /// <summary> /// Creates an instance of <see cref="RouteSegmentAttribute"/> /// </summary> /// <param name="order">The order. The fields with the lowest order will appear earlier in the path info part of the url.</param> public RouteSegmentAttribute(int order) { Order = order; } /// <summary> /// Return the order of the segment. Segments with the lower number will appear in url path earlier. /// </summary> public int Order { get; set; } /// <summary> /// Build a segment to predicate mapper /// </summary> /// <param name="propertyInfo"></param> /// <returns></returns> public virtual IRelativeRouteToPredicateMapper BuildMapper(PropertyInfo propertyInfo) { if (propertyInfo.PropertyType == typeof (DateTime)) { return new RouteDateSegmentAttribute.DateUrlSegmentMapper(DateSegmentFormat.YearMonthDay); } if (propertyInfo.GetCustomAttributes<ForeignKeyAttribute>().Any()) { var foreignKeyInfo = DataReferenceFacade.GetForeignKeyProperties(propertyInfo.DeclaringType) .FirstOrDefault(p => p.SourcePropertyName == propertyInfo.Name); if (foreignKeyInfo != null) { var targetType = foreignKeyInfo.TargetType; var dataTypeMapper = AttributeBasedRoutingHelper.GetPredicateMapper(targetType); if (dataTypeMapper != null) { var typeConst = typeof (DataReferenceRelativeRouteToPredicateMapper<,>) .MakeGenericType(targetType, foreignKeyInfo.SourcePropertyInfo.PropertyType) .GetConstructors().Single(); return (IRelativeRouteToPredicateMapper) typeConst.Invoke(new object[] { dataTypeMapper }); } } } var type = typeof (DefaultRelativeRouteToPredicateMapper<>).MakeGenericType(propertyInfo.PropertyType); var constructor = type.GetConstructor(new Type[0]); return constructor.Invoke(null) as IRelativeRouteToPredicateMapper; } } } ================================================ FILE: Composite/Data/SearchFacetAttribute.cs ================================================ using System; using System.Collections.Generic; using System.Linq; namespace Composite.Data { /// <summary> /// Indicates that the field should be used as a search facet /// </summary> [AttributeUsage(AttributeTargets.Property)] public class SearchFacetAttribute: Attribute { public SearchFacetAttribute() { } public int MinCount { get; set; } = int.MinValue; public int Limit { get; set; } = int.MaxValue; public virtual IEnumerable<string> GetTokens(object fieldValue) { if (fieldValue == null) return Enumerable.Empty<string>(); var value = fieldValue.ToString(); if (string.IsNullOrEmpty(value)) return Enumerable.Empty<string>(); return new[] { value }; } public string GetLabel(string stringValue) { return stringValue; } } } ================================================ FILE: Composite/Data/SearchableFieldAttribute.cs ================================================ using System; namespace Composite.Data { /// <summary> /// Indicates whether the field. /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class SearchableFieldAttribute : Attribute { /// <summary> /// Indicates whether the field should be a part of the search index. /// </summary> /// <param name="indexText">Indicates whether the field will be a part of the text index.</param> /// <param name="previewable">Indicates whether the field will will appear in search results.</param> /// <param name="faceted">Indicates whether the field will appear as a facet in search results.</param> public SearchableFieldAttribute(bool indexText, bool previewable, bool faceted) { IndexText = indexText; Previewable = previewable; Faceted = faceted; } /// <summary> /// Indicates whether the field will be a part of the text index. /// </summary> public bool IndexText { get; } /// <summary> /// Indicates whether the field value will appear in search results. /// </summary> public bool Previewable { get; } /// <summary> /// Indicates whether the field will appear as a facet in search results. /// </summary> public bool Faceted { get; } //public int PreviewOrder { get; }= 1000; //public int FacetFieldOrder { get; } = 1000; } } ================================================ FILE: Composite/Data/SearchableTypeAttribute.cs ================================================ using System; namespace Composite.Data { /// <summary> /// Indicates that the data of the given data type should be searchable. /// </summary> [AttributeUsage(AttributeTargets.Interface)] public class SearchableTypeAttribute: Attribute { } } ================================================ FILE: Composite/Data/SitemapNavigator.cs ================================================ using System; using System.Collections.ObjectModel; using System.Xml.Linq; using Composite.Core.Implementation; using System.Collections.Generic; namespace Composite.Data { /// <summary> /// Provide access to the C1 CMS sitemap structure and primary page attributes. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Sitemap")] public class SitemapNavigator : ImplementationContainer<SitemapNavigatorImplementation> { /// <summary> /// Initialize a new instance of the <see cref="SitemapNavigator"/> class using sitemap data from the provided <see cref="DataConnection"/>. /// </summary> /// <example> /// using (DataConnection dataConnection = new DataConnection()) /// { /// SitemapNavigator sitemapNavigator = new SitemapNavigator(dataConnection); /// string thisPageTitle = sitemapNavigator.CurrentPageNode.Title; /// } /// </example> /// <param name="connection">The <see cref="DataConnection"/> to read sitemap data from</param> public SitemapNavigator(DataConnection connection) : base(() => ImplementationFactory.CurrentFactory.CreateSitemapNavigator(connection)) { if (connection == null) throw new ArgumentNullException("connection"); } /// <summary> /// Gets a <see cref="PageNode"/> for a specific page id. /// </summary> /// <param name="id">Id of page to find.</param> /// <returns><see cref="PageNode"/> for the page or null if no page was found with the given id.</returns> public PageNode GetPageNodeById(Guid id) { return this.Implementation.GetPageNodeById(id); } /// <summary> /// Gets <see cref="PageNode"/>'s for all homepages. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "HomePage")] public IEnumerable<PageNode> HomePageNodes { get { return this.Implementation.HomePageNodes; } } /// <summary> /// Gets the Id's for all homepages. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "HomePage")] public IEnumerable<Guid> HomePageIds { get { return this.Implementation.HomePageIds; } } /// <summary> /// Gets the <see cref="PageNode"/> for the current page. /// </summary> public PageNode CurrentPageNode { get { return this.Implementation.CurrentPageNode; } } /// <summary> /// Gets the <see cref="PageNode"/> for the current homepage. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "HomePage")] public PageNode CurrentHomePageNode { get { return this.Implementation.CurrentHomePageNode; } } /// <summary> /// Gets the <see cref="PageNode"/> relating to the hostname. /// </summary> /// <param name="hostname">Hostname string to resolve to a <see cref="PageNode"/>.</param> /// <returns>The homepage <see cref="PageNode"/> element matching the specified hostname or the default homepage.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Hostname")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "hostname")] public PageNode GetPageNodeByHostname(string hostname) { return this.Implementation.GetPageNodeByHostname(hostname); } /// <summary> /// Gets the sitemaps for all sites. Do not modify this structure. To do modifications new up XElements taking sitemap root elements as parameter. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Sitemaps")] public ReadOnlyCollection<XElement> AllSitemapsXml { get { return this.Implementation.AllSitemapsXml; } } /// <summary> /// Gets the sitemap for the current site. Do not modify this structure. To do modifications new up XElements taking sitemap root elements as parameter. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Sitemap")] public XElement SitemapXml { get { return this.Implementation.SitemapXml; } } /// <summary> /// Gets the Id of the page currently being rendered /// </summary> public static Guid CurrentPageId { get { return ImplementationFactory.CurrentFactory.StatelessSitemapNavigator.CurrentPageId; } } /// <summary> /// Gets the Id of the top level page (homepage) for the page currently being rendered /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "HomePage")] public static Guid CurrentHomePageId { get { return ImplementationFactory.CurrentFactory.StatelessSitemapNavigator.CurrentHomePageId; } } } } ================================================ FILE: Composite/Data/SitemapScope.cs ================================================ namespace Composite.Data { /// <summary> /// Define a set of elements in a tree structure, relative to a particular node. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Sitemap")] public enum SitemapScope { /// <summary> /// This page. /// </summary> Current = 0, /// <summary> /// Children of this page. /// </summary> Children = 2, /// <summary> /// All descendants of this page. /// </summary> Descendants = 20, /// <summary> /// All descendants of this page and this page. /// </summary> DescendantsAndCurrent = 1, /// <summary> /// Pages sharing the same parent as this page, excluding this page. /// </summary> Siblings = 15, /// <summary> /// Pages sharing the same parent as this page, including this page. /// </summary> SiblingsAndSelf = 21, /// <summary> /// All ancestor pages /// </summary> Ancestors = 3, /// <exclude /> AncestorsAndCurrent = 4, /// <exclude /> Parent = 5, /// <exclude /> Level1 = 6, /// <exclude /> Level1AndSiblings = 16, /// <exclude /> Level1AndDescendants = 10, /// <exclude /> Level2 = 7, /// <exclude /> Level2AndSiblings = 17, /// <exclude /> Level2AndDescendants = 11, /// <exclude /> Level3 = 8, /// <exclude /> Level3AndSiblings = 18, /// <exclude /> Level3AndDescendants = 12, /// <exclude /> Level4 = 9, /// <exclude /> Level4AndSiblings = 19, /// <exclude /> Level4AndDescendants = 13, /// <exclude /> All = 14 } } ================================================ FILE: Composite/Data/StoreEventArgs.cs ================================================ using System; using System.Globalization; namespace Composite.Data { /// <summary> /// This class contains information for store change events. No specifics will be given as to which data item(s) were changed, /// but the store (type, scope, language) is available. /// /// Property DataEventsFired indicate if detailed data events have already been fired for the data store change. In situations where data /// was changed in the physical store by another process, detailed events cannot be fired and you need to rely on the StoreChange event to do cache flushed etc. /// </summary> /// <example> /// <code> /// void MyMethod() /// { /// DataEvents<IMyDataType>().OnStoreChange += new StoreEventHandler(DataEvents_StoreChanged); /// /// using (DataConnection connection = new DataConnection()) /// { /// IMyDataType myDataType = DataConnection.New<IMyDataType>(); /// myDataType.Name = "Foo"; /// /// connection.Add<IMyDataType>(myDataType); // This will fire the event - changes are made to the store! /// } /// } /// /// /// void DataEvents_StoreChanged(object sender, StoreEventArgs storeEventArgs) /// { /// Type dataType = storeEventArgs.DataType; // This will be the type that changed /// PublicationScope scope = storeEventArgs.PublicationScope; // The scope the event happened in - published vs. administrated /// CultureInfo locale = storeEventArgs.Locale; // The culture (language) the event happened in /// bool dataEventsFired = storeEventArgs.DataEventsFired; // True is detailed data item events have fired. False if a store reload happened and detailed events cannot be fired. /// } /// </code> /// </example> public class StoreEventArgs : EventArgs { private readonly Type _dataType; private readonly PublicationScope _publicationScope; private readonly CultureInfo _locale; private readonly bool _dataEventsFired; /// <summary> /// Initializes a new instance of the <see cref="StoreEventArgs"/> class. /// </summary> /// <param name="dataType">Type of the data.</param> /// <param name="publicationScope">The publication scope.</param> /// <param name="locale">The locale.</param> /// <param name="dataEventsFired">Value indicating whether detailed data events have been fired for this change event. /// When <c>false</c> the change happened outside the current process /// (in the physical store, perhaps done by another running instance). </param> /// <exclude/> internal StoreEventArgs(Type dataType, PublicationScope publicationScope, CultureInfo locale, bool dataEventsFired) { Verify.ArgumentNotNull(dataType, "dataType"); Verify.ArgumentNotNull(publicationScope, "publicationScope"); _dataType = dataType; _publicationScope = publicationScope; _locale = locale; _dataEventsFired = dataEventsFired; } /// <summary> /// Gets the data type that is the subject of the event fired. /// </summary> public Type DataType { get { return _dataType; } } /// <summary> /// Gets the data scope that is the subject of the event fired. /// </summary> public PublicationScope PublicationScope { get { return _publicationScope; } } /// <summary> /// Gets the locale that is the subject of the event fired. /// </summary> public CultureInfo Locale { get { return _locale; } } /// <summary> /// Gets a value indicating if detailed data events have been fired for this change event. When false the change happened outside the current process /// (in the physical store, perhaps done by another running instance). You can rely on detailed data events to do precise cache management and use the StoreChange event /// when DataEventsFired is false to do a complete cache flush. /// </summary> public bool DataEventsFired { get { return _dataEventsFired; } } } } ================================================ FILE: Composite/Data/StoreEventHandler.cs ================================================  namespace Composite.Data { /// <summary> /// The event handle type for data store change events. These events may be both internally and externally provoked. /// </summary> /// <param name="sender"></param> /// <param name="storeEventArgs"></param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Justification = "We keep handler in line tiwh DataEventHandler")] public delegate void StoreEventHandler(object sender, StoreEventArgs storeEventArgs); } ================================================ FILE: Composite/Data/StoreFieldTypeAttribute.cs ================================================ using System; using Composite.Data.DynamicTypes; namespace Composite.Data { /// <summary> /// Specifies what physical store type should be used to store this property. /// </summary> /// <example> This sample shows how to use the StoreFieldType attribute. /// Here a string field with a maximum of 40 characters. /// <code> /// // data interface attributes ... /// interface IMyDataType : IData /// { /// [StoreFieldType(PhysicalStoreFieldType.String, 40)] /// [ImmutableFieldId("{D75EA67F-AD14-4BAB-8547-6D87002809F1}")] /// string ProductName { get; set; } /// /// // more data properties ... /// /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class StoreFieldTypeAttribute : Attribute { private StoreFieldTypeAttribute() { this.IsNullable = false; } /// <summary> /// Specifies what physical store type should be used to store this property. /// This overload is intended for int, long, large string, date time, guid and bool. /// For decimal and string, use other overload where you can specify length values also. /// </summary> /// <param name="physicalStoreFieldType">PhysicalStoreFieldType to use</param> public StoreFieldTypeAttribute(PhysicalStoreFieldType physicalStoreFieldType) : this() { switch (physicalStoreFieldType) { case PhysicalStoreFieldType.Integer: this.StoreFieldType = StoreFieldType.Integer; return; case PhysicalStoreFieldType.Long: this.StoreFieldType = StoreFieldType.Long; return; case PhysicalStoreFieldType.LargeString: this.StoreFieldType = StoreFieldType.LargeString; return; case PhysicalStoreFieldType.DateTime: this.StoreFieldType = StoreFieldType.DateTime; return; case PhysicalStoreFieldType.Guid: this.StoreFieldType = StoreFieldType.Guid; return; case PhysicalStoreFieldType.Boolean: this.StoreFieldType = StoreFieldType.Boolean; return; } throw new ArgumentException(string.Format("[{0}] - field type {1}.{2} require some aditional arguments in the attribute constructor.", this.GetType().Name, typeof(PhysicalStoreFieldType).Name, physicalStoreFieldType)); } /// <summary> /// Specifies what physical store type should be used to store this property. /// This overload is intended for string. /// </summary> /// <param name="physicalStoreFieldType">PhysicalStoreFieldType to use - PhysicalStoreFieldType.String expected</param> /// <param name="maxLength">Number of characters to reserve in physical store</param> public StoreFieldTypeAttribute(PhysicalStoreFieldType physicalStoreFieldType, int maxLength) : this() { switch (physicalStoreFieldType) { case PhysicalStoreFieldType.String: this.StoreFieldType = StoreFieldType.String(maxLength); return; } throw new ArgumentException(string.Format("[{0}] - field type {1}.{2} does not take an int argument in the attribute constructor.", this.GetType().Name, typeof(PhysicalStoreFieldType).Name, physicalStoreFieldType)); } /// <summary> /// Specifies what physical store type should be used to store this property. /// This overload is intended for decimal. /// </summary> /// <param name="physicalStoreFieldType">PhysicalStoreFieldType to use - PhysicalStoreFieldType.Decimal expected</param> /// <param name="numericPrecision">Numeric precision for decimal</param> /// <param name="numericScale">Numeric scale for decimal</param> public StoreFieldTypeAttribute(PhysicalStoreFieldType physicalStoreFieldType, int numericPrecision, int numericScale) : this() { switch (physicalStoreFieldType) { case PhysicalStoreFieldType.Decimal: this.StoreFieldType = StoreFieldType.Decimal(numericPrecision, numericScale); return; } throw new ArgumentException(string.Format("[{0}] - field type {1}.{2} does not take two 'int' arguments in the attribute constructor.", this.GetType().Name, typeof(PhysicalStoreFieldType).Name, physicalStoreFieldType)); } /// <exclude /> public StoreFieldType StoreFieldType { get; private set; } /// <summary> /// When true the data store can allow null values. Default is false. /// </summary> public bool IsNullable { get; set; } } } ================================================ FILE: Composite/Data/StoreSortOrderAttribute.cs ================================================ using System; namespace Composite.Data { /// <summary> /// Add this attribute to your data interface to control the physical store sort order of data. /// This concept is known as the clustered index on SQL Server. /// </summary> /// <example> This sample shows how to use the StoreSortOrder attribute. /// <code> /// [StoreSortOrderAttribute("Date", "Title")] /// // (other IData attributes) /// interface IMyDataType : IData /// { /// // data type properties, must include Date and Title since we ref them above /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = true)] public sealed class StoreSortOrderAttribute : Attribute { /// <summary> /// Sprcify the names of properties to order data by in the physical store. The specified names must exist as properties on your data type. /// </summary> /// <param name="sortOrder">Names of properties to order data by in the physical store.</param> public StoreSortOrderAttribute(params string[] sortOrder) { this.SortOrder = sortOrder; } /// <exclude /> public string[] SortOrder { get; private set; } } } ================================================ FILE: Composite/Data/Streams/CachedMemoryStream.cs ================================================ using System.IO; namespace Composite.Data.Streams { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class CachedMemoryStream : MemoryStream { private byte[] _data = null; /// <exclude /> public byte[] Data { get { return _data; } } /// <exclude /> public override void Close() { SaveData(); base.Close(); } /// <exclude /> protected override void Dispose(bool disposing) { SaveData(); base.Dispose(disposing); } private void SaveData() { if (_data == null) { this.Seek(0, SeekOrigin.Begin); _data = new byte[this.Length]; this.Read(_data, 0, (int)this.Length); } } } } ================================================ FILE: Composite/Data/Streams/FileStreamManagerAttribute.cs ================================================ using System; namespace Composite.Data.Streams { /// <summary> /// Expected on <see cref="Composite.Data.Types.IFile"/> classes to identify what <see cref="IFileStreamManager"/> can provide read/write and monitoring access to files. /// </summary> [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public class FileStreamManagerAttribute : Attribute { private Type _fileStreamManagerType; /// <summary> /// Identify the <see cref="IFileStreamManager"/> that provide read/write and monitoring access to the file represented by the <see cref="Composite.Data.Types.IFile"/> this /// <see cref="FileStreamManagerAttribute"/> is attached to. /// </summary> /// <param name="fileStreamManagerType">the type of the class implementing <see cref="IFileStreamManager"/> for this file.</param> public FileStreamManagerAttribute(Type fileStreamManagerType) { _fileStreamManagerType = fileStreamManagerType; } internal Type FileStreamManagerResolverType { get { return _fileStreamManagerType; } } } } ================================================ FILE: Composite/Data/Streams/FileStreamManagerLocator.cs ================================================ using System; using System.Collections.Generic; using Composite.Core.Collections.Generic; using Composite.C1Console.Events; using Composite.Core.Logging; namespace Composite.Data.Streams { internal static class FileStreamManagerLocator { private static ResourceLocker<Resources> _resourceLocker = new ResourceLocker<Resources>(new Resources(), Resources.Initialize); static FileStreamManagerLocator() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static IFileStreamManager GetFileStreamManager(Type fileType) { if (fileType == null) throw new ArgumentNullException("fileType"); IFileStreamManager fileStreamManager; if (_resourceLocker.Resources.FileStreamManagerCache.TryGetValue(fileType, out fileStreamManager) == false) { using (_resourceLocker.ReadLocker) { if (_resourceLocker.Resources.FileStreamManagerCache.TryGetValue(fileType, out fileStreamManager) == false) { object[] attributes = fileType.GetCustomAttributes(typeof (FileStreamManagerAttribute), true); if (attributes.Length == 0) throw new InvalidOperationException(string.Format("The type '{0}' is missing the attribute '{1}'", fileType, typeof (FileStreamManagerAttribute))); FileStreamManagerAttribute fileStreamManagerResolverAttribute = (FileStreamManagerAttribute) attributes[0]; Type fileStreamManagerType = fileStreamManagerResolverAttribute.FileStreamManagerResolverType; if (fileStreamManagerType == null) throw new InvalidOperationException(string.Format("The constructor argument of '{0}' may not be null", typeof (FileStreamManagerAttribute))); if (typeof (IFileStreamManager).IsAssignableFrom(fileStreamManagerType) == false) throw new InvalidOperationException( string.Format("The type '{0}' does not implement the interface '{1}'", fileStreamManagerType, typeof (IFileStreamManager))); fileStreamManager = (IFileStreamManager) Activator.CreateInstance(fileStreamManagerType); _resourceLocker.Resources.FileStreamManagerCache.Add(fileType, fileStreamManager); } } } return fileStreamManager; } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private sealed class Resources { public Hashtable<Type, IFileStreamManager> FileStreamManagerCache { get; set; } public static void Initialize(Resources resources) { resources.FileStreamManagerCache = new Hashtable<Type, IFileStreamManager>(); } } } } ================================================ FILE: Composite/Data/Streams/IFileStreamManager.cs ================================================ using System.IO; using Composite.Data.Types; namespace Composite.Data.Streams { /// <summary> /// Declare what type of change happened to a file. /// </summary> public enum FileChangeType { /// <exclude /> Undefined = 0, /// <exclude /> Modified = 1, /// <exclude /> Renamed = 2, /// <exclude /> Deleted = 3 } /// <summary> /// Delegate used to signal changes to a file. /// </summary> public delegate void OnFileChangedDelegate(string filePath, FileChangeType changeType); /// <summary> /// Data Providers which expose <see cref="Composite.Data.Types.IFile"/> elements /// (like <see cref="Composite.Data.Types.IMediaFile"/> for a custom Media File Provider) expose access to stream reads/writes by annotating /// the class implementing <see cref="Composite.Data.Types.IFile"/> with the <see cref="FileStreamManagerAttribute"/> attribute, /// passing the type of a <see cref="IFileStreamManager"/> as attribute parameter. /// C1 CMS will, via the attribute on the <see cref="Composite.Data.Types.IFile"/>, get the type responsible for stream reads/writes. /// /// The class implementing this interface is expected to provide read/write access to the file store being introduced by a file oriented File Provider. /// </summary> /// <example> /// Here is an example of how to inform C1 CMS about IFileStreamManager /// <code> /// [FileStreamManager(typeof(MyFileStreamManager))] /// public abstract class SomeFile : IFile /// { /// /// .... /// } /// </code> /// </example> public interface IFileStreamManager { /// <summary> /// Returns the stream for the given file, represented as IFile. The stream is for reading. /// </summary> /// <param name="file">The data element representing the file for which a read stream is desired.</param> /// <returns>Stream for reading</returns> Stream GetReadStream(IFile file); /// <summary> /// Returns the stream for the given file, represented as IFile. This may be a new file, in which case the file stream manager is expected to create the file. /// </summary> /// <param name="file">The data element representing the file for which a write stream is desired.</param> /// <returns>Stream for writing</returns> Stream GetNewWriteStream(IFile file); /// <summary> /// The provided handler should be invoked if the file, represented as IFile, changes in the concrete store this IFileStreamManager represents. /// </summary> /// <param name="file">The file to monitor for file changes</param> /// <param name="handler">The handler to be invoked on changes</param> void SubscribeOnFileChanged(IFile file, OnFileChangedDelegate handler); } } ================================================ FILE: Composite/Data/TitleAttribute.cs ================================================ using System; namespace Composite.Data { /// <summary> /// Add this attribute to your data interface to give it a human readable title to be used in the C1 Console /// </summary> /// <example> This sample shows how to use the Title attribute. /// <code> /// [Title("My Data Type")] /// // (other IData attributes) /// interface IMyDataType : IData /// { /// // data type properties /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = false)] public sealed class TitleAttribute : Attribute { /// <summary> /// Set the title /// </summary> /// <param name="title">The (human readable) title to give the data type</param> public TitleAttribute(string title) { this.Title = title; } /// <exclude /> public string Title { get; private set; } } } ================================================ FILE: Composite/Data/Transactions/TransactionsFacade.cs ================================================ using System.Transactions; using System; namespace Composite.Data.Transactions { /// <summary> /// Ensures C1 compiant System.Transactions.TransactionScope services. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class TransactionsFacade { /// <exclude /> public static TimeSpan DefaultTransactionTimeout { get { return TimeSpan.FromMinutes(3); } } /// <exclude /> public static IsolationLevel DefaultTransactionIsolationLevel { get { return IsolationLevel.RepeatableRead; } } /// <exclude /> public static TransactionScope CreateNewScope() { return Create(false, DefaultTransactionTimeout); } /// <exclude /> public static TransactionScope Create(bool requiresNew) { return Create(requiresNew, DefaultTransactionTimeout); } /// <exclude /> public static TransactionScope Create(bool requiresNew, TimeSpan timeSpan) { IsolationLevel isolationLevel = (Transaction.Current != null ? Transaction.Current.IsolationLevel : DefaultTransactionIsolationLevel); var transOptions = new TransactionOptions { IsolationLevel = isolationLevel, Timeout = timeSpan }; return new TransactionScope(requiresNew ? TransactionScopeOption.RequiresNew : TransactionScopeOption.Required, transOptions); } /// <exclude /> public static TransactionScope CreateNewScope(TimeSpan timeSpan) { return Create(false, timeSpan); } /// <exclude /> public static TransactionScope SuppressTransactionScope() { return new TransactionScope(TransactionScopeOption.Suppress); } } } ================================================ FILE: Composite/Data/TreeOrderingProfileAttribute.cs ================================================ using System; namespace Composite.Data { /// <summary> /// Assign this to properties on your IData interfaces to control default ordering of tree items. /// </summary> /// <example> This sample shows how to use the TreeOrdering attribute. /// <code> /// // data interface attributes ... /// interface IMyDataType : IData /// { /// [TreeOrdering(1)] /// [StoreFieldType(PhysicalStoreFieldType.String, 40)] /// [ImmutableFieldId("{D75EA67F-AD14-4BAB-8547-6D87002809F1}")] /// string ProductName { get; set; } /// /// // more data properties ... /// /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class TreeOrderingAttribute : Attribute { /// <summary> /// Specify that this field should be used for default tree node ordering. Order is by default ascending. /// Multiple fields on a data type may have ordering. In that case the orderPriority has importance. /// </summary> /// <param name="orderPriority">Priority controls which fields are used first when ordering. Low number win.</param> public TreeOrderingAttribute(int orderPriority) { this.Priority = orderPriority; } /// <summary> /// Specify that this field should be used for default tree node ordering. Order is by default ascending. /// Multiple fields on a data type may have ordering. In that case the orderPriority has importance. /// </summary> /// <param name="orderPriority">Priority controls which fields are used first when ordering. Low number win.</param> /// <param name="orderDescending">When true this field will be used in descending (Z-A) order.</param> public TreeOrderingAttribute(int orderPriority, bool orderDescending) { this.Priority = orderPriority; this.Descending = orderDescending; } /// <summary> /// Priority for ordering. When multiple fields have this attribute attached this field is used. Low number win. /// </summary> public int Priority { get; set; } /// <summary> /// When true descending order (Z-A) will be used. /// </summary> public bool Descending { get; set; } } } ================================================ FILE: Composite/Data/Types/ExtensionMethods/IFileExtensions.cs ================================================ using System.IO; using System.Web.Hosting; using Composite.Core.IO; using Composite.Data.Plugins.DataProvider.Streams; using Composite.Data.Streams; namespace Composite.Data.Types { /// <summary> /// Extension methods for IFile /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class IFileExtensions { /// <exclude /> public static Stream GetReadStream(this IFile file) { IFileStreamManager manager = FileStreamManagerLocator.GetFileStreamManager(file.GetType()); return manager.GetReadStream(file); } /// <exclude /> public static Stream GetNewWriteStream(this IFile file) { IFileStreamManager manager = FileStreamManagerLocator.GetFileStreamManager(file.GetType()); return manager.GetNewWriteStream(file); } /// <exclude /> public static void SubscribeOnChanged(this IFile file, OnFileChangedDelegate handler) { IFileStreamManager manager = FileStreamManagerLocator.GetFileStreamManager(file.GetType()); manager.SubscribeOnFileChanged(file, handler); } /// <summary> /// Returns all text from the stream associated with the provided IFile /// </summary> public static string ReadAllText(this IFile file) { using (Stream fileStream = GetReadStream(file)) { using (C1StreamReader sr = new C1StreamReader(fileStream)) { return sr.ReadToEnd(); } } } /// <summary> /// Replaces the all files content with some new content /// </summary> /// <param name="file"></param> /// <param name="newContent"></param> public static void SetNewContent(this IFile file, string newContent) { using (C1StreamWriter sw = new C1StreamWriter(GetNewWriteStream(file))) { sw.Write(newContent); } } internal static string GetFilePath(this IFile file) { return (file is FileSystemFileBase) ? (file as FileSystemFileBase).SystemPath : null; } internal static string GetRelativeFilePath(this IFile file) { string filePath = GetFilePath(file); if (filePath == null) return null; return filePath.StartsWith(PathUtil.BaseDirectory) ? filePath.Substring(PathUtil.BaseDirectory.Length) : filePath; } } } ================================================ FILE: Composite/Data/Types/ExtensionMethods/IMediaFileExtensions.cs ================================================ namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class IMediaFileExtensions { /// <exclude /> public static string GetKeyPath(this IMediaFile mediaFile) { return mediaFile.StoreId + ":" + mediaFile.Id; } /// <exclude /> public static string GetCompositePath(this IMediaFile mediaFile) { return GetCompositePath(mediaFile.StoreId, mediaFile.FolderPath, mediaFile.FileName); } /// <exclude /> public static string GetCompositePath(string storeId, string folderPath, string filename) { if (folderPath != "/") { return storeId + ":" + folderPath + "/" + filename; } return storeId + ":/" + filename; } } } ================================================ FILE: Composite/Data/Types/ExtensionMethods/IMediaFileFolderExtensions.cs ================================================ namespace Composite.Data.Types { internal static class IMediaFileFolderExtensions { public static string GetKeyPath(this IMediaFileFolder mediaFileFolder) { return mediaFileFolder.StoreId + ":" + mediaFileFolder.Id; } public static string GetCompositePath(this IMediaFileFolder mediaFileFolder) { return string.Format("{0}:{1}", mediaFileFolder.StoreId, mediaFileFolder.Path); } } } ================================================ FILE: Composite/Data/Types/ExtensionMethods/Use_parent_namespace.txt ================================================  use "Composite.Data.Types" as namespace in this folder. ================================================ FILE: Composite/Data/Types/Foundation/ExceptingSerializerHandler.cs ================================================ using System; using Composite.Core.Serialization; namespace Composite.Data.Types.Foundation { /// <summary> /// This is for forcing the developer to implement thier own ISerializerHandler /// </summary> internal sealed class ExceptingSerializerHandler : ISerializerHandler { public string Serialize(object objectToSerialize) { throw new NotSupportedException(); } public object Deserialize(string serializedObject) { throw new NotSupportedException(); } } } ================================================ FILE: Composite/Data/Types/Foundation/PagePublishControlledAuxiliary.cs ================================================ using System.Collections.Generic; using System.Linq; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.PublishScheduling; using Composite.Data.Transactions; namespace Composite.Data.Types.Foundation { internal sealed class PagePublishControlledAuxiliary : IPublishControlledAuxiliary { public void OnAfterDataUpdated(IData data) { var page = (IPage)data; IEnumerable<IPagePlaceholderContent> pagePlaceholderContents; using (new DataScope(DataScopeIdentifier.Administrated)) { pagePlaceholderContents = (from content in DataFacade.GetData<IPagePlaceholderContent>(false) where content.PageId == page.Id && content.VersionId == page.VersionId select content).ToList(); } if (page.PublicationStatus == GenericPublishProcessController.Published) { using (var transactionScope = TransactionsFacade.CreateNewScope()) { using (new DataScope(DataScopeIdentifier.Public)) { DataFacade.Delete<IPagePlaceholderContent>( f => f.PageId == page.Id && f.VersionId == page.VersionId); } foreach (var pagePlaceholderContent in pagePlaceholderContents) { pagePlaceholderContent.PublicationStatus = page.PublicationStatus; DataFacade.Update(pagePlaceholderContent); } using (new DataScope(DataScopeIdentifier.Administrated)) { var publishSchedule = PublishScheduleHelper.GetPublishSchedule(typeof (IPage), page.Id.ToString(), page.DataSourceId.LocaleScope.Name); if (publishSchedule != null) { DataFacade.Delete(publishSchedule); } } transactionScope.Complete(); } } else { foreach (var pagePlaceholderContent in pagePlaceholderContents) { if (pagePlaceholderContent.PublicationStatus != page.PublicationStatus) { pagePlaceholderContent.PublicationStatus = page.PublicationStatus; DataFacade.Update(pagePlaceholderContent); } } } } public void OnAfterBuildNew(IData data) { // Noop } } } ================================================ FILE: Composite/Data/Types/ICompositionContainer.cs ================================================ using System; namespace Composite.Data.Types { /// <summary> /// Allows assigning meta data fields to different tabs in UI. /// There's always one default instance with label "Metadata". /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [KeyPropertyName("Id")] [ImmutableTypeId("{ECE41A30-0FC4-4902-B5C5-A607D8A9B298}")] [CachingAttribute(CachingType.Full)] [DataScope(DataScopeIdentifier.PublicName)] public interface ICompositionContainer : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{B9E34D3F-C8C0-4692-8EE4-31B174C96477}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 256)] [ImmutableFieldId("{572769B5-89CA-4ee8-9CD1-DE9D61702CA0}")] string Label { get; set; } } } ================================================ FILE: Composite/Data/Types/ICustomFunctionCallEditorMapping.cs ================================================ namespace Composite.Data.Types { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{67cf4b4d-1376-4589-abd4-5cfa9966670b}")] [KeyPropertyName("FunctionName")] [DataScope(DataScopeIdentifier.PublicName)] [CachingAttribute(CachingType.Full)] public interface ICustomFunctionCallEditorMapping: IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 255)] [ImmutableFieldId("{1145f17b-c93b-443f-917e-88b7cc4e85c5}")] string FunctionName { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 255)] [ImmutableFieldId("{96671d53-4657-439b-8abd-4e01f3c80fd7}")] string CustomEditorPath { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Integer, IsNullable = true)] [ImmutableFieldId("{3af4e226-c06d-448d-a93e-3457cd4e9bf6}")] int? Width { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Integer, IsNullable = true)] [ImmutableFieldId("{7bd25407-193b-42e5-ae59-26a99bdee2c1}")] int? Height { get; set; } } } ================================================ FILE: Composite/Data/Types/IDataItemTreeAttachmentPoint.cs ================================================ using System; using Composite.C1Console.Elements.Plugins.ElementAttachingProvider; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; namespace Composite.Data.Types { /// <summary> /// Represents a link between a tree definition and a data item. /// F.e. a tree that shows navigation elements, attached to a specific C1 page. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{24CDC117-4510-41C4-8A73-D1B4CD85FE2A}")] [KeyPropertyName(nameof(Id))] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [Caching(CachingType.Full)] public interface IDataItemTreeAttachmentPoint : IData { /// <summary> /// The Id value for the attachment point. /// </summary> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{BEB44A8E-37FD-4FA6-A420-B252B8590AD6}")] Guid Id { get; set; } /// <summary> /// The Id of the tree that is attached. /// </summary> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{FA9A44E0-9D41-491A-86C0-BC5189FFC023}")] string TreeId { get; set; } /// <summary> /// The position in which the tree elements should be shown, f.e. "Top" or "Bottom". See <see cref="ElementAttachingProviderPosition"/> /// </summary> [StoreFieldType(PhysicalStoreFieldType.String, 64)] [ImmutableFieldId("{6624A6CF-29DC-4E6A-8B88-25514BC00758}")] string Position { get; set; } /// <summary> /// The data type of the data item, to which a tree is attached. /// </summary> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{F08DB525-2218-4379-A6F6-A9A904DEF6FE}")] string InterfaceType { get; set; } /// <summary> /// The key value of the data item to which a tree is attached. /// </summary> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{8A50C365-586D-45F5-8881-EC3878E16593}")] string KeyValue { get; set; } } } ================================================ FILE: Composite/Data/Types/IDynamicTypeFormDefinitionFile.cs ================================================ namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{42f4ca9a-b18b-4d62-a4f5-5f04c06109ed}")] public interface IDynamicTypeFormDefinitionFile : IFile { } } ================================================ FILE: Composite/Data/Types/IFile.cs ================================================ using Composite.Data.Types.Foundation; using Composite.Core.Serialization; using Composite.Data.DynamicTypes; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [BuildNewHandler(typeof(IFileBuildNewHandler))] [DataScope(DataScopeIdentifier.PublicName)] [SerializerHandler(typeof(ExceptingSerializerHandler))] public interface IFile : IData { /// <exclude /> [ImmutableFieldId("{B9B50947-EE78-4744-9128-0832A66243D5}")] [StoreFieldType(PhysicalStoreFieldType.String, 512)] string FolderPath { get; set; } /// <exclude /> [ImmutableFieldId("{4FD98564-6077-4c6d-86E1-9C7F44B65E50}")] [StoreFieldType(PhysicalStoreFieldType.String, 128)] [SearchableField(true, false, false)] string FileName { get; set; } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class IFileUtils { /// <exclude /> public static bool ValidateValueLengths(this IFile file) { if ((file.FolderPath != null) && (file.FolderPath.Length > DataTypeDescriptor.Fields["FolderPath"].StoreType.MaximumLength)) return false; if ((file.FileName != null) && (file.FileName.Length > DataTypeDescriptor.Fields["FileName"].StoreType.MaximumLength)) return false; return true; } private static DataTypeDescriptor _dataTypeDescriptor = null; private static DataTypeDescriptor DataTypeDescriptor { get { if (_dataTypeDescriptor == null) { _dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(typeof(IFile)); } return _dataTypeDescriptor; } } } } ================================================ FILE: Composite/Data/Types/IFileBuildNewHandler.cs ================================================ using System; using System.CodeDom; using System.Collections.Generic; using System.IO; using Composite.C1Console.Events; using Composite.Core.Types; using Composite.Data.DynamicTypes; using Composite.Data.Foundation; using Composite.Data.Foundation.CodeGeneration; using Composite.Data.Streams; namespace Composite.Data.Types { internal static class FileBuildNewHandlerTypesManager { private static readonly object _lock = new object(); private static Dictionary<Type, Type> _fileBuildNewHandlerTypes = new Dictionary<Type, Type>(); static FileBuildNewHandlerTypesManager() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } internal static Type GetFileBuilderNewHandler(Type dataType) { Type result; if (!_fileBuildNewHandlerTypes.TryGetValue(dataType, out result)) { lock(_lock) { if (!_fileBuildNewHandlerTypes.TryGetValue(dataType, out result)) { DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(dataType); string fullName = EmptyDataClassCodeGenerator.GetEmptyClassTypeFullName(dataTypeDescriptor); result = TypeManager.TryGetType(fullName); if (result == null) { CodeAttributeDeclaration codeAttributeDeclaration = new CodeAttributeDeclaration( new CodeTypeReference(typeof(FileStreamManagerAttribute)), new [] { new CodeAttributeArgument(new CodeTypeOfExpression(typeof(IFileEmptyDataClassFileStreamManager))) }); result = EmptyDataClassTypeManager.CreateEmptyDataClassType(dataTypeDescriptor, typeof(IFileEmptyDataClassBase), codeAttributeDeclaration); } _fileBuildNewHandlerTypes.Add(dataType, result); } } } return result; } private static void Flush() { _fileBuildNewHandlerTypes = new Dictionary<Type, Type>(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } } internal sealed class IFileBuildNewHandler : IBuildNewHandler { public Type GetTypeToBuild(Type dataType) { return FileBuildNewHandlerTypesManager.GetFileBuilderNewHandler(dataType); } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class IFileEmptyDataClassBase : EmptyDataClassBase { private CachedMemoryStream _currentWriteStream; private Type _interfaceType; /// <exclude /> public IFileEmptyDataClassBase() { _interfaceType = typeof(IFile); } /// <exclude /> public CachedMemoryStream CurrentWriteStream { get { return _currentWriteStream; } set { _currentWriteStream = value; } } /// <exclude /> protected override Type _InterfaceType { get { return _interfaceType; } } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class IFileEmptyDataClassFileStreamManager : IFileStreamManager { /// <exclude /> public Stream GetReadStream(IFile file) { IFileEmptyDataClassBase castedFile = (IFileEmptyDataClassBase)file; if (castedFile.CurrentWriteStream == null) { return new MemoryStream(new byte[] { }); } else { return new MemoryStream(castedFile.CurrentWriteStream.Data); } } /// <exclude /> public Stream GetNewWriteStream(IFile file) { IFileEmptyDataClassBase castedFile = (IFileEmptyDataClassBase)file; castedFile.CurrentWriteStream = new CachedMemoryStream(); return castedFile.CurrentWriteStream; } /// <exclude /> public void SubscribeOnFileChanged(IFile file, OnFileChangedDelegate handler) { // Do nothing... } } } ================================================ FILE: Composite/Data/Types/IFileServices.cs ================================================ using System; using System.IO; using System.Linq; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class IFileServices { /// <exclude /> public static T GetFile<T>(string filePath) where T : class, IFile { string folderPath = Path.GetDirectoryName(filePath); string fileName = Path.GetFileName(filePath); var foundFile = (from file in DataFacade.GetData<T>() where string.Compare(file.FolderPath, folderPath, StringComparison.OrdinalIgnoreCase) == 0 && string.Compare(file.FileName, fileName, StringComparison.OrdinalIgnoreCase) == 0 select file).ToList(); if (foundFile.Count == 0) throw new InvalidOperationException(string.Format("Missing file '{0}'", filePath)); if (foundFile.Count > 1) throw new InvalidOperationException(string.Format("More than one file named '{0}'", filePath)); return foundFile[0]; } /// <exclude /> public static T TryGetFile<T>(string filePath) where T : class, IFile { string folderPath = Path.GetDirectoryName(filePath); string fileName = Path.GetFileName(filePath); var foundFile = (from file in DataFacade.GetData<T>() where file.FolderPath.Equals(folderPath, StringComparison.OrdinalIgnoreCase) && file.FileName.Equals(fileName, StringComparison.OrdinalIgnoreCase) select file).ToList(); if (foundFile.Count == 0) return null; if (foundFile.Count > 1) return null; return foundFile[0]; } } } ================================================ FILE: Composite/Data/Types/IFlowInformation.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{40063ED1-D547-4aff-AD58-F0BB68D571AC}")] [KeyPropertyName("Id")] [LabelPropertyName("Id")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] public interface IFlowInformation : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{375703F5-33AA-45c7-B3B1-401726A9A98C}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 64)] [ImmutableFieldId("{829CC401-E0D0-427b-9DCD-4AD19E6FBCB3}")] [NotNullValidator()] [ForeignKey(typeof(IUser), "Username", AllowCascadeDeletes = true)] string Username { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 64)] [ImmutableFieldId("{57AF5100-F625-4640-A418-BC149A22B718}")] [NotNullValidator()] string ConsoleId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{5C389A14-B2C6-494e-A14B-1E1E38ECFFDD}")] string SerializedFlowToken { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{9432E3D8-8C66-47dd-B71D-A9D5C84E855C}")] string SerializedEntityToken { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{D2AE7893-4C3B-419a-8BC3-5387457AA9E4}")] string SerializedActionToken { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.DateTime)] [ImmutableFieldId("{AF38EF8B-34FA-4d42-B49B-E427259E00F3}")] DateTime TimeStamp { get; set; } } } ================================================ FILE: Composite/Data/Types/IFolderWhiteList.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Composite.Core.IO; namespace Composite.Data.Types { /// <summary> /// Reference to a folder to be shown in the 'Layout' perspective. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{b831fee3-fb55-44be-b00d-034bbd83574f}")] [KeyPropertyName(0, "KeyName")] [KeyPropertyName(1, "TildeBasedPath")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.AdministratedName)] public interface IFolderWhiteList : IData { /// <exclude /> [ImmutableFieldId("{cb0bb5a7-c1fe-47a1-bfb4-6565bc9ffd4d}")] [StoreFieldType(PhysicalStoreFieldType.String, 128)] string KeyName { get; set; } /// <exclude /> [ImmutableFieldId("{d03415bd-ec41-4a57-8072-59e0a761f113}")] [StoreFieldType(PhysicalStoreFieldType.String, 512)] string TildeBasedPath { get; set; } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class IFolderWhiteListExtensions { /// <exclude /> public static string GetTildePath(string fullPath) { try { if (PathUtil.BaseDirectory.StartsWith(fullPath)) { return "~\\"; } string withoutBase = fullPath.Substring(PathUtil.BaseDirectory.Length); if (withoutBase.StartsWith("\\") == false) { withoutBase = "\\" + withoutBase; } return "~" + withoutBase; } catch (Exception ex) { throw new InvalidOperationException(string.Format("Failed to get tilde based path from '{0}'", fullPath), ex); } } /// <exclude /> public static string GetFullPath(this IFolderWhiteList folderWhiteList) { return PathUtil.Resolve(folderWhiteList.TildeBasedPath); } } } ================================================ FILE: Composite/Data/Types/IHostnameBinding.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Title("Hostname mapping")] [AutoUpdateble] [ImmutableTypeId("{2B0B1268-7237-4482-97A3-1BD4CAD6A08C}")] [KeyPropertyName("Id")] [LabelPropertyName("Hostname")] [DataScope(DataScopeIdentifier.PublicName)] [Caching(CachingType.Full)] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] public interface IHostnameBinding : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{405A7A25-6E53-4DDF-A6C2-26714D26D1F5}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 255, IsNullable = false)] [ImmutableFieldId("{36E7E803-178A-4453-9B5B-BF7148BA077B}")] [RegexValidator(@"^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$")] [NotNullValidator] string Hostname { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 64, IsNullable = false)] [ImmutableFieldId("{A9C79722-D62A-481A-B1DE-CFB37A68EB9A}")] [NotNullValidator] string Culture { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{2C2AEBF7-2CFC-4B6B-9199-991E4ABD8FFC}")] [DefaultFieldGuidValue("{00000000-0000-0000-0000-000000000000}")] Guid HomePageId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 255, IsNullable = true)] [ImmutableFieldId("{B0ADBBBF-15C9-4902-B202-BD4A1014725D}")] string PageNotFoundUrl { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString, IsNullable = true)] [ImmutableFieldId("{80C298F2-F493-465D-9F28-4F50DD0C03D5}")] string Aliases { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Boolean)] [ImmutableFieldId("{3ED674CC-24C2-2DDB-C53D-71421AA03127}")] bool IncludeHomePageInUrl { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Boolean)] [ImmutableFieldId("{A554BD68-C2F5-6F6F-4D3B-1FC2760BDE38}")] bool IncludeCultureInUrl { get; set; } /// <summary> /// When set to <value>true</value>, the system will generate HTTPS links to the hostname and /// will make automatic redirects from HTTP to HTTPS for the given hostname. /// </summary> [StoreFieldType(PhysicalStoreFieldType.Boolean)] [DefaultFieldBoolValue(false)] [ImmutableFieldId("{1F45F2E7-2FAF-4F33-ACCA-BFF32EF7818A}")] bool EnforceHttps { get; set; } /// <summary> /// When set to <value>true</value>, the system will use "HTTP 301 Permanent Redirect" when /// redirecting from an alias to the hostname. /// </summary> [StoreFieldType(PhysicalStoreFieldType.Boolean)] [DefaultFieldBoolValue(true)] [ImmutableFieldId("{d933184a-19c1-4292-8e2e-f4a1a163f087}")] bool UsePermanentRedirect { get; set; } } } ================================================ FILE: Composite/Data/Types/IImageFile.cs ================================================ using Composite.Core.WebClient.Renderings.Data; namespace Composite.Data.Types { /// <summary> /// This data interface represents a image media file in C1 CMS. This can be used to query images through a <see cref="Composite.Data.DataConnection"/>. /// </summary> [Title("C1 Image File")] [ImmutableTypeId("{BF54E59A-0EBC-4162-95B9-C46EE271C7A9}")] [KeyTemplatedXhtmlRenderer(XhtmlRenderingType.Embedable, XhtmlRenderingEncoding.AttributeContent, "<img src='~/media({field:StoreId}:{field:Id})' alt='{field:Title}' />")] public interface IImageFile : IMediaFile { } } ================================================ FILE: Composite/Data/Types/IInlineFunction.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{8CCA4975-8FE0-464A-A806-A098E9138FAE}")] [KeyPropertyName("Id")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [Caching(CachingType.Full)] public interface IInlineFunction : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{720643FF-9743-414B-AE2C-88A8CC4DADBB}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 128)] [ImmutableFieldId("{A3710B8F-BD8E-4A9A-BB7B-A796198C55B9}")] [Composite.Data.Validation.Validators.StringSizeValidator(1, 128)] [NotNullValidator()] string Name { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 128)] [ImmutableFieldId("{8C5BA3EE-FE14-4346-8CF2-8A0BEDAF94FB}")] [Composite.Data.Validation.Validators.StringSizeValidator(1, 128)] string Namespace { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{935757BE-4959-4CBD-92BC-2ABD40C2969B}")] string Description { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 512)] [ImmutableFieldId("{623358E0-506A-463F-A0D5-C6B6B8F916C3}")] string CodePath { get; set; } } } ================================================ FILE: Composite/Data/Types/IInlineFunctionAssemblyReference.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{D3AC39D8-1FE6-4BB3-BFEA-2DAFECACF0FC}")] [KeyPropertyName("Id")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [Caching(CachingType.Full)] public interface IInlineFunctionAssemblyReference : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{9F7C1C30-E115-479D-9471-AEB83A9AAF63}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{E08E79F6-ED40-447D-A2B6-592704FE7B96}")] Guid Function { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 128)] [ImmutableFieldId("{30DA8550-252A-4EBB-A9D4-78DA26784E4B}")] [NotNullValidator()] string Name { get; set; } /// <summary> /// This could be either Bin or System /// </summary> [StoreFieldType(PhysicalStoreFieldType.String, 128)] [ImmutableFieldId("{221D7E98-3859-49BF-AEED-57C580396680}")] string Location { get; set; } } } ================================================ FILE: Composite/Data/Types/ILockingInformation.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{306F78E9-CA7B-429b-8D7F-CB4B4DD44E5A}")] [KeyPropertyName("Id")] [LabelPropertyName("Id")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] public interface ILockingInformation : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{C0A019A4-33BE-46a3-B27C-ED7AF010976C}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{34BD5C80-C5FD-4932-A1E6-3459E2D7802D}")] [NotNullValidator()] string LockKey { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{9B13A361-9CCD-4dfc-97E5-8D9CA3C54660}")] [NotNullValidator()] string SerializedOwnerId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 64)] [ImmutableFieldId("{CADF7240-45C0-43a6-A6A1-D60887CC2D51}")] [NotNullValidator()] string Username { get; set; } } } ================================================ FILE: Composite/Data/Types/IMediaFile.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Core.WebClient.Renderings.Data; namespace Composite.Data.Types { /// <summary> /// This data interface represents a media file in C1 CMS. This can be used to query media through a <see cref="Composite.Data.DataConnection"/>. /// </summary> [Title("C1 Media File")] [KeyPropertyName("KeyPath")] [DataAncestorProviderAttribute(typeof(MediaFileDataAncesorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{A8716C78-1499-4155-875B-2545006385B2}")] [LabelPropertyName("CompositePath")] [RelevantToUserType(UserType.Developer)] [KeyTemplatedXhtmlRenderer(XhtmlRenderingType.Embedable, "<a href='~/media({field:StoreId}:{field:Id})'>{label}</a>")] public interface IMediaFile : IFile { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{a85bb1d0-1413-44e2-9b78-92ecd3fd1f77}")] Guid Id { get; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 2048)] [ImmutableFieldId("{46024846-b43c-4675-9a6e-ed16ffd29420}")] string KeyPath { get; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 2048)] [ImmutableFieldId("{9DAC181A-DA51-455e-BE73-55719FA2CC9C}")] string CompositePath { get; set; } /// <exclude /> [ImmutableFieldId("{D595E909-7E32-4dd0-90AE-63C2DAE0E7BF}")] [StoreFieldType(PhysicalStoreFieldType.String, 32)] string StoreId { get; set; } /// <exclude /> [ImmutableFieldId("{22FB743F-1731-426e-BB22-78A08F956749}")] [StoreFieldType(PhysicalStoreFieldType.String, 256)] [SearchableField(true, false, false)] string Title { get; set; } /// <exclude /> [ImmutableFieldId("{FA75B9B1-82D3-47ce-80F8-BAEF4CDE43FD}")] [StoreFieldType(PhysicalStoreFieldType.LargeString)] [SearchableField(true, true, false)] string Description { get; set; } /// <exclude /> [ImmutableFieldId("{016372B5-9692-4C2D-B64D-8FC6594BBCFF}")] [StoreFieldType(PhysicalStoreFieldType.LargeString)] [SearchableField(true, true, true)] string Tags { get; set; } /// <exclude /> [ImmutableFieldId("{D4B7D47E-49CF-43c9-AC36-4134B136860A}")] [StoreFieldType(PhysicalStoreFieldType.String, 128)] string Culture { get; set; } /// <exclude /> [ImmutableFieldId("{EBF481B7-7A5D-4678-93E9-1FF189311404}")] [StoreFieldType(PhysicalStoreFieldType.String, 256)] [SearchableField(false, true, true)] string MimeType { get; } /// <exclude /> [ImmutableFieldId("{BCD0C1A2-9769-4209-8D43-DB7DDBABBB8B}")] [StoreFieldType(PhysicalStoreFieldType.Integer, IsNullable=true)] int? Length { get; } /// <exclude /> [ImmutableFieldId("{6BBE4326-998A-4111-BA6F-CC05A518CF6A}")] [StoreFieldType(PhysicalStoreFieldType.DateTime, IsNullable = true)] [SearchableField(false, true, true)] DateTime? CreationTime { get; } /// <exclude /> [ImmutableFieldId("{564952B9-C95F-4408-BD00-206DF0CD45C6}")] [StoreFieldType(PhysicalStoreFieldType.DateTime, IsNullable = true)] DateTime? LastWriteTime { get; } /// <exclude /> [ImmutableFieldId("{72C36EED-15DC-44a8-98D5-EE828D3B6AB8}")] [StoreFieldType(PhysicalStoreFieldType.Boolean)] bool IsReadOnly { get; } } } ================================================ FILE: Composite/Data/Types/IMediaFileData.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{56916e07-6e3c-4488-8b46-78f6cb74ac2e}")] [KeyPropertyName("Id")] [DataScope(DataScopeIdentifier.PublicName)] [NotReferenceable] [CachingAttribute(CachingType.Full)] public interface IMediaFileData : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{04f39c14-7243-4152-9e05-f28e496feba1}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 2048, IsNullable = false)] [ImmutableFieldId("{f832f793-be88-418e-b134-1a72558643d0}")] [NotNullValidator] string FolderPath { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 2048, IsNullable = false)] [ImmutableFieldId("{00e64f23-aec9-4527-b964-4accd4cef548}")] [NotNullValidator] string FileName { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 256, IsNullable = true)] [ImmutableFieldId("{aac2be13-e487-49b9-90f9-1afc495ea844}")] string Title { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString, IsNullable = true)] [ImmutableFieldId("{6993c337-88c6-4e90-a1c2-64aeb73f0650}")] string Description { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString, IsNullable = true)] [ImmutableFieldId("{ef096303-74b9-4b90-9626-2cefecd0a3ce}")] string Tags { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 128, IsNullable = true)] [ImmutableFieldId("{068b92aa-3f46-43ab-b258-fa80dbb56fd6}")] string CultureInfo { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 256, IsNullable = true)] [ImmutableFieldId("{fdd38995-b933-44ba-9ad5-d5235ef0e402}")] string MimeType { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Integer, IsNullable = true)] [ImmutableFieldId("{cbab34f8-deaa-45cd-915c-dbe027110b25}")] [DefaultFieldIntValue(-1)] int? Length { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.DateTime, IsNullable = true)] [ImmutableFieldId("{d9095572-6a08-4115-999a-b70a449c827e}")] [DefaultFieldNowDateTimeValue] DateTime? CreationTime { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.DateTime, IsNullable = true)] [ImmutableFieldId("{d3b83ba0-35e0-4168-98a7-80cc4ebfc891}")] [DefaultFieldNowDateTimeValue] DateTime? LastWriteTime { get; set; } } } ================================================ FILE: Composite/Data/Types/IMediaFileFolder.cs ================================================ using System; using System.Linq; using Composite.Data.Hierarchy; namespace Composite.Data.Types { /// <summary> /// This data interface represents a media folder in C1 CMS. This can be used to query media folders through a <see cref="Composite.Data.DataConnection"/>. /// </summary> [Title("C1 Media Folder")] [KeyPropertyName("KeyPath")] [DataAncestorProviderAttribute(typeof(MediaFileDataAncesorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{76C4D9D8-2558-4475-801B-FB56C5E923A3}")] [LabelPropertyName("CompositePath")] [RelevantToUserType(UserType.Developer)] public interface IMediaFileFolder : IData { /// <summary> /// Gets the id. /// </summary> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{84c8046c-a53c-42dd-bd54-b64c6f7511c1}")] Guid Id { get; } /// <summary> /// Gets the key path. Should contain StoreId as well as Id. Used for identifying a media file within the system. /// Example: 'MediaArchive:63e1480c-1b8a-4ca1-ba02-792437e654ec' /// </summary> [StoreFieldType(PhysicalStoreFieldType.String, 2048)] [ImmutableFieldId("{e03e1acb-b5bd-4354-bfd4-5e2626381d82}")] string KeyPath { get; } /// <summary> /// Used for labels in widgets. Example: 'MediaArchive:/Folder1/Folder2' /// </summary> [ImmutableFieldId("{ADB2660D-BAB3-499a-AE12-50AA703FA3B0}")] [StoreFieldType(PhysicalStoreFieldType.String, 2048)] string CompositePath { get; set; } /// <exclude /> [ImmutableFieldId("{814D45C9-D424-4420-8DBB-3F93E4EF24E2}")] [StoreFieldType(PhysicalStoreFieldType.String, 32)] string StoreId { get; set; } /// <summary> /// Gets or sets the path. F.e. '/', '/Folder1', '/Folder1/Folder2' /// </summary> [ImmutableFieldId("{A71332BC-F6E5-4e1b-8BB6-7C6AA57BECC6}")] [StoreFieldType(PhysicalStoreFieldType.String, 2048)] string Path { get; set; } /// <summary> /// Gets or sets the title. /// </summary> [ImmutableFieldId("{E4DBB69F-B1F6-46a1-A8A6-BDDD4CB344D6}")] [StoreFieldType(PhysicalStoreFieldType.String, 256)] string Title { get; set; } /// <summary> /// Gets or sets the description. /// </summary> [ImmutableFieldId("{51CF6EFA-66C3-413e-9FCD-06EA52871182}")] [StoreFieldType(PhysicalStoreFieldType.LargeString)] string Description { get; set; } /// <summary> /// Gets a value indicating whether this media file is read only. /// </summary> [ImmutableFieldId("{FA03F9D5-C8AF-469c-BC02-F11118D21A0F}")] [StoreFieldType(PhysicalStoreFieldType.Boolean)] bool IsReadOnly { get; } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class IMediaFileFolderUtils { /// <summary> /// Creates a folder path given folder path and the name of the folder /// </summary> /// <param name="parentMediaFolder"></param> /// <param name="folderName"></param> /// <returns></returns> public static string CreateFolderPath(this IMediaFileFolder parentMediaFolder, string folderName) { return CreateFolderPath(parentMediaFolder.Path, folderName); } /// <summary> /// Creates a folder path given folder path and the name of the folder /// </summary> /// <param name="parentFolderPath"></param> /// <param name="folderName"></param> /// <returns></returns> public static string CreateFolderPath(string parentFolderPath, string folderName) { string folderPath; if (parentFolderPath == "/") { folderPath = parentFolderPath + folderName; } else { folderPath = parentFolderPath + "/" + folderName; } folderPath = folderPath.Replace('\\', '/'); while (folderPath.Contains("//")) { folderPath = folderPath.Replace("//", "/"); } if (!folderPath.StartsWith("/")) { folderPath = "/" + folderPath; } if (folderPath.EndsWith("/")) { folderPath = folderPath.Remove(folderPath.Length - 1); } return folderPath; } /// <summary> /// Returns the parent folder for the given media folder /// </summary> /// <param name="mediaFileFolder"></param> /// <returns></returns> public static string GetParentFolderPath(this IMediaFileFolder mediaFileFolder) { return GetParentFolderPath(mediaFileFolder.Path); } /// <summary> /// Returns the parent folder for the given media folder path /// </summary> /// <param name="path"></param> /// <returns></returns> public static string GetParentFolderPath(string path) { if (path == "/") { return path; } string parentPath = path.Substring(0, path.LastIndexOf("/")); if (parentPath == "") { return "/"; } return parentPath; } /// <summary> /// Returns true if the given media folder exists /// </summary> /// <param name="mediaFileFolder"></param> /// <returns></returns> public static bool DoesFolderExists(this IMediaFileFolder mediaFileFolder) { return DoesFolderExists(mediaFileFolder.Path); } /// <summary> /// Returns true if the given media folder path exists /// </summary> /// <param name="path"></param> /// <returns></returns> public static bool DoesFolderExists(string path) { if (path == "/") { return true; } using (DataConnection dataConnection = new DataConnection()) { return (from item in dataConnection.Get<IMediaFileFolder>() where item.Path == path select item).Any(); } } /// <summary> /// Returns true if the given media folders parent folder exists /// </summary> /// <param name="mediaFileFolder"></param> /// <returns></returns> public static bool DoesParentFolderExists(this IMediaFileFolder mediaFileFolder) { return DoesFolderExists(mediaFileFolder.GetParentFolderPath()); } } } ================================================ FILE: Composite/Data/Types/IMediaFileStore.cs ================================================ namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [KeyPropertyName("Id")] [DataScope(DataScopeIdentifier.PublicName)] public interface IMediaFileStore : IData { /// <exclude /> string Id { get; } /// <exclude /> string Title { get; } /// <exclude /> string Description { get; } /// <exclude /> bool IsReadOnly { get; } /// <exclude /> bool ProvidesMetadata { get; } } } ================================================ FILE: Composite/Data/Types/IMediaFolderData.cs ================================================ using System; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{cb22316c-4e41-4fe5-a30d-5abc35af124a}")] [KeyPropertyName("Id")] [DataScope(DataScopeIdentifier.PublicName)] [NotReferenceable] [CachingAttribute(CachingType.Full)] public interface IMediaFolderData : IData { /// <exclude /> [ImmutableFieldId("{aa5d40be-d250-4794-b517-bd6977658273}")] [StoreFieldType(PhysicalStoreFieldType.Guid)] Guid Id { get; set; } /// <exclude /> [ImmutableFieldId("{cd4f0524-3bfd-4110-bc93-e99713a7a5b7}")] [StoreFieldType(PhysicalStoreFieldType.String, 2048, IsNullable = false)] string Path { get; set; } /// <exclude /> [ImmutableFieldId("{4df0e07f-24c0-4d62-bdc7-d50620a530db}")] [StoreFieldType(PhysicalStoreFieldType.String, 256, IsNullable = true)] string Title { get; set; } /// <exclude /> [ImmutableFieldId("{65e42128-8580-4898-a2fd-0e35cf771c24}")] [StoreFieldType(PhysicalStoreFieldType.LargeString, IsNullable = true)] string Description { get; set; } } } ================================================ FILE: Composite/Data/Types/IMethodBasedFunctionInfo.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{0DE2844A-6B26-4566-B1D6-A460C68B1E3B}")] [KeyPropertyName("Id")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [Caching(CachingType.Full)] public interface IMethodBasedFunctionInfo : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{131D6F2F-01A8-40b5-882B-CCC03AF8C986}")] Guid Id { get; set; } /// <exclude /> [NotNullValidator()] [StoreFieldType(PhysicalStoreFieldType.String, 512)] [ImmutableFieldId("{36460984-0281-485b-985B-D9686697D3D4}")] string Type { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 64)] [ImmutableFieldId("{5CC73160-98FF-4d13-A5AB-FB20946C9064}")] string MethodName { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 512)] [ImmutableFieldId("{62C8BC67-B0A6-4cd6-9694-AD55460C5C90}")] string Namespace { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 64)] [ImmutableFieldId("{D8108EA4-0E3D-49d1-8687-1E1FFEB69029}")] string UserMethodName { get; set; } } } ================================================ FILE: Composite/Data/Types/INamedFunctionCall.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; namespace Composite.Data.Types { /// <summary> /// A named function call for an xslt function /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{7eccf947-1abd-43d5-b28b-551a44a3fe96}")] [KeyPropertyName(0, "XsltFunctionId")] [KeyPropertyName(1, "Name")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [Caching(CachingType.Full)] [NotReferenceable] public interface INamedFunctionCall : IData { /// <exclude /> [ImmutableFieldId("{f60e9cda-a461-4234-b225-5ea3eb51a1fb}")] [StoreFieldType(PhysicalStoreFieldType.Guid)] Guid XsltFunctionId { get; set; } /// <exclude /> [ImmutableFieldId("{4c042ad7-9bf5-4875-a369-3720c1b79380}")] [StoreFieldType(PhysicalStoreFieldType.String, 256)] string Name { get; set; } /// <exclude /> [ImmutableFieldId("{cfc67bfa-2252-4642-91dc-623ca9e1d027}")] [StoreFieldType(PhysicalStoreFieldType.LargeString)] string SerializedFunction { get; set; } } } ================================================ FILE: Composite/Data/Types/IPackageServerSource.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [KeyPropertyName("Id")] [CachingAttribute(CachingType.Full)] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{BAB5A2C3-880F-4b1b-AFEE-D1058015B9ED}")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] public interface IPackageServerSource : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{7B151CE0-F094-4610-BDF8-8EE4F07003E5}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{93E401CE-1AEE-4ba7-AE5B-C7FE0A872A1A}")] [NotNullValidator()] string Url { get; set; } } } ================================================ FILE: Composite/Data/Types/IPage.cs ================================================ using System; using Composite.Core.WebClient.Renderings.Data; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.Types.Foundation; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// This data interface represents a page in C1 CMS. This can be used to query pages through a <see cref="Composite.Data.DataConnection"/>. /// Note that a lot of page related tasks can be done with a <see cref="Composite.Data.SitemapNavigator"/>. /// And any changes done through this interface and a <see cref="Composite.Data.DataConnection"/> should be done with care. /// </summary> [Title("C1 Page")] [AutoUpdateble] [ImmutableTypeId("{C046F704-D3E4-4b3d-8CB9-77564FB0B9E7}")] [KeyPropertyName(nameof(Id))] [DataAncestorProvider(typeof(PageDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [DataScope(DataScopeIdentifier.AdministratedName)] [LabelPropertyName(nameof(Title))] [RelevantToUserType(UserType.Developer)] [CachingAttribute(CachingType.Full)] [PublishControlledAuxiliary(typeof(PagePublishControlledAuxiliary))] [PublishProcessControllerTypeAttribute(typeof(GenericPublishProcessController))] [KeyTemplatedXhtmlRenderer(XhtmlRenderingType.Embedable, "<a href='~/page({id})'>{label}</a>")] public interface IPage : IData, IChangeHistory, ICreationHistory, IPublishControlled, ILocalizedControlled, IVersioned { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{FA2691BB-191E-4520-BF60-F3B7D1762CE0}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{46D0EBCD-B604-4cc2-B0B0-C0F589172680}")] Guid TemplateId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{69303D16-F681-4C2F-BA73-AF8B2B94AAB2}")] [ForeignKey(typeof(IPageType), "Id", NullReferenceValue = "{00000000-0000-0000-0000-000000000000}", NullReferenceValueType = typeof(Guid))] [DefaultFieldGuidValue("{00000000-0000-0000-0000-000000000000}")] [SearchableField(false, true, true)] Guid PageTypeId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 255)] [ImmutableFieldId("{8A06D28E-DAD9-438d-9570-0C0120ADD560}")] [NotNullValidator] [SearchableField(true, false, false)] string Title { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 192, IsNullable = true)] [ImmutableFieldId("{3E398FA5-7961-4a75-A6CE-C147B7F4B90A}")] [SearchableField(true, false, false)] string MenuTitle { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 192)] [ImmutableFieldId("{C9A81ADE-DAD5-4740-A891-DF1CE2FAB498}")] [Composite.Data.Validation.Validators.RegexValidator(@"^[\s-\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}]*$")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "We want a string here")] string UrlTitle { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 192, IsNullable = true)] [ImmutableFieldId("{22787AD0-349A-432f-89C7-3D532B613BB7}")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "We want a string here")] [SearchableField(true, false, false)] string FriendlyUrl { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 1024, IsNullable = true)] [ImmutableFieldId("{3EECB770-1D8F-45e0-9B4D-2CA67A278FA3}")] [SearchableField(true, true, false)] string Description { get; set; } } } ================================================ FILE: Composite/Data/Types/IPageFolderDefinition.cs ================================================ using System; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [KeyPropertyName("Id")] [ImmutableTypeId("{1488334F-2AB6-4D8D-9E1B-7EE4A990469D}")] [CachingAttribute(CachingType.Full)] [DataScope(DataScopeIdentifier.PublicName)] public interface IPageFolderDefinition : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [DefaultFieldNewGuidValue()] [ImmutableFieldId("{383F3019-60AD-4E16-8ACF-6568A4A13B2A}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{3FF30313-C5C0-49CB-A8E6-1875864F8EAC}")] Guid PageId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{619E698B-9D3B-4DFA-BA1C-A591446FF1A2}")] Guid FolderTypeId { get; set; } } } ================================================ FILE: Composite/Data/Types/IPageMetaDataDefinition.cs ================================================ using System; using System.Collections.Generic; namespace Composite.Data.Types { /// <summary> /// Page meta data definition. /// </summary> /// <remarks> /// Using the same name for a metadata definition is allowed if metadata type and label are the same /// on all instances. /// </remarks> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [KeyPropertyName("Id")] [ImmutableTypeId("{F0101D4E-2EC2-4D24-B0BD-BE367DC7C3E1}")] [CachingAttribute(CachingType.Full)] [DataScope(DataScopeIdentifier.PublicName)] public interface IPageMetaDataDefinition : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [DefaultFieldNewGuidValue()] [ImmutableFieldId("{C30E50F4-64BF-46A8-B8C9-A8F8CA62C74D}")] Guid Id { get; set; } /// <summary> /// This is an id of a page or pagetype item and a reference to the /// elemen where this description is defined. /// This should be an id of a page or pagetype og Guid.Empty for /// the whole website /// </summary> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{5C8A6831-8B94-424c-90C7-7C9385E5DB7C}")] Guid DefiningItemId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 128)] [ImmutableFieldId("{8B421E9F-F0B5-4D27-B1E9-87D6814EAC0F}")] string Name { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 256)] [ImmutableFieldId("{3838006A-88D1-485F-8ED6-46E14E6A738B}")] string Label { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{9EA6FEA8-B2E7-4F44-A5F5-0169123CEC77}")] [ForeignKey(typeof(ICompositionContainer), "Id", AllowCascadeDeletes = true)] Guid MetaDataContainerId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{1AD2B5F6-F5AE-496A-B9FA-47BF5E90F5F2}")] Guid MetaDataTypeId { get; set; } /// <summary> /// Start level number relativ to the page where this is defined. /// 0 will include the page it self /// </summary> [StoreFieldType(PhysicalStoreFieldType.Integer)] [ImmutableFieldId("{8AC8520E-97B9-4F58-B9A4-D5ED33C482EC}")] int StartLevel { get; set; } /// <summary> /// The number of levels this definition affects /// Use int.Max for branch /// </summary> [StoreFieldType(PhysicalStoreFieldType.Integer)] [ImmutableFieldId("{C76C80E0-C8DF-4A7B-8931-D3C3B229F44E}")] int Levels { get; set; } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class PageMetaDataDefinitionEqualityComparer : IEqualityComparer<IPageMetaDataDefinition> { /// <exclude /> public bool Equals(IPageMetaDataDefinition x, IPageMetaDataDefinition y) { return x.Name == y.Name && x.MetaDataTypeId == y.MetaDataTypeId; } /// <exclude /> public int GetHashCode(IPageMetaDataDefinition obj) { return obj.Name.GetHashCode() ^ obj.MetaDataTypeId.GetHashCode(); } } } ================================================ FILE: Composite/Data/Types/IPagePlaceholderContent.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{3EAA3814-04E6-4c7f-8F1A-004A89BB0848}")] [KeyPropertyName(0, nameof(PageId))] [KeyPropertyName(1, nameof(PlaceHolderId))] [DataAncestorProvider(typeof(PropertyDataAncestorProvider))] [PropertyDataAncestorProvider(nameof(PageId), typeof(IPage), nameof(IPage.Id), null)] [DataScope(DataScopeIdentifier.PublicName)] [DataScope(DataScopeIdentifier.AdministratedName)] [CachingAttribute(CachingType.Full)] [PublishProcessControllerTypeAttribute(typeof(GenericPublishProcessController))] [Title("C1 Page Content")] public interface IPagePlaceholderContent : IData, IChangeHistory, ICreationHistory, IPublishControlled, ILocalizedControlled, IVersioned { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{19DFF302-F089-4900-8B64-35F88C82EC45}")] [ForeignKey(typeof(IPage), nameof(IPage.Id), AllowCascadeDeletes = true)] Guid PageId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 255)] [ImmutableFieldId("{D8243AA6-A02A-4383-9ED1-2A7C1A8841E2}")] [NotNullValidator] string PlaceHolderId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{DB0C7557-8C56-4924-A199-3A1E984BE2E8}")] [SearchableField(true, false, false)] string Content { get; set; } } } ================================================ FILE: Composite/Data/Types/IPagePublishSchedule.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; using Composite.Data.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [Obsolete] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [KeyPropertyName("Id")] [ImmutableTypeId("{545F5E10-31A2-40df-9FE8-DBAD1CFB9824}")] [DataScope(DataScopeIdentifier.AdministratedName)] public interface IPagePublishSchedule : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{3C0EF006-85BE-4761-BAEB-A785AFB805A2}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{38A48198-F4F6-4bcd-8499-74FAB902CB44}")] Guid PageId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{AEE4442E-2778-470f-9822-8CCAB99DC54F}")] Guid WorkflowInstanceId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.DateTime)] [ImmutableFieldId("{F8B01277-1887-4f58-9AEE-396D38210D8F}")] DateTime PublishDate { get; set; } /// <exclude /> [NotNullValidator()] [StringSizeValidator(2, 16)] [StoreFieldType(PhysicalStoreFieldType.String, 16)] [DefaultFieldStringValue("")] [ImmutableFieldId("{9D62C8D3-E42F-4926-8E45-5B465A59C8A6}")] string LocaleCultureName { get; set; } } } ================================================ FILE: Composite/Data/Types/IPageStructure.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{797A1A98-6E5C-4a1e-B346-AE547A1F4E90}")] [KeyPropertyName("Id")] [DataScope(DataScopeIdentifier.PublicName)] [CachingAttribute(CachingType.Full)] public interface IPageStructure : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{CBB49E56-A05C-4a33-9F8B-9253C2EDB9C2}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{57AF0FDA-BA4F-4281-ACAF-A56C28FEF2E6}")] Guid ParentId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Integer)] [ImmutableFieldId("{87BD6871-CF25-48f2-9ED5-BF41B272551F}")] int LocalOrdering { get; set; } } } ================================================ FILE: Composite/Data/Types/IPageTemplateFile.cs ================================================  namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("E98E754B-4616-4ACF-A2B5-CDA5F250B95E")] public interface IPageTemplateFile : IFile { } } ================================================ FILE: Composite/Data/Types/IPageType.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Core.Linq; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum PageTypeHomepageRelation { /// <exclude /> NoRestriction = 1, /// <exclude /> OnlySubPages = 2, /// <exclude /> OnlyHomePages = 3 } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PageTypeHomepageRelationExtensionMethods { /// <exclude /> public static PageTypeHomepageRelation GetPageTypeHomepageRelation(this string value) { if (string.IsNullOrEmpty(value)) throw new ArgumentNullException(nameof(value)); PageTypeHomepageRelation result; if (!Enum.TryParse<PageTypeHomepageRelation>(value, out result)) { throw new ArgumentException("The argument is wrongly formatted"); } return result; } /// <exclude /> [Obsolete("Use nameof() keyword instead", true)] public static string ToPageTypeHomepageRelationString(this PageTypeHomepageRelation pageTypeHomepageRelation) { return pageTypeHomepageRelation.ToString(); } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PageTypeExtensionMethods { /// <exclude /> public static IEnumerable<IPageType> GetChildPageSelectablePageTypes(this IPage parentPage, IPage childPage = null) { var pageTypes = DataFacade.GetData<IPageType>().AsEnumerable() .Where(pt => pt.Available); pageTypes = pageTypes.OrderBy(f => f.Name); if (parentPage == null) { return pageTypes .Where(f => f.HomepageRelation != nameof(PageTypeHomepageRelation.OnlySubPages)) .Evaluate(); } pageTypes = pageTypes .Where(f => f.HomepageRelation != nameof(PageTypeHomepageRelation.OnlyHomePages) || (childPage != null && f.Id == childPage.PageTypeId)) .Evaluate(); ICollection<IPageTypeParentRestriction> allParentRestrictions = null; var result = new List<IPageType>(); foreach (IPageType pageType in pageTypes) { if (childPage != null && pageType.Id == childPage.PageTypeId) { result.Add(pageType); continue; } allParentRestrictions = allParentRestrictions ?? DataFacade.GetData<IPageTypeParentRestriction>().ToList(); var parentRestrictions = allParentRestrictions.Where(f => f.PageTypeId == pageType.Id).ToList(); if (parentRestrictions.Count == 0 || parentRestrictions.Any(f => f.AllowedParentPageTypeId == parentPage.PageTypeId)) { result.Add(pageType); } } return result; } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{867BE4ED-9C6C-49B9-AC30-35D65066BA4C}")] [KeyPropertyName("Id")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [LabelPropertyName("Name")] [CachingAttribute(CachingType.Full)] public interface IPageType : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{333BFEA0-ACD2-4500-A258-5305DFC72DC7}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 256)] [ImmutableFieldId("{0170DD8F-D44D-4F84-BD79-296E75885FDD}")] string Name { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{CCAA5F15-63E4-42BF-8CDA-3AD0407520A7}")] string Description { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Boolean)] [ImmutableFieldId("{51DEADD0-7E5C-43F4-ADF5-5E092798B8DE}")] [DefaultFieldBoolValue(true)] bool Available { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Boolean)] [ImmutableFieldId("{A489FFEB-6D65-4ED6-84E2-3FECB8F3733D}")] [DefaultFieldBoolValue(true)] bool PresetMenuTitle { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{5C5A5B74-992C-4587-86C3-667B9BE22B36}")] Guid DefaultTemplateId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 64)] [ImmutableFieldId("{5924B690-F7CC-4110-A3AB-227BD0E87289}")] string HomepageRelation { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{4F9B76CB-5389-487C-92E3-A6DB4F1E5EFC}")] Guid DefaultChildPageType { get; set; } } } ================================================ FILE: Composite/Data/Types/IPageTypeDateFolderTypeLink.cs ================================================ using System; using System.Collections.Generic; using Composite.Data.DynamicTypes; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{A68C989B-2ECC-4C9C-8ACD-08B07BF52CF0}")] [KeyPropertyName("Id")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [CachingAttribute(CachingType.Full)] public interface IPageTypeDataFolderTypeLink : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{C94F9A58-2A0E-4A3E-BF22-570B223BD26E}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{62C9069C-5A42-4F72-AA06-D44A7AA63AA3}")] [ForeignKey(typeof(IPageType), "Id", AllowCascadeDeletes = true)] Guid PageTypeId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{76CC0DE4-B093-4EB1-8846-E8C8DE0D1620}")] Guid DataTypeId { get; set; } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class IPageTypeDataFolderTypeLinkExtensionMethods { /// <summary> /// Removes data items that refer to data types that are not registered, and returns an enumeration of valid links. /// </summary> /// <param name="pageTypeDataFolderTypeLinks"></param> /// <returns></returns> public static IEnumerable<IPageTypeDataFolderTypeLink> RemoveDeadLinks(this IEnumerable<IPageTypeDataFolderTypeLink> pageTypeDataFolderTypeLinks) { foreach (IPageTypeDataFolderTypeLink pageTypeDataFolderTypeLink in pageTypeDataFolderTypeLinks) { DataTypeDescriptor dataTypeDescriptor; if (!DynamicTypeManager.TryGetDataTypeDescriptor(pageTypeDataFolderTypeLink.DataTypeId, out dataTypeDescriptor)) { DataFacade.Delete<IPageTypeDataFolderTypeLink>(pageTypeDataFolderTypeLink); } else { yield return pageTypeDataFolderTypeLink; } } } } } ================================================ FILE: Composite/Data/Types/IPageTypeDefaultPageContent.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{C326C3F7-81C4-47BD-9C17-83BE2CF980BA}")] [KeyPropertyName("Id")] [LabelPropertyName("PlaceHolderId")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [CachingAttribute(CachingType.Full)] public interface IPageTypeDefaultPageContent : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{0EB4D9D3-32BB-4850-AAB7-B20CFBA4F571}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{B2CD7FDA-1CF5-4461-A6DB-1F188B28B054}")] [ForeignKey(typeof(IPageType), "Id", AllowCascadeDeletes = true)] Guid PageTypeId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 255)] [ImmutableFieldId("{122F2047-B01E-4F67-BBA3-CA67E50D985E}")] [NotNullValidator()] string PlaceHolderId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{0D1DEE90-220D-4741-AFD6-E18DB982A673}")] string Content { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 64, IsNullable = true)] [ImmutableFieldId("{68880B4B-437F-4041-BF44-FB77ADCE75AA}")] string ContainerClasses { get; set; } } } ================================================ FILE: Composite/Data/Types/IPageTypeMetaDataTypeLink.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; using System.Collections.Generic; using Composite.Data.DynamicTypes; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{37A346A5-8776-4765-9D57-A3F2CD8E459D}")] [LabelPropertyName("Name")] [KeyPropertyName("Id")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [CachingAttribute(CachingType.Full)] public interface IPageTypeMetaDataTypeLink : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{B186C166-9EA7-489A-BEFE-E576FE7E3FF9}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{6F0FD511-FA79-486E-A371-AFC7A3E6C614}")] [ForeignKey(typeof(IPageType), "Id", AllowCascadeDeletes = true)] Guid PageTypeId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{BCD3927D-D166-431D-936F-1B6843B91E82}")] Guid DataTypeId { get; set; } /// <summary> /// This should match the name of the ICompositionDescription /// </summary> [StoreFieldType(PhysicalStoreFieldType.String, 128)] [ImmutableFieldId("{8BD9BEDF-9677-4415-A3DD-E7BBD0A14286}")] [NotNullValidator()] string Name { get; set; } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class IPageTypeMetaDataTypeLinkExtensionMethods { /// <exclude /> public static IEnumerable<IPageTypeMetaDataTypeLink> RemoveDeadLinks(this IEnumerable<IPageTypeMetaDataTypeLink> pageTypeMetaDataTypeLinks) { foreach (IPageTypeMetaDataTypeLink pageTypeMetaDataTypeLink in pageTypeMetaDataTypeLinks) { DataTypeDescriptor dataTypeDescriptor; if (DynamicTypeManager.TryGetDataTypeDescriptor(pageTypeMetaDataTypeLink.DataTypeId, out dataTypeDescriptor) == false) { DataFacade.Delete<IPageTypeMetaDataTypeLink>(pageTypeMetaDataTypeLink); } else { yield return pageTypeMetaDataTypeLink; } } } } } ================================================ FILE: Composite/Data/Types/IPageTypePageTemplateRestriction.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{A7F15FD7-2175-42A9-8210-DB30BD45A1C1}")] [KeyPropertyName("Id")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [CachingAttribute(CachingType.Full)] public interface IPageTypePageTemplateRestriction : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{00695FA5-E6BC-492C-B519-6188131CED03}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{5B97F19B-C18B-4470-85BE-193E9208BB49}")] [ForeignKey(typeof(IPageType), "Id", AllowCascadeDeletes = true)] Guid PageTypeId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{29A3D441-66EB-484D-A15D-077B5F070F42}")] Guid PageTemplateId { get; set; } } } ================================================ FILE: Composite/Data/Types/IPageTypeParentRestriction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Data.Hierarchy.DataAncestorProviders; using Composite.Data.Hierarchy; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{776694C8-0074-45FD-9358-41D61113EA34}")] [KeyPropertyName("Id")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [CachingAttribute(CachingType.Full)] public interface IPageTypeParentRestriction : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{E0595ABC-1207-49D2-BA53-8055E8F4D851}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{42E5C8E5-9528-4C6F-94BD-DFA77F8D5FB7}")] [ForeignKey(typeof(IPageType), "Id", AllowCascadeDeletes = true)] Guid PageTypeId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{4668D87F-245D-4DBB-BFD0-2F09DDB7CD64}")] [ForeignKey(typeof(IPageType), "Id", AllowCascadeDeletes=true)] Guid AllowedParentPageTypeId { get; set; } } } ================================================ FILE: Composite/Data/Types/IPageTypeTreeLink.cs ================================================ using System; using System.Collections.Generic; using Composite.Data.DynamicTypes; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Composite.C1Console.Trees; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{5B4A6EF1-B3AF-4862-AA21-DAC96EAE300B}")] [KeyPropertyName("Id")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [CachingAttribute(CachingType.Full)] public interface IPageTypeTreeLink : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{AAD20063-DB23-4F54-93FA-C3E4092DF54A}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{FAB31A74-D71F-4C30-8FF9-8D053682E8E4}")] [ForeignKey(typeof(IPageType), "Id", AllowCascadeDeletes = true)] Guid PageTypeId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 2048)] [ImmutableFieldId("{A343ED1C-0298-4119-A56B-174F45106CFC}")] string TreeId { get; set; } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class IPageTypeTreeLinkExtensionMethods { /// <summary> /// Removes data items that refer to trees that are not registered. /// </summary> /// <param name="pageTypeTreeLinks"></param> /// <returns></returns> public static IEnumerable<IPageTypeTreeLink> RemoveDeadLinks(this IEnumerable<IPageTypeTreeLink> pageTypeTreeLinks) { foreach (IPageTypeTreeLink pageTypeTreeLink in pageTypeTreeLinks) { if (TreeFacade.GetTree(pageTypeTreeLink.TreeId) == null) { DataFacade.Delete<IPageTypeTreeLink>(pageTypeTreeLink); } else { yield return pageTypeTreeLink; } } } } } ================================================ FILE: Composite/Data/Types/IPageUnpublishSchedule.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; using Composite.Data.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [Obsolete] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [KeyPropertyName("Id")] [ImmutableTypeId("{20040E85-B2DE-40a8-A2BD-58ADA19DA2E4}")] [DataScope(DataScopeIdentifier.AdministratedName)] public interface IPageUnpublishSchedule : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{247BD023-54DC-44ab-BB2A-3044FE94A75B}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{43E1F55C-7CBE-4000-BDA7-B91EDEE9093A}")] Guid PageId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{D8E2C07B-F8F3-4312-8630-68DEBAA0D2B7}")] Guid WorkflowInstanceId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.DateTime)] [ImmutableFieldId("{B6091456-8BAC-4caf-B692-C5F14E5C10DB}")] DateTime UnpublishDate { get; set; } /// <exclude /> [NotNullValidator()] [StringSizeValidator(2, 16)] [StoreFieldType(PhysicalStoreFieldType.String, 16)] [DefaultFieldStringValue("")] [ImmutableFieldId("{9D62C8D3-E42F-4926-8E45-5B465A59C8A6}")] string LocaleCultureName { get; set; } } } ================================================ FILE: Composite/Data/Types/IParameter.cs ================================================ using System; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{13A37602-A8D6-4b31-B3FE-4F20F038BE10}")] [KeyPropertyName(0, "OwnerId")] [KeyPropertyName(1, "ParameterId")] [DataScope(DataScopeIdentifier.PublicName)] [Caching(CachingType.Full)] [NotReferenceable] public interface IParameter : IData { /// <exclude /> [ImmutableFieldId("{77C42214-8CAC-41ea-A1F9-7570E2549235}")] [StoreFieldType(PhysicalStoreFieldType.Guid)] Guid OwnerId { get; set; } /// <exclude /> [ImmutableFieldId("{8610C316-4F7E-4d70-B42A-73F4D5568BE9}")] [StoreFieldType(PhysicalStoreFieldType.Guid)] Guid ParameterId { get; set; } /// <exclude /> [ImmutableFieldId("{6B1CFEEA-2C07-4bf2-BAFD-187EDAA7E453}")] [StoreFieldType(PhysicalStoreFieldType.String, 128)] string Name { get; set; } /// <exclude /> [ImmutableFieldId("{57BA2948-A336-472f-A635-4B5A1D636707}")] [StoreFieldType(PhysicalStoreFieldType.String, 128)] string Label { get; set; } /// <exclude /> [ImmutableFieldId("{853D0AE0-DB10-4791-8624-3EEC027D0EF8}")] [StoreFieldType(PhysicalStoreFieldType.String, 512)] string HelpText { get; set; } /// <exclude /> [ImmutableFieldId("{5D983115-86BA-4bd6-86C9-90474E0C77B5}")] [StoreFieldType(PhysicalStoreFieldType.Integer)] int Position { get; set; } /// <exclude /> [ImmutableFieldId("{08098E61-5BCC-4b0d-AB9B-8636CC45EC0A}")] [StoreFieldType(PhysicalStoreFieldType.String, 512)] string TypeManagerName { get; set; } /// <exclude /> [ImmutableFieldId("{21DADDA0-BFAE-4f9d-A3BC-9099771DE73A}")] [StoreFieldType(PhysicalStoreFieldType.LargeString, IsNullable = true)] string WidgetFunctionMarkup { get; set; } /// <exclude /> [ImmutableFieldId("{16D47452-7933-46fd-A192-C2D10B695C0A}")] [StoreFieldType(PhysicalStoreFieldType.LargeString, IsNullable = true)] string DefaultValueFunctionMarkup { get; set; } /// <exclude /> [ImmutableFieldId("{11E5E571-8927-414c-8528-40E6876B0613}")] [StoreFieldType(PhysicalStoreFieldType.LargeString, IsNullable = true)] string TestValueFunctionMarkup { get; set; } } } ================================================ FILE: Composite/Data/Types/IPublishSchedule.cs ================================================ using System; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ImmutableTypeId("db542d7e-5cba-42e1-8a67-ad129941215c")] public interface IPublishSchedule : ISchedule { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.DateTime)] [ImmutableFieldId("d829eec8-76b0-46c7-9fdc-e93716451c91")] DateTime PublishDate { get; set; } } } ================================================ FILE: Composite/Data/Types/ISchedule.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; using Composite.Data.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// A base interface for <see cref="Composite.Data.Types.IPublishSchedule"/> and <see cref="Composite.Data.Types.IUnpublishSchedule"/> interfaces. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [KeyPropertyName("Id")] [DataScope(DataScopeIdentifier.AdministratedName)] public interface ISchedule : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("d617415e-a233-4dc4-b0b7-2b18668616cd")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("e6c8bd27-e3ea-4d0d-bbeb-e6a7a5200447")] Guid DataTypeId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 512)] [ImmutableFieldId("6a137199-8985-4721-93f4-d1a7ef305c22")] string DataId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("3814914a-5ac9-4e84-bb0e-47be3224991f")] Guid WorkflowInstanceId { get; set; } /// <exclude /> [NotNullValidator] [StringSizeValidator(0, 16)] [StoreFieldType(PhysicalStoreFieldType.String, 16)] [DefaultFieldStringValue("")] [ImmutableFieldId("8bfc68ee-8f63-4674-b1c8-d1ab1f1489f5")] string LocaleCultureName { get; set; } } } ================================================ FILE: Composite/Data/Types/ISearchEngineOptimizationKeyword.cs ================================================ using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Composite.Data.ProcessControlled; using Composite.Data.Validation.Validators; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [Caching(CachingType.Full)] [KeyPropertyName("Keyword")] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{895F967D-EEAA-437a-9463-E1F95C214ED6}")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] public interface ISearchEngineOptimizationKeyword : IData, ILocalizedControlled { /// <exclude /> [NotNullValidator()] [StringSizeValidator(1, 128)] [StoreFieldType(PhysicalStoreFieldType.String, 128)] [ImmutableFieldId("{87EE9B0E-3212-472b-8FDB-2984798CDB79}")] string Keyword { get; set; } } } ================================================ FILE: Composite/Data/Types/ISqlConnection.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{EEA30040-5B54-46c6-826A-4633E563AB70}")] [KeyPropertyName("Id")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [Caching(CachingType.Full)] [NotReferenceable] public interface ISqlConnection : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{37861406-C595-4c16-8845-B77DCF1B4EAB}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Boolean)] [ImmutableFieldId("{0887CB9C-1FC6-4d18-A288-CC6D8A44CCC8}")] bool IsMsSql { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 1024)] [ImmutableFieldId("{82F89ADD-060D-4f09-B69A-16509CB2E730}")] string EncryptedConnectionString { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 255)] [ImmutableFieldId("{9CBA57D7-6EA8-45da-BC0B-AFD929212B73}")] string Name { get; set; } } } ================================================ FILE: Composite/Data/Types/ISqlFunctionInfo.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{2D78129F-863F-4c5a-B126-1405628351AC}")] [KeyPropertyName("Id")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [Caching(CachingType.Full)] [NotReferenceable] public interface ISqlFunctionInfo : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{8C69D7E7-D36D-4d0a-AD6F-C17C13C84F0F}")] Guid Id { get; set;} /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 255)] [ImmutableFieldId("{CACA9F21-97CC-4b6d-8901-893F376E9F54}")] [NotNullValidator()] string Name { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{3352125A-456D-41e9-9431-6701FCA1010D}")] Guid ConnectionId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Boolean)] [ImmutableFieldId("{776C9FF2-ED3C-4d9f-867D-15062B392714}")] bool IsStoredProcedure { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Boolean)] [ImmutableFieldId("{A1586CD5-6006-494a-A638-BFAA209D817B}")] bool ReturnsXml { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Boolean)] [ImmutableFieldId("{7DDDDAAA-D1A6-4a98-8B34-426125001A35}")] bool IsQuery { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{BE436E9F-A199-436a-911D-2E6B5C2A4A6E}")] string Command { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 255)] [ImmutableFieldId("{B6686738-1485-49b1-95D5-944C72D1897C}")] [NotNullValidator()] string Namespace { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 512)] [ImmutableFieldId("{89609E03-AFA4-42b6-90AA-FC5CFBAA2136}")] string Description { get; set; } } } ================================================ FILE: Composite/Data/Types/ISystemActiveLocale.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Composite.Data.Validation.Validators; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [Caching(CachingType.Full)] [KeyPropertyName("Id")] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{13A5FCB2-1481-4443-866D-8976B4789B6C}")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] public interface ISystemActiveLocale : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{ABFBC594-8EE2-4578-9414-34713F1E9A39}")] Guid Id { get; set; } /// <exclude /> [NotNullValidator()] [StringSizeValidator(2, 16)] [StoreFieldType(PhysicalStoreFieldType.String, 16)] [ImmutableFieldId("{4A1AEACC-846F-49d4-A0AE-A870AC2D840B}")] string CultureName { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 64)] [StringSizeValidator(0, 64)] [ImmutableFieldId("{85009F2B-EB00-4d9f-AC43-36D6BEB99181}")] string UrlMappingName { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Boolean)] [ImmutableFieldId("{3CF887A9-44FB-4193-A070-67E4324F9206}")] bool IsDefault { get; set; } } } ================================================ FILE: Composite/Data/Types/ITaskItem.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{08BAFC6D-841B-4ad7-B565-F3F5A962952A}")] [KeyPropertyName("Id")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [CachingAttribute(CachingType.Full)] public interface ITaskItem : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{EE312CF7-AB0A-4b4c-B524-4C92E475F08E}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 255)] [ImmutableFieldId("{C800E783-7C68-4b3d-B839-56685104DC65}")] [NotNullValidator()] string TaskId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 2048)] [ImmutableFieldId("{28474560-8CE3-4f6f-A83D-C4F996228BF2}")] [NotNullValidator()] string TaskManagerType { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{F7B9A678-B0BD-4ba5-8805-C8C2B52921AB}")] [NotNullValidator()] string SerializedFlowToken { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.DateTime)] [ImmutableFieldId("{34E4FC09-6FFF-4fcc-BB40-59F437B2FAB6}")] DateTime StartTime { get; set; } } } ================================================ FILE: Composite/Data/Types/IUnpublishSchedule.cs ================================================ using System; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ImmutableTypeId("e0ec4c0f-31d9-42af-ba1a-65b102945a51")] public interface IUnpublishSchedule : ISchedule { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.DateTime)] [ImmutableFieldId("024666a4-7c22-4fb5-8ddd-3fc248ce15ac")] DateTime UnpublishDate { get; set; } } } ================================================ FILE: Composite/Data/Types/IUrlConfiguration.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Title("Hostname configuration")] [AutoUpdateble] [ImmutableTypeId("{5552C35A-A72A-55F1-9630-ACC66FE44BBE}")] [DataScope(DataScopeIdentifier.PublicName)] [KeyPropertyName("Id")] [CachingAttribute(CachingType.Full)] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] public interface IUrlConfiguration : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{D0C48D08-1318-7441-D2C0-425D31894C1F}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 255, IsNullable = false)] [ImmutableFieldId("{C0504E0C-B487-3951-AA18-DBF28DD681B5}")] [RegexValidator(@"^((\.([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9]))*)$")] string PageUrlSuffix { get; set; } } } ================================================ FILE: Composite/Data/Types/IUser.cs ================================================ using System; using Composite.C1Console.Security; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Composite.Data.Validation.Validators; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// This data interface represents a administrative user in C1 CMS. This can be used to query users through a <see cref="Composite.Data.DataConnection"/>. /// </summary> [AutoUpdateble] [KeyPropertyName(nameof(Id))] [LabelPropertyName(nameof(Username))] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{AA086DC1-E5F6-4568-8BED-460D3275380F}")] [Caching(CachingType.Full)] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [Title("C1 Console User")] public interface IUser : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{480CF63A-A2E9-43e7-8034-778E55A0B6ED}")] Guid Id { get; set; } /// <exclude /> [NotNullValidator()] [StringSizeValidator(2, 64)] [StoreFieldType(PhysicalStoreFieldType.String, 64)] [ImmutableFieldId("{C36F8A02-4F7E-437c-A3D9-AADE8A531EFA}")] string Username { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 128, IsNullable = true)] [ImmutableFieldId("{20F756AD-F03D-453E-B464-D2C13051A647}")] string Name { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 128, IsNullable = true)] [ImmutableFieldId("{C0929E14-3FB8-4CE5-8374-997A7508DF80}")] string Email { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 64, IsNullable = true)] [ImmutableFieldId("{C7A7D63C-EA87-48ac-B009-5D4050A2F248}")] [Obsolete("Use IUserFormLogin data type instead (new name is 'IUserFormLogin.Folder'). Will be removed in future releases.")] string Group { get; set; } /// <summary> /// Determines whether the user is locked /// </summary> [StoreFieldType(PhysicalStoreFieldType.Boolean)] [DefaultFieldBoolValue(false)] [ImmutableFieldId("{72BFFBDC-E4FF-4BD4-9BB1-B86FAEA39468}")] [Obsolete("Use IUserFormLogin data type instead. Will be removed in future releases.")] bool IsLocked { get; set; } /// <summary> /// Contains a code describing lockout reason (f.e. locked by an administrator or automatically after X failed login attempts) /// For possible values, see enumeration <see cref="UserLockoutReason"/> /// </summary> [StoreFieldType(PhysicalStoreFieldType.Integer)] [DefaultFieldIntValue(0)] [ImmutableFieldId("{39CBCCFA-CFB2-4E79-9204-C9596A3FC0E9}")] [Obsolete("Use IUserFormLogin data type instead. Will be removed in future releases.")] int LockoutReason { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 256, IsNullable = true)] [ImmutableFieldId("{C0230DEB-5394-4819-BE18-A60CF5FA69F0}")] [Obsolete("Use IUserFormLogin data type instead. Will be removed in future releases.")] string EncryptedPassword { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 128, IsNullable = true)] [ImmutableFieldId("{CA2CF6F8-489B-4D60-B3C3-AF46D1259647}")] [Obsolete("Use IUserFormLogin data type instead. Will be removed in future releases.")] string PasswordHashSalt { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.DateTime)] [ImmutableFieldId("{35457DA7-A13E-4A6C-9008-3D619A519F2B}")] [DefaultFieldNowDateTimeValue] [Obsolete("Use IUserFormLogin data type instead. Will be removed in future releases.")] DateTime LastPasswordChangeDate { get; set; } } } ================================================ FILE: Composite/Data/Types/IUserActiveLocale.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Composite.Data.Validation.Validators; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [Caching(CachingType.Full)] [KeyPropertyName("Id")] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{9187ABF1-DDD6-4470-A29E-766FABD5BA53}")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] public interface IUserActiveLocale : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{65638F6C-0610-4563-8552-EF26FDCC7FF3}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 64)] [ImmutableFieldId("{DA8843CA-C550-4b73-93F8-5CB8C40C086C}")] [ForeignKey(typeof(IUser), "Username", AllowCascadeDeletes = true)] string Username { get; set; } /// <exclude /> [NotNullValidator()] [StringSizeValidator(2, 16)] [StoreFieldType(PhysicalStoreFieldType.String, 16)] [ImmutableFieldId("{D11E77B2-459B-43e4-9F98-CB5A9F44A812}")] string CultureName { get; set; } } } ================================================ FILE: Composite/Data/Types/IUserActivePerspective.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [KeyPropertyName(nameof(Id))] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{A7C6D249-1A71-4486-A252-706D8E1981D8}")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [Caching(CachingType.Full)] public interface IUserActivePerspective : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{9BB04474-DB50-4df1-8EF1-562DE7F58B1A}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 128)] [ImmutableFieldId("{2D5BC444-377A-4337-9486-8210630E6E09}")] [ForeignKey(typeof(IUser), "Username", AllowCascadeDeletes = true)] string Username { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{5AC5A7E4-4A75-4926-AB53-1A736732A9D4}")] string SerializedEntityToken { get; set; } } } ================================================ FILE: Composite/Data/Types/IUserConsoleInformation.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{7630098C-CF7B-4e16-A86F-E455FA871ABF}")] [KeyPropertyName("Id")] [LabelPropertyName("Id")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] public interface IUserConsoleInformation : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{2F91C083-A3BB-4226-B229-66FE2D653A35}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 64)] [ImmutableFieldId("{11154624-8574-48c0-97B0-E1AFFEAC7AD4}")] [NotNullValidator()] [ForeignKey(typeof(IUser), "Username", AllowCascadeDeletes = true)] string Username { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 64)] [ImmutableFieldId("{A955C07B-9FDC-40b2-8C18-87D097E94329}")] [NotNullValidator()] string ConsoleId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.DateTime)] [ImmutableFieldId("{39567CE9-C85F-439e-871D-EC97F3F79016}")] DateTime TimeStamp { get; set; } } } ================================================ FILE: Composite/Data/Types/IUserDeveloperSettings.cs ================================================ using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Composite.Data.Validation.Validators; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [Caching(CachingType.Full)] [KeyPropertyName("Username")] [LabelPropertyName("Username")] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{10ECFF01-0590-4b9a-9FD0-EE7BD1EC0CD8}")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] public interface IUserDeveloperSettings : IData { /// <exclude /> [NotNullValidator()] [StringSizeValidator(2, 64)] [StoreFieldType(PhysicalStoreFieldType.String, 64)] [ImmutableFieldId("{F2425F85-5B41-4f73-8F9A-54CAAAE266FC}")] [ForeignKey(typeof(IUser), "Username", AllowCascadeDeletes = true)] string Username { get; set; } /// <exclude /> [NotNullValidator()] [StoreFieldType(PhysicalStoreFieldType.String, 256)] [ImmutableFieldId("{303F58C7-5F51-4b53-BDEF-ED8025E6EA1A}")] string LastSpecifiedNamespace { get; set; } } } ================================================ FILE: Composite/Data/Types/IUserFormLogin.cs ================================================ using System; using Composite.C1Console.Security; using Composite.Data.Validation.Validators; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// Contains information about console user's password and login status (whether it is locked) /// </summary> [AutoUpdateble] [KeyPropertyName("UserId")] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{137a4e25-3b97-4c41-9ca2-2bea99fc2a2c}")] [Caching(CachingType.Full)] public interface IUserFormLogin: IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{3576f435-1ca4-4e22-94e8-1a5165ee9d60}")] [ForeignKey(typeof(IUser), "Id", AllowCascadeDeletes = true)] Guid UserId { get; set; } /// <exclude /> [NotNullValidator] [StringSizeValidator(1, 64)] [StoreFieldType(PhysicalStoreFieldType.String, 64)] [ImmutableFieldId("{dbfb9790-ec68-44fc-bab7-f46517c5abcf}")] string Folder { get; set; } /// <summary> /// Determines whether the user is locked /// </summary> [StoreFieldType(PhysicalStoreFieldType.Boolean)] [DefaultFieldBoolValue(false)] [ImmutableFieldId("{43df4e85-383d-47f1-8396-6d4bbfcf7d22}")] bool IsLocked { get; set; } /// <summary> /// Contains a code describing lockout reason (f.e. locked by an administrator or automatically after X failed login attempts) /// For possible values, see enumeration <see cref="UserLockoutReason"/> /// </summary> [StoreFieldType(PhysicalStoreFieldType.Integer)] [DefaultFieldIntValue(0)] [ImmutableFieldId("{10651e29-e64f-4550-a123-7c24a38dc97b}")] int LockoutReason { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 256)] [ImmutableFieldId("{fd51ed7d-5b4d-4abc-a682-6d01047e496a}")] string PasswordHash { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 128)] [ImmutableFieldId("{ff1d3308-3822-4bd9-bf04-7c7b8cf6142b}")] string PasswordHashSalt { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.DateTime)] [ImmutableFieldId("{bc2fb04a-802d-4c69-ac0c-9a71e95a8c97}")] [DefaultFieldNowDateTimeValue] DateTime LastPasswordChangeDate { get; set; } } } ================================================ FILE: Composite/Data/Types/IUserGroup.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// This data interface represents a user group in C1 CMS. This can be used to query user groups through a <see cref="Composite.Data.DataConnection"/>. /// </summary> [AutoUpdateble] [KeyPropertyName("Id")] [LabelPropertyName("Name")] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{F32B2CBB-92A1-473c-99D6-5D0C20A7480E}")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] public interface IUserGroup : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{93EA801A-AA0D-4cac-BE31-EDF9A8345D29}")] Guid Id { get; set; } /// <exclude /> [NotNullValidator()] [Composite.Data.Validation.Validators.StringSizeValidator(2, 64)] [StoreFieldType(PhysicalStoreFieldType.String, 64)] [ImmutableFieldId("{86C65F7F-64EA-4fcc-980D-AAF79C32CEC6}")] string Name { get; set; } } } ================================================ FILE: Composite/Data/Types/IUserGroupActiveLocale.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Composite.Data.Validation.Validators; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [Caching(CachingType.Full)] [KeyPropertyName("Id")] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{f60f4da8-59df-460f-84bf-5bf20700036b}")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] public interface IUserGroupActiveLocale : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{80c5cc7c-bf23-4c7d-bfe0-d168eda41d50}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{f28ada6a-12bd-43bf-aef8-1b693ee3d390}")] Guid UserGroupId { get; set; } /// <exclude /> [NotNullValidator()] [StringSizeValidator(2, 16)] [StoreFieldType(PhysicalStoreFieldType.String, 16)] [ImmutableFieldId("{ddc38768-16e8-444c-a982-80f2a55b0b75}")] [ForeignKey(typeof(ISystemActiveLocale), nameof(ISystemActiveLocale.CultureName), AllowCascadeDeletes = true)] string CultureName { get; set; } } } ================================================ FILE: Composite/Data/Types/IUserGroupActivePerspective.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [KeyPropertyName(nameof(Id))] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{13FBE551-DC00-4ad4-8720-7FF66264C002}")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [Caching(CachingType.Full)] public interface IUserGroupActivePerspective : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{2BC54612-C92E-4cc4-8B6B-2B4C9EABADC5}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{45B9D62A-6DDC-4bdf-BFE3-4D4CD0D6A658}")] Guid UserGroupId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{56CAEDCB-600D-476c-B085-617CA773721F}")] string SerializedEntityToken { get; set; } } } ================================================ FILE: Composite/Data/Types/IUserGroupPermissionDefinition.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [KeyPropertyName("Id")] [Caching(CachingType.Full)] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{72786B98-C6B6-4192-9438-A4DFB72CF086}")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] public interface IUserGroupPermissionDefinition : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{EE4DD9A0-F0EB-43b7-82DE-7B6B81C02913}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{E2F41EFE-70CA-448f-86DD-C41FD19E6274}")] Guid UserGroupId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{03FB7549-1C6E-401a-983C-9C0793102A7A}")] string SerializedEntityToken { get; set; } } } ================================================ FILE: Composite/Data/Types/IUserGroupPermissionDefinitionPermissionType.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [KeyPropertyName("Id")] [Caching(CachingType.Full)] [LabelPropertyName("PermissionTypeName")] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{21FA38B5-7B45-4f2d-9F40-2BDDA80724B8}")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] public interface IUserGroupPermissionDefinitionPermissionType : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{DCEDF510-8742-431b-B10C-66ADCCC6A71F}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{32D99BCA-1DD2-4b52-9887-5089B5EAA055}")] [ForeignKey(typeof(IUserGroupPermissionDefinition), "Id", AllowCascadeDeletes = true)] Guid UserGroupPermissionDefinitionId { get; set; } /// <exclude /> [NotNullValidator()] [StoreFieldType(PhysicalStoreFieldType.String, 64)] [ImmutableFieldId("{63A05B43-EF86-4e8c-801B-A80D4D0202AA}")] string PermissionTypeName { get; set; } } } ================================================ FILE: Composite/Data/Types/IUserPasswordHistory.cs ================================================ using System; using Composite.C1Console.Security; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Composite.Data.Validation.Validators; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// Contains information about a password previously used by a user. /// </summary> [AutoUpdateble] [KeyPropertyName("Id")] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{63651A11-0D1B-4ADC-99E7-C2B71B5A26B1}")] public interface IUserPasswordHistory : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{F71AFE78-EED8-4BCC-BFBE-C1BDE5B792E0}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{2B266EF3-AD8C-4CFD-8407-211A2CF3044E}")] [ForeignKey(typeof(IUser), "Id", AllowCascadeDeletes = true)] Guid UserId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 256)] [ImmutableFieldId("{B75CD57F-73E5-4C63-9DFE-11380825E37F}")] string PasswordHash { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 128)] [ImmutableFieldId("{2A789CF6-6E29-40F5-9462-D8CA39953C33}")] string PasswordSalt { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.DateTime)] [ImmutableFieldId("{0D7D5E71-521C-456F-A6ED-577DE68B58C8}")] [DefaultFieldNowDateTimeValue] DateTime SetDate { get; set; } } } ================================================ FILE: Composite/Data/Types/IUserPermissionDefinition.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [KeyPropertyName("Id")] [Caching(CachingType.Full)] [LabelPropertyName("Username")] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{0E4BEF62-6C11-4029-B2F5-4BCC8E46F051}")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] public interface IUserPermissionDefinition : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{95D7C9BF-F9E0-41aa-8EEB-8B3336390856}")] Guid Id { get; set; } /// <exclude /> [NotNullValidator()] [StoreFieldType(PhysicalStoreFieldType.String, 64)] [ImmutableFieldId("{8BBE4B23-1B04-452b-B9A3-83EA3B2E52DB}")] [ForeignKey(typeof(IUser), "Username", AllowCascadeDeletes = true)] string Username { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.LargeString)] [ImmutableFieldId("{15D09268-1119-47d6-A004-99DEABFEF886}")] string SerializedEntityToken { get; set; } } } ================================================ FILE: Composite/Data/Types/IUserPermissionDefinitionPermissionType.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [KeyPropertyName("Id")] [Caching(CachingType.Full)] [LabelPropertyName("PermissionTypeName")] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{4169D18C-8445-4419-8863-F26955AA66D1}")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] public interface IUserPermissionDefinitionPermissionType : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{945834C0-32B8-4ad6-89D9-396415A6D938}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{EF4BB677-6BCF-4f3a-B416-76C3DCD174CB}")] [ForeignKey(typeof(IUserPermissionDefinition), "Id", AllowCascadeDeletes = true)] Guid UserPermissionDefinitionId { get; set; } /// <exclude /> [NotNullValidator()] [StoreFieldType(PhysicalStoreFieldType.String, 64)] [ImmutableFieldId("{E7512410-3FD4-4d3b-9D8A-45734A21CB1D}")] string PermissionTypeName { get; set; } } } ================================================ FILE: Composite/Data/Types/IUserSettings.cs ================================================ using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Composite.Data.Validation.Validators; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [Caching(CachingType.Full)] [KeyPropertyName("Username")] [LabelPropertyName("Username")] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{F89054CB-C0E0-41ad-948D-4AEA4055C3A3}")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] public interface IUserSettings : IData { /// <exclude /> [NotNullValidator()] [StringSizeValidator(2, 64)] [StoreFieldType(PhysicalStoreFieldType.String, 64)] [ImmutableFieldId("{A7BEC71E-0CA9-4b33-A1E7-F2B5B5744647}")] [ForeignKey(typeof(IUser), "Username", AllowCascadeDeletes = true)] string Username { get; set; } /// <exclude /> [NotNullValidator()] [StringSizeValidator(2, 16)] [StoreFieldType(PhysicalStoreFieldType.String, 16)] [ImmutableFieldId("{9D62C8D3-E42F-4926-8E45-5B465A59C8A6}")] string CultureName { get; set; } /// <exclude /> [NotNullValidator()] [StringSizeValidator(2, 16)] [StoreFieldType(PhysicalStoreFieldType.String, 16)] [ImmutableFieldId("{F1BC3D80-AD86-4730-A6EE-65E19BEFD443}")] [DefaultFieldStringValue("en-US")] //for easy upgrade string C1ConsoleUiLanguage { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 16, IsNullable = true)] [ImmutableFieldId("{931130A1-5CDD-487a-B51F-76A0396D3216}")] string CurrentActiveLocaleCultureName { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 16, IsNullable = true)] [ImmutableFieldId("{0D354A92-461D-4ff8-B797-F2897119CD3B}")] string ForeignLocaleCultureName { get; set; } } } ================================================ FILE: Composite/Data/Types/IUserUserGroupRelation.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; namespace Composite.Data.Types { /// <summary> /// This data interface represents a user relation to a user group in C1 CMS. This can be used to query user group members through a <see cref="Composite.Data.DataConnection"/>. /// </summary> [AutoUpdateble] [Caching(CachingType.Full)] [KeyPropertyName(0, "UserId")] [KeyPropertyName(1, "UserGroupId")] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("{956BC414-4612-4a8a-A673-B82695F322DD}")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] public interface IUserUserGroupRelation : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ForeignKey(typeof(IUser), "Id", AllowCascadeDeletes = true)] [ImmutableFieldId("{529E233A-0386-4cca-8A32-69FE156EAEE1}")] Guid UserId { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ForeignKey(typeof(IUserGroup), "Id", AllowCascadeDeletes = true)] [ImmutableFieldId("{9BB13E81-3125-45eb-87A8-D0DE671A3102}")] Guid UserGroupId { get; set; } } } ================================================ FILE: Composite/Data/Types/IVersioned.cs ================================================ using System; namespace Composite.Data.Types { /// <summary> /// Represents a data type that supports multiple versions of the same data item /// </summary> [VersionKeyPropertyName(nameof(VersionId))] public interface IVersioned : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{f42d511b-1d76-4c05-a895-99f23b757e1e}")] [DefaultFieldNewGuidValue] Guid VersionId { get; set; } } } ================================================ FILE: Composite/Data/Types/IVisualFunction.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{FB2EAE51-1214-491d-8174-3A99DF90DFFA}")] [KeyPropertyName("Id")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [Caching(CachingType.Full)] [NotReferenceable] public interface IVisualFunction : IData { /// <exclude /> [ImmutableFieldId("{F8678EC3-FA5A-4141-9C93-130C93A49413}")] [StoreFieldType(PhysicalStoreFieldType.Guid)] Guid Id { get; set; } /// <exclude /> [ImmutableFieldId("{6CED428C-6190-4176-9E6D-C6DBCF9BD4C3}")] [StoreFieldType(PhysicalStoreFieldType.String, 256)] string Name { get; set; } /// <exclude /> [ImmutableFieldId("{D6E1D464-1343-4f08-AB97-759D7DD1EB80}")] [StoreFieldType(PhysicalStoreFieldType.String, 512)] string Namespace { get; set; } /// <exclude /> [ImmutableFieldId("{A40492CA-BEB9-43cb-83CA-082889575A36}")] [StoreFieldType(PhysicalStoreFieldType.String, 512)] string Description { get; set; } /// <exclude /> [ImmutableFieldId("{4737CCE8-9302-438a-87B0-DF28C974DC57}")] [StoreFieldType(PhysicalStoreFieldType.String,256)] string TypeManagerName { get; set; } /// <exclude /> [ImmutableFieldId("{FE3D5717-8F42-48e8-A089-AD431BEA1708}")] [StoreFieldType(PhysicalStoreFieldType.LargeString)] string XhtmlTemplate { get; set; } /// <exclude /> [ImmutableFieldId("{92479348-53B0-410d-8200-B3C6D7AFE54E}")] [StoreFieldType(PhysicalStoreFieldType.Integer)] int MaximumItemsToList { get; set; } /// <exclude /> [ImmutableFieldId("{3E41CE01-166F-41fb-A0FA-93EB5E3391DA}")] [StoreFieldType(PhysicalStoreFieldType.String, 64)] string OrderbyFieldName { get; set; } /// <exclude /> [ImmutableFieldId("{790B0F2E-CAB7-4eea-9EB2-5E49C8DE7575}")] [StoreFieldType(PhysicalStoreFieldType.Boolean)] [DefaultFieldBoolValue(true)] bool OrderbyAscending { get; set; } } } ================================================ FILE: Composite/Data/Types/IXmlPageTemplate.cs ================================================ using System; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{7B54D7D2-6BE6-48a6-9AE1-2E0373073D1D}")] [KeyPropertyName("Id")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] [LabelPropertyName("Title")] [CachingAttribute(CachingType.Full)] public interface IXmlPageTemplate : IData { /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.Guid)] [ImmutableFieldId("{E94FDE4D-7FDB-4b0e-A320-83EE73A73397}")] Guid Id { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 249)] [ImmutableFieldId("{BF377CD5-A96F-44f1-91AF-CF2E6F530E61}")] [NotNullValidator()] string Title { get; set; } /// <exclude /> [StoreFieldType(PhysicalStoreFieldType.String, 255)] [ImmutableFieldId("{0F654E1F-1453-428f-9EC9-7CC9CFBD59DC}")] string PageTemplateFilePath { get; set; } } } ================================================ FILE: Composite/Data/Types/IXsltFile.cs ================================================  namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DataScope(DataScopeIdentifier.PublicName)] [ImmutableTypeId("AE2DCD1A-D68F-45CC-8F0A-A2D1775FC098")] public interface IXsltFile : IFile { } } ================================================ FILE: Composite/Data/Types/IXsltFunction.cs ================================================ using System; using Composite.Data; using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; using Composite.Data.Caching; using Composite.Data.Validation.Validators; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{F6F0B424-0AFA-4d9a-9DF1-C57F2B7F7C8D}")] [KeyPropertyName("Id")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.PublicName)] public interface IXsltFunction : IData { /// <exclude /> [ImmutableFieldId("{25E73650-E7F8-4a4b-8510-9BDA1C1B2D61}")] [StoreFieldType(PhysicalStoreFieldType.Guid)] Guid Id { get; set; } /// <exclude /> [ImmutableFieldId("{8DD6A2E7-CDCE-46b9-B517-36D633B98311}")] [StoreFieldType(PhysicalStoreFieldType.String, 256)] [Composite.Data.Validation.Validators.StringSizeValidator(1, 256)] string Name { get; set; } /// <exclude /> [ImmutableFieldId("{DC241562-2B30-4d06-852D-12E5CFF81EE8}")] [StoreFieldType(PhysicalStoreFieldType.String, 512)] [Composite.Data.Validation.Validators.StringSizeValidator(1, 512)] string Namespace { get; set; } /// <exclude /> [ImmutableFieldId("{2670BEEE-4A6A-4f0f-83E6-8103EEA25D09}")] [StoreFieldType(PhysicalStoreFieldType.String, 512)] string Description { get; set; } /// <exclude /> [ImmutableFieldId("{1B695E1A-9EBD-4ce8-BA36-711D1E84D8AF}")] [StoreFieldType(PhysicalStoreFieldType.String, 32)] string OutputXmlSubType { get; set; } /// <exclude /> [ImmutableFieldId("{271AEA09-75CC-45d5-9D7F-C96B1177D046}")] [StoreFieldType(PhysicalStoreFieldType.String, 1024)] string XslFilePath { get; set; } } } ================================================ FILE: Composite/Data/Types/MediaFileDataAncesorProvider.cs ================================================ using System; using System.Linq; using Composite.Data.Hierarchy; using Composite.Core.Extensions; namespace Composite.Data.Types { internal sealed class MediaFileDataAncesorProvider : IDataAncestorProvider { public IData GetParent(IData data) { string parentFolderPath; string storeId; if (data is IMediaFile) { var file = (IMediaFile)data; parentFolderPath = file.FolderPath; storeId = file.StoreId; } else if (data is IMediaFileFolder) { var folder = (IMediaFileFolder) data; int lastIndex = folder.Path.LastIndexOf('/'); if (lastIndex == 0) { return null; } parentFolderPath = folder.Path.Substring(0, lastIndex); storeId = folder.StoreId; } else { throw new ArgumentException("Must be either of type IMediaFile or IMediaFileFolder", nameof(data)); } var queryable = DataFacade.GetData<IMediaFileFolder>(); return queryable.IsEnumerableQuery() ? queryable.AsEnumerable() .FirstOrDefault(item => item.Path == parentFolderPath && item.StoreId == storeId) : queryable.FirstOrDefault(item => item.Path == parentFolderPath && item.StoreId == storeId); } } } ================================================ FILE: Composite/Data/Types/PageInsertPosition.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Users; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> public interface IPageInsertionPosition { /// <exclude /> void CreatePageStructure(IPage page, Guid parentPageId); } /// <summary> /// Contains awailable page insertion positions /// </summary> public static class PageInsertPosition { /// <summary> /// The page will be added as the last page in the list of child pages. /// </summary> public static IPageInsertionPosition Bottom => new BottomPageInsertPosition(); /// <summary> /// The page will be added as the first page in the list of child pages. /// </summary> public static IPageInsertionPosition Top => new TopPageInsertPosition(); /// <summary> /// A page will be added with respect to the aplhabetic order. /// </summary> public static IPageInsertionPosition Alphabetic => new AlphabeticPageInsertPosition(); /// <summary> /// The page will appear after a given page /// </summary> /// <param name="existingPageId">An existing page after which a new page should be inserted</param> /// <returns></returns> public static IPageInsertionPosition After(Guid existingPageId) => new AfterPageInsertPosition(existingPageId); internal class BottomPageInsertPosition : IPageInsertionPosition { public void CreatePageStructure(IPage page, Guid parentPageId) { if (DataFacade.GetData<IPageStructure>(f => f.Id == page.Id).Any()) return; int siblingPageCount = (from ps in DataFacade.GetData<IPageStructure>() where ps.ParentId == parentPageId select ps).Count(); IPageStructure newPageStructure = DataFacade.BuildNew<IPageStructure>(); newPageStructure.ParentId = parentPageId; newPageStructure.Id = page.Id; newPageStructure.LocalOrdering = siblingPageCount; DataFacade.AddNew<IPageStructure>(newPageStructure); } } internal class TopPageInsertPosition : IPageInsertionPosition { public void CreatePageStructure(IPage page, Guid parentPageId) { if (DataFacade.GetData<IPageStructure>(f => f.Id == page.Id).Any()) return; PageServices.InsertIntoPositionInternal(page.Id, parentPageId, 0); } } internal class AlphabeticPageInsertPosition : IPageInsertionPosition { public void CreatePageStructure(IPage newPage, Guid parentPageId) { if (DataFacade.GetData<IPageStructure>(f => f.Id == newPage.Id).Any()) return; List<IPageStructure> pageStructures = (from ps in DataFacade.GetData<IPageStructure>() where ps.ParentId == parentPageId orderby ps.LocalOrdering select ps).ToList(); var cultureInfo = UserSettings.CultureInfo; int targetLocalOrdering = pageStructures.Any() ? -1 : 0; foreach (IPageStructure pageStructure in pageStructures) { if (targetLocalOrdering != -1) { pageStructure.LocalOrdering++; continue; } IPage page = (from p in DataFacade.GetData<IPage>() where p.Id == pageStructure.Id select p).SingleOrDefault(); if (page == null) { continue; } if (string.Compare(page.Title, newPage.Title, true, cultureInfo) > 0) { targetLocalOrdering = pageStructure.LocalOrdering; pageStructure.LocalOrdering++; } } if (targetLocalOrdering == -1) { targetLocalOrdering = pageStructures.Last().LocalOrdering + 1; } else { DataFacade.Update(pageStructures.Where(page => page.LocalOrdering > targetLocalOrdering)); } var newPageStructure = DataFacade.BuildNew<IPageStructure>(); newPageStructure.ParentId = parentPageId; newPageStructure.Id = newPage.Id; newPageStructure.LocalOrdering = targetLocalOrdering; DataFacade.AddNew(newPageStructure); } } internal class AfterPageInsertPosition : IPageInsertionPosition { private readonly Guid _existingPageId; public AfterPageInsertPosition(Guid existingPageId) { _existingPageId = existingPageId; } public void CreatePageStructure(IPage newPage, Guid parentPageId) { if (DataFacade.GetData<IPageStructure>(f => f.Id == newPage.Id).Any()) return; var pageStructures = (from ps in DataFacade.GetData<IPageStructure>() where ps.ParentId == parentPageId orderby ps.LocalOrdering select ps).ToList(); bool pageInserted = false; foreach (IPageStructure pageStructure in pageStructures) { if (!pageInserted) { if (pageStructure.Id == _existingPageId) { IPageStructure newPageStructure = DataFacade.BuildNew<IPageStructure>(); newPageStructure.ParentId = parentPageId; newPageStructure.Id = newPage.Id; newPageStructure.LocalOrdering = pageStructure.LocalOrdering + 1; DataFacade.AddNew<IPageStructure>(newPageStructure); pageInserted = true; } } else { pageStructure.LocalOrdering += 1; } } DataFacade.Update(pageStructures); } } } } ================================================ FILE: Composite/Data/Types/PageServices.cs ================================================ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using Composite.C1Console.Trees; using Composite.C1Console.Users; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Data.ProcessControlled; using Composite.Data.Transactions; namespace Composite.Data.Types { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class PageServices { private static readonly object _lock = new object(); /// <exclude /> public static Guid GetParentId(this IPage page) { Verify.ArgumentNotNull(page, nameof(page)); Verify.ArgumentCondition(page.DataSourceId.ExistsInStore, nameof(page), "The given data have not been added yet"); return PageManager.GetParentId(page.Id); } /// <exclude /> public static int GetLocalOrdering(this IPage page) { Verify.ArgumentNotNull(page, nameof(page)); Verify.ArgumentCondition(page.DataSourceId.ExistsInStore, nameof(page), "The given data have not been added yet"); using (new DataScope(DataScopeIdentifier.Administrated)) { return PageManager.GetLocalOrdering(page.Id); } } /// <exclude /> public static IQueryable<IPage> GetChildren(this IPage page) { Verify.ArgumentNotNull(page, nameof(page)); Verify.ArgumentCondition(page.DataSourceId.ExistsInStore, nameof(page), "The given data have not been added yet"); return GetChildren(page.Id); } /// <exclude /> public static IQueryable<IPage> GetChildren(Guid parentId) { var structure = DataFacade.GetData<IPageStructure>(); var pages = DataFacade.GetData<IPage>(); if (structure.IsEnumerableQuery() && pages.IsEnumerableQuery()) { return (from ps in structure.AsEnumerable() where ps.ParentId == parentId join p in pages.AsEnumerable() on ps.Id equals p.Id orderby ps.LocalOrdering select p).AsQueryable(); } return from ps in structure where ps.ParentId == parentId join p in pages on ps.Id equals p.Id orderby ps.LocalOrdering select p; #warning revisit this - we return all versions (by design so far). Any ordering on page versions? - check history for original intent } /// <exclude /> public static int GetChildrenCount(Guid parentId) { using (new DataScope(DataScopeIdentifier.Administrated)) { return PageManager.GetChildrenIDs(parentId).Count; } } /// <exclude /> public static ReadOnlyCollection<Guid> GetChildrenIDs(Guid parentId) { using (new DataScope(DataScopeIdentifier.Administrated)) { return PageManager.GetChildrenIDs(parentId); } } /// <exclude /> public static bool IsChildrenAlphabeticOrdered(Guid parentId) { lock (_lock) { var pageIds = PageManager.GetChildrenIDs(parentId); if (pageIds.Count == 0) return true; IPage firstPage = PageManager.GetPageById(pageIds[0], true); for (int i = 1; i < pageIds.Count; i++) { IPage currentPage = PageManager.GetPageById(pageIds[i], true); if (((firstPage != null) && (currentPage != null)) && (string.Compare(firstPage.Title, currentPage.Title, true, UserSettings.CultureInfo) > 0)) { return false; } if (currentPage != null) { firstPage = currentPage; } } return true; } } /// <exclude /> public static IPage GetPageFromLocalOrder(Guid parentId, int localOrder) { Guid pageId; using (new DataScope(DataScopeIdentifier.Administrated)) { // FirstOrDefault used here because local ordering could be "corrupt" IPageStructure pageStructure = (from ps in DataFacade.GetData<IPageStructure>() where ps.ParentId == parentId && ps.LocalOrdering == localOrder select ps).FirstOrDefault(); if (pageStructure == null) return null; pageId = pageStructure.Id; } return DataFacade.GetData<IPage>(f => f.Id == pageId).FirstOrDefault(); } /// <exclude /> [Obsolete("Use Add() method instead")] public static IPage AddPageAtTop(this IPage newPage, Guid parentId) { return AddPageAtTop(newPage, parentId, true); } /// <exclude /> [Obsolete("Use Add() method instead")] public static IPage AddPageAtTop(this IPage newPage, Guid parentId, bool addNewPage) { return newPage.InsertIntoPosition(parentId, 0, addNewPage); } /// <exclude /> [Obsolete("Use Add() method instead")] public static IPage AddPageAtBottom(this IPage newPage, Guid parentId) { return AddPageAtBottom(newPage, parentId, true); } /// <exclude /> [Obsolete("Use Add() method instead")] public static IPage AddPageAtBottom(this IPage newPage, Guid parentId, bool addNewPage) { Verify.ArgumentNotNull(newPage, nameof(newPage)); lock (_lock) { PageInsertPosition.Bottom.CreatePageStructure(newPage, parentId); return addNewPage ? DataFacade.AddNew<IPage>(newPage) : newPage; } } /// <summary> /// Adds a page to the specified position. /// </summary> /// <param name="newPage">The new page to be added.</param> /// <param name="parentId">The parent id.</param> /// <param name="pageInsertionPosition">The page insertion position</param> /// <returns></returns> public static IPage Add(this IPage newPage, Guid parentId, IPageInsertionPosition pageInsertionPosition) { Verify.ArgumentNotNull(newPage, nameof(newPage)); Verify.ArgumentNotNull(pageInsertionPosition, nameof(pageInsertionPosition)); lock (_lock) { pageInsertionPosition.CreatePageStructure(newPage, parentId); newPage = DataFacade.AddNew<IPage>(newPage); AddPageTypeRelatedData(newPage); } return newPage; } /// <exclude /> [Obsolete("Use Add() method instead")] public static IPage AddPageAlphabetic(this IPage newPage, Guid parentId) { Verify.ArgumentNotNull(newPage, nameof(newPage)); lock (_lock) { PageInsertPosition.Alphabetic.CreatePageStructure(newPage, parentId); return DataFacade.AddNew<IPage>(newPage); } } /// <exclude /> [Obsolete("Use Add() method instead")] public static IPage AddPageAfter(this IPage newPage, Guid parentId, Guid existingPageId) { return AddPageAfter(newPage, parentId, existingPageId, true); } /// <exclude /> public static IPage MoveTo(this IPage page, Guid parentId, int localOrder, bool addNewPage) { Verify.ArgumentNotNull(page, nameof(page)); lock (_lock) { IPageStructure pageStructure = DataFacade.GetData<IPageStructure>(f => f.Id == page.Id).FirstOrDefault(); if (pageStructure != null) { if (pageStructure.ParentId == parentId) { if (localOrder == pageStructure.LocalOrdering) { // If page is already has the right order - don't do anything return page; } if (localOrder > pageStructure.LocalOrdering) { localOrder--; } } DataFacade.Delete(pageStructure); if (pageStructure.ParentId != parentId) { FixOrder(pageStructure.ParentId); } } return InsertIntoPosition(page, parentId, localOrder, addNewPage); } } private static void FixOrder(Guid parentId) { List<IPageStructure> pageStructures = DataFacade.GetData<IPageStructure>(ps => ps.ParentId == parentId).ToList(); pageStructures = pageStructures.OrderBy(ps => ps.LocalOrdering).ToList(); for (int i = pageStructures.Count - 1; i >= 0; i--) { if (pageStructures[i].LocalOrdering == i) // If order is correct, skipping the page structure object { pageStructures.RemoveAt(i); continue; } pageStructures[i].LocalOrdering = i; } if (pageStructures.Count == 0) return; DataFacade.Update(pageStructures); } /// <exclude /> public static IPage InsertIntoPosition(this IPage newPage, Guid parentId, int localOrder, bool addNewPage) { Verify.ArgumentNotNull(newPage, nameof(newPage)); lock (_lock) { InsertIntoPositionInternal(newPage.Id, parentId, localOrder); return addNewPage ? DataFacade.AddNew(newPage) : newPage; } } internal static void InsertIntoPositionInternal(Guid newPageId, Guid parentId, int localOrder) { List<IPageStructure> pageStructures = (from ps in DataFacade.GetData<IPageStructure>(false) where ps.ParentId == parentId orderby ps.LocalOrdering select ps).ToList(); var toBeUpdated = new List<IData>(); for (int i = 0; i < pageStructures.Count; i++) { int newSortOrder = i < localOrder ? i : i + 1; if (pageStructures[i].LocalOrdering != newSortOrder) { pageStructures[i].LocalOrdering = newSortOrder; toBeUpdated.Add(pageStructures[i]); } } DataFacade.Update(toBeUpdated); if (localOrder > pageStructures.Count) { localOrder = pageStructures.Count; } var newPageStructure = DataFacade.BuildNew<IPageStructure>(); newPageStructure.Id = newPageId; newPageStructure.ParentId = parentId; newPageStructure.LocalOrdering = localOrder; DataFacade.AddNew(newPageStructure); } /// <exclude /> public static IPage AddPageAfter(this IPage newPage, Guid parentId, Guid existingPageId, bool addNewPage) { Verify.ArgumentNotNull(newPage, nameof(newPage)); lock (_lock) { PageInsertPosition.After(existingPageId).CreatePageStructure(newPage, parentId); if (addNewPage) { return DataFacade.AddNew<IPage>(newPage); } return newPage; } } /// <exclude /> public static IEnumerable<IPage> GetSubChildren(this IPage parentPage) { Verify.ArgumentNotNull(parentPage, nameof(parentPage)); lock (_lock) { foreach (IPage childPage in parentPage.GetChildren()) { yield return childPage; foreach (IPage subPage in childPage.GetSubChildren()) { yield return subPage; } } if (GlobalSettingsFacade.AllowChildPagesTranslationWithoutParent) { var pagesLookup = DataFacade.GetData<IPage>(true).ToLookup(p => p.Id); foreach (Guid emptyPageId in GetEmptyChildren(parentPage.Id, pagesLookup)) { foreach (var page in GetSubChildrenInEmptyParent(emptyPageId, pagesLookup)) { yield return page; } } } } } private static IEnumerable<IPage> GetSubChildrenInEmptyParent(Guid emptyParentId, ILookup<Guid, IPage> pages) { foreach (IPage childPage in GetChildren(emptyParentId)) { yield return childPage; foreach (IPage subPage in childPage.GetSubChildren()) { yield return subPage; } } foreach (Guid emptyPageId in GetEmptyChildren(emptyParentId, pages)) { foreach (IPage subPage in GetSubChildrenInEmptyParent(emptyPageId, pages)) { yield return subPage; } } } private static IQueryable<Guid> GetEmptyChildren(Guid parentId, ILookup<Guid, IPage> pages) { var structure = DataFacade.GetData<IPageStructure>(true); if (structure.IsEnumerableQuery()) { return (from ps in structure.AsEnumerable() where ps.ParentId == parentId && !pages[ps.Id].Any() select ps.Id).AsQueryable(); } return from ps in structure where ps.ParentId == parentId && !pages[ps.Id].Any() select ps.Id; } /// <summary> /// This method will delete the pagestructure corresponding to the given page if this /// page is the last page. /// </summary> /// <param name="page">The page that is about to be deleted.</param> public static void DeletePageStructure(this IPage page) { DeletePageStructure(page, true); } internal static void DeletePageStructure(this IPage page, bool updateSiblingsOrder) { if (ExistsInOtherLocale(page)) { return; } var structureInfo = DataFacade.GetData<IPageStructure>(false).SingleOrDefault(f => f.Id == page.Id); if (structureInfo == null) { return; } int localOrdering = structureInfo.LocalOrdering; DataFacade.Delete<IPageStructure>(structureInfo); if (!updateSiblingsOrder) return; List<IPageStructure> siblings = DataFacade.GetData<IPageStructure>( f => f.ParentId == structureInfo.ParentId && f.LocalOrdering >= localOrdering).ToList(); // If there's a page with the same local ordering - we're not changing anything if (siblings.Count == 0 || siblings.Any(ps => ps.LocalOrdering == localOrdering)) { return; } foreach (IPageStructure sibling in siblings) { sibling.LocalOrdering--; DataFacade.Update(sibling); } } private static bool ExistsInOtherLocale(IPage page) { var otherLocales = DataLocalizationFacade.ActiveLocalizationCultures.Except(new[] {page.DataSourceId.LocaleScope}); foreach (CultureInfo cultureInfo in otherLocales) { using (new DataScope(cultureInfo)) { bool exists = DataFacade.GetData<IPage>(f => f.Id == page.Id).Any(); if (exists) { return true; } } } return false; } /// <summary> /// Gets a default page type id for a given page type, if available. /// </summary> /// <param name="pageTypeId"></param> public static Guid? GetDefaultPageTemplateId(Guid pageTypeId) { IPageType pageType = DataFacade.GetData<IPageType>().Single(f => f.Id == pageTypeId); if (pageType.DefaultTemplateId != Guid.Empty) { return pageType.DefaultTemplateId; } var templateRestrictions = DataFacade.GetData<IPageTypePageTemplateRestriction>() .Where(f => f.PageTypeId == pageTypeId); return templateRestrictions.FirstOrDefault()?.PageTemplateId; } /// <summary> /// Creates page type related data for a newly created IPage, based on a given page type id. /// Including: default placeholder content, page folders, page applications. /// </summary> /// <param name="page"></param> public static void AddPageTypeRelatedData(IPage page) { Guid pageTypeId = page.PageTypeId; Verify.That(pageTypeId != Guid.Empty, "PageTypeId field should not be Guid.Empty"); // Adding default page content IEnumerable<IPageTypeDefaultPageContent> pageTypeDefaultPageContents = DataFacade.GetData<IPageTypeDefaultPageContent>(). Where(f => f.PageTypeId == pageTypeId). Evaluate(); foreach (IPageTypeDefaultPageContent pageTypeDefaultPageContent in pageTypeDefaultPageContents) { IPagePlaceholderContent pagePlaceholderContent = DataFacade.BuildNew<IPagePlaceholderContent>(); pagePlaceholderContent.PageId = page.Id; pagePlaceholderContent.VersionId = page.VersionId; pagePlaceholderContent.PlaceHolderId = pageTypeDefaultPageContent.PlaceHolderId; pagePlaceholderContent.Content = pageTypeDefaultPageContent.Content; DataFacade.AddNew<IPagePlaceholderContent>(pagePlaceholderContent); } AddPageTypePageFoldersAndApplications(page); } /// <summary> /// Deletes the versions of the given page in its current localization scope. /// </summary> public static void DeletePage(IPage page) { DeletePage(page, true); } /// <summary> /// Deletes the versions of the given page in its current localization scope. /// </summary> public static void DeletePage(IPage page, bool deleteChildPages) { using (var transactionScope = TransactionsFacade.CreateNewScope()) { using (var conn = new DataConnection()) { conn.DisableServices(); var cultures = DataLocalizationFacade.ActiveLocalizationCultures.ToList(); cultures.Remove(page.DataSourceId.LocaleScope); if (deleteChildPages) { List<IPage> pagesToDelete = page.GetSubChildren().ToList(); foreach (IPage childPage in pagesToDelete) { if (!ExistInOtherLocale(cultures, childPage)) { RemoveAllFolderAndMetaDataDefinitions(childPage); } childPage.DeletePageStructure(false); ProcessControllerFacade.FullDelete(childPage); } } if (!ExistInOtherLocale(cultures, page)) { RemoveAllFolderAndMetaDataDefinitions(page); } page.DeletePageStructure(); Guid pageId = page.Id; var pageVersions = DataFacade.GetData<IPage>(p => p.Id == pageId).ToList(); ProcessControllerFacade.FullDelete(pageVersions); } transactionScope.Complete(); } } private static bool ExistInOtherLocale(List<CultureInfo> cultures, IPage page) { foreach (CultureInfo localeCultureInfo in cultures) { using (new DataScope(localeCultureInfo)) { if (Composite.Data.PageManager.GetPageById(page.Id) != null) { return true; } } } return false; } private static void RemoveAllFolderAndMetaDataDefinitions(IPage page) { foreach (Type folderType in page.GetDefinedFolderTypes()) { page.RemoveFolderDefinition(folderType, true); } foreach (Tuple<Type, string> metaDataTypeAndName in page.GetDefinedMetaDataTypeAndNames()) { page.RemoveMetaDataDefinition(metaDataTypeAndName.Item2, true); } } /// <summary> /// Delete the specific version of the page in the current localization scope. /// </summary> /// <param name="pageId"></param> /// <param name="versionId"></param> /// <param name="locale"></param> public static void DeletePage(Guid pageId, Guid versionId, CultureInfo locale) { DeletePage(pageId, versionId, locale, true); } /// <summary> /// Delete the specific version of the page in the current localization scope. /// </summary> /// <param name="pageId"></param> /// <param name="versionId"></param> /// <param name="locale"></param> /// <param name="deleteChildPages"></param> public static void DeletePage(Guid pageId, Guid versionId, CultureInfo locale, bool deleteChildPages) { Verify.ArgumentNotNull(locale, nameof(locale)); using (var conn = new DataConnection(PublicationScope.Unpublished, locale)) { var pages = conn.Get<IPage>().Where(p => p.Id == pageId).ToList(); if (pages.Count == 1 && pages[0].VersionId == versionId) { DeletePage(pages[0], deleteChildPages); return; } } var publicationScopes = new[] {PublicationScope.Published, PublicationScope.Unpublished}; using (var transactionScope = TransactionsFacade.CreateNewScope()) { foreach (var publicationScope in publicationScopes) { using (var conn = new DataConnection(publicationScope, locale)) { var pageToDelete = conn.Get<IPage>() .SingleOrDefault(p => p.Id == pageId && p.VersionId == versionId); var placeholders = conn.Get<IPagePlaceholderContent>() .Where(p => p.PageId == pageId && p.VersionId == versionId).ToList(); if (placeholders.Any()) { DataFacade.Delete(placeholders, false, false); } if (pageToDelete != null) { // References should be retained if another version of the page exists; hence, the use of CascadeDeleteType.Disable is justified. DataFacade.Delete(pageToDelete, CascadeDeleteType.Disable); } } } transactionScope.Complete(); } } internal static bool AddPageTypePageFoldersAndApplications(IPage page) { #warning Validate that having a page type with associated PageType PageFolders or Applications does not break on 2nd add for same page id Guid pageTypeId = page.PageTypeId; bool treeRefreshindNeeded = false; // Adding page folders IEnumerable<IPageTypeDataFolderTypeLink> pageTypeDataFolderTypeLinks = DataFacade.GetData<IPageTypeDataFolderTypeLink>(). Where(f => f.PageTypeId == pageTypeId). Evaluate(). RemoveDeadLinks(); foreach (IPageTypeDataFolderTypeLink pageTypeDataFolderTypeLink in pageTypeDataFolderTypeLinks) { page.AddFolderDefinition(pageTypeDataFolderTypeLink.DataTypeId); treeRefreshindNeeded = true; } // Adding applications IEnumerable<IPageTypeTreeLink> pageTypeTreeLinks = DataFacade.GetData<IPageTypeTreeLink>(). Where(f => f.PageTypeId == pageTypeId). Evaluate(). RemoveDeadLinks(); var entityToken = page.GetDataEntityToken(); foreach (IPageTypeTreeLink pageTypeTreeLink in pageTypeTreeLinks) { var tree = TreeFacade.GetTree(pageTypeTreeLink.TreeId); if (tree.HasAttachmentPoints(entityToken)) continue; TreeFacade.AddPersistedAttachmentPoint(pageTypeTreeLink.TreeId, typeof(IPage), page.Id); treeRefreshindNeeded = true; } return treeRefreshindNeeded; } } } ================================================ FILE: Composite/Data/Types/StoreIdFilter/Foundation/IStoreIdFilterQueryable.cs ================================================ using System.Linq; namespace Composite.Data.Types.StoreIdFilter.Foundation { internal interface IStoreIdFilterQueryable { IQueryable Source { get; } } } ================================================ FILE: Composite/Data/Types/StoreIdFilter/Foundation/StoreIdFilterQueryableCache.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.C1Console.Events; using Composite.Core.Logging; namespace Composite.Data.Types.StoreIdFilter.Foundation { internal static class StoreIdFilterQueryableCache { private static Dictionary<Type, Dictionary<Type, MethodInfo>> _storeIdFilterQueryableCreateQueryCache = new Dictionary<Type, Dictionary<Type, MethodInfo>>(); private static Dictionary<Type, Dictionary<Type, MethodInfo>> _storeIdFilterQueryableExecuteMethodInfoCache = new Dictionary<Type, Dictionary<Type, MethodInfo>>(); private static Dictionary<Type, MethodInfo> _storeIdFilterQueryableGetEnumeratorMethodInfoCache = new Dictionary<Type, MethodInfo>(); static StoreIdFilterQueryableCache() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlush); } public static MethodInfo GetStoreIdFilterQueryableCreateQueryMethodInfo(Type genericType, Type expressionType) { Dictionary<Type, MethodInfo> methodInfoes; if (_storeIdFilterQueryableExecuteMethodInfoCache.TryGetValue(genericType, out methodInfoes) == false) { methodInfoes = new Dictionary<Type, MethodInfo>(); _storeIdFilterQueryableExecuteMethodInfoCache.Add(genericType, methodInfoes); } MethodInfo methodInfo; if (methodInfoes.TryGetValue(expressionType, out methodInfo) == false) { Type type = typeof(StoreIdFilterQueryable<>).MakeGenericType(new Type[] { genericType }); methodInfo = (from method in type.GetMethods() where method.Name == "CreateQuery" && method.IsGenericMethod select method).First(); methodInfo = methodInfo.MakeGenericMethod(new Type[] { expressionType }); methodInfoes.Add(expressionType, methodInfo); } return methodInfo; } public static MethodInfo GetStoreIdFilterQueryableExecuteMethodInfo(Type genericType, Type expressionType) { Dictionary<Type, MethodInfo> methodInfoes; if (_storeIdFilterQueryableExecuteMethodInfoCache.TryGetValue(genericType, out methodInfoes) == false) { methodInfoes = new Dictionary<Type, MethodInfo>(); _storeIdFilterQueryableExecuteMethodInfoCache.Add(genericType, methodInfoes); } MethodInfo methodInfo; if (methodInfoes.TryGetValue(expressionType, out methodInfo) == false) { Type type = typeof(StoreIdFilterQueryable<>).MakeGenericType(new Type[] { genericType }); methodInfo = (from method in type.GetMethods() where method.Name == "Execute" && method.IsGenericMethod select method).First(); methodInfo = methodInfo.MakeGenericMethod(new Type[] { expressionType }); methodInfoes.Add(expressionType, methodInfo); } return methodInfo; } public static MethodInfo GetStoreIdFilterQueryableGetEnumeratorMethodInfo(Type genericType) { MethodInfo methodInfo; if (_storeIdFilterQueryableGetEnumeratorMethodInfoCache.TryGetValue(genericType, out methodInfo) == false) { Type type = typeof(StoreIdFilterQueryable<>).MakeGenericType(new Type[] { genericType }); methodInfo = (from method in type.GetMethods() where method.Name == "GetEnumerator" select method).First(); _storeIdFilterQueryableGetEnumeratorMethodInfoCache.Add(genericType, methodInfo); } return methodInfo; } private static void Flush() { _storeIdFilterQueryableCreateQueryCache = new Dictionary<Type, Dictionary<Type, MethodInfo>>(); _storeIdFilterQueryableGetEnumeratorMethodInfoCache = new Dictionary<Type, MethodInfo>(); _storeIdFilterQueryableExecuteMethodInfoCache = new Dictionary<Type, Dictionary<Type, MethodInfo>>(); } private static void OnFlush(FlushEventArgs args) { Flush(); } } } ================================================ FILE: Composite/Data/Types/StoreIdFilter/Foundation/StoreIdFilterQueryableChangeSourceExpressionVisitor.cs ================================================ using System.Linq.Expressions; namespace Composite.Data.Types.StoreIdFilter.Foundation { internal sealed class StoreIdFilterQueryableChangeSourceExpressionVisitor : ExpressionVisitor { private readonly Expression _newSourceExpression; public StoreIdFilterQueryableChangeSourceExpressionVisitor() { } public StoreIdFilterQueryableChangeSourceExpressionVisitor(Expression newSourceExpression) { _newSourceExpression = newSourceExpression; } protected override Expression VisitConstant(ConstantExpression c) { var storeIdFilterQueryable = c.Value as IStoreIdFilterQueryable; if (storeIdFilterQueryable == null) { return base.VisitConstant(c); } return _newSourceExpression ?? storeIdFilterQueryable.Source.Expression; } } } ================================================ FILE: Composite/Data/Types/StoreIdFilter/Foundation/StoreIdFilterQueryableExpressionVisitor.cs ================================================ using System; using System.Linq.Expressions; using System.Reflection; namespace Composite.Data.Types.StoreIdFilter.Foundation { /// <summary> /// Searches for a "StoreId" filtering in an expression tree. /// </summary> internal sealed class StoreIdFilterQueryableExpressionVisitor : ExpressionVisitor { private static readonly MemberInfo _mediaFileStoreIdMemberInfo = typeof(IMediaFile).GetMember("StoreId")[0]; private static readonly MemberInfo _mediaFileFolderStoreIdMemberInfo = typeof(IMediaFileFolder).GetMember("StoreId")[0]; public StoreIdFilterQueryableExpressionVisitor() { this.FoundStoreId = null; } protected override Expression VisitConstant(ConstantExpression c) { if (c.Value is IStorageFilter) { FoundStoreId = (c.Value as IStorageFilter).StoreId; } return base.VisitConstant(c); } protected override Expression VisitBinary(BinaryExpression b) { if (b.Method != null && b.Method.Name == "op_Equality") { bool hasStoreIdMemberExpression = IsStoreIdMemberExpression(b.Left) || IsStoreIdMemberExpression(b.Right); if (hasStoreIdMemberExpression) { string storeId = GetStoreId(b.Left) ?? GetStoreId(b.Right); if (storeId != null) { this.FoundStoreId = storeId; } } } return base.VisitBinary(b); } public string FoundStoreId { get; private set; } private bool IsStoreIdMemberExpression(Expression expression) { MemberExpression memberExpression = expression as MemberExpression; if (memberExpression == null) return false; if (memberExpression.Expression.Type != typeof(IMediaFile) && memberExpression.Expression.Type != typeof(IMediaFileFolder)) { return false; } if (memberExpression.Member != _mediaFileStoreIdMemberInfo && memberExpression.Member != _mediaFileFolderStoreIdMemberInfo) { return false; } return true; } private string GetStoreId(Expression expression) { if (expression is ConstantExpression) { var constantExpression = expression as ConstantExpression; if (constantExpression.Value == null || constantExpression.Type != typeof (string)) return null; return (string)constantExpression.Value; } if (expression is MemberExpression) { var memberExpression = expression as MemberExpression; if (memberExpression.Expression.NodeType != ExpressionType.Constant) return null; object obj = ((ConstantExpression)memberExpression.Expression).Value; FieldInfo fieldInfo = memberExpression.Member as FieldInfo; if (fieldInfo == null) return null; return (string)fieldInfo.GetValue(obj); } throw new InvalidOperationException("This line should not be reachable"); } } } ================================================ FILE: Composite/Data/Types/StoreIdFilter/StoreIdFilterQueryable.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Data.Types.StoreIdFilter.Foundation; namespace Composite.Data.Types.StoreIdFilter { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IStorageFilter { /// <exclude /> string StoreId { get; } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class StoreIdFilterQueryable<T> : IStoreIdFilterQueryable, IOrderedQueryable<T>, IQueryProvider, IStorageFilter { private readonly IQueryable<T> _originalQueryable; private readonly string _storeId; private readonly Expression _currentExpression; private static readonly PropertyInfo _mediaFileStoreIdPropertyInfo = typeof(IMediaFile).GetProperty("StoreId"); private static readonly PropertyInfo _mediaFileFolderStoreIdPropertyInfo = typeof(IMediaFileFolder).GetProperty("StoreId"); /// <exclude /> public StoreIdFilterQueryable(IQueryable<T> originalQueryable, string storeId) { _originalQueryable = originalQueryable; _storeId = storeId; _currentExpression = Expression.Constant(this); } /// <exclude /> public StoreIdFilterQueryable(IQueryable<T> originalQueryable, string storeId, Expression currentExpression) { _originalQueryable = originalQueryable; _storeId = storeId; _currentExpression = currentExpression; } /// <exclude /> public IQueryable<S> CreateQuery<S>(Expression expression) { var visitor = new StoreIdFilterQueryableChangeSourceExpressionVisitor(); Expression newExpression = visitor.Visit(expression); IQueryable<S> newOriginalQueryable = _originalQueryable.Provider.CreateQuery<S>(newExpression); return new StoreIdFilterQueryable<S>(newOriginalQueryable, _storeId, expression); } /// <exclude /> public IQueryable CreateQuery(Expression expression) { if (_currentExpression == expression) return this; MethodInfo methodInfo = StoreIdFilterQueryableCache.GetStoreIdFilterQueryableCreateQueryMethodInfo(typeof(T), expression.Type); return (IQueryable)methodInfo.Invoke(this, new object[] { expression }); } /// <exclude /> public S Execute<S>(Expression expression) { var visitor = new StoreIdFilterQueryableExpressionVisitor(); visitor.Visit(_currentExpression); if (visitor.FoundStoreId == _storeId) { var sourceChangingVisitor = new StoreIdFilterQueryableChangeSourceExpressionVisitor(); Expression newExpression = sourceChangingVisitor.Visit(expression); return _originalQueryable.Provider.Execute<S>(newExpression); } else { List<T> emptyList = new List<T>(); var sourceChangingVisitor = new StoreIdFilterQueryableChangeSourceExpressionVisitor(emptyList.AsQueryable().Expression); Expression newExpression = sourceChangingVisitor.Visit(expression); return emptyList.AsQueryable().Provider.Execute<S>(newExpression); } } /// <exclude /> public object Execute(Expression expression) { MethodInfo methodInfo = StoreIdFilterQueryableCache.GetStoreIdFilterQueryableExecuteMethodInfo(typeof(T), expression.Type); return methodInfo.Invoke(this, new object[] { expression }); } /// <exclude /> public IEnumerator<T> GetEnumerator() { var visitor = new StoreIdFilterQueryableExpressionVisitor(); visitor.Visit(_currentExpression); if (visitor.FoundStoreId == null) { throw new InvalidOperationException("Missing storeId test found in where"); } if (visitor.FoundStoreId != _storeId) { return new List<T>().GetEnumerator(); } return FilterByStoreId(_originalQueryable).GetEnumerator(); } IEnumerable<T> FilterByStoreId(IEnumerable<T> enumeration) { foreach (T item in enumeration) { if (GetStoreId(item) == _storeId) { yield return item; } } } static string GetStoreId(T item) { if (item is IMediaFile) { return (string) _mediaFileStoreIdPropertyInfo.GetValue(item, null); } if (item is IMediaFileFolder) { return (string)_mediaFileFolderStoreIdPropertyInfo.GetValue(item, null); } throw new InvalidOperationException("This line should not be reachable"); } /// <exclude /> IEnumerator IEnumerable.GetEnumerator() { MethodInfo methodInfo = StoreIdFilterQueryableCache.GetStoreIdFilterQueryableGetEnumeratorMethodInfo(typeof(T)); return (IEnumerator)methodInfo.Invoke(this, null); } /// <exclude /> public Expression Expression { get { return _currentExpression; } } /// <exclude /> public Type ElementType { get { return typeof(T); } } /// <exclude /> public IQueryProvider Provider { get { return this; } } /// <exclude /> public IQueryable Source { get { return _originalQueryable; } } /// <exclude /> public string StoreId { get { return _storeId; } } } } ================================================ FILE: Composite/Data/Types/TypeVersionAttribute.cs ================================================ using System; namespace Composite.Data { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("This is no longer used in C1. From version 3.0", true)] public sealed class TypeVersionAttribute : Attribute { /// <exclude /> public TypeVersionAttribute(int version) { this.Version = version; } /// <exclude /> public int Version { get; private set; } } } ================================================ FILE: Composite/Data/Types/VersionedDataHelperContract.cs ================================================ using System; using System.Collections.Generic; using System.Linq; namespace Composite.Data.Types { /// <summary> /// Contract for defining IVersioned extra methods and helper functions /// </summary> public abstract class VersionedDataHelperContract { /// <summary> /// Returns version name for the IVersioned data if it could otherwise returns null /// </summary> public abstract string LocalizedVersionName<T>(T data) where T : IVersioned; /// <summary> /// Returns currently live version name for the IVersioned data if it could otherwise returns null /// </summary> public abstract string GetLiveVersionName<T>(T data) where T : IVersioned; /// <summary> /// Returns column name and tooltip for the extra fields in publication overview, if no extra fields needed returns null /// </summary> public abstract List<VersionedExtraPropertiesColumnInfo> GetExtraPropertiesNames(); /// <summary> /// Returns values for the extra fields in publication overview, if no extra fields needed returns null /// </summary> public abstract List<VersionedExtraProperties> GetExtraProperties<T>(T data) where T : IVersioned; /// <summary> /// Orders the selected data. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dataset"></param> /// <returns></returns> public virtual IEnumerable<T> Order<T>(IEnumerable<T> dataset) where T : IVersioned { return dataset; } } /// <summary> /// This class should be used in every versioning package to register it's naming and detecting of live versions /// </summary> public static class VersionedDataHelper { private static readonly List<VersionedDataHelperContract> _services = new List<VersionedDataHelperContract>(); static VersionedDataHelper() { DataEvents<IPage>.OnBeforeAdd += (sender, args) => { var page = (IPage) args.Data; if (page.VersionId == Guid.Empty) { page.VersionId = Guid.NewGuid(); } }; } internal static void Initialize() { // The initialization code is in the static constructor } /// <summary> /// Returns if there are any versioning package instances available /// </summary> public static bool IsThereAnyVersioningServices => _services.Any(); /// <summary> /// Registers instances of versioning packages /// </summary> public static void RegisterVersionHelper(VersionedDataHelperContract vpc) { _services.Add(vpc); } /// <summary> /// Returns version name for the IVersioned data /// </summary> public static string LocalizedVersionName<T>(this T str) where T : IVersioned { var defaultVersionName = Core.ResourceSystem.LocalizationFiles.Composite_Management.DefaultVersionName; if (_services.Count == 0) { return defaultVersionName; } var versionNames = _services .Select(p => p.LocalizedVersionName(str)) .Where(name => name != null).ToList(); return versionNames.Any() ? string.Join(",", versionNames) : defaultVersionName; } /// <summary> /// Returns column name and tooltip for the extra fields in publication overview /// </summary> public static IEnumerable<VersionedExtraPropertiesColumnInfo> GetExtraPropertyNames() { return _services?.SelectMany(p => p.GetExtraPropertiesNames() ?? Enumerable.Empty<VersionedExtraPropertiesColumnInfo>()).ToList(); } /// <summary> /// Returns values for the extra fields in publication overview /// </summary> public static IEnumerable<VersionedExtraProperties> GetExtraProperties<T>(this T str) where T : IVersioned { return _services.SelectMany(p => p.GetExtraProperties(str) ?? Enumerable.Empty<VersionedExtraProperties>()).ToList(); } /// <summary> /// Returns currently live version name for the IVersioned data /// </summary> public static string GetLiveVersionName<T>(this T data) where T : IVersioned { if (!_services.Any()) { return null; } var versionNames = _services.Select(p => p.GetLiveVersionName(data)).Where(name => name != null).ToList(); return versionNames.Any() ? string.Join(",", versionNames) : null; } /// <summary> /// Orders the data given in the dataset. /// </summary> /// <typeparam name="TDataType">The data type.</typeparam> /// <param name="dataset">The data set to be ordered.</param> /// <returns></returns> public static IEnumerable<TDataType> OrderByVersions<TDataType>(this IEnumerable<TDataType> dataset) where TDataType : IVersioned { if (dataset is ICollection<TDataType> collection && collection.Count < 2) { return collection; } var result = dataset; foreach (var service in _services) { result = service.Order(result); } return result; } } /// <summary> /// Represents Extra fields that a Versioning package needs to insert to the publication overview /// </summary> public class VersionedExtraProperties { /// <exclude /> public string ColumnName; /// <exclude /> public string Value; /// <exclude /> public string SortableValue; } /// <summary> /// Represents column title and tooltip for the Extra fields that a Versioning package needs to insert to the publication overview /// </summary> public class VersionedExtraPropertiesColumnInfo { /// <exclude /> public string ColumnName; /// <exclude /> public string ColumnTooltip; } } ================================================ FILE: Composite/Data/UserTypeEnum.cs ================================================  namespace Composite.Data { /// <summary> /// Used by the <see cref="Composite.Data.RelevantToUserTypeAttribute"/> attribute. /// </summary> public enum UserType { /// <summary> /// Signals relevance to developers, making the data type visible when selecting data types in the C1 Console /// </summary> Developer = 1 } } ================================================ FILE: Composite/Data/Validation/ClientValidationRuleFacade.cs ================================================ using System; using System.Collections.Generic; using Composite.Data.Validation.ClientValidationRules; namespace Composite.Data.Validation { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ClientValidationRuleFacade { private static IClientValidationRuleFacade _implementation = new ClientValidationRuleFacadeImpl(); internal static IClientValidationRuleFacade Implementation { get { return _implementation; } set { _implementation = value; } } /// <exclude /> public static List<ClientValidationRule> GetClientValidationRules(object objectForValidation, string propertyName) { Verify.ArgumentNotNull(objectForValidation, "objectForValidation"); return _implementation.GetClientValidationRules(objectForValidation.GetType(), propertyName); } /// <exclude /> public static List<ClientValidationRule> GetClientValidationRules(Type type, string propertyName) { return _implementation.GetClientValidationRules(type, propertyName); } } } ================================================ FILE: Composite/Data/Validation/ClientValidationRuleFacadeImpl.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.Core.Types; using Composite.Data.Validation.ClientValidationRules; using Composite.Data.Validation.Foundation; using Composite.Data.Validation.Foundation.PluginFacades; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Validation { internal sealed class ClientValidationRuleFacadeImpl : IClientValidationRuleFacade { public List<ClientValidationRule> GetClientValidationRules(Type type, string propertyName) { Verify.ArgumentNotNull(type, "type"); Verify.ArgumentNotNullOrEmpty(propertyName, "propertyName"); PropertyInfo propertyInfo = type.GetProperty(propertyName); Verify.IsNotNull(propertyInfo, "The property named '{0}' not found on the type '{1}'", propertyName, type); List<ValidatorAttribute> attributes = propertyInfo.GetCustomAttributesRecursively<ValidatorAttribute>().ToList(); var rules = new List<ClientValidationRule>(); foreach (ValidatorAttribute attribute in attributes) { string translatorName = ClientValidationRuleTranslatorRegistry.GetTranslatorName(attribute.GetType()); if (translatorName != null) { ClientValidationRule rule = ClientValidationRuleTranslatorPluginFacade.Translate(translatorName, attribute); rules.Add(rule); } } return rules; } } } ================================================ FILE: Composite/Data/Validation/ClientValidationRuleSerializerHandler.cs ================================================ using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using Composite.Core.Serialization; namespace Composite.Data.Validation { internal sealed class ClientValidationRuleSerializerHandler : ISerializerHandler { public string Serialize(object objectToSerialize) { using (MemoryStream ms = new MemoryStream()) { BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(ms, objectToSerialize); ms.Seek(0, SeekOrigin.Begin); using (BinaryReader br = new BinaryReader(ms)) { byte[] bytes = br.ReadBytes((int)ms.Length); string result = Convert.ToBase64String(bytes); return result; } } } public object Deserialize(string serializedObject) { byte[] bytes = Convert.FromBase64String(serializedObject); using (MemoryStream ms = new MemoryStream(bytes)) { BinaryFormatter binaryFormatter = new BinaryFormatter(); object result = binaryFormatter.Deserialize(ms); return result; } } } } ================================================ FILE: Composite/Data/Validation/ClientValidationRules/ClientValidationRule.cs ================================================ using System; using Composite.Core.Serialization; namespace Composite.Data.Validation.ClientValidationRules { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] [SerializerHandler(typeof(ClientValidationRuleSerializerHandler))] public abstract class ClientValidationRule { } } ================================================ FILE: Composite/Data/Validation/ClientValidationRules/NotNullClientValidationRule.cs ================================================ using System; namespace Composite.Data.Validation.ClientValidationRules { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class NotNullClientValidationRule : ClientValidationRule { } } ================================================ FILE: Composite/Data/Validation/ClientValidationRules/RegexClientValidationRule.cs ================================================ using System; namespace Composite.Data.Validation.ClientValidationRules { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class RegexClientValidationRule : ClientValidationRule { /// <exclude /> public RegexClientValidationRule(string expression) { this.Expression = expression; } /// <exclude /> public string Expression { get; private set; } } } ================================================ FILE: Composite/Data/Validation/ClientValidationRules/StringLengthClientValidationRule.cs ================================================ using System; namespace Composite.Data.Validation.ClientValidationRules { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable] public sealed class StringLengthClientValidationRule : ClientValidationRule { /// <exclude /> public StringLengthClientValidationRule(int lowerBound, int upperBound) { this.LowerBound = lowerBound; this.UpperBound = upperBound; } /// <exclude /> public int LowerBound { get; private set; } /// <exclude /> public int UpperBound { get; private set; } } } ================================================ FILE: Composite/Data/Validation/ConstructorBasedPropertyValidatorBuilder.cs ================================================ using System; using System.CodeDom; namespace Composite.Data.Validation { internal sealed class ConstructorBasedPropertyValidatorBuilder<T> : PropertyValidatorBuilder<T> { private readonly CodeAttributeDeclaration _codeAttributeDeclaration; private readonly Attribute _attribute; public ConstructorBasedPropertyValidatorBuilder(CodeAttributeDeclaration codeAttributeDeclaration, Attribute attribute) { _codeAttributeDeclaration = codeAttributeDeclaration; _attribute = attribute; } public override CodeAttributeDeclaration GetCodeAttributeDeclaration() { return _codeAttributeDeclaration; } public override Attribute GetAttribute() { return _attribute; } } } ================================================ FILE: Composite/Data/Validation/DataValidationResult.cs ================================================ using Composite.Data; using Microsoft.Practices.EnterpriseLibrary.Validation; namespace Composite.Data.Validation { internal sealed class DataValidationResult { internal DataValidationResult(IData data, ValidationResults validationResults) { this.Data = data; this.ValidationResults = validationResults; } public IData Data { get; private set; } public ValidationResults ValidationResults { get; private set; } public T GetData<T>() where T : class, IData { return (T)this.Data; } } } ================================================ FILE: Composite/Data/Validation/DataValidationResults.cs ================================================ using Composite.Data; using Microsoft.Practices.EnterpriseLibrary.Validation; namespace Composite.Data.Validation { internal sealed class DataValidationResults { internal DataValidationResults() { } internal void AddResult(IData data, ValidationResults validationResults) { } } } ================================================ FILE: Composite/Data/Validation/Foundation/ClientValidationRuleTranslatorRegistry.cs ================================================ using System; using Composite.C1Console.Events; namespace Composite.Data.Validation.Foundation { internal static class ClientValidationRuleTranslatorRegistry { private static IClientValidationRuleTranslatorRegistry _implementation = new ClientValidationRuleTranslatorRegistryImpl(); internal static IClientValidationRuleTranslatorRegistry Implementation { get { return _implementation; } set { _implementation = value; } } static ClientValidationRuleTranslatorRegistry() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static string GetTranslatorName(Type attributeType) { return _implementation.GetTranslatorName(attributeType); } private static void OnFlushEvent(FlushEventArgs args) { _implementation.OnFlush(); } } } ================================================ FILE: Composite/Data/Validation/Foundation/ClientValidationRuleTranslatorRegistryImpl.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.Data.Validation.Foundation.PluginFacades; using Composite.Data.Validation.Plugins.ClientValidationRuleTranslator; using Composite.Data.Validation.Plugins.ClientValidationRuleTranslator.Runtime; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Validation.Foundation { internal class ClientValidationRuleTranslatorRegistryImpl : IClientValidationRuleTranslatorRegistry { private ResourceLocker<Resources> _resourceLocker = new ResourceLocker<Resources>(new Resources(), Resources.Initialize); public string GetTranslatorName(Type attributeType) { if (attributeType == null) throw new ArgumentNullException("attributeType"); using (_resourceLocker.Locker) { string name = null; _resourceLocker.Resources.AttributeTypeToTranslatorName.TryGetValue(attributeType, out name); return name; } } public void OnFlush() { _resourceLocker.ResetInitialization(); } private sealed class Resources { public Dictionary<Type, string> AttributeTypeToTranslatorName { get; set; } public static void Initialize(Resources resources) { resources.AttributeTypeToTranslatorName = new Dictionary<Type, string>(); if (ConfigurationServices.ConfigurationSource == null) throw new ConfigurationErrorsException(string.Format("No configuration source specified")); ClientValidationRuleTranslatorSettings settings = ConfigurationServices.ConfigurationSource.GetSection(ClientValidationRuleTranslatorSettings.SectionName) as ClientValidationRuleTranslatorSettings; if (settings == null) throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", ClientValidationRuleTranslatorSettings.SectionName)); foreach (ClientValidationRuleTranslatorData data in settings.ClientValidationRuleTranslatorPlugins) { IEnumerable<Type> types = ClientValidationRuleTranslatorPluginFacade.GetSupportedAttributeTypes(data.Name); foreach (Type type in types) { if (resources.AttributeTypeToTranslatorName.ContainsKey(type)) throw new InvalidOperationException(string.Format("The attribute type '{0}' is already handle by a nother translator", type)); if (typeof(ValidatorAttribute).IsAssignableFrom(type) == false) throw new InvalidOperationException(string.Format("The type '{0}' is not an {1}", type, typeof(ValidatorAttribute))); resources.AttributeTypeToTranslatorName.Add(type, data.Name); } } } } } } ================================================ FILE: Composite/Data/Validation/Foundation/IClientValidationRuleTranslatorRegistry.cs ================================================ using System; namespace Composite.Data.Validation.Foundation { internal interface IClientValidationRuleTranslatorRegistry { string GetTranslatorName(Type attributeType); void OnFlush(); } } ================================================ FILE: Composite/Data/Validation/Foundation/PluginFacades/ClientValidationRuleTranslatorPluginFacade.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Events; using Composite.Data.Validation.ClientValidationRules; namespace Composite.Data.Validation.Foundation.PluginFacades { internal static class ClientValidationRuleTranslatorPluginFacade { private static IClientValidationRuleTranslatorPluginFacade _implementation = new ClientValidationRuleTranslatorPluginFacadeImpl(); internal static IClientValidationRuleTranslatorPluginFacade Implementation { get { return _implementation; } set { _implementation = value; } } static ClientValidationRuleTranslatorPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static IEnumerable<Type> GetSupportedAttributeTypes(string translatorName) { return _implementation.GetSupportedAttributeTypes(translatorName); } public static ClientValidationRule Translate(string translatorName, Attribute attribute) { return _implementation.Translate(translatorName, attribute); } private static void OnFlushEvent(FlushEventArgs args) { _implementation.OnFlush(); } } } ================================================ FILE: Composite/Data/Validation/Foundation/PluginFacades/ClientValidationRuleTranslatorPluginFacadeImpl.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.Data.Validation.ClientValidationRules; using Composite.Data.Validation.Plugins.ClientValidationRuleTranslator; using Composite.Data.Validation.Plugins.ClientValidationRuleTranslator.Runtime; namespace Composite.Data.Validation.Foundation.PluginFacades { internal sealed class ClientValidationRuleTranslatorPluginFacadeImpl : IClientValidationRuleTranslatorPluginFacade { private ResourceLocker<Resources> _resourceLocker; public ClientValidationRuleTranslatorPluginFacadeImpl() { _resourceLocker = new ResourceLocker<Resources>(new Resources { Owner = this }, Resources.Initialize); } public IEnumerable<Type> GetSupportedAttributeTypes(string translatorName) { if (string.IsNullOrEmpty(translatorName)) throw new ArgumentNullException("translatorName"); using (_resourceLocker.ReadLocker) { IClientValidationRuleTranslator provider = GetClientValidationRuleTranslator(translatorName); return provider.GetSupportedAttributeTypes(); } } public ClientValidationRule Translate(string translatorName, Attribute attribute) { if (string.IsNullOrEmpty(translatorName)) throw new ArgumentNullException("translatorName"); if (attribute == null) throw new ArgumentNullException("attribute"); using (_resourceLocker.ReadLocker) { IClientValidationRuleTranslator provider = GetClientValidationRuleTranslator(translatorName); return provider.Translate(attribute); } } public void OnFlush() { _resourceLocker.ResetInitialization(); } private IClientValidationRuleTranslator GetClientValidationRuleTranslator(string providerName) { using (_resourceLocker.Locker) { IClientValidationRuleTranslator provider; if (_resourceLocker.Resources.TranslatorCache.TryGetValue(providerName, out provider) == false) { try { provider = _resourceLocker.Resources.Factory.Create(providerName); _resourceLocker.Resources.TranslatorCache.Add(providerName, provider); } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } return provider; } } private void HandleConfigurationError(Exception ex) { OnFlush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", ClientValidationRuleTranslatorSettings.SectionName), ex); } private sealed class Resources { public ClientValidationRuleTranslatorFactory Factory { get; set; } public Dictionary<string, IClientValidationRuleTranslator> TranslatorCache { get; set; } public ClientValidationRuleTranslatorPluginFacadeImpl Owner { get; set; } public static void Initialize(Resources resources) { try { resources.Factory = new ClientValidationRuleTranslatorFactory(); } catch (NullReferenceException ex) { resources.Owner.HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { resources.Owner.HandleConfigurationError(ex); } resources.TranslatorCache = new Dictionary<string, IClientValidationRuleTranslator>(); } } } } ================================================ FILE: Composite/Data/Validation/Foundation/PluginFacades/IClientValidationRuleTranslatorPluginFacade.cs ================================================ using System; using System.Collections.Generic; using Composite.Data.Validation.ClientValidationRules; namespace Composite.Data.Validation.Foundation.PluginFacades { internal interface IClientValidationRuleTranslatorPluginFacade { IEnumerable<Type> GetSupportedAttributeTypes(string translatorName); ClientValidationRule Translate(string translatorName, Attribute attribute); void OnFlush(); } } ================================================ FILE: Composite/Data/Validation/IClientValidationRuleFacade.cs ================================================ using System; using System.Collections.Generic; using Composite.Data.Validation.ClientValidationRules; namespace Composite.Data.Validation { internal interface IClientValidationRuleFacade { List<ClientValidationRule> GetClientValidationRules(Type type, string propertyName); } } ================================================ FILE: Composite/Data/Validation/IPropertyValidatorBuilder.cs ================================================ using System; using System.CodeDom; namespace Composite.Data.Validation { internal interface IPropertyValidatorBuilder { /// <summary> /// This method should return a CodeAttributeDeclaration that will beused for /// code genereting the correct attribute this class represents. /// </summary> /// <returns></returns> //MRJ: Data module refac: Change this to return something else: AttributeType and List of strings for making CodeSnippitExpression CodeAttributeDeclaration GetCodeAttributeDeclaration(); Attribute GetAttribute(); } } ================================================ FILE: Composite/Data/Validation/IValidationFacade.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Practices.EnterpriseLibrary.Validation; using Composite.Data; namespace Composite.Data.Validation { internal interface IValidationFacade { ValidationResults Validate<T>(T data) where T : class, IData; ValidationResults Validate(Type interfaceType, IData data); void OnFlush(); } } ================================================ FILE: Composite/Data/Validation/Plugins/ClientValidationRuleTranslator/ClientValidationRuleTranslatorData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Data.Validation.Plugins.ClientValidationRuleTranslator { [ConfigurationElementType(typeof(NonConfigurableClientValidationRuleTranslator))] internal class ClientValidationRuleTranslatorData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/Data/Validation/Plugins/ClientValidationRuleTranslator/IClientValidationRuleTranslator.cs ================================================ using System; using System.Collections.Generic; using Composite.Data.Validation.ClientValidationRules; using Composite.Data.Validation.Plugins.ClientValidationRuleTranslator.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Data.Validation.Plugins.ClientValidationRuleTranslator { [CustomFactory(typeof(ClientValidationRuleTranslatorCustomFactory))] [ConfigurationNameMapper(typeof(ClientValidationRuleTranslatorDefaultNameRetriever))] internal interface IClientValidationRuleTranslator { IEnumerable<Type> GetSupportedAttributeTypes(); ClientValidationRule Translate(Attribute attribute); } } ================================================ FILE: Composite/Data/Validation/Plugins/ClientValidationRuleTranslator/NonConfigurableClientValidationRuleTranslator.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Data.Validation.Plugins.ClientValidationRuleTranslator { [Assembler(typeof(NonConfigurableClientValidationRuleTranslatorAssembler))] internal class NonConfigurableClientValidationRuleTranslator : ClientValidationRuleTranslatorData { } internal sealed class NonConfigurableClientValidationRuleTranslatorAssembler : IAssembler<IClientValidationRuleTranslator, ClientValidationRuleTranslatorData> { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IClientValidationRuleTranslator Assemble(IBuilderContext context, ClientValidationRuleTranslatorData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IClientValidationRuleTranslator)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/Data/Validation/Plugins/ClientValidationRuleTranslator/Runtime/ClientValidationRuleTranslatorCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Data.Validation.Plugins.ClientValidationRuleTranslator.Runtime { internal sealed class ClientValidationRuleTranslatorCustomFactory : AssemblerBasedCustomFactory<IClientValidationRuleTranslator, ClientValidationRuleTranslatorData> { protected override ClientValidationRuleTranslatorData GetConfiguration(string name, IConfigurationSource configurationSource) { ClientValidationRuleTranslatorSettings settings = configurationSource.GetSection(ClientValidationRuleTranslatorSettings.SectionName) as ClientValidationRuleTranslatorSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", ClientValidationRuleTranslatorSettings.SectionName)); } return settings.ClientValidationRuleTranslatorPlugins.Get(name); } } } ================================================ FILE: Composite/Data/Validation/Plugins/ClientValidationRuleTranslator/Runtime/ClientValidationRuleTranslatorDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Data.Validation.Plugins.ClientValidationRuleTranslator.Runtime { internal sealed class ClientValidationRuleTranslatorDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/Data/Validation/Plugins/ClientValidationRuleTranslator/Runtime/ClientValidationRuleTranslatorFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Data.Validation.Plugins.ClientValidationRuleTranslator.Runtime { internal sealed class ClientValidationRuleTranslatorFactory : NameTypeFactoryBase<IClientValidationRuleTranslator> { public ClientValidationRuleTranslatorFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/Data/Validation/Plugins/ClientValidationRuleTranslator/Runtime/ClientValidationRuleTranslatorSettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Data.Validation.Plugins.ClientValidationRuleTranslator.Runtime { internal sealed class ClientValidationRuleTranslatorSettings : SerializableConfigurationSection { public const string SectionName = "Composite.Data.Validation.Plugins.ClientValidationRuleTranslatorConfiguration"; private const string _clientValidationRuleTranslatorProperty = "ClientValidationRuleTranslatorPlugins"; [ConfigurationProperty(_clientValidationRuleTranslatorProperty)] public NameTypeManagerTypeConfigurationElementCollection<ClientValidationRuleTranslatorData> ClientValidationRuleTranslatorPlugins { get { return (NameTypeManagerTypeConfigurationElementCollection<ClientValidationRuleTranslatorData>)base[_clientValidationRuleTranslatorProperty]; } } } } ================================================ FILE: Composite/Data/Validation/PropertyValidatorBuilder.cs ================================================ using System; using System.CodeDom; namespace Composite.Data.Validation { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class PropertyValidatorBuilder<T> : IPropertyValidatorBuilder { /// <summary> /// This method should return a CodeAttributeDeclaration that will beused for /// code generating the correct attribute this class represents. /// </summary> /// <returns></returns> public abstract CodeAttributeDeclaration GetCodeAttributeDeclaration(); /// <exclude /> public abstract Attribute GetAttribute(); } } ================================================ FILE: Composite/Data/Validation/ValidationFacade.cs ================================================ using System; using Composite.Data; using Composite.C1Console.Events; using Microsoft.Practices.EnterpriseLibrary.Validation; namespace Composite.Data.Validation { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ValidationFacade { private static IValidationFacade _implementation = new ValidationFacadeImpl(); internal static IValidationFacade Implementation { get { return _implementation; } set { _implementation = value; } } /// <exclude /> static ValidationFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } /// <exclude /> public static ValidationResults Validate<T>(T data) where T : class, IData { return _implementation.Validate<T>(data); } // Overload /// <exclude /> public static ValidationResults Validate(IData data) { return Validate(data.DataSourceId.InterfaceType, data); } /// <exclude /> public static ValidationResults Validate(Type interfaceType, IData data) { return _implementation.Validate(interfaceType, data); } private static void OnFlushEvent(FlushEventArgs args) { _implementation.OnFlush(); } } } ================================================ FILE: Composite/Data/Validation/ValidationFacadeImpl.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.Core; using Composite.Core.Collections.Generic; using Microsoft.Practices.EnterpriseLibrary.Validation; namespace Composite.Data.Validation { internal class ValidationFacadeImpl : IValidationFacade { private ResourceLocker<Resources> _resourceLocker = new ResourceLocker<Resources>(new Resources(), Resources.Initialize); public ValidationResults Validate<T>(T data) where T : class, IData { ValidationResults validationResults = Microsoft.Practices.EnterpriseLibrary.Validation.Validation.ValidateFromAttributes<T>(data); return validationResults; } public ValidationResults Validate(Type interfaceType, IData data) { MethodInfo methodInfo; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.MethodCache.TryGetValue(interfaceType, out methodInfo) == false) { methodInfo = (from mi in typeof(ValidationFacade).GetMethods() where (mi.Name == "Validate") && (mi.ContainsGenericParameters) select mi).First(); methodInfo = methodInfo.MakeGenericMethod(new Type[] { interfaceType }); _resourceLocker.Resources.MethodCache.Add(interfaceType, methodInfo); } } ValidationResults validationResults; try { validationResults = (ValidationResults)methodInfo.Invoke(null, new object[] { data }); } catch (TargetInvocationException ex) { Log.LogError("ValidationFacade", ex); validationResults = new ValidationResults(); validationResults.AddResult(new ValidationResult("Exception thrown while validating. Please check field values.", data, "", "", null)); } return validationResults; } public void OnFlush() { _resourceLocker.ResetInitialization(); } private sealed class Resources { public Dictionary<Type, MethodInfo> MethodCache { get; set; } public static void Initialize(Resources resources) { resources.MethodCache = new Dictionary<Type, MethodInfo>(); } } } } ================================================ FILE: Composite/Data/Validation/Validators/DecimalPrecisionValidator.cs ================================================ using System.Globalization; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; using Composite.Core.Types; using Microsoft.Practices.EnterpriseLibrary.Validation; using System.Collections.Generic; using System; using System.Linq; namespace Composite.Data.Validation.Validators { internal sealed class DecimalPrecisionValidator : Validator { public DecimalPrecisionValidator() : base("To many digits", "decimal") { } protected override string DefaultMessageTemplate { get { return "To many digits"; } } protected override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults) { if(objectToValidate == null) { // Skipping valudation if optional decimal is a null return; } var number = (decimal)objectToValidate; List<DecimalPrecisionValidatorAttribute> attributes = currentTarget.GetType().GetProperty(key).GetCustomAttributesRecursively<DecimalPrecisionValidatorAttribute>().ToList(); var validatiorAttribute = attributes[0]; if (number != Decimal.Round(number, validatiorAttribute.Scale)) { LogValidationResult(validationResults, GetString("Validation.Decimal.SymbolsAfterPointAllowed").FormatWith(validatiorAttribute.Scale), currentTarget, key); return; } string str = number.ToString(CultureInfo.InvariantCulture); int separatorIndex = str.IndexOf('.'); if(separatorIndex > 0) { str = str.Substring(0, separatorIndex); } if (str.StartsWith("-")) str = str.Substring(1); int allowedDigitsBeforeSeparator = validatiorAttribute.Precision - validatiorAttribute.Scale; if (str.Length > allowedDigitsBeforeSeparator) { LogValidationResult(validationResults, GetString("Validation.Decimal.SymbolsBeforePointAllowed").FormatWith(allowedDigitsBeforeSeparator), currentTarget, key); } } private static string GetString(string key) { return StringResourceSystemFacade.GetString("Composite.Management", key); } } } ================================================ FILE: Composite/Data/Validation/Validators/DecimalPrecisionValidatorAttribute.cs ================================================ using System; namespace Composite.Data.Validation.Validators { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)] public sealed class DecimalPrecisionValidatorAttribute : Microsoft.Practices.EnterpriseLibrary.Validation.Validators.ValueValidatorAttribute { /// <exclude /> [Obsolete("Use constructor that allow for both precision and scale")] public DecimalPrecisionValidatorAttribute(int digits) { this.Precision = digits + 10; // uneducated guess this.Scale = digits; } /// <summary> /// Creates a decimal precision validator /// </summary> /// <param name="precision">Digits in total</param> /// <param name="scale">Digits after decimal point</param> public DecimalPrecisionValidatorAttribute(int precision, int scale) { if (precision < scale) throw new ArgumentException("Precision cannot be less than scale", "precision"); this.Precision = precision; this.Scale = scale; } /// <summary> /// Number of digits after decimal point - normally you would call this scale. /// </summary> [Obsolete("Use 'Scale'")] public int Digits { get { return this.Scale; } } /// <summary> /// Number of digits after the separator /// </summary> public int Scale { get; private set; } /// <summary> /// Number of digits in total /// </summary> public int Precision { get; private set; } /// <exclude /> protected override Microsoft.Practices.EnterpriseLibrary.Validation.Validator DoCreateValidator(Type targetType) { return new DecimalPrecisionValidator(); } } } ================================================ FILE: Composite/Data/Validation/Validators/DecimalRangeValidatorAttribute.cs ================================================ using System; namespace Composite.Data.Validation.Validators { /// <summary> /// Validator rule for data type properties. /// Validate that a decimal field has a value than falls within a minimum and maximum value. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)] public sealed class DecimalRangeValidatorAttribute : Microsoft.Practices.EnterpriseLibrary.Validation.Validators.ValueValidatorAttribute { /// <summary> /// Validator rule for data type properties. /// Validate that a decimal field has a value than falls within a minimum and maximum value. /// </summary> public DecimalRangeValidatorAttribute(decimal lowerBound, decimal upperBound) { this.LowerBound = lowerBound; this.UpperBound = upperBound; } /// <exclude /> public decimal LowerBound { get; private set; } /// <exclude /> public decimal UpperBound { get; private set; } /// <exclude /> protected override Microsoft.Practices.EnterpriseLibrary.Validation.Validator DoCreateValidator(Type targetType) { return new Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RangeValidator<decimal>( this.LowerBound, Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RangeBoundaryType.Inclusive, this.UpperBound, Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RangeBoundaryType.Inclusive); } } } ================================================ FILE: Composite/Data/Validation/Validators/GuidNotEmptyAttribute.cs ================================================ using System; namespace Composite.Data.Validation.Validators { /// <summary> /// Validator rule for data type properties. /// Validate that a Guid is not Guid.Empty. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)] public sealed class GuidNotEmptyAttribute : Microsoft.Practices.EnterpriseLibrary.Validation.Validators.ValueValidatorAttribute { /// <summary> /// Validator rule for data type properties. /// Validate that a Guid is not Guid.Empty. /// </summary> public GuidNotEmptyAttribute() { } /// <exclude /> protected override Microsoft.Practices.EnterpriseLibrary.Validation.Validator DoCreateValidator(Type targetType) { return new GuidNotEmptyValidator(); } } } ================================================ FILE: Composite/Data/Validation/Validators/GuidNotEmptyValidator.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Validation; namespace Composite.Data.Validation.Validators { internal class GuidNotEmptyValidator : Validator { public GuidNotEmptyValidator() : base("Empty guid value not allowed", "value") { } protected override string DefaultMessageTemplate { get { return "Empty guid value not allowed"; } } protected override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults) { Guid guid = (Guid)objectToValidate; if (guid == Guid.Empty) { LogValidationResult(validationResults, "Empty value not allowed", currentTarget, key); } } } } ================================================ FILE: Composite/Data/Validation/Validators/IntegerRangeValidatorAttribute.cs ================================================ using System; namespace Composite.Data.Validation.Validators { /// <summary> /// Validator rule for data type properties. /// Validate that an integer has a value than falls within a minimum and maximum value. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)] public sealed class IntegerRangeValidatorAttribute : Microsoft.Practices.EnterpriseLibrary.Validation.Validators.ValueValidatorAttribute { /// <summary> /// Validator rule for data type properties. /// Validate that an integer has a value than falls within a minimum and maximum value. /// </summary> public IntegerRangeValidatorAttribute(int lowerBound, int upperBound) { this.LowerBound = lowerBound; this.UpperBound = upperBound; } /// <exclude /> public int LowerBound { get; private set; } /// <exclude /> public int UpperBound { get; private set; } /// <exclude /> protected override Microsoft.Practices.EnterpriseLibrary.Validation.Validator DoCreateValidator(Type targetType) { return new Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RangeValidator<int>( this.LowerBound, Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RangeBoundaryType.Inclusive, this.UpperBound, Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RangeBoundaryType.Inclusive); } } } ================================================ FILE: Composite/Data/Validation/Validators/LazyFunctionProviedPropertyAttribute.cs ================================================ using System; using System.Linq; using System.Reflection; using System.Xml.Linq; using Composite.Core; using Composite.Functions; using Microsoft.Practices.EnterpriseLibrary.Validation; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Validation.Validators { /// <summary> /// This is for internal use only! It is a work around to function providing /// a IPropertyValidatorBuilder that provides CodeDOM when the data type /// interface is code generated. This means that the functions should /// be loaded BEFORE the interface is code generated, which is bad architecture. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)] public class LazyFunctionProviedPropertyAttribute : ValueValidatorAttribute { private static MethodInfo _doCreateValidatorMethodInfo; private string FunctionMarkup { get; set; } /// <summary> /// </summary> /// <param name="functionMarkup"></param> /// <exclude /> public LazyFunctionProviedPropertyAttribute(string functionMarkup) { FunctionMarkup = functionMarkup; } /// <summary> /// /// </summary> /// <param name="targetType"></param> /// <returns></returns> /// <exclude /> protected override Validator DoCreateValidator(Type targetType) { try { BaseRuntimeTreeNode node = FunctionFacade.BuildTree(XElement.Parse(FunctionMarkup)); IPropertyValidatorBuilder propertyValidatorBuilder = node.GetValue<IPropertyValidatorBuilder>(); ValidatorAttribute validatorAttribute = (ValidatorAttribute)propertyValidatorBuilder.GetAttribute(); Validator validator = (Validator)DoCreateValidatorMethodInfo.Invoke(validatorAttribute, new object[] { targetType }); return validator; } catch (Exception ex) { string message = string.Format("Validator function markup parse / execution failed with the following error: '{0}'. The validator attribute is dropped.", ex.Message); Log.LogError("LazyFunctionProviedPropertyAttribute", message); } return new LazyFunctionProviedPropertyValidator(); } private static MethodInfo DoCreateValidatorMethodInfo { get { if (_doCreateValidatorMethodInfo == null) { _doCreateValidatorMethodInfo = typeof(ValidatorAttribute).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance). Where(f => f.Name == "DoCreateValidator" && f.GetParameters().Length == 1). Single(); } return _doCreateValidatorMethodInfo; } } } } ================================================ FILE: Composite/Data/Validation/Validators/LazyFunctionProviedPropertyValidator.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Validation; namespace Composite.Data.Validation.Validators { internal class LazyFunctionProviedPropertyValidator : Validator { public LazyFunctionProviedPropertyValidator() : base("", "") { } protected override string DefaultMessageTemplate { get { return ""; } } protected override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults) { } } } ================================================ FILE: Composite/Data/Validation/Validators/NullDateTimeRangeValidatorAttribute.cs ================================================ using System; using System.Globalization; using Microsoft.Practices.EnterpriseLibrary.Validation; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Validation.Validators { /// <summary> /// Validator rule for data type properties. /// Validate that a Nullable<DateTime> - when not null - has a value than falls within a minimum and maximum value. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)] public sealed class NullDateTimeRangeValidatorAttribute : ValueValidatorAttribute { private readonly DateTime _lowerBound; private readonly DateTime _upperBound; private readonly RangeBoundaryType _upperBoundType; private readonly RangeBoundaryType _lowerBoundType; /// <exclude /> public NullDateTimeRangeValidatorAttribute(string upperBound) : this(ConvertToISO8601Date(upperBound)) { } /// <exclude /> public NullDateTimeRangeValidatorAttribute(DateTime upperBound) : this(DateTime.MinValue, RangeBoundaryType.Ignore, upperBound, RangeBoundaryType.Inclusive) { } /// <exclude /> public NullDateTimeRangeValidatorAttribute(string lowerBound, string upperBound) : this(ConvertToISO8601Date(lowerBound), ConvertToISO8601Date(upperBound)) { } /// <exclude /> public NullDateTimeRangeValidatorAttribute(DateTime lowerBound, DateTime upperBound) : this(lowerBound, RangeBoundaryType.Inclusive, upperBound, RangeBoundaryType.Inclusive) { } /// <exclude /> public NullDateTimeRangeValidatorAttribute(string lowerBound, RangeBoundaryType lowerBoundType, string upperBound, RangeBoundaryType upperBoundType) : this(ConvertToISO8601Date(lowerBound), lowerBoundType, ConvertToISO8601Date(upperBound), upperBoundType) { } /// <exclude /> public NullDateTimeRangeValidatorAttribute(DateTime lowerBound, RangeBoundaryType lowerBoundType, DateTime upperBound, RangeBoundaryType upperBoundType) { _lowerBound = lowerBound; _lowerBoundType = lowerBoundType; _upperBound = upperBound; _upperBoundType = upperBoundType; } /// <exclude /> protected override Validator DoCreateValidator(Type targetType) { return new NullableDateTimeRangeValidator(new RangeValidator<DateTime>( _lowerBound, _lowerBoundType, _upperBound, _upperBoundType)); } private static DateTime ConvertToISO8601Date(string iso8601DateString) { if (string.IsNullOrEmpty(iso8601DateString)) { return new DateTime(); } return DateTime.ParseExact(iso8601DateString, "s", CultureInfo.InvariantCulture); } private class NullableDateTimeRangeValidator : Validator<DateTime?> { private readonly RangeValidator<DateTime> _innerValidator; public NullableDateTimeRangeValidator(RangeValidator<DateTime> innerValidator) : base(null, null) { _innerValidator = innerValidator; } protected override string DefaultMessageTemplate { get { return _innerValidator.MessageTemplate; } } protected override void DoValidate(DateTime? objectToValidate, object currentTarget, string key, ValidationResults validationResults) { if (objectToValidate == null) { return; } validationResults.AddAllResults(_innerValidator.Validate(objectToValidate.Value)); } } } } ================================================ FILE: Composite/Data/Validation/Validators/NullDecimalRangeValidatorAttribute.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Validation; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Validation.Validators { /// <summary> /// Validator rule for data type properties. /// Validate that an nullable decimal - when not null - has a value than falls within a minimum and maximum value. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)] public sealed class NullDecimalRangeValidatorAttribute : ValueValidatorAttribute { /// <summary> /// Validator rule for data type properties. /// Validate that an nullable decimal - when not null - has a value than falls within a minimum and maximum value. /// </summary> public NullDecimalRangeValidatorAttribute(decimal lowerBound, decimal upperBound) { this.LowerBound = lowerBound; this.UpperBound = upperBound; } /// <exclude /> public decimal LowerBound { get; private set; } /// <exclude /> public decimal UpperBound { get; private set; } /// <exclude /> protected override Validator DoCreateValidator(Type targetType) { return new NullableDecimalRangeValidator(new RangeValidator<decimal>( this.LowerBound, RangeBoundaryType.Inclusive, this.UpperBound, RangeBoundaryType.Inclusive)); } private class NullableDecimalRangeValidator : Validator<decimal?> { private readonly RangeValidator<decimal> _innerValidator; public NullableDecimalRangeValidator(RangeValidator<decimal> innerValidator) : base(null, null) { _innerValidator = innerValidator; } protected override string DefaultMessageTemplate { get { return _innerValidator.MessageTemplate; } } protected override void DoValidate(decimal? objectToValidate, object currentTarget, string key, ValidationResults validationResults) { if (objectToValidate == null) { return; } validationResults.AddAllResults(_innerValidator.Validate(objectToValidate.Value)); } } } } ================================================ FILE: Composite/Data/Validation/Validators/NullIntegerRangeValidatorAttribute.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Validation; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Validation.Validators { /// <summary> /// Validator rule for data type properties. /// Validate that an nullable integer - when not null - has a value than falls within a minimum and maximum value. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)] public sealed class NullIntegerRangeValidatorAttribute : ValueValidatorAttribute { /// <summary> /// Validator rule for data type properties. /// Validate that an nullable integer - when not null - has a value than falls within a minimum and maximum value. /// </summary> public NullIntegerRangeValidatorAttribute(int lowerBound, int upperBound) { this.LowerBound = lowerBound; this.UpperBound = upperBound; } /// <exclude /> public int LowerBound { get; private set; } /// <exclude /> public int UpperBound { get; private set; } /// <exclude /> protected override Validator DoCreateValidator(Type targetType) { return new NullableIntRangeValidator(new RangeValidator<int>( this.LowerBound, RangeBoundaryType.Inclusive, this.UpperBound, RangeBoundaryType.Inclusive)); } private class NullableIntRangeValidator : Validator<int?> { private readonly RangeValidator<int> _innerValidator; public NullableIntRangeValidator(RangeValidator<int> innerValidator) : base(null, null) { _innerValidator = innerValidator; } protected override string DefaultMessageTemplate { get { return _innerValidator.MessageTemplate; } } protected override void DoValidate(int? objectToValidate, object currentTarget, string key, ValidationResults validationResults) { if (objectToValidate == null) { return; } validationResults.AddAllResults(_innerValidator.Validate(objectToValidate.Value)); } } } } ================================================ FILE: Composite/Data/Validation/Validators/NullStringLengthValidator.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Validation; namespace Composite.Data.Validation.Validators { internal sealed class NullStringLengthValidator : Validator { private int _lowerBound; private int _upperBound; public NullStringLengthValidator(int lowerBound, int upperBound) : base("The string is either too long or too short", "string") { _lowerBound = lowerBound; _upperBound = upperBound; } protected override string DefaultMessageTemplate { get { return "The string is either too long or too short"; } } protected override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults) { if (objectToValidate != null) { string theString = (string)objectToValidate; if ((theString.Length < _lowerBound) || (theString.Length > _upperBound)) { LogValidationResult(validationResults, string.Format("The length of the string should be in the range {0} to {1} or null", _lowerBound, _upperBound), currentTarget, key); } } } } } ================================================ FILE: Composite/Data/Validation/Validators/NullStringLengthValidatorAttribute.cs ================================================ using System; namespace Composite.Data.Validation.Validators { /// <summary> /// Validator rule for data type properties. /// Validate that a string - when not null - has a length than falls within a minimum and maximum length. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)] public sealed class NullStringLengthValidatorAttribute : Microsoft.Practices.EnterpriseLibrary.Validation.Validators.ValueValidatorAttribute { /// <summary> /// Validator rule for data type properties. /// Validate that a string - when not null - has a length than falls within a minimum and maximum length. /// </summary> public NullStringLengthValidatorAttribute(int lowerBound, int upperBound) { this.LowerBound = lowerBound; this.UpperBound = upperBound; } /// <exclude /> public int LowerBound { get; private set; } /// <exclude /> public int UpperBound { get; private set; } /// <exclude /> protected override Microsoft.Practices.EnterpriseLibrary.Validation.Validator DoCreateValidator(Type targetType) { return new NullStringLengthValidator(this.LowerBound, this.UpperBound); } } } ================================================ FILE: Composite/Data/Validation/Validators/PasswordValidator.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Validation; namespace Composite.Data.Validation.Validators { [Obsolete("No longer used")] internal class PasswordValidator : Validator { public PasswordValidator() : base("The password is not good enough", "password") { } protected override string DefaultMessageTemplate { get { return "The password is not good enough"; } } protected override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults) { string password = objectToValidate as string; if (password != null) { if (password.Length < 6) { LogValidationResult(validationResults, "The password should have a minimum length of 6", currentTarget, key); } } } } } ================================================ FILE: Composite/Data/Validation/Validators/PasswordValidatorAttribute.cs ================================================ using System; namespace Composite.Data.Validation.Validators { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)] public sealed class PasswordValidatorAttribute : Microsoft.Practices.EnterpriseLibrary.Validation.Validators.ValueValidatorAttribute { /// <exclude /> public PasswordValidatorAttribute() { } /// <exclude /> protected override Microsoft.Practices.EnterpriseLibrary.Validation.Validator DoCreateValidator(Type targetType) { return new PasswordValidator(); } } } ================================================ FILE: Composite/Data/Validation/Validators/RegexValidatorAttribute.cs ================================================ using System; using System.Text.RegularExpressions; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Validation.Validators { /// <summary> /// Validator rule for data type properties. /// Represents a <see cref="RegexValidator"/>. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)] public sealed class RegexValidatorAttribute : Microsoft.Practices.EnterpriseLibrary.Validation.Validators.ValueValidatorAttribute { /// <summary> /// Validator rule for data type properties. /// Represents a <see cref="RegexValidator"/>. /// </summary> public RegexValidatorAttribute(string pattern) { this.Pattern = pattern; } /// <exclude /> public string Pattern { get; private set; } /// <exclude /> protected override Microsoft.Practices.EnterpriseLibrary.Validation.Validator DoCreateValidator(Type targetType) { return new Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RegexValidator( this.Pattern, null, null, RegexOptions.None, this.MessageTemplate, Negated); } } } ================================================ FILE: Composite/Data/Validation/Validators/StringLengthValidatorAttribute.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Validation.Validators { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)] public sealed class StringLengthValidatorAttribute : ValueValidatorAttribute { /// <exclude /> public StringLengthValidatorAttribute(int lowerBound, int upperBound) { this.LowerBound = lowerBound; this.UpperBound = upperBound; } /// <exclude /> public int LowerBound { get; private set; } /// <exclude /> public int UpperBound { get; private set; } /// <exclude /> protected override Microsoft.Practices.EnterpriseLibrary.Validation.Validator DoCreateValidator(Type targetType) { int lowerBound = Math.Min(LowerBound, UpperBound); int upperBound = Math.Max(LowerBound, UpperBound); return new StringLengthValidator( lowerBound, RangeBoundaryType.Inclusive, upperBound, RangeBoundaryType.Inclusive, Negated); } } } ================================================ FILE: Composite/Data/Validation/Validators/StringSizeValidatorAttribute.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Composite.Data.Validation.Validators { /// <summary> /// Validator rule for data type properties. /// Validate that a string has a length than falls within a minimum and maximum length. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)] public sealed class StringSizeValidatorAttribute : ValueValidatorAttribute { /// <summary> /// Validator rule for data type properties. /// Validate that a string has a length than falls within a minimum and maximum length. /// </summary> /// <param name="lowerBound">minimum</param> /// <param name="upperBound">maximum</param> public StringSizeValidatorAttribute(int lowerBound, int upperBound) { this.LowerBound = lowerBound; this.UpperBound = upperBound; } /// <exclude /> public int LowerBound { get; private set; } /// <exclude /> public int UpperBound { get; private set; } /// <exclude /> protected override Microsoft.Practices.EnterpriseLibrary.Validation.Validator DoCreateValidator(Type targetType) { int lowerBound = Math.Min(LowerBound, UpperBound); int upperBound = Math.Max(LowerBound, UpperBound); return new StringLengthValidator( lowerBound, RangeBoundaryType.Inclusive, upperBound, RangeBoundaryType.Inclusive, Negated); } } } ================================================ FILE: Composite/Data/VersionKeyPropertyName.cs ================================================ using System; namespace Composite.Data { /// <exclude /> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = true, Inherited = true)] public sealed class VersionKeyPropertyNameAttribute : Attribute { /// <exclude /> public VersionKeyPropertyNameAttribute(string propertyName) { this.VersionKeyPropertyName = propertyName; } /// <exclude /> public string VersionKeyPropertyName { get; } } } ================================================ FILE: Composite/Functions/AttributeBasedRoutedDataUrlMapper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.C1Console.Elements.ElementProviderHelpers.DataGroupingProviderHelper; using Composite.Core.Routing; using Composite.Core.Types; using Composite.Data; namespace Composite.Functions { internal class AttributeBasedRoutedDataUrlMapper : IRoutedDataUrlMapper { private readonly Guid _pageId; private readonly Type _dataType; private static readonly MethodInfo _getFilteredDataMethodInfo; private static readonly MethodInfo _getFilteredDataQueryableMethodInfo; private readonly IRelativeRouteToPredicateMapper _mapper; static AttributeBasedRoutedDataUrlMapper() { _getFilteredDataMethodInfo = StaticReflection.GetGenericMethodInfo(() => GetFilteredData<IData>(null)); _getFilteredDataQueryableMethodInfo = StaticReflection.GetGenericMethodInfo(a => GetFilteredDataQueryable<IPageRelatedData>(Guid.Empty)); } protected AttributeBasedRoutedDataUrlMapper(Type dataType, Guid pageId, IRelativeRouteToPredicateMapper mapper) { _pageId = pageId; _mapper = mapper; _dataType = dataType; } public static AttributeBasedRoutedDataUrlMapper GetDataUrlMapper(Type dataType, Guid pageId) { var mapper = AttributeBasedRoutingHelper.GetPredicateMapper(dataType); if (mapper == null) { return null; } return new AttributeBasedRoutedDataUrlMapper(dataType, pageId, mapper); } public RoutedDataModel GetRouteDataModel(PageUrlData pageUrlData) { if (pageUrlData.PageId != _pageId) return null; string pathInfo = pageUrlData.PathInfo; bool pathIsEmpty = string.IsNullOrEmpty(pathInfo); int pathInfoSegmentsExpected = _mapper.PathSegmentsCount; if (pathIsEmpty && (pathInfoSegmentsExpected > 0 || !pageUrlData.HasQueryParameters)) { return new RoutedDataModel(GetDataQueryable); } if (pathIsEmpty != (pathInfoSegmentsExpected == 0)) { return null; } string[] segments = !pathIsEmpty ? pathInfo.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries) : Array.Empty<string>(); if (segments.Length != pathInfoSegmentsExpected) { return null; } var relativeRoute = new RelativeRoute { PathSegments = segments, QueryString = pageUrlData.QueryParameters }; var valueProvider = _mapper as AttributeBasedRoutingHelper.IRelativeRouteResover; if (valueProvider != null) { var data = valueProvider.TryGetData(pageUrlData.PageId, relativeRoute); return data != null ? new RoutedDataModel(data) : null; } var filterExpression = GetPredicate(_pageId, relativeRoute); if (filterExpression == null) { return null; } var dataSet = (IReadOnlyCollection<IData>) _getFilteredDataMethodInfo.MakeGenericMethod(_dataType) .Invoke(null, new object[] {filterExpression}); if (dataSet.Count == 0) { return null; } if (dataSet.Count > 1) { throw new DataUrlCollisionException(_dataType, relativeRoute); } return new RoutedDataModel(dataSet.First()); } private IQueryable GetDataQueryable() { IQueryable unorderedQuery; if (typeof (IPageRelatedData).IsAssignableFrom(_dataType)) { unorderedQuery = (IQueryable)_getFilteredDataQueryableMethodInfo.MakeGenericMethod(_dataType) .Invoke(null, new object[] {_pageId}); } else { unorderedQuery = DataFacade.GetData(_dataType); } return DataGroupingProviderHelper.OrderData(unorderedQuery, _dataType); } private static IQueryable GetFilteredDataQueryable<TDataType>(Guid pageId) where TDataType: class, IPageRelatedData { return DataFacade.GetData<TDataType>().Where(data => data.PageId == pageId); } private static IReadOnlyCollection<IData> GetFilteredData<T>(Expression<Func<T, bool>> lambdaExpression) where T : class, IData { return DataFacade.GetData<T>().Where(lambdaExpression).Take(2).ToList(); } public PageUrlData BuildItemUrl(IData item) { var page = PageManager.GetPageById(_pageId); if (page == null) { return null; } var route = GetRoute(item); if (route == null) { return null; } string pathInfo = route.PathSegments.Any() ? "/" + string.Join("/", route.PathSegments) : null; if (pathInfo == null && (route.QueryString == null || route.QueryString.Count == 0)) { return null; } return new PageUrlData(page) { PathInfo = pathInfo, QueryParameters = route.QueryString }; } private RelativeRoute GetRoute(IData data) { var @interface = typeof(IRelativeRouteToPredicateMapper<>).MakeGenericType(_dataType); return @interface.GetMethod("GetRoute").Invoke(_mapper, new object[] { data, true }) as RelativeRoute; } private Expression GetPredicate(Guid pageId, RelativeRoute relativeRoute) { var @interface = typeof (IRelativeRouteToPredicateMapper<>).MakeGenericType(_dataType); return @interface.GetMethod("GetPredicate").Invoke(_mapper, new object[] {pageId, relativeRoute}) as Expression; } } } ================================================ FILE: Composite/Functions/BaseFunctionRuntimeTreeNode.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Core.Extensions; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class BaseFunctionRuntimeTreeNode : BaseRuntimeTreeNode { /// <exclude /> protected List<BaseParameterRuntimeTreeNode> Parameters { get; set; } /// <exclude /> public void SetParameter(BaseParameterRuntimeTreeNode parameterRuntimeTreeNode) { if (parameterRuntimeTreeNode == null) throw new ArgumentNullException("parameterRuntimeTreeNode"); BaseParameterRuntimeTreeNode node = this.Parameters.Find(n => n.Name == parameterRuntimeTreeNode.Name); if (node != null) { this.Parameters.Remove(node); } this.Parameters.Add(parameterRuntimeTreeNode); } /// <exclude /> public void RemoveParameter(string parameterName) { if (string.IsNullOrEmpty(parameterName)) throw new ArgumentException("parameterName can not be null or an empty string"); BaseParameterRuntimeTreeNode toRemove = this.Parameters.Where(f => f.Name == parameterName).FirstOrDefault(); if (toRemove != null) { this.Parameters.Remove(toRemove); } } /// <summary> /// Returns information about parameters that have been set. /// </summary> public IEnumerable<BaseParameterRuntimeTreeNode> GetSetParameters() { return this.Parameters; } /// <exclude /> public override bool ContainsNestedFunctions { get { foreach (var parameter in this.Parameters) { if (parameter.GetAllSubFunctionNames().Count() > 0) { return true; } } return false; } } /// <exclude /> abstract protected IMetaFunction HostedFunction { get; } /// <summary> /// Returns the composite name of the hosted function /// </summary> /// <returns></returns> public string GetCompositeName() { return this.HostedFunction.CompositeName(); } /// <summary> /// Returns the name (without namespace) of the hosted function /// </summary> /// <returns></returns> public string GetName() { return this.HostedFunction.Name; } /// <summary> /// Returns the namespace of the hosted function /// </summary> /// <returns></returns> public string GetNamespace() { return this.HostedFunction.Namespace; } /// <summary> /// Returns the description of the hosted function /// </summary> /// <returns></returns> public string GetDescription() { return this.HostedFunction.Description; } /// <exclude /> protected void ValidateNotSelfCalling() { var function = HostedFunction; if (function is ICompoundFunction && (function as ICompoundFunction).AllowRecursiveCall) { return; } string functionName = GetCompositeName(); foreach (BaseParameterRuntimeTreeNode parameterRuntimeTreeNode in Parameters) { if (IsSelfCalling(functionName, parameterRuntimeTreeNode)) { throw new InvalidOperationException("The function '{0}' is calling itself. A function should implement '{1}' interface in order not to be affected by that limitation." .FormatWith(functionName, typeof(ICompoundFunction).FullName)); } } } private static bool IsSelfCalling(string functionName, BaseRuntimeTreeNode runtimeTreeNode) { if (runtimeTreeNode is FunctionParameterRuntimeTreeNode) { FunctionParameterRuntimeTreeNode functionParameterRuntimeTreeNode = runtimeTreeNode as FunctionParameterRuntimeTreeNode; if (functionParameterRuntimeTreeNode.GetHostedFunction().GetCompositeName() == functionName) { return true; } return IsSelfCalling(functionName, functionParameterRuntimeTreeNode.GetHostedFunction()); } if (runtimeTreeNode is BaseFunctionRuntimeTreeNode) { BaseFunctionRuntimeTreeNode functionRuntimeTreeNode = runtimeTreeNode as BaseFunctionRuntimeTreeNode; if (functionName == functionRuntimeTreeNode.GetCompositeName()) { return true; } foreach (BaseParameterRuntimeTreeNode parameterRuntimeTreeNode in functionRuntimeTreeNode.Parameters) { if (IsSelfCalling(functionName, parameterRuntimeTreeNode)) { return true; } } return false; } return false; } } } ================================================ FILE: Composite/Functions/BaseParameterRuntimeTreeNode.cs ================================================ using System; using System.Collections.Generic; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class BaseParameterRuntimeTreeNode : BaseRuntimeTreeNode { /// <exclude /> protected BaseParameterRuntimeTreeNode(string name) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name"); this.Name = name; } /// <exclude /> public string Name { get; private set; } } } ================================================ FILE: Composite/Functions/BaseRuntimeTreeNode.cs ================================================ using System; using System.Xml.Linq; using System.Collections.Generic; using Composite.Core.Types; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class BaseRuntimeTreeNode { internal BaseRuntimeTreeNode() { } /// <exclude /> public object GetValue() { FunctionContextContainer internalContextContainer = new FunctionContextContainer(); return GetValue(internalContextContainer); } /// <exclude /> public abstract object GetValue(FunctionContextContainer contextContainer); /// <exclude /> public T GetValue<T>() { FunctionContextContainer internalContextContainer = new FunctionContextContainer(); return GetValue<T>(internalContextContainer); } /// <exclude /> public virtual object GetValue(FunctionContextContainer contextContainer, Type type) { Verify.ArgumentNotNull(contextContainer, "contextContainer"); object value = this.GetValue(contextContainer); if (value == null || type.IsInstanceOfType(value)) { return value; } return ValueTypeConverter.Convert(value, type); } /// <exclude /> public T GetValue<T>(FunctionContextContainer contextContainer) { return (T) GetValue(contextContainer, typeof(T)); } /// <exclude /> public object GetCachedValue() { FunctionContextContainer internalContextContainer = new FunctionContextContainer(); return GetValue(internalContextContainer); } /// <exclude /> public abstract IEnumerable<string> GetAllSubFunctionNames(); /// <exclude /> public abstract bool ContainsNestedFunctions { get; } /// <exclude /> public abstract XElement Serialize(); } } ================================================ FILE: Composite/Functions/BaseRuntimeTreeNodeValueXmlSerializer.cs ================================================ using System; using System.Linq; using System.Xml.Linq; using Composite.Core.Serialization; namespace Composite.Functions { internal sealed class BaseRuntimeTreeNodeValueXmlSerializer : IValueXmlSerializer { public bool TrySerialize(Type objectToSerializeType, object objectToSerialize, IXmlSerializer xmlSerializer, out XElement serializedObject) { if (objectToSerializeType == null) throw new ArgumentNullException("objectToSerializeType"); serializedObject = null; if (typeof(BaseRuntimeTreeNode).IsAssignableFrom(objectToSerializeType)) { serializedObject = new XElement("BaseRuntimeTreeNode"); if (objectToSerialize != null) { BaseRuntimeTreeNode baseRuntimeTreeNode = objectToSerialize as BaseRuntimeTreeNode; serializedObject.Add(new XElement("Value", baseRuntimeTreeNode.Serialize())); } return true; } else { return false; } } public bool TryDeserialize(XElement serializedObject, IXmlSerializer xmlSerializer, out object deserializedObject) { if (serializedObject == null) throw new ArgumentNullException("serializedObject"); deserializedObject = null; if (serializedObject.Name.LocalName != "BaseRuntimeTreeNode") return false; XElement valueElement = serializedObject.Element("Value"); if (valueElement != null) { if (valueElement.Elements().Count() != 1) return false; deserializedObject = FunctionFacade.BuildTree(valueElement.Elements().Single()); } return true; } } } ================================================ FILE: Composite/Functions/BaseValueProvider.cs ================================================ using System.Xml.Linq; using Composite.Core.Types; namespace Composite.Functions { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class BaseValueProvider { /// <exclude /> public BaseValueProvider() { } /// <exclude /> public object GetValue() { var internalContextContainer = new FunctionContextContainer(); return GetValue(internalContextContainer); } /// <exclude /> public abstract object GetValue(FunctionContextContainer contextContainer); /// <exclude /> public virtual T GetValue<T>(FunctionContextContainer contextContainer) { object value = this.GetValue(contextContainer); if (value == null || value is T) { return (T)value; } else { return ValueTypeConverter.Convert<T>(value); } } /// <exclude /> public abstract XObject Serialize(); } } ================================================ FILE: Composite/Functions/ConstantObjectParameterRuntimeTreeNode.cs ================================================ using System.Collections; using System.Collections.Generic; using System.Xml.Linq; using Composite.Core.Xml; using Composite.Functions.Foundation; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ConstantObjectParameterRuntimeTreeNode : BaseParameterRuntimeTreeNode { private readonly object _constantValue; /// <exclude /> public ConstantObjectParameterRuntimeTreeNode(string name, object constantValue) : base(name) { _constantValue = constantValue; } /// <exclude /> public override object GetValue(FunctionContextContainer contextContainer) { return _constantValue; } /// <exclude /> public override IEnumerable<string> GetAllSubFunctionNames() { return new string[0]; } /// <exclude /> public override bool ContainsNestedFunctions { get { return false; } } /// <exclude /> public override XElement Serialize() { var element = new XElement(FunctionTreeConfigurationNames.ParamTag, new XAttribute(FunctionTreeConfigurationNames.NameAttribute, this.Name)); if (_constantValue is IEnumerable && !(_constantValue is string)) { foreach (object obj in (IEnumerable)_constantValue) { element.Add(new XElement(FunctionTreeConfigurationNames.ParamElementTag, new XAttribute(FunctionTreeConfigurationNames.ValueAttribute, XmlSerializationHelper.GetSerializableObject(obj)))); } return element; } object xValue; if (_constantValue is XNode) { if (_constantValue is XDocument) { xValue = ((XDocument) _constantValue).Root; } else { xValue = _constantValue; } } else { xValue = new XAttribute(FunctionTreeConfigurationNames.ValueAttributeName, XmlSerializationHelper.GetSerializableObject(_constantValue) ?? string.Empty); } element.Add(xValue); return element; } } } ================================================ FILE: Composite/Functions/ConstantParameterRuntimeTreeNode.cs ================================================ using System; using System.Collections.Generic; using System.Xml.Linq; using Composite.Core.Types; using Composite.Core.Xml; using Composite.Functions.Foundation; namespace Composite.Functions { internal sealed class ConstantParameterRuntimeTreeNode : BaseParameterRuntimeTreeNode { private readonly object _constantValue; private readonly bool _isEnumerable; private readonly XAttribute _attribute; public ConstantParameterRuntimeTreeNode(string name, string constantValue) : base(name) { _constantValue = constantValue; } public ConstantParameterRuntimeTreeNode(string name, XAttribute valueAttribute) : base(name) { _attribute = valueAttribute; } public ConstantParameterRuntimeTreeNode(string name, IEnumerable<string> constantValue) : base(name) { _constantValue = constantValue; _isEnumerable = true; } public override object GetValue(FunctionContextContainer contextContainer) { Verify.ArgumentNotNull(contextContainer, "contextContainer"); return _attribute != null ? _attribute.Value : _constantValue; } public override object GetValue(FunctionContextContainer contextContainer, Type type) { Verify.ArgumentNotNull(contextContainer, "contextContainer"); Verify.ArgumentNotNull(type, "type"); if (_attribute != null) { return XmlSerializationHelper.Deserialize(_attribute, type); } return ValueTypeConverter.Convert(_constantValue, type); } public override IEnumerable<string> GetAllSubFunctionNames() { yield break; } public override bool ContainsNestedFunctions { get { return false; } } public override XElement Serialize() { var element = new XElement(FunctionTreeConfigurationNames.ParamTag, new XAttribute(FunctionTreeConfigurationNames.NameAttribute, this.Name)); if (_isEnumerable) { var strings = (IEnumerable<string>) _constantValue; foreach (string s in strings) { element.Add(new XElement(FunctionTreeConfigurationNames.ParamElementTag, new XAttribute(FunctionTreeConfigurationNames.ValueAttribute, s))); } return element; } if (_attribute != null) { element.Add(new XAttribute(FunctionTreeConfigurationNames.ValueAttribute, _attribute.Value)); } if (_constantValue != null) { element.Add(new XAttribute(FunctionTreeConfigurationNames.ValueAttribute, _constantValue)); } return element; } } } ================================================ FILE: Composite/Functions/ConstantValueProvider.cs ================================================ using System.Xml.Linq; using Composite.Functions.Foundation; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ConstantValueProvider : BaseValueProvider { private object _value; /// <exclude /> public ConstantValueProvider(object value) { _value = value; } /// <exclude /> public override object GetValue(FunctionContextContainer contextContainer) { return _value; } /// <exclude /> public override XObject Serialize() { if (_value != null) { return new XAttribute(FunctionTreeConfigurationNames.ValueAttributeName, _value); } else { return null; } } } } ================================================ FILE: Composite/Functions/DynamicMethodHelper.cs ================================================ using System; using System.Reflection; using System.Reflection.Emit; namespace Composite.Functions { internal class DynamicMethodHelper { public delegate object FunctionCall(Func<object> body); private static readonly MethodInfo FuncObject_InvokeMethodInfo = typeof(Func<object>).GetMethod("Invoke"); /// <summary> /// Creates a dynamic method with the specified name. To be used for adding information into StackTrace. /// </summary> public static FunctionCall GetDynamicMethod(string methodName) { var wrapper = new DynamicMethod( methodName, typeof(object), new[] { typeof(Func<object>) }, typeof(FunctionFacade).Module); var wrapperBody = wrapper.GetILGenerator(); wrapperBody.Emit(OpCodes.Ldarg_0); wrapperBody.EmitCall(OpCodes.Callvirt, FuncObject_InvokeMethodInfo, null); wrapperBody.Emit(OpCodes.Ret); return (FunctionCall)wrapper.CreateDelegate(typeof(FunctionCall)); } } } ================================================ FILE: Composite/Functions/Forms/FunctionParameterElementProducer.cs ================================================ using Composite.C1Console.Forms; namespace Composite.Functions.Forms { [ControlValueProperty("Producers")] internal class FunctionParameterElementProducer : IFunctionProducer { [RequiredValue] public string value { get; set; } public object GetResult() { return new ConstantParameterRuntimeTreeNode("_HHH_", this.value); } } } ================================================ FILE: Composite/Functions/Forms/FunctionParameterProducer.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Forms; namespace Composite.Functions.Forms { [ControlValueProperty("Producers")] internal sealed class FunctionParameterProducer : IFunctionProducer { public FunctionParameterProducer() { this.Producers = new List<BaseRuntimeTreeNode>(); } [RequiredValue] public string name { get; set; } public object value { get; set; } [FormsProperty] public List<BaseRuntimeTreeNode> Producers { get; private set; } public object GetResult() { if (this.value != null) { if (this.value is FunctionRuntimeTreeNode) { return new FunctionParameterRuntimeTreeNode(this.name, this.value as FunctionRuntimeTreeNode); } if (this.value is string) { return new ConstantParameterRuntimeTreeNode(this.name, this.value as string); } throw new NotImplementedException(); } if (Producers.Count == 1) { var functionNode = Producers[0] as FunctionRuntimeTreeNode; if (functionNode != null) { return new FunctionParameterRuntimeTreeNode(this.name, functionNode); } var constantObjectNode = Producers[0] as ConstantObjectParameterRuntimeTreeNode; if (constantObjectNode != null) { return new ConstantObjectParameterRuntimeTreeNode(this.name, constantObjectNode.GetValue()); } } if (Producers.All(p => p is ConstantParameterRuntimeTreeNode)) { IEnumerable<string> values = Producers.OfType<ConstantParameterRuntimeTreeNode>().Select(f => (string)f.GetValue()); return new ConstantParameterRuntimeTreeNode(this.name, values); } throw new NotImplementedException(); } } } ================================================ FILE: Composite/Functions/Forms/FunctionProducer.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Forms; namespace Composite.Functions.Forms { [ControlValueProperty("Producers")] internal sealed class FunctionProducer : IFunctionProducer { public FunctionProducer() { this.Producers = new List<BaseParameterRuntimeTreeNode>(); } [RequiredValue] public string name { get; set; } [FormsProperty()] public List<BaseParameterRuntimeTreeNode> Producers { get; private set; } public object GetResult() { IFunction function = FunctionFacade.GetFunction(this.name); FunctionRuntimeTreeNode functionNode = new FunctionRuntimeTreeNode(function, this.Producers); return functionNode; } } } ================================================ FILE: Composite/Functions/Forms/FunctionProducerMediator.cs ================================================ using System; using Composite.C1Console.Forms; using Composite.C1Console.Forms.Plugins.ProducerMediator; using Composite.Core.Extensions; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Functions.Forms { [ConfigurationElementType(typeof(NonConfigurableProducerMediator))] internal sealed class FunctionProducerMediator : IProducerMediator { public object CreateProducer(IFormChannelIdentifier channel, string namespaceName, string name) { switch (name) { case "function": return new FunctionProducer(); case "param": return new FunctionParameterProducer(); case "paramelement": return new FunctionParameterElementProducer(); default: throw new NotSupportedException("Not supported producer tag. Check whether the namespace or the tag name is correct. {{ {0} }} {1}".FormatWith(namespaceName, name)); } } public object EvaluateProducer(object producer) { IFunctionProducer functionProducer = (IFunctionProducer)producer; return functionProducer.GetResult(); } } } ================================================ FILE: Composite/Functions/Forms/IFunctionProducer.cs ================================================  namespace Composite.Functions.Forms { internal interface IFunctionProducer { object GetResult(); } } ================================================ FILE: Composite/Functions/Foundation/FunctionContainer.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Composite.Core; using Composite.Core.Configuration; using Composite.Functions.Foundation.PluginFacades; using Composite.Functions.Plugins.FunctionProvider.Runtime; namespace Composite.Functions.Foundation { internal sealed class FunctionContainer : MetaFunctionContainer { internal FunctionContainer(List<string> excludedFunctionNames) : base(excludedFunctionNames) { } protected override IEnumerable<string> OnGetProviderNames() { if ((ConfigurationServices.ConfigurationSource == null) || (ConfigurationServices.ConfigurationSource.GetSection(FunctionProviderSettings.SectionName) == null)) { Log.LogError("FunctionProviderRegistry", "Failed to load the configuration section '{0}' from the configuration", FunctionProviderSettings.SectionName); return new List<string>(); } var functionProviderSettings = ConfigurationServices.ConfigurationSource.GetSection(FunctionProviderSettings.SectionName) as FunctionProviderSettings; return functionProviderSettings.FunctionProviderPlugins.Select(plugin => plugin.Name); } protected override IEnumerable<IMetaFunction> OnGetFunctionsFromProvider(string providerName, FunctionTypesToReturn functionTypesToReturn) { switch (functionTypesToReturn) { case FunctionTypesToReturn.StaticDependentFunctions: return FunctionProviderPluginFacade.Functions(providerName); case FunctionTypesToReturn.DynamicDependentOnlyFunctions: return FunctionProviderPluginFacade.DynamicTypeDependentFunctions(providerName); case FunctionTypesToReturn.AllFunctions: IEnumerable<IMetaFunction> functions = FunctionProviderPluginFacade.Functions(providerName); return functions.Concat(FunctionProviderPluginFacade.DynamicTypeDependentFunctions(providerName)); } throw new NotImplementedException(string.Format("Unexpected FunctionTypesToReturn enumeration value '{0}' from provider '{1}'", functionTypesToReturn, providerName)); } protected override void OnFunctionsAdded(List<string> functionNames, bool fireEvents) { if (fireEvents) { FunctionEventSystemFacade.FireFunctionAddedEvent(new FunctionsAddedEventArgs(functionNames)); } } protected override void OnFunctionsRemoved(List<string> functionNames) { FunctionEventSystemFacade.FireFunctionRemovedEvent(new FunctionsRemovedEventArgs(functionNames)); } protected override string FunctionType { get { return "Function"; } } } } ================================================ FILE: Composite/Functions/Foundation/FunctionTreeConfigurationNames.cs ================================================ using System.ComponentModel; using System.Xml.Linq; namespace Composite.Functions.Foundation { /// <summary> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] public static class FunctionTreeConfigurationNames { private static readonly XName _paramTag = (XNamespace) NamespaceName + ParamTagName; private static readonly XName _paramElementTag = (XNamespace) NamespaceName + ParamElementTagName; private static readonly XName _valueAttribute = ValueAttributeName; private static readonly XName _nameAttribute = NameAttributeName; /// <exclude /> public static XName ParamTag { get { return _paramTag; } } /// <exclude /> public static XName ParamElementTag { get { return _paramElementTag; } } /// <exclude /> public static XName NameAttribute { get { return _nameAttribute; } } /// <exclude /> public static XName ValueAttribute { get { return _valueAttribute; } } /// <exclude /> public static string NamespaceName { get { return "http://www.composite.net/ns/function/1.0"; } } /// <exclude /> public static string ParamTagName { get { return "param"; } } /// <exclude /> public static string ParamElementTagName { get { return "paramelement"; } } /// <exclude /> public static string FunctionTagName { get { return "function"; } } /// <exclude /> public static string WidgetFunctionTagName { get { return "widgetfunction"; } } /// <exclude /> public static string HelpDefinitionTagName { get { return "helpdefinition"; } } /// <exclude /> public static string NameAttributeName { get { return "name"; } } /// <exclude /> public static string ValueAttributeName { get { return "value"; } } /// <exclude /> public static string LabelAttributeName { get { return "label"; } } /// <exclude /> public static string BindingSourceNameAttributeName { get { return "bindingsourcename"; } } /// <exclude /> public static string HelpTextAttributeName { get { return "helptext"; } } } } ================================================ FILE: Composite/Functions/Foundation/IMetaFunctionProviderRegistry.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Composite.Functions.Foundation { internal interface IMetaFunctionProviderRegistry { List<string> FunctionNames { get; } List<string> WidgetFunctionNames { get; } IEnumerable<string> FunctionNamesByProviderName(string providerName); IEnumerable<string> WidgetFunctionNamesByProviderName(string providerName); IEnumerable<string> GetFunctionNamesByType(Type supportedType); IEnumerable<string> GetWidgetFunctionNamesByType(Type supportedType); IFunction GetFunction(string name); IWidgetFunction GetWidgetFunction(string name); IEnumerable<Type> FunctionSupportedTypes { get; } IEnumerable<Type> WidgetFunctionSupportedTypes { get; } void ReinitializeFunctionFromProvider(string providerName); void ReinitializeWidgetFunctionFromProvider(string providerName); void Initialize_PostDataTypes(); void Flush(); } } ================================================ FILE: Composite/Functions/Foundation/MetaFunctionContainer.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Core.Extensions; using System.Collections; using Composite.Core; namespace Composite.Functions.Foundation { internal abstract class MetaFunctionContainer { private static readonly string LogTitle = typeof (MetaFunctionContainer).Name; private readonly List<string> _excludedFunctionNames; private readonly Dictionary<string, IMetaFunction> _functionByNameDictionary = new Dictionary<string, IMetaFunction>(); private readonly Dictionary<Type, List<string>> _functionNamesByTypeDictionary = new Dictionary<Type, List<string>>(); private readonly Dictionary<Type, List<string>> _downcastableFunctionNamesByTypeDictionary = new Dictionary<Type, List<string>>(); private readonly Dictionary<string, List<string>> _functionNamesByProviderName = new Dictionary<string, List<string>>(); protected abstract IEnumerable<string> OnGetProviderNames(); protected abstract IEnumerable<IMetaFunction> OnGetFunctionsFromProvider(string providerName, FunctionTypesToReturn functionTypesToReturn); protected abstract void OnFunctionsAdded(List<string> functionNames, bool fireEvents); protected abstract void OnFunctionsRemoved(List<string> functionNames); protected abstract string FunctionType { get; } protected MetaFunctionContainer(List<string> excludedFunctionNames) { _excludedFunctionNames = excludedFunctionNames; } public void Initialize(bool dynamicTypes) { if (dynamicTypes) { InitializeAllFunctions(FunctionTypesToReturn.DynamicDependentOnlyFunctions, false); } else { InitializeAllFunctions(FunctionTypesToReturn.StaticDependentFunctions, false); } } public IEnumerable<string> FunctionNames { get { return _functionByNameDictionary.Keys; } } public IEnumerable<string> FunctionNamesByProviderName(string providerName) { List<string> functionNames; if (_functionNamesByProviderName.TryGetValue(providerName, out functionNames) == false) { functionNames = new List<string>(); } return functionNames; } public IEnumerable<string> GetFunctionNamesByType(Type supportedType) { List<string> functionNames = new List<string>(); foreach (var typeMappedFunctions in _functionNamesByTypeDictionary) { bool useableType = supportedType.IsAssignableFrom(typeMappedFunctions.Key); if (useableType) { // Negate that string is an IEnumerable - thats just plain stupid. if ((supportedType is IEnumerable && typeMappedFunctions.Key == typeof(string)) == false) { functionNames.AddRange(typeMappedFunctions.Value); } } } foreach (var typeMappedFunctions in _downcastableFunctionNamesByTypeDictionary) { bool useableType = typeMappedFunctions.Key.IsAssignableFrom(supportedType); if (useableType) { functionNames.AddRange(typeMappedFunctions.Value.Where(f => functionNames.Contains(f)==false)); } } return functionNames; } public IEnumerable<Type> FunctionSupportedTypes { get { return _functionNamesByTypeDictionary.Keys; } } public IMetaFunction GetFunction(string functionName) { IMetaFunction function; if (_functionByNameDictionary.TryGetValue(functionName, out function) == false) { throw new ArgumentException(string.Format("The {0} named '{1}' is not known. Ensure it exists with the exact spelling and casing you provided.", this.FunctionType, functionName)); } return function; } public void ReInitializeFunctionsFromProvider(string providerName) { RemoveFunctionsByProvider(providerName); InitializeFunctionsFromProvider(providerName, FunctionTypesToReturn.AllFunctions, true); } private void InitializeAllFunctions(FunctionTypesToReturn functionTypesToReturn, bool fireUpdateEvents) { foreach (string providerName in OnGetProviderNames()) { InitializeFunctionsFromProvider(providerName, functionTypesToReturn, fireUpdateEvents); } } private void InitializeFunctionsFromProvider(string providerName, FunctionTypesToReturn functionTypesToReturn,bool fireEvents) { List<string> loadedFunctionNames = new List<string>(); foreach (IMetaFunction function in OnGetFunctionsFromProvider(providerName, functionTypesToReturn).OrderBy(f => f.CompositeName())) { if (function.IsNamespaceCorrectFormat() == false) { Log.LogWarning(LogTitle, string.Format("{0} named '{1}' has an invalid namespace '{2}'", this.FunctionType, function.Name, function.Namespace)); continue; } string combinedName = StringExtensionMethods.CreateNamespace(function.Namespace, function.Name, '.'); if (_excludedFunctionNames.Contains(combinedName)) { continue; } if (FunctionExists(combinedName)) { RemoveFunction(combinedName); _excludedFunctionNames.Add(combinedName); Log.LogWarning(LogTitle, "Function name clash: '{0}'", combinedName); continue; } try { AddFunction(providerName, function); loadedFunctionNames.Add(function.CompositeName()); } catch (Exception ex) { Log.LogError(LogTitle, "Error adding function '{0}'. Function type {0}", combinedName, this.FunctionType); Log.LogError(LogTitle, ex); } } if (_functionNamesByProviderName.ContainsKey(providerName)) { //foreach (string functionName in _functionNamesByProviderName[providerName]) //{ // if (loadedFunctionNames.Contains(functionName)) // { // Log.LogVerbose("FunctionProviderRegistry", string.Format("{0} loaded: '{1}' from provider '{2}'", this.FunctionType, functionName, providerName)); // } //} OnFunctionsAdded(_functionNamesByProviderName[providerName].ToList(), fireEvents); } } private void AddFunction(string providerName, IMetaFunction function) { string compositeName = function.CompositeName(); _functionByNameDictionary.Add(compositeName, function); List<string> functionNamesByProviderNameList; if (_functionNamesByProviderName.TryGetValue(providerName, out functionNamesByProviderNameList) == false) { functionNamesByProviderNameList = new List<string>(); _functionNamesByProviderName.Add(providerName, functionNamesByProviderNameList); } functionNamesByProviderNameList.Add(compositeName); List<string> functionNamesByType; if (_functionNamesByTypeDictionary.TryGetValue(function.ReturnType, out functionNamesByType) == false) { functionNamesByType = new List<string>(); _functionNamesByTypeDictionary.Add(function.ReturnType, functionNamesByType); } functionNamesByType.Add(compositeName); if (function is IDowncastableFunction && ((IDowncastableFunction)function).ReturnValueIsDowncastable) { List<string> downcastableFunctionNamesByType; if (_downcastableFunctionNamesByTypeDictionary.TryGetValue(function.ReturnType, out downcastableFunctionNamesByType) == false) { downcastableFunctionNamesByType = new List<string>(); _downcastableFunctionNamesByTypeDictionary.Add(function.ReturnType, downcastableFunctionNamesByType); } downcastableFunctionNamesByType.Add(compositeName); } } private void RemoveFunctionsByProvider(string providerName) { if (_functionNamesByProviderName.ContainsKey(providerName) == false) return; List<string> functionNames = _functionNamesByProviderName[providerName]; foreach (string functionName in functionNames) { _functionByNameDictionary.Remove(functionName); foreach (List<string> functionNamesByType in _functionNamesByTypeDictionary.Values) { functionNamesByType.Remove(functionName); } foreach (List<string> functionNamesByType in _downcastableFunctionNamesByTypeDictionary.Values) { functionNamesByType.Remove(functionName); } Log.LogVerbose(LogTitle, "{0} unloaded: '{1}'", this.FunctionType, functionName); } _functionNamesByProviderName.Remove(providerName); OnFunctionsRemoved(functionNames); } private void RemoveFunction(string functionName) { _functionByNameDictionary.Remove(functionName); foreach (List<string> functionNamesByProvder in _functionNamesByProviderName.Values) { functionNamesByProvder.Remove(functionName); } foreach (List<string> functionNamesByType in _functionNamesByTypeDictionary.Values) { functionNamesByType.Remove(functionName); } foreach (List<string> functionNamesByType in _downcastableFunctionNamesByTypeDictionary.Values) { functionNamesByType.Remove(functionName); } } private bool FunctionExists(string functionName) { return _functionByNameDictionary.ContainsKey(functionName); } protected enum FunctionTypesToReturn { /// <summary> /// Only functions that DOES NOT relay on dynamic types may be returned /// IFunctionProvider.Functions /// </summary> StaticDependentFunctions, /// <summary> /// Only functions that DOES relay on dynamic types may be return /// IDynamicTypeFunctionProvider.DynamicTypeDependentFunctions /// </summary> DynamicDependentOnlyFunctions, /// <summary> /// All functions may be returned /// IFunctionProvider.Functions /// AND /// IDynamicTypeFunctionProvider.DynamicTypeDependentFunctions /// </summary> AllFunctions } } } ================================================ FILE: Composite/Functions/Foundation/MetaFunctionProviderRegistry.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using Composite.C1Console.Events; namespace Composite.Functions.Foundation { internal static class MetaFunctionProviderRegistry { private static IMetaFunctionProviderRegistry _metaFunctionProviderRegistry = new MetaFunctionProviderRegistryImpl(); static MetaFunctionProviderRegistry() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } internal static IMetaFunctionProviderRegistry Implementation { get { return _metaFunctionProviderRegistry; } set { _metaFunctionProviderRegistry = value; } } public static List<string> FunctionNames { get { return _metaFunctionProviderRegistry.FunctionNames; } } public static List<string> WidgetFunctionNames { get { return _metaFunctionProviderRegistry.WidgetFunctionNames; } } public static IEnumerable<string> FunctionNamesByProviderName(string providerName) { return _metaFunctionProviderRegistry.FunctionNamesByProviderName(providerName); } public static IEnumerable<string> WidgetFunctionNamesByProviderName(string providerName) { return _metaFunctionProviderRegistry.WidgetFunctionNamesByProviderName(providerName); } public static IEnumerable<string> GetFunctionNamesByType(Type supportedType) { return _metaFunctionProviderRegistry.GetFunctionNamesByType(supportedType); } public static IEnumerable<string> GetWidgetFunctionNamesByType(Type supportedType) { return _metaFunctionProviderRegistry.GetWidgetFunctionNamesByType(supportedType); } public static IFunction GetFunction(string name) { return _metaFunctionProviderRegistry.GetFunction(name); } public static IWidgetFunction GetWidgetFunction(string name) { return _metaFunctionProviderRegistry.GetWidgetFunction(name); } public static IEnumerable<Type> FunctionSupportedTypes { get { return _metaFunctionProviderRegistry.FunctionSupportedTypes; } } public static IEnumerable<Type> WidgetFunctionSupportedTypes { get { return _metaFunctionProviderRegistry.WidgetFunctionSupportedTypes; } } internal static void ReinitializeFunctionFromProvider(string providerName) { _metaFunctionProviderRegistry.ReinitializeFunctionFromProvider(providerName); } internal static void ReinitializeWidgetFunctionFromProvider(string providerName) { _metaFunctionProviderRegistry.ReinitializeWidgetFunctionFromProvider(providerName); } internal static void Initialize_PostDataTypes() { if (RuntimeInformation.IsDebugBuild) { GlobalInitializerFacade.ValidateIsOnlyCalledFromGlobalInitializerFacade(new StackTrace()); } _metaFunctionProviderRegistry.Initialize_PostDataTypes(); } private static void OnFlushEvent(FlushEventArgs args) { _metaFunctionProviderRegistry.Flush(); } } } ================================================ FILE: Composite/Functions/Foundation/MetaFunctionProviderRegistryImpl.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Core.Collections.Generic; using Composite.Core.Logging; namespace Composite.Functions.Foundation { internal sealed class MetaFunctionProviderRegistryImpl : IMetaFunctionProviderRegistry { private ResourceLocker<Resources> _resourceLocker = new ResourceLocker<Resources>(new Resources(), Resources.DoInitialize); public List<string> FunctionNames { get { using (GlobalInitializerFacade.CoreIsInitializedScope) { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.FunctionContainer.FunctionNames.ToList(); } } } } public List<string> WidgetFunctionNames { get { using (GlobalInitializerFacade.CoreIsInitializedScope) { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.WidgetFunctionContainer.FunctionNames.ToList(); } } } } public IEnumerable<string> FunctionNamesByProviderName(string providerName) { if (string.IsNullOrEmpty(providerName)) throw new ArgumentNullException("providerName"); using (GlobalInitializerFacade.CoreIsInitializedScope) { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.FunctionContainer.FunctionNamesByProviderName(providerName); } } } public IEnumerable<string> WidgetFunctionNamesByProviderName(string providerName) { if (string.IsNullOrEmpty(providerName)) throw new ArgumentNullException("providerName"); using (GlobalInitializerFacade.CoreIsInitializedScope) { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.WidgetFunctionContainer.FunctionNamesByProviderName(providerName); } } } public IEnumerable<string> GetFunctionNamesByType(Type supportedType) { if (supportedType == null) throw new ArgumentNullException("supportedType"); using (GlobalInitializerFacade.CoreIsInitializedScope) { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.FunctionContainer.GetFunctionNamesByType(supportedType); } } } public IEnumerable<string> GetWidgetFunctionNamesByType(Type supportedType) { if (supportedType == null) throw new ArgumentNullException("supportedType"); using (GlobalInitializerFacade.CoreIsInitializedScope) { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.WidgetFunctionContainer.GetFunctionNamesByType(supportedType); } } } public IFunction GetFunction(string name) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name"); using (GlobalInitializerFacade.CoreIsInitializedScope) { using (_resourceLocker.ReadLocker) { return (IFunction)_resourceLocker.Resources.FunctionContainer.GetFunction(name); } } } public IWidgetFunction GetWidgetFunction(string name) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name"); using (GlobalInitializerFacade.CoreIsInitializedScope) { using (_resourceLocker.ReadLocker) { return (IWidgetFunction)_resourceLocker.Resources.WidgetFunctionContainer.GetFunction(name); } } } public IEnumerable<Type> FunctionSupportedTypes { get { using (GlobalInitializerFacade.CoreIsInitializedScope) { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.FunctionContainer.FunctionSupportedTypes; } } } } public IEnumerable<Type> WidgetFunctionSupportedTypes { get { using (GlobalInitializerFacade.CoreIsInitializedScope) { using (_resourceLocker.ReadLocker) { return _resourceLocker.Resources.WidgetFunctionContainer.FunctionSupportedTypes; } } } } public void ReinitializeFunctionFromProvider(string providerName) { if (string.IsNullOrEmpty(providerName)) throw new ArgumentNullException("providerName"); using (GlobalInitializerFacade.CoreIsInitializedScope) { using (_resourceLocker.Locker) { _resourceLocker.Resources.FunctionContainer.ReInitializeFunctionsFromProvider(providerName); } } } public void ReinitializeWidgetFunctionFromProvider(string providerName) { if (string.IsNullOrEmpty(providerName)) throw new ArgumentNullException("providerName"); using (GlobalInitializerFacade.CoreIsInitializedScope) { using (_resourceLocker.Locker) { _resourceLocker.Resources.WidgetFunctionContainer.ReInitializeFunctionsFromProvider(providerName); } } } public void Initialize_PostDataTypes() { _resourceLocker.ResetInitialization(); using (_resourceLocker.Locker) { // Keeping static/dynamic function initialization order for backward compatibility _resourceLocker.Resources.FunctionContainer.Initialize(false); _resourceLocker.Resources.WidgetFunctionContainer.Initialize(false); _resourceLocker.Resources.FunctionContainer.Initialize(true); _resourceLocker.Resources.WidgetFunctionContainer.Initialize(true); } } public void Flush() { _resourceLocker.ResetInitialization(); } private sealed class Resources { public static void DoInitialize(Resources resources) { resources.ExcludedFunctionNames = new List<string>(); resources.FunctionContainer = new FunctionContainer(resources.ExcludedFunctionNames); resources.WidgetFunctionContainer = new WidgetFunctionContainer(resources.ExcludedFunctionNames); } public FunctionContainer FunctionContainer { get; set; } public WidgetFunctionContainer WidgetFunctionContainer { get; set; } public List<string> ExcludedFunctionNames { get; set; } } } } ================================================ FILE: Composite/Functions/Foundation/PluginFacades/FunctionProviderPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.C1Console.Events; using Composite.Functions.Plugins.FunctionProvider; using Composite.Functions.Plugins.FunctionProvider.Runtime; namespace Composite.Functions.Foundation.PluginFacades { internal static class FunctionProviderPluginFacade { private static ResourceLocker<Resources> _resourceLocker = new ResourceLocker<Resources>(new Resources(), Resources.Initialize); static FunctionProviderPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static IEnumerable<IFunction> Functions(string providerName) { using (_resourceLocker.Locker) { List<IFunction> functions = new List<IFunction>(); IFunctionProvider provider = GetFunctionProvider(providerName); var functionsFromProvider = provider.Functions; Verify.IsNotNull(functionsFromProvider, "Provider '{0}' has returned null function colleciton", providerName); foreach (IFunction function in functionsFromProvider) { functions.Add(new FunctionWrapper(function)); } return functions; } } public static IEnumerable<IFunction> DynamicTypeDependentFunctions(string providerName) { using (_resourceLocker.Locker) { List<IFunction> functions = new List<IFunction>(); IDynamicTypeFunctionProvider provider = GetFunctionProvider(providerName) as IDynamicTypeFunctionProvider; if (provider != null) { foreach (IFunction function in provider.DynamicTypeDependentFunctions) { functions.Add(new FunctionWrapper(function)); } } return functions; } } internal static IFunctionProvider GetFunctionProvider(string providerName) { IFunctionProvider functionProvider; var resources = _resourceLocker; using (resources.Locker) { if (resources.Resources.ProviderCache.TryGetValue(providerName, out functionProvider) == false) { try { functionProvider = resources.Resources.Factory.Create(providerName); functionProvider.FunctionNotifier = new FunctionNotifier(providerName); resources.Resources.ProviderCache.Add(providerName, functionProvider); } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } } return functionProvider; } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", FunctionProviderSettings.SectionName), ex); } private sealed class Resources { public FunctionProviderFactory Factory { get; set; } public Dictionary<string, IFunctionProvider> ProviderCache { get; set; } public static void Initialize(Resources resources) { try { resources.Factory = new FunctionProviderFactory(); } catch (NullReferenceException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } resources.ProviderCache = new Dictionary<string, IFunctionProvider>(); } } } } ================================================ FILE: Composite/Functions/Foundation/PluginFacades/FunctionWrapper.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Web; using System.Xml.Linq; using Composite.Core.Xml; using Composite.C1Console.Security; namespace Composite.Functions.Foundation.PluginFacades { /// <summary> /// This class is used for catching exceptions from plugins and handling them correctly /// </summary> [DebuggerDisplay("Name = {Name}, Namespace = {Namespace}")] internal sealed class FunctionWrapper : IDowncastableFunction, ICompoundFunction, IFunctionInitializationInfo, IDynamicFunction { private static readonly string LogTitle = typeof (FunctionWrapper).Name; private readonly IFunction _functionToWrap; internal FunctionWrapper(IFunction functionToWrap) { _functionToWrap = functionToWrap; } public IFunction InnerFunction { get { return _functionToWrap; } } public string Name { get { return _functionToWrap.Name; } } public string Namespace { get { return _functionToWrap.Namespace; } } public string Description { get { return _functionToWrap.Description; } } public Type ReturnType { get { return _functionToWrap.ReturnType; } } public IEnumerable<ParameterProfile> ParameterProfiles { get { if (_functionToWrap.ParameterProfiles == null) { return new ParameterProfile[0]; } return _functionToWrap.ParameterProfiles; } } public object Execute(ParameterList parameters, FunctionContextContainer context) { try { var dynamicMethod = DynamicMethodHelper.GetDynamicMethod("<C1 function> " + _functionToWrap.CompositeName()); return dynamicMethod(() => _functionToWrap.Execute(parameters, context)); } catch (Exception ex) { if (_functionToWrap.ReturnType == typeof(XhtmlDocument) || (_functionToWrap.ReturnType == typeof(void) && ex is HttpCompileException)) { XElement errorBoxHtml; if (context.ProcessException(_functionToWrap.CompositeName(), ex, LogTitle, out errorBoxHtml)) { XhtmlDocument errorInfoDocument = new XhtmlDocument(); errorInfoDocument.Body.Add(errorBoxHtml); return errorInfoDocument; } } throw; } } public EntityToken EntityToken { get { return _functionToWrap.EntityToken; } } public bool ReturnValueIsDowncastable { get { if (_functionToWrap is IDowncastableFunction) { return ((IDowncastableFunction)_functionToWrap).ReturnValueIsDowncastable; } return false; } } public bool AllowRecursiveCall { get { return _functionToWrap is ICompoundFunction compoundFunction && compoundFunction.AllowRecursiveCall; } } bool IFunctionInitializationInfo.FunctionInitializedCorrectly { get { if(!(_functionToWrap is IFunctionInitializationInfo)) { return true; } return ((IFunctionInitializationInfo) _functionToWrap).FunctionInitializedCorrectly; } } public bool PreventFunctionOutputCaching => _functionToWrap is IDynamicFunction df && df.PreventFunctionOutputCaching; } } ================================================ FILE: Composite/Functions/Foundation/PluginFacades/WidgetFunctionProviderPluginFacade.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using Composite.Core.Collections.Generic; using Composite.C1Console.Events; using Composite.Core.Extensions; using Composite.Functions.Plugins.WidgetFunctionProvider; using Composite.Functions.Plugins.WidgetFunctionProvider.Runtime; namespace Composite.Functions.Foundation.PluginFacades { internal static class WidgetFunctionProviderPluginFacade { private static ResourceLocker<Resources> _resourceLocker = new ResourceLocker<Resources>(new Resources(), Resources.Initialize); static WidgetFunctionProviderPluginFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static IEnumerable<IWidgetFunction> Functions(string providerName) { using (_resourceLocker.Locker) { var widgetFunctions = new List<IWidgetFunction>(); var provider = GetFunctionProvider(providerName); provider.Functions?.ForEach(func => widgetFunctions.Add(new WidgetFunctionWrapper(func))); return widgetFunctions; } } public static IEnumerable<IWidgetFunction> DynamicTypeDependentFunctions(string providerName) { using (_resourceLocker.Locker) { var widgetFunctions = new List<IWidgetFunction>(); var provider = GetFunctionProvider(providerName); if (provider is IDynamicTypeWidgetFunctionProvider dtProvider) { dtProvider.DynamicTypeDependentFunctions?.ForEach(func => widgetFunctions.Add(new WidgetFunctionWrapper(func))); } return widgetFunctions; } } private static IWidgetFunctionProvider GetFunctionProvider(string providerName) { IWidgetFunctionProvider widgetFunctionProvider; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.ProviderCache.TryGetValue(providerName, out widgetFunctionProvider) == false) { try { widgetFunctionProvider = _resourceLocker.Resources.Factory.Create(providerName); widgetFunctionProvider.WidgetFunctionNotifier = new WidgetFunctionNotifier(providerName); _resourceLocker.Resources.ProviderCache.Add(providerName, widgetFunctionProvider); } catch (ArgumentException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } } } return widgetFunctionProvider; } private static void Flush() { _resourceLocker.ResetInitialization(); } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } private static void HandleConfigurationError(Exception ex) { Flush(); throw new ConfigurationErrorsException(string.Format("Failed to load the configuration section '{0}' from the configuration.", WidgetFunctionProviderSettings.SectionName), ex); } private sealed class Resources { public WidgetFunctionProviderFactory Factory { get; set; } public Dictionary<string, IWidgetFunctionProvider> ProviderCache { get; set; } public static void Initialize(Resources resources) { try { resources.Factory = new WidgetFunctionProviderFactory(); } catch (NullReferenceException ex) { HandleConfigurationError(ex); } catch (ConfigurationErrorsException ex) { HandleConfigurationError(ex); } resources.ProviderCache = new Dictionary<string, IWidgetFunctionProvider>(); } } } } ================================================ FILE: Composite/Functions/Foundation/PluginFacades/WidgetFunctionWrapper.cs ================================================ using System; using System.Collections.Generic; using System.Xml.Linq; using Composite.C1Console.Security; namespace Composite.Functions.Foundation.PluginFacades { /// <summary> /// This class is used for caching exceptions from plugins and hadling them correcty /// </summary> internal sealed class WidgetFunctionWrapper : IWidgetFunction, IFunctionInitializationInfo { private IWidgetFunction _widgetFunctionToWrap; internal WidgetFunctionWrapper(IWidgetFunction widgetFunctionToWrap) { _widgetFunctionToWrap = widgetFunctionToWrap; } public string Name { get { return _widgetFunctionToWrap.Name; } } public string Namespace { get { return _widgetFunctionToWrap.Namespace; } } public string Description { get { return _widgetFunctionToWrap.Description; } } public Type ReturnType { get { return _widgetFunctionToWrap.ReturnType; } } public IEnumerable<ParameterProfile> ParameterProfiles { get { if (_widgetFunctionToWrap.ParameterProfiles != null) { return _widgetFunctionToWrap.ParameterProfiles; } return new ParameterProfile[] { }; } } public XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { return _widgetFunctionToWrap.GetWidgetMarkup(parameters, label, help, bindingSourceName); } public EntityToken EntityToken { get { return _widgetFunctionToWrap.EntityToken; } } bool IFunctionInitializationInfo.FunctionInitializedCorrectly { get { if (!(_widgetFunctionToWrap is IFunctionInitializationInfo)) { return true; } return ((IFunctionInitializationInfo)_widgetFunctionToWrap).FunctionInitializedCorrectly; } } } } ================================================ FILE: Composite/Functions/Foundation/PluginFacades/XslExtensionsProviderPluginFacade.cs ================================================ using System.Collections.Generic; using Composite.Core.Collections.Generic; using Composite.Functions.Foundation.PluginFacades.Runtime; using Composite.Functions.Plugins.XslExtensionsProvider; using Composite.Core.Types; namespace Composite.Functions.Foundation.PluginFacades { internal static class XslExtensionsProviderPluginFacade { static Resources _resources = new Resources(); static XslExtensionsProviderPluginFacade() { Resources.Initialize(_resources); } public static List<Pair<string, object>> CreateExtensions(string providerName) { return GetProvider(providerName).CreateExtensions(); } private static IXslExtensionsProvider GetProvider(string providerName) { Resources resources = _resources; IXslExtensionsProvider provider = resources.ProviderCache[providerName]; if(provider != null) { return provider; } lock(resources.SyncRoot) { provider = resources.ProviderCache[providerName]; if (provider != null) { return provider; } provider = resources.Factory.Create(providerName); resources.ProviderCache[providerName] = provider; } return provider; } private sealed class Resources { public readonly object SyncRoot = new object(); public readonly XslExtensionsProviderFactory Factory = new XslExtensionsProviderFactory(); public Hashtable<string, IXslExtensionsProvider> ProviderCache { get; set; } public static void Initialize(Resources resources) { resources.ProviderCache = new Hashtable<string, IXslExtensionsProvider>(); } } } } ================================================ FILE: Composite/Functions/Foundation/WidgetFunctionContainer.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Core.Configuration; using Composite.Functions.Foundation.PluginFacades; using Composite.Functions.Plugins.WidgetFunctionProvider.Runtime; using Composite.Core.Logging; namespace Composite.Functions.Foundation { internal sealed class WidgetFunctionContainer : MetaFunctionContainer { internal WidgetFunctionContainer(List<string> excludedFunctionNames) : base(excludedFunctionNames) { } protected override IEnumerable<string> OnGetProviderNames() { if ((ConfigurationServices.ConfigurationSource != null) && (ConfigurationServices.ConfigurationSource.GetSection(WidgetFunctionProviderSettings.SectionName) != null)) { WidgetFunctionProviderSettings functionProviderSettings = ConfigurationServices.ConfigurationSource.GetSection(WidgetFunctionProviderSettings.SectionName) as WidgetFunctionProviderSettings; return functionProviderSettings.WidgetFunctionProviderPlugins.Select(plugin => plugin.Name); } else { LoggingService.LogError("FunctionProviderRegistry", string.Format("Failed to load the configuration section '{0}' from the configuration", WidgetFunctionProviderSettings.SectionName)); return new List<string>(); } } protected override IEnumerable<IMetaFunction> OnGetFunctionsFromProvider(string providerName, FunctionTypesToReturn functionTypesToReturn) { IEnumerable<IMetaFunction> functions = new List<IMetaFunction>(); switch (functionTypesToReturn) { case FunctionTypesToReturn.StaticDependentFunctions: try { functions = WidgetFunctionProviderPluginFacade.Functions(providerName).Cast<IMetaFunction>(); } catch (Exception ex) { LoggingService.LogCritical("FunctionProviderRegistry", ex); } break; case FunctionTypesToReturn.DynamicDependentOnlyFunctions: try { functions = WidgetFunctionProviderPluginFacade.DynamicTypeDependentFunctions(providerName).Cast<IMetaFunction>(); } catch (Exception ex) { LoggingService.LogCritical("FunctionProviderRegistry", ex); } break; case FunctionTypesToReturn.AllFunctions: try { functions = WidgetFunctionProviderPluginFacade.Functions(providerName).Cast<IMetaFunction>(); } catch (Exception ex) { LoggingService.LogCritical("FunctionProviderRegistry", ex); } try { functions = functions.Concat(WidgetFunctionProviderPluginFacade.DynamicTypeDependentFunctions(providerName).Cast<IMetaFunction>()); } catch (Exception ex) { LoggingService.LogCritical("FunctionProviderRegistry", ex); } break; default: throw new NotImplementedException(); } return functions; } protected override void OnFunctionsAdded(List<string> functionNames, bool fireEvents) { if (fireEvents) { FunctionEventSystemFacade.FireWidgetFunctionAddedEvent(new WidgetFunctionsAddedEventArgs(functionNames)); } } protected override void OnFunctionsRemoved(List<string> functionNames) { FunctionEventSystemFacade.FireWidgetFunctionRemovedEvent(new WidgetFunctionsRemovedEventArgs(functionNames)); } protected override string FunctionType { get { return "WidgetFunction"; } } } } ================================================ FILE: Composite/Functions/Foundation/XslExtensionsProviderRegistry.cs ================================================ using System.Collections.Generic; using System.Linq; using Composite.Core.Configuration; using Composite.Functions.Plugins.XslExtensionsProvider.Runtime; namespace Composite.Functions.Foundation { internal static class XslExtensionsProviderRegistry { public static IEnumerable<string> XslExtensionsProviderNames { get { XslExtensionsProviderSettings settings = ConfigurationServices.ConfigurationSource.GetSection(XslExtensionsProviderSettings.SectionName) as XslExtensionsProviderSettings; return settings.XslExtensionProviders.Select(provider => provider.Name); } } } } ================================================ FILE: Composite/Functions/FunctionAttribute.cs ================================================ using System; namespace Composite.Functions { /// <summary> /// Adds a desctiotion about a C1 Function. /// /// Different C1 Function providers let developers create new C1 Functions by creating artifacts like static funtions in C#, /// Razor Web Pages, User Controls etc. These C1 Functions can have descriptions and this attribute let you control this /// description. /// /// The use of this attribute is relative to the C1 Function provider being used. /// </summary> /// <example> /// Here is an example of how to use <see cref="FunctionAttribute" />: /// <code> /// [Function(Description="The description goes here")] /// public static int GetItemCount() /// { /// // more code here /// } /// </code> /// </example> /// <example> /// Here is an example of how to use <see cref="FunctionAttribute" /> to annotate a class: /// <code> /// [FunctionParameter(Label="Item count", DefaultValue=10)] /// public int ItemCount { get; set; } /// </code> /// Note that <see cref="P:Composite.Functions.FunctionParameterAttribute.Name" /> is not expected when <see cref="FunctionParameterAttribute" /> is used this way. /// </example> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] public sealed class FunctionAttribute : Attribute { /// <summary> /// Describe a function for use in the C1 Function system. /// </summary> public FunctionAttribute() { } /// <summary> /// The description of the function. /// </summary> public string Description { get; set; } } } ================================================ FILE: Composite/Functions/FunctionCallEditorManager.cs ================================================ using System.Linq; using Composite.Core.Collections.Generic; using Composite.Data; using Composite.Data.Types; using Composite.Core.WebClient; namespace Composite.Functions { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class FunctionCallEditorManager { private static readonly Hashtable<string, FunctionCallEditorSettings> _customEditorSettings = new Hashtable<string, FunctionCallEditorSettings>(); /// <summary> /// Returns a relative path a to a custom funtion call editor for the specified function. /// </summary> /// <param name="functionName">The function name</param> /// <returns>A relative path to a custom call editor, or <value>null</value> if no custom editor was defined.</returns> public static FunctionCallEditorSettings GetCustomEditorSettings(string functionName) { var settings = _customEditorSettings[functionName]; if (settings != null) { return settings; } using (var c = new DataConnection()) { var mapping = c.Get<ICustomFunctionCallEditorMapping>().FirstOrDefault(e => e.FunctionName == functionName); if (mapping != null) { return new FunctionCallEditorSettings { Url = UrlUtils.ResolvePublicUrl(mapping.CustomEditorPath), Width = mapping.Width, Height = mapping.Height }; } } return null; } /// <summary> /// Registers the custom call editor. /// </summary> /// <param name="functionName">Name of the function.</param> /// <param name="tildeBasedPath">A tilde based website path, like ~/Composite/custom.aspx</param> public static void RegisterCustomCallEditor(string functionName, string tildeBasedPath) { RegisterCustomCallEditor(functionName, tildeBasedPath, null, null); } /// <summary> /// Registers the custom call editor. /// </summary> /// <param name="functionName">Name of the function.</param> /// <param name="tildeBasedPath">A tilde based website path, like ~/Composite/custom.aspx</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> public static void RegisterCustomCallEditor(string functionName, string tildeBasedPath, int? width, int? height) { Verify.ArgumentCondition(tildeBasedPath.StartsWith("~"), "tildeBasedPath", "Must start with tilde (~)"); lock (_customEditorSettings) { _customEditorSettings[functionName] = new FunctionCallEditorSettings { Url = UrlUtils.ResolvePublicUrl(tildeBasedPath), Width = width, Height = height }; } } } } ================================================ FILE: Composite/Functions/FunctionCallEditorSettings.cs ================================================ namespace Composite.Functions { /// <summary> /// Settings for custom function call editor /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class FunctionCallEditorSettings { /// <summary> /// Gets the URL. /// </summary> /// <value> /// The URL. /// </value> public string Url { get; internal set; } /// <summary> /// Gets the height. /// </summary> /// <value> /// The height. /// </value> public int? Height { get; internal set; } /// <summary> /// Gets the width. /// </summary> /// <value> /// The width. /// </value> public int? Width { get; internal set; } } } ================================================ FILE: Composite/Functions/FunctionContextContainer.cs ================================================ using System; using System.Collections.Generic; using System.Threading; using System.Web; using System.Web.UI; using System.Xml.Linq; using Composite.Core; using Composite.Core.Types; using Composite.Core.Xml; namespace Composite.Functions { /// <summary> /// Context for evaluating function calls. Functions: /// 1) Container for embedded <see cref="Control"/>-s /// 2) Passing parameters into nested function calls. Applicable in xml template rendering logic. /// 3) Suppressing exceptions from XHTML functions. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class FunctionContextContainer { private readonly ParameterList _parameterList; private readonly Dictionary<string, object> _parameterDictionary; internal bool ExceptionsSuppressed { get; private set; } #region constructors /// <exclude /> public FunctionContextContainer() { } /// <exclude /> public FunctionContextContainer(ParameterList parameterList) { _parameterList = parameterList; } /// <exclude /> public FunctionContextContainer(Dictionary<string, object> parameterDictionary) { _parameterDictionary = parameterDictionary; } /// <exclude /> public FunctionContextContainer(FunctionContextContainer inheritFromContainer, Dictionary<string, object> parameterDictionary) { _parameterDictionary = parameterDictionary; this.XEmbedableMapper = inheritFromContainer.XEmbedableMapper; this.SuppressXhtmlExceptions = inheritFromContainer.SuppressXhtmlExceptions; } #endregion /// <summary> /// Used for embedding ASP.NET controls into xhtml markup. /// </summary> public IFunctionResultToXEmbedableMapper XEmbedableMapper { get; set; } /// <summary> /// When set to <value>True</value>, exceptions from C1 functions which results are rendered into xhtml will /// be caught, logged and the result xhtml will contain an error description element. /// </summary> public bool SuppressXhtmlExceptions { get; set; } /// <exclude /> public object GetParameterValue(string parameterName, Type targetType) { Verify.ArgumentNotNullOrEmpty(parameterName, "parameterName"); if (_parameterList != null) { return _parameterList.GetParameter(parameterName, targetType); } if (_parameterDictionary != null) { Verify.That(_parameterDictionary.ContainsKey(parameterName), "Parameter '{0}' hasn't been defined.", parameterName); object value = _parameterDictionary[parameterName]; if (value != null && !targetType.IsInstanceOfType(value)) { return ValueTypeConverter.Convert(value, targetType); } return value; } throw new InvalidOperationException("Unable to get parameter values. This context has been constructed without parameters."); } /// <exclude /> public object MakeXEmbedable(object resultObject) { if (this.XEmbedableMapper != null) { XNode resultElement; if (this.XEmbedableMapper.TryMakeXEmbedable(this, resultObject, out resultElement)) { return resultElement; } } if (resultObject is XDocument) { return ((XDocument)resultObject).Root; } return resultObject; } /// <summary> /// Checks whether an exception has to be re-thrown, if not - writes it to the log /// and returns markup that should be inserted as function's result. /// </summary> /// <param name="functionName">The name of the function</param> /// <param name="exception">The exception</param> /// <param name="logTitle">The log entry title.</param> /// <param name="errorBoxHtml">The markup that should be inserted instead of the function call</param> /// <returns><value>True</value> if the exception has to be re-thrown, <value>False</value> otherwise.</returns> public bool ProcessException(string functionName, Exception exception, string logTitle, out XElement errorBoxHtml) { if (!SuppressXhtmlExceptions || exception is ThreadAbortException || exception is ThreadInterruptedException || exception is AppDomainUnloadedException || exception is OutOfMemoryException || IsHttpException(exception)) { errorBoxHtml = null; return false; } Log.LogError("Function: " + functionName, exception); errorBoxHtml = XhtmlErrorFormatter.GetErrorDescriptionHtmlElement(exception, functionName); ExceptionsSuppressed = true; return true; } private bool IsHttpException(Exception exception) { return (!(exception is HttpCompileException) && exception is HttpException) || (exception.InnerException != null && IsHttpException(exception.InnerException)); } } } ================================================ FILE: Composite/Functions/FunctionEventSystemFacade.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Events; using Composite.Core.Logging; namespace Composite.Functions { internal static class FunctionEventSystemFacade { internal delegate void FunctionsAddedEventDelegate(FunctionsAddedEventArgs args); internal delegate void FunctionsRemovedEventDelegate(FunctionsRemovedEventArgs args); internal delegate void WidgetFunctionsAddedEventDelegate(WidgetFunctionsAddedEventArgs args); internal delegate void WidgetFunctionsRemovedEventDelegate(WidgetFunctionsRemovedEventArgs args); private static event FunctionsAddedEventDelegate _functionsAddedEvent; private static event FunctionsRemovedEventDelegate _functionsRemovedEvent; private static event WidgetFunctionsAddedEventDelegate _widgetFunctionsAddedEvent; private static event WidgetFunctionsRemovedEventDelegate _widgetFunctionsRemovedEvent; private static object _lock = new object(); static FunctionEventSystemFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } public static void SubscribeToFunctionsAddedEvent(FunctionsAddedEventDelegate functionsAddedEventDelegate) { lock (_lock) { _functionsAddedEvent += functionsAddedEventDelegate; } } public static void SubscribeToFunctionsRemovedEvent(FunctionsRemovedEventDelegate functionsRemovedEventDelegate) { lock (_lock) { _functionsRemovedEvent += functionsRemovedEventDelegate; } } public static void SubscribeToWidgetFunctionsAddedEvent(WidgetFunctionsAddedEventDelegate widgetFunctionsAddedEventDelegate) { lock (_lock) { _widgetFunctionsAddedEvent += widgetFunctionsAddedEventDelegate; } } public static void SubscribeToWidgetFunctionsRemovedEvent(WidgetFunctionsRemovedEventDelegate widgetFunctionsRemovedEventDelegate) { lock (_lock) { _widgetFunctionsRemovedEvent += widgetFunctionsRemovedEventDelegate; } } public static void FireFunctionAddedEvent(FunctionsAddedEventArgs functionsAddedEventArgs) { lock (_lock) { if (_functionsAddedEvent != null) { FunctionsAddedEventDelegate functionsAddedEvent = _functionsAddedEvent; functionsAddedEvent(functionsAddedEventArgs); } } } public static void FireFunctionRemovedEvent(FunctionsRemovedEventArgs functionsRemovedEventArgs) { lock (_lock) { if (_functionsRemovedEvent != null) { FunctionsRemovedEventDelegate functionsRemovedEvent = _functionsRemovedEvent; functionsRemovedEvent(functionsRemovedEventArgs); } } } public static void FireWidgetFunctionAddedEvent(WidgetFunctionsAddedEventArgs widgetFunctionsAddedEventArgs) { lock (_lock) { if (_widgetFunctionsAddedEvent != null) { WidgetFunctionsAddedEventDelegate widgetFunctionsAddedEvent = _widgetFunctionsAddedEvent; widgetFunctionsAddedEvent(widgetFunctionsAddedEventArgs); } } } public static void FireWidgetFunctionRemovedEvent(WidgetFunctionsRemovedEventArgs widgetFunctionsRemovedEventArgs) { lock (_lock) { if (_widgetFunctionsRemovedEvent != null) { WidgetFunctionsRemovedEventDelegate widgetFunctionsRemovedEvent = _widgetFunctionsRemovedEvent; widgetFunctionsRemovedEvent(widgetFunctionsRemovedEventArgs); } } } private static void Flush() { lock (_lock) { _functionsAddedEvent = null; _functionsRemovedEvent = null; _widgetFunctionsAddedEvent = null; _widgetFunctionsRemovedEvent = null; } } private static void OnFlushEvent(FlushEventArgs args) { Flush(); } } internal sealed class FunctionsAddedEventArgs : EventArgs { internal FunctionsAddedEventArgs(List<string> functionsAdded) { this.FunctionsAdded = functionsAdded; } public List<string> FunctionsAdded { get; private set; } } internal sealed class FunctionsRemovedEventArgs : EventArgs { internal FunctionsRemovedEventArgs(List<string> functionsRemoved) { this.FunctionsRemoved = functionsRemoved; } public List<string> FunctionsRemoved { get; private set; } } internal sealed class WidgetFunctionsAddedEventArgs : EventArgs { internal WidgetFunctionsAddedEventArgs(List<string> widgetFunctionsAdded) { this.WidgetFunctionsAdded = widgetFunctionsAdded; } public List<string> WidgetFunctionsAdded { get; private set; } } internal sealed class WidgetFunctionsRemovedEventArgs : EventArgs { internal WidgetFunctionsRemovedEventArgs(List<string> widgetFunctionsRemoved) { this.WidgetFunctionsRemoved = widgetFunctionsRemoved; } public List<string> WidgetFunctionsRemoved { get; private set; } } } ================================================ FILE: Composite/Functions/FunctionFacade.cs ================================================ using System; using System.Xml.Linq; using System.Collections.Generic; using Composite.Functions.Foundation; using Composite.Core.Extensions; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class FunctionFacade { /// <exclude /> public static List<string> FunctionNames { get { return MetaFunctionProviderRegistry.FunctionNames; } } /// <exclude /> public static List<string> WidgetFunctionNames { get { return MetaFunctionProviderRegistry.WidgetFunctionNames; } } /// <exclude /> public static IFunction GetFunction(string name) { return MetaFunctionProviderRegistry.GetFunction(name); } /// <exclude /> public static bool TryGetFunction(out IMetaFunction foundFunction, string name, Type functionType) { if (functionType == typeof(IFunction)) { if (MetaFunctionProviderRegistry.FunctionNames.Contains(name)) { foundFunction = GetFunction(name); return true; } foundFunction = null; return false; } if (functionType == typeof(IWidgetFunction)) { if (MetaFunctionProviderRegistry.WidgetFunctionNames.Contains(name)) { foundFunction = GetWidgetFunction(name); return true; } foundFunction = null; return false; } throw new ArgumentException("Type of function must be IFunction or IWidgetFunction"); } /// <exclude /> public static bool TryGetFunction(out IFunction foundFunction, string name) { if (MetaFunctionProviderRegistry.FunctionNames.Contains(name)) { foundFunction = GetFunction(name); return true; } foundFunction = null; return false; } /// <exclude /> public static bool TryGetWidgetFunction(out IWidgetFunction foundFunction, string name) { if (MetaFunctionProviderRegistry.WidgetFunctionNames.Contains(name)) { foundFunction = GetWidgetFunction(name); return true; } foundFunction = null; return false; } /// <exclude /> public static IWidgetFunction GetWidgetFunction(string name) { return MetaFunctionProviderRegistry.GetWidgetFunction(name); } /// <exclude /> public static IEnumerable<IFunction> GetFunctionsByProvider(string providerName) { foreach (string functionName in MetaFunctionProviderRegistry.FunctionNamesByProviderName(providerName)) { yield return MetaFunctionProviderRegistry.GetFunction(functionName); } } /// <exclude /> public static IEnumerable<string> GetFunctionNamesByProvider(string providerName) { return MetaFunctionProviderRegistry.FunctionNamesByProviderName(providerName); } /// <exclude /> public static IEnumerable<string> GetFunctionNamesByType(Type supportedType) { return MetaFunctionProviderRegistry.GetFunctionNamesByType(supportedType); } /// <exclude /> public static IEnumerable<string> GetWidgetFunctionNamesByType(Type supportedType) { return MetaFunctionProviderRegistry.GetWidgetFunctionNamesByType(supportedType); } /// <exclude /> public static IEnumerable<Type> FunctionSupportedTypes { get { return MetaFunctionProviderRegistry.FunctionSupportedTypes; } } /// <exclude /> public static IEnumerable<Type> WidgetFunctionSupportedTypes { get { return MetaFunctionProviderRegistry.WidgetFunctionSupportedTypes; } } /// <exclude /> public static bool FunctionExists(string namespaceName, string name) { IFunction fun; bool exists = FunctionFacade.TryGetFunction(out fun, StringExtensionMethods.CreateNamespace(namespaceName, name)); return exists; } /// <exclude /> public static BaseRuntimeTreeNode BuildTree(IFunction function, IDictionary<string, object> parameters) { List<BaseParameterRuntimeTreeNode> parameterNodes = new List<BaseParameterRuntimeTreeNode>(); if (parameters != null) { foreach (KeyValuePair<string, object> kvp in parameters) { parameterNodes.Add(new ConstantObjectParameterRuntimeTreeNode(kvp.Key, kvp.Value)); } } return new FunctionRuntimeTreeNode(function, parameterNodes); } /// <exclude /> public static BaseRuntimeTreeNode BuildTree(XElement element) { return FunctionTreeBuilder.Build(element); } /// <exclude /> public static T Execute<T>(IFunction function, IDictionary<string, object> parameters) { var functionContextContainer = new FunctionContextContainer(); return Execute<T>(function, parameters, functionContextContainer); } /// <exclude /> public static T Execute<T>(IFunction function, IDictionary<string, object> parameters, FunctionContextContainer functionContextContainer) { BaseRuntimeTreeNode node = BuildTree(function, parameters); return (T)node.GetValue(functionContextContainer); } /// <exclude /> public static T Execute<T>(IFunction function) { Dictionary<string, object> parameters = new Dictionary<string, object>(); FunctionContextContainer container = new FunctionContextContainer(); return Execute<T>(function, parameters, container); } /// <exclude /> public static T Execute<T>(IFunction function, System.Collections.Specialized.NameValueCollection parameterValues) { Dictionary<string, object> parameters = new Dictionary<string, object>(); foreach (var parameterName in parameterValues.AllKeys) { if (parameterName != null && parameterValues[parameterName] != null) { parameters.Add(parameterName, parameterValues[parameterName]); } } FunctionContextContainer container = new FunctionContextContainer(); return Execute<T>(function, parameters, container); } //public static XElement GetWidgetMarkup(IWidgetFunction widgetFunction, Type targetType, IDictionary<string, object> parameters, string label, HelpDefinition helpDefinition, string bindingSourceName, FunctionContextContainer functionContextContainer) //{ // List<BaseParameterRuntimeTreeNode> parameterNodes = new List<BaseParameterRuntimeTreeNode>(); // if (parameters != null) // { // foreach (KeyValuePair<string, object> kvp in parameters) // { // parameterNodes.Add(new ConstantObjectParameterRuntimeTreeNode(kvp.Key, kvp.Value)); // } // } // BaseRuntimeTreeNode node = new WidgetFunctionRuntimeTreeNode(widgetFunction, label, helpDefinition, bindingSourceName, parameterNodes); // return (XElement)node.GetValue(functionContextContainer); //} /// <exclude /> public static XElement GetWidgetMarkup(IWidgetFunction widgetFunction, Type targetType, IEnumerable<BaseParameterRuntimeTreeNode> parameters, string label, HelpDefinition helpDefinition, string bindingSourceName, FunctionContextContainer functionContextContainer) { List<BaseParameterRuntimeTreeNode> parameterNodes = new List<BaseParameterRuntimeTreeNode>(); if (parameters != null) { foreach (BaseParameterRuntimeTreeNode parameterNode in parameters) { parameterNodes.Add(parameterNode); } } BaseRuntimeTreeNode node = new WidgetFunctionRuntimeTreeNode(widgetFunction, label, helpDefinition, bindingSourceName, parameterNodes); return (XElement)node.GetValue(functionContextContainer); } /// <exclude /> public static string BuildUniqueFunctionName(string functionNamespace, string nameStem) { string nameCandidate = nameStem; int i = 1; while (FunctionFacade.FunctionNames.Contains(string.Format("{0}.{1}", functionNamespace, nameCandidate))) { i++; nameCandidate = string.Format("{0}{1}", nameStem, i); } return nameCandidate; } /// <exclude /> public static string GetFunctionCompositionName(string functionNamespace, string name) { return StringExtensionMethods.CreateNamespace(functionNamespace, name); } } } ================================================ FILE: Composite/Functions/FunctionParameterAttribute.cs ================================================ using System; using System.Collections.Generic; using System.Reflection; using System.Xml.Linq; using Composite.Core.Extensions; namespace Composite.Functions { /// <summary> /// Adds information about C1 Function parameters like label, help text, default value and custom widget markup. /// /// Different C1 Function providers let developers create new C1 Functions by creating artifacts like static funtions in C#, /// Razor Web Pages, User Controls etc. These C1 Functions can have parameters, typically defined as actual parameters (for /// static functions) or as public get/set propeties. This attribute signal that a C1 Function parameter is being defined and /// add label, help etc. /// /// The use of this attribute is relative to the C1 Function provider being used. /// </summary> /// <example> /// Here is an example of how to use <see cref="FunctionParameterAttribute" /> to annotate multiple parameters of a function: /// <code> /// [FunctionParameter(Name="searchTerm", Label="Search term", Help="One or more keywords to search for")] /// [FunctionParameter(Name="filter", Label="Filter", Help="Filter to apply to data before searching for search term", DefaultValue=null)] /// public static int GetItemCount( string searchTerm, Expression<Func<IMyDataType,bool>> filter ) /// { /// if (filter == null ) filter = _defaultFilter; /// // more code here /// } /// </code> /// Note that <see cref="P:Composite.Functions.FunctionParameterAttribute.Name" /> is required when <see cref="FunctionParameterAttribute" /> is used this way. /// </example> /// <example> /// Here is an example of how to use <see cref="FunctionParameterAttribute" /> to annotate a property: /// <code> /// [FunctionParameter(Label="Item count", DefaultValue=10)] /// public int ItemCount { get; set; } /// </code> /// Note that <see cref="P:Composite.Functions.FunctionParameterAttribute.Name" /> is not expected when <see cref="FunctionParameterAttribute" /> is used this way. /// </example> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)] public sealed class FunctionParameterAttribute : Attribute { private object _defaultValue; /// <summary> /// Describe a function parameter for use in the C1 Function system. /// </summary> public FunctionParameterAttribute() { this.Name = null; this.HasDefaultValue = false; } /// <summary> /// The name of the function parameter being described. This should match the parameter name in the method. /// </summary> public string Name { get; set; } /// <summary> /// Human readable label for this parameter /// </summary> public string Label { get; set; } /// <summary> /// Human readable help for this parameter /// </summary> public string Help { get; set; } /// <summary> /// Set this property to control the form input field used to set the parameters value. /// </summary> public string WidgetMarkup { get; set; } /// <summary> /// Gets or sets the name of the widget function. /// </summary> /// <value> /// The name of the widget function. /// </value> public string WidgetFunctionName { get; set; } /// <summary> /// Gets or sets the widget factory method. /// </summary> /// <value> /// The widget factory method. /// </value> public string WidgetFactoryMethod { get; set; } /// <summary> /// Gets or sets the widget factory class. /// </summary> /// <value> /// The widget factory class. /// </value> public Type WidgetFactoryClass { get; set; } /// <summary> /// Optional. Default value that should be assigned to the parameter if not specified by the caller. You can use 'null' for complex objects that can not be expressed in attribute code and the check for null in the code. /// </summary> public object DefaultValue { get { return _defaultValue; } set { _defaultValue = value; HasDefaultValue = true; } } /// <summary> /// Allows to hide the parameter in the "simple view" mode of function call editing. /// Will be ignored is the field is requires and does not have a value or a default value. /// </summary> public bool HideInSimpleView { get; set; } /// <summary> /// Indicate if this parameter definition has a default value or not. /// </summary> public bool HasDefaultValue { get; private set; } /// <summary> /// Indicate if Name is defined for this attribute. /// </summary> public bool HasName { get { return !string.IsNullOrWhiteSpace(this.Name); } } /// <summary> /// Indicate if Label is defined for this attribute. /// </summary> public bool HasLabel { get { return !string.IsNullOrWhiteSpace(this.Label); } } /// <summary> /// Indicate if Help is defined for this attribute. /// </summary> public bool HasHelp { get { return !string.IsNullOrWhiteSpace(this.Help); } } /// <summary> /// Indicate if WidgetMarkup is defined for this attribute. /// </summary> public bool HasWidgetMarkup { get { return !string.IsNullOrWhiteSpace(this.WidgetMarkup) || !string.IsNullOrWhiteSpace(this.WidgetFunctionName) || !string.IsNullOrWhiteSpace(this.WidgetFactoryMethod); } } /// <summary> /// Gets the widget markup /// </summary> /// <param name="owner">Class that contains</param> /// <param name="parameterProperty">The parameter property.</param> /// <returns></returns> public WidgetFunctionProvider GetWidgetFunctionProvider(Type owner, PropertyInfo parameterProperty) { if(!HasWidgetMarkup) { return null; } if(!WidgetMarkup.IsNullOrEmpty()) { var markup = XElement.Parse(WidgetMarkup); return new WidgetFunctionProvider(markup); } if(!WidgetFunctionName.IsNullOrEmpty()) { return new WidgetFunctionProvider(WidgetFunctionName); } if(!WidgetFactoryMethod.IsNullOrEmpty()) { Type factoryType = WidgetFactoryClass ?? owner; Verify.IsNotNull(factoryType, "WidgetFactoryClass isn't defined"); var methodInfo = factoryType.GetMethod(WidgetFactoryMethod, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); Verify.IsNotNull(methodInfo, "Failed to get static method '{0}' on type '{1}'", WidgetFactoryMethod, factoryType.FullName); object result = null; var parameters = methodInfo.GetParameters(); if(parameters.Length == 0) { result = methodInfo.Invoke(null, new object[0]); } else if(parameters.Length == 1 && parameters[0].ParameterType == typeof(string)) { result = methodInfo.Invoke(null, new object[] { Name }); } else if (parameters.Length == 1 && parameters[0].ParameterType == typeof(PropertyInfo)) { Verify.IsNotNull(parameterProperty, "parameterProperty isn't defined"); result = methodInfo.Invoke(null, new object[] { parameterProperty }); } else { throw new InvalidOperationException("Unknown method signature"); } if (result == null) return null; if(result is XElement) { return new WidgetFunctionProvider(result as XElement); } if(result is IWidgetFunction) { return new WidgetFunctionProvider(result as IWidgetFunction); } if(result is WidgetFunctionProvider) { return result as WidgetFunctionProvider; } throw new InvalidOperationException("Unexpected widget type '{0}'".FormatWith(result.GetType())); } throw new InvalidOperationException("This line should not be reachable"); } } } ================================================ FILE: Composite/Functions/FunctionParameterDescriptionAttribute.cs ================================================ using System; namespace Composite.Functions { /// <summary> /// Add information about parameters to functions callable via the "C# Function" feature. /// </summary> /// <remarks> /// This class has been marked as obsolete. Use <see cref="FunctionParameterAttribute" />. /// </remarks> /// <example> /// Here is an example of how to use <see cref="FunctionParameterDescriptionAttribute" /> /// <code> /// [FunctionParameterDescription("searchTerm", "Search term", "One or more keywords to search for")] /// [FunctionParameterDescription("filter", "Filter", "Filter to apply to data before searching for search term", null)] /// public static int GetItemCount( string searchTerm, Expression<Func<IMyDataType,bool>> filter ) /// { /// if (filter == null ) filter = _defaultFilter; /// // more code here /// } /// </code> /// </example> /// <exclude /> [Obsolete("Use FunctionParameterAttribute instead ...", false)] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public sealed class FunctionParameterDescriptionAttribute : Attribute { /// <summary> /// Describe a function parameter for use in the C1 Function system. /// </summary> /// <param name="parameterName">The programmatic name of the parameter</param> /// <param name="parameterLabel">Human readable label</param> /// <param name="parameterHelpText">Human readable help text</param> public FunctionParameterDescriptionAttribute(string parameterName, string parameterLabel, string parameterHelpText) { this.ParameterName = parameterName; this.ParameterLabel = parameterLabel; this.ParameterHelpText = parameterHelpText; this.HasDefaultValue = false; } /// <summary> /// Describe a function parameter for use in the C1 Function system. /// </summary> /// <param name="parameterName">The programmatic name of the parameter</param> /// <param name="parameterLabel">Human readable label</param> /// <param name="parameterHelpText">Human readable help text</param> /// <param name="defaultValue">Optional. Default value that should be assigned to the parameter if not specified by the caller. You can use 'null' for complex objects that can not be expressed in attribute code and the check for null in the code.</param> public FunctionParameterDescriptionAttribute(string parameterName, string parameterLabel, string parameterHelpText, object defaultValue) : this(parameterName, parameterLabel, parameterHelpText) { this.DefaultValue = defaultValue; this.HasDefaultValue = true; } /// <summary> /// The name of the function parameter being described. This should match the parameter name in the method. /// </summary> public string ParameterName { get; private set; } /// <summary> /// Optional. Default value that should be assigned to the parameter if not specified by the caller. You can use 'null' for complex objects that can not be expressed in attribute code and the check for null in the code. /// </summary> public object DefaultValue { get; private set; } /// <summary> /// Human readable label for this parameter /// </summary> public string ParameterLabel { get; private set; } /// <summary> /// Human readable help for this parameter /// </summary> public string ParameterHelpText { get; private set; } /// <summary> /// Indicate if this parameter definition has a default value or not. /// </summary> public bool HasDefaultValue { get; private set; } } } ================================================ FILE: Composite/Functions/FunctionParameterIgnoreAttribute.cs ================================================ using System; namespace Composite.Functions { /// <summary> /// Put this attribute on properties to make C1 CMS skip them when infering C1 Function parameters from a class. /// /// If you need a property on your class, but do not want this property to be part of the C1 Function signature use this attrobute. /// </summary> /// <example> /// Here is an example of how to use <see cref="FunctionParameterIgnoreAttribute" /> to make C1 CMS skip a property when infering parameters: /// <code> /// [FunctionParameterIgnore()] /// public int ItemCount { get; set; } /// </code> /// </example> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public sealed class FunctionParameterIgnoreAttribute : Attribute { /// <summary> /// Declare that a property should be ignored as a C1 Function parameter. /// </summary> public FunctionParameterIgnoreAttribute() { } } } ================================================ FILE: Composite/Functions/FunctionParameterRuntimeTreeNode.cs ================================================ using System; using System.Threading; using System.Xml.Linq; using System.Collections.Generic; using Composite.Functions.Foundation; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class FunctionParameterRuntimeTreeNode : BaseParameterRuntimeTreeNode { private FunctionRuntimeTreeNode _functionNode; /// <exclude /> public FunctionParameterRuntimeTreeNode(string name, FunctionRuntimeTreeNode functionNode) : base(name) { _functionNode = functionNode; } /// <exclude /> public FunctionRuntimeTreeNode GetHostedFunction() { return _functionNode; } /// <exclude /> public override bool ContainsNestedFunctions { get { return _functionNode.ContainsNestedFunctions; } } /// <exclude /> public override object GetValue(FunctionContextContainer contextContainer) { Verify.ArgumentNotNull(contextContainer, "contextContainer"); return _functionNode.GetValue(contextContainer); } /// <exclude /> public override IEnumerable<string> GetAllSubFunctionNames() { return _functionNode.GetAllSubFunctionNames(); } /// <exclude /> public override XElement Serialize() { // ensure "f:function" naming: XElement element = XElement.Parse(string.Format(@"<f:{0} xmlns:f=""{1}"" />", FunctionTreeConfigurationNames.ParamTagName, FunctionTreeConfigurationNames.NamespaceName)); element.Add(new XAttribute(FunctionTreeConfigurationNames.NameAttributeName, this.Name)); element.Add(_functionNode.Serialize()); return element; } } } ================================================ FILE: Composite/Functions/FunctionRuntimeTreeNode.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Xml.Linq; using Composite.Core; using Composite.Data; using Composite.Functions.Foundation; using Composite.Core.Instrumentation; using Composite.Core.Extensions; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DebuggerDisplay("FunctionRuntimeTreeNode: {_function.Namespace + '.' + _function.Name}")] public sealed class FunctionRuntimeTreeNode : BaseFunctionRuntimeTreeNode { private readonly IFunction _function; /// <exclude /> protected override IMetaFunction HostedFunction { get { return _function; } } /// <exclude /> public FunctionRuntimeTreeNode(IFunction function) { _function = function; this.Parameters = new List<BaseParameterRuntimeTreeNode>(); } internal FunctionRuntimeTreeNode(IFunction function, List<BaseParameterRuntimeTreeNode> parameters) { _function = function; this.Parameters = parameters; } /// <exclude /> public override object GetValue(FunctionContextContainer contextContainer) { if (contextContainer == null) throw new ArgumentNullException("contextContainer"); string functionName = _function.CompositeName() ?? "<unknown function>"; using (TimerProfilerFacade.CreateTimerProfiler(functionName)) { ValidateNotSelfCalling(); try { var parameters = new ParameterList(contextContainer); foreach (ParameterProfile parameterProfile in _function.ParameterProfiles) { List<BaseParameterRuntimeTreeNode> parameterTreeNodes = this.Parameters.Where(ptn => ptn.Name == parameterProfile.Name).ToList(); if (parameterTreeNodes.Count > 0) { parameters.AddLazyParameter(parameterProfile.Name, parameterTreeNodes[0], parameterProfile.Type); continue; } if (parameterProfile.Type.IsGenericType && parameterProfile.Type.GetGenericTypeDefinition() == typeof(NullableDataReference<>)) { parameters.AddConstantParameter(parameterProfile.Name, null, parameterProfile.Type); continue; } if (parameterProfile.IsRequired) { var injectedValue = TryGetInjectedValue(parameterProfile.Type); if (injectedValue == null) { throw new ArgumentException("Missing parameter '{0}' (type of {1})".FormatWith(parameterProfile.Name, parameterProfile.Type.FullName)); } parameters.AddConstantParameter(parameterProfile.Name, injectedValue, parameterProfile.Type); continue; } BaseValueProvider valueProvider = parameterProfile.FallbackValueProvider; object value; try { value = valueProvider.GetValue(contextContainer); } catch (Exception ex) { throw new InvalidOperationException($"Failed to get value for parameter '{parameterProfile.Name}' in function '{functionName}'.", ex); } parameters.AddConstantParameter(parameterProfile.Name, value, parameterProfile.Type, true); } object result; IDisposable measurement = null; try { if (functionName != "Composite.Utils.GetInputParameter") { var nodeToLog = functionName; if (_function is IDynamicFunction df && df.PreventFunctionOutputCaching) { nodeToLog += " (PreventCaching)"; } measurement = Profiler.Measure(nodeToLog, () => _function.EntityToken); } result = _function.Execute(parameters, contextContainer); } finally { measurement?.Dispose(); } return result; } catch(ThreadAbortException) { return null; // Nothing will be returned as ThreadAbort will propagate } catch (Exception ex) { throw new InvalidOperationException($"Failed to get value for function '{functionName}'", ex); } } } private static object TryGetInjectedValue(Type type) { return ServiceLocator.GetService(type); } /// <exclude /> public override IEnumerable<string> GetAllSubFunctionNames() { var names = new List<string> { _function.CompositeName() }; foreach (BaseParameterRuntimeTreeNode parameter in this.Parameters) { names.AddRange(parameter.GetAllSubFunctionNames()); } return names.Distinct(); } /// <exclude /> public override XElement Serialize() { // ensure "f:function" naming: XElement element = XElement.Parse(string.Format(@"<f:{0} xmlns:f=""{1}"" />", FunctionTreeConfigurationNames.FunctionTagName, FunctionTreeConfigurationNames.NamespaceName)); element.Add(new XAttribute(FunctionTreeConfigurationNames.NameAttributeName, _function.CompositeName())); foreach (ParameterProfile parameterProfile in _function.ParameterProfiles) { BaseParameterRuntimeTreeNode parameterRuntimeTreeNode = this.Parameters.FirstOrDefault(ptn => ptn.Name == parameterProfile.Name); if (parameterRuntimeTreeNode != null) { element.Add(parameterRuntimeTreeNode.Serialize()); } } return element; } } } ================================================ FILE: Composite/Functions/FunctionTreeBuilder.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.Core; using Composite.Core.Extensions; using Composite.Functions.Foundation; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class FunctionTreeBuilder { /// <exclude /> public static BaseRuntimeTreeNode Build(XElement element) { return Build(element, false); } internal static BaseRuntimeTreeNode Build(XElement element, bool ignoreUnusedParameters) { if (element == null) throw new ArgumentNullException("element"); if (element.Name.Namespace != FunctionTreeConfigurationNames.NamespaceName) throw new InvalidOperationException(string.Format("The namespace '{0}' is not supported", element.Name.Namespace)); if (element.Name.LocalName == FunctionTreeConfigurationNames.FunctionTagName) { return BuildFunctionRuntimeNode(element, ignoreUnusedParameters); } if (element.Name.LocalName == FunctionTreeConfigurationNames.WidgetFunctionTagName) { return BuildWidgetFunctionRuntimeNode(element); } if (element.Name.LocalName == FunctionTreeConfigurationNames.ParamTagName) { return BuildParameterFunctionRuntimeNode(element); } throw new InvalidOperationException(string.Format("The tag named '{0}' is not supported", element.Name.LocalName)); } /// <exclude /> public static FunctionRuntimeTreeNode BuildFunction(string functionName, Dictionary<string, string> parameters) { var functionParams = new List<BaseParameterRuntimeTreeNode>(); foreach (var parameter in parameters) { functionParams.Add(new ConstantParameterRuntimeTreeNode(parameter.Key, parameter.Value)); } IFunction function = FunctionFacade.GetFunction(functionName); return new FunctionRuntimeTreeNode(function, functionParams); } /// <exclude /> public static WidgetFunctionRuntimeTreeNode BuildWidgetFunction(string widgetFunctionName, string label, HelpDefinition helpDefinition, string bindingSourceName) { IWidgetFunction widgetFunction = FunctionFacade.GetWidgetFunction(widgetFunctionName); return new WidgetFunctionRuntimeTreeNode(widgetFunction, label, helpDefinition, bindingSourceName); } private static FunctionRuntimeTreeNode BuildFunctionRuntimeNode(XElement element, bool ignoreUnusedParameters) { XAttribute nameAttribute = element.Attribute(FunctionTreeConfigurationNames.NameAttributeName); if (nameAttribute == null) throw new InvalidOperationException(string.Format("Missing attribute named '{0}'", FunctionTreeConfigurationNames.NameAttributeName)); var parameters = new List<BaseParameterRuntimeTreeNode>(); foreach (XElement childElement in element.Elements()) { if (childElement.Name.LocalName == FunctionTreeConfigurationNames.ParamTagName) { BaseParameterRuntimeTreeNode parameterTreeNode = BuildParameterFunctionRuntimeNode(childElement); parameters.Add(parameterTreeNode); } else { throw new InvalidOperationException(string.Format("Only '{0}' tags allowed inside '{1}' tags", FunctionTreeConfigurationNames.ParamTagName, FunctionTreeConfigurationNames.FunctionTagName)); } } IFunction function = FunctionFacade.GetFunction(nameAttribute.Value); if (FunctionInitializedCorrectly(function)) { for (int index = parameters.Count - 1; index >= 0 ; index--) { BaseParameterRuntimeTreeNode parameter = parameters[index]; if (function.ParameterProfiles.All(pp => pp.Name != parameter.Name)) { string message = "The parameter '{0}' is not defined in the function named '{1}' parameter profiles" .FormatWith(parameter.Name, function.CompositeName()); if (ignoreUnusedParameters) { Log.LogWarning(typeof(FunctionTreeBuilder).Name, message); parameters.RemoveAt(index); continue; } throw new InvalidOperationException(message); } } } return new FunctionRuntimeTreeNode(function, parameters); } private static bool FunctionInitializedCorrectly(IFunction function) { return !(function is IFunctionInitializationInfo) || (function as IFunctionInitializationInfo).FunctionInitializedCorrectly; } private static string AttributeValueOrEmpty(XElement element, string attributeName) { var attribute = element.Attribute(attributeName); return (attribute == null ? "" : attribute.Value); } private static WidgetFunctionRuntimeTreeNode BuildWidgetFunctionRuntimeNode(XElement element) { XAttribute nameAttribute = element.Attribute(FunctionTreeConfigurationNames.NameAttributeName); if (nameAttribute == null) { throw new InvalidOperationException(string.Format("Missing attribute named '{0}'", FunctionTreeConfigurationNames.NameAttributeName)); } string label = AttributeValueOrEmpty(element, FunctionTreeConfigurationNames.LabelAttributeName); string bindingSourceName = AttributeValueOrEmpty(element, FunctionTreeConfigurationNames.BindingSourceNameAttributeName); HelpDefinition helpDefinition = null; var parameters = new List<BaseParameterRuntimeTreeNode>(); foreach (XElement childElement in element.Elements()) { if (childElement.Name.LocalName == FunctionTreeConfigurationNames.HelpDefinitionTagName) { helpDefinition = HelpDefinition.Deserialize(childElement); } else if (childElement.Name.LocalName == FunctionTreeConfigurationNames.ParamTagName) { BaseParameterRuntimeTreeNode parameterTreeNode = BuildParameterFunctionRuntimeNode(childElement); parameters.Add(parameterTreeNode); } else { throw new InvalidOperationException(string.Format("Only '{0}' tags allowed inside '{1}' tags", FunctionTreeConfigurationNames.ParamTagName, FunctionTreeConfigurationNames.FunctionTagName)); } } if (helpDefinition == null) helpDefinition = new HelpDefinition(""); IWidgetFunction widgetFunction = FunctionFacade.GetWidgetFunction(nameAttribute.Value); foreach (BaseParameterRuntimeTreeNode parameter in parameters) { if (widgetFunction.ParameterProfiles.All(pp => pp.Name != parameter.Name)) { throw new InvalidOperationException(string.Format("The parameter '{0}' is not defined in the function named '{1}' parameter profiles", parameter.Name, widgetFunction.CompositeName())); } } return new WidgetFunctionRuntimeTreeNode(widgetFunction, label, helpDefinition, bindingSourceName, parameters); } private static BaseParameterRuntimeTreeNode BuildParameterFunctionRuntimeNode(XElement element) { XAttribute nameAttribute = element.Attribute(FunctionTreeConfigurationNames.NameAttribute); Verify.IsNotNull(nameAttribute, "Missing attribute named '{0}'", FunctionTreeConfigurationNames.NameAttributeName); string parameterName = nameAttribute.Value; XAttribute valueAttribute = element.Attribute(FunctionTreeConfigurationNames.ValueAttribute); if (valueAttribute != null) { return new ConstantParameterRuntimeTreeNode(parameterName, valueAttribute); } if (!element.Elements().Any()) { if (string.IsNullOrWhiteSpace(element.Value)) { return new ConstantParameterRuntimeTreeNode(parameterName, (string)null); } return new ConstantParameterRuntimeTreeNode(parameterName, element.Value); } if ((element.Elements().Count() == 1) && (element.Elements().First().Name.LocalName == FunctionTreeConfigurationNames.FunctionTagName)) { XElement childElement = element.Elements().First(); if (childElement.Name.LocalName != FunctionTreeConfigurationNames.FunctionTagName) { throw new InvalidOperationException(string.Format("Missing '{0}' child element (found '{1}')", FunctionTreeConfigurationNames.FunctionTagName, childElement.Name.LocalName)); } FunctionRuntimeTreeNode functionNode = BuildFunctionRuntimeNode(childElement, false); return new FunctionParameterRuntimeTreeNode(parameterName, functionNode); } if ((element.Elements().Count() == 1) && (element.Elements().First().Name.LocalName != FunctionTreeConfigurationNames.ParamElementTagName)) { return new XElementParameterRuntimeTreeNode(parameterName, element.Elements().First()); } if (element.Elements().All(f => f.Name.LocalName == FunctionTreeConfigurationNames.ParamElementTagName)) { var strings = new List<string>(); foreach(XElement elm in element.Elements()) { XAttribute attr = elm.Attribute(FunctionTreeConfigurationNames.ValueAttribute); Verify.IsNotNull(attr, "One or more {0} are missing the attribute {1}", FunctionTreeConfigurationNames.ParamElementTagName, FunctionTreeConfigurationNames.ValueAttributeName); strings.Add(attr.Value); } return new ConstantParameterRuntimeTreeNode(parameterName, strings); } if (element.Nodes().Any()) { object value = element.Nodes().All(f => f is XElement) ? element.Elements() : element.Nodes(); return new ConstantObjectParameterRuntimeTreeNode(parameterName, value); } throw new InvalidProgramException("Wrong xml format in parameter '{0}'".FormatWith(parameterName)); } } } ================================================ FILE: Composite/Functions/FunctionValueProvider.cs ================================================ using System; using System.Xml.Linq; using System.Collections.Generic; namespace Composite.Functions { internal sealed class FunctionValueProvider : BaseValueProvider { private FunctionRuntimeTreeNode _functionFunctionRuntimeNode = null; private string _functionName = null; private List<BaseParameterRuntimeTreeNode> _parameters = null; private XElement _serializedFunction = null; private object _lock = new object(); public FunctionValueProvider(FunctionRuntimeTreeNode functionFunctionRuntimeNode) { if (functionFunctionRuntimeNode == null) throw new ArgumentNullException("functionFunctionRuntimeNode"); _functionFunctionRuntimeNode = functionFunctionRuntimeNode; } public FunctionValueProvider(string functionName, List<BaseParameterRuntimeTreeNode> parameters) { if (string.IsNullOrEmpty(functionName)) throw new ArgumentException("functionName may not be null or empty"); if (parameters == null) throw new ArgumentNullException("parameters"); _functionName = functionName; _parameters = parameters; } public FunctionValueProvider(XElement serializedFunction) { if (serializedFunction == null) throw new ArgumentNullException("serializedFunction"); _serializedFunction = serializedFunction; } public override object GetValue(FunctionContextContainer contextContainer) { if (contextContainer == null) throw new ArgumentNullException("contextContainer"); Initialize(); return _functionFunctionRuntimeNode.GetValue(contextContainer); } public override XObject Serialize() { Initialize(); return _functionFunctionRuntimeNode.Serialize(); } private void Initialize() { if (_functionFunctionRuntimeNode == null) { lock (_lock) { if (_functionFunctionRuntimeNode == null) { if (_serializedFunction == null) { IFunction function = FunctionFacade.GetFunction(_functionName); _functionFunctionRuntimeNode = new FunctionRuntimeTreeNode(function, _parameters); } else { _functionFunctionRuntimeNode = (FunctionRuntimeTreeNode)FunctionTreeBuilder.Build(_serializedFunction); } } } } } } } ================================================ FILE: Composite/Functions/HelpDefinition.cs ================================================ using System.Xml.Linq; using System; using Composite.Functions.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class HelpDefinition { /// <exclude /> public HelpDefinition GetLocalized() { if (this.HelpText.StartsWith("${")) { return new HelpDefinition(StringResourceSystemFacade.ParseString(this.HelpText)); } else { return new HelpDefinition(this.HelpText); } } /// <exclude /> public HelpDefinition(string helpText) { this.HelpText = helpText; } /// <exclude /> public string HelpText { get; private set; } /// <exclude /> public XElement Serialize() { XElement element = XElement.Parse(string.Format(@"<f:{0} xmlns:f=""{1}"" />", FunctionTreeConfigurationNames.HelpDefinitionTagName, FunctionTreeConfigurationNames.NamespaceName)); element.Add(new XAttribute(FunctionTreeConfigurationNames.HelpTextAttributeName, this.HelpText)); return element; } /// <exclude /> public static HelpDefinition Deserialize(XElement serializedHelpDefinition) { if (serializedHelpDefinition == null) throw new ArgumentNullException("serializedHelpDefinition"); if (serializedHelpDefinition.Name.LocalName != FunctionTreeConfigurationNames.HelpDefinitionTagName) throw new ArgumentException("Wrong serialized format"); XAttribute helpTextAttribute = serializedHelpDefinition.Attribute(FunctionTreeConfigurationNames.HelpTextAttributeName); if (helpTextAttribute == null) throw new ArgumentException("Wrong serialized format"); return new HelpDefinition(helpTextAttribute.Value); } } } ================================================ FILE: Composite/Functions/ICompoundFunction.cs ================================================ namespace Composite.Functions { /// <summary> /// Indicates that a function is allowed to have recursive calls. /// </summary> internal interface ICompoundFunction: IMetaFunction { bool AllowRecursiveCall { get; } } } ================================================ FILE: Composite/Functions/IDowncastableFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Composite.Functions { internal interface IDowncastableFunction : IFunction { bool ReturnValueIsDowncastable { get; } } } ================================================ FILE: Composite/Functions/IDynamicFunction.cs ================================================ namespace Composite.Functions { /// <summary> /// Allows defining whether function results should be cached during the donut caching. /// </summary> public interface IDynamicFunction : IFunction { /// <summary> /// Indicates whether the function output can be cached. /// </summary> bool PreventFunctionOutputCaching { get; } } } ================================================ FILE: Composite/Functions/IFunction.cs ================================================ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IFunction : IMetaFunction { /// <exclude /> object Execute(ParameterList parameters, FunctionContextContainer context); } internal static class IFunctionOverloads { public static T Execute<T>(this IFunction function, NameValueCollection parameters) { return FunctionFacade.Execute<T>(function, parameters); ; } } } ================================================ FILE: Composite/Functions/IFunctionInitializationInfo.cs ================================================ namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IFunctionInitializationInfo: IMetaFunction { /// <exclude /> bool FunctionInitializedCorrectly { get; } } } ================================================ FILE: Composite/Functions/IFunctionResultToXEmbedableMapper.cs ================================================ using System.Xml.Linq; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IFunctionResultToXEmbedableMapper { /// <exclude /> bool TryMakeXEmbedable(FunctionContextContainer contextContainer, object resultObject, out XNode resultElement); } } ================================================ FILE: Composite/Functions/IMetaFunction.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IMetaFunction { /// <exclude /> string Name { get; } /// <exclude /> string Namespace { get; } /// <exclude /> string Description { get; } /// <exclude /> Type ReturnType { get; } /// <exclude /> IEnumerable<ParameterProfile> ParameterProfiles { get; } /// <exclude /> EntityToken EntityToken { get; } } } ================================================ FILE: Composite/Functions/IMetaFunctionExtensionMethods.cs ================================================ using System.Collections.Generic; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class IMetaFunctionExtensionMethods { /// <exclude /> public static string CompositeName(this IMetaFunction metaFunction) { return CompositeName(metaFunction.Namespace, metaFunction.Name); } /// <exclude /> public static string CompositeName(string namespaceName, string name) { return StringExtensionMethods.CreateNamespace(namespaceName, name, '.'); } /// <exclude /> public static bool IsNamespaceCorrectFormat(this IMetaFunction metaFunction) { if (metaFunction.Namespace == "") return true; if (metaFunction.Namespace.StartsWith(".") || metaFunction.Namespace.EndsWith(".")) { return false; } string[] splits = metaFunction.Namespace.Split('.'); foreach (string split in splits) { if (split == "") return false; } return true; } /// <exclude /> public static bool ValidateParameterProfiles(this IMetaFunction metaFunction) { List<string> names = new List<string>(); foreach (ParameterProfile parameterProfile in metaFunction.ParameterProfiles) { if (names.Contains(parameterProfile.Name)) { return false; } names.Add(parameterProfile.Name); } return true; } /// <exclude /> public static string DescriptionLocalized(this IMetaFunction function) { if (function.Description != null && function.Description.Contains("${")) { return StringResourceSystemFacade.ParseString(function.Description); } return function.Description; } } } ================================================ FILE: Composite/Functions/IRoutedDataUrlMapper.cs ================================================ using Composite.Core.Routing; using Composite.Data; namespace Composite.Functions { /// <exclude /> public interface IRoutedDataUrlMapper { /// <exclude /> RoutedDataModel GetRouteDataModel(PageUrlData pageUrlData); /// <exclude /> PageUrlData BuildItemUrl(IData item); } } ================================================ FILE: Composite/Functions/IWidgetFunction.cs ================================================ using System; using System.Xml.Linq; using System.Collections.Generic; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IWidgetFunction : IMetaFunction { /// <exclude /> XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition helpDefinition, string bindingSourceName); } } ================================================ FILE: Composite/Functions/Inline/InlineFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.C1Console.Security; using Composite.Core.Linq; using Composite.Data; using Composite.Data.Types; using Composite.Functions.ManagedParameters; namespace Composite.Functions.Inline { internal class InlineFunction : IFunction, IFunctionInitializationInfo { protected readonly IInlineFunction _function; private IEnumerable<ParameterProfile> _parameterProfile; protected InlineFunction(IInlineFunction info, MethodInfo methodInfo) { Verify.ArgumentNotNull(info, "info"); _function = info; MethodInfo = methodInfo; } public static IFunction Create(IInlineFunction info) { var errors = new StringInlineFunctionCreateMethodErrorHandler(); MethodInfo methodInfo = InlineFunctionHelper.Create(info, null, errors); if (methodInfo == null) return new NotLoadedInlineFunction(info, errors); return new InlineFunction(info, methodInfo); } public virtual object Execute(ParameterList parameters, FunctionContextContainer context) { IList<object> arguments = new List<object>(); foreach (ParameterProfile paramProfile in ParameterProfiles) { arguments.Add(parameters.GetParameter(paramProfile.Name, paramProfile.Type)); } return this.MethodInfo.Invoke(null, arguments.ToArray()); } public string Name { get { return _function.Name; } } public string Namespace { get { return _function.Namespace; } } public string Description { get { return _function.Description; } } public virtual Type ReturnType { get { return MethodInfo.ReturnType; } } public IEnumerable<ParameterProfile> ParameterProfiles { get { if (_parameterProfile == null) { _parameterProfile = ManagedParameterManager.GetParameterProfiles(_function.Id).Evaluate(); } return _parameterProfile; } } virtual protected MethodInfo MethodInfo { get; set; } public EntityToken EntityToken { get { return _function.GetDataEntityToken(); } } bool IFunctionInitializationInfo.FunctionInitializedCorrectly { get { return true; } } } internal class LazyInitializedInlineFunction : InlineFunction, IFunctionInitializationInfo { private readonly Type _cachedReturnType; private bool _initialized; private NotLoadedInlineFunction _notLoadedInlineFunction; public LazyInitializedInlineFunction(IInlineFunction inlineFunction) : base(inlineFunction, null) { } public LazyInitializedInlineFunction(IInlineFunction inlineFunction, Type cachedReturnType) : base(inlineFunction, null) { this._cachedReturnType = cachedReturnType; } public override Type ReturnType { get { return _initialized ? base.ReturnType : _cachedReturnType; } } private void EnsureInitialized() { if (!_initialized) lock (this) if (!_initialized) { Initialize(); _initialized = true; } } private void Initialize() { var errors = new StringInlineFunctionCreateMethodErrorHandler(); MethodInfo methodInfo = InlineFunctionHelper.Create(_function, null, errors); if (methodInfo == null) { _notLoadedInlineFunction = new NotLoadedInlineFunction(_function, errors); } else { MethodInfo = methodInfo; } } protected override MethodInfo MethodInfo { get { EnsureInitialized(); if (_notLoadedInlineFunction != null) { throw new InvalidOperationException("Function hasn't been initialized"); } return base.MethodInfo; } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (_notLoadedInlineFunction != null) { return (_notLoadedInlineFunction as IFunction).Execute(parameters, context); } return base.Execute(parameters, context); } bool IFunctionInitializationInfo.FunctionInitializedCorrectly { get { EnsureInitialized(); return _notLoadedInlineFunction == null; } } } } ================================================ FILE: Composite/Functions/Inline/InlineFunctionCreateMethodErrorHandler.cs ================================================  using System; namespace Composite.Functions.Inline { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class InlineFunctionCreateMethodErrorHandler { /// <exclude /> public virtual bool HasErrors { get { return false; } } /// <exclude /> public virtual void OnCompileError(int line, string errorNumber, string message) { } /// <exclude /> public virtual void OnMissingContainerType(string message) { } /// <exclude /> public virtual void OnNamespaceMismatch(string message) { } /// <exclude /> public virtual void OnMissionMethod(string message) { } /// <exclude /> public virtual void OnLoadSourceError(Exception exception) { } } } ================================================ FILE: Composite/Functions/Inline/InlineFunctionHelper.cs ================================================ using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Web.Hosting; using Composite.Core; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Linq; using Composite.Core.Types; using Composite.Data; using Composite.Data.Types; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Plugins_MethodBasedFunctionProviderElementProvider; namespace Composite.Functions.Inline { /// <summary /> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] public static class InlineFunctionHelper { private static readonly string LogTitle = typeof(InlineFunctionHelper).Name; /// <exclude /> public static string MethodClassContainerName => "InlineMethodFunction"; /// <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; } private static void LogMessageIfNotShuttingDown(IInlineFunction function, string message) { if (!HostingEnvironment.ApplicationHost.ShutdownInitiated()) { Log.LogWarning(LogTitle, $"{function.Namespace}.{function.Name} : {message}"); } } /// <exclude /> public static IEnumerable<string> DefaultAssemblies { get { var systemPath = Path.GetDirectoryName(typeof(String).Assembly.Location); yield return Path.Combine(systemPath, "System.dll"); yield return Path.Combine(systemPath, "System.Core.dll"); yield return Path.Combine(systemPath, "System.Xml.dll"); yield return Path.Combine(systemPath, "System.Xml.Linq.dll"); yield return Path.Combine(systemPath, "System.Web.dll"); yield return Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.BinDirectory), "Composite.dll"); var compositeGeneretedPath = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.BinDirectory), "Composite.Generated.dll"); if (C1File.Exists(compositeGeneretedPath)) { yield return compositeGeneretedPath; } var compositeWorkflowsPath = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.BinDirectory), "Composite.Workflows.dll"); if (C1File.Exists(compositeWorkflowsPath)) { yield return compositeWorkflowsPath; } } } internal static string GetSourceFilePath(this IInlineFunction function) { return Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.InlineCSharpFunctionDirectory), function.CodePath); } /// <exclude /> public static string GetFunctionCode(this IInlineFunction function) { var filepath = GetSourceFilePath(function); // Making 5 attempts to read the file for (var i = 5; i > 0; i--) { try { return C1File.ReadAllText(filepath); } catch (FileNotFoundException) { throw; } catch (IOException) { if (i == 1) throw; Thread.Sleep(100); } } throw new InvalidOperationException("This line should not be reachable"); } /// <exclude /> public static void DeleteFunctionCode(this IInlineFunction function) { var filepath = GetSourceFilePath(function); FileUtils.Delete(filepath); } /// <exclude /> public static void SetFunctionCode(this IInlineFunction function, string content) { var directoryPath = PathUtil.Resolve(GlobalSettingsFacade.InlineCSharpFunctionDirectory); if (C1Directory.Exists(directoryPath) == false) { C1Directory.CreateDirectory(directoryPath); } var filepath = Path.Combine(directoryPath, function.CodePath); C1File.WriteAllText(filepath, content); } /// <exclude /> public static void FunctionRenamed(IInlineFunction newFunction, IInlineFunction oldFunction) { newFunction.UpdateCodePath(); var directoryPath = PathUtil.Resolve(GlobalSettingsFacade.InlineCSharpFunctionDirectory); var oldFilepath = Path.Combine(directoryPath, oldFunction.CodePath); var newFilepath = Path.Combine(directoryPath, newFunction.CodePath); C1File.Move(oldFilepath, newFilepath); } /// <exclude /> public static void UpdateCodePath(this IInlineFunction function) { function.CodePath = function.Namespace; if (string.IsNullOrEmpty(function.CodePath) == false) { function.CodePath += "."; } function.CodePath += function.Name + ".cs"; } /// <exclude /> public static IEnumerable<string> GetReferencableAssemblies() { var path = Path.GetDirectoryName(typeof(String).Assembly.Location); foreach (var file in Directory.GetFiles(path, "System*.dll")) { yield return file; } foreach (var file in AssemblyFacade.GetAssembliesFromBin(true)) { yield return file; } } /// <exclude /> public static string GetAssemblyLocation(string fullPath) { var systemPath = Path.GetDirectoryName(typeof(String).Assembly.Location).ToLowerInvariant(); if (fullPath.ToLowerInvariant().StartsWith(systemPath)) { return "System"; } var binPath = PathUtil.Resolve(GlobalSettingsFacade.BinDirectory).ToLowerInvariant(); if (fullPath.ToLowerInvariant().StartsWith(binPath)) { return "Bin"; } throw new NotImplementedException(); } /// <exclude /> public static string GetAssemblyFullPath(string filename, string location) { location = location.ToLowerInvariant(); switch (location) { case "system": return Path.Combine(Path.GetDirectoryName(typeof(String).Assembly.Location), filename); case "bin": return Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.BinDirectory), filename); default: throw new NotImplementedException(); } } } } ================================================ FILE: Composite/Functions/Inline/NotLoadedInlineFunction.cs ================================================ using System; using System.Collections.Generic; using System.IO; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Xml; using Composite.Data; using Composite.Data.Types; namespace Composite.Functions.Inline { internal class NotLoadedInlineFunction : IFunction, IFunctionInitializationInfo { private readonly IInlineFunction _function; private string[] _sourceCode; private readonly StringInlineFunctionCreateMethodErrorHandler _errors; public NotLoadedInlineFunction(IInlineFunction functionInfo, StringInlineFunctionCreateMethodErrorHandler errors) { Verify.ArgumentCondition(errors.HasErrors, "errors", "No errors information provided"); _function = functionInfo; _errors = errors; } object IFunction.Execute(ParameterList parameters, FunctionContextContainer context) { if (_errors.CompileErrors.Count > 0) { var error = _errors.CompileErrors[0]; var exception = new InvalidOperationException("{1} Line {0}: {2}".FormatWith(error.Item1, error.Item2, error.Item3)); if (_sourceCode == null) { string filepath = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.InlineCSharpFunctionDirectory), _function.CodePath); if (C1File.Exists(filepath)) { _sourceCode = C1File.ReadAllLines(filepath); } else { _sourceCode = new string[0]; } } if (_sourceCode.Length > 0) { XhtmlErrorFormatter.EmbedSourceCodeInformation(exception, _sourceCode, error.Item1); } throw exception; } if (_errors.LoadingException != null) { throw _errors.LoadingException; } throw new InvalidOperationException("Function wasn't loaded due to compilation errors"); } public string Name { get { return _function.Name; } } public string Namespace { get { return _function.Namespace; } } public string Description { get { if (_errors.CompileErrors.Count > 0) { var error = _errors.CompileErrors[0]; return "{1} Line {0}: {2}".FormatWith(error.Item1, error.Item2, error.Item3); } if (_errors.LoadingException != null) { return _errors.LoadingException.Message; } return _function.Description; } } Type IMetaFunction.ReturnType { get { return typeof(void); } } IEnumerable<ParameterProfile> IMetaFunction.ParameterProfiles { get { return new ParameterProfile[0]; } } bool IFunctionInitializationInfo.FunctionInitializedCorrectly { get { return false; } } public C1Console.Security.EntityToken EntityToken { get { return _function.GetDataEntityToken(); } } } } ================================================ FILE: Composite/Functions/Inline/StringInlineFunctionCreateMethodErrorHandler.cs ================================================ using System; using System.Collections.Generic; namespace Composite.Functions.Inline { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class StringInlineFunctionCreateMethodErrorHandler : InlineFunctionCreateMethodErrorHandler { bool _hasErrors; /// <exclude /> public StringInlineFunctionCreateMethodErrorHandler() { _hasErrors = false; this.CompileErrors = new List<Tuple<int, string, string>>(); } /// <exclude /> public List<Tuple<int, string, string>> CompileErrors { get; set; } /// <exclude /> public string MissingContainerType { get; set; } /// <exclude /> public string NamespaceMismatch { get; set; } /// <exclude /> public string MissionMethod { get; set; } /// <exclude /> public Exception LoadingException { get; set; } /// <exclude /> public override bool HasErrors { get { return _hasErrors; } } /// <exclude /> public override void OnCompileError(int line, string errorNumber, string message) { _hasErrors = true; this.CompileErrors.Add(new Tuple<int, string, string>(line, errorNumber, message)); } /// <exclude /> public override void OnMissingContainerType(string message) { _hasErrors = true; this.MissingContainerType = message; } /// <exclude /> public override void OnNamespaceMismatch(string message) { _hasErrors = true; this.NamespaceMismatch = message; } /// <exclude /> public override void OnMissionMethod(string message) { _hasErrors = true; this.MissionMethod = message; } /// <exclude /> public override void OnLoadSourceError(Exception exception) { _hasErrors = true; LoadingException = exception; } } } ================================================ FILE: Composite/Functions/ManagedParameters/ManagedParameterDefinition.cs ================================================ using System; namespace Composite.Functions.ManagedParameters { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Serializable()] public sealed class ManagedParameterDefinition { /// <exclude /> public ManagedParameterDefinition() { this.Id = Guid.NewGuid(); this.HelpText = ""; this.Position = -1; } /// <exclude /> public Guid Id { get; set; } /// <exclude /> public string Name { get; set; } /// <exclude /> public string Label { get; set; } /// <exclude /> public string HelpText { get; set; } /// <exclude /> public int Position { get; set; } /// <exclude /> public Type Type { get; set; } /// <exclude /> public string WidgetFunctionMarkup { get; set; } /// <exclude /> public string DefaultValueFunctionMarkup { get; set; } /// <exclude /> public string TestValueFunctionMarkup { get; set; } } } ================================================ FILE: Composite/Functions/ManagedParameters/ManagedParameterManager.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Transactions; using System.Xml.Linq; using Composite.Data; using Composite.Data.Types; using Composite.Core.Extensions; using Composite.Data.Transactions; using Composite.Core.Types; namespace Composite.Functions.ManagedParameters { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class ManagedParameterManager { /// <exclude /> public static IEnumerable<ManagedParameterDefinition> Load(Guid ownerId) { return (from parameter in DataFacade.GetData<IParameter>().AsEnumerable() where parameter.OwnerId == ownerId orderby parameter.Position select BuildParameterDefinition(parameter)).ToList(); } /// <exclude /> public static void Save(Guid ownerId, IEnumerable<ManagedParameterDefinition> parameterDefinitions) { var dataParams = new List<IParameter>(); foreach (ManagedParameterDefinition paramDef in parameterDefinitions) { ValidateParameter(paramDef); dataParams.Add(BuildIParameter(ownerId, paramDef)); } using (TransactionScope transationScope = TransactionsFacade.CreateNewScope()) { DataFacade.Delete<IParameter>(f => f.OwnerId == ownerId); foreach (IParameter param in dataParams) { DataFacade.AddNew<IParameter>(param); } transationScope.Complete(); } } /// <exclude /> public static IEnumerable<ParameterProfile> GetParameterProfiles(Guid ownerId) { return new ManagedParameterProfiles(ownerId); } /// <exclude /> public static IEnumerable<ParameterProfile> GetParameterProfiles(IEnumerable<ManagedParameterDefinition> parameterDefinitions) { var dataParams = new List<IParameter>(); foreach (ManagedParameterDefinition paramDef in parameterDefinitions) { ValidateParameter(paramDef); dataParams.Add(BuildIParameter(Guid.Empty, paramDef)); } return new ManagedParameterProfiles(dataParams); } /// <exclude /> public static ParameterList GetParametersListForTest(IEnumerable<ManagedParameterDefinition> parameterDefinitions) { ParameterList parameterList = new ParameterList(null); foreach (var parameterDefinition in parameterDefinitions) { if (!parameterDefinition.TestValueFunctionMarkup.IsNullOrEmpty()) { FunctionRuntimeTreeNode functionNode = (FunctionRuntimeTreeNode)FunctionTreeBuilder.Build(XElement.Parse(parameterDefinition.TestValueFunctionMarkup)); FunctionValueProvider valueProvider = new FunctionValueProvider(functionNode); object value = valueProvider.GetValue(); parameterList.AddConstantParameter(parameterDefinition.Name, value, parameterDefinition.Type); } else if (!parameterDefinition.DefaultValueFunctionMarkup.IsNullOrEmpty()) { FunctionRuntimeTreeNode functionNode = (FunctionRuntimeTreeNode)FunctionTreeBuilder.Build(XElement.Parse(parameterDefinition.DefaultValueFunctionMarkup)); FunctionValueProvider valueProvider = new FunctionValueProvider(functionNode); object value = valueProvider.GetValue(); parameterList.AddConstantParameter(parameterDefinition.Name, value, parameterDefinition.Type); } else throw new InvalidOperationException("Parameter '{0}' have neigther 'test value' nor 'default value' specified.".FormatWith(parameterDefinition.Name)); } return parameterList; } private static void ValidateParameter(ManagedParameterDefinition parameterDefinition) { if (string.IsNullOrEmpty(parameterDefinition.Name)) throw new InvalidOperationException("Name property can not be null or an empty string"); if (parameterDefinition.Type == null) throw new InvalidOperationException("Type property can not be null"); if (string.IsNullOrEmpty(parameterDefinition.Label)) throw new InvalidOperationException("Parameter '{0}' has an empty 'Label' field".FormatWith(parameterDefinition.Name)); } private static IParameter BuildIParameter(Guid ownerId, ManagedParameterDefinition parameterDefinition) { IParameter newParam = DataFacade.BuildNew<IParameter>(); newParam.OwnerId = ownerId; newParam.ParameterId = parameterDefinition.Id; newParam.Name = parameterDefinition.Name; newParam.TypeManagerName = TypeManager.SerializeType( parameterDefinition.Type); newParam.Label = parameterDefinition.Label; newParam.HelpText = parameterDefinition.HelpText; newParam.Position = parameterDefinition.Position; newParam.WidgetFunctionMarkup = parameterDefinition.WidgetFunctionMarkup; newParam.DefaultValueFunctionMarkup = parameterDefinition.DefaultValueFunctionMarkup; newParam.TestValueFunctionMarkup = parameterDefinition.TestValueFunctionMarkup; return newParam; } private static ManagedParameterDefinition BuildParameterDefinition(IParameter parameterData) { ManagedParameterDefinition paramDef = new ManagedParameterDefinition(); paramDef.Id = parameterData.ParameterId; paramDef.Name = parameterData.Name; paramDef.Type = TypeManager.GetType(parameterData.TypeManagerName); paramDef.Label = parameterData.Label; paramDef.HelpText = parameterData.HelpText; paramDef.Position = parameterData.Position; paramDef.WidgetFunctionMarkup = parameterData.WidgetFunctionMarkup; paramDef.DefaultValueFunctionMarkup = parameterData.DefaultValueFunctionMarkup; paramDef.TestValueFunctionMarkup = parameterData.TestValueFunctionMarkup; return paramDef; } private class ManagedParameterProfiles : IEnumerable<ParameterProfile> { private readonly Guid _ownerId; private List<ParameterProfile> _parameterProfiles; private static readonly object _syncRoot = new object(); private static List<IParameter> _parameterCache; static ManagedParameterProfiles() { DataEventSystemFacade.SubscribeToStoreChanged<IParameter>((a, b) => ClearParametersCache(), true); } public ManagedParameterProfiles(Guid ownerId) { _ownerId = ownerId; } public ManagedParameterProfiles(IEnumerable<IParameter> parameters) { _parameterProfiles = new List<ParameterProfile>(); foreach (var parameter in parameters) { ParameterProfile pp = BuildParameterProfile(parameter); _parameterProfiles.Add(pp); } } public IEnumerator<ParameterProfile> GetEnumerator() { Initialize(); return _parameterProfiles.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { Initialize(); return _parameterProfiles.GetEnumerator(); } private void Initialize() { if (_parameterProfiles == null) { lock (this) { if (_parameterProfiles == null) { _parameterProfiles = GetParameters(); } } } } private List<ParameterProfile> GetParameters() { var result = new List<ParameterProfile>(); var parameters = from parameter in GetParametersCached() where parameter.OwnerId == _ownerId orderby parameter.Position select parameter; foreach (var parameter in parameters) { result.Add(BuildParameterProfile(parameter)); } return result; } private static void ClearParametersCache() { lock(_syncRoot) { _parameterCache = null; } } private static IEnumerable<IParameter> GetParametersCached() { var parameters = _parameterCache; if (parameters != null) return parameters; lock(_syncRoot) { if (_parameterCache == null) { _parameterCache = DataFacade.GetData<IParameter>().ToList(); } parameters = _parameterCache; } return parameters; } private ParameterProfile BuildParameterProfile(IParameter parameter) { Type parameterType = TypeManager.GetType(parameter.TypeManagerName); bool isRequired = false; BaseValueProvider defaultValueProvider; if (string.IsNullOrEmpty(parameter.DefaultValueFunctionMarkup)) { defaultValueProvider = new NoValueValueProvider(); isRequired = true; } else { defaultValueProvider = new FunctionValueProvider(XElement.Parse(parameter.DefaultValueFunctionMarkup)); } WidgetFunctionProvider widgetFunctionProvider; if (string.IsNullOrEmpty(parameter.WidgetFunctionMarkup) == false) { widgetFunctionProvider = new WidgetFunctionProvider(XElement.Parse(parameter.WidgetFunctionMarkup)); } else { widgetFunctionProvider = WidgetFunctionProvider.BuildNoWidgetProvider(); } return new ParameterProfile(parameter.Name, parameterType, isRequired, defaultValueProvider, widgetFunctionProvider, parameter.Label, new HelpDefinition(parameter.HelpText)); } } } } ================================================ FILE: Composite/Functions/NamedFunctionCall.cs ================================================ namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class NamedFunctionCall { /// <exclude /> public NamedFunctionCall(string name, BaseFunctionRuntimeTreeNode functionCall) { this.Name = name; this.FunctionCall = functionCall; } /// <exclude /> public string Name { get; set; } /// <exclude /> public BaseFunctionRuntimeTreeNode FunctionCall { get; set; } } } ================================================ FILE: Composite/Functions/NamedFunctionCallValueXmlSerializer.cs ================================================ using System; using System.Linq; using System.Xml.Linq; using Composite.Core.Serialization; namespace Composite.Functions { internal sealed class NamedFunctionCallValueXmlSerializer : IValueXmlSerializer { public bool TrySerialize(Type objectToSerializeType, object objectToSerialize, IXmlSerializer xmlSerializer, out XElement serializedObject) { if (objectToSerializeType == null) throw new ArgumentNullException("objectToSerializeType"); if (xmlSerializer == null) throw new ArgumentNullException("xmlSerializer"); serializedObject = null; if (objectToSerializeType != typeof(NamedFunctionCall)) return false; NamedFunctionCall namedFunctionCall = objectToSerialize as NamedFunctionCall; serializedObject = new XElement("NamedFunctionCall"); if (namedFunctionCall != null) { serializedObject.Add(new XElement("Name", xmlSerializer.Serialize(typeof(string), namedFunctionCall.Name))); if (namedFunctionCall.FunctionCall != null) { serializedObject.Add(new XElement("Value", namedFunctionCall.FunctionCall.Serialize())); } } return true; } public bool TryDeserialize(XElement serializedObject, IXmlSerializer xmlSerializer, out object deserializedObject) { if (serializedObject == null) throw new ArgumentNullException("serializedObject"); if (xmlSerializer == null) throw new ArgumentNullException("xmlSerializer"); deserializedObject = null; if (serializedObject.Name.LocalName != "NamedFunctionCall") return false; NamedFunctionCall namedFunctionCall = new NamedFunctionCall(null, null); XElement nameElement = serializedObject.Element("Name"); if (nameElement != null) { if (nameElement.Elements().Count() != 1) return false; namedFunctionCall.Name = (string)xmlSerializer.Deserialize(nameElement.Elements().Single()); } XElement valueElement = serializedObject.Element("Value"); if (valueElement != null) { if (valueElement.Elements().Count() != 1) return false; object result; try { result = FunctionFacade.BuildTree(valueElement.Elements().Single()); } catch (Exception) { return false; } if ((result is BaseFunctionRuntimeTreeNode) == false) return false; namedFunctionCall.FunctionCall = (BaseFunctionRuntimeTreeNode)result; } deserializedObject = namedFunctionCall; return true; } } } ================================================ FILE: Composite/Functions/NoValueValueProvider.cs ================================================ using System; using System.Xml.Linq; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class NoValueValueProvider : BaseValueProvider { /// <exclude /> public override object GetValue(FunctionContextContainer contextContainer) { throw new InvalidOperationException("No value exists"); } /// <exclude /> public override XObject Serialize() { throw new InvalidOperationException("No value exists"); } } } ================================================ FILE: Composite/Functions/ParameterList.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using Composite.Core.Types; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [DebuggerDisplay("Count = {_parameters.Count}")] public sealed class ParameterList { [DebuggerDisplay("{ValueObject}")] private class StoredParameterReturnValue { public object ValueObject { get; set; } public Type ValueType { get; set; } public bool IsDefaultValue { get; set; } } private readonly FunctionContextContainer _functionContextContainer; private readonly Dictionary<string, StoredParameterReturnValue> _parameters = new Dictionary<string, StoredParameterReturnValue>(); private static readonly MethodInfo NewLazyObjectMethodInfo = StaticReflection.GetGenericMethodInfo(() => NewLazyObject<object>(null)); /// <exclude /> public ParameterList(FunctionContextContainer functionContextContainer) { _functionContextContainer = functionContextContainer; } /// <exclude /> public IEnumerable<string> AllParameterNames { get { return _parameters.Keys; } } /// <exclude /> public T GetParameter<T>(string parameterName) { object value = GetParameter(parameterName); if (value == null || value is T) { return (T)value; } return ValueTypeConverter.Convert<T>(value); } /// <exclude /> public bool TryGetParameter<T>(string parameterName, out T value) { object objectValue; bool found = TryGetParameter(parameterName, out objectValue); if (!found) { value = default(T); return false; } if (objectValue == null || objectValue is T) { value = (T)objectValue; } else { value = ValueTypeConverter.Convert<T>(objectValue); } return true; } /// <exclude /> public object GetParameter(string parameterName, Type targetType) { object value = GetParameter(parameterName); if (value != null && !targetType.IsInstanceOfType(value)) { return ValueTypeConverter.Convert(value, targetType); } return value; } /// <exclude /> public object GetParameter(string parameterName) { object value; if (!TryGetParameter(parameterName, out value)) throw new ArgumentException(string.Format("No parameter named '{0}' exists", parameterName)); return value; } /// <summary> /// Fetches the tree node object of a parameter, if available. In contrast to the TryGetValue() function /// this will give you the 'value definition' rather than the result of calling it. /// </summary> /// <param name="parameterName">Name of the parameter</param> /// <param name="runtimeTreeNode"></param> /// <returns></returns> public bool TryGetParameterRuntimeTreeNode(string parameterName, out BaseRuntimeTreeNode runtimeTreeNode) { StoredParameterReturnValue storedParameterReturnValue; bool paramFound = _parameters.TryGetValue(parameterName, out storedParameterReturnValue); bool valueIsTreeNode = paramFound && storedParameterReturnValue.ValueObject is BaseRuntimeTreeNode; if (!valueIsTreeNode) { runtimeTreeNode = null; return false; } runtimeTreeNode = (BaseRuntimeTreeNode) storedParameterReturnValue.ValueObject; return true; } /// <exclude /> public bool TryGetParameter(string parameterName, out object value) { StoredParameterReturnValue storedParameterReturnValue; bool parameterFound = _parameters.TryGetValue(parameterName, out storedParameterReturnValue); if (!parameterFound) { value = null; return false; } object valueObject = storedParameterReturnValue.ValueObject; var parameterType = storedParameterReturnValue.ValueType; if (parameterType.IsGenericType && parameterType.GetGenericTypeDefinition() == typeof (Lazy<>)) { Type genericArgument = parameterType.GetGenericArguments()[0]; value = CreateLazyObject(() => EvaluateTreeNode(valueObject, genericArgument, _functionContextContainer), genericArgument); } else { value = EvaluateTreeNode(valueObject, parameterType, _functionContextContainer); } return true; } private static object EvaluateTreeNode(object node, Type type, FunctionContextContainer functionContextContainer) { if (node is BaseRuntimeTreeNode) { node = ((BaseRuntimeTreeNode)node).GetValue(functionContextContainer, type); } if (node != null && !type.IsInstanceOfType(node)) { node = ValueTypeConverter.Convert(node, type); } return node; } private static object CreateLazyObject(Func<object> func, Type type) { return NewLazyObjectMethodInfo.MakeGenericMethod(type).Invoke(null, new object[] { func }); } private static Lazy<T> NewLazyObject<T>(Func<object> func) { return new Lazy<T>(() => (T) func(), true); } /// <exclude /> public bool IsDefaultValue(string parameterName) { return _parameters[parameterName].IsDefaultValue; } /// <exclude /> public void AddConstantParameter(string parameterName, object value, Type parameterType, bool isDefaultValue = false) { Verify.That(!_parameters.ContainsKey(parameterName), "Parameter '{0}' has already been assigned", parameterName); _parameters.Add(parameterName, new StoredParameterReturnValue { ValueObject = value, ValueType = parameterType, IsDefaultValue = isDefaultValue}); } /// <exclude /> public void AddLazyParameter(string parameterName, BaseRuntimeTreeNode runtimeTreeNode, Type parameterType) { Verify.That(!_parameters.ContainsKey(parameterName), "Parameter '{0}' has already been assigned", parameterName); _parameters.Add(parameterName, new StoredParameterReturnValue { ValueObject = runtimeTreeNode, ValueType = parameterType, IsDefaultValue = false }); } } } ================================================ FILE: Composite/Functions/ParameterProfile.cs ================================================ using System; using System.Collections.Generic; using Composite.Core; using Composite.Core.Application; using Composite.Core.Types; using Composite.Data; using Composite.Core.ResourceSystem; using Composite.Core.Extensions; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ParameterProfile { private readonly WidgetFunctionProvider _widgetFunctionProvider; private Dictionary<string, object> _widgetFunctionRuntimeParameters; private bool? _isInjectedValue; /// <exclude /> public ParameterProfile(string name, Type type, bool isRequired, BaseValueProvider fallbackValueProvider, WidgetFunctionProvider widgetFunctionProvider, string label, HelpDefinition helpDefinition) : this(name, type, isRequired, fallbackValueProvider, widgetFunctionProvider, label, helpDefinition, false) { } /// <exclude /> public ParameterProfile( string name, Type type, bool isRequired, BaseValueProvider fallbackValueProvider, WidgetFunctionProvider widgetFunctionProvider, string label, HelpDefinition helpDefinition, bool hideInSimpleView) { Verify.ArgumentNotNull(name, "name"); Verify.ArgumentNotNull(type, "type"); Verify.ArgumentNotNull(fallbackValueProvider, "fallbackValueProvider"); Verify.ArgumentCondition(!label.IsNullOrEmpty(), "label", "label may not be null or an empty string"); Verify.ArgumentNotNull(helpDefinition, "helpDefinition"); this.Name = name; this.Type = type; this.IsRequired = isRequired && (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(NullableDataReference<>)); this.FallbackValueProvider = fallbackValueProvider; _widgetFunctionProvider = widgetFunctionProvider; this.Label = label; this.HelpDefinition = helpDefinition; this.HideInSimpleView = hideInSimpleView; } /// <exclude /> public ParameterProfile( string name, Type type, bool isRequired, BaseValueProvider fallbackValueProvider, WidgetFunctionProvider widgetFunctionProvider, Dictionary<string,object> widgetFunctionRuntimeParameters, string label, HelpDefinition helpDefinition) : this( name, type, isRequired, fallbackValueProvider, widgetFunctionProvider, label, helpDefinition ) { _widgetFunctionRuntimeParameters = widgetFunctionRuntimeParameters; } /// <summary> /// Shows whether the value for the parameter can be dynamically provided. /// </summary> public bool IsInjectedValue { get { if (_isInjectedValue == null) { var type = Type; _isInjectedValue = !type.IsPrimitive && ServiceLocator.HasService(type); } return _isInjectedValue.Value; } } /// <exclude /> public string Name { get; private set; } /// <exclude /> public Type Type { get; private set; } /// <exclude /> public bool IsRequired { get; private set; } /// <exclude /> public BaseValueProvider FallbackValueProvider { get; private set; } /// <exclude /> public bool HideInSimpleView { get; internal set; } /// <exclude /> public IWidgetFunction WidgetFunction { get { return _widgetFunctionProvider != null ? _widgetFunctionProvider.WidgetFunction : null; } } /// <exclude /> public IEnumerable<BaseParameterRuntimeTreeNode> WidgetFunctionParameters { get { return _widgetFunctionProvider.WidgetFunctionParameters; } } //#warning Kill this? // public Dictionary<string,object> WidgetFunctionRuntimeParameters // { // get // { // if (_widgetFunctionRuntimeParameters == null) return null; // Dictionary<string, object> parameters = new Dictionary<string, object>(_widgetFunctionRuntimeParameters); // foreach (BaseParameterRuntimeTreeNode param in _widgetFunctionProvider.WidgetFunctionParameters) // { // if (parameters.ContainsKey(param.Name) == false) // { // parameters.Add(param.Name, param.GetValue()); // } // } // return parameters; // } // } /// <exclude /> public string Label{ get; private set; } /// <exclude /> public HelpDefinition HelpDefinition { get; private set; } /// <exclude /> public object GetDefaultValue() { // Initializing the binding object value = null; try { var fallbackValueProvider = FallbackValueProvider; if (!(fallbackValueProvider is NoValueValueProvider)) { object defaultValue = fallbackValueProvider.GetValue(); if (defaultValue != null) { value = ValueTypeConverter.Convert(defaultValue, this.Type); } } } catch (Exception ex) { Log.LogWarning(typeof(ParameterProfile).Name, ex); } if (value == null) { if (this.Type == typeof(bool)) { value = false; } } return value; } /// <exclude /> public string LabelLocalized { get { return this.Label.StartsWith("${") ? StringResourceSystemFacade.ParseString(this.Label) : this.Label; } } } } ================================================ FILE: Composite/Functions/PathInfoRoutedDataUrlMapper.cs ================================================ using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.C1Console.Elements.ElementProviderHelpers.DataGroupingProviderHelper; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.Routing; using Composite.Core.Routing.Foundation.PluginFacades; using Composite.Core.Types; using Composite.Core.WebClient; using Composite.Data; using DataRouteKind = Composite.Functions.RoutedData.DataRouteKind; namespace Composite.Functions { internal class PathInfoRoutedDataUrlMapper<T> : IRoutedDataUrlMapper where T : class, IData { private readonly Guid _pageId; private readonly DataRouteKind _dataRouteKind; private static PropertyInfo _keyPropertyInfo; private static PropertyInfo _labelPropertyInfo; public PathInfoRoutedDataUrlMapper(Guid pageId, DataRouteKind dataRouteKind) { _pageId = pageId; _dataRouteKind = dataRouteKind; if ((dataRouteKind & DataRouteKind.Key) > 0 && _keyPropertyInfo == null) { // TODO: support for compound keys _keyPropertyInfo = typeof(T).GetKeyProperties() .SingleOrException("No key fields found on data type '{0}''", "Data type '{0}' should have a single key field", typeof(T).FullName); } if ((dataRouteKind & DataRouteKind.Label) > 0 && _labelPropertyInfo == null) { var labelPropertyInfo = typeof(T).GetLabelPropertyInfo(); Verify.IsNotNull(labelPropertyInfo, "No label property defined for type '{0}'", typeof(T)); Verify.That(labelPropertyInfo.PropertyType == typeof(string), "Not string label fields aren't supported. Label property '{0}', data type '{1}'", labelPropertyInfo.Name, typeof(T)); _labelPropertyInfo = labelPropertyInfo; } } public RoutedDataModel GetRouteDataModel(PageUrlData pageUrlData) { string pathInfo = pageUrlData.PathInfo; if (pathInfo.IsNullOrEmpty()) { return new RoutedDataModel(GetListQueryable); } switch (_dataRouteKind) { case DataRouteKind.Key: case DataRouteKind.KeyAndLabel: { string key; string label = null; if (_dataRouteKind == DataRouteKind.KeyAndLabel) { string[] parts = pathInfo.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length > 2) { return new RoutedDataModel(); } key = parts[0]; label = parts.Length == 2 ? parts[1] : null; } else { if (pathInfo.Length < 2 || pathInfo.LastIndexOf('/') > 0) { return new RoutedDataModel(); } key = pathInfo.Substring(1); } var keyType = _keyPropertyInfo.PropertyType; bool keyParsed; object keyValue; if (keyType == typeof (Guid)) { Guid guid; keyParsed = UrlUtils.TryExpandGuid(key, out guid) && guid != Guid.Empty; keyValue = guid; } else { keyValue = ValueTypeConverter.Convert(key, keyType); keyParsed = keyValue != null; } if(!keyParsed) { return new RoutedDataModel(); } var data = DataFacade.TryGetDataByUniqueKey<T>(keyValue); return new RoutedDataModel(data); } case DataRouteKind.Label: { if (pathInfo.Length < 2 || pathInfo.LastIndexOf('/') > 0) { return new RoutedDataModel(); } string label = UrlUtils.DecodeUrlInvalidCharacters(pathInfo.Substring(1)); var data = GetDataByLabel(label); return new RoutedDataModel(data); } default: throw new InvalidOperationException("Not supported data url kind: " + _dataRouteKind); } } private IQueryable GetListQueryable() { IQueryable<T> unorderedQuery = DataFacade.GetData<T>(); if (typeof (IPageRelatedData).IsAssignableFrom(typeof (T))) { unorderedQuery = unorderedQuery.Where(t => (t as IPageRelatedData).PageId == _pageId); } return DataGroupingProviderHelper.OrderData(unorderedQuery, typeof(T)); } public PageUrlData BuildItemUrl(IData dataItem) { Verify.ArgumentNotNull(dataItem, "dataItem"); string keyUrlPart = null; string labelUrlPart = null; if ((_dataRouteKind & DataRouteKind.Key) > 0) { keyUrlPart = GetUrlKey(dataItem); } if ((_dataRouteKind & DataRouteKind.Label) > 0) { labelUrlPart = GetUrlLabel(dataItem, _dataRouteKind == DataRouteKind.KeyAndLabel); } string pathInfo; switch (_dataRouteKind) { case DataRouteKind.Key: pathInfo = "/" + keyUrlPart; break; case DataRouteKind.KeyAndLabel: pathInfo = "/" + keyUrlPart + "/" + labelUrlPart; break; case DataRouteKind.Label: pathInfo = "/" + labelUrlPart; break; default: throw new InvalidOperationException("Not supported data url kind: " + _dataRouteKind); } var culture = LocalizationScopeManager.CurrentLocalizationScope; var publicationScope = DataScopeManager.CurrentDataScope.ToPublicationScope(); return new PageUrlData(_pageId, publicationScope, culture) { PathInfo = pathInfo }; } private static T GetDataByLabel(string label) { var query = DataFacade.GetData<T>(); var parameterExpression = Expression.Parameter(typeof (T)); var labelPropertyExpression = Expression.Property(parameterExpression, _labelPropertyInfo); var equalsExpression = Expression.Equal(labelPropertyExpression, Expression.Constant(label)); var lambdaExpression = Expression.Lambda<Func<T, bool>>(equalsExpression, parameterExpression); var list = query.Where(lambdaExpression).Take(2).ToList(); if (list.Count == 0) { return null; } if (list.Count > 1) { throw new DataUrlCollisionException(typeof(T), new RelativeRoute {PathSegments = new []{label}}); } return list[0]; } private static string LabelToUrlPart(string label, bool allowDataLoss) { return allowDataLoss ? UrlFormattersPluginFacade.FormatUrl(label, true) : UrlUtils.EncodeUrlInvalidCharacters(label); } private static string GetUrlLabel(IData data, bool allowDataLoss) { object labelValue = _labelPropertyInfo.GetValue(data); if (labelValue == null) { return null; } string label = ValueTypeConverter.Convert<string>(labelValue); return string.IsNullOrEmpty(label) ? null : LabelToUrlPart(label, allowDataLoss); } private static string GetUrlKey(IData data) { object keyValue = _keyPropertyInfo.GetValue(data); if (keyValue == null) { return null; } if (keyValue is Guid) { return UrlUtils.CompressGuid((Guid) keyValue); } string urlKey = keyValue.ToString(); return string.IsNullOrEmpty(urlKey) ? null : urlKey; } } } ================================================ FILE: Composite/Functions/Plugins/FunctionProvider/FunctionNotifier.cs ================================================ using Composite.C1Console.Events; using Composite.Core.Configuration; using Composite.Functions.Foundation; namespace Composite.Functions.Plugins.FunctionProvider { /// <summary> /// A function provider can use this class to notify if the providers list of functions /// has been changed. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class FunctionNotifier { internal FunctionNotifier(string providerName) { this.ProviderName = providerName; } /// <exclude /> public void FunctionsUpdated() { if (SystemSetupFacade.SetupIsRunning) { return; } MetaFunctionProviderRegistry.ReinitializeFunctionFromProvider(this.ProviderName); GlobalEventSystemFacade.FireDesignChangeEvent(); } private string ProviderName { get; set; } } } ================================================ FILE: Composite/Functions/Plugins/FunctionProvider/FunctionProviderData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Functions.Plugins.FunctionProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ConfigurationElementType(typeof(NonConfigurableFunctionProvider))] public class FunctionProviderData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/Functions/Plugins/FunctionProvider/IDynamicTypeFunctionProvider.cs ================================================ using System.Collections.Generic; namespace Composite.Functions.Plugins.FunctionProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IDynamicTypeFunctionProvider : IFunctionProvider { /// <exclude /> IEnumerable<IFunction> DynamicTypeDependentFunctions { get; } } } ================================================ FILE: Composite/Functions/Plugins/FunctionProvider/IFunctionProvider.cs ================================================ using System.Collections.Generic; using Composite.Functions.Plugins.FunctionProvider.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Functions.Plugins.FunctionProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [CustomFactory(typeof(FunctionProviderCustomFactory))] [ConfigurationNameMapper(typeof(FunctionProviderDefaultNameRetriever))] public interface IFunctionProvider { /// <exclude /> FunctionNotifier FunctionNotifier { set; } /// <exclude /> IEnumerable<IFunction> Functions { get; } } } ================================================ FILE: Composite/Functions/Plugins/FunctionProvider/NonConfigurableFunctionProvider.cs ================================================ using System; using Microsoft.Practices.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Functions.Plugins.FunctionProvider { [Assembler(typeof(NonConfigurableFunctionProviderAssembler))] internal sealed class NonConfigurableFunctionProvider : FunctionProviderData { } internal sealed class NonConfigurableFunctionProviderAssembler : IAssembler<IFunctionProvider, FunctionProviderData> { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IFunctionProvider Assemble(IBuilderContext context, FunctionProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IFunctionProvider)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/Functions/Plugins/FunctionProvider/Runtime/FunctionProviderCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Functions.Plugins.FunctionProvider.Runtime { internal sealed class FunctionProviderCustomFactory : AssemblerBasedCustomFactory<IFunctionProvider, FunctionProviderData> { protected override FunctionProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { FunctionProviderSettings settings = configurationSource.GetSection(FunctionProviderSettings.SectionName) as FunctionProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", FunctionProviderSettings.SectionName)); } return settings.FunctionProviderPlugins.Get(name); } } } ================================================ FILE: Composite/Functions/Plugins/FunctionProvider/Runtime/FunctionProviderDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Functions.Plugins.FunctionProvider.Runtime { internal sealed class FunctionProviderDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/Functions/Plugins/FunctionProvider/Runtime/FunctionProviderFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Functions.Plugins.FunctionProvider.Runtime { internal sealed class FunctionProviderFactory : NameTypeFactoryBase<IFunctionProvider> { public FunctionProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/Functions/Plugins/FunctionProvider/Runtime/FunctionProviderSettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Functions.Plugins.FunctionProvider.Runtime { internal sealed class FunctionProviderSettings : SerializableConfigurationSection { public const string SectionName = "Composite.Functions.Plugins.FunctionProviderConfiguration"; private const string _dataProviderPluginsProperty = "FunctionProviderPlugins"; [ConfigurationProperty(_dataProviderPluginsProperty)] public NameTypeManagerTypeConfigurationElementCollection<FunctionProviderData> FunctionProviderPlugins { get { return (NameTypeManagerTypeConfigurationElementCollection<FunctionProviderData>)base[_dataProviderPluginsProperty]; } } } } ================================================ FILE: Composite/Functions/Plugins/WidgetFunctionProvider/IDynamicTypeWidgetFunctionProvider.cs ================================================ using System.Collections.Generic; namespace Composite.Functions.Plugins.WidgetFunctionProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IDynamicTypeWidgetFunctionProvider : IWidgetFunctionProvider { /// <exclude /> IEnumerable<IWidgetFunction> DynamicTypeDependentFunctions { get; } } } ================================================ FILE: Composite/Functions/Plugins/WidgetFunctionProvider/IWidgetFunctionProvider.cs ================================================ using System.Collections.Generic; using Composite.Functions.Plugins.WidgetFunctionProvider.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Functions.Plugins.WidgetFunctionProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [CustomFactory(typeof(WidgetFunctionProviderCustomFactory))] [ConfigurationNameMapper(typeof(WidgetFunctionProviderDefaultNameRetriever))] public interface IWidgetFunctionProvider { /// <exclude /> WidgetFunctionNotifier WidgetFunctionNotifier { set; } /// <exclude /> IEnumerable<IWidgetFunction> Functions { get; } } } ================================================ FILE: Composite/Functions/Plugins/WidgetFunctionProvider/NonConfigurableWidgetFunctionProvider.cs ================================================ using System; using Microsoft.Practices.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Functions.Plugins.WidgetFunctionProvider { [Assembler(typeof(NonConfigurableWidgetFunctionProviderAssembler))] internal sealed class NonConfigurableWidgetFunctionProvider : WidgetFunctionProviderData { } internal sealed class NonConfigurableWidgetFunctionProviderAssembler : IAssembler<IWidgetFunctionProvider, WidgetFunctionProviderData> { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IWidgetFunctionProvider Assemble(IBuilderContext context, WidgetFunctionProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return (IWidgetFunctionProvider)Activator.CreateInstance(objectConfiguration.Type); } } } ================================================ FILE: Composite/Functions/Plugins/WidgetFunctionProvider/Runtime/WidgetFunctionProviderCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Functions.Plugins.WidgetFunctionProvider.Runtime { internal sealed class WidgetFunctionProviderCustomFactory : AssemblerBasedCustomFactory<IWidgetFunctionProvider, WidgetFunctionProviderData> { protected override WidgetFunctionProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { WidgetFunctionProviderSettings settings = configurationSource.GetSection(WidgetFunctionProviderSettings.SectionName) as WidgetFunctionProviderSettings; if (null == settings) { throw new ConfigurationErrorsException(string.Format("The configuration section '{0}' was not found in the configuration", WidgetFunctionProviderSettings.SectionName)); } return settings.WidgetFunctionProviderPlugins.Get(name); } } } ================================================ FILE: Composite/Functions/Plugins/WidgetFunctionProvider/Runtime/WidgetFunctionProviderDefaultNameRetriever.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Functions.Plugins.WidgetFunctionProvider.Runtime { internal sealed class WidgetFunctionProviderDefaultNameRetriever : IConfigurationNameMapper { public string MapName(string name, IConfigurationSource configSource) { return null; } } } ================================================ FILE: Composite/Functions/Plugins/WidgetFunctionProvider/Runtime/WidgetFunctionProviderFactory.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Functions.Plugins.WidgetFunctionProvider.Runtime { internal sealed class WidgetFunctionProviderFactory : NameTypeFactoryBase<IWidgetFunctionProvider> { public WidgetFunctionProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/Functions/Plugins/WidgetFunctionProvider/Runtime/WidgetFunctionProviderSettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Functions.Plugins.WidgetFunctionProvider.Runtime { internal sealed class WidgetFunctionProviderSettings : SerializableConfigurationSection { public const string SectionName = "Composite.Functions.Plugins.WidgetFunctionProviderConfiguration"; private const string _dataProviderPluginsProperty = "WidgetFunctionProviderPlugins"; [ConfigurationProperty(_dataProviderPluginsProperty)] public NameTypeManagerTypeConfigurationElementCollection<WidgetFunctionProviderData> WidgetFunctionProviderPlugins { get { return (NameTypeManagerTypeConfigurationElementCollection<WidgetFunctionProviderData>)base[_dataProviderPluginsProperty]; } } } } ================================================ FILE: Composite/Functions/Plugins/WidgetFunctionProvider/WidgetFunctionNotifier.cs ================================================ using Composite.Functions.Foundation; namespace Composite.Functions.Plugins.WidgetFunctionProvider { /// <summary> /// A widget function provider can use this class to notify if the providers list of functions /// has been changed. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class WidgetFunctionNotifier { internal WidgetFunctionNotifier(string providerName) { this.ProviderName = providerName; } /// <exclude /> public void WidgetFunctionsUpdated() { MetaFunctionProviderRegistry.ReinitializeWidgetFunctionFromProvider(this.ProviderName); } private string ProviderName { get; set; } } } ================================================ FILE: Composite/Functions/Plugins/WidgetFunctionProvider/WidgetFunctionProviderData.cs ================================================ using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Functions.Plugins.WidgetFunctionProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ConfigurationElementType(typeof(NonConfigurableWidgetFunctionProvider))] public class WidgetFunctionProviderData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/Functions/Plugins/XslExtensionsProvider/IXslExtensionsProvider.cs ================================================ using System.Collections.Generic; using Composite.Functions.Plugins.FunctionProvider.Runtime; using Composite.Functions.Plugins.XslExtensionsProvider.Runtime; using Composite.Core.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Functions.Plugins.XslExtensionsProvider { [CustomFactory(typeof(XslExtensionsProviderCustomFactory))] [ConfigurationNameMapper(typeof(FunctionProviderDefaultNameRetriever))] internal interface IXslExtensionsProvider { List<Pair<string, object>> CreateExtensions(); } } ================================================ FILE: Composite/Functions/Plugins/XslExtensionsProvider/Runtime/XslExtensionsProviderCustomFactory.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Functions.Plugins.XslExtensionsProvider.Runtime { internal sealed class XslExtensionsProviderCustomFactory : AssemblerBasedCustomFactory<IXslExtensionsProvider, XslExtensionsProviderData> { protected override XslExtensionsProviderData GetConfiguration(string name, IConfigurationSource configurationSource) { XslExtensionsProviderSettings settings = configurationSource.GetSection(XslExtensionsProviderSettings.SectionName) as XslExtensionsProviderSettings; if (null == settings) { throw new ConfigurationErrorsException( string.Format("The configuration section '{0}' was not found in the configuration", XslExtensionsProviderSettings.SectionName)); } return settings.XslExtensionProviders.Get(name); } } } ================================================ FILE: Composite/Functions/Plugins/XslExtensionsProvider/Runtime/XslExtensionsProviderFactory.cs ================================================ using Composite.Core.Configuration; using Composite.Functions.Plugins.XslExtensionsProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Functions.Foundation.PluginFacades.Runtime { internal sealed class XslExtensionsProviderFactory : NameTypeFactoryBase<IXslExtensionsProvider> { public XslExtensionsProviderFactory() : base(ConfigurationServices.ConfigurationSource) { } } } ================================================ FILE: Composite/Functions/Plugins/XslExtensionsProvider/Runtime/XslExtensionsProviderSettings.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Functions.Plugins.XslExtensionsProvider.Runtime { internal sealed class XslExtensionsProviderSettings : SerializableConfigurationSection { public const string SectionName = "Composite.Functions.Plugins.XslExtensionsProviderConfiguration"; private const string _dataProviderPluginsProperty = "XslExtensionProviders"; [ConfigurationProperty(_dataProviderPluginsProperty)] public NameTypeManagerTypeConfigurationElementCollection<XslExtensionsProviderData> XslExtensionProviders { get { return (NameTypeManagerTypeConfigurationElementCollection<XslExtensionsProviderData>)base[_dataProviderPluginsProperty]; } } } } ================================================ FILE: Composite/Functions/Plugins/XslExtensionsProvider/XslExtensionsProviderData.cs ================================================ using Composite.Core.Configuration; namespace Composite.Functions.Plugins.XslExtensionsProvider { internal class XslExtensionsProviderData : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/Functions/RoutedData.cs ================================================ using System; using Composite.Core.WebClient.Renderings.Page; using Composite.Data; using Microsoft.Extensions.DependencyInjection; using Composite.Core.Routing; using Composite.Core.Routing.Pages; using System.Web; using System.Linq; namespace Composite.Functions { /// <summary> /// Parameter return type for functions handling data references passed via url format, defined with attribute on the data types. /// If none defined, it the url format will be the same as in <see cref="RoutedData.ById{T}"/> /// </summary> /// <typeparam name="T"></typeparam> public class RoutedData<T> : PathInfoRoutedData<T> where T : class, IData { /// <exclude /> protected override IRoutedDataUrlMapper GetUrlMapper() { var pageId = PageRenderer.CurrentPageId; Verify.That(pageId != Guid.Empty, "The current page is not set"); IRoutedDataUrlMapper mapper = AttributeBasedRoutedDataUrlMapper.GetDataUrlMapper(typeof(T), pageId); return mapper ?? new PathInfoRoutedDataUrlMapper<T>(pageId, RoutedData.DataRouteKind.Key); } } /// <summary> /// Contains subclasses that can be used as function parameters that provide data routing. /// </summary> public static class RoutedData { [Flags] internal enum DataRouteKind { Key = 1, Label = 2, KeyAndLabel = 3, } /// <summary> /// Registers function parameter types that enable data url routing. /// </summary> /// <param name="serviceCollection"></param> public static void AddRoutedData(this IServiceCollection serviceCollection) { Action<Type> registerType = type => serviceCollection.Add(new ServiceDescriptor(type, type, ServiceLifetime.Scoped)); registerType(typeof(ById<>)); registerType(typeof(ByIdAndLabel<>)); registerType(typeof(ByLabel<>)); registerType(typeof(RoutedData<>)); } /// <summary> /// Parameter return type for functions handling data references passed via url {pageUrl}/{DataId} /// </summary> /// <typeparam name="T">The data type.</typeparam> public class ById<T> : PathInfoRoutedData<T> where T : class, IData { /// <exclude /> protected override IRoutedDataUrlMapper GetUrlMapper() { var page = PageRenderer.CurrentPage; Verify.IsNotNull(page, "The current page is not set"); return new PathInfoRoutedDataUrlMapper<T>(page.Id, DataRouteKind.Key); } } /// <summary> /// Parameter return type for functions handling data references passed via url {pageUrl}/{DataId}/{data label} /// </summary> /// <typeparam name="T">The data type.</typeparam> public class ByIdAndLabel<T> : PathInfoRoutedData<T> where T : class, IData { /// <exclude /> protected override IRoutedDataUrlMapper GetUrlMapper() { var page = PageRenderer.CurrentPage; Verify.IsNotNull(page, "The current page is not set"); return new PathInfoRoutedDataUrlMapper<T>(page.Id, DataRouteKind.KeyAndLabel); } } /// <summary> /// Parameter return type for functions handling data references passed via url {pageUrl}/{data label} /// </summary> /// <typeparam name="T">The data type.</typeparam> public class ByLabel<T> : PathInfoRoutedData<T> where T : class, IData { /// <exclude /> protected override IRoutedDataUrlMapper GetUrlMapper() { var page = PageRenderer.CurrentPage; Verify.IsNotNull(page, "The current page is not set"); // return new LabelDataUrlMapper(page); return new PathInfoRoutedDataUrlMapper<T>(page.Id, DataRouteKind.Label); } } /// <summary> /// Gets a instance of a <see cref="IDataUrlMapper"/> that can map data references to URLs of with the following format "/{page URL}/{data ID}" /// </summary> /// <param name="pageId">The page id.</param> /// <param name="dataType">The data type.</param> /// <returns></returns> public static IDataUrlMapper GetRoutedByIdDataUrlMapper(Guid pageId, Type dataType) { return GetMapperByType(dataType, pageId, DataRouteKind.Key); } /// <summary> /// Gets a instance of a <see cref="IDataUrlMapper"/> that can map data references to URLs of with the following format "/{page URL}/{data item label}" /// </summary> /// <param name="pageId">The page id.</param> /// <param name="dataType">The data type.</param> /// <returns></returns> public static IDataUrlMapper GetRoutedByLabelDataUrlMapper(Guid pageId, Type dataType) { return GetMapperByType(dataType, pageId, DataRouteKind.Label); } /// <summary> /// Gets a instance of a <see cref="IDataUrlMapper"/> that can map data references to URLs of with the following format "/{page URL}/{data ID}/{data item label}" /// </summary> /// <param name="pageId">The page id.</param> /// <param name="dataType">The data type.</param> /// <returns></returns> public static IDataUrlMapper GetRoutedByIdAndLabelDataUrlMapper(Guid pageId, Type dataType) { return GetMapperByType(dataType, pageId, DataRouteKind.KeyAndLabel); } /// <summary> /// Get a default <see cref="IDataUrlMapper"/> for the given data type. /// </summary> /// <param name="pageId">The page id.</param> /// <param name="dataType">The data type.</param> /// <returns></returns> public static IDataUrlMapper GetDefaultDataUrlMapper(Guid pageId, Type dataType) { IRoutedDataUrlMapper mapper = AttributeBasedRoutedDataUrlMapper.GetDataUrlMapper(dataType, pageId); if (mapper == null) { return GetRoutedByIdDataUrlMapper(pageId, dataType); } return new RoutedDataUrlMapperAdapter(mapper); } private static IDataUrlMapper GetMapperByType(Type dataType, Guid pageId, DataRouteKind routeKind) { Verify.ArgumentNotNull(dataType, "dataType"); Verify.ArgumentCondition(pageId != Guid.Empty, "pageId", "An empty guid is not allowed here"); // TODO: use static reflection here var constructor = typeof (PathInfoRoutedDataUrlMapper<>) .MakeGenericType(dataType) .GetConstructor(new [] {typeof (Guid), typeof (DataRouteKind)}); Verify.IsNotNull(constructor, "Failed to get PathInfoRoutedDataUrlMapper constructor"); var routedDataUrlMapper = (IRoutedDataUrlMapper) constructor.Invoke(new object[] {pageId, routeKind}); return new RoutedDataUrlMapperAdapter(routedDataUrlMapper); } internal class RoutedDataUrlMapperAdapter : IDataUrlMapper { private readonly IRoutedDataUrlMapper _mapper; public RoutedDataUrlMapperAdapter(IRoutedDataUrlMapper mapper) { _mapper = mapper; } public IDataReference GetData(PageUrlData pageUrlData) { var model = _mapper.GetRouteDataModel(pageUrlData); return model.IsRouteResolved && model.IsItem ? model.Item.ToDataReference() : null; } public PageUrlData GetPageUrlData(IDataReference instance) { var data = instance.Data; return data != null ? _mapper.BuildItemUrl(data) : null; } } } /// <exclude /> public class RoutedDataModel { /// <exclude /> public RoutedDataModel() { } /// <exclude /> public RoutedDataModel(IData item) { Item = item; IsItem = item != null; IsRouteResolved = item != null; } /// <exclude /> public RoutedDataModel(Func<IQueryable> getQueryable) { QueryableBuilder = getQueryable; IsRouteResolved = true; } /// <exclude /> public bool IsRouteResolved { get; protected set; } /// <exclude /> public bool IsItem { get; protected set; } /// <exclude /> public IData Item { get; protected set; } /// <exclude /> public Func<IQueryable> QueryableBuilder { get; protected set; } } /// <summary> /// Base class for return type of a data parameter. /// </summary> /// <typeparam name="T"></typeparam> public abstract class PathInfoRoutedData<T> where T : class, IData { private RoutedDataModel _model; /// <summary> /// Creates an instace of <see cref="PathInfoRoutedData{T}"/> /// </summary> protected PathInfoRoutedData() { var urlMapper = GetUrlMapper(); Verify.IsNotNull(urlMapper, "UrlMapper is null"); DataUrls.RegisterDynamicDataUrlMapper(PageRenderer.CurrentPageId, typeof(T), new RoutedData.RoutedDataUrlMapperAdapter(urlMapper)); var pageUrlData = C1PageRoute.PageUrlData; RoutedDataModel model; try { model = urlMapper.GetRouteDataModel(pageUrlData) ?? new RoutedDataModel(); } catch (DataUrlCollisionException) { C1PageRoute.RegisterPathInfoUsage(); throw; } SetModel(model); if (!string.IsNullOrEmpty(pageUrlData.PathInfo) && model.IsRouteResolved) { if (model.IsItem) { var canonicalUrlData = urlMapper.BuildItemUrl(model.Item); if (canonicalUrlData.PathInfo != pageUrlData.PathInfo) { string newUrl = PageUrls.BuildUrl(canonicalUrlData); if (newUrl != null) { PermanentRedirect(newUrl); } } } C1PageRoute.RegisterPathInfoUsage(); } } private static void PermanentRedirect(string url) { var response = HttpContext.Current.Response; response.AddHeader("Location", url); response.StatusCode = 301; // "Moved Permanently" response.End(); } /// <exclude /> protected abstract IRoutedDataUrlMapper GetUrlMapper(); /// <summary> /// Sets the data model. /// </summary> /// <param name="model">The data model.</param> protected virtual void SetModel(RoutedDataModel model) { _model = model; } /// <summary> /// A data item to be shown in a detail view. /// </summary> public virtual T Item { get { var model = Model; Verify.That(model.IsItem, "This property should not be called when IsDetailView is false"); return (T)model.Item; } } /// <summary> /// Indicates whether the route has been resolved. /// </summary> public bool IsRouteResolved { get { return Model.IsRouteResolved; } } /// <summary> /// Indicates whether a detail view should be shown /// </summary> public bool IsItem { get { return Model.IsItem; } } /// <summary> /// Indicates whether a list view should be shown /// </summary> public bool IsList { get { return Model.IsRouteResolved && !Model.IsItem; } } /// <summary> /// Returns a filtered list of data items. /// </summary> public virtual IQueryable<T> List { get { var model = Model; if (!model.IsRouteResolved) { return Enumerable.Empty<T>().AsQueryable(); } return model.IsItem ? (new[] { (T)model.Item }).AsQueryable() : (IQueryable<T>)model.QueryableBuilder(); } } /// <summary> /// Returns a public url to the specified data item. /// </summary> /// <param name="data">The data item.</param> /// <returns></returns> public virtual string ItemUrl(IData data) { var mapper = GetUrlMapper(); return PageUrls.BuildUrl(mapper.BuildItemUrl(data)); } /// <summary> /// Returns a public url to the specified data item key. /// </summary> /// <param name="key">The key value.</param> /// <returns></returns> public virtual string ItemUrl(object key) { var data = DataFacade.GetDataByUniqueKey<T>(key); if (data == null) { return null; } var mapper = GetUrlMapper(); return PageUrls.BuildUrl(mapper.BuildItemUrl(data)); } /// <summary> /// Returns a url link to the current page /// </summary> public virtual string ListUrl { get { return PageUrls.BuildUrl(PageRenderer.CurrentPage) ?? PageUrls.BuildUrl(PageRenderer.CurrentPage, UrlKind.Internal); } } /// <summary> /// Returns a currently resolved model. /// </summary> protected virtual RoutedDataModel Model { get { Verify.IsNotNull(_model, "The model object is not set"); return _model; } } } } ================================================ FILE: Composite/Functions/StandardFunctionSecurityAncestorProvider.cs ================================================ using System.Collections.Generic; using System.Linq; using Composite.C1Console.Security; using Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider; namespace Composite.Functions { /// <summary> /// Use this security ancestor provider for custom functions that /// will be an element under the 'All Functions' section in the C1 console. /// This provider assumes that the full name of the function, including namespace, /// is stored in the Id property of the entity token. /// Example: /// entityToken.Id = "Composite.Forms.Renderer" /// NOTE: That this might have changed if someone changes this in the provider code! /// </summary> public class StandardFunctionSecurityAncestorProvider : ISecurityAncestorProvider { /// <summary> /// Returns a parent entity token for the given function entity token. /// </summary> /// <param name="entityToken"></param> /// <returns></returns> public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { string fullname = entityToken.Id; string providerName = entityToken.Source; if (fullname.Contains('.')) { fullname = fullname.Remove(fullname.LastIndexOf('.')); } string id = BaseFunctionProviderElementProvider.CreateId(fullname, "AllFunctionsElementProvider"); yield return new BaseFunctionFolderElementEntityToken(id); } } } ================================================ FILE: Composite/Functions/StandardFunctions.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Constant; using Composite.Core.Xml; using Composite.Data; using Composite.Core.Extensions; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class StandardFunctions { /// <exclude /> public static IFunction GetDefaultFunctionByType(Type type) { if (type == typeof (string)) return StandardFunctions.StringFunction; if (type == typeof (int) || type == typeof (int?)) return StandardFunctions.IntegerFunction; if (type == typeof (Decimal) || type == typeof (Decimal?)) return StandardFunctions.DecimalFunction; if (type == typeof (DateTime) || type == typeof (DateTime?)) return StandardFunctions.DateTimeFunction; if (type == typeof (Guid) || type == typeof (Guid?)) return StandardFunctions.GuidFunction; if (type == typeof (bool) || type == typeof (bool?)) return StandardFunctions.BooleanFunction; if (type == typeof (XhtmlDocument)) return StandardFunctions.XhtmlDocumentFunction; if (type.IsGenericType) { if (type.GetGenericTypeDefinition() == typeof (NullableDataReference<>)) { var referenceType = type.GetGenericArguments().First(); var functionName = StringExtensionMethods.CreateNamespace(referenceType.FullName, "GetNullableDataReference"); IFunction function; if (FunctionFacade.TryGetFunction(out function, functionName)) return function; } else if (type.GetGenericTypeDefinition() == typeof (DataReference<>)) { var referenceType = type.GetGenericArguments().First(); var functionName = StringExtensionMethods.CreateNamespace(referenceType.FullName, "GetDataReference"); IFunction function; if (FunctionFacade.TryGetFunction(out function, functionName)) return function; } } return null; } /// <exclude /> public static IFunction StringFunction { get { return FunctionFacade.GetFunction("Composite.Constant.String"); } } /// <exclude /> public static IFunction DateTimeFunction { get { return FunctionFacade.GetFunction("Composite.Utils.Date.Now"); } } /// <exclude /> public static IFunction BooleanFunction { get { return FunctionFacade.GetFunction("Composite.Constant.Boolean"); } } /// <exclude /> public static IFunction DecimalFunction { get { return FunctionFacade.GetFunction("Composite.Constant.Decimal"); } } /// <exclude /> public static IFunction IntegerFunction { get { return FunctionFacade.GetFunction("Composite.Constant.Integer"); } } /// <exclude /> public static IFunction GuidFunction { get { return FunctionFacade.GetFunction("Composite.Constant.Guid"); } } /// <exclude /> public static IFunction XhtmlDocumentFunction { get { return FunctionFacade.GetFunction("Composite.Constant.XhtmlDocument"); } } } } ================================================ FILE: Composite/Functions/StandardWidgetFunctions.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Xml.Linq; using Composite.Core.Types; using Composite.Core.Xml; using Composite.Data; using Composite.Data.Types; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Bool; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.DataReference; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.DataType; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Date; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Decimal; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.GuidWidgetFunctions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Integer; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.String; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class StandardWidgetFunctions { /// <exclude /> public static string GetDefaultWidgetFunctionNameByType(Type type) { WidgetFunctionProvider provider = GetDefaultWidgetFunctionProviderByType(type); if (provider == null) return null; return provider.WidgetFunctionCompositeName; } /// <exclude /> public static WidgetFunctionProvider GetDefaultWidgetFunctionProviderByType(Type type) { return GetDefaultWidgetFunctionProviderByType(type, true); } /// <exclude /> public static WidgetFunctionProvider GetDefaultWidgetFunctionProviderByType(Type type, bool required) { if (type == typeof(string)) return StandardWidgetFunctions.TextBoxWidget; if (type == typeof(int) || type == typeof(int?)) return StandardWidgetFunctions.IntegerTextBoxWidget; if (type == typeof(Decimal) || type == typeof(Decimal?)) return StandardWidgetFunctions.DecimalTextBoxWidget; if (type == typeof(DateTime) || type == typeof(DateTime?)) return StandardWidgetFunctions.DateSelectorWidget; if (type == typeof(Guid) || type == typeof(Guid?)) return StandardWidgetFunctions.GuidTextBoxWidget; if (type == typeof(bool) || type == typeof(bool?)) return StandardWidgetFunctions.CheckBoxWidget; if (type == typeof(DataReference<IImageFile>)) return StandardWidgetFunctions.GetImageSelectorWidget(required); if (type == typeof(NullableDataReference<IImageFile>)) return StandardWidgetFunctions.GetImageSelectorWidget(false); if (type == typeof(DataReference<IMediaFile>)) return StandardWidgetFunctions.GetMediaFileSelectorWidget(required); if (type == typeof(NullableDataReference<IMediaFile>)) return StandardWidgetFunctions.GetMediaFileSelectorWidget(false); if (type == typeof(XhtmlDocument)) return StandardWidgetFunctions.VisualXhtmlDocumentEditorWidget; IEnumerable<string> functionNames = FunctionFacade.GetWidgetFunctionNamesByType(type); foreach (string functionName in functionNames) { IWidgetFunction widgetFunction = FunctionFacade.GetWidgetFunction(functionName); bool sameType = widgetFunction.ReturnType == type; if (!sameType && !required && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(DataReference<>) && type.IsAssignableFrom(widgetFunction.ReturnType) && widgetFunction.ReturnType == typeof(NullableDataReference<>).MakeGenericType(type.GetGenericArguments())) { sameType = true; } if (sameType && !widgetFunction.ParameterProfiles.Any(p => p.IsRequired)) { return new WidgetFunctionProvider(widgetFunction); } } if (type.IsLazyGenericType()) { var lazyType = type.GetGenericArguments().First(); var provider = GetDefaultWidgetFunctionProviderByType(lazyType, required); if (provider!=null) { return provider; } } return null; } /// <exclude /> public static WidgetFunctionProvider DateSelectorWidget { get { return new WidgetFunctionProvider(DateSelectorWidgetFunction.CompositeName); } } /// <exclude /> public static WidgetFunctionProvider DateTimeSelectorWidget { get { return new WidgetFunctionProvider(DateTimeSelectorWidgetFunction.CompositeName); } } /// <exclude /> public static WidgetFunctionProvider TextBoxWidget { get { return new WidgetFunctionProvider(TextBoxWidgetFuntion.CompositeName); } } /// <exclude /> public static WidgetFunctionProvider GuidTextBoxWidget { get { return new WidgetFunctionProvider(GuidTextBoxWidgetFuntion.CompositeName); } } /// <exclude /> public static WidgetFunctionProvider DataTypeSelectorWidget { get { return new WidgetFunctionProvider(DataTypeSelectorWidgetFunction.CompositeName); } } /// <exclude /> public static WidgetFunctionProvider TextAreaWidget { get { return new WidgetFunctionProvider(TextAreaWidgetFuntion.CompositeName); } } /// <exclude /> public static WidgetFunctionProvider UrlComboBoxWidget { get { return new WidgetFunctionProvider(UrlComboBoxWidgetFunction.CompositeName); } } /// <exclude /> public static WidgetFunctionProvider VisualXhtmlDocumentEditorWidget { get { return new WidgetFunctionProvider(Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.XhtmlDocument.VisualXhtmlEditorFuntion.CompositeName); } } /// <exclude /> public static WidgetFunctionProvider IntegerTextBoxWidget { get { return new WidgetFunctionProvider(IntegerTextBoxWidgetFuntion.CompositeName); } } /// <exclude /> public static WidgetFunctionProvider DecimalTextBoxWidget { get { return new WidgetFunctionProvider(DecimalTextBoxWidgetFuntion.CompositeName); } } /// <exclude /> public static WidgetFunctionProvider CheckBoxWidget { get { return new WidgetFunctionProvider(CheckBoxWidgetFuntion.CompositeName); } } /// <exclude /> public static WidgetFunctionProvider GetDataReferenceWidget(Type interfaceType) { if (interfaceType == null) throw new ArgumentNullException("interfaceType"); if (typeof(IData).IsAssignableFrom(interfaceType) == false) throw new ArgumentException(string.Format("The interface type '{0}' does not inherit the interface '{1}", interfaceType, typeof(IData))); MethodInfo methodInfo = (from mi in typeof(StandardWidgetFunctions).GetMethods(BindingFlags.Public | BindingFlags.Static) where mi.Name == "GetDataReferenceWidget" && mi.GetParameters().Length == 0 select mi).Single(); methodInfo = methodInfo.MakeGenericMethod(new Type[] { interfaceType }); return (WidgetFunctionProvider)methodInfo.Invoke(null, null); } /// <exclude /> public static WidgetFunctionProvider GetDataReferenceWidget<T>() where T : class, IData { if (typeof(T) == typeof(IPage)) { return new WidgetFunctionProvider(PageReferenceSelectorWidgetFunction.CompositeName); } if (typeof(T) == typeof(IMediaFile)) { return GetMediaFileSelectorWidget(true); } if (typeof(T) == typeof(IImageFile)) { return GetImageSelectorWidget(true); } return new WidgetFunctionProvider(DataReferenceSelectorWidgetFunction<T>.CompositeName); } /// <exclude /> public static WidgetFunctionProvider GetNullableDataReferenceWidget<T>() where T : class, IData { if (typeof(T) == typeof(IPage)) { return new WidgetFunctionProvider(NullablePageReferenceSelectorWidgetFunction.CompositeName); } if (typeof(T) == typeof(IMediaFile)) { return GetMediaFileSelectorWidget(false); } if (typeof(T) == typeof(IImageFile)) { return GetImageSelectorWidget(false); } return new WidgetFunctionProvider(NullableDataReferenceSelectorWidgetFunction<T>.CompositeName); } /// <exclude /> public static WidgetFunctionProvider GetImageSelectorWidget(bool selectionRequired) { List<BaseParameterRuntimeTreeNode> widgetParams = new List<BaseParameterRuntimeTreeNode>(); widgetParams.Add( new ConstantObjectParameterRuntimeTreeNode(ImageSelectorWidgetFunction.RequiredParameterName, selectionRequired)); return new WidgetFunctionProvider(ImageSelectorWidgetFunction.CompositeName, widgetParams); } /// <exclude /> public static WidgetFunctionProvider GetMediaFileSelectorWidget(bool selectionRequired) { List<BaseParameterRuntimeTreeNode> widgetParams = new List<BaseParameterRuntimeTreeNode>(); widgetParams.Add(new ConstantObjectParameterRuntimeTreeNode(MediaFileSelectorWidgetFunction.RequiredParameterName, selectionRequired)); return new WidgetFunctionProvider(MediaFileSelectorWidgetFunction.CompositeName, widgetParams); } /// <exclude /> public static WidgetFunctionProvider GetBoolSelectorWidget(string trueLabel, string falseLabel) { return new WidgetFunctionProvider(new BoolSelectorWidgetFuntion(null, trueLabel, falseLabel)); } /// <exclude /> public static XElement BuildBasicFormsMarkup(XNamespace uiControlNamespace, string uiControlName, string bindingPropertyName, string label, HelpDefinition help, string bindingSourceName) { XNamespace forms10Space = Namespaces.BindingForms10; XElement widgetMarkup = new XElement(uiControlNamespace + uiControlName, new XAttribute("Label", label), new XAttribute("Help", help.HelpText), new XElement(uiControlNamespace + string.Format("{0}.{1}", uiControlName, bindingPropertyName), new XElement(forms10Space + "bind", new XAttribute("source", bindingSourceName)))); return widgetMarkup; } /// <exclude /> public static XElement BuildStaticCallPopulatedSelectorFormsMarkup(ParameterList parameters, string label, HelpDefinition helpDefinition, string bindingSourceName, Type optionsGeneratingStaticType, string optionsGeneratingStaticMethodName, object optionsGeneratingStaticMethodParameterValue, string optionsObjectKeyPropertyName, string optionsObjectLabelPropertyName, bool multiSelect, bool compactMode, bool required, bool bindToString) { string tagName = (multiSelect==true? "MultiKeySelector": "KeySelector"); string bindingPropertyName = (multiSelect && bindToString ? "SelectedAsString" : "Selected"); XElement selector = StandardWidgetFunctions.BuildBasicFormsMarkup(Namespaces.BindingFormsStdUiControls10, tagName, bindingPropertyName, label, helpDefinition, bindingSourceName); XNamespace f = Namespaces.BindingFormsStdFuncLib10; selector.Add( new XAttribute("OptionsKeyField", optionsObjectKeyPropertyName), new XAttribute("OptionsLabelField", optionsObjectLabelPropertyName), new XAttribute("Required", required), ( multiSelect ? new XAttribute("CompactMode", compactMode) : null), new XElement(selector.Name.Namespace + (tagName + ".Options"), new XElement(f + "StaticMethodCall", new XAttribute("Type", TypeManager.SerializeType(optionsGeneratingStaticType)), new XAttribute("Method", optionsGeneratingStaticMethodName)))); if (optionsGeneratingStaticMethodParameterValue != null) selector.Descendants(f + "StaticMethodCall").First().Add( new XAttribute("Parameters", optionsGeneratingStaticMethodParameterValue)); return selector; } /// <summary> /// Creates a WidgetFunctionProvider that yields a drop down list populated with options from a static method call. You can return anonymous types. /// </summary> /// <param name="optionsGeneratingStaticType">The type containing the static method to call</param> /// <param name="optionsGeneratingStaticMethodName">The name of the static method to call. The method should take no parameters and return an IEnumerable.</param> /// <param name="optionsObjectKeyPropertyName">The name of the property on the return item type to use as key in the drop down</param> /// <param name="optionsObjectLabelPropertyName">The name of the property on the return item type to use as label in the drop down</param> /// <param name="multiSelector"></param> /// <param name="required"></param> /// <returns></returns> public static WidgetFunctionProvider DropDownList(Type optionsGeneratingStaticType, string optionsGeneratingStaticMethodName, string optionsObjectKeyPropertyName, string optionsObjectLabelPropertyName, bool multiSelector, bool required) { return new WidgetFunctionProvider( new AdHocDropDownListWidgetFunction(optionsGeneratingStaticType, optionsGeneratingStaticMethodName, optionsObjectKeyPropertyName, optionsObjectLabelPropertyName, multiSelector, true, required)); } /// <summary> /// Creates a WidgetFunctionProvider that yields a drop down list populated with options from a static method call. You can return anonymous types. /// </summary> /// <param name="optionsGeneratingStaticType">The type containing the static method to call</param> /// <param name="optionsGeneratingStaticMethodName">The name of the static method to call. The method should take no parameters and return an IEnumerable.</param> /// <param name="optionsObjectKeyPropertyName">The name of the property on the return item type to use as key in the drop down</param> /// <param name="optionsObjectLabelPropertyName">The name of the property on the return item type to use as label in the drop down</param> /// <param name="multiSelector"></param> /// <returns></returns> public static WidgetFunctionProvider DropDownList(Type optionsGeneratingStaticType, string optionsGeneratingStaticMethodName, string optionsObjectKeyPropertyName, string optionsObjectLabelPropertyName, bool multiSelector) { return DropDownList(optionsGeneratingStaticType, optionsGeneratingStaticMethodName, optionsObjectKeyPropertyName, optionsObjectLabelPropertyName, multiSelector, true); } /// <exclude /> public static WidgetFunctionProvider DropDownList(Type optionsGeneratingStaticType, string optionsGeneratingStaticMethodName, bool multiSelector, bool required) { return new WidgetFunctionProvider( new AdHocDropDownListWidgetFunction(optionsGeneratingStaticType, optionsGeneratingStaticMethodName, ".", ".", multiSelector, true, required)); } /// <exclude /> public static WidgetFunctionProvider DropDownList(Type optionsGeneratingStaticType, string optionsGeneratingStaticMethodName, object optionsGeneratingStaticMethodParameterValue, string optionsObjectKeyPropertyName, string optionsObjectLabelPropertyName, bool multiSelector, bool required) { return new WidgetFunctionProvider( new AdHocDropDownListWidgetFunction(optionsGeneratingStaticType, optionsGeneratingStaticMethodName, optionsGeneratingStaticMethodParameterValue, optionsObjectKeyPropertyName, optionsObjectLabelPropertyName, multiSelector, true, required)); } /// <exclude /> public static WidgetFunctionProvider DropDownList(Type optionsGeneratingStaticType, string optionsGeneratingStaticMethodName, object optionsGeneratingStaticMethodParameterValue, bool multiSelector, bool compact, bool required) { return new WidgetFunctionProvider( new AdHocDropDownListWidgetFunction(optionsGeneratingStaticType, optionsGeneratingStaticMethodName, optionsGeneratingStaticMethodParameterValue, ".", ".", multiSelector, compact, required)); } private class AdHocDropDownListWidgetFunction : IWidgetFunction { private readonly Type _type; private readonly string _methodName; private readonly string _keyPropertyName; private readonly string _labelPropertyName; private readonly object _parameterValue; private readonly bool _multiSelector; private readonly bool _compact; private readonly bool _required; public AdHocDropDownListWidgetFunction(Type optionsGeneratingStaticType, string optionsGeneratingStaticMethodName, string optionsObjectKeyPropertyName, string optionsObjectLabelPropertyName, bool multiSelector, bool compact, bool required) { _type = optionsGeneratingStaticType; _methodName = optionsGeneratingStaticMethodName; _keyPropertyName = optionsObjectKeyPropertyName; _labelPropertyName = optionsObjectLabelPropertyName; _multiSelector = multiSelector; _compact = compact; _required = required; } public AdHocDropDownListWidgetFunction(Type optionsGeneratingStaticType, string optionsGeneratingStaticMethodName, object parameterValue, string optionsObjectKeyPropertyName, string optionsObjectLabelPropertyName, bool multiSelector, bool compact, bool required) : this(optionsGeneratingStaticType, optionsGeneratingStaticMethodName, optionsObjectKeyPropertyName, optionsObjectLabelPropertyName, multiSelector, compact, required) { if (parameterValue == null) throw new ArgumentNullException("parameterValue"); _parameterValue = parameterValue; } public XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition helpDefinition, string bindingSourceName) { return StandardWidgetFunctions.BuildStaticCallPopulatedSelectorFormsMarkup( parameters, label, helpDefinition, bindingSourceName, _type, _methodName, _parameterValue, _keyPropertyName, _labelPropertyName, _multiSelector, _compact, _required, false); } public string Name { get { return "AdHocDropDownListWidget"; } } public string Namespace { get { return "Composite.AdHoc"; } } public virtual string Description { get { return ""; } } public Type ReturnType { get { return typeof(object); } } public IEnumerable<ParameterProfile> ParameterProfiles { get { yield break; } } public Composite.C1Console.Security.EntityToken EntityToken { get { throw new NotImplementedException(); } } } } } ================================================ FILE: Composite/Functions/WidgetFunctionProvider.cs ================================================ using System; using System.Linq; using System.Xml.Linq; using System.Collections.Generic; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class WidgetFunctionProvider { /// <exclude /> public static WidgetFunctionProvider BuildNoWidgetProvider() { return new WidgetFunctionProvider(); } private string _widgetFunctionName = null; private IWidgetFunction _widgetFunction = null; private IEnumerable<BaseParameterRuntimeTreeNode> _setParameters = null; private XElement _serializedWidgetFunction = null; private object _lock = new object(); private WidgetFunctionProvider() { } internal WidgetFunctionProvider(string widgetName) { if (string.IsNullOrEmpty(widgetName)) throw new ArgumentNullException("widgetName"); _widgetFunctionName = widgetName; } internal WidgetFunctionProvider(string widgetName, IEnumerable<BaseParameterRuntimeTreeNode> parameters) { if (string.IsNullOrEmpty(widgetName)) throw new ArgumentNullException("widgetName"); if (parameters == null) throw new ArgumentNullException("parameters"); _widgetFunctionName = widgetName; _setParameters = parameters; } /// <exclude /> public WidgetFunctionProvider(IWidgetFunction widgetFunction) { if (widgetFunction == null) throw new ArgumentNullException("widgetFunction"); _widgetFunction = widgetFunction; } /// <exclude /> public WidgetFunctionProvider(XElement serializedWidgetFunction) { _serializedWidgetFunction = serializedWidgetFunction; } /// <exclude /> public string WidgetFunctionCompositeName { get { if (string.IsNullOrEmpty(_widgetFunctionName) == false) { return _widgetFunctionName; } EnsureWidgetFunction(); if (_widgetFunction != null) { return _widgetFunction.CompositeName(); } throw new InvalidOperationException("Neither name nor IWidgetFunction found"); } } /// <exclude /> public IWidgetFunction WidgetFunction { get { EnsureWidgetFunction(); if (_widgetFunction == null) { if (string.IsNullOrEmpty(_widgetFunctionName) == false) { _widgetFunction = FunctionFacade.GetWidgetFunction(_widgetFunctionName); } } return _widgetFunction; } } /// <exclude /> public IEnumerable<BaseParameterRuntimeTreeNode> WidgetFunctionParameters { get { if (_setParameters == null) { yield break; } else { foreach (BaseParameterRuntimeTreeNode param in _setParameters) { yield return param; } } } } /// <exclude /> public XElement SerializedWidgetFunction { get { EnsureWidgetFunction(); WidgetFunctionRuntimeTreeNode widgetRuntimeTreeNode = new WidgetFunctionRuntimeTreeNode(this.WidgetFunction, this.WidgetFunctionParameters.ToList()); return widgetRuntimeTreeNode.Serialize(); } } private void EnsureWidgetFunction() { lock (_lock) { if (_widgetFunction == null && _serializedWidgetFunction != null) { WidgetFunctionRuntimeTreeNode functionNode = (WidgetFunctionRuntimeTreeNode)FunctionFacade.BuildTree(_serializedWidgetFunction); _setParameters = functionNode.GetSetParameters().ToList(); _widgetFunction = functionNode.GetWidgetFunction(); } } } } } ================================================ FILE: Composite/Functions/WidgetFunctionRuntimeTreeNode.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Threading; using System.Xml.Linq; using Composite.Functions.Foundation; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class WidgetFunctionRuntimeTreeNode : BaseFunctionRuntimeTreeNode { private IWidgetFunction _widgetFunction; /// <exclude /> public WidgetFunctionRuntimeTreeNode(IWidgetFunction widgetFunction) : this(widgetFunction, "", new HelpDefinition(""), "", new List<BaseParameterRuntimeTreeNode>()) { } /// <exclude /> public WidgetFunctionRuntimeTreeNode(IWidgetFunction widgetFunction, List<BaseParameterRuntimeTreeNode> parameters) : this(widgetFunction, "", new HelpDefinition(""), "", parameters) { } /// <exclude /> public WidgetFunctionRuntimeTreeNode(IWidgetFunction widgetFunction, string label, HelpDefinition helpDefinition, string bindingSourceName) : this(widgetFunction, label, helpDefinition, bindingSourceName, new List<BaseParameterRuntimeTreeNode>()) { } /// <exclude /> public string Label { get; set; } /// <exclude /> public HelpDefinition HelpDefinition { get; set; } /// <exclude /> public string BindingSourceName { get; set; } internal WidgetFunctionRuntimeTreeNode(IWidgetFunction widgetFunction, string label, HelpDefinition helpDefinition, string bindingSourceName, List<BaseParameterRuntimeTreeNode> parameters) { _widgetFunction = widgetFunction; this.Label = label; this.HelpDefinition = helpDefinition; this.BindingSourceName = bindingSourceName; this.Parameters = parameters; } /// <exclude /> protected override IMetaFunction HostedFunction { get { return _widgetFunction; } } /// <exclude /> public IWidgetFunction GetWidgetFunction() { return _widgetFunction; } /// <exclude /> public override object GetValue(FunctionContextContainer contextContainer) { if (contextContainer == null) throw new ArgumentNullException("contextContainer"); ValidateNotSelfCalling(); ParameterList parameters = new ParameterList(contextContainer); foreach (ParameterProfile parameterProfile in _widgetFunction.ParameterProfiles) { BaseParameterRuntimeTreeNode parameterTreeNode = this.Parameters.Where(ptn => ptn.Name == parameterProfile.Name).SingleOrDefault(); if (parameterTreeNode == null) { BaseValueProvider valueProvider = parameterProfile.FallbackValueProvider; object value = valueProvider.GetValue(contextContainer); parameters.AddConstantParameter(parameterProfile.Name, value, parameterProfile.Type); } else { parameters.AddLazyParameter(parameterProfile.Name, parameterTreeNode, parameterProfile.Type); } } return _widgetFunction.GetWidgetMarkup(parameters, this.Label, this.HelpDefinition, this.BindingSourceName); } /// <exclude /> public override IEnumerable<string> GetAllSubFunctionNames() { List<string> names = new List<string>(); foreach (BaseParameterRuntimeTreeNode parameter in this.Parameters) { names.AddRange(parameter.GetAllSubFunctionNames()); } return names.Distinct(); } /// <exclude /> public override bool ContainsNestedFunctions { get { foreach (var parameter in this.Parameters) { if (parameter.ContainsNestedFunctions) { return true; } } return false; } } /// <exclude /> public override XElement Serialize() { XElement element = XElement.Parse(string.Format(@"<f:{0} xmlns:f=""{1}"" />", FunctionTreeConfigurationNames.WidgetFunctionTagName, FunctionTreeConfigurationNames.NamespaceName)); element.Add(new XAttribute(FunctionTreeConfigurationNames.NameAttributeName, _widgetFunction.CompositeName())); if (!string.IsNullOrEmpty(this.Label)) element.Add(new XAttribute(FunctionTreeConfigurationNames.LabelAttributeName, this.Label)); if (!string.IsNullOrEmpty(this.BindingSourceName)) element.Add(new XAttribute(FunctionTreeConfigurationNames.BindingSourceNameAttributeName, this.BindingSourceName)); if (this.HelpDefinition != null && !string.IsNullOrEmpty(this.HelpDefinition.HelpText)) { element.Add(this.HelpDefinition.Serialize()); } foreach (ParameterProfile parameterProfile in _widgetFunction.ParameterProfiles) { BaseParameterRuntimeTreeNode parameterRuntimeTreeNode = this.Parameters.Where(ptn => ptn.Name == parameterProfile.Name).FirstOrDefault(); if (parameterRuntimeTreeNode != null) { element.Add(parameterRuntimeTreeNode.Serialize()); } } return element; } } } ================================================ FILE: Composite/Functions/XElementParameterRuntimeTreeNode.cs ================================================ using System; using System.Collections.Generic; using System.Xml.Linq; using System.Linq; using Composite.Functions.Foundation; using Composite.Core.Xml; namespace Composite.Functions { internal sealed class XElementParameterRuntimeTreeNode : BaseParameterRuntimeTreeNode { private XElement _element; private XElement ExecuteInnerFunctions(FunctionContextContainer contextContainer) { XElement resultRoot = new XElement(_element); int loopCount = 0; while (true) { XName functionXName = Namespaces.Function10 + FunctionTreeConfigurationNames.FunctionTagName; IEnumerable<XElement> nestedFunctionCalls = resultRoot.Descendants(functionXName).Where(f => !f.Ancestors(functionXName).Any()); var evaluatedListOfInnerFunctions = nestedFunctionCalls.ToList(); if (!evaluatedListOfInnerFunctions.Any()) { break; } if (loopCount++ > 1000) { throw new InvalidOperationException("One or more function seems to be returning markup generating endless recursion. The following markup seems to generate the problem: " + evaluatedListOfInnerFunctions.First().ToString()); } var functionCallResults = new object[evaluatedListOfInnerFunctions.Count]; for(int i=0; i<evaluatedListOfInnerFunctions.Count; i++) { XElement functionCallDefinition = evaluatedListOfInnerFunctions[i]; BaseRuntimeTreeNode runtimeTreeNode = FunctionTreeBuilder.Build(functionCallDefinition); functionCallResults[i] = runtimeTreeNode.GetValue(contextContainer); }; for (int i = 0; i < evaluatedListOfInnerFunctions.Count; i++) { object embedableResult = contextContainer.MakeXEmbedable(functionCallResults[i]); if (embedableResult is XAttribute) { evaluatedListOfInnerFunctions[i].Parent.Add(embedableResult); evaluatedListOfInnerFunctions[i].Remove(); } else { evaluatedListOfInnerFunctions[i].ReplaceWith(embedableResult); } } } return resultRoot; } public XElementParameterRuntimeTreeNode(string name, XElement element) : base(name) { _element = element; } public override object GetValue(FunctionContextContainer contextContainer) { Verify.ArgumentNotNull(contextContainer, "contextContainer"); return ExecuteInnerFunctions(contextContainer); } public override IEnumerable<string> GetAllSubFunctionNames() { return from nameAttribute in _element.Elements(Namespaces.Function10 + FunctionTreeConfigurationNames.FunctionTagName).Attributes( FunctionTreeConfigurationNames.NameAttributeName ) select nameAttribute.Value; } public override bool ContainsNestedFunctions { get { return GetAllSubFunctionNames().Any(); } } public XElement GetHostedXElement() { return _element; } public override XElement Serialize() { XElement element = new XElement(XName.Get(FunctionTreeConfigurationNames.ParamTagName, FunctionTreeConfigurationNames.NamespaceName), new XAttribute(FunctionTreeConfigurationNames.NameAttributeName, this.Name), _element ); return element; } } } ================================================ FILE: Composite/Functions/XslExtensionsManager.cs ================================================ using System; using System.Collections.Generic; using System.Xml.Xsl; using Composite.Functions.Foundation; using Composite.Functions.Foundation.PluginFacades; using Composite.Core.Logging; using Composite.Core.Extensions; using Composite.Core.Types; namespace Composite.Functions { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class XslExtensionsManager { /// <exclude /> public static void Register(XsltArgumentList argumentList) { foreach(string providerName in XslExtensionsProviderRegistry.XslExtensionsProviderNames) { List<Pair<string, object>> extensions; try { extensions = XslExtensionsProviderPluginFacade.CreateExtensions(providerName); } catch(Exception ex) { string message = "Failed to get xsl extensions from provider '{0}'".FormatWith(providerName); LoggingService.LogError("XslExtensionsManager", new InvalidOperationException(message, ex)); continue; } if(extensions != null) { foreach (Pair<string, object> pair in extensions) { argumentList.AddExtensionObject(pair.First, pair.Second); } } } } } } ================================================ FILE: Composite/GlobalInitializerFacade.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Web; using System.Web.Hosting; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Core; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Instrumentation; using Composite.Core.Logging; using Composite.Core.PackageSystem; using Composite.Core.Routing; using Composite.Core.Threading; using Composite.Core.Types; using Composite.Data.Foundation; using Composite.Data.ProcessControlled; using Composite.Functions.Foundation; using Composite.Data.Foundation.PluginFacades; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Sql; namespace Composite { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class GlobalInitializerFacade { private static readonly string LogTitle = "RGB(194, 252, 131)" + nameof(GlobalInitializerFacade); private static readonly string LogTitleNormal = nameof(GlobalInitializerFacade); private static bool _coreInitialized; private static bool _initializing; private static bool _typesAutoUpdated; private static bool _unhandledExceptionLoggingInitialized; private static bool _preInitHandlersRunning; private static Exception _exceptionThrownDuringInitialization; private static DateTime _exceptionThrownDuringInitializationTimeStamp; private static int _fatalErrorFlushCount; private static readonly ReaderWriterLock _readerWriterLock = new ReaderWriterLock(); private static Thread _hookingFacadeThread; // This is used to wait on the the thread if a reinitialize is issued private static Exception _hookingFacadeException; // This will hold the exception from the before the reinitialize was issued private static readonly ThreadLockingInformation _threadLocking = new ThreadLockingInformation(); /// <exclude /> [Obsolete("Not used")] public static bool DynamicTypesGenerated => false; /// <exclude /> public static bool SystemCoreInitializing => _initializing; /// <exclude /> public static bool SystemCoreInitialized => _coreInitialized; /// <summary> /// This is true during a total flush of the system (re-initialize). /// </summary> public static bool IsReinitializingTheSystem { get; private set; } static GlobalInitializerFacade() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } /// <summary> /// This method will initialize the system (if it has not been initialized). /// </summary> public static void EnsureSystemIsInitialized() { InitializeTheSystem(); } /// <summary> /// This method will initialize the system (if it has not been initialized). /// </summary> public static void InitializeTheSystem() { Verify.That(!_preInitHandlersRunning, "DataFacade related methods should not be called in OnBeforeInitialize() method of a startup handler. Please move the code to OnInitialized() instead."); if (_exceptionThrownDuringInitialization != null) { TimeSpan timeSpan = DateTime.Now - _exceptionThrownDuringInitializationTimeStamp; if (timeSpan < TimeSpan.FromMinutes(5.0)) { Log.LogCritical(LogTitleNormal, $"Exception recorded: {timeSpan} ago"); throw new Exception("Failed to initialize the system", _exceptionThrownDuringInitialization); } _exceptionThrownDuringInitialization = null; } if (!_initializing && !_coreInitialized) { using (CoreLockScope) { if (!_initializing && !_coreInitialized) { try { _initializing = true; if (!SystemSetupFacade.IsSystemFirstTimeInitialized && RuntimeInformation.IsDebugBuild) { Log.LogWarning(LogTitleNormal, new InvalidOperationException("System is initializing, yet missing first time initialization")); } using (ThreadDataManager.EnsureInitialize()) { DoInitialize(); } GC.Collect(); // Collecting generation 2 after initialization _fatalErrorFlushCount = 0; } catch (Exception ex) { _exceptionThrownDuringInitialization = ex; _exceptionThrownDuringInitializationTimeStamp = DateTime.Now; var shutdownReason = HostingEnvironment.ShutdownReason; if (shutdownReason != ApplicationShutdownReason.None) { Log.LogCritical(LogTitleNormal, "Shutdown reason: " + HostingEnvironment.ShutdownReason); } Log.LogCritical(LogTitleNormal, ex); throw; } finally { _coreInitialized = true; _initializing = false; } } EnabledUnhandledExceptionsLogging(); } } } private static void EnabledUnhandledExceptionsLogging() { if (_unhandledExceptionLoggingInitialized) return; AppDomain.CurrentDomain.UnhandledException += (sender, args) => { var ex = (Exception)args.ExceptionObject; Log.LogCritical("Unhandled exception", ex); LogManager.Flush(); }; _unhandledExceptionLoggingInitialized = true; } private static void DoInitialize() { int startTime = Environment.TickCount; Guid installationId = InstallationInformationFacade.InstallationId; Log.LogVerbose(LogTitle, "Initializing the system core - installation id = " + installationId); using (new LogExecutionTime(LogTitle, "Initialization of the static data types")) { DataProviderRegistry.InitializeDataTypes(); } using (new LogExecutionTime(LogTitle, "Auto update of static data types")) { bool typesUpdated = AutoUpdateDataTypes(); if (typesUpdated) { using (new LogExecutionTime(LogTitle, "Reinitialization of the static data types")) { SqlTableInformationStore.Flush(); DataProviderRegistry.Flush(); DataProviderPluginFacade.Flush(); DataProviderRegistry.InitializeDataTypes(); } CodeGenerationManager.GenerateCompositeGeneratedAssembly(true); } } using (new LogExecutionTime(LogTitle, "Ensure data stores")) { bool dataStoresCreated = DataStoreExistenceVerifier.EnsureDataStores(); if (dataStoresCreated) { Log.LogVerbose(LogTitle, "Initialization of the system was halted, performing a flush"); _initializing = false; GlobalEventSystemFacade.FlushTheSystem(); return; } } using (new LogExecutionTime(LogTitle, "Initializing data process controllers")) { ProcessControllerFacade.Initialize_PostDataTypes(); } using (new LogExecutionTime(LogTitle, "Initializing data type references")) { DataReferenceRegistry.Initialize_PostDataTypes(); } using (new LogExecutionTime(LogTitle, "Initializing data type associations")) { DataAssociationRegistry.Initialize_PostDataTypes(); } using (new LogExecutionTime(LogTitle, "Initializing internal urls")) { InternalUrls.Initialize_PostDataTypes(); } using (new LogExecutionTime(LogTitle, "Initializing functions")) { MetaFunctionProviderRegistry.Initialize_PostDataTypes(); } Log.LogVerbose(LogTitle, "Starting initialization of administrative secondaries"); if (SystemSetupFacade.IsSystemFirstTimeInitialized && !SystemSetupFacade.SetupIsRunning && HostingEnvironment.IsHosted) { using (new LogExecutionTime(LogTitle, "Initializing workflow runtime")) { WorkflowFacade.EnsureInitialization(); } } using (new LogExecutionTime(LogTitle, "Auto installing packages")) { DoAutoInstallPackages(); } int executionTime = Environment.TickCount - startTime; Log.LogVerbose(LogTitle, $"Done initializing of the system core. ({executionTime} ms)"); } private static bool AutoUpdateDataTypes() { if (!GlobalSettingsFacade.EnableDataTypesAutoUpdate) { return false; } if (_typesAutoUpdated) { // This is here to catch update -> failed -> update -> failed -> ... loop DataInterfaceAutoUpdater.TestEnsureUpdateAllInterfaces(); return false; } bool flushTheSystem = DataInterfaceAutoUpdater.EnsureUpdateAllInterfaces(); _typesAutoUpdated = true; return flushTheSystem; } /// <exclude /> public static void ReinitializeTheSystem(RunInWriterLockScopeDelegate runInWriterLockScopeDelegate) { ReinitializeTheSystem(runInWriterLockScopeDelegate, false); } internal static void ReinitializeTheSystem(RunInWriterLockScopeDelegate runInWriterLockScopeDelegate, bool initializeHooksInTheSameThread) { if (_hookingFacadeThread != null) { _hookingFacadeThread.Join(TimeSpan.FromSeconds(30)); if (_hookingFacadeException != null) { throw new InvalidOperationException("The initialization of the HookingFacade failed before this reinitialization was issued", _hookingFacadeException); } } using (CoreLockScope) { IsReinitializingTheSystem = true; runInWriterLockScopeDelegate(); _coreInitialized = false; _initializing = false; _exceptionThrownDuringInitialization = null; Verify.That(_fatalErrorFlushCount <= 1, "Failed to reload the system. See the log for the details."); InitializeTheSystem(); IsReinitializingTheSystem = false; } } private static void EnsureHookingFacade(object timeSpanToDelayStart) { // NOTE: Condition is made for unit-testing if (HostingEnvironment.IsHosted) { var kvp = (KeyValuePair<TimeSpan, StackTrace>)timeSpanToDelayStart; _hookingFacadeException = null; Thread.Sleep(kvp.Key); try { using (CoreIsInitializedScope) { using (ThreadDataManager.EnsureInitialize()) { HookingFacade.EnsureInitialization(); } } } catch (Exception ex) { _hookingFacadeException = ex; } } _hookingFacadeThread = null; } /// <exclude /> public static void WaitUntilAllIsInitialized() { using (CoreIsInitializedScope) { _hookingFacadeThread?.Join(); } } /// <exclude /> public static void FatalResetTheSystem() { Log.LogWarning(LogTitle, "Unhandled error occurred, reinitializing the system!"); ReinitializeTheSystem(delegate { _fatalErrorFlushCount++; GlobalEventSystemFacade.FlushTheSystem(); }); } /// <exclude /> public static void UninitializeTheSystem(RunInWriterLockScopeDelegate runInWriterLockScopeDelegate) { using (CoreLockScope) { using (new LogExecutionTime(LogTitle, "Uninitializing the system")) { runInWriterLockScopeDelegate(); } _coreInitialized = false; _initializing = false; _exceptionThrownDuringInitialization = null; } } internal static IDisposable GetPreInitHandlersScope() { return new PreInitHandlersScope(); } private class PreInitHandlersScope : IDisposable { public PreInitHandlersScope() { _preInitHandlersRunning = true; } public void Dispose() { _preInitHandlersRunning = false; #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// <exclude /> ~PreInitHandlersScope() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } #region Package installation private class AutoInstallPackageInfo { public bool ToBeDeleted { get; set; } public string FilePath { get; set; } } private static void DoAutoInstallPackages() { if (IsReinitializingTheSystem) return; try { // This is not so good, unittests run and normal runs should have same semantic behavior. // But if this is not here, some unittests will start failing. /MRJ if (RuntimeInformation.IsUnittest) return; var zipFiles = new List<AutoInstallPackageInfo>(); string directory = PathUtil.Resolve(GlobalSettingsFacade.AutoPackageInstallDirectory); if (C1Directory.Exists(directory)) { Log.LogVerbose(LogTitle, $"Installing packages from: {directory}"); zipFiles.AddRange(C1Directory.GetFiles(directory, "*.zip") .OrderBy(f => f) .Select(f => new AutoInstallPackageInfo { FilePath = f, ToBeDeleted = true })); } else { Log.LogVerbose(LogTitle, $"Auto install directory not found: {directory}"); } if (RuntimeInformation.IsDebugBuild) { string workflowTestDir = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.AutoPackageInstallDirectory), "WorkflowTesting"); if (C1Directory.Exists(workflowTestDir)) { Log.LogVerbose(LogTitle, $"Installing packages from: {workflowTestDir}"); zipFiles.AddRange(C1Directory.GetFiles(workflowTestDir, "*.zip") .OrderBy(f => f) .Select(f => new AutoInstallPackageInfo { FilePath = f, ToBeDeleted = false })); } } foreach (var zipFile in zipFiles) { try { using (Stream zipFileStream = C1File.OpenRead(zipFile.FilePath)) { Log.LogVerbose(LogTitle, $"Installing package: {zipFile.FilePath}"); PackageManagerInstallProcess packageManagerInstallProcess = PackageManager.Install(zipFileStream, true); if (packageManagerInstallProcess.PreInstallValidationResult.Count > 0) { Log.LogError(LogTitleNormal, "Package installation failed! (Pre install validation error)"); LogErrors(packageManagerInstallProcess.PreInstallValidationResult); continue; } List<PackageFragmentValidationResult> validationResults = packageManagerInstallProcess.Validate(); if (validationResults.Count > 0) { Log.LogError(LogTitleNormal, "Package installation failed! (Validation error)"); LogErrors(validationResults); continue; } List<PackageFragmentValidationResult> installResult = packageManagerInstallProcess.Install(); if (installResult.Count > 0) { Log.LogError(LogTitleNormal, "Package installation failed! (Installation error)"); LogErrors(installResult); continue; } } } catch (Exception ex) { Log.LogWarning(LogTitleNormal, ex); } if (zipFile.ToBeDeleted) { FileUtils.Delete(zipFile.FilePath); } } } catch (Exception ex) { Log.LogError(LogTitleNormal, ex); } } #endregion #region Utilities /// <exclude /> public static void ValidateIsOnlyCalledFromGlobalInitializerFacade(StackTrace stackTrace) { MethodBase methodInfo = stackTrace.GetFrame(1).GetMethod(); if (methodInfo.DeclaringType != typeof(GlobalInitializerFacade)) { throw new SystemException($"The method {methodInfo} may only be called by the {typeof(GlobalInitializerFacade)}"); } } private static void LogErrors(IEnumerable<PackageFragmentValidationResult> packageErrors) { foreach (PackageFragmentValidationResult packageFragmentValidationResult in packageErrors) { Log.LogError(LogTitleNormal, packageFragmentValidationResult.Message); if (packageFragmentValidationResult.Exception != null) { Log.LogError(LogTitleNormal, "With following exception:"); Log.LogError(LogTitleNormal, packageFragmentValidationResult.Exception); } } } private static void OnFlushEvent(FlushEventArgs args) { using (CoreLockScope) { _coreInitialized = false; } } #endregion #region Locking /// <exclude /> public delegate void RunInWriterLockScopeDelegate(); /// <exclude /> public static void RunInWriterLockScope(RunInWriterLockScopeDelegate runInWriterLockScopeDelegate) { using (CoreLockScope) { runInWriterLockScopeDelegate(); } } /// <summary> /// Locks the initialization token until disposed. Use this in a using {} statement. /// </summary> internal static IDisposable CoreLockScope { get { var stackTrace = new StackTrace(); var method = stackTrace.GetFrame(1).GetMethod(); return new LockerToken(true, $"{method.DeclaringType.Name}.{method.Name}"); } } /// <summary> /// Using this in a using-statement will ensure that the code are /// executed AFTER the system has been initialized. /// </summary> public static IDisposable CoreIsInitializedScope { get { // This line ensures that the system is always initialized. // Even if the InitializeTheSystem method is NOT called during // application startup. InitializeTheSystem(); return new LockerToken(); } } /// <summary> /// Using this in a using-statement will ensure that the code is /// executed AFTER any existing locks has been released. /// </summary> public static IDisposable CoreNotLockedScope => new LockerToken(); private static void AcquireReaderLock() { _readerWriterLock.AcquireReaderLock(GlobalSettingsFacade.DefaultReaderLockWaitTimeout); } private static void AcquireWriterLock() { int threadId = Thread.CurrentThread.ManagedThreadId; if (_readerWriterLock.IsReaderLockHeld) { LockCookie lockCookie = _readerWriterLock.UpgradeToWriterLock(GlobalSettingsFacade.DefaultWriterLockWaitTimeout); lock(_threadLocking) { _threadLocking.LockCookiesPerThreadId.Add(threadId, lockCookie); } } else { _readerWriterLock.AcquireWriterLock(GlobalSettingsFacade.DefaultWriterLockWaitTimeout); } lock (_threadLocking) { if (_threadLocking.WriterLocksPerThreadId.ContainsKey(threadId)) { _threadLocking.WriterLocksPerThreadId[threadId] = _threadLocking.WriterLocksPerThreadId[threadId] + 1; } else { _threadLocking.WriterLocksPerThreadId.Add(threadId, 1); } } } private static void ReleaseReaderLock() { _readerWriterLock.ReleaseReaderLock(); } private static void ReleaseWriterLock() { int threadId = Thread.CurrentThread.ManagedThreadId; if (_threadLocking.WriterLocksPerThreadId[threadId] == 1 && _threadLocking.LockCookiesPerThreadId.ContainsKey(threadId)) { LockCookie lockCookie = _threadLocking.LockCookiesPerThreadId[threadId]; lock(_threadLocking) { _threadLocking.LockCookiesPerThreadId.Remove(threadId); } _readerWriterLock.DowngradeFromWriterLock(ref lockCookie); } else { _readerWriterLock.ReleaseWriterLock(); } lock (_threadLocking) { _threadLocking.WriterLocksPerThreadId[threadId] = _threadLocking.WriterLocksPerThreadId[threadId] - 1; if (_threadLocking.WriterLocksPerThreadId[threadId] == 0) { _threadLocking.WriterLocksPerThreadId.Remove(threadId); } } } /// <summary> /// Encapsulates calls to [Acquire|Release][Reader|Writer]Lock(), keeps log of writer locks /// </summary> private sealed class LockerToken : IDisposable { private readonly bool _isWriterLock; private readonly string _lockSource; /// <summary> /// Creates a read lock /// </summary> internal LockerToken() : this(false, null) { } internal LockerToken(bool writerLock, string lockSource) { _isWriterLock = writerLock; _lockSource = lockSource; if (!writerLock) { AcquireReaderLock(); return; } Verify.ArgumentCondition(!lockSource.IsNullOrEmpty(), nameof(lockSource), "Write locks must be obtained with a string identifying the source"); #region Logging the action string methodInfo = string.Empty; if (RuntimeInformation.IsUnittest) { var stackTrace = new StackTrace(); StackFrame stackFrame = (from sf in stackTrace.AsQueryable() where sf.GetMethod().DeclaringType.Assembly.FullName.Contains("Composite.Test") select sf).FirstOrDefault(); if (stackFrame != null) { methodInfo = ", Method:" + stackFrame.GetMethod().Name; } } Log.LogVerbose(LogTitle, $"Writer Lock Acquired (Managed Thread ID: {Thread.CurrentThread.ManagedThreadId}, Source: {lockSource}{methodInfo})"); #endregion Logging the action AcquireWriterLock(); } public void Dispose() { #if LeakCheck GC.SuppressFinalize(this); #endif if (!_isWriterLock) { ReleaseReaderLock(); return; } #region Logging the action string methodInfo = string.Empty; if (RuntimeInformation.IsUnittest) { var stackTrace = new StackTrace(); StackFrame stackFrame = (from sf in stackTrace.AsQueryable() where sf.GetMethod().DeclaringType.Assembly.FullName.Contains("Composite.Test") select sf).FirstOrDefault(); if (stackFrame != null) { methodInfo = ", Method: " + stackFrame.GetMethod().Name; } } Log.LogVerbose(LogTitle, $"Writer Lock Releasing (Managed Thread ID: {Thread.CurrentThread.ManagedThreadId}, Source: {_lockSource}{methodInfo})"); #endregion ReleaseWriterLock(); } #if LeakCheck private string stack = Environment.StackTrace; /// <exclude /> ~LockerToken() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } #endregion private sealed class ThreadLockingInformation { public readonly Hashtable<int, int> WriterLocksPerThreadId = new Hashtable<int, int>(); public readonly Hashtable<int, LockCookie> LockCookiesPerThreadId = new Hashtable<int, LockCookie>(); } } } ================================================ FILE: Composite/Plugins/Application/ApplicationOnlineHandlers/AspNetApplicationOnlineHandler/AspNetApplicationOnlineHandler.cs ================================================ using System; using System.Configuration; using System.IO; using Composite.Core.Application; using Composite.Core.Application.Plugins.ApplicationOnlineHandler; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.ResourceSystem; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Application.ApplicationOnlineHandlers.AspNetApplicationOnlineHandler { [ConfigurationElementType(typeof(AspNetApplicationOnlineHandlerData))] internal sealed class AspNetApplicationOnlineHandler : IApplicationOnlineHandler { private readonly string _sourceFilename; public AspNetApplicationOnlineHandler(string appOfflineFilename) { Verify.ArgumentNotNullOrEmpty(appOfflineFilename, "appOfflineFilename"); _sourceFilename = Path.Combine(PathUtil.BaseDirectory, PathUtil.Resolve(appOfflineFilename)); } public void TurnApplicationOffline() { ApplicationOfflineCheckHttpModule.FilePath = _sourceFilename; ApplicationOfflineCheckHttpModule.IsOffline = true; } public void TurnApplicationOnline() { ApplicationOfflineCheckHttpModule.IsOffline = false; } public bool IsApplicationOnline() { return !ApplicationOfflineCheckHttpModule.IsOffline; } public bool CanPutApplicationOffline(out string errorMessage) { if(!C1File.Exists(_sourceFilename)) { errorMessage = "AspNetApplicationOnlineHandler: Template file '{0}' is missing".FormatWith(_sourceFilename); return false; } string websiteRoot = PathUtil.BaseDirectory; if (!PathUtil.WritePermissionGranted(websiteRoot)) { errorMessage = StringResourceSystemFacade.GetString( "Composite.Core.PackageSystem.PackageFragmentInstallers", "NotEnoughNtfsPermissions") .FormatWith(websiteRoot); return false; } errorMessage = null; return true; } } [Assembler(typeof(AspNetApplicationOnlineHandlerAssembler))] internal class AspNetApplicationOnlineHandlerData : ApplicationOnlineHandlerData { private const string _appOfflineFilenamePropertyName = "appOfflineFilename"; [ConfigurationProperty(_appOfflineFilenamePropertyName, IsRequired = true)] public string AppOfflineFilename { get { return (string)base[_appOfflineFilenamePropertyName]; } set { base[_appOfflineFilenamePropertyName] = value; } } } internal sealed class AspNetApplicationOnlineHandlerAssembler : IAssembler<IApplicationOnlineHandler, ApplicationOnlineHandlerData> { public IApplicationOnlineHandler Assemble(IBuilderContext context, ApplicationOnlineHandlerData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { AspNetApplicationOnlineHandlerData data = (AspNetApplicationOnlineHandlerData)objectConfiguration; return new AspNetApplicationOnlineHandler(data.AppOfflineFilename); } } } ================================================ FILE: Composite/Plugins/Application/ApplicationStartupHandlers/AttributeBasedApplicationStartupHandler/AttributeBasedApplicationStartupHandler.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Security; using System.Xml; using System.Xml.Serialization; using Composite.Core; using Composite.Core.Application; using Composite.Core.Application.Plugins.ApplicationStartupHandler; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.Types; using Microsoft.Extensions.DependencyInjection; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Core.Application { /// <summary> /// Using this attribute on a class will cause the CMS to call methods on it at startup. /// The following methods will be called, if they exist: /// /// <code> /// /* This handler will be called first, before C1 initialization, and allow you to register services exposed by <see cref="Composite.Core.ServiceLocator"/> /// public void ConfigureServices(<see cref="Microsoft.Extensions.DependencyInjection.IServiceCollection"/> serviceCollection) {} /// /* This handler will be called before C1 initialization. The data layer cannot be used here. */ /// public void OnBeforeInitialize() {} /// /* This handler will be called after initialization of C1 core. */ /// public void OnInitialized() {} /// </code> /// </summary> /// <example> /// To register a service on <see cref="Composite.Core.ServiceLocator"/>: /// <code> /// [ApplicationStartup] /// public class MyServiceRegistration /// { /// public void ConfigureServices(IServiceCollection serviceCollection) /// { /// // Register a singleton service that will be retrievable via Composite.Core.ServiceLocator /// serviceCollection.AddSingleton(typeof(ITestStuff), typeof(TestStuff)); /// } /// } /// </code> /// /// If OnBeforeInitialize() or OnInitialized() has any parameters, they will be provided via the ServiceLocator. /// /// <code> /// [ApplicationStartup] /// public class MyAppStartupHandler /// { /// public void OnBeforeInitialize() /// { /// } /// /// public void OnInitialized(Composite.Core.Logging.ILog log) /// { /// log.LogInformation("Dependency Injection supported here"); /// } /// } /// </code> /// </example> /// <notes> /// Class and method can be static, but do not need to be. /// </notes> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public sealed class ApplicationStartupAttribute : Attribute { /// <summary> /// If set to <value>True</value>, the exceptions will not be muted and the website will fail to start. /// </summary> public bool AbortStartupOnException { get; set; } } } namespace Composite.Plugins.Application.ApplicationStartupHandlers.AttributeBasedApplicationStartupHandler { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ConfigurationElementType(typeof(NonConfigurableApplicationStartupHandler))] public sealed class AttributeBasedApplicationStartupHandler : IApplicationStartupHandler { /// <exclude /> public void ConfigureServices(IServiceCollection serviceCollection) { var serviceCollectionParameter = new object[] { serviceCollection }; foreach (var startupHandler in _startupHandlers) { var methodInfo = startupHandler.ConfigureServicesMethod; try { if (methodInfo != null) { if (methodInfo.IsStatic) { methodInfo.Invoke(null, serviceCollectionParameter); } else { var instance = Activator.CreateInstance(methodInfo.DeclaringType); methodInfo.Invoke(instance, serviceCollectionParameter); } } } catch (Exception ex) { ProcessHandlerException(startupHandler, methodInfo, ex); } } } /// <exclude /> public void OnBeforeInitialize(IServiceProvider serviceProvider) { ExecuteEventHandlers(serviceProvider, handler => handler.OnBeforeInitializeMethod); } /// <exclude /> public void OnInitialized(IServiceProvider serviceProvider) { ExecuteEventHandlers(serviceProvider, handler => handler.OnInitializedMethod); } private class StartupHandlerInfo { public StartupHandlerInfo(Type type, ApplicationStartupAttribute attribute) { Type = type; Attribute = attribute; } public Type Type { get; } public ApplicationStartupAttribute Attribute { get; } public MethodInfo OnBeforeInitializeMethod { get; set; } public MethodInfo OnInitializedMethod { get; set; } public MethodInfo ConfigureServicesMethod { get; set; } } private static readonly string LogTitle = typeof (AttributeBasedApplicationStartupHandler).Name; private static readonly string CacheFileName = "StartupHandlersCache.xml"; private static readonly string OnBeforeInitializeMethodName = nameof(IApplicationStartupHandler.OnBeforeInitialize); private static readonly string OnInitializedMethodName = nameof(IApplicationStartupHandler.OnInitialized); private static readonly string ConfigureServicesMethodName = nameof(IApplicationStartupHandler.ConfigureServices); private readonly List<StartupHandlerInfo> _startupHandlers = new List<StartupHandlerInfo>(); private static readonly string[] AssembliesToIgnore = { "Composite.Workflows", "Composite.Generated", "ICSharpCode.SharpZipLib", "TidyNet", "System.", "Microsoft.", "Newtonsoft.Json" }; private static XmlSerializer _xmlSerializer; private string _cacheFilePath; /// <exclude /> public AttributeBasedApplicationStartupHandler() { List<AssemblyInfo> cachedTypesInfo = GetCachedAssemblyInfo(); bool cacheHasBeenUpdated = false; foreach(string filePath in AssemblyFacade.GetAssembliesFromBin()) { StartupHandlerInfo[] types = null; try { types = GetSubscribedTypes(filePath, cachedTypesInfo, ref cacheHasBeenUpdated); } catch (Exception e) { LogAssemblyLoadException(filePath, e); } if(types != null) { Subscribe(types); } } Assembly appCodeAsm = AssemblyFacade.GetAppCodeAssembly(); if (appCodeAsm != null) { Subscribe(GetSubscribedTypes(appCodeAsm.GetTypes())); } if (cacheHasBeenUpdated) { SaveTypesCache(cachedTypesInfo); } } private void Subscribe(StartupHandlerInfo[] startupHandlers) { foreach (StartupHandlerInfo startupHandler in startupHandlers) { var type = startupHandler.Type; var methods = type.GetMethods(); startupHandler.ConfigureServicesMethod = methods.FirstOrDefault(m => m.Name == ConfigureServicesMethodName && m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType == typeof(IServiceCollection)); startupHandler.OnBeforeInitializeMethod = methods.FirstOrDefault(m => m.Name == OnBeforeInitializeMethodName); startupHandler.OnInitializedMethod = methods.FirstOrDefault(m => m.Name == OnInitializedMethodName); _startupHandlers.Add(startupHandler); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass", Justification = "This is a temp file, do not go through IO layer")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass", Justification = "This is a temp file, do not go through IO layer")] private List<AssemblyInfo> GetCachedAssemblyInfo() { var result = new List<AssemblyInfo>(); if (!File.Exists(CacheFilePath)) { return result; } SubscribedTypesCache cached; try { using (var fileStream = File.Open(CacheFilePath, FileMode.Open)) { cached = GetSerializer().Deserialize(fileStream) as SubscribedTypesCache; } } catch (Exception ex) { if(ex is IOException || ex is UnauthorizedAccessException) { Log.LogWarning(LogTitle, $"Failed to open file '{CacheFilePath}'"); Log.LogError(LogTitle, ex); return result; } Exception innerEx = ex; if(ex is InvalidOperationException && ex.InnerException != null) { innerEx = ex.InnerException; } if(innerEx is XmlException || innerEx is SerializationException) { Log.LogWarning(LogTitle, $"Failed to deserialize file '{CacheFilePath}'"); Log.LogError(LogTitle, ex); return result; } throw; } if (cached?.Assemblies != null && cached.Assemblies.Length != 0) { result.AddRange(cached.Assemblies); } return result; } private static StartupHandlerInfo[] GetSubscribedTypes( string filePath, List<AssemblyInfo> cachedTypesInfo, ref bool cacheHasBeenUpdated) { string assemblyName = Path.GetFileNameWithoutExtension(filePath); foreach (string assemblyToIgnore in AssembliesToIgnore) { if (assemblyName == assemblyToIgnore || assemblyName.StartsWith(assemblyToIgnore + ",") || (assemblyToIgnore.EndsWith(".") && assemblyName.StartsWith(assemblyToIgnore))) { return null; } } DateTime modificationDate = C1File.GetLastWriteTime(filePath); var cachedInfo = cachedTypesInfo.FirstOrDefault(asm => asm.AssemblyName == assemblyName); if (cachedInfo != null) { if (cachedInfo.LastModified == modificationDate) { string[] subscribedTypesNames = cachedInfo.SubscribedTypes; if(subscribedTypesNames.Length == 0) { return new StartupHandlerInfo[0]; } var asm = Assembly.LoadFrom(filePath); return (from typeName in subscribedTypesNames let type = asm.GetType(typeName) where type != null let attribute = type.GetCustomAttributes(false) .OfType<ApplicationStartupAttribute>() .FirstOrDefault() where attribute != null select new StartupHandlerInfo(type, attribute)).ToArray(); } // Removing cache entry if it is obsolete cachedTypesInfo.Remove(cachedInfo); } Assembly assembly; try { assembly = Assembly.LoadFrom(filePath); } catch (ReflectionTypeLoadException ex) { Log.LogWarning(LogTitle, $"Failed to load assembly '{filePath}'"); if(ex.LoaderExceptions != null && ex.LoaderExceptions.Length > 0) { Log.LogError(LogTitle, ex.LoaderExceptions[0]); } return null; } if (!AssemblyFacade.AssemblyPotentiallyUsesType(assembly, typeof (ApplicationStartupAttribute))) { return null; } Type[] types; if (!TryGetTypes(assembly, out types)) { return new StartupHandlerInfo[0]; } var result = GetSubscribedTypes(types); var newCacheEntry = new AssemblyInfo { AssemblyName = assembly.GetName().Name, LastModified = modificationDate, SubscribedTypes = result.Select(sh => sh.Type.FullName).ToArray() }; cachedTypesInfo.Add(newCacheEntry); cacheHasBeenUpdated = true; return result; } private static StartupHandlerInfo[] GetSubscribedTypes(Type[] types) { var result = new List<StartupHandlerInfo>(); foreach (Type type in types) { try { var attribute = type.GetCustomAttributes(false) .OfType<ApplicationStartupAttribute>() .FirstOrDefault(); if (attribute != null) { result.Add(new StartupHandlerInfo(type, attribute)); } } catch(SecurityException) { // While running under "medium trust" getting attributes may throw SecurityException while getting attributes for some classes } } return result.ToArray(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass", Justification = "This is a temp file, do not go through IO layer")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass", Justification = "This is a temp file, do not go through IO layer")] private void SaveTypesCache(List<AssemblyInfo> cachedTypesInfo) { SubscribedTypesCache root = null; if(cachedTypesInfo.Count > 0) { root = new SubscribedTypesCache {Assemblies = cachedTypesInfo.ToArray()}; } try { if(root == null) { File.Delete(CacheFilePath); } else { if (!C1Directory.Exists(CacheDirectoryPath)) { C1Directory.CreateDirectory(CacheDirectoryPath); } using (var fileStream = File.Open(CacheFilePath, FileMode.Create)) { GetSerializer().Serialize(fileStream, root); } } } catch (Exception) { Log.LogWarning(LogTitle, $"Failed to open file '{CacheFilePath}' for writing - this may lead to slower start up times, if this issue persist. In that case, check that this file is accessible to the web application for writes."); } } [DebuggerStepThrough] private static bool TryGetTypes(Assembly assembly, out Type[] types) { try { types = assembly.GetTypes(); return true; } catch (TypeLoadException exception) { Log.LogError(LogTitle, new Exception($"Failed to load assembly '{assembly.FullName}'", exception)); types = null; return false; } catch(ReflectionTypeLoadException exception) { var exceptionToLog = exception.LoaderExceptions != null ? exception.LoaderExceptions.First() : exception; Log.LogError(LogTitle, new Exception($"Failed to load assembly '{assembly.FullName}'", exceptionToLog)); types = null; return false; } } /// <exclude /> [Obsolete("Use Composite.Core.Types.AssemblyFacade.IsAppCodeDll(assembly)", true)] public static bool IsAppCodeDll(Assembly assembly) { return AssemblyFacade.IsAppCodeDll(assembly); } private static XmlSerializer GetSerializer() { // NOTE: Performance critical to have serializer inside Composite.Core.XmlSerializers.dll if (_xmlSerializer == null) { _xmlSerializer = new XmlSerializer(typeof(SubscribedTypesCache), new [] {typeof(AssemblyInfo)}); } return _xmlSerializer; } private static string CacheDirectoryPath => PathUtil.Resolve(GlobalSettingsFacade.CacheDirectory); private string CacheFilePath { get { if (_cacheFilePath == null) { _cacheFilePath = Path.Combine(CacheDirectoryPath, CacheFileName); } return _cacheFilePath; } } private void ExecuteEventHandlers(IServiceProvider serviceProvider, Func<StartupHandlerInfo,MethodInfo> methodLocator) { foreach (var startupHandler in _startupHandlers.Where(h => methodLocator(h) != null)) { MethodInfo methodInfo = methodLocator(startupHandler); try { InvokeWithServices(serviceProvider, methodInfo); } catch (Exception ex) { ProcessHandlerException(startupHandler, methodInfo, ex); } } } private void ProcessHandlerException(StartupHandlerInfo startupHandler, MethodInfo methodInfo, Exception ex) { var type = methodInfo.DeclaringType; var message = $"Failed to execute startup handler. Type: '{type.FullName}', Assembly: '{type.Assembly.FullName}'"; if (startupHandler.Attribute.AbortStartupOnException) { throw new InvalidOperationException(message, ex); } Log.LogError(LogTitle, message); Log.LogError(LogTitle, ex is TargetInvocationException ? ex.InnerException : ex); } private static void InvokeWithServices(IServiceProvider serviceProvider, MethodInfo methodInfo) { object[] methodArguments = methodInfo.GetParameters().Select(p => serviceProvider.GetRequiredService(p.ParameterType)).ToArray(); object methodClass = methodInfo.IsStatic ? null : ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, methodInfo.DeclaringType); methodInfo.Invoke(methodClass, methodArguments); } private static void LogAssemblyLoadException(string filePath, Exception e) { var logEx = new InvalidOperationException($"Failed to load types from file '{filePath}'", e); Log.LogError(LogTitle, logEx); Exception toExamine = e; while (toExamine != null) { ReflectionTypeLoadException reflectionTypeLoadException = toExamine as ReflectionTypeLoadException; if (reflectionTypeLoadException != null) { Exception[] loaderExceptions = reflectionTypeLoadException.LoaderExceptions; foreach (Exception loaderException in loaderExceptions) { Log.LogError(LogTitle + " | LOADEREXCEPTION", loaderException.Message); } } toExamine = toExamine.InnerException; } } /// <exclude /> [Serializable] public class SubscribedTypesCache { /// <exclude /> public AssemblyInfo[] Assemblies { get; set; } } /// <exclude /> [Serializable] public class AssemblyInfo { /// <exclude /> public string AssemblyName { get; set; } /// <exclude /> public DateTime LastModified { get; set; } /// <exclude /> public string[] SubscribedTypes; } } } ================================================ FILE: Composite/Plugins/Commands/ConsoleCommandHandlers/BrowseUrl.cs ================================================ using Composite.C1Console.Commands; using Composite.C1Console.Commands.Plugins.ConsoleCommandHandler; using Composite.C1Console.Elements; using Composite.Core.Extensions; using Composite.Core.Routing; using Composite.Data; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Commands.ConsoleCommandHandlers { [ConfigurationElementType(typeof(NonConfigurableConsoleCommandHandler))] internal class BrowseUrl : IConsoleCommandHandler { public void HandleConsoleCommand(string consoleId, string commandPayload) { string url = commandPayload; var entityToken = UrlToEntityTokenFacade.TryGetEntityToken(url); if (entityToken == null) { PageUrlData pageUrlData = PageUrls.ParseUrl(url); var page = pageUrlData?.GetPage(); if (page == null) { return; } entityToken = page.GetDataEntityToken(); } ConsoleCommandHelper.SelectConsoleElement(consoleId, entityToken); } } } ================================================ FILE: Composite/Plugins/Commands/ConsoleCommandHandlers/ConsoleCommandHelper.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Elements; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.Core.WebClient.FlowMediators; using Composite.Core.WebClient.Services.TreeServiceObjects; namespace Composite.Plugins.Commands.ConsoleCommandHandlers { static class ConsoleCommandHelper { /// <summary> /// Selects the specified element in the console /// </summary> /// <param name="consoleId">The console id.</param> /// <param name="entityToken">The entity token.</param> public static void SelectConsoleElement(string consoleId, EntityToken entityToken) { var serializedEntityToken = EntityTokenSerializer.Serialize(entityToken, true); var rootEntityToken = AttachingPoint.PerspectivesRoot.EntityToken; var refreshInfo = TreeServicesFacade.FindEntityToken(rootEntityToken, entityToken, new List<RefreshChildrenParams>(new[] { new RefreshChildrenParams { ProviderName = rootEntityToken.Source, EntityToken = EntityTokenSerializer.Serialize(rootEntityToken, true) } })); if (refreshInfo == null || refreshInfo.Count == 0) { return; } string perspectiveElementKey = refreshInfo.Count > 1 ? refreshInfo[1].ElementKey : refreshInfo[0].ElementKey; var selectItem = new SelectElementQueueItem { EntityToken = serializedEntityToken, PerspectiveElementKey = perspectiveElementKey }; ConsoleMessageQueueFacade.Enqueue(selectItem, consoleId); } /// <summary> /// Selects the specified element in the console, doesn't change the perspective /// </summary> /// <param name="consoleId">The console id.</param> /// <param name="entityToken">The entity token.</param> public static void SelectConsoleElementWithoutPerspectiveChange(string consoleId, EntityToken entityToken) { var serializedEntityToken = EntityTokenSerializer.Serialize(entityToken, true); var selectItem = new SelectElementQueueItem { EntityToken = serializedEntityToken, }; ConsoleMessageQueueFacade.Enqueue(selectItem, consoleId); } } } ================================================ FILE: Composite/Plugins/Commands/ConsoleCommandHandlers/FocusData.cs ================================================ using System.Linq; using Composite.C1Console.Commands; using Composite.C1Console.Commands.Plugins.ConsoleCommandHandler; using Composite.Core.Types; using Composite.Data; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Commands.ConsoleCommandHandlers { [ConfigurationElementType(typeof(NonConfigurableConsoleCommandHandler))] internal class FocusData : IConsoleCommandHandler { public void HandleConsoleCommand(string consoleId, string commandPayload) { string[] parts = commandPayload.Split(':'); if (parts.Length < 2) { return; } string typeName = parts[0]; string keyString = string.Join(":", parts.Skip(1)); var supportedInterfaces = DataFacade.GetAllInterfaces(); var type = supportedInterfaces.FirstOrDefault(t => t.Name == typeName || t.FullName == typeName); if (type == null) { return; } var keyProperty = type.GetSingleKeyProperty(); object key = ValueTypeConverter.Convert(keyString, keyProperty.PropertyType); IData data; using (new DataConnection()) { data = DataFacade.TryGetDataByUniqueKey(type, key); if (data == null) { return; } } var entityToken = data.GetDataEntityToken(); ConsoleCommandHelper.SelectConsoleElement(consoleId, entityToken); } } } ================================================ FILE: Composite/Plugins/Commands/ConsoleCommandHandlers/FocusElement.cs ================================================ using Composite.C1Console.Commands; using Composite.C1Console.Commands.Plugins.ConsoleCommandHandler; using Composite.C1Console.Security; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Commands.ConsoleCommandHandlers { [ConfigurationElementType(typeof(NonConfigurableConsoleCommandHandler))] internal class FocusElement : IConsoleCommandHandler { public void HandleConsoleCommand(string consoleId, string commandPayload) { var serializedEntityToken = commandPayload.Replace("%5C", "\\"); var entityToken = EntityTokenSerializer.Deserialize(serializedEntityToken); ConsoleCommandHelper.SelectConsoleElement(consoleId, entityToken); } } } ================================================ FILE: Composite/Plugins/Components/ComponentProviderSettings.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; using Composite.Core.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Components { internal class ComponentProviderSettings : SerializableConfigurationSection { public const string SectionName = "Composite.Plugins.Components.ComponentProviderConfiguration"; private const string ComponentProvidersProperty = "ComponentProviders"; [ConfigurationProperty(ComponentProvidersProperty, IsRequired = true)] public NameTypeConfigurationElementCollection<ComponentProviderData, ComponentProviderData> ComponentProviders => (NameTypeConfigurationElementCollection<ComponentProviderData, ComponentProviderData>)base[ComponentProvidersProperty]; internal static ComponentProviderData GetProviderPath(string name) { var settings = ConfigurationServices.ConfigurationSource.GetSection(ComponentProviderSettings.SectionName) as ComponentProviderSettings; return settings?.ComponentProviders.FirstOrDefault(provider => provider.Name.Equals(name)); } } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] internal class ComponentProviderData : NameTypeConfigurationElement { [ConfigurationProperty("directory", IsRequired = false, DefaultValue = "~/App_Data/Components")] public string Directory { get { return (string)base["directory"]; } set { base["directory"] = value; } } [ConfigurationProperty("fileSearchPattern", IsRequired = false, DefaultValue = "*.xml")] public string FileSearchPattern { get { return (string)base["fileSearchPattern"]; } set { base["fileSearchPattern"] = value; } } [ConfigurationProperty("topDirectoryOnly", IsRequired = false, DefaultValue = false)] public bool TopDirectoryOnly { get { return (bool)base["topDirectoryOnly"]; } set { base["topDirectoryOnly"] = value; } } } } ================================================ FILE: Composite/Plugins/Components/ComponentTags/TagManager.cs ================================================ using System.Collections.Generic; using System.Linq; using Composite.C1Console.RichContent.Components; using Composite.Core; using Composite.Core.Application; using Composite.Core.IO; using Composite.Core.ResourceSystem; using Composite.Core.Xml; using Microsoft.Extensions.DependencyInjection; namespace Composite.Plugins.Components.ComponentTags { /// <exclude /> [ApplicationStartup] public class TagManagerRegistrar { /// <exclude /> public void ConfigureServices(IServiceCollection serviceCollection) { serviceCollection.Add(ServiceDescriptor.Singleton(new TagManager())); } } /// <summary> /// Service for working with component tags /// </summary> public class TagManager { private static Dictionary<string, string> _tagToTitleMap; private const string TagConfigurationsRelativePath = "~/App_Data/Composite/Configuration/ComponentTags.xml"; internal TagManager() { var doc = XDocumentUtils.Load(PathUtil.Resolve(TagConfigurationsRelativePath)); _tagToTitleMap = (from element in doc.Root?.Elements() select new {Name = element.GetAttributeValue("name"), Value = element.GetAttributeValue("title")}) .ToDictionary(o => o.Name, o => o.Value); } /// <summary> /// Tries to find a locale title for given tag /// </summary> /// <param name="tag"></param> /// <returns></returns> public string GetTagTitle(string tag) { if (_tagToTitleMap.ContainsKey(tag)) { return StringResourceSystemFacade.ParseString(_tagToTitleMap[tag]); } return tag; } /// <summary> /// return a list of tags based on their ordering in configuration file /// </summary> /// <returns></returns> public IEnumerable<string> GetRegisteredTagOrdering() { return _tagToTitleMap.Select(f => GetTagTitle(f.Key)); } /// <summary> /// return a list of all tags based on their ordering in configuration file /// </summary> /// <returns></returns> public IEnumerable<string> GetAllTags() { var componentManager = ServiceLocator.GetRequiredService<ComponentManager>(); return GetRegisteredTagOrdering().Union(componentManager.GetComponents().SelectMany(f=>f.GroupingTags)); } } } ================================================ FILE: Composite/Plugins/Components/ComponentsEndpoint/ComponentsEndpoint.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Castle.Core.Internal; using Composite.C1Console.RichContent.Components; using Composite.C1Console.RichContent.ContainerClasses; using Composite.Core.Application; using Composite.Core.WebClient.Services.WampRouter; using WampSharp.V2.Rpc; namespace Composite.Plugins.Components.ComponentsEndpoint { [ApplicationStartup] internal class ComponentsEndpoint { public static void OnInitialized(ComponentManager componentManager, ComponentChangeNotifier componentChangeNotifier) { WampRouterFacade.RegisterCallee(new ComponentsRpcService(componentManager)); WampRouterFacade.RegisterPublisher(new ComponentPublisher(componentChangeNotifier)); } } /// <summary> /// Rpc service collection for interaction with components /// </summary> public class ComponentsRpcService : IRpcService { private static ComponentManager _componentManager; internal ComponentsRpcService(ComponentManager componentManager) { _componentManager = componentManager; } /// <summary> /// To get all components /// </summary> /// <returns>list of Components</returns> [WampProcedure("components.get")] public IEnumerable<Component> GetComponents(string containerclass = null) { var sepratedContainerClass = ContainerClassManager.ParseToList(containerclass).ToList(); if (!sepratedContainerClass.IsNullOrEmpty()) { return _componentManager.GetComponents() .Where( f => (f.ContainerClasses.IsNullOrEmpty() || f.ContainerClasses.Intersect(sepratedContainerClass).Any()) && (f.AntiTags.IsNullOrEmpty() || !f.AntiTags.Intersect(sepratedContainerClass).Any())); } return _componentManager.GetComponents(); } /// <summary> /// Select a component for use, signal that dialog is finished /// </summary> /// <returns>list of Components</returns> [WampProcedure("components.pick")] public void FinishProvider() { } /// <summary> /// Close dialog without changes /// </summary> /// <returns>list of Components</returns> [WampProcedure("structure.dialog.cancel")] public void CancelProvider() { } } /// <summary> /// Publisher for interaction with components /// </summary> public class ComponentPublisher : IWampEventHandler<ComponentChange,bool> { private readonly ComponentChangeNotifier _componentChangeNotifier; /// <summary> /// Change in components topic /// </summary> public static string Topic => "components.new"; string IWampEventHandler<ComponentChange, bool>.Topic => Topic; /// <summary> /// Event to observe when there is any change in components /// </summary> public IObservable<ComponentChange> Event => _componentChangeNotifier; internal ComponentPublisher(ComponentChangeNotifier componentChangeNotifier) { _componentChangeNotifier = componentChangeNotifier; } /// <summary> /// Data returning after any change happens in components /// </summary> public bool GetNewData() { return true; } } } ================================================ FILE: Composite/Plugins/Components/ComponentsEndpoint/ComponentsResponseMessage.cs ================================================ using System.Collections.Generic; using System.Reflection; using Composite.Core; using Composite.Core.ResourceSystem; using Composite.Core.WebClient.Services.WampRouter; using Composite.Plugins.Components.ComponentTags; using WampSharp.V2.Rpc; namespace Composite.Plugins.Components.ComponentsEndpoint { /// <exclude /> public class ComponentsResponseMessage { /// <exclude /> public string Name => "component-selector-shim"; /// <exclude /> public string Type => "dialogPageShim"; /// <exclude /> public Dialog Dialog => new Dialog(); } /// <exclude /> public class Dialog { /// <exclude /> public string Name => "component-selector"; /// <exclude /> public string SearchPlaceholder => StringResourceSystemFacade.GetString("Composite.Web.VisualEditor", "Components.Window.DialogFilterPlaceholder"); /// <exclude /> public List<Pane> Panes => new List<Pane>() { new Pane() }; } /// <exclude /> public class Pane { /// <exclude /> public Pane() { var tagManager = ServiceLocator.GetRequiredService<TagManager>(); Categories = tagManager.GetAllTags(); } /// <exclude /> public string Name => "component-list"; /// <exclude /> public string Type => "palette"; /// <exclude /> public string Headline => StringResourceSystemFacade.GetString("Composite.Web.VisualEditor", "Components.Window.Headline"); /// <exclude /> public string Context => "left-aside"; /// <exclude /> public string NoItemsText => StringResourceSystemFacade.GetString("Composite.Web.VisualEditor", "Components.Window.NoItems"); /// <exclude /> public IEnumerable<string> Categories { get; } /// <exclude /> public Provider Provider => new Provider(); /// <exclude /> public FinishButton FinishButton => new FinishButton(); /// <exclude /> public FinishProvider FinishProvider => new FinishProvider(); /// <exclude /> public CancelButton CancelButton => new CancelButton(); /// <exclude /> public CancelProvider CancelProvider => new CancelProvider(); /// <exclude /> public UpdateProvider UpdateTopic => new UpdateProvider(); } /// <exclude /> public class Provider : ProviderResponse { /// <exclude /> public override string Name => "elementSource"; /// <exclude /> public override string Uri => ResponseMessageHelper.GetProcedureName<ComponentsRpcService>( nameof(ComponentsRpcService.GetComponents)); } /// <exclude /> public class FinishButton : ButtonResponse { /// <exclude /> public override string Label => StringResourceSystemFacade.GetString("Composite.Web.VisualEditor", "Components.Window.Ok"); /// <exclude /> public override string Style => "main"; } /// <exclude /> public class FinishProvider : ProviderResponse { /// <exclude /> public override string Name => "elementInsert"; /// <exclude /> public override string Protocol => "post"; /// <exclude /> public string Response => "Dialog.RESPONSE_ACCEPT"; /// <exclude /> public string Action => "DialogPageBinding.ACTION_RESPONSE"; /// <exclude /> public List<string> Markup => new List<string>() { "selectedComponentDefinition" }; /// <exclude /> public override string Uri => ""; } /// <exclude /> public class CancelButton : ButtonResponse { /// <exclude /> public override string Label => StringResourceSystemFacade.GetString("Composite.Web.VisualEditor", "Components.Window.Cancel"); /// <exclude /> public override string Style => "dialog"; } /// <exclude /> public class CancelProvider : ProviderResponse { /// <exclude /> public override string Name => "componentListCancel"; /// <exclude /> public override string Protocol => "post"; /// <exclude /> public string Action => "DialogPageBinding.ACTION_RESPONSE"; /// <exclude /> public string Response => "Dialog.RESPONSE_CANCEL"; /// <exclude /> public override string Uri => ""; } /// <exclude /> public class UpdateProvider : ProviderResponse { /// <exclude /> public override string Name => "updateTopic"; /// <exclude /> public override string Uri => ComponentPublisher.Topic; } internal static class ResponseMessageHelper { internal static string GetProcedureName<T>(string methodName) where T : IRpcService { return ((WampProcedureAttribute)MethodBase.GetMethodFromHandle( typeof(T).GetMethod(methodName).MethodHandle) .GetCustomAttributes(typeof(WampProcedureAttribute), true)[0]).Procedure; } } /// <summary> /// Page structure provider contract /// </summary> public abstract class ProviderResponse { /// <summary> /// provider's name /// </summary> public abstract string Name { get; } /// <summary> /// provider's protocol /// </summary> public virtual string Protocol => "wamp"; /// <summary> /// provider's uri /// </summary> public abstract string Uri { get; } } /// <summary> /// page structure button contract /// </summary> public abstract class ButtonResponse { /// <summary> /// button label /// </summary> public abstract string Label { get; } /// <summary> /// button style /// </summary> public abstract string Style { get; } } } ================================================ FILE: Composite/Plugins/Components/FileBasedComponentProvider/FileBasedComponentProvider.cs ================================================ using System; using Composite.C1Console.RichContent.Components; using Composite.Core.Application; using Microsoft.Extensions.DependencyInjection; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reactive.Linq; using System.Security.Cryptography; using System.Text; using System.Xml; using System.Xml.Linq; using Castle.Core.Internal; using Composite.C1Console.RichContent.ContainerClasses; using Composite.Core; using Composite.Core.IO; using Composite.Core.ResourceSystem; using Composite.Core.Xml; using Composite.Plugins.Components.ComponentTags; namespace Composite.Plugins.Components.FileBasedComponentProvider { /// <exclude /> [ApplicationStartup()] public class FileBasedComponentProviderRegistrator { /// <exclude /> public void ConfigureServices(IServiceCollection serviceCollection) { serviceCollection.AddSingleton(typeof(IComponentProvider), typeof(FileBasedComponentProvider)); } } /// <exclude /> public class FileBasedComponentProvider : IComponentProvider { private const string Title = "title"; private const string Description = "description"; private const string Tags = "tags"; private const string ContainerClasses = "container-classes"; private const string Image = "image"; private const string Icon = "icon"; private const string AntiTags = "container-anti-classes"; private readonly ComponentChangeNotifier _changeNotifier; private readonly string _providerDirectory; private readonly string _searchPattern; private readonly SearchOption _searchOption; /// <exclude /> public FileBasedComponentProvider(ComponentChangeNotifier changeNotifier) { _changeNotifier = changeNotifier; var componentProviderSetting = ComponentProviderSettings.GetProviderPath(nameof(FileBasedComponentProvider)); Verify.IsNotNull(componentProviderSetting, "No components configuration found for the provider " + nameof(FileBasedComponentProvider)); _providerDirectory = componentProviderSetting.Directory; _searchPattern = componentProviderSetting.FileSearchPattern; _searchOption = componentProviderSetting.TopDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories; Directory.CreateDirectory(PathUtil.Resolve(_providerDirectory)); FileBasedComponentObservable().Subscribe( x => _changeNotifier.ProviderChange(x.ProviderId)); } /// <exclude /> public string ProviderId => nameof(FileBasedComponentProvider); /// <exclude /> public IEnumerable<Component> GetComponents() { return GetAllComponents(); } private IEnumerable<Component> GetAllComponents() { return C1Directory.GetFiles( PathUtil.Resolve(_providerDirectory), _searchPattern, _searchOption) .Select(GetComponentsFromFile).Where(f => f != null); } private Component GetComponentsFromFile(string componentFile) { XDocument document =null; try { document = XDocumentUtils.Load(componentFile); } catch (XmlException exception) { Log.LogError(nameof(FileBasedComponentProvider),$"Error in reading component file: {exception}"); return null; } var xElement = document.Descendants().FirstOrDefault(); if (xElement != null) { #warning making id based on file location, check again once function based provider come alive var xmlBytes = new UnicodeEncoding().GetBytes(componentFile); var hashedXmlBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(xmlBytes); var id = new Guid(hashedXmlBytes); var title = StringResourceSystemFacade.ParseString(xElement.GetAttributeValue(Namespaces.Components + Title)) ?? Path.GetFileNameWithoutExtension(componentFile); var description = StringResourceSystemFacade.ParseString(xElement.GetAttributeValue(Namespaces.Components + Description)) ?? ""; var groupingTagsRaw = StringResourceSystemFacade.ParseString(xElement.GetAttributeValue(Namespaces.Components + Tags)) ?? GuessGroupingTagsBasedOnPath(componentFile); List<string> groupingTags = new List<string>(); if (!groupingTagsRaw.IsNullOrEmpty()) { var tagManager = ServiceLocator.GetRequiredService<TagManager>(); groupingTags.AddRange( groupingTagsRaw.ToLower() .Split(',') .Select(f => f.Trim()) .Select(tagManager.GetTagTitle) .ToList()); } var containerClasses = ContainerClassManager.ParseToList(xElement.GetAttributeValue(Namespaces.Components + ContainerClasses)); var antiTags = ContainerClassManager.ParseToList(xElement.GetAttributeValue(Namespaces.Components + AntiTags)); var componentImage = new ComponentImage() { CustomImageUri = xElement.GetAttributeValue(Namespaces.Components + Image), IconName = xElement.GetAttributeValue(Namespaces.Components + Icon) }; xElement.Attributes().Where(f=>f.Name.Namespace == Namespaces.Components).Remove(); return new Component { Id = id, Title = title, Description = description, GroupingTags = groupingTags, ContainerClasses = containerClasses, AntiTags = antiTags, ComponentImage = componentImage, ComponentDefinition = xElement.Document.GetDocumentAsString() }; } return null; } private string GuessGroupingTagsBasedOnPath(string componentFile) { var componentPath = Path.GetDirectoryName(componentFile); var cleanedProviderDirectory = _providerDirectory.Replace('/', '\\').Replace("~", ""); var componentPathfromComponentFolder = componentPath?.Substring( componentPath.IndexOf(cleanedProviderDirectory, StringComparison.Ordinal) + cleanedProviderDirectory.Length); return componentPathfromComponentFolder?.Replace('\\', ',').Trim(','); } private IObservable<ComponentChange> FileBasedComponentObservable() { var fileSystemWatcher = new FileSystemWatcher { Path = PathUtil.Resolve(_providerDirectory), IncludeSubdirectories = _searchOption == SearchOption.AllDirectories, EnableRaisingEvents = true, Filter = _searchPattern }; return Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>( h => fileSystemWatcher.Deleted += h, h => fileSystemWatcher.Deleted -= h) .Select(e => new ComponentChange() { ProviderId = nameof(FileBasedComponentProvider) }) .Merge(Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>( h => fileSystemWatcher.Changed += h, h => fileSystemWatcher.Changed -= h) .Select(e => new ComponentChange() { ProviderId = nameof(FileBasedComponentProvider) })) .Merge(Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>( h => fileSystemWatcher.Created += h, h => fileSystemWatcher.Created -= h) .Select(e => new ComponentChange() { ProviderId = nameof(FileBasedComponentProvider) })) .Merge(Observable.FromEventPattern<RenamedEventHandler, RenamedEventArgs>( h => fileSystemWatcher.Renamed += h, h => fileSystemWatcher.Renamed -= h) .Select(e => new ComponentChange() { ProviderId = nameof(FileBasedComponentProvider) })); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/Common/PropertyNameMappingConfigurationElement.cs ================================================ using System.Configuration; namespace Composite.Plugins.Data.DataProviders.Common { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class PropertyNameMappingConfigurationElement : ConfigurationElement { private const string _propertyNamePropertyName = "propertyName"; /// <exclude /> [ConfigurationProperty(_propertyNamePropertyName, IsRequired=true)] public string PropertyName { get { return (string)base[_propertyNamePropertyName]; } set { base[_propertyNamePropertyName] = value; } } private const string _sourcePropertyNamePropertyName = "sourcePropertyName"; /// <exclude /> [ConfigurationProperty(_sourcePropertyNamePropertyName, IsRequired=true)] public string SourcePropertyName { get { return (string)base[_sourcePropertyNamePropertyName]; } set { base[_sourcePropertyNamePropertyName] = value; } } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/Common/PropertyNameMappingConfigurationElementCollection.cs ================================================ using System.Collections.Generic; using System.Configuration; using System.Linq; namespace Composite.Plugins.Data.DataProviders.Common { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class PropertyNameMappingConfigurationElementCollection : ConfigurationElementCollection, IEnumerable<PropertyNameMappingConfigurationElement> { /// <exclude /> public void Add(string propertyName, string sourcePropertyName) { var element = new PropertyNameMappingConfigurationElement(); element.PropertyName = propertyName; element.SourcePropertyName = sourcePropertyName; BaseAdd(element); } /// <exclude /> protected override ConfigurationElement CreateNewElement() { return new PropertyNameMappingConfigurationElement(); } /// <exclude /> protected override object GetElementKey(ConfigurationElement element) { return string.Format("{0}{1}", ((PropertyNameMappingConfigurationElement)element).PropertyName, ((PropertyNameMappingConfigurationElement)element).SourcePropertyName); } IEnumerator<PropertyNameMappingConfigurationElement> IEnumerable<PropertyNameMappingConfigurationElement>.GetEnumerator() { return this.OfType<PropertyNameMappingConfigurationElement>().GetEnumerator(); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/FileSystemDataProvider/FileSystemDataProvider.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.IO; using System.Linq; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.Types; using Composite.Data; using Composite.Data.Plugins.DataProvider; using Composite.Data.Plugins.DataProvider.Streams; using Composite.Data.Types; using Composite.Plugins.Data.DataProviders.FileSystemDataProvider.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; using System.Diagnostics; namespace Composite.Plugins.Data.DataProviders.FileSystemDataProvider { [ConfigurationElementType(typeof(FileSystemDataProviderData))] internal class FileSystemDataProvider : IWritableDataProvider, IFileSystemDataProvider { private DataProviderContext _context; private string _resolvedRootDirectory; private Type _fileInterfaceType; private string _fileSearchPattern; private SearchOption _fileSearchOptions; private int _resolvedRootDirectoryPathLength; private Type _fileSystemFileTypeWithInterface; private object _lock = new object(); internal FileSystemDataProvider(string resolvedRootDirectory, Type fileInterfaceType, string fileSearchPattern, bool topDirectoryOnly) { if (string.IsNullOrEmpty(resolvedRootDirectory)) throw new ArgumentNullException("resolvedRootDirectory"); if (fileInterfaceType == null) throw new ArgumentNullException("fileInterfaceType"); if (string.IsNullOrEmpty(fileSearchPattern)) throw new ArgumentNullException("fileSearchPattern"); if (typeof(IFile).IsAssignableFrom(fileInterfaceType) == false) throw new ArgumentException(string.Format("The interface '{0}' does not implement the interface '{1}'", fileInterfaceType, typeof(IFile))); if (typeof(IFile).GetPropertiesRecursively().Count < fileInterfaceType.GetPropertiesRecursively().Count) throw new ArgumentException(string.Format("The interface '{0}' may not have any properties", fileInterfaceType)); resolvedRootDirectory = resolvedRootDirectory.Replace("/", @"\"); if (Path.IsPathRooted(resolvedRootDirectory) == false) throw new ArgumentException("Path must be rooted", "resolvedRootDirectory"); if (resolvedRootDirectory.EndsWith("/") || resolvedRootDirectory.EndsWith(@"\")) resolvedRootDirectory = resolvedRootDirectory.Substring(0, resolvedRootDirectory.Length - 1); _resolvedRootDirectory = resolvedRootDirectory; _fileInterfaceType = fileInterfaceType; _fileSearchPattern = fileSearchPattern; _resolvedRootDirectoryPathLength = _resolvedRootDirectory.Length; _fileSearchOptions = (topDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories); _fileSystemFileTypeWithInterface = FileSystemFileGenerator.GenerateFileSystemFileWithInterface(fileInterfaceType); } public DataProviderContext Context { set { _context = value; } } public IEnumerable<Type> GetSupportedInterfaces() { List<Type> supportedInterfaces = new List<Type>(); supportedInterfaces.Add(_fileInterfaceType); return supportedInterfaces; } public IQueryable<T> GetData<T>() where T : class, IData { CheckInterface(typeof(T)); return GetFiles<T>(); } public T GetData<T>(IDataId dataId) where T : class, IData { CheckInterface(typeof(T)); FileSystemFileDataId fileSystemFileDataId = dataId as FileSystemFileDataId; if (fileSystemFileDataId == null) { return null; } return BuildNewFileSystemFile<T>(fileSystemFileDataId.FullPath); } public void Update(IEnumerable<IData> datas) { foreach (IData data in datas) { CheckInterface(data.GetType()); FileSystemFileDataId id = (FileSystemFileDataId)data.DataSourceId.DataId; string oldPath = id.FullPath; FileSystemFile file = (FileSystemFile)data; file.SystemPath = CreateSystemPath(file.Path); FileSystemFileStreamManager.WriteFileToDisk(file); if (file.SystemPath != oldPath) { C1File.Delete(oldPath); } } } public List<T> AddNew<T>(IEnumerable<T> datas) where T : class, IData { List<T> result = new List<T>(); foreach (IData data in datas) { CheckInterface(data.GetType()); IFile file = (IFile)data; string filename = CreateSystemPath( Path.Combine(file.FolderPath, file.FileName)); FileSystemFile fileSystemFile = Activator.CreateInstance(_fileSystemFileTypeWithInterface) as FileSystemFile; fileSystemFile.SetDataSourceId(_context.CreateDataSourceId(new FileSystemFileDataId(filename), _fileInterfaceType)); fileSystemFile.FolderPath = file.FolderPath; fileSystemFile.FileName = file.FileName; fileSystemFile.SystemPath = filename; using (C1StreamReader streamReader = new C1StreamReader(file.GetReadStream())) { using (C1StreamWriter streamWriter = new C1StreamWriter(fileSystemFile.GetNewWriteStream())) { streamWriter.Write(streamReader.ReadToEnd()); } } FileSystemFileStreamManager.WriteFileToDisk(fileSystemFile); result.Add(fileSystemFile as T); } return result; } public void Delete(IEnumerable<DataSourceId> dataSourceIds) { foreach (DataSourceId dataSourceId in dataSourceIds) { FileSystemFileDataId dataId = (FileSystemFileDataId)dataSourceId.DataId; FileSystemFileStreamManager.DeleteFile(dataId.FullPath); C1File.Delete(dataId.FullPath); } } [DebuggerStepThrough] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass", Justification = "This is what we want, touch is used later on")] public bool ValidatePath<TFile>(TFile file, out string errorMessage) where TFile: IFile { errorMessage = ""; string filename = CreateSystemPath(Path.Combine(file.FolderPath, file.FileName)); if (filename.Length > 250) return false; return true; } private IQueryable<T> GetFiles<T>() where T : class, IData { var result = from file in C1Directory.GetFiles(_resolvedRootDirectory, _fileSearchPattern, _fileSearchOptions) select BuildNewFileSystemFile<T>(file); return result.AsQueryable(); } private void CheckInterface(Type interfaceType) { if (_fileInterfaceType.IsAssignableFrom(interfaceType) == false) throw new ArgumentException(string.Format("Unexpected interface '{0}' - only '{1}' is supported", interfaceType, _fileInterfaceType)); } private T BuildNewFileSystemFile<T>(string fullPath) where T : class, IData { string localPath = fullPath.Substring(_resolvedRootDirectoryPathLength).Replace('/', '\\'); return BuildNewFileSystemFile<T>(_context.CreateDataSourceId(new FileSystemFileDataId(fullPath), _fileInterfaceType), localPath, fullPath); } private T BuildNewFileSystemFile<T>(DataSourceId dataSourceId, string localPath, string fullPath) where T : class, IData { FileSystemFile fileSystemFile = Activator.CreateInstance(_fileSystemFileTypeWithInterface) as FileSystemFile; fileSystemFile.SetDataSourceId(dataSourceId); fileSystemFile.FolderPath = Path.GetDirectoryName(localPath); fileSystemFile.FileName = Path.GetFileName(localPath); fileSystemFile.SystemPath = fullPath; return fileSystemFile as T; } private string CreateSystemPath(string localPath) { localPath = localPath.Replace('/', '\\'); if (localPath.StartsWith("\\") == false) throw new InvalidOperationException(string.Format("The path '{0}' should start with a '\\'", localPath)); string lPath = localPath.Remove(0, 1); string s = Path.Combine(_resolvedRootDirectory, lPath); return Path.Combine(_resolvedRootDirectory, lPath); } } [Assembler(typeof(FileSystemDataProviderAssembler))] internal sealed class FileSystemDataProviderData : DataProviderData { private const string _rootDirectoryProperty = "rootDirectory"; [ConfigurationProperty(_rootDirectoryProperty, IsRequired = true)] public string RootDirectory { get { return (string)base[_rootDirectoryProperty]; } set { base[_rootDirectoryProperty] = value; } } private const string _fileSearchPatternProperty = "fileSearchPattern"; [ConfigurationProperty(_fileSearchPatternProperty, IsRequired = false, DefaultValue = "*")] public string FileSearchPattern { get { return (string)base[_fileSearchPatternProperty]; } set { base[_fileSearchPatternProperty] = value; } } private const string _topDirectoryOnlyProperty = "topDirectoryOnly"; [ConfigurationProperty(_topDirectoryOnlyProperty, IsRequired = false, DefaultValue = false)] public bool TopDirectoryOnly { get { return (bool)base[_topDirectoryOnlyProperty]; } set { base[_topDirectoryOnlyProperty] = value; } } private const string _fileInterfaceTypeProperty = "fileInterfaceType"; [ConfigurationProperty(_fileInterfaceTypeProperty, IsRequired = false, DefaultValue = typeof(IFile))] [TypeConverter(typeof(TypeManagerTypeNameConverter))] public Type FileInterfaceType { get { return (Type)base[_fileInterfaceTypeProperty]; } set { base[_fileInterfaceTypeProperty] = value; } } } internal sealed class FileSystemDataProviderAssembler : IAssembler<IDataProvider, DataProviderData> { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IDataProvider Assemble(IBuilderContext context, DataProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { FileSystemDataProviderData configuration = objectConfiguration as FileSystemDataProviderData; if (configuration == null) throw new ArgumentException("Expected configuration to be of type FileSystemDataProviderData", "objectConfiguration"); string resolvedRootDirectory = PathUtil.Resolve(configuration.RootDirectory); if (typeof(IFile).IsAssignableFrom(configuration.FileInterfaceType) == false) { string invalidInterfaceSelectionMsg = string.Format("The supplied fileInterfaceType '{0}' does not implement '{1}'", configuration.FileInterfaceType, typeof(IFile)); throw new ConfigurationErrorsException(invalidInterfaceSelectionMsg, configuration.ElementInformation.Source, configuration.ElementInformation.LineNumber); } if (string.IsNullOrEmpty(configuration.FileSearchPattern)) { string invalidFileSearchPatternMsg = "The file search pattern can not be empty. Use '*' for all files."; throw new ConfigurationErrorsException(invalidFileSearchPatternMsg, configuration.ElementInformation.Source, configuration.ElementInformation.LineNumber); } return new FileSystemDataProvider(resolvedRootDirectory, configuration.FileInterfaceType, configuration.FileSearchPattern, configuration.TopDirectoryOnly); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/FileSystemDataProvider/Foundation/FileSystemFile.cs ================================================ using Composite.Data; using Composite.Data.Types; using Composite.Data.Streams; using Composite.Data.Plugins.DataProvider.Streams; namespace Composite.Plugins.Data.DataProviders.FileSystemDataProvider.Foundation { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [FileStreamManager(typeof(FileSystemFileStreamManager))] public abstract class FileSystemFile : FileSystemFileBase, IFile { private DataSourceId _dataSourceId; /// <exclude /> public FileSystemFile() { } /// <exclude /> public DataSourceId DataSourceId { get { return _dataSourceId; } set { _dataSourceId = value; } } internal void SetDataSourceId(DataSourceId dataSourceId) { _dataSourceId = dataSourceId; } internal string Path { get { return System.IO.Path.Combine(this.FolderPath, this.FileName); } } /// <exclude /> public string FolderPath { get; set; } /// <exclude /> public string FileName { get; set; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/FileSystemDataProvider/Foundation/FileSystemFileDataId.cs ================================================ using System; using Composite.Data; namespace Composite.Plugins.Data.DataProviders.FileSystemDataProvider.Foundation { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class FileSystemFileDataId : IDataId { private string _fullPath; /// <exclude /> public FileSystemFileDataId() {} internal FileSystemFileDataId(string fullPath) { _fullPath = fullPath; } /// <exclude /> public string FullPath { get { if (string.IsNullOrEmpty(_fullPath)) throw new InvalidOperationException("RelativePath has not been initialized or has an invalid value"); return _fullPath; } set { _fullPath = value; } } /// <exclude /> public override int GetHashCode() => _fullPath.GetHashCode(); /// <exclude /> public override bool Equals(object obj) => obj is FileSystemFileDataId dataId && dataId.FullPath == _fullPath; } } ================================================ FILE: Composite/Plugins/Data/DataProviders/FileSystemDataProvider/Foundation/FileSystemFileGenerator.cs ================================================ using System; using System.Reflection; using System.Reflection.Emit; namespace Composite.Plugins.Data.DataProviders.FileSystemDataProvider.Foundation { internal static class FileSystemFileGenerator { internal static Type GenerateFileSystemFileWithInterface(Type interfaceType) { var asm = new AssemblyName(typeof(FileSystemFileGenerator).Name); AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(asm, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule"); var typeSignature = typeof (FileSystemFileGenerator).Namespace + ".Generated." + interfaceType.FullName.Replace(".", "_"); TypeBuilder tb = moduleBuilder.DefineType(typeSignature, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout, typeof(FileSystemFile), new [] { interfaceType }); return tb.CreateType(); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/FileSystemMediaFileProvider/FileSystemMediaFile.cs ================================================ using System; using System.Globalization; using System.IO; using System.Security.Cryptography; using System.Text; using Composite.Core; using Composite.Core.IO; using Composite.Data; using Composite.Data.Plugins.DataProvider.Streams; using Composite.Data.Streams; using Composite.Data.Types; namespace Composite.Plugins.Data.DataProviders.FileSystemMediaFileProvider { [FileStreamManager(typeof(FileSystemFileStreamManager))] internal sealed class FileSystemMediaFile : FileSystemFileBase, IMediaFile { public FileSystemMediaFile(string systemPath, string fileName, string folderName, string storeId, DataSourceId dataSourceId) { Id = CalculateId(folderName, fileName); SystemPath = systemPath; FileName = fileName; FolderPath = folderName; StoreId = storeId; DataSourceId = dataSourceId; } private static Guid CalculateId(string folderName, string fileName) { return GetHashValue(folderName + "/" + fileName); } private static Guid GetHashValue(string value) { return HashingHelper.ComputeMD5Hash(value, Encoding.ASCII); } public Guid Id { get; internal set; } public string KeyPath { get { return this.GetKeyPath(); } } public string CompositePath { get { return this.GetCompositePath(); } set { throw new NotImplementedException(); } } public string StoreId { get; set; } public string Title { get { return this.FileName; } set { this.FileName = value; } } public string Description { get { return ""; } set { } } public string Tags { get { return ""; } set { } } public string Culture { get { return CultureInfo.InvariantCulture.Name; } set { ; } } public string MimeType { get { return MimeTypeInfo.GetCanonicalFromExtension(Path.GetExtension(this.FileName)); } } public int? Length { get { C1FileInfo fileInfo = new C1FileInfo(this.SystemPath); return (int)fileInfo.Length; } } public DateTime? CreationTime { get { return C1File.GetCreationTime(this.SystemPath); } } public DateTime? LastWriteTime { get { return C1File.GetLastWriteTime(this.SystemPath); } } public bool IsReadOnly { get { return (C1File.GetAttributes(this.SystemPath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly; } set { ; } } public string FolderPath { get; set; } public string FileName { get; set; } public DataSourceId DataSourceId { get; private set; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/FileSystemMediaFileProvider/FileSystemMediaFileFolder.cs ================================================ using System; using Composite.Data.Types; using Composite.Data; namespace Composite.Plugins.Data.DataProviders.FileSystemMediaFileProvider { internal sealed class FileSystemMediaFileFolder : IMediaFileFolder { private string _path; private string _storeId; private readonly DataSourceId _dataSourceId; public FileSystemMediaFileFolder(string path, string storeId, DataSourceId dataSourceId) { Id = Guid.NewGuid(); _path = path; _storeId = storeId; _dataSourceId = dataSourceId; IsReadOnly = false; } public Guid Id { get; private set; } public string KeyPath { get { return this.GetKeyPath(); } } public string CompositePath { get { return this.GetCompositePath(); } set { throw new NotImplementedException(); } } public string StoreId { get { return _storeId; } set { _storeId = value; ; } } public string Path { get { return _path; } set { _path = value; } } public string Title { get { return ""; } set { ; } } public string Description { get { return ""; } set { ; } } public bool IsReadOnly { get; set; } public DataSourceId DataSourceId { get { return _dataSourceId; } } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/FileSystemMediaFileProvider/FileSystemMediaFileProvider.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using Composite.Core.IO; using Composite.Data; using Composite.Data.Plugins.DataProvider; using Composite.Data.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Data.DataProviders.FileSystemMediaFileProvider { [ConfigurationElementType(typeof(MediaArchiveDataProviderData))] internal sealed class FileSystemMediaFileProvider : IWritableDataProvider { private readonly string _storeId; private readonly string _storeDescription; private readonly string _storeTitle; private readonly string _rootDir; private readonly string[] _excludedDirs; private MediaArchiveStore _store; private DataProviderContext _context; private static readonly int _folderType = 1; private static readonly int _fileType = 2; private static readonly int _storeType = 3; public FileSystemMediaFileProvider(string rootDir, string[] excludedDirs, string storeId, string storeDesc, string storeTitle) { _rootDir = rootDir; _excludedDirs = excludedDirs; _storeId = storeId; _storeDescription = storeDesc; _storeTitle = storeTitle; } private IMediaFileStore Store { get { if (_store == null) { _store = new MediaArchiveStore(_storeId, _storeTitle, _storeDescription, _context.CreateDataSourceId(new MediaDataId(_storeType), typeof(IMediaFileStore))); } return _store; } } public DataProviderContext Context { set { _context = value; } } public IEnumerable<Type> GetSupportedInterfaces() { return new List<Type> { typeof(IMediaFile), typeof(IMediaFileFolder), typeof(IMediaFileStore) }; } public void Update(IEnumerable<IData> datas) { foreach (IData data in datas) { if (data == null) { throw new ArgumentException("Data in list to update must be non-null"); } } foreach (IData data in datas) { MediaDataId dataId = data.DataSourceId.DataId as MediaDataId; if (dataId == null) { throw new ArgumentException("Invalid IData"); } if (dataId.MediaType == _fileType) { IMediaFile updatedFile = (IMediaFile)data; if (updatedFile.StoreId != this.Store.Id) { continue; } if (updatedFile.IsReadOnly) { throw new ArgumentException("Cannot update read only media file " + dataId.FileName); } if (updatedFile.FileName != dataId.FileName || updatedFile.FolderPath != dataId.Path) { string oldPos = GetAbsolutePath(dataId); string newPos = GetAbsolutePath(updatedFile); C1File.Move(oldPos, newPos); } using (Stream readStream = updatedFile.GetReadStream()) { using (Stream writeStream = C1File.Open(GetAbsolutePath(updatedFile), FileMode.Create)) { readStream.CopyTo(writeStream); } } } else { IMediaFileFolder updatedFolder = (IMediaFileFolder)data; if (updatedFolder.StoreId != this.Store.Id) { continue; } if (updatedFolder.IsReadOnly) { throw new ArgumentException("Cannot update read only media folder " + dataId.Path); } C1Directory.Move(GetAbsolutePath(dataId), GetAbsolutePath(updatedFolder)); } } } public List<T> AddNew<T>(IEnumerable<T> datas) where T : class, IData { var result = new List<T>(); foreach (IData data in datas) { if (data == null) { throw new ArgumentException("Data in list to add must be non-null"); } CheckInterface(typeof(T)); } foreach (IData data in datas) { if (typeof(T) == typeof(IMediaFile)) { IMediaFile file = (IMediaFile) data; string fullPath = Path.Combine(Path.Combine(_rootDir, file.FolderPath.Remove(0, 1)), file.FileName); using (Stream readStream = file.GetReadStream()) { using (Stream writeStream = C1File.Open(fullPath, FileMode.CreateNew)) { readStream.CopyTo(writeStream); } } result.Add(CreateFile(fullPath) as T); } else if (typeof(T) == typeof(IMediaFileFolder)) { IMediaFileFolder folder = (IMediaFileFolder)data; string fullPath = Path.Combine(_rootDir, folder.Path.Remove(0, 1)); C1Directory.CreateDirectory(fullPath); result.Add(CreateFolder(fullPath) as T); } } return result; } public void Delete(IEnumerable<DataSourceId> dataSourceIds) { foreach (DataSourceId dataSourceId in dataSourceIds) { if (dataSourceId == null) { throw new ArgumentException("DataSourceIds must me non-null"); } } foreach (DataSourceId dataSourceId in dataSourceIds) { MediaDataId dataId = dataSourceId.DataId as MediaDataId; if (dataId.MediaType == _fileType) { if(IsReadOnlyFolder(dataId.Path)) { throw new ArgumentException("Cannot delete read only file " + dataId.FileName); } C1File.Delete(GetAbsolutePath(dataId)); } else { if (IsReadOnlyFolder(dataId.Path)) { throw new ArgumentException("Cannot delete read only folder " + dataId.Path); } C1Directory.Delete(GetAbsolutePath(dataId), true); } } } public IQueryable<T> GetData<T>() where T : class, IData { CheckInterface(typeof(T)); if (typeof(T) == typeof(IMediaFile)) { var excludePaths = (from dir in _excludedDirs select PathUtil.Resolve(_rootDir + dir.Replace('/', '\\')) + @"\").ToList(); var matches = from filePath in C1Directory.GetFiles( _rootDir, "*", SearchOption.AllDirectories) where !excludePaths.Where( filePath.StartsWith ).Any() select CreateFile( filePath ); return matches.Cast<T>().AsQueryable(); } if (typeof(T) == typeof(IMediaFileFolder)) { var excludePaths = (from dir in _excludedDirs select PathUtil.Resolve(_rootDir + dir.Replace('/','\\')) + @"\").ToList(); var matches = from dirPath in C1Directory.GetDirectories(_rootDir, "*", SearchOption.AllDirectories) where !excludePaths.Any(f => (dirPath + @"\").StartsWith(f)) select CreateFolder(dirPath); return matches.Cast<T>().AsQueryable(); } return new List<T> { Store as T}.AsQueryable<T>(); } public T GetData<T>(IDataId dataId) where T : class, IData { if (dataId == null) { throw new ArgumentNullException("dataId"); } CheckInterface(typeof(T)); MediaDataId mediaDataId = dataId as MediaDataId; if (mediaDataId == null) { return null; } if (mediaDataId.MediaType == _folderType) { if (typeof(T) != typeof(IMediaFileFolder)) { throw new ArgumentException("The dataId specifies a IMediaFileFolder, but the generic method was invoked with different type"); } FileSystemMediaFileFolder folder = (from dirInfo in C1Directory.GetDirectories(_rootDir, "*", SearchOption.AllDirectories) where GetRelativePath(dirInfo) == mediaDataId.Path select CreateFolder(dirInfo)).FirstOrDefault(); return folder as T; } if (mediaDataId.MediaType == _fileType) { if (typeof(T) != typeof(IMediaFile)) { throw new ArgumentException("The dataId specifies a IMediaFile, but the generic method was invoked with different type"); } FileSystemMediaFile file = (from fileInfo in C1Directory.GetFiles(_rootDir, "*", SearchOption.AllDirectories) where GetRelativePath(Path.GetDirectoryName(fileInfo)) == mediaDataId.Path && Path.GetFileName(fileInfo) == mediaDataId.FileName select CreateFile(fileInfo)).FirstOrDefault(); return file as T; } return Store as T; } internal sealed class MediaDataId : IDataId { public MediaDataId(int type, string path = null, string fileName = null) { MediaType = type; Path = path; FileName = fileName; } public int MediaType { get; } public string Path { get; } public string FileName { get; } public override int GetHashCode() => MediaType ^ (Path ?? "").GetHashCode() ^ (FileName ?? "").GetHashCode(); } private string GetAbsolutePath(IMediaFile file) { return Path.Combine(Path.Combine(_rootDir, file.FolderPath.Remove(0, 1)), file.FileName); } private string GetAbsolutePath(IMediaFileFolder folder) { return Path.Combine(_rootDir, folder.Path.Remove(0, 1)); } private string GetAbsolutePath(MediaDataId mediaData) { string folderPath = Path.Combine(_rootDir, mediaData.Path.Remove(0, 1)); if (mediaData.MediaType == _fileType) { return Path.Combine(folderPath, mediaData.FileName); } return folderPath; } private bool IsReadOnlyFolder(string folder) { var folders = from item in _excludedDirs where folder == item || (item.StartsWith(folder) && item[folder.Length] == '/') select item; return folders.Any(); } private bool IsExcludedFolder(string folder) { var folders = from item in _excludedDirs where folder == item || (folder.StartsWith(item) && folder[item.Length] == '/') select item; return folders.Any(); } private string GetRelativePath(string path) { string result = path.Substring(_rootDir.Length).Replace("\\", @"/"); return result == string.Empty ? "/" : result; } private FileSystemMediaFileFolder CreateFolder(string dir) { string relativeDir = GetRelativePath(dir); var folder = new FileSystemMediaFileFolder(relativeDir, Store.Id, _context.CreateDataSourceId(new MediaDataId(_folderType, relativeDir), typeof(IMediaFileFolder))); folder.IsReadOnly = IsReadOnlyFolder(folder.Path); return folder; } private FileSystemMediaFile CreateFile(string filePath) { string relativeDir = GetRelativePath(Path.GetDirectoryName(filePath)); string fileName = Path.GetFileName(filePath); DataSourceId dataSourceId = _context.CreateDataSourceId(new MediaDataId (_fileType , relativeDir, fileName), typeof(IMediaFile)); return new FileSystemMediaFile(filePath, fileName, relativeDir, this.Store.Id, dataSourceId); } private void CheckInterface(Type interfaceType) { if (!typeof(IMediaFile).IsAssignableFrom(interfaceType) && !typeof(IMediaFileFolder).IsAssignableFrom(interfaceType) && !typeof(IMediaFileStore).IsAssignableFrom(interfaceType)) { throw new ArgumentException($"Unexpected interface '{interfaceType}' - only '{typeof(IMediaFile)}, {typeof(IMediaFileFolder)} and {typeof(IMediaFileStore)}' are supported"); } } private sealed class MediaArchiveStore : IMediaFileStore { public MediaArchiveStore(string id, string title, string description, DataSourceId dataSourceId) { Id = id; Title = title; Description = description; DataSourceId = dataSourceId; } public string Id { get; } public string Title { get; } public string Description { get; } //public string Tags { get; set; } public bool IsReadOnly => false; public bool ProvidesMetadata => false; public DataSourceId DataSourceId { get; } } } [Assembler(typeof(FileSystemMediaFileProviderAssembler))] internal sealed class MediaArchiveDataProviderData : DataProviderData { private const string _rootDirectoryProperty = "rootDirectory"; [ConfigurationProperty(_rootDirectoryProperty, IsRequired = true)] public string RootDirectory { get { return (string)base[_rootDirectoryProperty]; } set { base[_rootDirectoryProperty] = value; } } private const string _excludedDirectoriesProperty = "excludedDirectories"; [ConfigurationProperty(_excludedDirectoriesProperty, IsRequired = true)] public string ExcludedDirectories { get { return (string)base[_excludedDirectoriesProperty]; } set { base[_excludedDirectoriesProperty] = value; } } private const string _storeIdProperty = "storeId"; [ConfigurationProperty(_storeIdProperty, IsRequired = true)] public string StoreId { get { return (string)base[_storeIdProperty]; } set { base[_storeIdProperty] = value; } } private const string _storeDescriptionProperty = "storeDescription"; [ConfigurationProperty(_storeDescriptionProperty, IsRequired = true)] public string StoreDescription { get { return (string)base[_storeDescriptionProperty]; } set { base[_storeDescriptionProperty] = value; } } private const string _storeTitleProperty = "storeTitle"; [ConfigurationProperty(_storeTitleProperty, IsRequired = true)] public string StoreTitle { get { return (string)base[_storeTitleProperty]; } set { base[_storeTitleProperty] = value; } } } internal sealed class FileSystemMediaFileProviderAssembler : IAssembler<IDataProvider, DataProviderData> { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IDataProvider Assemble(IBuilderContext context, DataProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { MediaArchiveDataProviderData configuration = objectConfiguration as MediaArchiveDataProviderData; if (configuration == null) throw new ArgumentException("Expected configuration to be of type MediaFileDataProviderData", "objectConfiguration"); string resolvedRootDirectory = PathUtil.Resolve(configuration.RootDirectory); if (!C1Directory.Exists(resolvedRootDirectory)) { string directoryNotFoundMsg = $"Directory '{configuration.RootDirectory}' not found"; throw new ConfigurationErrorsException(directoryNotFoundMsg, configuration.ElementInformation.Source, configuration.ElementInformation.LineNumber); } if (resolvedRootDirectory.EndsWith("\\")) { resolvedRootDirectory = Path.GetDirectoryName(resolvedRootDirectory); } string[] excludedDirs; if (configuration.ExcludedDirectories == null) { excludedDirs = Array.Empty<string>(); } else { excludedDirs = configuration.ExcludedDirectories.Split(';'); } return new FileSystemMediaFileProvider(resolvedRootDirectory, excludedDirs, configuration.StoreId, configuration.StoreDescription, configuration.StoreTitle); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/CodeGeneration/DataContextAssembler.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Data.Linq; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Emit; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration { internal static class DataContextAssembler { private static int VersionNumber; public static Type EmitDataContextClass(IEnumerable<SqlDataProvider.StoreTypeInfo> fields) { return EmitDataContextClass(fields.Select(f => new Tuple<string, Type>(f.FieldName, f.FieldType))); } public static Type EmitDataContextClass(IEnumerable<Tuple<string, Type>> fields) { var aName = new AssemblyName("SqlDataProvider.DataContext"); var appDomain = System.Threading.Thread.GetDomain(); var aBuilder = appDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Run); var module = aBuilder.DefineDynamicModule(aName.Name); TypeBuilder type = module.DefineType("DynamicDataContext" + (VersionNumber++), TypeAttributes.Public, typeof(DataContextBase), new []{ typeof(ISqlDataContext) } ); FieldInfo helperClassFieldInfo = BuildField_sqlDataContextHelperClass(type); BuildConstructor(type, helperClassFieldInfo); BuildMethod_Add(type, helperClassFieldInfo); BuildMethod_Remove(type, helperClassFieldInfo); foreach (var field in fields) { type.DefineField(field.Item1, field.Item2, FieldAttributes.Public); } return type.CreateType(); } private static ConstructorInfo BuildConstructor(TypeBuilder type, FieldInfo helperClassFieldInfo) { // Declaring method builder // Method attributes ConstructorBuilder method = type.DefineConstructor(MethodAttributes.Public, 0, new[] { typeof(IDbConnection) }); // Preparing Reflection instances ConstructorInfo ctor1 = typeof(DebuggerNonUserCodeAttribute).GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[]{ }, null ); ConstructorInfo ctor2 = typeof(DataContextBase).GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[]{ typeof(IDbConnection) }, null ); ConstructorInfo ctor3 = typeof(SqlDataContextHelperClass).GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[]{ typeof(DataContext) }, null ); FieldInfo field4 = helperClassFieldInfo; // Adding custom attributes to method // [DebuggerNonUserCodeAttribute] method.SetCustomAttribute( new CustomAttributeBuilder( ctor1, new Type[] { } ) ); // Parameter connection //ParameterBuilder connection = method.DefineParameter(0, ParameterAttributes.None, "connection"); ILGenerator gen = method.GetILGenerator(); // Writing body gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Call, ctor2); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Newobj, ctor3); gen.Emit(OpCodes.Stfld, field4); gen.Emit(OpCodes.Ret); // finished return method; } private static FieldBuilder BuildField_sqlDataContextHelperClass(TypeBuilder type) { FieldBuilder field = type.DefineField( "_sqlDataContextHelperClass", typeof(SqlDataContextHelperClass), FieldAttributes.Private ); return field; } private static MethodBuilder BuildMethod_Add(TypeBuilder type, FieldInfo helperClassFieldInfo) { // Declaring method builder // Method attributes System.Reflection.MethodAttributes methodAttributes = System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.Virtual | System.Reflection.MethodAttributes.Final | System.Reflection.MethodAttributes.HideBySig | System.Reflection.MethodAttributes.NewSlot; MethodBuilder method = type.DefineMethod("Add", methodAttributes); // Preparing Reflection instances FieldInfo field1 = helperClassFieldInfo; MethodInfo method2 = typeof(SqlDataContextHelperClass).GetMethod( "Add", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[]{ typeof(Object), typeof(String) }, null ); // Setting return type method.SetReturnType(typeof(void)); // Adding parameters method.SetParameters( typeof(Object), typeof(String) ); // Parameter entity ParameterBuilder entity = method.DefineParameter(1, ParameterAttributes.None, "entity"); // Parameter fieldName ParameterBuilder fieldName = method.DefineParameter(2, ParameterAttributes.None, "fieldName"); ILGenerator gen = method.GetILGenerator(); // Writing body gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, field1); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Ldarg_2); gen.Emit(OpCodes.Callvirt, method2); gen.Emit(OpCodes.Ret); // finished return method; } private static MethodBuilder BuildMethod_Remove(TypeBuilder type, FieldInfo helperClassFieldInfo) { // Declaring method builder // Method attributes System.Reflection.MethodAttributes methodAttributes = System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.Virtual | System.Reflection.MethodAttributes.Final | System.Reflection.MethodAttributes.HideBySig | System.Reflection.MethodAttributes.NewSlot; MethodBuilder method = type.DefineMethod("Remove", methodAttributes); // Preparing Reflection instances FieldInfo field1 = helperClassFieldInfo; MethodInfo method2 = typeof(SqlDataContextHelperClass).GetMethod( "Remove", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[]{ typeof(Object), typeof(String) }, null ); // Setting return type method.SetReturnType(typeof(void)); // Adding parameters method.SetParameters( typeof(Object), typeof(String) ); // Parameter entity ParameterBuilder entity = method.DefineParameter(1, ParameterAttributes.None, "entity"); // Parameter fieldName ParameterBuilder fieldName = method.DefineParameter(2, ParameterAttributes.None, "fieldName"); ILGenerator gen = method.GetILGenerator(); // Writing body gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, field1); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Ldarg_2); gen.Emit(OpCodes.Callvirt, method2); gen.Emit(OpCodes.Ret); // finished return method; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/CodeGeneration/DataContextBase.cs ================================================ using System; using System.Data; using System.Data.Linq; using System.Diagnostics; using System.Data.Linq.Mapping; using System.Reflection; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class DataContextBase : DataContext { private static readonly MethodInfo NewIdMethodInfo = typeof (DataContextBase).GetMethod("NewId"); /// <exclude /> [DebuggerNonUserCode] public DataContextBase(IDbConnection connection) : base(connection) { } /// <exclude /> [Function(Name = "NEWID", IsComposable = true)] public Guid NewId() { return Guid.NewGuid(); } internal static MethodInfo GetNewIdMethodInfo() { return NewIdMethodInfo; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/CodeGeneration/DataContextClassGenerator.cs ================================================ using System; using System.CodeDom; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Reflection; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration { internal class DataContextClassGenerator { private const string SqlDataContextHelperClassName = "_sqlDataContextHelperClass"; private readonly string _dataContextClassName; private readonly IEnumerable<Tuple<string, string>> _entityClassNamesAndDataContextFieldNames; /// <summary> /// /// </summary> /// <param name="dataContextClassName"></param> /// <param name="entityClassNamesAndDataContextFieldNames">For all datatypes datacopes. (EntityClassName, DataContextFieldName)</param> public DataContextClassGenerator(string dataContextClassName, IEnumerable<Tuple<string, string>> entityClassNamesAndDataContextFieldNames) { _dataContextClassName = dataContextClassName; _entityClassNamesAndDataContextFieldNames = entityClassNamesAndDataContextFieldNames; } public CodeTypeDeclaration CreateClass() { CodeTypeDeclaration declaration = new CodeTypeDeclaration(); declaration.Name = _dataContextClassName; declaration.IsClass = true; declaration.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed; declaration.BaseTypes.Add(typeof(DataContextBase)); declaration.BaseTypes.Add(typeof(ISqlDataContext)); CodeMemberField codeMemberField = new CodeMemberField(typeof(SqlDataContextHelperClass), SqlDataContextHelperClassName); declaration.Members.Add(codeMemberField); AddConstructor(declaration); AddEntityFields(declaration); AddSqlDataContextMethods(declaration); return declaration; } private static void AddConstructor(CodeTypeDeclaration declaration) { CodeConstructor constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public; constructor.Parameters.Add( new CodeParameterDeclarationExpression( typeof(IDbConnection), "connection")); constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("connection")); constructor.CustomAttributes.Add(new CodeAttributeDeclaration( new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute)) )); constructor.Statements.Add( new CodeAssignStatement( new CodeVariableReferenceExpression(SqlDataContextHelperClassName), new CodeObjectCreateExpression( typeof(SqlDataContextHelperClass), new CodeExpression[] { new CodeThisReferenceExpression() } ) )); declaration.Members.Add(constructor); } private void AddEntityFields(CodeTypeDeclaration declaration) { foreach (Tuple<string, string> value in _entityClassNamesAndDataContextFieldNames) { string entityClassName = value.Item1; string dataContextFieldName = value.Item2; CodeMemberField codeMemberField = new CodeMemberField(new CodeTypeReference(entityClassName), dataContextFieldName); codeMemberField.Attributes = MemberAttributes.Public; declaration.Members.Add(codeMemberField); } } private static void AddSqlDataContextMethods(CodeTypeDeclaration declaration) { CodeMemberMethod codeMemberMethodAdd = new CodeMemberMethod(); codeMemberMethodAdd.Name = "Add"; codeMemberMethodAdd.Attributes = MemberAttributes.Public | MemberAttributes.Final; codeMemberMethodAdd.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "entity")); codeMemberMethodAdd.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "fieldName")); codeMemberMethodAdd.Statements.Add( new CodeMethodInvokeExpression( new CodeVariableReferenceExpression(SqlDataContextHelperClassName), "Add", new CodeExpression[] { new CodeVariableReferenceExpression("entity"), new CodeVariableReferenceExpression("fieldName") } )); declaration.Members.Add(codeMemberMethodAdd); CodeMemberMethod codeMemberMethodRemove = new CodeMemberMethod(); codeMemberMethodRemove.Name = "Remove"; codeMemberMethodRemove.Attributes = MemberAttributes.Public | MemberAttributes.Final; codeMemberMethodRemove.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "entity")); codeMemberMethodRemove.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "fieldName")); codeMemberMethodRemove.Statements.Add( new CodeMethodInvokeExpression( new CodeVariableReferenceExpression(SqlDataContextHelperClassName), "Remove", new CodeExpression[] { new CodeVariableReferenceExpression("entity"), new CodeVariableReferenceExpression("fieldName") } )); declaration.Members.Add(codeMemberMethodRemove); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/CodeGeneration/DataIdClassGenerator.cs ================================================ using System; using System.CodeDom; using System.Linq; using System.Reflection; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Plugins.Data.DataProviders.XmlDataProvider.CodeGeneration; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration { internal sealed class DataIdClassGenerator { private readonly string _dataIdClassName; private readonly DataTypeDescriptor _dataTypeDescriptor; public DataIdClassGenerator(DataTypeDescriptor dataTypeDescriptor, string dataIdClassName) { _dataTypeDescriptor = dataTypeDescriptor; _dataIdClassName = dataIdClassName; } public CodeTypeDeclaration CreateClass() { var codeTypeDeclaration = new CodeTypeDeclaration(_dataIdClassName) { IsClass = true, TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed }; codeTypeDeclaration.BaseTypes.Add(typeof(IDataId)); AddDefaultConstructor(codeTypeDeclaration); AddConstructor(codeTypeDeclaration); AddProperties(codeTypeDeclaration); AddEqualsMethod(codeTypeDeclaration); AddGetHashCodeMethod(codeTypeDeclaration); return codeTypeDeclaration; } private static void AddDefaultConstructor(CodeTypeDeclaration declaration) { var defaultConstructor = new CodeConstructor {Attributes = MemberAttributes.Public | MemberAttributes.Final}; declaration.Members.Add(defaultConstructor); } private void AddConstructor(CodeTypeDeclaration declaration) { var constructor = new CodeConstructor { Attributes = MemberAttributes.Public | MemberAttributes.Final }; foreach (var keyField in _dataTypeDescriptor.PhysicalKeyFields) { Type keyPropertyType = keyField.InstanceType; constructor.Parameters.Add(new CodeParameterDeclarationExpression(keyPropertyType, MakeParamName(keyField.Name))); AddAsignment(constructor, keyField.Name); } declaration.Members.Add(constructor); } private void AddProperties(CodeTypeDeclaration declaration) { foreach (var keyProperty in _dataTypeDescriptor.PhysicalKeyFields) { string keyPropertyName = keyProperty.Name; Type keyPropertyType = keyProperty.InstanceType; string propertyFieldName = MakePropertyFieldName(keyPropertyName); declaration.Members.Add(new CodeMemberField(keyPropertyType, propertyFieldName)); var property = new CodeMemberProperty { Name = keyPropertyName, Attributes = MemberAttributes.Public | MemberAttributes.Final, HasSet = true, HasGet = true, Type = new CodeTypeReference(keyPropertyType) }; property.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), propertyFieldName))); property.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), propertyFieldName), new CodeArgumentReferenceExpression("value"))); declaration.Members.Add(property); } } private static void AddAsignment(CodeConstructor constructor, string name) { string paramName = MakeParamName(name); string propertyFieldName = MakePropertyFieldName(name); constructor.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), propertyFieldName ), new CodeArgumentReferenceExpression(paramName) ) ); } private void AddEqualsMethod(CodeTypeDeclaration declaration) { Verify.That(_dataTypeDescriptor.KeyPropertyNames.Count > 0, "A dynamic type should have at least one key property"); //Generates code like // public override bool Equals(object obj) // { // return obj != null && typeof(TestDataId).IsAssignableFrom(obj.GetType()) // && object.Equals(this.Id, (obj as TestDataId).Id) && .....; // } const string argumentName = "obj"; var method = new CodeMemberMethod { Attributes = MemberAttributes.Public | MemberAttributes.Override, Name = nameof(object.Equals), ReturnType = new CodeTypeReference(typeof(bool)) }; method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), argumentName)); var argument = new CodeArgumentReferenceExpression(argumentName); // CODEGEN: obj != null && typeof(TestDataId).IsAssignableFrom(obj.GetType()) CodeExpression condition = new CodeBinaryOperatorExpression( new CodeBinaryOperatorExpression( argument, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)), CodeBinaryOperatorType.BooleanAnd, new CodeMethodInvokeExpression( new CodeTypeOfExpression(new CodeTypeReference(_dataIdClassName)), nameof(Type.IsAssignableFrom), new CodeMethodInvokeExpression(argument, nameof(GetType)))); foreach (string keyPropertyName in _dataTypeDescriptor.PhysicalKeyPropertyNames) { string propertyFieldName = MakePropertyFieldName(_dataTypeDescriptor.Fields[keyPropertyName].Name); CodeExpression newCondition = new CodeMethodInvokeExpression( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), propertyFieldName), nameof(object.Equals), new CodeFieldReferenceExpression( new CodeCastExpression(this._dataIdClassName, argument), propertyFieldName)); condition = new CodeBinaryOperatorExpression( condition, CodeBinaryOperatorType.BooleanAnd, newCondition); } method.Statements.Add(new CodeMethodReturnStatement(condition)); declaration.Members.Add(method); } private void AddGetHashCodeMethod(CodeTypeDeclaration declaration) { // CODEGEN: private int _hashcode; var hashcodeField = new CodeMemberField(typeof(int), "_hashcode"); // CODEGEN: // public override int GetHashCode() // { // if(_hashcode == 0) // { // _hashcode = _fullPath.GetHashCode() ^ ....; // if(_hashcode == 0) // { // _hashCode = -1; // } // } // // return _hashcode; // } var method = new CodeMemberMethod { Attributes = MemberAttributes.Public | MemberAttributes.Override, Name = nameof(GetHashCode), ReturnType = new CodeTypeReference(typeof(int)) }; Verify.That(_dataTypeDescriptor.KeyPropertyNames.Count > 0, "A dynamic type should have at least one key property"); CodeExpression hashCodeExpression = null; #warning We DO want IDataId classes to reflect both id and VersionId for data, right? foreach (string keyPropertyName in _dataTypeDescriptor.PhysicalKeyFields.Select(f => f.Name)) { string propertyFieldName = MakePropertyFieldName(_dataTypeDescriptor.Fields[keyPropertyName].Name); CodeExpression hashCodePart = new CodeMethodInvokeExpression( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), propertyFieldName), nameof(GetHashCode)); if (hashCodeExpression == null) { hashCodeExpression = hashCodePart; } else { hashCodeExpression = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(DataProviderHelperBase)), nameof(DataProviderHelperBase.Xor)), hashCodeExpression, hashCodePart); } } // "this.__hashcode" var hashCodeFieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_hashcode"); method.Statements.Add(new CodeConditionStatement( new CodeBinaryOperatorExpression( hashCodeFieldReference, CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(0)), new CodeAssignStatement(hashCodeFieldReference, hashCodeExpression), new CodeConditionStatement( new CodeBinaryOperatorExpression( hashCodeFieldReference, CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(0)), new CodeAssignStatement(hashCodeFieldReference, new CodePrimitiveExpression(-1))))); // "return __hashcode" method.Statements.Add(new CodeMethodReturnStatement(hashCodeFieldReference)); declaration.Members.Add(hashcodeField); declaration.Members.Add(method); } private static string MakeParamName(string name) => $"parm{name}"; private static string MakePropertyFieldName(string name) => $"_property{name}"; } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/CodeGeneration/EntityBaseClassGenerator.cs ================================================ using System; using System.CodeDom; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Reflection; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration { internal class EntityBaseClassGenerator { private readonly string _entityBaseClassName; private readonly string _dataIdClassName; private readonly DataTypeDescriptor _dataTypeDescriptor; private readonly string _providerName; public EntityBaseClassGenerator(DataTypeDescriptor dataTypeDescriptor, string entityBaseClassName, string dataIdClassName, string providerName) { _entityBaseClassName = entityBaseClassName; _dataIdClassName = dataIdClassName; _dataTypeDescriptor = dataTypeDescriptor; _providerName = providerName; } public CodeTypeDeclaration CreateClass() { var codeTypeDeclaration = new CodeTypeDeclaration(_entityBaseClassName) { IsClass = true, TypeAttributes = TypeAttributes.Public | TypeAttributes.Abstract }; codeTypeDeclaration.BaseTypes.Add(typeof(INotifyPropertyChanged)); codeTypeDeclaration.BaseTypes.Add(typeof(INotifyPropertyChanging)); codeTypeDeclaration.BaseTypes.Add(typeof(IEntity)); codeTypeDeclaration.BaseTypes.Add(_dataTypeDescriptor.GetFullInterfaceName()); codeTypeDeclaration.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(DataSourceId).FullName), EntityClassesFieldNames.DataSourceIdFieldName)); codeTypeDeclaration.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(DataScopeIdentifier).FullName), EntityClassesFieldNames.DataSourceIdScopeFieldName) { Attributes = MemberAttributes.Family }); codeTypeDeclaration.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(CultureInfo).FullName), EntityClassesFieldNames.DataSourceIdCultureFieldName) { Attributes = MemberAttributes.Family }); AddConstructor(codeTypeDeclaration); AddIEntityImplementation(codeTypeDeclaration); AddIDataSourceProperty(codeTypeDeclaration); AddProperties(codeTypeDeclaration); EntityCodeGeneratorHelper.AddPropertyChanging(codeTypeDeclaration); EntityCodeGeneratorHelper.AddPropertyChanged(codeTypeDeclaration); return codeTypeDeclaration; } private static void AddConstructor(CodeTypeDeclaration declaration) { var constructor = new CodeConstructor { Attributes = MemberAttributes.Public }; constructor.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), EntityClassesFieldNames.DataSourceIdFieldName ), new CodePrimitiveExpression(null) ) ); declaration.Members.Add(constructor); } private void AddIEntityImplementation(CodeTypeDeclaration declaration) { var method = new CodeMemberMethod { Name = "Commit", Attributes = MemberAttributes.Public | MemberAttributes.Final }; foreach (DataFieldDescriptor dataFieldDescriptor in _dataTypeDescriptor.Fields) { string propertyName = dataFieldDescriptor.Name; string fieldName = $"_{propertyName}"; string nullableFieldName = $"_{propertyName}Nullable"; method.Statements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), nullableFieldName ), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null) ), new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeThisReferenceExpression(), "OnPropertyChanging", new CodePrimitiveExpression(propertyName) ) ), new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), fieldName ), new CodePropertyReferenceExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), nullableFieldName ), "Value" ) ), new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeThisReferenceExpression(), "OnPropertyChanged", new CodePrimitiveExpression(propertyName) ) ), new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), nullableFieldName ), new CodePrimitiveExpression(null) ) ) ); } declaration.Members.Add(method); } private void AddIDataSourceProperty(CodeTypeDeclaration declaration) { PropertyInfo propertyInfo = typeof(IData).GetProperty(nameof(IData.DataSourceId)); var codeProperty = new CodeMemberProperty { Attributes = MemberAttributes.Public | MemberAttributes.Final, Name = propertyInfo.Name, HasGet = true, HasSet = false, Type = new CodeTypeReference(propertyInfo.PropertyType) }; var dataIdConstructorParms = new List<CodeExpression>(); foreach (string propertyName in _dataTypeDescriptor.PhysicalKeyFields.Select(f=>f.Name)) { dataIdConstructorParms.Add( new CodePropertyReferenceExpression( new CodeThisReferenceExpression(), propertyName )); } codeProperty.GetStatements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), EntityClassesFieldNames.DataSourceIdFieldName ), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null) ), new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), EntityClassesFieldNames.DataSourceIdFieldName ), new CodeObjectCreateExpression( new CodeTypeReference(typeof(DataSourceId)), new CodeObjectCreateExpression( new CodeTypeReference(_dataIdClassName), dataIdConstructorParms.ToArray() ), new CodePrimitiveExpression(_providerName), new CodeTypeOfExpression(_dataTypeDescriptor.GetFullInterfaceName()), new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), EntityClassesFieldNames.DataSourceIdScopeFieldName ), new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), EntityClassesFieldNames.DataSourceIdCultureFieldName ) ) ) ) ); codeProperty.GetStatements.Add( new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), EntityClassesFieldNames.DataSourceIdFieldName ) )); declaration.Members.Add(codeProperty); } private void AddProperties(CodeTypeDeclaration declaration) { foreach (DataFieldDescriptor dataFieldDescriptor in _dataTypeDescriptor.Fields) { string propertyName = dataFieldDescriptor.Name; Type propertyType = dataFieldDescriptor.InstanceType; string fieldName = $"_{propertyName}"; string nullableFieldName = $"_{propertyName}Nullable"; AddPropertiesAddField(declaration, propertyType, fieldName); AddPropertiesAddNullableField(declaration, propertyType, nullableFieldName); AddPropertiesAddProperty(declaration, propertyName, propertyType, fieldName, nullableFieldName); } } private static void AddPropertiesAddField(CodeTypeDeclaration declaration, Type propertyType, string fieldName) { var fieldMember = new CodeMemberField { Name = fieldName, Type = new CodeTypeReference(propertyType), Attributes = MemberAttributes.Family }; declaration.Members.Add(fieldMember); } private static void AddPropertiesAddNullableField(CodeTypeDeclaration declaration, Type propertyType, string fieldName) { var fieldMember = new CodeMemberField { Name = fieldName, Type = new CodeTypeReference(typeof (ExtendedNullable<>).FullName, new CodeTypeReference(propertyType)), Attributes = MemberAttributes.Family, InitExpression = new CodePrimitiveExpression(null) }; declaration.Members.Add(fieldMember); } private static void AddPropertiesAddProperty(CodeTypeDeclaration declaration, string propertyName, Type propertyType, string fieldName, string nullableFieldName) { var propertyMember = new CodeMemberProperty { Name = propertyName, Type = new CodeTypeReference(propertyType), Attributes = MemberAttributes.Public, HasSet = true, HasGet = true }; propertyMember.GetStatements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), nullableFieldName ), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null) ), new CodeStatement[] { new CodeMethodReturnStatement( new CodePropertyReferenceExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), nullableFieldName ), "Value" ) ) }, new CodeStatement[] { new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), fieldName ) ) } ) ); propertyMember.SetStatements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), nullableFieldName ), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null) ), new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), nullableFieldName ), new CodeObjectCreateExpression( new CodeTypeReference(typeof(ExtendedNullable<>).FullName, new CodeTypeReference(propertyType)) ) ) ) ); propertyMember.SetStatements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), nullableFieldName ), new CodeArgumentReferenceExpression("value") ) ); declaration.Members.Add(propertyMember); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/CodeGeneration/EntityClassGenerator.cs ================================================ using System; using System.CodeDom; using System.Collections.Generic; using System.Data.Linq.Mapping; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Sql; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration { /// <summary> /// There exists an entity class per { datacope, locale } mutation and only one base entity class. /// <example> /// The data type is publishable and localized and there exists two locales (EN, DK). /// This would result in 4 entity classes: /// unpublished+en, enpublished+dk, published+en, published+dk /// </example> /// </summary> internal sealed class EntityClassGenerator { private readonly DataTypeDescriptor _dataTypeDescriptor; private readonly string _entityClassName; private readonly string _entityBaseClassName; private readonly string _tableName; private readonly string _dataScopeIdentifierName; private readonly string _localeCultureName; public EntityClassGenerator(DataTypeDescriptor dataTypeDescriptor, string entityClassName, string entityBaseClassName, string tableName, string dataScopeIdentifierName, string localeCultureName) { _dataTypeDescriptor = dataTypeDescriptor; _entityClassName = entityClassName; _entityBaseClassName = entityBaseClassName; _tableName = tableName; _dataScopeIdentifierName = dataScopeIdentifierName; _localeCultureName = localeCultureName; } public CodeTypeDeclaration CreateClass() { var debugDisplayText = $"SQL entity for '{_dataTypeDescriptor.GetFullInterfaceName()}', culture = '{_localeCultureName}', scope = '{_dataScopeIdentifierName}'"; foreach (var keyPropertyName in _dataTypeDescriptor.KeyPropertyNames) { debugDisplayText += $", {keyPropertyName} = {{{keyPropertyName}}}"; } var labelFieldName = _dataTypeDescriptor.LabelFieldName; if (!string.IsNullOrEmpty(labelFieldName) && !_dataTypeDescriptor.KeyPropertyNames.Contains(labelFieldName)) { debugDisplayText += $", {labelFieldName} = {{{labelFieldName}}}"; } var codeTypeDeclaration = new CodeTypeDeclaration(_entityClassName) { IsClass = true, TypeAttributes = TypeAttributes.Public }; codeTypeDeclaration.BaseTypes.Add(new CodeTypeReference(_entityBaseClassName)); codeTypeDeclaration.CustomAttributes.AddRange(new [] { new CodeAttributeDeclaration( new CodeTypeReference(typeof(TableAttribute)), new CodeAttributeArgument("Name", new CodePrimitiveExpression(_tableName)) ), new CodeAttributeDeclaration( new CodeTypeReference(typeof(DebuggerDisplayAttribute)), new CodeAttributeArgument( new CodePrimitiveExpression(debugDisplayText) ) ) }); string propertyName = typeof(DataScopeIdentifier).GetProperties(BindingFlags.Static | BindingFlags.Public). Where(f => f.Name.Equals(_dataScopeIdentifierName, StringComparison.OrdinalIgnoreCase)). Select(f => f.Name). Single(); CodeMemberField constDataSourceIdCodeMemberField = new CodeMemberField( new CodeTypeReference(typeof(DataScopeIdentifier).FullName), EntityClassesFieldNames.DataSourceIdScopeConstFieldName ); constDataSourceIdCodeMemberField.Attributes = MemberAttributes.Static; constDataSourceIdCodeMemberField.InitExpression = new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(typeof(DataScopeIdentifier)), propertyName ); codeTypeDeclaration.Members.Add(constDataSourceIdCodeMemberField); CodeMemberField constCultureCodeMemberField = new CodeMemberField( new CodeTypeReference(typeof(CultureInfo).FullName), EntityClassesFieldNames.DataSourceIdCultureConstFieldName ); constCultureCodeMemberField.Attributes = MemberAttributes.Static; constCultureCodeMemberField.InitExpression = new CodeObjectCreateExpression( new CodeTypeReference(typeof(CultureInfo)), new CodePrimitiveExpression(_localeCultureName) ); codeTypeDeclaration.Members.Add(constCultureCodeMemberField); AddEntityClassConstructor(codeTypeDeclaration); AddProperties(codeTypeDeclaration); return codeTypeDeclaration; } private static void AddEntityClassConstructor(CodeTypeDeclaration declaration) { CodeConstructor constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public; constructor.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), EntityClassesFieldNames.DataSourceIdScopeFieldName ), new CodeFieldReferenceExpression( null, EntityClassesFieldNames.DataSourceIdScopeConstFieldName ) ) ); constructor.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), EntityClassesFieldNames.DataSourceIdCultureFieldName ), new CodeFieldReferenceExpression( null, EntityClassesFieldNames.DataSourceIdCultureConstFieldName ) ) ); declaration.Members.Add(constructor); } private void AddProperties(CodeTypeDeclaration declaration) { foreach (DataFieldDescriptor dataFieldDescriptor in _dataTypeDescriptor.Fields) { string propertyName = dataFieldDescriptor.Name; Type propertyType = dataFieldDescriptor.InstanceType; string fieldName = string.Format("_{0}", propertyName); string nullableFieldName = string.Format("_{0}Nullable", propertyName); AddPropertiesAddProperty(declaration, propertyName, propertyType, fieldName, nullableFieldName); } } private void AddPropertiesAddProperty(CodeTypeDeclaration declaration, string propertyName, Type propertyType, string fieldName, string nullableFieldName) { SqlColumnInformation columnInformation = _dataTypeDescriptor.CreateSqlColumnInformation(propertyName); string name = propertyName; Type type = propertyType; string dbName = propertyName; string dbType = EntityCodeGeneratorHelper.GetDbType(columnInformation.SqlDbType, columnInformation.IsNullable); bool isNullable = columnInformation.IsNullable; bool isId = columnInformation.IsPrimaryKey; bool isAutoGen = columnInformation.IsIdentity; CodeMemberProperty propertyMember = new CodeMemberProperty(); propertyMember.Name = name; propertyMember.Type = new CodeTypeReference(type); propertyMember.Attributes = MemberAttributes.Public; propertyMember.HasSet = true; propertyMember.HasGet = true; propertyMember.GetStatements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), nullableFieldName ), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null) ), new CodeStatement[] { new CodeMethodReturnStatement( new CodePropertyReferenceExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), nullableFieldName ), "Value" ) ) }, new CodeStatement[] { new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), fieldName ) ) } ) ); propertyMember.SetStatements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodeBaseReferenceExpression(), name ), new CodeArgumentReferenceExpression("value") ) ); propertyMember.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute)))); var codeAttributeArguments = new List<CodeAttributeArgument> { new CodeAttributeArgument("Name", new CodePrimitiveExpression(dbName)), new CodeAttributeArgument("Storage", new CodePrimitiveExpression(fieldName)), new CodeAttributeArgument("DbType", new CodePrimitiveExpression(dbType)), new CodeAttributeArgument("CanBeNull", new CodePrimitiveExpression(isNullable)), new CodeAttributeArgument("IsPrimaryKey", new CodePrimitiveExpression(isId)), new CodeAttributeArgument("IsDbGenerated", new CodePrimitiveExpression(isAutoGen)), new CodeAttributeArgument("UpdateCheck", new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof (UpdateCheck)), nameof(UpdateCheck.Never)) ) }; propertyMember.CustomAttributes.Add(new CodeAttributeDeclaration( new CodeTypeReference(typeof(ColumnAttribute)), codeAttributeArguments.ToArray() )); declaration.Members.Add(propertyMember); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/CodeGeneration/EntityClassesFieldNames.cs ================================================  namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration { internal static class EntityClassesFieldNames { public const string DataSourceIdFieldName = "_dataSourceId"; public const string DataSourceIdScopeFieldName = "_dataScopeIdentifier"; public const string DataSourceIdCultureFieldName = "_locale"; public const string DataSourceIdScopeConstFieldName = "DataScope"; public const string DataSourceIdCultureConstFieldName = "Locale"; } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/CodeGeneration/EntityCodeGeneratorHelper.cs ================================================ using System.CodeDom; using System.ComponentModel; using System.Data; using System.Diagnostics; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration { internal static class EntityCodeGeneratorHelper { public static string GetDbType(SqlDbType dbType, bool isNullable) { string s = dbType.ToString().ToLowerInvariant(); if (s == "varchar") s = "nvarchar"; return string.Format("{0}{1}", s, isNullable ? "" : " NOT NULL"); } public static void AddPropertyChanging(CodeTypeDeclaration declaration) { CodeMemberEvent changingEvent = new CodeMemberEvent(); changingEvent.Name = "PropertyChanging"; changingEvent.Type = new CodeTypeReference(typeof(PropertyChangingEventHandler)); changingEvent.Attributes = MemberAttributes.Public; declaration.Members.Add(changingEvent); CodeMemberMethod changingMethod = new CodeMemberMethod(); changingMethod.Name = "OnPropertyChanging"; changingMethod.ReturnType = new CodeTypeReference(typeof(void)); changingMethod.Attributes = MemberAttributes.Family; changingMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "propertyName")); changingMethod.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute)))); changingMethod.Statements.Add(new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "PropertyChanging"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null) ), new CodeStatement[] { new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeThisReferenceExpression(), "PropertyChanging", new CodeExpression[] { new CodeThisReferenceExpression(), new CodeObjectCreateExpression( typeof(PropertyChangingEventArgs), new CodeExpression[] { new CodeArgumentReferenceExpression("propertyName") } ) } ) ) } )); declaration.Members.Add(changingMethod); } public static void AddPropertyChanged(CodeTypeDeclaration declaration) { CodeMemberEvent changingEvent = new CodeMemberEvent(); changingEvent.Name = "PropertyChanged"; changingEvent.Type = new CodeTypeReference(typeof(PropertyChangedEventHandler)); changingEvent.Attributes = MemberAttributes.Public; declaration.Members.Add(changingEvent); CodeMemberMethod changingMethod = new CodeMemberMethod(); changingMethod.Name = "OnPropertyChanged"; changingMethod.ReturnType = new CodeTypeReference(typeof(void)); changingMethod.Attributes = MemberAttributes.Family; changingMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "propertyName")); changingMethod.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute)))); changingMethod.Statements.Add(new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "PropertyChanged"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null) ), new CodeStatement[] { new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeThisReferenceExpression(), "PropertyChanged", new CodeExpression[] { new CodeThisReferenceExpression(), new CodeObjectCreateExpression( typeof(PropertyChangedEventArgs), new CodeExpression[] { new CodeArgumentReferenceExpression("propertyName") } ) } ) ) } )); declaration.Members.Add(changingMethod); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/CodeGeneration/IEntity.cs ================================================  namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IEntity { /// <exclude /> void Commit(); } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/CodeGeneration/ISqlDataContext.cs ================================================  namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface ISqlDataContext { /// <exclude /> void Add(object entity, string tableName); /// <exclude /> void Remove(object entity, string tableName); } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/CodeGeneration/SqlDataContextHelperClass.cs ================================================ using System; using System.Data.Linq; using System.Reflection; using Composite.Core.Collections.Generic; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Foundation; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration { /// <summary> /// Provides an api to work with generated tables of a DataContext object. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class SqlDataContextHelperClass { readonly DataContext _dataContext; private readonly Hashtable<string, ITable> _tables = new Hashtable<string, ITable>(); private readonly object _syncRoot = new object(); /// <exclude /> public SqlDataContextHelperClass(DataContext dataContext) { _dataContext = dataContext; } /// <exclude /> public void Add(object entity, string tableName) { EnsureTableInitialized(tableName); _tables[tableName].InsertOnSubmit(entity); } /// <exclude /> public void Remove(object entity, string tableName) { EnsureTableInitialized(tableName); ITable table = _tables[tableName]; table.Attach(entity); table.DeleteOnSubmit(entity); } private void EnsureTableInitialized(string tableName) { if(_tables.ContainsKey(tableName)) { return; } lock(_syncRoot) { if (_tables.ContainsKey(tableName)) { return; } Type dataContextType = _dataContext.GetType(); FieldInfo fi = dataContextType.GetField(tableName); Verify.IsNotNull(fi, "DataContext class should have a field with name '{0}'", tableName); Type entityType = fi.FieldType; // Operation takes 3 ms every request :( ITable table = _dataContext.GetTable(entityType); _tables.Add(tableName, table); } } /// <exclude /> internal static ITable GetTable(DataContext _dataContext, SqlDataTypeStoreTable storeInformation) { FieldInfo fi = storeInformation.DataContextQueryableFieldInfo; Verify.IsNotNull(fi, "Missing FieldInfo for a DataContext field."); object value = fi.GetValue(_dataContext); if(value == null) { var helperClassFieldInfo =_dataContext.GetType().GetField("_sqlDataContextHelperClass", BindingFlags.NonPublic | BindingFlags.Instance); Verify.IsNotNull(helperClassFieldInfo, "Helper field isn't exist in DataContext object."); var helper = helperClassFieldInfo.GetValue(_dataContext) as SqlDataContextHelperClass; Verify.That(helper != null, "Helper object has not been set"); helper.EnsureTableInitialized(fi.Name); value = helper._tables[fi.Name]; } return Verify.ResultNotNull(value as ITable); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/CodeGeneration/SqlDataProviderCodeBuilder.cs ================================================ using System; using System.CodeDom; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Linq.Mapping; using System.Linq; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.Serialization.CodeGeneration; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.ProcessControlled; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Foundation; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration { internal class SqlDataProviderCodeBuilder { private readonly CodeGenerationBuilder _codeGenerationBuilder; private readonly string _providerName; private readonly List<Tuple<string, string>> _entityClassNamesAndDataContextFieldNames = new List<Tuple<string, string>>(); private readonly string _namespaceName; public SqlDataProviderCodeBuilder(string providerName, CodeGenerationBuilder codeGenerationBuilder) { _codeGenerationBuilder = codeGenerationBuilder; _providerName = providerName; _namespaceName = NamesCreator.MakeNamespaceName(providerName); AddCodeNamespaces(); } internal void AddDataType(DataTypeDescriptor dataTypeDescriptor, IEnumerable<SqlDataTypeStoreDataScope> sqlDataTypeStoreDataScopes) { Type interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor); if (interfaceType == null) return; IEnumerable<Tuple<string, string>> names; SqlProviderCodeGenerator codeGenerator = new SqlProviderCodeGenerator(_providerName); IEnumerable<CodeTypeDeclaration> codeTypeDeclarations = codeGenerator.CreateCodeDOMs(dataTypeDescriptor, sqlDataTypeStoreDataScopes, out names); codeTypeDeclarations.ForEach(f => _codeGenerationBuilder.AddType(_namespaceName, f)); _entityClassNamesAndDataContextFieldNames.AddRange(names); _codeGenerationBuilder.AddReference(interfaceType.Assembly); // Property serializer for entity tokens and more string dataIdClassFullName = NamesCreator.MakeDataIdClassFullName(dataTypeDescriptor, _providerName); var keyPropertiesDictionary = new Dictionary<string, Type>(); var keyPropertiesList = new List<Tuple<string, Type>>(); foreach (var keyField in dataTypeDescriptor.PhysicalKeyFields) { Verify.That(!keyPropertiesDictionary.ContainsKey(keyField.Name), "Key field with name '{0}' already present. Data type: {1}. Check for multiple [KeyPropertyName(...)] attributes", keyField.Name, dataTypeDescriptor.Namespace + "." + dataTypeDescriptor.Name); keyPropertiesDictionary.Add(keyField.Name, keyField.InstanceType); keyPropertiesList.Add(new Tuple<string, Type>(keyField.Name, keyField.InstanceType)); } PropertySerializerTypeCodeGenerator.AddPropertySerializerTypeCode(_codeGenerationBuilder, dataIdClassFullName, keyPropertiesList); } /// <summary> /// This will not add needed entity class and data context field names if the data entity class does not exist /// </summary> /// <param name="dataTypeDescriptor"></param> /// <param name="sqlDataTypeStoreDataScopes"></param> internal void AddExistingDataType(DataTypeDescriptor dataTypeDescriptor, IEnumerable<SqlDataTypeStoreDataScope> sqlDataTypeStoreDataScopes) { SqlProviderCodeGenerator codeGenerator = new SqlProviderCodeGenerator(_providerName); IEnumerable<Tuple<string, string>> names = codeGenerator.CreateEntityClassNamesAndDataContextFieldNames(dataTypeDescriptor, sqlDataTypeStoreDataScopes); foreach (Tuple<string, string> name in names) { Type type = TypeManager.TryGetType(NamesCreator.MakeNamespaceName(_providerName) + "." + name.Item1); if (type != null) { _codeGenerationBuilder.AddReference(type.Assembly.Location); _entityClassNamesAndDataContextFieldNames.Add(name); foreach (Type interfaceType in type.GetInterfaces()) { _codeGenerationBuilder.AddReference(interfaceType.Assembly); } } } } internal void AddDataContext() { SqlProviderCodeGenerator codeGenerator = new SqlProviderCodeGenerator(_providerName); IEnumerable<CodeTypeDeclaration> codeTypeDeclarations = codeGenerator.CreateDataContextCodeDOMs(_entityClassNamesAndDataContextFieldNames); codeTypeDeclarations.ForEach(f => _codeGenerationBuilder.AddType(_namespaceName, f)); } private void AddCodeNamespaces() { _codeGenerationBuilder.AddReference(typeof(Exception).Assembly); _codeGenerationBuilder.AddReference(typeof(DbType).Assembly); _codeGenerationBuilder.AddReference(typeof(IQueryable).Assembly); _codeGenerationBuilder.AddReference(typeof(TableAttribute).Assembly); _codeGenerationBuilder.AddReference(typeof(IContainer).Assembly); _codeGenerationBuilder.AddReference(typeof(ExpressionCreator).Assembly); _codeGenerationBuilder.AddReference(typeof(ExtendedNullable<>).Assembly); _codeGenerationBuilder.AddReference(typeof(DataSourceId).Assembly); _codeGenerationBuilder.AddReference(typeof(IProcessControlled).Assembly); _codeGenerationBuilder.AddReference(typeof(SqlDataProvider).Assembly); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/CodeGeneration/SqlDataProviderCodeProvider.cs ================================================ using System.ComponentModel; using Composite.Core.Types; using Composite.Data.Foundation.PluginFacades; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration { /// <summary> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] internal class SqlDataProviderCodeProvider : ICodeProvider { public string ProviderName { get; private set; } public SqlDataProviderCodeProvider(string providerName) { ProviderName = providerName; } public void GetCodeToCompile(CodeGenerationBuilder builder) { var sqlDataProvider = (SqlDataProvider)DataProviderPluginFacade.GetDataProvider(ProviderName); sqlDataProvider.BuildAllCode(builder); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/CodeGeneration/SqlDataProviderHelperGenerator.cs ================================================ using System; using System.CodeDom; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Core.Linq; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.Plugins.DataProvider; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration { internal class SqlDataProviderHelperGenerator { private readonly DataTypeDescriptor _dataTypeDescriptor; private readonly string _sqlDataProviderHelperClassName; private readonly string _dataIdClassName; private readonly string _entityClassName; private readonly string _dataContextFieldName; public SqlDataProviderHelperGenerator(DataTypeDescriptor dataTypeDescriptor, string sqlDataProviderHelperClassName, string dataIdClassName, string entityClassName, string dataContextFieldName) { _dataTypeDescriptor = dataTypeDescriptor; _sqlDataProviderHelperClassName = sqlDataProviderHelperClassName; _dataIdClassName = dataIdClassName; _entityClassName = entityClassName; _dataContextFieldName = dataContextFieldName; } public CodeTypeDeclaration CreateClass() { var declaration = new CodeTypeDeclaration(_sqlDataProviderHelperClassName) { IsClass = true, TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed }; declaration.BaseTypes.Add(typeof(ISqlDataProviderHelper)); foreach (string keyFieldName in _dataTypeDescriptor.PhysicalKeyPropertyNames) { string fieldName = CreateDataIdPropertyInfoFieldName(keyFieldName); CodeMemberField codeField = new CodeMemberField(new CodeTypeReference(typeof (PropertyInfo)), fieldName) { InitExpression = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeTypeReferenceExpression(typeof (IDataExtensions)), nameof(IDataExtensions.GetDataPropertyRecursively) ), new CodeExpression[] { new CodeTypeOfExpression(_entityClassName), new CodePrimitiveExpression(keyFieldName) } ) }; declaration.Members.Add(codeField); } AddGetDataByIdMethod(declaration); AddAddDataMethod(declaration); AddRemoveDataMethod(declaration); return declaration; } private void AddGetDataByIdMethod(CodeTypeDeclaration declaration) { const string queryableVariableName = "queryable"; const string dataIdVariableName = "dataId"; const string dataProivderContextVariableName = "dataProivderContext"; const string castedDataIdVariableName = "castedDataId"; const string castedQueryableVariableName = "castedQueryable"; const string paramterExpressionVariableName = "paramter"; const string whereBodyExpressionVariableName = "whereBody"; const string whereLambdaExpressionVariableName = "whereLambda"; const string whereExpressionVariableName = "whereExpression"; const string resultVariableName = "result"; CodeMemberMethod codeMethod = new CodeMemberMethod(); codeMethod.Name = "GetDataById"; codeMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; codeMethod.ReturnType = new CodeTypeReference(typeof(IData)); codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(IQueryable)), queryableVariableName)); codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(IDataId)), dataIdVariableName)); codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(DataProviderContext)), dataProivderContextVariableName)); // casted dataid variable codeMethod.Statements.Add( new CodeVariableDeclarationStatement( new CodeTypeReference(_dataIdClassName), castedDataIdVariableName, new CodeCastExpression( new CodeTypeReference(_dataIdClassName), new CodeVariableReferenceExpression(dataIdVariableName) ) )); // casted queryable variable codeMethod.Statements.Add( new CodeVariableDeclarationStatement( new CodeTypeReference(typeof(IQueryable<>).FullName, new [] { new CodeTypeReference(_entityClassName) }), castedQueryableVariableName, new CodeCastExpression( new CodeTypeReference(typeof(IQueryable<>).FullName, new [] { new CodeTypeReference(_entityClassName) }), new CodeVariableReferenceExpression(queryableVariableName) ) )); // parameter expression variable codeMethod.Statements.Add( new CodeVariableDeclarationStatement( new CodeTypeReference(typeof(ParameterExpression)), paramterExpressionVariableName, new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(Expression)), "Parameter", new CodeExpression[] { new CodeTypeOfExpression(new CodeTypeReference(_entityClassName)), new CodePrimitiveExpression("_getDataByIdParameter_") } ) )); // where body variable CodeExpression currentExpression = null; foreach (string propertyName in _dataTypeDescriptor.PhysicalKeyPropertyNames) { CodeExpression newExpression = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(Expression)), "Equal", new CodeExpression[] { new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(Expression)), "Property", new CodeExpression[] { new CodeVariableReferenceExpression(paramterExpressionVariableName), new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), CreateDataIdPropertyInfoFieldName(propertyName) ) } ), new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(Expression)), "Constant", new CodeExpression[] { new CodePropertyReferenceExpression( new CodeVariableReferenceExpression(castedDataIdVariableName), propertyName ) } ) } ); if (currentExpression == null) { currentExpression = newExpression; } else { currentExpression = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(Expression)), "And", new [] { currentExpression, newExpression } ); } } codeMethod.Statements.Add( new CodeVariableDeclarationStatement( new CodeTypeReference(typeof(Expression)), whereBodyExpressionVariableName, currentExpression )); // where lambda variable codeMethod.Statements.Add( new CodeVariableDeclarationStatement( new CodeTypeReference(typeof(LambdaExpression)), whereLambdaExpressionVariableName, new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(Expression)), "Lambda", new CodeExpression[] { new CodeVariableReferenceExpression(whereBodyExpressionVariableName), new CodeArrayCreateExpression( new CodeTypeReference(typeof(ParameterExpression)), new CodeExpression[] { new CodeVariableReferenceExpression(paramterExpressionVariableName) } ) } ) )); // where expression variable codeMethod.Statements.Add( new CodeVariableDeclarationStatement( new CodeTypeReference(typeof(Expression)), whereExpressionVariableName, new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(ExpressionCreator)), "Where", new CodeExpression[] { new CodePropertyReferenceExpression( new CodeVariableReferenceExpression(castedQueryableVariableName), "Expression" ), new CodeVariableReferenceExpression(whereLambdaExpressionVariableName), } ) )); // get result and store en list variable codeMethod.Statements.Add( new CodeVariableDeclarationStatement( new CodeTypeReference(typeof(List<>).FullName, new [] { new CodeTypeReference(_entityClassName) }), resultVariableName, new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(Enumerable)), "ToList", new CodeExpression[] { new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression(castedQueryableVariableName), "Provider" ), "CreateQuery", new [] { new CodeTypeReference(_entityClassName) } ), new CodeExpression[] { new CodeVariableReferenceExpression(whereExpressionVariableName) } ) } ) )); // test result and return null on empty, wrappe result and return on one, else except codeMethod.Statements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression(resultVariableName), "Count" ), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(1) ), new CodeStatement[] { new CodeMethodReturnStatement( new CodeArrayIndexerExpression( new CodeVariableReferenceExpression(resultVariableName), new CodeExpression[] { new CodePrimitiveExpression(0) } ) ) }, new CodeStatement[] { new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression(resultVariableName), "Count" ), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0) ), new CodeStatement[] { new CodeMethodReturnStatement( new CodePrimitiveExpression(null) ) }, new CodeStatement[] { } ) } )); codeMethod.Statements.Add( new CodeThrowExceptionStatement( new CodeObjectCreateExpression( new CodeTypeReference(typeof(InvalidOperationException)), new CodePrimitiveExpression("More than one data item matched the given data id") ) )); declaration.Members.Add(codeMethod); } private void AddAddDataMethod(CodeTypeDeclaration declaration) { const string dataContextVariableName = "dataContext"; const string dataToAddVariableName = "dataToAdd"; const string dataProivderContextVariableName = "dataProivderContext"; const string castedDataToAddVariableName = "castedDataToAdd"; const string entityClassVariableName = "entity"; CodeMemberMethod codeMethod = new CodeMemberMethod(); codeMethod.Name = "AddData"; codeMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; codeMethod.ReturnType = new CodeTypeReference(typeof(IData)); codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(ISqlDataContext)), dataContextVariableName)); codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(IData)), dataToAddVariableName)); codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(DataProviderContext)), dataProivderContextVariableName)); codeMethod.Statements.Add( new CodeVariableDeclarationStatement( new CodeTypeReference(_dataTypeDescriptor.GetFullInterfaceName()), castedDataToAddVariableName, new CodeCastExpression( new CodeTypeReference(_dataTypeDescriptor.GetFullInterfaceName()), new CodeVariableReferenceExpression(dataToAddVariableName) ) )); codeMethod.Statements.Add( new CodeVariableDeclarationStatement( new CodeTypeReference(_entityClassName), entityClassVariableName, new CodeObjectCreateExpression( new CodeTypeReference(_entityClassName), new CodeExpression[] { } ) )); foreach (string propertyName in _dataTypeDescriptor.Fields.Select(f => f.Name)) { codeMethod.Statements.Add(new CodeCommentStatement(string.Format("Interface property {0}", propertyName))); codeMethod.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression(entityClassVariableName), propertyName ), new CodePropertyReferenceExpression( new CodeVariableReferenceExpression(castedDataToAddVariableName), propertyName ) )); } codeMethod.Statements.Add(new CodeCommentStatement("Done with properties")); codeMethod.Statements.Add( new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeVariableReferenceExpression(dataContextVariableName), "Add", new CodeExpression[] { new CodeVariableReferenceExpression(entityClassVariableName), new CodePrimitiveExpression(_dataContextFieldName) } ) )); codeMethod.Statements.Add( new CodeMethodReturnStatement( new CodeVariableReferenceExpression(entityClassVariableName) )); declaration.Members.Add(codeMethod); } private void AddRemoveDataMethod(CodeTypeDeclaration declaration) { const string dataContextVariableName = "dataContext"; const string dataToRemoveVariableName = "dataToRemove"; CodeMemberMethod codeMethod = new CodeMemberMethod(); codeMethod.Name = "RemoveData"; codeMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; codeMethod.ReturnType = new CodeTypeReference(typeof(void)); codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(ISqlDataContext)), dataContextVariableName)); codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(IData)), dataToRemoveVariableName)); codeMethod.Statements.Add( new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeVariableReferenceExpression(dataContextVariableName), "Remove", new CodeExpression[] { new CodeVariableReferenceExpression(dataToRemoveVariableName), new CodePrimitiveExpression(_dataContextFieldName) } ) )); declaration.Members.Add(codeMethod); } private static string CreateDataIdPropertyInfoFieldName(string propertyName) { return $"_dataIdEntityPropertyInfo{propertyName}"; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/CodeGeneration/SqlProviderCodeGenerator.cs ================================================ using System; using System.CodeDom; using System.Collections.Generic; using Composite.Data.DynamicTypes; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Foundation; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration { internal class SqlProviderCodeGenerator { private readonly string _providerName; public SqlProviderCodeGenerator(string providerName) { _providerName = providerName; } public IEnumerable<CodeTypeDeclaration> CreateCodeDOMs(DataTypeDescriptor dataTypeDescriptor, IEnumerable<SqlDataTypeStoreDataScope> sqlDataTypeStoreDataScopes, out IEnumerable<Tuple<string, string>> entityClassNamesAndDataContextFieldNames) { List<CodeTypeDeclaration> result = new List<CodeTypeDeclaration>(); string dataIdClassName = NamesCreator.MakeDataIdClassName(dataTypeDescriptor); string entityBaseClassName = NamesCreator.MakeEntityBaseClassName(dataTypeDescriptor); DataIdClassGenerator dataIdClassGenerator = new DataIdClassGenerator(dataTypeDescriptor, dataIdClassName); CodeTypeDeclaration dataIdClassCodeTypeDeclaration = dataIdClassGenerator.CreateClass(); result.Add(dataIdClassCodeTypeDeclaration); EntityBaseClassGenerator entityBaseClassGenerator = new EntityBaseClassGenerator(dataTypeDescriptor, entityBaseClassName, dataIdClassName, _providerName); CodeTypeDeclaration entityBaseClassCodeTypeDeclaration = entityBaseClassGenerator.CreateClass(); result.Add(entityBaseClassCodeTypeDeclaration); List<Tuple<string, string>> outResult = new List<Tuple<string, string>>(); foreach (SqlDataTypeStoreDataScope dataScope in sqlDataTypeStoreDataScopes) { string entityClassName = NamesCreator.MakeEntityClassName(dataTypeDescriptor, dataScope.DataScopeName, dataScope.CultureName); EntityClassGenerator entityClassGenerator = new EntityClassGenerator(dataTypeDescriptor, entityClassName, entityBaseClassName, dataScope.TableName, dataScope.DataScopeName, dataScope.CultureName); CodeTypeDeclaration entityClassCodeTypeDeclaration = entityClassGenerator.CreateClass(); result.Add(entityClassCodeTypeDeclaration); string sqlDataProviderHelperClassName = NamesCreator.MakeSqlDataProviderHelperClassName(dataTypeDescriptor, dataScope.DataScopeName, dataScope.CultureName); string dataContextFieldName = NamesCreator.MakeDataContextFieldName(dataScope.TableName); SqlDataProviderHelperGenerator sqlDataProviderHelperGenerator = new SqlDataProviderHelperGenerator(dataTypeDescriptor, sqlDataProviderHelperClassName, dataIdClassName, entityClassName, dataContextFieldName); CodeTypeDeclaration sqlDataProviderHelperTypeDeclaration = sqlDataProviderHelperGenerator.CreateClass(); result.Add(sqlDataProviderHelperTypeDeclaration); outResult.Add(new Tuple<string, string>(entityClassName, dataContextFieldName)); } entityClassNamesAndDataContextFieldNames = outResult; return result; } public IEnumerable<Tuple<string, string>> CreateEntityClassNamesAndDataContextFieldNames(DataTypeDescriptor dataTypeDescriptor, IEnumerable<SqlDataTypeStoreDataScope> sqlDataTypeStoreDataScopes) { List<Tuple<string, string>> entityClassNamesAndDataContextFieldNames = new List<Tuple<string, string>>(); foreach (SqlDataTypeStoreDataScope dataScope in sqlDataTypeStoreDataScopes) { string entityClassName = NamesCreator.MakeEntityClassName(dataTypeDescriptor, dataScope.DataScopeName, dataScope.CultureName); string dataContextFieldName = NamesCreator.MakeDataContextFieldName(dataScope.TableName); entityClassNamesAndDataContextFieldNames.Add(new Tuple<string, string>(entityClassName, dataContextFieldName)); } return entityClassNamesAndDataContextFieldNames; } public IEnumerable<CodeTypeDeclaration> CreateDataContextCodeDOMs(IEnumerable<Tuple<string, string>> entityClassNamesAndDataContextFieldNames) { string dataContextClassName = NamesCreator.MakeDataContextClassName(_providerName); DataContextClassGenerator dataContextClassGenerator = new DataContextClassGenerator(dataContextClassName, entityClassNamesAndDataContextFieldNames); CodeTypeDeclaration dataContextTypeDeclaration = dataContextClassGenerator.CreateClass(); yield return dataContextTypeDeclaration; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/Foundation/DynamicTypesCommon.cs ================================================ using System; using System.Data; using System.Globalization; using Composite.Core.Extensions; using Composite.Data; using Composite.Data.DynamicTypes; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Foundation { internal static class DynamicTypesCommon { internal static string GenerateTableName(DataTypeDescriptor dataTypeDescriptor) { return dataTypeDescriptor.GetFullInterfaceName().Replace('.', '_'); } internal static string GenerateTableName(DataTypeDescriptor dataTypeDescriptor, DataScopeIdentifier dataScope, CultureInfo cultureInfo) { string tableName = dataTypeDescriptor.GetFullInterfaceName().Replace('.', '_'); switch (dataScope.Name) { case DataScopeIdentifier.PublicName: break; case DataScopeIdentifier.AdministratedName: tableName += "_Unpublished"; break; default: throw new InvalidOperationException("Unsupported data scope identifier: '{0}'".FormatWith(dataScope.Name)); } if (!cultureInfo.Name.IsNullOrEmpty()) { tableName += "_" + cultureInfo.Name.Replace('-', '_').Replace(' ', '_'); } return tableName; } internal static string GenerateListTableName(DataTypeDescriptor typeDescriptor, DataFieldDescriptor fieldDescriptor) { return string.Format("{0}_{1}", GenerateTableName(typeDescriptor), fieldDescriptor.Name); } internal static string MapStoreTypeToSqlDataType(StoreFieldType storeType) { string result = string.Format(" [{0}]", GetStoreTypeToSqlDataTypeMapping(storeType)); switch (storeType.PhysicalStoreType) { case PhysicalStoreFieldType.String: return string.Format("{0}({1})", result, storeType.MaximumLength); case PhysicalStoreFieldType.LargeString: return string.Format("{0}({1})", result, "max"); case PhysicalStoreFieldType.Decimal: return string.Format("{0}({1},{2})", result, storeType.NumericPrecision, storeType.NumericScale); default: return result; } } internal static SqlDbType GetStoreTypeToSqlDataTypeMapping(StoreFieldType storeType) { switch (storeType.PhysicalStoreType) { case PhysicalStoreFieldType.Integer: return SqlDbType.Int; case PhysicalStoreFieldType.Long: return SqlDbType.BigInt; case PhysicalStoreFieldType.String: return SqlDbType.NVarChar; case PhysicalStoreFieldType.LargeString: return SqlDbType.NVarChar; case PhysicalStoreFieldType.DateTime: return SqlDbType.DateTime; case PhysicalStoreFieldType.Decimal: return SqlDbType.Decimal; case PhysicalStoreFieldType.Boolean: return SqlDbType.Bit; case PhysicalStoreFieldType.Guid: return SqlDbType.UniqueIdentifier; default: throw new ArgumentException("Unknown store type on field"); } } internal static bool AreSame(DataFieldDescriptor a, DataFieldDescriptor b) { return a.ToXml().ToString() == b.ToXml().ToString(); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/Foundation/InterfaceConfigurationManipulator.cs ================================================ using System; using System.IO; using System.Linq; using Composite.Core; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Plugins.Data.DataProviders.Common; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Foundation { /// <summary> /// Add, change and remove type-to-table mapping information /// </summary> internal static class InterfaceConfigurationManipulator { private static readonly string LogTitle = typeof(InterfaceConfigurationManipulator).Name; static readonly object _syncRoot = new object(); internal static InterfaceConfigurationElement AddNew(string providerName, DataTypeDescriptor dataTypeDescriptor) { lock (_syncRoot) { var configuration = new SqlDataProviderConfiguration(providerName); if (configuration.Section.Interfaces.ContainsInterfaceType(dataTypeDescriptor.DataTypeId)) { Log.LogWarning(LogTitle, "Configuration file '{0}' already contains an interface with data type ID '{1}', type name '{2}'. " + "Possibly there are multiple AppDomain-s running.", configuration.ConfigurationFilePath, dataTypeDescriptor.DataTypeId, dataTypeDescriptor); return configuration.Section.Interfaces.Get(dataTypeDescriptor); } InterfaceConfigurationElement interfaceConfig = BuildInterfaceConfigurationElement(dataTypeDescriptor); configuration.Section.Interfaces.Add(interfaceConfig); configuration.Save(); return interfaceConfig; } } internal static InterfaceConfigurationElement RefreshLocalizationInfo(string providerName, DataTypeDescriptor dataTypeDescriptor) { var changeDescriptor = new DataTypeChangeDescriptor(dataTypeDescriptor, dataTypeDescriptor); return Change(providerName, changeDescriptor, true); } internal static bool ConfigurationExists( string providerName, DataTypeDescriptor dataTypeDescriptor) { lock (_syncRoot) { var configuration = new SqlDataProviderConfiguration(providerName); InterfaceConfigurationElement interfaceConfig = BuildInterfaceConfigurationElement(dataTypeDescriptor); return configuration.Section.Interfaces.ContainsInterfaceType(interfaceConfig); } } internal static InterfaceConfigurationElement Change(string providerName, DataTypeChangeDescriptor changeDescriptor, bool localeChanges) { lock (_syncRoot) { var originalType = changeDescriptor.OriginalType; var alteredType = changeDescriptor.AlteredType; bool typeNameChanged = originalType.Namespace != alteredType.Namespace || originalType.Name != alteredType.Name; if (!localeChanges && !changeDescriptor.AddedDataScopes.Any() && !changeDescriptor.DeletedDataScopes.Any() && !changeDescriptor.AddedKeyFields.Any() && !changeDescriptor.DeletedKeyFields.Any() && !changeDescriptor.KeyFieldsOrderChanged && !typeNameChanged) { // No changes to the config is needed, lets not touch the file. return null; } var configuration = new SqlDataProviderConfiguration(providerName); Guid dataTypeId = originalType.DataTypeId; var existingElement = configuration.Section.Interfaces.Get(originalType); Verify.IsNotNull(existingElement, "Configuration does not contain the original interface with id '{0}'", dataTypeId); configuration.Section.Interfaces.Remove(originalType); InterfaceConfigurationElement newInterfaceConfig = BuildInterfaceConfigurationElement(alteredType, existingElement, typeNameChanged); configuration.Section.Interfaces.Add(newInterfaceConfig); configuration.Save(); return newInterfaceConfig; } } internal static void Remove(string providerName, DataTypeDescriptor dataTypeDescriptor) { lock (_syncRoot) { var configuration = new SqlDataProviderConfiguration(providerName); if (configuration.Section.Interfaces.ContainsInterfaceType(dataTypeDescriptor)) { configuration.Section.Interfaces.Remove(dataTypeDescriptor); configuration.Save(); } } } private static InterfaceConfigurationElement BuildInterfaceConfigurationElement( DataTypeDescriptor dataTypeDescriptor, InterfaceConfigurationElement existingElement = null, bool updateTableNames = false) { var propertyMappings = new PropertyNameMappingConfigurationElementCollection(); //foreach (DataFieldDescriptor field in dataTypeDescriptor.Fields) //{ // propertyMappings.Add(field.Name, field.Name); //} var keyInfo = new SimpleNameTypeConfigurationElementCollection(); foreach (DataFieldDescriptor field in dataTypeDescriptor.PhysicalKeyFields) { keyInfo.Add(field.Name, field.InstanceType); } var stores = new StoreConfigurationElementCollection(); // Fix logic for the case of a localized interface without languages foreach (DataScopeIdentifier dataScope in dataTypeDescriptor.DataScopes) { foreach (var culture in SqlDataProviderStoreManipulator.GetCultures(dataTypeDescriptor)) { string tableName = null; if (!updateTableNames && existingElement != null) { foreach (StoreConfigurationElement table in existingElement.ConfigurationStores) { if (table.DataScope == dataScope.Name && table.CultureName == culture.Name) { tableName = table.TableName; break; } } } tableName = tableName ?? DynamicTypesCommon.GenerateTableName(dataTypeDescriptor, dataScope, culture); stores.Add(new StoreConfigurationElement {TableName = tableName, DataScope = dataScope.Name, CultureName = culture.Name}); } } return new InterfaceConfigurationElement { DataTypeId = dataTypeDescriptor.DataTypeId, IsGeneratedType = dataTypeDescriptor.IsCodeGenerated, ConfigurationStores = stores, ConfigurationPropertyNameMappings = propertyMappings, ConfigurationDataIdProperties = keyInfo, ConfigurationPropertyInitializers = new SimpleNameTypeConfigurationElementCollection() }; } internal static string GetConfigurationFilePath(string dataProviderName) { return Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.ConfigurationDirectory), $"{dataProviderName}.config"); } private sealed class SqlDataProviderConfiguration { readonly string _configurationFilePath; readonly C1Configuration _configuration; public SqlDataProviderConfiguration(string providerName) { _configurationFilePath = GetConfigurationFilePath(providerName); _configuration = new C1Configuration(_configurationFilePath); Section = _configuration.GetSection(SqlDataProviderConfigurationSection.SectionName) as SqlDataProviderConfigurationSection; if (Section == null) { Section = new SqlDataProviderConfigurationSection(); _configuration.Sections.Add(SqlDataProviderConfigurationSection.SectionName, Section); } } public SqlDataProviderConfigurationSection Section { get; private set; } public string ConfigurationFilePath { get { return _configurationFilePath; } } public void Save() { _configuration.Save(); } } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/Foundation/NamesCreator.cs ================================================ using Composite.Data.DynamicTypes; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Foundation { internal static class NamesCreator { internal static string MakeDataIdClassName(DataTypeDescriptor dataTypeDescriptor) { return $"{MakeNiceTypeFullName(dataTypeDescriptor)}DataId"; } internal static string MakeDataIdClassFullName(DataTypeDescriptor dataTypeDescriptor, string providerName) { return $"{MakeNamespaceName(providerName)}.{MakeDataIdClassName(dataTypeDescriptor)}"; } internal static string MakeEntityBaseClassName(DataTypeDescriptor dataTypeDescriptor) { return $"{MakeNiceTypeFullName(dataTypeDescriptor)}EntityBase"; } internal static string MakeEntityBaseClassFullName(DataTypeDescriptor dataTypeDescriptor, string providerName) { return $"{MakeNamespaceName(providerName)}.{MakeEntityBaseClassName(dataTypeDescriptor)}"; } internal static string MakeEntityClassName(DataTypeDescriptor dataTypeDescriptor, string dataScopeIdentifierName, string localeCultureName) { var typeName = MakeNiceTypeFullName(dataTypeDescriptor); if (string.IsNullOrEmpty(localeCultureName)) { return $"{typeName}_{dataScopeIdentifierName}Entity"; } return $"{typeName}_{dataScopeIdentifierName}_{localeCultureName.Replace("-", "")}Entity"; } internal static string MakeEntityClassFullName(DataTypeDescriptor dataTypeDescriptor, string dataScopeIdentifierName, string localeCultureName, string providerName) { return $"{MakeNamespaceName(providerName)}.{MakeEntityClassName(dataTypeDescriptor, dataScopeIdentifierName, localeCultureName)}"; } internal static string MakeSqlDataProviderHelperClassName(DataTypeDescriptor dataTypeDescriptor, string dataScopeIdentifierName, string localeCultureName) { var typeName = MakeNiceTypeFullName(dataTypeDescriptor); if (string.IsNullOrEmpty(localeCultureName)) return $"{typeName}_{dataScopeIdentifierName}SqlDataProviderHelper"; return $"{typeName}_{dataScopeIdentifierName}_{localeCultureName.Replace("-", "")}SqlDataProviderHelper"; } internal static string MakeSqlDataProviderHelperClassFullName(DataTypeDescriptor dataTypeDescriptor, string dataScopeIdentifierName, string localeCultureName, string providerName) { var className = MakeSqlDataProviderHelperClassName(dataTypeDescriptor, dataScopeIdentifierName, localeCultureName); return $"{MakeNamespaceName(providerName)}.{className}"; } internal static string MakeDataContextFieldName(string tableName) { return tableName; } internal static string MakeDataContextClassName(string providerName) { return $"{providerName}DataContext"; } internal static string MakeDataContextClassFullName(string providerName) { return $"{MakeNamespaceName(providerName)}.{MakeDataContextClassName(providerName)}"; } internal static string MakeNamespaceName(string providerName) { return "CompositeGenerated." + providerName; } private static string MakeNiceTypeFullName(DataTypeDescriptor dataTypeDescriptor) { return dataTypeDescriptor.GetFullInterfaceName().Replace('.', '_').Replace('+', '_'); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/Foundation/RequireTransactionScope.cs ================================================ using System; using System.ComponentModel; using System.Transactions; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Foundation { /// <summary> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] internal class RequireTransactionScope : IDisposable { private TransactionScope _scope; public RequireTransactionScope() { if (Transaction.Current == null) { _scope = new TransactionScope(); } } public void Complete() { if (_scope != null) { _scope.Complete(); } } public void Dispose() { if (_scope != null) { _scope.Dispose(); } #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// <exclude /> ~RequireTransactionScope() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/Foundation/SqlDataProviderStoreManipulator.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.Sql; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.Types; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Sql; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Foundation { internal sealed class SqlDataProviderStoreManipulator { private static readonly object _lock = new object(); private readonly string _connectionString; private readonly IEnumerable<InterfaceConfigurationElement> _generatedInterfaces; internal SqlDataProviderStoreManipulator(string connectionString, IEnumerable<InterfaceConfigurationElement> generatedInterfaces) { Verify.ArgumentNotNullOrEmpty(connectionString, "connectionString"); Verify.ArgumentNotNull(generatedInterfaces, "generatedInterfaces"); _connectionString = connectionString; _generatedInterfaces = generatedInterfaces; } internal void CreateStoresForType(DataTypeDescriptor typeDescriptor, Action<string> existingTablesValidator) { lock (_lock) { foreach (DataScopeIdentifier dataScope in typeDescriptor.DataScopes) { foreach (var culture in GetCultures(typeDescriptor)) { CreateStore(typeDescriptor, dataScope, culture, existingTablesValidator); } } } } internal void AddLocale(DataTypeDescriptor typeDescriptor, CultureInfo cultureInfo) { foreach (DataScopeIdentifier dataScope in typeDescriptor.DataScopes) { CreateStore(typeDescriptor, dataScope, cultureInfo); } } internal void RemoveLocale(string providerName, DataTypeDescriptor typeDescriptor, CultureInfo cultureInfo) { foreach (DataScopeIdentifier dataScope in typeDescriptor.DataScopes) { DropStore(typeDescriptor, dataScope, cultureInfo); } } internal static IEnumerable<CultureInfo> GetCultures(DataTypeDescriptor typeDescriptor) { if (typeDescriptor.Localizeable) { return DataLocalizationFacade.ActiveLocalizationCultures; } return new [] { CultureInfo.InvariantCulture }; } private void CreateScopeData(DataTypeDescriptor typeDescriptor, DataScopeIdentifier dataScope) { foreach (var cultureInfo in GetCultures(typeDescriptor)) { CreateStore(typeDescriptor, dataScope, cultureInfo); } } internal void CreateStore(DataTypeDescriptor typeDescriptor, DataScopeIdentifier dataScope, CultureInfo cultureInfo, Action<string> existingTablesValidator = null) { string tableName = DynamicTypesCommon.GenerateTableName(typeDescriptor, dataScope, cultureInfo); var tables = GetTablesList(); if (tables.Contains(tableName)) { if (existingTablesValidator != null) { existingTablesValidator(tableName); return; } throw new InvalidOperationException($"Database already contains a table named {tableName}"); } var sql = new StringBuilder(); var sqlColumns = typeDescriptor.Fields.Select(fieldDescriptor => GetColumnInfo(tableName, fieldDescriptor.Name, typeDescriptor, fieldDescriptor, true, false) ).ToList(); sql.AppendFormat("CREATE TABLE dbo.[{0}]({1});", tableName, string.Join(",", sqlColumns)); sql.Append(SetPrimaryKey(tableName, typeDescriptor.PhysicalKeyPropertyNames, typeDescriptor.PrimaryKeyIsClusteredIndex)); try { ExecuteNonQuery(sql.ToString()); } catch (Exception ex) { throw MakeVerboseException(ex); } foreach (var index in typeDescriptor.Indexes) { CreateIndex(tableName, index); } SqlTableInformationStore.ClearCache(_connectionString, tableName); } internal List<string> GetTablesList() { string sql = @" SELECT t.Name FROM sysobjects s INNER JOIN sysobjects t ON s.parent_obj = t.id WHERE t.xtype = 'U'"; DataTable dt = ExecuteReader(sql); List<string> tables = (from DataRow dr in dt.Rows select dr["Name"].ToString()).ToList(); return tables; } #region Db helpers public DataTable ExecuteReader(string commandText) { var conn = SqlConnectionManager.GetConnection(_connectionString); using (var cmd = new SqlCommand(commandText, conn)) { using (var dt = new DataTable()) { using (var rdr = cmd.ExecuteReader()) { if (rdr != null) dt.Load(rdr); return dt; } } } } public void ExecuteNonQuery(string commandText) { if (string.IsNullOrEmpty(commandText)) { return; } Log.LogInformation("SqlDataProvider", commandText); var conn = SqlConnectionManager.GetConnection(_connectionString); using (var cmd = new SqlCommand(commandText, conn)) { cmd.ExecuteNonQuery(); } } public void ExecuteNonQuery(SqlCommand cmd) { var conn = SqlConnectionManager.GetConnection(_connectionString); cmd.Connection = conn; cmd.ExecuteNonQuery(); } public void ExecuteStoredProcedure(string spName, string[] spParams) { string sql = string.Format("{0} {1}", spName, string.Join(",", spParams)); ExecuteNonQuery(sql); } #endregion private string GetConfiguredTableName(DataTypeDescriptor dataTypeDescriptor, DataScopeIdentifier dataScope, string cultureName) { var stores = (from dataInterface in _generatedInterfaces where dataInterface.DataTypeId == dataTypeDescriptor.DataTypeId select dataInterface.Stores).FirstOrDefault(); if (stores == null) { return null; } var tableName = (from store in stores where store.CultureName == cultureName && store.DataScope == dataScope.Name select store.TableName).FirstOrDefault(); return tableName; } internal string TryNormalizeTypeFullName(string typeName) { Type type = TypeManager.TryGetType(typeName); if (type != null) { return TypeManager.TrySerializeType(type); } return typeName; } internal void AlterStoresForType(UpdateDataTypeDescriptor updateDataTypeDescriptor) { DataTypeChangeDescriptor changeDescriptor = updateDataTypeDescriptor.CreateDataTypeChangeDescriptor(); lock (_lock) { foreach (DataScopeIdentifier dataScope in changeDescriptor.AddedDataScopes) { CreateScopeData(changeDescriptor.AlteredType, dataScope); } foreach (DataScopeIdentifier dataScope in changeDescriptor.ExistingDataScopes) { AlterScopeData(updateDataTypeDescriptor, changeDescriptor, dataScope); } if (updateDataTypeDescriptor.PublicationAdded) { HandleEnablingOfPublication(changeDescriptor); } if (updateDataTypeDescriptor.PublicationRemoved) { HandleDisablingOfPublication(changeDescriptor); } foreach (DataScopeIdentifier dataScope in changeDescriptor.DeletedDataScopes) { DropScopeData(changeDescriptor.AlteredType, dataScope); } } } private void HandleDisablingOfPublication(DataTypeChangeDescriptor changeDescriptor) { IEnumerable<CultureInfo> locales = GetCultures(changeDescriptor.OriginalType); foreach (CultureInfo locale in locales) { string oldTableName = GetConfiguredTableName(changeDescriptor.OriginalType, DataScopeIdentifier.Administrated, locale.Name); string newTableName = DynamicTypesCommon.GenerateTableName(changeDescriptor.AlteredType, DataScopeIdentifier.Public, locale); StringBuilder fieldList = GetCommonFields(changeDescriptor); string removeCommandText = string.Format(@"DELETE FROM [{0}];", newTableName); ExecuteNonQuery(removeCommandText); string copyCommandText = string.Format(@" INSERT INTO [{0}] ({2}) SELECT {2} FROM [{1}];", newTableName, oldTableName, fieldList); ExecuteNonQuery(copyCommandText); } } private static StringBuilder GetCommonFields(DataTypeChangeDescriptor changeDescriptor) { var fieldList = new StringBuilder(); foreach (DataFieldDescriptor dataFieldDescriptor in changeDescriptor.OriginalType.Fields) { if (!changeDescriptor.AlteredType.Fields.Any(f => f.Id == dataFieldDescriptor.Id)) continue; if (fieldList.Length > 0) fieldList.Append(", "); fieldList.Append("[" + dataFieldDescriptor.Name + "]"); } return fieldList; } private void HandleEnablingOfPublication(DataTypeChangeDescriptor changeDescriptor) { IEnumerable<CultureInfo> locales = GetCultures(changeDescriptor.OriginalType); foreach (CultureInfo locale in locales) { string oldTableName = GetConfiguredTableName(changeDescriptor.OriginalType, DataScopeIdentifier.Public, locale.Name); string newTableName = DynamicTypesCommon.GenerateTableName(changeDescriptor.AlteredType, DataScopeIdentifier.Administrated, locale); StringBuilder fieldList = GetCommonFields(changeDescriptor); string copyCommandText = string.Format(@" INSERT INTO [{0}] ({2}) SELECT {2} FROM [{1}];", newTableName, oldTableName, fieldList); ExecuteNonQuery(copyCommandText); string updateOldCommandText = string.Format("UPDATE [{0}] SET [{1}] = '{2}'", oldTableName, "PublicationStatus", GenericPublishProcessController.Published); ExecuteNonQuery(updateOldCommandText); string updateNewCommandText = string.Format("UPDATE [{0}] SET [{1}] = '{2}'", newTableName, "PublicationStatus", GenericPublishProcessController.Published); ExecuteNonQuery(updateNewCommandText); } } private void AlterScopeData(UpdateDataTypeDescriptor updateDataTypeDescriptor, DataTypeChangeDescriptor changeDescriptor, DataScopeIdentifier dataScope) { var culturesToDelete = new List<CultureInfo>(); var culturesToChange = new List<CultureInfo>(); var oldCultures = GetCultures(changeDescriptor.OriginalType).Evaluate(); var newCultures = GetCultures(changeDescriptor.AlteredType).Evaluate(); foreach (var culture in oldCultures) { if (newCultures.Contains(culture)) { culturesToChange.Add(culture); } else { culturesToDelete.Add(culture); } } var culturesToAdd = newCultures.Where(culture => !oldCultures.Contains(culture)).ToList(); culturesToAdd.ForEach(culture => CreateStore(changeDescriptor.AlteredType, dataScope, culture)); culturesToChange.ForEach(culture => AlterStore(updateDataTypeDescriptor, changeDescriptor, dataScope, culture)); if (updateDataTypeDescriptor.LocalesToCopyTo != null) { StringBuilder fieldList = GetCommonFields(changeDescriptor); string fromTableName = GetConfiguredTableName(changeDescriptor.OriginalType, dataScope, ""); foreach (CultureInfo locale in updateDataTypeDescriptor.LocalesToCopyTo) { string toTableName = DynamicTypesCommon.GenerateTableName(changeDescriptor.AlteredType, dataScope, locale); string copyCommandText = string.Format(@" INSERT INTO [{0}] ({2}) SELECT {2} FROM [{1}];", toTableName, fromTableName, fieldList); ExecuteNonQuery(copyCommandText); string updateCommandText = string.Format("UPDATE [{0}] SET [{1}] = '{2}'", toTableName, "SourceCultureName", locale.Name); ExecuteNonQuery(updateCommandText); } string removeCommandText = string.Format(@"DELETE FROM [{0}];", fromTableName); ExecuteNonQuery(removeCommandText); } if (updateDataTypeDescriptor.LocaleToCopyFrom != null) { StringBuilder fieldList = GetCommonFields(changeDescriptor); string fromTableName = GetConfiguredTableName(changeDescriptor.OriginalType, dataScope, updateDataTypeDescriptor.LocaleToCopyFrom.Name); string toTableName = DynamicTypesCommon.GenerateTableName(changeDescriptor.AlteredType, dataScope, CultureInfo.InvariantCulture); string copyCommandText = string.Format(@" INSERT INTO [{0}] ({2}) SELECT {2} FROM [{1}];", toTableName, fromTableName, fieldList); ExecuteNonQuery(copyCommandText); } culturesToDelete.ForEach(culture => DropStore(changeDescriptor.OriginalType, dataScope, culture)); } private void AlterStore(UpdateDataTypeDescriptor updateDataTypeDescriptor, DataTypeChangeDescriptor changeDescriptor, DataScopeIdentifier dataScope, CultureInfo culture) { try { string originalTableName = GetConfiguredTableName(changeDescriptor.OriginalType, dataScope, culture.Name); string alteredTableName = originalTableName; // This could be done more nicely! But only give the table a new name if the type has changed its name and not because we changed the naming scheme if (updateDataTypeDescriptor.OldDataTypeDescriptor.Name != updateDataTypeDescriptor.NewDataTypeDescriptor.Name || updateDataTypeDescriptor.OldDataTypeDescriptor.Namespace != updateDataTypeDescriptor.NewDataTypeDescriptor.Namespace) { alteredTableName = DynamicTypesCommon.GenerateTableName(changeDescriptor.AlteredType, dataScope, culture); } var tables = GetTablesList(); if (!tables.Contains(originalTableName)) { throw new InvalidOperationException( $"Unable to alter data type store for type '{changeDescriptor.AlteredType.GetFullInterfaceName()}'. The database does not contain expected table '{originalTableName}'"); } bool primaryKeyChanged = changeDescriptor.AddedKeyFields.Any() || changeDescriptor.DeletedKeyFields.Any() || changeDescriptor.KeyFieldsOrderChanged || changeDescriptor.VersionKeyFieldsChanged || changeDescriptor.OriginalType.PrimaryKeyIsClusteredIndex != changeDescriptor.AlteredType.PrimaryKeyIsClusteredIndex; DropConstraints(originalTableName, primaryKeyChanged); if (originalTableName != alteredTableName) { if (tables.Contains(alteredTableName)) throw new InvalidOperationException( $"Can not rename table '{originalTableName}' to '{alteredTableName}'. A table with that name already exists"); RenameTable(originalTableName, alteredTableName); } var newIndexes = changeDescriptor.AlteredType.Indexes.Select(i => i.ToString()).ToList(); foreach (var oldIndex in changeDescriptor.OriginalType.Indexes) { if (!newIndexes.Contains(oldIndex.ToString())) { DropIndex(alteredTableName, oldIndex); } } DropFields(alteredTableName, changeDescriptor.DeletedFields, changeDescriptor.OriginalType.Fields); ImplementFieldChanges(alteredTableName, changeDescriptor.AlteredType, changeDescriptor.ExistingFields); Dictionary<string, object> defaultValues = null; if (updateDataTypeDescriptor.PublicationAdded) { defaultValues = new Dictionary<string, object> { {"PublicationStatus", GenericPublishProcessController.Draft} }; } AppendFields(alteredTableName, changeDescriptor, changeDescriptor.AddedFields, defaultValues); // Clustered index has to be created first. var createIndexActions = new List<Tuple<bool, Action>>(); if (primaryKeyChanged) { bool isClusteredIndex = changeDescriptor.AlteredType.PrimaryKeyIsClusteredIndex; createIndexActions.Add(new Tuple<bool, Action>(isClusteredIndex, () => ExecuteNonQuery(SetPrimaryKey(alteredTableName, changeDescriptor.AlteredType.PhysicalKeyPropertyNames, isClusteredIndex)) )); } var oldIndexes = changeDescriptor.OriginalType.Indexes.Select(i => i.ToString()).ToList(); foreach (var newIndex in changeDescriptor.AlteredType.Indexes) { if (!oldIndexes.Contains(newIndex.ToString())) { var index = newIndex; createIndexActions.Add(new Tuple<bool, Action>(newIndex.Clustered, () => CreateIndex(alteredTableName, index))); } } createIndexActions.Sort((a, b) => b.Item1.CompareTo(a.Item1)); foreach (var createIndex in createIndexActions) { createIndex.Item2(); } SqlTableInformationStore.ClearCache(_connectionString, originalTableName); SqlTableInformationStore.ClearCache(_connectionString, alteredTableName); } catch (Exception ex) { throw MakeVerboseException(ex); } } internal void RenameTable(string oldTableName, string newTableName) { ExecuteStoredProcedure("sp_rename", new[] { SqlQuoted(oldTableName), SqlQuoted(newTableName) }); } internal void DropStoresForType(string providerName, DataTypeDescriptor typeDescriptor) { lock (_lock) { foreach (DataScopeIdentifier dataScope in typeDescriptor.DataScopes) { DropScopeData(typeDescriptor, dataScope); } } } private void DropScopeData(DataTypeDescriptor typeDescriptor, DataScopeIdentifier dataScope) { foreach (var culture in GetCultures(typeDescriptor)) { DropStore(typeDescriptor, dataScope, culture); } } private void DropStore(DataTypeDescriptor dataTypeDescriptor, DataScopeIdentifier dataScope, CultureInfo cultureInfo) { string tableName = GetConfiguredTableName(dataTypeDescriptor, dataScope, cultureInfo.Name); if (string.IsNullOrEmpty(tableName)) { return; } try { var tables = GetTablesList(); if (tables.Contains(tableName)) { ExecuteNonQuery($"DROP TABLE [{tableName}];"); SqlTableInformationStore.ClearCache(_connectionString, tableName); } } catch (Exception ex) { throw MakeVerboseException(ex); } } private void ImplementFieldChanges( string tableName, DataTypeDescriptor typeDescriptor, IEnumerable<DataTypeChangeDescriptor.ExistingFieldInfo> existingFieldDescription) { foreach (var changedFieldDescriptor in existingFieldDescription) { // Recreating deleted constraints, if necessary - renaming the column/changing its type bool changes = changedFieldDescriptor.AlteredFieldHasChanges; var columnName = changedFieldDescriptor.OriginalField.Name; ConfigureColumn(tableName, columnName, typeDescriptor, changedFieldDescriptor.AlteredField, changedFieldDescriptor.OriginalField, changes); } } internal void RenameColumn(string tableName, string oldColumnName, string newColumnName) { string oldName = "{0}.{1}".FormatWith(tableName, oldColumnName); ExecuteStoredProcedure("sp_rename", new[] { SqlQuoted(oldName), SqlQuoted(newColumnName), "'COLUMN'" }); } private void DropFields(string tableName, IEnumerable<DataFieldDescriptor> fieldsToDrop, IEnumerable<DataFieldDescriptor> fields) { var sql = new StringBuilder(); foreach (var deletedFieldDescriptor in fieldsToDrop) { var columnExists = fields.Any(f => f.Name.Equals(deletedFieldDescriptor.Name)); if (columnExists) { sql.AppendFormat("ALTER TABLE [{0}] DROP COLUMN [{1}];", tableName, deletedFieldDescriptor.Name); } else { Log.LogWarning(typeof(SqlDataProvider).FullName, "Column '{0}' on table '{1}' has already been dropped", deletedFieldDescriptor.Name, tableName); } } ExecuteNonQuery(sql.ToString()); } private void AppendFields(string tableName, DataTypeChangeDescriptor changeDescriptor, IEnumerable<DataFieldDescriptor> addedFieldDescriptions, Dictionary<string, object> defaultValues = null) { foreach (var addedFieldDescriptor in addedFieldDescriptions) { string fieldName = addedFieldDescriptor.Name; object defaultValue = null; if (defaultValues != null && defaultValues.ContainsKey(fieldName)) { defaultValue = defaultValues[addedFieldDescriptor.Name]; } CreateColumn(tableName, changeDescriptor.AlteredType, addedFieldDescriptor, defaultValue); // Updating VersionId field if (addedFieldDescriptor.Name == nameof(IVersioned.VersionId) && changeDescriptor.AlteredType.SuperInterfaces.Contains(typeof (IVersioned))) { string sourceField; if (changeDescriptor.AlteredType.DataTypeId == typeof (IPage).GetImmutableTypeId()) { sourceField = nameof(IPage.Id); } else { sourceField = changeDescriptor.AlteredType.Fields .Where(f => f.InstanceType == typeof(Guid) && (f.ForeignKeyReferenceTypeName?.Contains(typeof (IPage).FullName) ?? false)) .OrderByDescending(f => f.Name == nameof(IPageData.PageId)) .Select(f => f.Name) .FirstOrDefault(); } if (sourceField != null) { string updateVersionIdCommandText = $"UPDATE [{tableName}] SET [{nameof(IVersioned.VersionId)}] = [{sourceField}]"; ExecuteNonQuery(updateVersionIdCommandText); } } } } private IEnumerable<string> GetConstraints(string tableName, string constraintType = null) { /* This is the list of all possible values for this column (xtype): C = CHECK constraint D = Default or DEFAULT constraint F = FOREIGN KEY constraint L = Log P = Stored procedure PK = PRIMARY KEY constraint (type is K) RF = Replication filter stored procedure S = System table TR = Trigger U = User table UQ = UNIQUE constraint (type is K) V = View X = Extended stored procedure */ string type = string.IsNullOrEmpty(constraintType) ? string.Empty : string.Format(" AND s.xtype = '{0}'", constraintType); string commandText = string.Format(@" SELECT * FROM sysobjects s INNER JOIN sysobjects t ON s.parent_obj = t.id WHERE t.name = '{0}'{1}", tableName, type); var dt = ExecuteReader(commandText); var constraints = (from DataRow dr in dt.Rows select dr["Name"].ToString()).ToList(); return constraints; } private void DropConstraints(string tableName, bool includingPrimaryKey) { var sql = new StringBuilder(); var constraints = GetConstraints(tableName); foreach (var constraint in constraints) { if (includingPrimaryKey || !IsPrimaryKeyContraint(constraint)) { sql.AppendFormat("ALTER TABLE [{0}] DROP CONSTRAINT [{1}];", tableName, constraint); } } ExecuteNonQuery(sql.ToString()); } internal string SetPrimaryKey(string tableName, IEnumerable<string> fieldNames, bool createAsClustered) { if (!fieldNames.Any()) { return string.Empty; } string primaryKeyIndexName = GeneratePrimaryKeyContraintName(tableName); return string.Format("ALTER TABLE [{0}] ADD CONSTRAINT [{1}] PRIMARY KEY{2}({3});", tableName, primaryKeyIndexName, createAsClustered ? " CLUSTERED " : " NONCLUSTERED ", string.Join(",", fieldNames.Distinct().Select(field => "[" + field + "]"))); } private Exception MakeVerboseException(Exception ex) { var message = new StringBuilder(); Exception nested = ex; while (nested != null) { message.Append(nested.Message); message.Append(" "); nested = nested.InnerException; } return new InvalidOperationException(message.ToString(), ex); } private void CreateColumn(string tableName, DataTypeDescriptor typeDescriptor, DataFieldDescriptor fieldDescriptor, object defaultValue = null) { if (defaultValue == null && !fieldDescriptor.IsNullable && fieldDescriptor.DefaultValue != null) { ExecuteNonQuery("ALTER TABLE [{0}] ADD {1};" .FormatWith(tableName, GetColumnInfo(tableName, fieldDescriptor.Name, typeDescriptor, fieldDescriptor, true, false))); return; } // Creating a column, making it nullable ExecuteNonQuery("ALTER TABLE [{0}] ADD {1};" .FormatWith(tableName, GetColumnInfo(tableName, fieldDescriptor.Name, typeDescriptor, fieldDescriptor, true, true))); // Setting default value with "UPDATE" statement if (defaultValue != null || (!fieldDescriptor.IsNullable && fieldDescriptor.DefaultValue == null)) { string defaultValueStr; if(defaultValue != null) { Type typeOfDefaultValue = defaultValue.GetType(); defaultValueStr = (typeOfDefaultValue == typeof(string) || typeOfDefaultValue == typeof(Guid)) ? ("'" + defaultValue + "'") : defaultValue.ToString(); } else { defaultValueStr = GetDefaultValueText(fieldDescriptor.StoreType); } ExecuteNonQuery("UPDATE [{0}] SET [{1}] = {2};" .FormatWith(tableName, fieldDescriptor.Name, defaultValueStr)); } // Making column not nullable if necessary if(!fieldDescriptor.IsNullable) { AlterColumn(tableName, GetColumnInfo(tableName, fieldDescriptor.Name, typeDescriptor, fieldDescriptor, false, false)); } } private void ConfigureColumn(string tableName, string columnName, DataTypeDescriptor typeDescriptor, DataFieldDescriptor fieldDescriptor, DataFieldDescriptor originalFieldDescriptor, bool changes) { string fieldName = fieldDescriptor.Name; if (columnName != fieldName) { RenameColumn(tableName, columnName, fieldName); } if(changes) { bool fieldBecameRequired = !fieldDescriptor.IsNullable && originalFieldDescriptor.IsNullable; if(fieldBecameRequired) { if (fieldDescriptor.StoreType.ToString() != originalFieldDescriptor.StoreType.ToString()) { AlterColumn(tableName, GetColumnInfo(tableName, fieldName, typeDescriptor, fieldDescriptor, false, true)); } string defaultValue = TranslatesIntoDefaultConstraint(fieldDescriptor.DefaultValue) ? GetDefaultValueText(fieldDescriptor.DefaultValue) : GetDefaultValueText(fieldDescriptor.StoreType); ExecuteNonQuery("UPDATE [{0}] SET [{1}] = {2} WHERE [{1}] IS NULL" .FormatWith(tableName, fieldDescriptor.Name, defaultValue)); } AlterColumn(tableName, GetColumnInfo(tableName, fieldDescriptor.Name, typeDescriptor, fieldDescriptor, false, false)); } ExecuteNonQuery(SetDefaultValue(tableName, fieldDescriptor.Name, fieldDescriptor.DefaultValue)); } private void AlterColumn(string tableName, string columnInfo) { ExecuteNonQuery(string.Format("ALTER TABLE [{0}] ALTER COLUMN {1};", tableName, columnInfo)); } internal string GetColumnInfo(string tableName, string columnName, DataTypeDescriptor dataTypeDescriptor, DataFieldDescriptor fieldDescriptor, bool includeDefault, bool forceNullable) { string defaultInfo = string.Empty; string fieldName = fieldDescriptor.Name; bool isKeyField = dataTypeDescriptor.KeyPropertyNames.Contains(fieldName) || fieldDescriptor.ForeignKeyReferenceTypeName != null; if (TranslatesIntoDefaultConstraint(fieldDescriptor.DefaultValue)) { if (includeDefault) { defaultInfo = string.Format("CONSTRAINT [{0}] DEFAULT {1}", SqlSafeName("DF", tableName, columnName), GetDefaultValueText(fieldDescriptor.DefaultValue)); } } // Enabling case sensitive comparison for the random string fields var defaultValue = fieldDescriptor.DefaultValue; string collation = string.Empty; if (defaultValue?.ValueType == DefaultValueType.RandomString || (isKeyField && fieldDescriptor.StoreType.IsString)) { collation = "COLLATE Latin1_General_CS_AS"; } return string.Format( "[{0}] {1} {2} {3} {4}", fieldDescriptor.Name, DynamicTypesCommon.MapStoreTypeToSqlDataType(fieldDescriptor.StoreType), collation, fieldDescriptor.IsNullable || forceNullable ? "NULL" : "NOT NULL", defaultInfo); } private string SetDefaultValue(string tableName, string columnName, DefaultValue defaultValue) { if (!TranslatesIntoDefaultConstraint(defaultValue)) return string.Empty; string constraintName = SqlSafeName("DF", tableName, columnName); return string.Format("ALTER TABLE [{0}] ADD CONSTRAINT [{1}] DEFAULT {2} FOR [{3}];", tableName, constraintName, GetDefaultValueText(defaultValue), columnName); } private string GetDefaultValueText(StoreFieldType storeFieldType) { Verify.ArgumentNotNull(storeFieldType, "storeFieldType"); switch (storeFieldType.PhysicalStoreType) { case PhysicalStoreFieldType.String: case PhysicalStoreFieldType.LargeString: return "N''"; case PhysicalStoreFieldType.Guid: return "'00000000-0000-0000-0000-000000000000'"; case PhysicalStoreFieldType.Integer: case PhysicalStoreFieldType.Long: case PhysicalStoreFieldType.Decimal: return "0"; case PhysicalStoreFieldType.Boolean: return "0"; case PhysicalStoreFieldType.DateTime: return "getdate()"; } throw new NotImplementedException("Supplied StoreFieldType contains an unsupported PhysicalStoreType '{0}'." .FormatWith(storeFieldType.PhysicalStoreType)); } private bool TranslatesIntoDefaultConstraint(DefaultValue defaultValue) { return defaultValue != null && defaultValue.ValueType != DefaultValueType.RandomString; } private string GetDefaultValueText(DefaultValue defaultValue) { Verify.ArgumentNotNull(defaultValue, "defaultValue"); switch (defaultValue.ValueType) { case DefaultValueType.DateTimeNow: return "getdate()"; case DefaultValueType.String: case DefaultValueType.Guid: return "N" + SqlQuoted(defaultValue.Value); case DefaultValueType.NewGuid: return "newid()"; case DefaultValueType.Integer: return defaultValue.Value.ToString(); case DefaultValueType.Boolean: return ((bool)defaultValue.Value ? "1" : "0"); case DefaultValueType.DateTime: return SqlQuoted(((DateTime)defaultValue.Value).ToString("yyyy-MM-dd HH:mm:ss")); case DefaultValueType.Decimal: return ((decimal)defaultValue.Value).ToString("F", CultureInfo.InvariantCulture); } throw new NotImplementedException("Supplied DefaultValue contains an unsupported DefaultValueType '{0}'." .FormatWith(defaultValue.ValueType)); } private void CreateIndex(string tableName, DataTypeIndex index) { string indexName = GetIndexName(index); var fields = new StringBuilder(); foreach (var field in index.Fields) { if (fields.Length > 0) { fields.Append(", "); } fields.Append('[').Append(field.Item1).Append(']'); if (field.Item2 == IndexDirection.Descending) { fields.Append(" DESC"); } } var sql = string.Format("CREATE {0}CLUSTERED INDEX [{1}] ON [{2}] ({3})", !index.Clustered ? "NON" : "", indexName, tableName, fields); ExecuteNonQuery(sql); } private void DropIndex(string tableName, DataTypeIndex index) { string indexName = GetIndexName(index); var sql = string.Format("DROP INDEX [{0}] ON [{1}]", indexName, tableName); ExecuteNonQuery(sql); } private string GetIndexName(DataTypeIndex index) { var result = new StringBuilder().Append("IX_"); foreach (var field in index.Fields) { result.Append('_').Append(field.Item1); } return result.ToString(); } private string SqlQuoted(object obj) { return SqlQuoted(obj.ToString()); } private static string SqlQuoted(string theString) { return string.Format("'{0}'", theString.Replace("'", "''")); } private static bool IsPrimaryKeyContraint(string contraintName) { return contraintName.StartsWith("PK_"); } private static string GeneratePrimaryKeyContraintName(string tableName) { return SqlSafeName("PK", tableName); } private static string SqlSafeName(string prefix, string elementName) { string name = string.Format("{0}_{1}", prefix, elementName); if (name.Length > 128) { string random = System.IO.Path.GetRandomFileName(); name = name.Substring(0, 128 - random.Length) + random; } return name; } private static string SqlSafeName(string prefix, string parentName, string subName) { string stem = string.Format("{0}_{1}_", prefix, parentName); if (stem.Length + subName.Length > 128) { stem = stem.Substring(0, 127 - subName.Length) + "_"; } return stem + subName; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/Foundation/SqlDataTypeStoreTable.cs ================================================ using System; using System.ComponentModel; using System.Reflection; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Foundation { /// <summary> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] internal sealed class SqlDataTypeStoreTable { public SqlDataTypeStoreTable( Guid dataTypeId, FieldInfo dataContextQueryableFieldInfo, ISqlDataProviderHelper sqlDataProviderHelper, string dataContextFieldName, Type dataContextFieldType) { DataTypeId = dataTypeId; DataContextQueryableFieldInfo = dataContextQueryableFieldInfo; SqlDataProviderHelper = sqlDataProviderHelper; DataContextFieldName = dataContextFieldName; DataContextFieldType = dataContextFieldType; } public Guid DataTypeId { get; set; } public FieldInfo DataContextQueryableFieldInfo { get; set; } public ISqlDataProviderHelper SqlDataProviderHelper { get; set; } public string DataContextFieldName { get; set; } public Type DataContextFieldType { get; set; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/Foundation/SqlDataTypeStoreTableKey.cs ================================================ using System; using System.ComponentModel; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Foundation { /// <summary> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] internal class SqlDataTypeStoreTableKey : Tuple<string, string> { public SqlDataTypeStoreTableKey(string dataScopeIdentifierName, string localeCultureName) : base(dataScopeIdentifierName, localeCultureName) { } public string DataScopeIdentifierName { get { return Item1; } } public string LocaleCultureName { get { return Item2; } } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/Foundation/SqlLoggerTextWriter.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Composite.Core; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Foundation { internal sealed class SqlLoggerTextWriter : System.IO.TextWriter { private static readonly Regex ContainsParamRegex = new Regex(@"@(p|x)[0-9]+", RegexOptions.Compiled); private static readonly Regex ParamRegex = new Regex(@"-- (?<param>@(p|x)[0-9]+):", RegexOptions.Compiled); private readonly SqlLoggingContext _sqlLoggingContext; private readonly ConcurrentDictionary<int, Tuple<string, Dictionary<string, string>>> _threadData = new ConcurrentDictionary<int, Tuple<string, Dictionary<string, string>>>(); public SqlLoggerTextWriter(SqlLoggingContext sqlLoggingContext) { _sqlLoggingContext = sqlLoggingContext; if (_sqlLoggingContext.TablesToIgnore == null) _sqlLoggingContext.TablesToIgnore = new List<string>(); } public override Encoding Encoding => Encoding.UTF8; public override void WriteLine(string value) { if (!value.StartsWith("--")) { HandleNewQuery(value); } else if (!value.StartsWith("-- Context:")) { HandleParameter(value); } else { HandleEndQuery(); } } private void HandleNewQuery(string value) { if (_sqlLoggingContext.TablesToIgnore.Any(value.Contains)) { return; } int parameterCount = ContainsParamRegex.Matches(value).Count; if (parameterCount == 0) { AddLogEntry(value); return; } var entry = new Tuple<string, Dictionary<string, string>>(value, new Dictionary<string, string>()); _threadData[Thread.CurrentThread.ManagedThreadId] = entry; } private void HandleParameter(string value) { Tuple<string, Dictionary<string, string>> entry; if (!_threadData.TryGetValue(Thread.CurrentThread.ManagedThreadId, out entry)) { return; } Match match = ParamRegex.Match(value); string paramId = match.Groups["param"].Value; if (string.IsNullOrEmpty(paramId)) { Log.LogWarning(nameof(SqlLoggerTextWriter), "Failed to parse parameter line: " + value); return; } string paramValue = value.Substring(value.IndexOf('[')); entry.Item2.Add(paramId, paramValue); } public void HandleEndQuery() { Tuple<string, Dictionary<string, string>> entry; var threadId = Thread.CurrentThread.ManagedThreadId; if (_threadData.TryRemove(threadId, out entry)) { string value = entry.Item1; foreach (var kvp in entry.Item2) { value = value.Replace(kvp.Key, kvp.Value); } AddLogEntry(value); } } private void AddLogEntry(string value) { if (_sqlLoggingContext.IncludeStack) { var sb = new StringBuilder(); sb.AppendLine(value); sb.AppendLine("Stack trace:"); var trace = new StackTrace(8, true); foreach (StackFrame stackFrame in trace.GetFrames()) { MemberInfo methodInfo = stackFrame.GetMethod(); string type = ""; if (methodInfo.DeclaringType != null) { type = methodInfo.DeclaringType.FullName; } sb.AppendLine($" at {type}.{methodInfo.Name} line {stackFrame.GetFileLineNumber()}"); } value = sb.ToString(); } Log.LogVerbose("RGB(0, 128, 192)SqlQuery", value); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/ISqlDataProviderHelper.cs ================================================ using System.Linq; using Composite.Data; using Composite.Data.Plugins.DataProvider; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface ISqlDataProviderHelper { /// <exclude /> IData GetDataById(IQueryable queryable, IDataId dataId, DataProviderContext dataProviderContext); /// <exclude /> IData AddData(ISqlDataContext dataContext, IData dataToAdd, DataProviderContext dataProviderContext); /// <exclude /> void RemoveData(ISqlDataContext dataContext, IData dataToRemove); } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/Sql/ISqlTableInformation.cs ================================================ using System.Collections.Generic; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Sql { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface ISqlTableInformation { /// <exclude /> string TableName { get; } /// <exclude /> bool HasIdentityColumn { get; } /// <exclude /> string IdentityColumnName { get; } /// <exclude /> SqlColumnInformation this[string columnName] { get; } /// <exclude /> IEnumerable<SqlColumnInformation> ColumnInformations { get; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/Sql/ISqlTableInformationStore.cs ================================================ namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Sql { internal interface ISqlTableInformationStore { ISqlTableInformation GetTableInformation(string connectionString, string tableName); void ClearCache(string connectionString, string tableName); void OnFlush(); } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/Sql/SqlColumnInformation.cs ================================================ using System; using System.Data; using System.ComponentModel; using System.Linq; using Composite.Data.DynamicTypes; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Foundation; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Sql { internal static class SqlColumnInformationExtensions { public static SqlColumnInformation CreateSqlColumnInformation(this DataTypeDescriptor dataTypeDescriptor, string fieldName) { DataFieldDescriptor dataFieldDescriptor = dataTypeDescriptor.Fields[fieldName]; return new SqlColumnInformation( dataFieldDescriptor.Name, dataTypeDescriptor.PhysicalKeyPropertyNames.Contains(dataFieldDescriptor.Name), false, false, dataFieldDescriptor.IsNullable, dataFieldDescriptor.InstanceType, DynamicTypesCommon.GetStoreTypeToSqlDataTypeMapping(dataFieldDescriptor.StoreType) ); } } /// <summary> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] public sealed class SqlColumnInformation { private readonly string _columnName; private readonly string _trimmedColumnName; private readonly bool _isPrimaryKey; private readonly bool _isIdentity; private readonly bool _isComputed; private readonly bool _isNullable; private readonly Type _type; private readonly SqlDbType _sqlDbType; private int? _hashCode; internal SqlColumnInformation( string columnName, bool isPrimaryKey, bool isIdentity, bool isComputed, bool isNullable, Type type, SqlDbType sqlDbType) { _columnName = columnName; _trimmedColumnName = _columnName.Replace(" ", ""); _isPrimaryKey = isPrimaryKey; _isIdentity = isIdentity; _isComputed = isComputed; _isNullable = isNullable; _type = type; _sqlDbType = sqlDbType; } /// <exclude /> public string ColumnName => _columnName; /// <exclude /> public string TrimmedColumnName => _trimmedColumnName; /// <exclude /> public bool IsPrimaryKey => _isPrimaryKey; /// <exclude /> public bool IsIdentity => _isIdentity; /// <exclude /> public bool IsComputed => _isComputed; /// <exclude /> public bool IsNullable => _isNullable; /// <exclude /> public Type Type => _type; /// <exclude /> public SqlDbType SqlDbType => _sqlDbType; /// <exclude /> public override int GetHashCode() { if (!_hashCode.HasValue) { _hashCode = _columnName.GetHashCode() ^ _trimmedColumnName.GetHashCode() ^ _isPrimaryKey.GetHashCode() ^ _isIdentity.GetHashCode() ^ _isComputed.GetHashCode() ^ _isNullable.GetHashCode() ^ _type.GetHashCode() ^ _sqlDbType.GetHashCode(); } return _hashCode.Value; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/Sql/SqlTableInformation.cs ================================================ using System.Collections.Generic; using Composite.Core.Linq; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Sql { internal sealed class SqlTableInformation : ISqlTableInformation { private readonly string _tableName; private bool _hasIdentityColumn; private string _identityColumnName; private readonly Dictionary<string, SqlColumnInformation> _columns = new Dictionary<string, SqlColumnInformation>(); private int? _hashCode; internal SqlTableInformation(string tableName) { _tableName = tableName; } public string TableName { get { return _tableName; } } public bool HasIdentityColumn { get { return _hasIdentityColumn; } } public string IdentityColumnName { get { return _identityColumnName; } } public SqlColumnInformation this[string columnName] { get { return _columns[columnName]; } } public IEnumerable<SqlColumnInformation> ColumnInformations { get { foreach(SqlColumnInformation column in _columns.Values) { yield return column; } } } internal void AddColumnInformation(SqlColumnInformation columnInformation) { if (columnInformation.IsIdentity) { _hasIdentityColumn = true; _identityColumnName = columnInformation.ColumnName; } _columns.Add(columnInformation.ColumnName, columnInformation); _hashCode = null; } public override int GetHashCode() { if (!_hashCode.HasValue) { int calculatedHashCode =_tableName.GetHashCode() ^ _hasIdentityColumn.GetHashCode() ^ _columns.GetContentHashCode(); if (_hasIdentityColumn) { calculatedHashCode ^= _identityColumnName.GetHashCode(); } _hashCode = calculatedHashCode; } return _hashCode.Value; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/Sql/SqlTableInformationStore.cs ================================================ using Composite.C1Console.Events; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Sql { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class SqlTableInformationStore { private static ISqlTableInformationStore _implementation = new SqlTableInformationStoreImpl(); internal static ISqlTableInformationStore Implementation { get { return _implementation; } set { _implementation = value; } } static SqlTableInformationStore() { GlobalEventSystemFacade.SubscribeToFlushEvent(args => Flush()); } /// <exclude /> public static ISqlTableInformation GetTableInformation(string connectionString, string tableName) { return _implementation.GetTableInformation(connectionString, tableName); } /// <exclude /> public static void ClearCache(string connectionString, string tableName) { _implementation.ClearCache(connectionString, tableName); } internal static void Flush() { _implementation.OnFlush(); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/Sql/SqlTableInformationStoreImpl.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Linq; using Composite.Core.Extensions; using Composite.Core.Sql; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Sql { internal class SqlTableInformationStoreImpl : ISqlTableInformationStore { private static Dictionary<string, ISqlTableInformation> _tableInformationCache = new Dictionary<string, ISqlTableInformation>(); private static Dictionary<string, Dictionary<string, ColumnInfo>> _columnsInformationCache; public ISqlTableInformation GetTableInformation(string connectionString, string tableName) { Verify.ArgumentNotNullOrEmpty(connectionString, "connectionString"); Verify.ArgumentNotNullOrEmpty(tableName, "tableName)"); string key = GetTableCacheKey(connectionString, tableName); if (!_tableInformationCache.ContainsKey(key)) { SqlTableInformation sqlTableInformation = CreateSqlTableInformation(connectionString, tableName); _tableInformationCache.Add(key, sqlTableInformation); } return _tableInformationCache[key]; } public void OnFlush() { _tableInformationCache = new Dictionary<string, ISqlTableInformation>(); _columnsInformationCache = null; } public void ClearCache(string connectionString, string tableName) { _tableInformationCache.Remove(GetTableCacheKey(connectionString, tableName)); _columnsInformationCache = null; } private static string GetTableCacheKey(string connectionString, string tableName) { return tableName + " " + connectionString.GetHashCode(); } private static Dictionary<string, ColumnInfo> GetColumnsInfo(SqlConnection connection, string tableName) { var columnsCache = _columnsInformationCache; if(columnsCache == null) { columnsCache = new Dictionary<string, Dictionary<string, ColumnInfo>>(); const string queryString = @"SELECT tableName = obj.name, columnName = col.name, isPrimaryKey = CASE WHEN tc.CONSTRAINT_TYPE = 'PRIMARY KEY' THEN 1 ELSE 0 END, isIdentity = CASE WHEN col.status & 0x80 = 0 THEN 0 ELSE 1 END, isComputed = col.iscomputed, isNullable = col.isnullable FROM SysObjects obj INNER JOIN SysColumns col ON obj.id = col.id LEFT OUTER JOIN (INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc ON tc.TABLE_NAME = kcu.TABLE_NAME AND tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY') ON obj.name = kcu.TABLE_NAME AND col.name = kcu.COLUMN_NAME where obj.xtype = 'U' AND exists(select * from INFORMATION_SCHEMA.TABLES t where t.TABLE_NAME = obj.name AND t.TABLE_SCHEMA = SCHEMA_NAME()) ORDER BY col.colorder"; using (var command = new SqlCommand(queryString, connection)) { using (var reader = command.ExecuteReader()) { foreach (DbDataRecord record in reader) { string tblName = record.GetString(0); if (!columnsCache.ContainsKey(tblName)) { columnsCache.Add(tblName, new Dictionary<string, ColumnInfo>()); } string fieldName = record.GetString(1); columnsCache[tblName].Add(fieldName, new ColumnInfo { TableName = tblName, Name = fieldName, IsPrimaryKey = record.GetInt32(2) == 1, IsIdentity = record.GetInt32(3) == 1, IsComputed = record.GetInt32(4) == 1, IsNullable = record.GetInt32(5) == 1 }); } } } string[] tableNames = columnsCache.Keys.ToArray(); if (tableNames.Any()) { // Performing a query with will get no rows but provide us with columns' types information var fieldTypesQuery = string.Join(";", tableNames.Select(t => "SELECT * FROM [{0}] WHERE 1 = 2".FormatWith(t))); int index = 0; using (var command = new SqlCommand(fieldTypesQuery, connection)) using (var reader = command.ExecuteReader()) { do { Verify.That(index < tableNames.Length, "Too many results received"); for (int i = 0; i < reader.FieldCount; ++i) { string name = reader.GetName(i); Type type = reader.GetProviderSpecificFieldType(i); var fieldsInfo = columnsCache[tableNames[index]]; fieldsInfo[name].Type = type; } index++; } while (reader.NextResult()); } } _columnsInformationCache = columnsCache; } return columnsCache.ContainsKey(tableName) ? columnsCache[tableName] : new Dictionary<string, ColumnInfo>(); } private static SqlTableInformation CreateSqlTableInformation(string connectionString, string tableName) { var connection = SqlConnectionManager.GetConnection(connectionString); var columns = GetColumnsInfo(connection, tableName); // Checking if the necessary table exists if(columns.Count == 0) { return null; } var tableInformation = new SqlTableInformation(tableName); foreach(var column in columns.Values) { tableInformation.AddColumnInformation( new SqlColumnInformation( column.Name, column.IsPrimaryKey, column.IsIdentity, column.IsComputed, column.IsNullable, ConvertSqlTypeToSystemType(column.Type), ConvertSqlTypeToSqlDbType(column.Type) )); } return tableInformation; } private static SqlDbType ConvertSqlTypeToSqlDbType(Type type) { //if (type == typeof(SqlBinary)) return SqlDbType.Binary; if (type == typeof(SqlBoolean)) return SqlDbType.Bit; if (type == typeof(SqlByte)) return SqlDbType.TinyInt; //if (type == typeof(SqlChars)) return SqlDbType.NVarChar; if (type == typeof(SqlDateTime)) return SqlDbType.DateTime; if (type == typeof(SqlDecimal)) return SqlDbType.Decimal; if (type == typeof(SqlSingle)) return SqlDbType.Real; if (type == typeof(SqlGuid)) return SqlDbType.UniqueIdentifier; if (type == typeof(SqlInt16)) return SqlDbType.SmallInt; if (type == typeof(SqlInt32)) return SqlDbType.Int; if (type == typeof(SqlInt64)) return SqlDbType.BigInt; if (type == typeof(SqlMoney)) return SqlDbType.Money; if (type == typeof(SqlString)) return SqlDbType.NVarChar; // else if (type == typeof(SqlXml)) return SqlDbType.Xml; throw new NotImplementedException(string.Format("The sql type {0} not supported", type.FullName)); } private static Type ConvertSqlTypeToSystemType(Type type) { //if (type == typeof(SqlBinary)) return SqlDbType.Binary; if (type == typeof(SqlBoolean)) return typeof(bool); if (type == typeof(SqlByte)) return typeof(byte); //if (type == typeof(SqlChars)) return SqlDbType.NVarChar; if (type == typeof(SqlDateTime)) return typeof(DateTime); if (type == typeof(SqlDecimal)) return typeof(decimal); if (type == typeof(SqlSingle)) return typeof(Single); if (type == typeof(SqlGuid)) return typeof(Guid); if (type == typeof(SqlInt16)) return typeof(Int16); if (type == typeof(SqlInt32)) return typeof(Int32); if (type == typeof(SqlInt64)) return typeof(Int64); if (type == typeof(SqlMoney)) return typeof(double); if (type == typeof(SqlString)) return typeof(string); //if (type == typeof(SqlXml)) return SqlDbType.Xml; throw new NotImplementedException(string.Format("The sql type {0} not supported", type.FullName)); } private class ColumnInfo { public string TableName; public string Name; public bool IsPrimaryKey; public bool IsIdentity; public bool IsComputed; public bool IsNullable; public Type Type; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/SqlDataProvider.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using Composite.Core; using Composite.Core.Configuration; using Composite.Core.Instrumentation; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.Plugins.DataProvider; using Composite.Plugins.Data.DataProviders.Common; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider { [ConfigurationElementType(typeof(SqlDataProviderData))] internal partial class SqlDataProvider : IGeneratedTypesDataProvider, ILocalizedDataProvider { private readonly string _connectionString; private readonly List<InterfaceConfigurationElement> _interfaceConfigurationElements; private SqlDataTypeStoresContainer _sqlDataTypeStoresContainer; private readonly SqlLoggingContext _sqlLoggingContext; private DataProviderContext _dataProviderContext; private SqlDataProviderStoreManipulator _sqlDataProviderStoreManipulator; private readonly object _lock = new object(); public SqlDataProvider(string connectionString, IEnumerable<InterfaceConfigurationElement> interfaceConfigurationElement, SqlLoggingContext sqlLoggingContext = null) { _connectionString = connectionString; _interfaceConfigurationElements = interfaceConfigurationElement.ToList(); _sqlLoggingContext = sqlLoggingContext; } public DataProviderContext Context { set { _dataProviderContext = value; CodeGenerationManager.AddAssemblyCodeProvider(new SqlDataProviderCodeProvider(_dataProviderContext.ProviderName)); InitializeExistingStores(); } } public IEnumerable<Type> GetSupportedInterfaces() { return _sqlDataTypeStoresContainer.SupportedInterfaces; } public IEnumerable<Type> GetKnownInterfaces() { return _sqlDataTypeStoresContainer.KnownInterfaces; } public IEnumerable<Type> GetGeneratedInterfaces() { return _sqlDataTypeStoresContainer.GeneratedInterfaces; } public IQueryable<T> GetData<T>() where T : class, IData { using (TimerProfilerFacade.CreateTimerProfiler(typeof(T).ToString())) { string errorMessage; if (!DataTypeValidationRegistry.IsValidForProvider(typeof(T), _dataProviderContext.ProviderName, out errorMessage)) { throw new InvalidOperationException(errorMessage); } SqlDataTypeStore result = _sqlDataTypeStoresContainer.GetDataTypeStore(typeof(T)); return (IQueryable<T>)result.GetQueryable(); } } public T GetData<T>(IDataId dataId) where T : class, IData { Verify.ArgumentNotNull(dataId, "dataId"); using (TimerProfilerFacade.CreateTimerProfiler(string.Format("dataId ({0})", typeof(T)))) { string errorMessage; if (!DataTypeValidationRegistry.IsValidForProvider(typeof(T), _dataProviderContext.ProviderName, out errorMessage)) { throw new InvalidOperationException(errorMessage); } SqlDataTypeStore result = _sqlDataTypeStoresContainer.GetDataTypeStore(typeof(T)); IData data = result.GetDataByDataId(dataId, _dataProviderContext); return (T)data; } } public void Update(IEnumerable<IData> datas) { using (TimerProfilerFacade.CreateTimerProfiler()) { if (datas == null) throw new ArgumentNullException("datas"); Type interfaceType = null; foreach (IData data in datas) { if (data == null) throw new ArgumentException("datas enumeration may not contain nulls"); if (data.DataSourceId == null) throw new ArgumentException("data in datas enumeration may not contain null DataSourceIds"); if (interfaceType == null) { interfaceType = data.DataSourceId.InterfaceType; } else if (interfaceType != data.DataSourceId.InterfaceType) { throw new ArgumentException(string.Format("Only one data interface per enumerable type supported")); } } string errorMessage; if (!DataTypeValidationRegistry.IsValidForProvider(interfaceType, _dataProviderContext.ProviderName, out errorMessage)) { throw new InvalidOperationException(errorMessage); } _sqlDataTypeStoresContainer.Update(datas); } } public List<T> AddNew<T>(IEnumerable<T> dataset) where T : class, IData { Verify.ArgumentNotNull(dataset, "dataset"); using (TimerProfilerFacade.CreateTimerProfiler()) { string errorMessage; if (!DataTypeValidationRegistry.IsValidForProvider(typeof(T), _dataProviderContext.ProviderName, out errorMessage)) { throw new InvalidOperationException(errorMessage); } using (var scope = new RequireTransactionScope()) { var result = _sqlDataTypeStoresContainer.AddNew<T>(dataset, _dataProviderContext); scope.Complete(); return result; } } } public void Delete(IEnumerable<DataSourceId> dataSourceIds) { Verify.ArgumentNotNull(dataSourceIds, "dataSourceIds"); using (TimerProfilerFacade.CreateTimerProfiler()) { Type interfaceType = null; foreach (DataSourceId dataSourceId in dataSourceIds) { if (dataSourceId == null) throw new ArgumentException("datas enumeration may not contain nulls"); if (interfaceType == null) { interfaceType = dataSourceId.InterfaceType; } else if (interfaceType != dataSourceId.InterfaceType) { throw new ArgumentException(string.Format("Only one data interface per enumerable type supported")); } } string errorMessage; if (!DataTypeValidationRegistry.IsValidForProvider(interfaceType, _dataProviderContext.ProviderName, out errorMessage)) { throw new InvalidOperationException(errorMessage); } _sqlDataTypeStoresContainer.Delete(dataSourceIds, _dataProviderContext); } } public void AddLocale(CultureInfo cultureInfo) { var supportedInterfaces = GetSupportedInterfaces(); foreach (var type in supportedInterfaces) { if (!DataLocalizationFacade.IsLocalized(type)) { continue; } var typeDesrciptor = DynamicTypeManager.GetDataTypeDescriptor(type); SqlStoreManipulator.AddLocale(typeDesrciptor, cultureInfo); InterfaceConfigurationElement oldElement = _interfaceConfigurationElements.Single(f => f.DataTypeId == typeDesrciptor.DataTypeId); InterfaceConfigurationElement newElement = InterfaceConfigurationManipulator.RefreshLocalizationInfo(_dataProviderContext.ProviderName, typeDesrciptor); _interfaceConfigurationElements.Remove(oldElement); _interfaceConfigurationElements.Add(newElement); } } public void RemoveLocale(CultureInfo cultureInfo) { var supportedInterfaces = GetSupportedInterfaces(); foreach (var type in supportedInterfaces) { if (!DataLocalizationFacade.IsLocalized(type)) { continue; } var typeDesrciptor = DynamicTypeManager.GetDataTypeDescriptor(type); SqlStoreManipulator.RemoveLocale(_dataProviderContext.ProviderName, typeDesrciptor, cultureInfo); InterfaceConfigurationElement oldElement = _interfaceConfigurationElements.Where(f => f.DataTypeId == typeDesrciptor.DataTypeId).Single(); InterfaceConfigurationElement newElement = InterfaceConfigurationManipulator.RefreshLocalizationInfo(_dataProviderContext.ProviderName, typeDesrciptor); _interfaceConfigurationElements.Remove(oldElement); _interfaceConfigurationElements.Add(newElement); } } internal void BuildAllCode(CodeGenerationBuilder codeGenerationBuilder) { var codeBuilder = new SqlDataProviderCodeBuilder(_dataProviderContext.ProviderName, codeGenerationBuilder); foreach (InterfaceConfigurationElement element in _interfaceConfigurationElements) { if (element.DataTypeId == Guid.Empty) continue; var dataTypeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(element.DataTypeId); if (!dataTypeDescriptor.ValidateRuntimeType()) { Log.LogError(LogTitle, string.Format("The non code generated interface type '{0}' was not found, skipping code generation for that type", dataTypeDescriptor)); continue; } var sqlDataTypeStoreDataScopes = new List<SqlDataTypeStoreDataScope>(); foreach (StorageInformation storageInformation in element.Stores) { var sqlDataTypeStoreDataScope = new SqlDataTypeStoreDataScope { DataScopeName = storageInformation.DataScope, CultureName = storageInformation.CultureName, TableName = storageInformation.TableName }; sqlDataTypeStoreDataScopes.Add(sqlDataTypeStoreDataScope); } codeBuilder.AddDataType(dataTypeDescriptor, sqlDataTypeStoreDataScopes); } codeBuilder.AddDataContext(); } private SqlDataProviderStoreManipulator SqlStoreManipulator { get { if (_sqlDataProviderStoreManipulator == null) { lock (_lock) { if (_sqlDataProviderStoreManipulator == null) { _sqlDataProviderStoreManipulator = new SqlDataProviderStoreManipulator(_connectionString, _interfaceConfigurationElements); } } } return _sqlDataProviderStoreManipulator; } } } internal sealed class SqlDataProviderAssembler : IAssembler<IDataProvider, DataProviderData> { private static readonly string LogTitle = typeof (SqlDataProviderAssembler).Name; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IDataProvider Assemble(IBuilderContext context, DataProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { var sqlDataProviderData = (SqlDataProviderData)objectConfiguration; string configFilePath = InterfaceConfigurationManipulator.GetConfigurationFilePath(sqlDataProviderData.Name); var configuration = new C1Configuration(configFilePath); var section = configuration.GetSection(SqlDataProviderConfigurationSection.SectionName) as SqlDataProviderConfigurationSection; if (section == null) { section = new SqlDataProviderConfigurationSection(); configuration.Sections.Add(SqlDataProviderConfigurationSection.SectionName, section); configuration.Save(); } var interfaceConfigurationElements = new List<InterfaceConfigurationElement>(); foreach (InterfaceConfigurationElement table in section.Interfaces) { interfaceConfigurationElements.Add(table); } var sqlLoggingContext = new SqlLoggingContext { Enabled = sqlDataProviderData.SqlQueryLoggingEnabled, IncludeStack = sqlDataProviderData.SqlQueryLoggingIncludeStack, TypesToIgnore = new List<Type>(), TablesToIgnore = new List<string>() }; if (sqlDataProviderData.SqlQueryLoggingEnabled) { foreach (LoggingIgnoreInterfacesConfigurationElement element in sqlDataProviderData.LoggingIgnoreInterfaces) { Type interfaceType = TypeManager.TryGetType(element.InterfaceType); if (interfaceType != null) { sqlLoggingContext.TypesToIgnore.Add(interfaceType); InterfaceConfigurationElement interfaceElement = interfaceConfigurationElements.SingleOrDefault(f => f.DataTypeId == interfaceType.GetImmutableTypeId()); if (interfaceElement == null) continue; foreach (StoreConfigurationElement store in interfaceElement.ConfigurationStores) { sqlLoggingContext.TablesToIgnore.Add(store.TableName); } } } } string connectionString = sqlDataProviderData.ConnectionString; if (string.IsNullOrEmpty(connectionString)) { string connectionStringName = sqlDataProviderData.ConnectionStringName; if (string.IsNullOrEmpty(connectionStringName)) { throw new ConfigurationErrorsException("SqlDataProvider requires one of the following properties to be specified: 'connectionString', 'connectionStringName'"); } var connStringConfigNode = System.Web.Configuration.WebConfigurationManager.ConnectionStrings[connectionStringName]; Verify.IsNotNull(connStringConfigNode, "Failed to find an SQL connection string by name '{0}'", connectionStringName); connectionString = connStringConfigNode.ConnectionString; } return new SqlDataProvider(connectionString, interfaceConfigurationElements, sqlLoggingContext); } } internal sealed class SqlLoggingContext { public bool Enabled { get; set; } public bool IncludeStack { get; set; } public List<Type> TypesToIgnore { get; set; } public List<string> TablesToIgnore { get; set; } } [Assembler(typeof(SqlDataProviderAssembler))] internal sealed class SqlDataProviderData : DataProviderData { private const string _connectionStringPropertyName = "connectionString"; [System.Configuration.ConfigurationProperty(_connectionStringPropertyName, IsRequired = false)] public string ConnectionString { get { return (string)base[_connectionStringPropertyName]; } set { base[_connectionStringPropertyName] = value; } } private const string _connectionStringNamePropertyName = "connectionStringName"; [System.Configuration.ConfigurationProperty(_connectionStringNamePropertyName, IsRequired = false)] public string ConnectionStringName { get { return (string)base[_connectionStringNamePropertyName]; } set { base[_connectionStringNamePropertyName] = value; } } private const string _sqlQueryLoggingEnabledPropertyName = "sqlQueryLoggingEnabled"; [System.Configuration.ConfigurationProperty(_sqlQueryLoggingEnabledPropertyName, IsRequired = false, DefaultValue = false)] public bool SqlQueryLoggingEnabled { get { return (bool)base[_sqlQueryLoggingEnabledPropertyName]; } set { base[_sqlQueryLoggingEnabledPropertyName] = value; } } private const string _sqlQueryLoggingIncludeStackPropertyName = "sqlQueryLoggingIncludeStack"; [System.Configuration.ConfigurationProperty(_sqlQueryLoggingIncludeStackPropertyName, IsRequired = false, DefaultValue = false)] public bool SqlQueryLoggingIncludeStack { get { return (bool)base[_sqlQueryLoggingIncludeStackPropertyName]; } set { base[_sqlQueryLoggingIncludeStackPropertyName] = value; } } private const string _logginIgnoreInterfacesNamePropertyName = "LoggingIgnoreInterfaces"; [System.Configuration.ConfigurationProperty(_logginIgnoreInterfacesNamePropertyName, IsRequired = false)] public LoggingIgnoreInterfacesConfigurationElementCollection LoggingIgnoreInterfaces { get { return (LoggingIgnoreInterfacesConfigurationElementCollection)base[_logginIgnoreInterfacesNamePropertyName]; } set { base[_logginIgnoreInterfacesNamePropertyName] = value; } } } internal sealed class LoggingIgnoreInterfacesConfigurationElementCollection : System.Configuration.ConfigurationElementCollection { protected override System.Configuration.ConfigurationElement CreateNewElement() { return new LoggingIgnoreInterfacesConfigurationElement(); } protected override object GetElementKey(System.Configuration.ConfigurationElement element) { return ((LoggingIgnoreInterfacesConfigurationElement)element).InterfaceType; } } internal sealed class LoggingIgnoreInterfacesConfigurationElement : System.Configuration.ConfigurationElement { private const string _interfaceTypePropertyName = "interfaceType"; [System.Configuration.ConfigurationProperty(_interfaceTypePropertyName, IsRequired = true)] public string InterfaceType { get { return (string)base[_interfaceTypePropertyName]; } set { base[_interfaceTypePropertyName] = value; } } } internal sealed class SqlDataProviderConfigurationSection : System.Configuration.ConfigurationSection { public const string SectionName = "Composite.Data.Plugins.SqlDataProviderConfiguration"; private const string _InterfacesNamePropertyName = "Interfaces"; [System.Configuration.ConfigurationProperty(_InterfacesNamePropertyName, IsRequired = false)] public InterfaceConfigurationElementCollection Interfaces { get { return (InterfaceConfigurationElementCollection)base[_InterfacesNamePropertyName]; } set { base[_InterfacesNamePropertyName] = value; } } } internal sealed class StorageInformation { public StorageInformation(string dataScope, string cultureName, string tableName) { DataScope = dataScope; CultureName = cultureName; TableName = tableName; } public string DataScope { get; private set; } public string CultureName { get; private set; } public string TableName { get; private set; } } internal sealed class InterfaceConfigurationElement : System.Configuration.ConfigurationElement { public IEnumerable<StorageInformation> Stores { get { var stores = new List<StorageInformation>(); foreach (StoreConfigurationElement element in ConfigurationStores) { stores.Add(new StorageInformation(element.DataScope, element.CultureName, element.TableName)); } return stores; } } public Dictionary<string, Type> DataIdProperties { get { var dic = new Dictionary<string, Type>(); foreach (SimpleNameTypeConfigurationElement element in ConfigurationDataIdProperties) { dic.Add(element.Name, element.Type); } return dic; } } public Dictionary<string, string> PropertyNameMappings { get { var dic = new Dictionary<string, string>(); foreach (PropertyNameMappingConfigurationElement element in ConfigurationPropertyNameMappings) { dic.Add(element.PropertyName, element.SourcePropertyName); } return dic; } } public Dictionary<string, Type> PropertyInitializers { get { var dic = new Dictionary<string, Type>(); if (ConfigurationPropertyInitializers != null) { foreach (SimpleNameTypeConfigurationElement element in ConfigurationPropertyInitializers) { dic.Add(element.Name, element.Type); } } return dic; } } private const string _storesPropertyName = "Stores"; [System.Configuration.ConfigurationProperty(_storesPropertyName, IsRequired = false)] public StoreConfigurationElementCollection ConfigurationStores { get { var baseValue = (StoreConfigurationElementCollection)base[_storesPropertyName]; return baseValue ?? new StoreConfigurationElementCollection(); } set { base[_storesPropertyName] = value; } } private const string _dataTypeIdName = "dataTypeId"; [System.Configuration.ConfigurationProperty(_dataTypeIdName, IsRequired = true)] public Guid DataTypeId { get { return (Guid)base[_dataTypeIdName]; } set { base[_dataTypeIdName] = value; } } private const string _isGeneratedTypePropertyName = "isGeneratedType"; [System.Configuration.ConfigurationProperty(_isGeneratedTypePropertyName, IsRequired = true)] public bool IsGeneratedType { get { return (bool)base[_isGeneratedTypePropertyName]; } set { base[_isGeneratedTypePropertyName] = value; } } private const string _dataIdPropertiesPropertyName = "DataIdProperties"; [System.Configuration.ConfigurationProperty(_dataIdPropertiesPropertyName, IsRequired = true)] public SimpleNameTypeConfigurationElementCollection ConfigurationDataIdProperties { get { return (SimpleNameTypeConfigurationElementCollection)base[_dataIdPropertiesPropertyName]; } set { base[_dataIdPropertiesPropertyName] = value; } } private const string _propertyNameMappingsPropertyName = "PropertyNameMappings"; [System.Configuration.ConfigurationProperty(_propertyNameMappingsPropertyName, IsRequired = false)] public PropertyNameMappingConfigurationElementCollection ConfigurationPropertyNameMappings { get { return (PropertyNameMappingConfigurationElementCollection)base[_propertyNameMappingsPropertyName]; } set { base[_propertyNameMappingsPropertyName] = value; } } private const string _propertyInitializersPropertyName = "PropertyInitializers"; [System.Configuration.ConfigurationProperty(_propertyInitializersPropertyName, IsRequired = false)] public SimpleNameTypeConfigurationElementCollection ConfigurationPropertyInitializers { get { return (SimpleNameTypeConfigurationElementCollection)base[_propertyInitializersPropertyName]; } set { base[_propertyInitializersPropertyName] = value; } } } internal sealed class InterfaceConfigurationElementCollection : System.Configuration.ConfigurationElementCollection { public void Add(InterfaceConfigurationElement element) { BaseAdd(element); } protected override System.Configuration.ConfigurationElement CreateNewElement() { return new InterfaceConfigurationElement(); } protected override object GetElementKey(System.Configuration.ConfigurationElement element) { Guid? dataTypeId = ((InterfaceConfigurationElement) element).DataTypeId; Verify.IsNotNull(dataTypeId, "Configuration element is missing attribute 'dataTypeId'"); return dataTypeId; } internal bool ContainsInterfaceType(InterfaceConfigurationElement interfaceConfigurationElement) { return ContainsInterfaceType(interfaceConfigurationElement.DataTypeId); } internal bool ContainsInterfaceType(DataTypeDescriptor dataTypeDescriptor) { return ContainsInterfaceType(dataTypeDescriptor.DataTypeId); } internal InterfaceConfigurationElement Get(DataTypeDescriptor dataTypeDescriptor) { foreach (InterfaceConfigurationElement element in this) { object key = GetElementKey(element); if ((Guid)key == dataTypeDescriptor.DataTypeId) { return element; } } return null; } internal bool ContainsInterfaceType(Guid dataTypeId) { object[] allKeys = BaseGetAllKeys(); return allKeys.Contains(dataTypeId); } internal void Remove(DataTypeDescriptor dataTypeDescriptor) { Remove(dataTypeDescriptor.DataTypeId); } internal void Remove(Guid dataTypeId) { this.BaseRemove(dataTypeId); } } internal sealed class StoreConfigurationElement : System.Configuration.ConfigurationElement { private const string _tableNamePropertyName = "tableName"; [System.Configuration.ConfigurationProperty(_tableNamePropertyName, IsKey = true, IsRequired = true)] public string TableName { get { return (string)base[_tableNamePropertyName]; } set { base[_tableNamePropertyName] = value; } } private const string _dataScopePropertyName = "dataScope"; [System.Configuration.ConfigurationProperty(_dataScopePropertyName, IsRequired = true)] public string DataScope { get { return (string)base[_dataScopePropertyName]; } set { base[_dataScopePropertyName] = value; } } private const string _culturePropertyName = "cultureName"; [System.Configuration.ConfigurationProperty(_culturePropertyName, DefaultValue = "")] public string CultureName { get { return (string)base[_culturePropertyName]; } set { base[_culturePropertyName] = value; } } } internal sealed class StoreConfigurationElementCollection : System.Configuration.ConfigurationElementCollection { public void Add(StoreConfigurationElement element) { BaseAdd(element); } protected override System.Configuration.ConfigurationElement CreateNewElement() { return new StoreConfigurationElement(); } protected override object GetElementKey(System.Configuration.ConfigurationElement element) { return ((StoreConfigurationElement)element).TableName; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/SqlDataProvider_Stores.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Data.Linq; using System.IO; using System.Linq; using System.Reflection; using Composite.Core; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.Core.Instrumentation; using Composite.Core.Linq; using Composite.Core.Sql; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.Foundation; using Composite.Data.Foundation.CodeGeneration; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Foundation; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Sql; using System.Text; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider { internal partial class SqlDataProvider { private static readonly string LogTitle = typeof(SqlDataProvider).Name; private readonly List<SqlDataTypeStoreTable> _createdSqlDataTypeStoreTables = new List<SqlDataTypeStoreTable>(); private Assembly _compositeGeneratedAssembly; private static readonly Hashtable<Type, bool> _typeLoadResults = new Hashtable<Type, bool>(); public void CreateStores(IReadOnlyCollection<DataTypeDescriptor> dataTypeDescriptors) { var types = DataTypeTypesManager.GetDataTypes(dataTypeDescriptors); foreach (var dataTypeDescriptor in dataTypeDescriptors) { if (InterfaceConfigurationManipulator.ConfigurationExists(_dataProviderContext.ProviderName, dataTypeDescriptor)) { var filePath = InterfaceConfigurationManipulator.GetConfigurationFilePath(_dataProviderContext.ProviderName); throw new InvalidOperationException( $"SqlDataProvider configuration already contains a interface named '{dataTypeDescriptor.TypeManagerTypeName}', Id: '{dataTypeDescriptor.DataTypeId}'. Remove it from the configuration file '{filePath}' and restart the application."); } } // Creating Sql tables and adding to the configuration var configElements = new Dictionary<DataTypeDescriptor, InterfaceConfigurationElement>(); foreach (var dataTypeDescriptor in dataTypeDescriptors) { Type type = types[dataTypeDescriptor.DataTypeId]; Action<string> existingTablesValidator = tableName => { var errors = new StringBuilder(); var interfaceType = type; if (!ValidateTable(interfaceType, tableName, errors)) { throw new InvalidOperationException($"Table '{tableName}' already exists but isn't valid: {errors.ToString()}"); } }; SqlStoreManipulator.CreateStoresForType(dataTypeDescriptor, existingTablesValidator); InterfaceConfigurationElement element = InterfaceConfigurationManipulator.AddNew(_dataProviderContext.ProviderName, dataTypeDescriptor); _interfaceConfigurationElements.Add(element); configElements.Add(dataTypeDescriptor, element); } // Generating necessary classes and performing validation Dictionary<DataTypeDescriptor, IEnumerable<SqlDataTypeStoreDataScope>> allSqlDataTypeStoreDataScopes = BuildAllExistingDataTypeStoreDataScopes(); bool dataContextRecompilationNeeded = false; var toCompileList = new List<HelperClassesGenerationInfo>(); var generatedClassesInfo = new Dictionary<DataTypeDescriptor, InterfaceGeneratedClassesInfo>(); Type dataContextClass = _sqlDataTypeStoresContainer.DataContextClass; foreach (var dataTypeDescriptor in dataTypeDescriptors) { var element = configElements[dataTypeDescriptor]; // InitializeStoreResult initializeStoreResult = InitializeStore(element, allSqlDataTypeStoreDataScopes); HelperClassesGenerationInfo toCompile = null; var classesInfo = InitializeStoreTypes(element, allSqlDataTypeStoreDataScopes, dataContextClass, null, false, ref dataContextRecompilationNeeded, ref toCompile); if (classesInfo != null && toCompile != null) { toCompileList.Add(toCompile); generatedClassesInfo[dataTypeDescriptor] = classesInfo; } } // Compiling missing classes if (toCompileList.Any()) { var codeGenerationBuilder = new CodeGenerationBuilder(_dataProviderContext.ProviderName + ":CreateStores"); foreach (var toCompile in toCompileList) { toCompile.GenerateCodeAction(codeGenerationBuilder); } var generatedHelperClasses = CodeGenerationManager.CompileRuntimeTempTypes(codeGenerationBuilder, false).ToArray(); foreach (var toCompile in toCompileList) { toCompile.PopulateFieldsAction(generatedHelperClasses); } } // Emitting a new DataContext class if (dataContextRecompilationNeeded) { var newDataTypeIds = new HashSet<Guid>(dataTypeDescriptors.Select(d => d.DataTypeId)); _createdSqlDataTypeStoreTables.RemoveAll(f => newDataTypeIds.Contains(f.DataTypeId)); var fields = _createdSqlDataTypeStoreTables.Select(s => new Tuple<string, Type>(s.DataContextFieldName, s.DataContextFieldType)).ToList(); foreach (var classesInfo in generatedClassesInfo.Values) { fields.AddRange(classesInfo.Fields.Select(f => new Tuple<string, Type>(f.Value.FieldName, f.Value.FieldType))); } dataContextClass = DataContextAssembler.EmitDataContextClass(fields); UpdateCreatedSqlDataTypeStoreTables(dataContextClass); } _sqlDataTypeStoresContainer.DataContextClass = dataContextClass; // Registering the new type/tables foreach (var dataTypeDescriptor in dataTypeDescriptors) { InterfaceGeneratedClassesInfo classesInfo; if (!generatedClassesInfo.TryGetValue(dataTypeDescriptor, out classesInfo)) { throw new InvalidOperationException($"No generated classes for data type '{dataTypeDescriptor.Name}' found"); } InitializeStoreResult initInfo = EmbedDataContextInfo(classesInfo, dataContextClass); AddDataTypeStore(initInfo, false); } } public void AlterStore(UpdateDataTypeDescriptor updateDataTypeDescriptor, bool forceCompile) { var dataTypeChangeDescriptor = updateDataTypeDescriptor.CreateDataTypeChangeDescriptor(); using (TimerProfilerFacade.CreateTimerProfiler()) { SqlStoreManipulator.AlterStoresForType(updateDataTypeDescriptor); bool localizationChanged = dataTypeChangeDescriptor.AlteredType.Localizeable != dataTypeChangeDescriptor.OriginalType.Localizeable; var oldElement = _interfaceConfigurationElements.Single(f => f.DataTypeId == updateDataTypeDescriptor.OldDataTypeDescriptor.DataTypeId); var newElement = InterfaceConfigurationManipulator.Change(_dataProviderContext.ProviderName, dataTypeChangeDescriptor, localizationChanged); if (newElement != null) { _interfaceConfigurationElements.Remove(oldElement); _interfaceConfigurationElements.Add(newElement); } if (forceCompile) { Dictionary<DataTypeDescriptor, IEnumerable<SqlDataTypeStoreDataScope>> allSqlDataTypeStoreDataScopes = BuildAllExistingDataTypeStoreDataScopes(); InitializeStoreResult initializeStoreResult = InitializeStore(newElement ?? oldElement, allSqlDataTypeStoreDataScopes, true); if (!updateDataTypeDescriptor.NewDataTypeDescriptor.IsCodeGenerated) { var interfaceType = updateDataTypeDescriptor.NewDataTypeDescriptor.GetInterfaceType(); if (!DataTypeValidationRegistry.IsValidForProvider(interfaceType, _dataProviderContext.ProviderName)) { // Revalidating alternated static data type _sqlDataTypeStoresContainer.RemoveKnownInterface(interfaceType); DataTypeValidationRegistry.ClearValidationError(interfaceType, _dataProviderContext.ProviderName); AddDataTypeStore(initializeStoreResult); } } } } } public void DropStore(DataTypeDescriptor dataTypeDescriptor) { using (TimerProfilerFacade.CreateTimerProfiler()) { SqlStoreManipulator.DropStoresForType(_dataProviderContext.ProviderName, dataTypeDescriptor); InterfaceConfigurationManipulator.Remove(_dataProviderContext.ProviderName, dataTypeDescriptor); InterfaceConfigurationElement oldElement = _interfaceConfigurationElements.FirstOrDefault(f => f.DataTypeId == dataTypeDescriptor.DataTypeId); if (oldElement != null) { _interfaceConfigurationElements.Remove(oldElement); } Guid dataTypeId = dataTypeDescriptor.DataTypeId; int storesRemoved = _createdSqlDataTypeStoreTables.RemoveAll(item => item.DataTypeId == dataTypeId); if (storesRemoved > 0) { Type interfaceType = dataTypeDescriptor.GetInterfaceType(); _sqlDataTypeStoresContainer.ForgetInterface(interfaceType); } } } private void InitializeExistingStores() { _compositeGeneratedAssembly = _compositeGeneratedAssembly ?? AssemblyFacade.GetGeneratedAssemblyFromBin(); _sqlDataTypeStoresContainer = new SqlDataTypeStoresContainer(_dataProviderContext.ProviderName, _connectionString, _sqlLoggingContext); Dictionary<DataTypeDescriptor, IEnumerable<SqlDataTypeStoreDataScope>> allSqlDataTypeStoreDataScopes = BuildAllExistingDataTypeStoreDataScopes(); var initializedStores = new List<InterfaceGeneratedClassesInfo>(); bool dataContextRecompilationNeeded = false; Type dataContextClass = TryLoadDataContext(ref dataContextRecompilationNeeded); var dataTypes = LoadDataTypes(_interfaceConfigurationElements); var compilationData = new List<HelperClassesGenerationInfo>(); foreach (InterfaceConfigurationElement element in _interfaceConfigurationElements) { HelperClassesGenerationInfo toCompile = null; var generatedClassesInfo = InitializeStoreTypes(element, allSqlDataTypeStoreDataScopes, dataContextClass, dataTypes, false, ref dataContextRecompilationNeeded, ref toCompile); if (generatedClassesInfo == null) continue; if (toCompile != null) { compilationData.Add(toCompile); } initializedStores.Add(generatedClassesInfo); } if (compilationData.Any()) { var codeGenerationBuilder = new CodeGenerationBuilder(_dataProviderContext.ProviderName + " : compiling missing classes"); foreach (var toCompile in compilationData) { toCompile.GenerateCodeAction(codeGenerationBuilder); } // Precompiling DataWrapper classes as well to improve loading time foreach (var interfaceType in dataTypes.Values) { if (DataWrapperTypeManager.TryGetWrapperType(interfaceType.FullName) == null) { DataWrapperCodeGenerator.AddDataWrapperClassCode(codeGenerationBuilder, interfaceType); } } Type[] types = null; try { types = CodeGenerationManager.CompileRuntimeTempTypes(codeGenerationBuilder, false).ToArray(); } catch (Exception ex) { Log.LogWarning(LogTitle, ex); } if (types != null) { foreach (var toCompile in compilationData) { toCompile.PopulateFieldsAction(types); } } } if (dataContextRecompilationNeeded) { dataContextClass = DataContextAssembler.EmitDataContextClass( initializedStores .Where(s => s.Fields != null) .SelectMany(s => s.Fields.Values).Evaluate()); } _sqlDataTypeStoresContainer.DataContextClass = dataContextClass; foreach (var typeInfo in initializedStores) { var store = EmbedDataContextInfo(typeInfo, dataContextClass); AddDataTypeStore(store, true, true); } } /// <summary> /// Loads all the data types referenced in the provider's configuration file. /// </summary> private static Dictionary<Guid, Type> LoadDataTypes(IEnumerable<InterfaceConfigurationElement> configurationElements) { var dataTypeDescriptors = new List<DataTypeDescriptor>(); foreach (InterfaceConfigurationElement element in configurationElements) { Guid dataTypeId = element.DataTypeId; var dataTypeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(dataTypeId, true); if (dataTypeDescriptor == null) { throw NewConfigurationException(element, "Failed to get a DataTypeDescriptor by id '{dataTypeId}'"); } dataTypeDescriptors.Add(dataTypeDescriptor); } return DataTypeTypesManager.GetDataTypes(dataTypeDescriptors); } private static Exception NewConfigurationException(ConfigurationElement element, string message) { return new ConfigurationErrorsException(message, element.ElementInformation.Source, element.ElementInformation.LineNumber); } private InitializeStoreResult InitializeStore(InterfaceConfigurationElement element, Dictionary<DataTypeDescriptor, IEnumerable<SqlDataTypeStoreDataScope>> allSqlDataTypeStoreDataScopes, bool forceCompile = false) { bool dataContextRecompilationNeeded = false; Type dataContextClass = _sqlDataTypeStoresContainer.DataContextClass; var initInfo = InitializeStoreTypes(element, allSqlDataTypeStoreDataScopes, dataContextClass, forceCompile, ref dataContextRecompilationNeeded); if (initInfo.InterfaceType == null) { return new InitializeStoreResult(); } if (dataContextRecompilationNeeded) { _createdSqlDataTypeStoreTables.RemoveAll(f => f.DataTypeId == initInfo.DataTypeDescriptor.DataTypeId); var existingFields = _createdSqlDataTypeStoreTables.Select( s => new Tuple<string, Type>(s.DataContextFieldName, s.DataContextFieldType)); var newFields = initInfo.Fields.Select(f => new Tuple<string, Type>(f.Value.FieldName, f.Value.FieldType)); dataContextClass = DataContextAssembler.EmitDataContextClass(existingFields.Concat(newFields).Evaluate()); UpdateCreatedSqlDataTypeStoreTables(dataContextClass); } _sqlDataTypeStoresContainer.DataContextClass = dataContextClass; return EmbedDataContextInfo(initInfo, dataContextClass); } private Type TryLoadDataContext(ref bool forceCompile) { string dataContextClassFullName = NamesCreator.MakeDataContextClassFullName(_dataProviderContext.ProviderName); Type dataContextClass = TryGetGeneratedType(dataContextClassFullName); // Trying to instantiate a data context object if (dataContextClass != null && !TryLoadDataContextClass(dataContextClass)) { forceCompile = true; return null; } return dataContextClass; } private InitializeStoreResult EmbedDataContextInfo(InterfaceGeneratedClassesInfo initInfo, Type dataContextType) { var result = new InitializeStoreResult(); if (initInfo.InterfaceType == null) { return result; } result.InterfaceType = initInfo.InterfaceType; var sqlDataTypeStoreTables = new Dictionary<SqlDataTypeStoreTableKey, SqlDataTypeStoreTable>(); foreach (SqlDataTypeStoreDataScope storeDataScope in initInfo.DataScopes) { var key = new SqlDataTypeStoreTableKey(storeDataScope.DataScopeName, storeDataScope.CultureName); result.TableNames.Add(key, storeDataScope.TableName); Verify.IsNotNull(initInfo.Fields, "Fields collection is null"); StoreTypeInfo fieldInfo; if (!initInfo.Fields.TryGetValue(key, out fieldInfo)) { continue; } Verify.IsNotNull(fieldInfo, "Field info is missing"); FieldInfo dataContextFieldInfo = dataContextType != null ? dataContextType.GetField(fieldInfo.FieldName) : fieldInfo.DataContextField; Type sqlDataProvdierHelperType = fieldInfo.SqlHelperClass; var sqlDataProviderHelper = (ISqlDataProviderHelper)Activator.CreateInstance(sqlDataProvdierHelperType); var sqlDataTypeStoreTable = new SqlDataTypeStoreTable( initInfo.DataTypeDescriptor.DataTypeId, dataContextFieldInfo, sqlDataProviderHelper, fieldInfo.FieldName, fieldInfo.FieldType); _createdSqlDataTypeStoreTables.Add(sqlDataTypeStoreTable); sqlDataTypeStoreTables.Add(key, sqlDataTypeStoreTable); } var sqlDataTypeStore = new SqlDataTypeStore(result.InterfaceType, sqlDataTypeStoreTables, initInfo.DataTypeDescriptor.IsCodeGenerated, _sqlDataTypeStoresContainer); result.SqlDataTypeStore = sqlDataTypeStore; return result; } private InterfaceGeneratedClassesInfo InitializeStoreTypes(InterfaceConfigurationElement element, Dictionary<DataTypeDescriptor, IEnumerable<SqlDataTypeStoreDataScope>> allSqlDataTypeStoreDataScopes, Type dataContextClass, bool forceCompile, ref bool dataContextRecompilationNeeded) { HelperClassesGenerationInfo toCompile = null; var result = InitializeStoreTypes(element, allSqlDataTypeStoreDataScopes, dataContextClass, null, forceCompile, ref dataContextRecompilationNeeded, ref toCompile); if (result != null && toCompile != null) { var codeGenerationBuilder = new CodeGenerationBuilder(_dataProviderContext.ProviderName + ":" + result.InterfaceType.FullName); toCompile.GenerateCodeAction(codeGenerationBuilder); var types = CodeGenerationManager.CompileRuntimeTempTypes(codeGenerationBuilder, false).ToArray(); toCompile.PopulateFieldsAction(types); } return result; } private InterfaceGeneratedClassesInfo InitializeStoreTypes(InterfaceConfigurationElement element, Dictionary<DataTypeDescriptor, IEnumerable<SqlDataTypeStoreDataScope>> allSqlDataTypeStoreDataScopes, Type dataContextClass, Dictionary<Guid, Type> dataTypes, bool forceCompile, ref bool dataContextRecompilationNeeded, ref HelperClassesGenerationInfo helperClassesGenerationInfo) { var result = new InterfaceGeneratedClassesInfo(); var dataScopes = new List<SqlDataTypeStoreDataScope>(); foreach (StorageInformation storageInformation in element.Stores) { var sqlDataTypeStoreDataScope = new SqlDataTypeStoreDataScope { DataScopeName = storageInformation.DataScope, CultureName = storageInformation.CultureName, TableName = storageInformation.TableName }; dataScopes.Add(sqlDataTypeStoreDataScope); } result.DataScopes = dataScopes; Guid dataTypeId = element.DataTypeId; var dataTypeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(dataTypeId, true); if (dataTypeDescriptor == null) { throw NewConfigurationException(element, $"Failed to get a DataTypeDescriptor by id '{dataTypeId}'"); } result.DataTypeDescriptor = dataTypeDescriptor; Type interfaceType = null; try { if (dataTypes == null || !dataTypes.TryGetValue(dataTypeId, out interfaceType) || interfaceType == null) { interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor); } if (interfaceType == null) { Log.LogWarning(LogTitle, "The data interface type '{0}' does not exists and is not code generated. It will not be unusable", dataTypeDescriptor.TypeManagerTypeName); return result; } result.InterfaceType = interfaceType; string validationMessage; bool isValid = DataTypeValidationRegistry.Validate(interfaceType, dataTypeDescriptor, out validationMessage); if (!isValid) { Log.LogCritical(LogTitle, validationMessage); throw new InvalidOperationException(validationMessage); } Dictionary<SqlDataTypeStoreTableKey, StoreTypeInfo> fields; helperClassesGenerationInfo = EnsureNeededTypes(dataTypeDescriptor, dataScopes, allSqlDataTypeStoreDataScopes, dataContextClass, out fields, ref dataContextRecompilationNeeded, forceCompile); result.Fields = fields; return result; } catch (Exception ex) { if (interfaceType != null) { DataProviderRegistry.RegisterDataTypeInitializationError(interfaceType, ex); DataProviderRegistry.AddKnownDataType(interfaceType, _dataProviderContext.ProviderName); Log.LogError(LogTitle, "Failed initialization for the datatype {0}", dataTypeDescriptor.TypeManagerTypeName); } Log.LogError(LogTitle, ex); result.Fields = new Dictionary<SqlDataTypeStoreTableKey, StoreTypeInfo>(); return result; } } private class InitializeStoreResult { public InitializeStoreResult() { TableNames = new Dictionary<SqlDataTypeStoreTableKey, string>(); } public Type InterfaceType { get; set; } public SqlDataTypeStore SqlDataTypeStore { get; set; } public Dictionary<SqlDataTypeStoreTableKey, string> TableNames { get; set; } } private class InterfaceGeneratedClassesInfo { public Type InterfaceType { get; set; } public List<SqlDataTypeStoreDataScope> DataScopes { get; set; } public DataTypeDescriptor DataTypeDescriptor { get; set; } public Dictionary<SqlDataTypeStoreTableKey, StoreTypeInfo> Fields { get; set; } } private void AddDataTypeStore(InitializeStoreResult initializeStoreResult, bool doValidate = true, bool isInitialization = false) { if (initializeStoreResult.InterfaceType == null) { return; } bool isValid = initializeStoreResult.SqlDataTypeStore != null; if (isValid && doValidate) { isValid = ValidateTables(initializeStoreResult, isInitialization); } if (!isValid) { _sqlDataTypeStoresContainer.AddKnownInterface(initializeStoreResult.InterfaceType); return; } _sqlDataTypeStoresContainer.AddSupportedDataTypeStore(initializeStoreResult.InterfaceType, initializeStoreResult.SqlDataTypeStore); DataProviderRegistry.AddNewDataType(initializeStoreResult.InterfaceType, _dataProviderContext.ProviderName); } private bool ValidateTables(InitializeStoreResult initializeStoreResult, bool isInitialization) { var errors = new StringBuilder(); bool isValid = true; var interfaceType = initializeStoreResult.InterfaceType; foreach (string tableName in initializeStoreResult.TableNames.Values) { bool isTableValid = ValidateTable(interfaceType, tableName, errors); if (!isTableValid) isValid = false; } if (!isValid) { DataTypeValidationRegistry.AddValidationError(initializeStoreResult.InterfaceType, _dataProviderContext.ProviderName, errors.ToString()); if (isInitialization && GlobalSettingsFacade.EnableDataTypesAutoUpdate && interfaceType.IsAutoUpdateble() && !interfaceType.IsGenerated()) { Log.LogInformation(LogTitle, "Data schema for the data interface '{0}' on the SqlDataProvider '{1}' is not matching and will be updated.", initializeStoreResult.InterfaceType, _dataProviderContext.ProviderName); Log.LogInformation(LogTitle, errors.ToString()); } else { Log.LogCritical(LogTitle, "The data interface '{0}' will not work for the SqlDataProvider '{1}'", initializeStoreResult.InterfaceType, _dataProviderContext.ProviderName); Log.LogCritical(LogTitle, errors.ToString()); } } return isValid; } private bool ValidateTable(Type interfaceType, string tableName, StringBuilder errors) { ISqlTableInformation sqlTableInformation = SqlTableInformationStore.GetTableInformation(_connectionString, tableName); if (sqlTableInformation == null) { errors.AppendLine($"Table '{tableName}' does not exist"); return false; } int primaryKeyCount = sqlTableInformation.ColumnInformations.Count(column => column.IsPrimaryKey); if (primaryKeyCount == 0) { errors.AppendLine($"The table '{tableName}' is missing a primary key"); return false; } var columns = new List<SqlColumnInformation>(sqlTableInformation.ColumnInformations); var properties = interfaceType.GetPropertiesRecursively(); foreach (PropertyInfo property in properties) { if (property.Name == nameof(IData.DataSourceId)) continue; SqlColumnInformation column = columns.Find(col => col.ColumnName == property.Name); if (column == null) { errors.AppendLine($"The interface property named '{property.Name}' does not exist in the table '{sqlTableInformation.TableName}' as a column."); return false; } if (!column.IsNullable || column.Type == typeof(string)) { if (column.Type != property.PropertyType) { errors.AppendLine($"Type mismatch for property '{property.Name}'. Type '{property.PropertyType}' does not match the database column type '{column.Type}'."); return false; } } } // Updating schema from C1 4.1, to be removed in future versions. // if (typeof (ILocalizedControlled).IsAssignableFrom(interfaceType) // && !properties.Any(p => p.Name == "CultureName") // && columns.Any(c => c.ColumnName == "CultureName")) // { // Log.LogInformation(LogTitle, "Removing obsolete 'CultureName' column from table '{0}'", tableName); // string selectConstraintName = string.Format( // @"SELECT df.name 'ConstraintName' // FROM sys.default_constraints df // INNER JOIN sys.tables t ON df.parent_object_id = t.object_id // INNER JOIN sys.columns c ON df.parent_object_id = c.object_id AND df.parent_column_id = c.column_id // where t.name = '{0}' // and c.name = 'CultureName'", tableName); // var dt = ExecuteReader(selectConstraintName); // List<string> constraints = (from DataRow dr in dt.Rows select dr["ConstraintName"].ToString()).ToList(); // foreach (var constrainName in constraints) // { // ExecuteSql("ALTER TABLE [{0}] DROP CONSTRAINT [{1}]".FormatWith(tableName, constrainName)); // } // string sql = "ALTER TABLE [{0}] DROP COLUMN [CultureName]".FormatWith(tableName); // ExecuteSql(sql); // } return true; } //private void ExecuteSql(string sql) //{ // var conn = SqlConnectionManager.GetConnection(_connectionString); // Log.LogInformation(LogTitle, sql); // using (var cmd = new SqlCommand(sql, conn)) // { // cmd.ExecuteNonQuery(); // } //} //private DataTable ExecuteReader(string commandText) //{ // var conn = SqlConnectionManager.GetConnection(_connectionString); // using (var cmd = new SqlCommand(commandText, conn)) // { // using (var dt = new DataTable()) // { // using (var rdr = cmd.ExecuteReader()) // { // if (rdr != null) dt.Load(rdr); // return dt; // } // } // } //} internal class StoreTypeInfo { public StoreTypeInfo(string fieldName, Type fieldType, Type sqlHelperType) { FieldName = fieldName; FieldType = fieldType; SqlHelperClass = sqlHelperType; } public string FieldName; public Type FieldType; public Type SqlHelperClass; public FieldInfo DataContextField; } /// <summary> /// Checks that tables related to specified data type included in current DataContext class, if not - compiles a new version of DataContext that contains them /// </summary> private HelperClassesGenerationInfo EnsureNeededTypes( DataTypeDescriptor dataTypeDescriptor, IEnumerable<SqlDataTypeStoreDataScope> sqlDataTypeStoreDataScopes, Dictionary<DataTypeDescriptor, IEnumerable<SqlDataTypeStoreDataScope>> allSqlDataTypeStoreDataScopes, Type dataContextClassType, out Dictionary<SqlDataTypeStoreTableKey, StoreTypeInfo> fields, ref bool dataContextRecompileNeeded, bool forceCompile = false) { lock (_lock) { // Getting the interface (ensuring that it exists) Type interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor); var storeDataScopesToCompile = new List<SqlDataTypeStoreDataScope>(); var storeDataScopesAlreadyCompiled = new List<SqlDataTypeStoreDataScope>(); fields = new Dictionary<SqlDataTypeStoreTableKey, StoreTypeInfo>(); foreach (SqlDataTypeStoreDataScope storeDataScope in sqlDataTypeStoreDataScopes) { string dataContextFieldName = NamesCreator.MakeDataContextFieldName(storeDataScope.TableName); FieldInfo dataContextFieldInfo = null; if (dataContextClassType != null) { dataContextFieldInfo = dataContextClassType.GetFields(BindingFlags.Public | BindingFlags.Instance) .SingleOrDefault(f => f.Name == dataContextFieldName); } string sqlDataProviderHelperClassFullName = NamesCreator.MakeSqlDataProviderHelperClassFullName(dataTypeDescriptor, storeDataScope.DataScopeName, storeDataScope.CultureName, _dataProviderContext.ProviderName); string entityClassName = NamesCreator.MakeEntityClassFullName(dataTypeDescriptor, storeDataScope.DataScopeName, storeDataScope.CultureName, _dataProviderContext.ProviderName); Type sqlDataProviderHelperClass = null, entityClass = null; try { sqlDataProviderHelperClass = TryGetGeneratedType(sqlDataProviderHelperClassFullName); entityClass = TryGetGeneratedType(entityClassName); forceCompile = forceCompile || CodeGenerationManager.IsRecompileNeeded(interfaceType, new[] { sqlDataProviderHelperClass, entityClass }); } catch (TypeLoadException) { forceCompile = true; } if (!forceCompile) { var storeTypeInfo = new StoreTypeInfo(dataContextFieldName, entityClass, sqlDataProviderHelperClass) { DataContextField = dataContextFieldInfo }; fields.Add(new SqlDataTypeStoreTableKey(storeDataScope.DataScopeName, storeDataScope.CultureName), storeTypeInfo); } if (dataContextFieldInfo == null) { dataContextRecompileNeeded = true; } if (forceCompile) { storeDataScopesToCompile.Add(storeDataScope); } else { storeDataScopesAlreadyCompiled.Add(storeDataScope); } } if (storeDataScopesToCompile.Any()) { dataContextRecompileNeeded = true; if (!dataTypeDescriptor.IsCodeGenerated) { // Building a new descriptor so generated classes take in account field changes dataTypeDescriptor = DynamicTypeManager.BuildNewDataTypeDescriptor(interfaceType); } return CompileMissingClasses(dataTypeDescriptor, allSqlDataTypeStoreDataScopes, fields, storeDataScopesToCompile, storeDataScopesAlreadyCompiled); } } return null; } private bool TryLoadDataContextClass(Type dataContextClassType) { if (_typeLoadResults.ContainsKey(dataContextClassType)) { return _typeLoadResults[dataContextClassType]; } bool success = true; var connection = SqlConnectionManager.GetConnection(_connectionString); try { var dataContext = (DataContext)Activator.CreateInstance(dataContextClassType, connection); dataContext.Dispose(); } catch (Exception ex) { var innerEx = ex; while (innerEx is TargetInvocationException) { innerEx = innerEx.InnerException; } if (!(innerEx is TypeLoadException || innerEx is FileNotFoundException)) { throw; } Log.LogWarning(LogTitle, "Failed to load DataContext class, creating a new one."); Log.LogWarning(LogTitle, innerEx.Message); success = false; } lock (_typeLoadResults) { _typeLoadResults[dataContextClassType] = success; } return success; } private class HelperClassesGenerationInfo { public Action<CodeGenerationBuilder> GenerateCodeAction; public Action<Type[]> PopulateFieldsAction; } private HelperClassesGenerationInfo CompileMissingClasses(DataTypeDescriptor dataTypeDescriptor, Dictionary<DataTypeDescriptor, IEnumerable<SqlDataTypeStoreDataScope>> allSqlDataTypeStoreDataScopes, Dictionary<SqlDataTypeStoreTableKey, StoreTypeInfo> fields, List<SqlDataTypeStoreDataScope> storeDataScopesToCompile, List<SqlDataTypeStoreDataScope> storeDataScopesAlreadyCompiled) { return new HelperClassesGenerationInfo { GenerateCodeAction = codeGenerationBuilder => { var sqlDataProviderCodeBuilder = new SqlDataProviderCodeBuilder(_dataProviderContext.ProviderName, codeGenerationBuilder); sqlDataProviderCodeBuilder.AddDataType(dataTypeDescriptor, storeDataScopesToCompile); sqlDataProviderCodeBuilder.AddExistingDataType(dataTypeDescriptor, storeDataScopesAlreadyCompiled); }, PopulateFieldsAction = types => { foreach (SqlDataTypeStoreDataScope storeDataScope in storeDataScopesToCompile) { string dataContextFieldName = NamesCreator.MakeDataContextFieldName(storeDataScope.TableName); string helperClassFullName = NamesCreator.MakeSqlDataProviderHelperClassFullName( dataTypeDescriptor, storeDataScope.DataScopeName, storeDataScope.CultureName, _dataProviderContext.ProviderName); Type helperClass = types.Single(f => f.FullName == helperClassFullName); string entityClassFullName = NamesCreator.MakeEntityClassFullName( dataTypeDescriptor, storeDataScope.DataScopeName, storeDataScope.CultureName, _dataProviderContext.ProviderName); Type entityClass = types.Single(f => f.FullName == entityClassFullName); var storeTableKey = new SqlDataTypeStoreTableKey(storeDataScope.DataScopeName, storeDataScope.CultureName); fields[storeTableKey] = new StoreTypeInfo(dataContextFieldName, entityClass, helperClass); } foreach (SqlDataTypeStoreDataScope storeDataScope in storeDataScopesAlreadyCompiled) { string dataContextFieldName = NamesCreator.MakeDataContextFieldName(storeDataScope.TableName); string helperClassFullName = NamesCreator.MakeSqlDataProviderHelperClassFullName( dataTypeDescriptor, storeDataScope.DataScopeName, storeDataScope.CultureName, _dataProviderContext.ProviderName); Type helperClass = TryGetGeneratedType(helperClassFullName); string entityClassFullName = NamesCreator.MakeEntityClassFullName( dataTypeDescriptor, storeDataScope.DataScopeName, storeDataScope.CultureName, _dataProviderContext.ProviderName); Type entityClass = TryGetGeneratedType(entityClassFullName); var storeTableKey = new SqlDataTypeStoreTableKey(storeDataScope.DataScopeName, storeDataScope.CultureName); fields[storeTableKey] = new StoreTypeInfo(dataContextFieldName, entityClass, helperClass); } } }; } private Type TryGetGeneratedType(string typeName) { Type compiledType = CodeGenerationManager.GetCompiledType(typeName); if (compiledType != null) return compiledType; if (_compositeGeneratedAssembly != null) { Type result = _compositeGeneratedAssembly.GetType(typeName, false); if (result != null) return result; } return TypeManager.TryGetType(typeName); } /// <summary> /// This method updates the DataContextQueryableFieldInfo property on all existing store tables. /// </summary> /// <remarks> /// This is needed due to the fact that all data stores share the same /// DataContext class and the DataContext class is code generated everytime /// a new store is code generated. /// </remarks> /// <param name="newDataContextClassType"></param> private void UpdateCreatedSqlDataTypeStoreTables(Type newDataContextClassType) { foreach (SqlDataTypeStoreTable dataTypeStoreTable in _createdSqlDataTypeStoreTables) { Verify.IsNotNull(dataTypeStoreTable.DataContextQueryableFieldInfo, "Missing field info"); string fieldName = dataTypeStoreTable.DataContextQueryableFieldInfo.Name; FieldInfo newFieldInfo = newDataContextClassType.GetFields(BindingFlags.Public | BindingFlags.Instance).SingleOrDefault(f => f.Name == fieldName); if (newFieldInfo != null) { dataTypeStoreTable.DataContextQueryableFieldInfo = newFieldInfo; } else { Log.LogWarning(LogTitle, $"DataContext missing field newly created field '{fieldName}'"); } } } private Dictionary<DataTypeDescriptor, IEnumerable<SqlDataTypeStoreDataScope>> BuildAllExistingDataTypeStoreDataScopes() { var allSqlDataTypeStoreDataScopes = new Dictionary<DataTypeDescriptor, IEnumerable<SqlDataTypeStoreDataScope>>(); foreach (InterfaceConfigurationElement element in _interfaceConfigurationElements) { Guid dataTypeId = element.DataTypeId; var dataTypeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(dataTypeId, true); if (dataTypeDescriptor == null) { Log.LogWarning(LogTitle, $"Failed to get data type descriptor by id '{dataTypeId}'"); continue; } var sqlDataTypeStoreDataScopes = new List<SqlDataTypeStoreDataScope>(); foreach (StorageInformation storageInformation in element.Stores) { var sqlDataTypeStoreDataScope = new SqlDataTypeStoreDataScope { DataScopeName = storageInformation.DataScope, CultureName = storageInformation.CultureName, TableName = storageInformation.TableName }; sqlDataTypeStoreDataScopes.Add(sqlDataTypeStoreDataScope); } allSqlDataTypeStoreDataScopes.Add(dataTypeDescriptor, sqlDataTypeStoreDataScopes); } return allSqlDataTypeStoreDataScopes; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/SqlDataTypeStore.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Data.Linq; using System.Linq; using Composite.Data; using Composite.Data.Plugins.DataProvider; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Foundation; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider { internal sealed class SqlDataTypeStore { private readonly SqlDataTypeStoresContainer _sqlDataTypeStoresContainer; private Type _listOfInterfaceType = null; internal SqlDataTypeStore(Type interfaceType, Dictionary<SqlDataTypeStoreTableKey, SqlDataTypeStoreTable> sqlDataTypeStoreTables, bool isGeneretedDataType, SqlDataTypeStoresContainer sqlDataTypeStoresContainer) { _sqlDataTypeStoresContainer = sqlDataTypeStoresContainer; InterfaceType = interfaceType; StoreTables = sqlDataTypeStoreTables; IsGeneretedDataType = isGeneretedDataType; } public Type InterfaceType { get; private set; } public bool IsGeneretedDataType { get; private set; } internal Dictionary<SqlDataTypeStoreTableKey, SqlDataTypeStoreTable> StoreTables { get; private set; } public IQueryable GetQueryable() { SqlDataTypeStoreTableKey tableKey = GetTableKey(); IQueryable queryable; if (StoreTables.ContainsKey(tableKey)) { queryable = SqlDataContextHelperClass.GetTable(_sqlDataTypeStoresContainer.GetDataContext(), StoreTables[tableKey]); } else { if (_listOfInterfaceType == null) { _listOfInterfaceType = typeof(List<>); _listOfInterfaceType = _listOfInterfaceType.MakeGenericType(InterfaceType); } IEnumerable list = (IEnumerable)Activator.CreateInstance(_listOfInterfaceType, null); return list.AsQueryable(); } return queryable; } public IData GetDataByDataId(IDataId dataId, DataProviderContext dataProivderContext) { SqlDataTypeStoreTable storage = GetCurrentTable(); return storage.SqlDataProviderHelper.GetDataById(GetQueryable(), dataId, dataProivderContext); } public IData AddNew(IData dataToAdd, DataProviderContext dataProivderContext, DataContext dataContext) { SqlDataTypeStoreTable storeTable = GetCurrentTable(); return storeTable.SqlDataProviderHelper.AddData((ISqlDataContext)dataContext, dataToAdd, dataProivderContext); } public void RemoveData(IData dataToRemove, DataContext dataContext) { SqlDataTypeStoreTable storeTable = GetCurrentTable(); storeTable.SqlDataProviderHelper.RemoveData((ISqlDataContext)dataContext, dataToRemove); } private SqlDataTypeStoreTableKey GetTableKey() { string dataScope = DataScopeManager.MapByType(InterfaceType).Name; string cultureInfo = LocalizationScopeManager.MapByType(InterfaceType).Name; return new SqlDataTypeStoreTableKey(dataScope, cultureInfo); } private SqlDataTypeStoreTable GetCurrentTable() { SqlDataTypeStoreTableKey tableKey = GetTableKey(); if (StoreTables.ContainsKey(tableKey) == false) throw new InvalidOperationException(string.Format("No SQL table defined for the interface type '{0}' in the data scope '{1}' and locale '{2}'", InterfaceType.FullName, tableKey.DataScopeIdentifierName, tableKey.LocaleCultureName)); return StoreTables[tableKey]; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/SqlDataTypeStoreDataScope.cs ================================================  namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider { internal class SqlDataTypeStoreDataScope { internal string DataScopeName { get; set; } internal string CultureName { get; set; } internal string TableName { get; set; } public override bool Equals(object obj) { return Equals(obj as SqlDataTypeStoreDataScope); } public bool Equals(SqlDataTypeStoreDataScope sqlDataTypeStoreDataScope) { if (sqlDataTypeStoreDataScope == null) return false; return sqlDataTypeStoreDataScope.DataScopeName == DataScopeName && sqlDataTypeStoreDataScope.CultureName == CultureName && sqlDataTypeStoreDataScope.TableName == TableName; } public override int GetHashCode() { return DataScopeName.GetHashCode() ^ CultureName.GetHashCode() ^ TableName.GetHashCode(); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MSSqlServerDataProvider/SqlDataTypeStoresContainer.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Data; using System.Data.Linq; using System.Data.SqlTypes; using System.Reflection; using Composite.Core.Sql; using Composite.Core.Threading; using Composite.Data; using Composite.Data.Plugins.DataProvider; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.CodeGeneration; using Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider.Foundation; namespace Composite.Plugins.Data.DataProviders.MSSqlServerDataProvider { internal sealed class SqlDataTypeStoresContainer { private static readonly ConcurrentDictionary<Type, List<PropertyInfo>> _dateTimeProperties = new ConcurrentDictionary<Type, List<PropertyInfo>>(); private readonly Dictionary<Type, SqlDataTypeStore> _sqlDataTypeStores = new Dictionary<Type, SqlDataTypeStore>(); private readonly List<Type> _supportedInterfaces = new List<Type>(); private readonly List<Type> _knownInterfaces = new List<Type>(); private readonly List<Type> _generatedInterfaces = new List<Type>(); private readonly string _providerName; private readonly SqlLoggingContext _sqlLoggingContext; internal SqlDataTypeStoresContainer(string providerName, string connectionString, SqlLoggingContext sqlLoggingContext = null) { _providerName = providerName; ConnectionString = connectionString; _sqlLoggingContext = sqlLoggingContext; } public string ConnectionString { get; internal set; } /// <summary> /// All working data types /// </summary> public IEnumerable<Type> SupportedInterfaces => _supportedInterfaces; /// <summary> /// All data types, including non working due to config error or something else /// </summary> public IEnumerable<Type> KnownInterfaces => _knownInterfaces; /// <summary> /// All working generated data types /// </summary> public IEnumerable<Type> GeneratedInterfaces => _generatedInterfaces; internal Type DataContextClass { get; set; } public SqlDataTypeStore GetDataTypeStore(Type interfaceType) { SqlDataTypeStore store; if (!_sqlDataTypeStores.TryGetValue(interfaceType, out store)) { throw new InvalidOperationException($"Interface '{interfaceType}' is not supported"); } return store; } /// <summary> /// This method adds the support of the given data interface type to the xml data provider. /// </summary> /// <param name="interfaceType"></param> /// <param name="sqlDataTypeStore"></param> internal void AddSupportedDataTypeStore(Type interfaceType, SqlDataTypeStore sqlDataTypeStore) { Verify.That(!_sqlDataTypeStores.ContainsKey(interfaceType), "Type {0} is registered in the SqlDataProvider configuration multiple types", interfaceType); _sqlDataTypeStores.Add(interfaceType, sqlDataTypeStore); _supportedInterfaces.Add(interfaceType); AddKnownInterface(interfaceType); if (sqlDataTypeStore.IsGeneretedDataType) { _generatedInterfaces.Add(interfaceType); } } internal void AddKnownInterface(Type interfaceType) { _knownInterfaces.Add(interfaceType); } internal void RemoveKnownInterface(Type interfaceType) { _knownInterfaces.Remove(interfaceType); } #region CRUD methos public List<T> AddNew<T>(IEnumerable<T> dataset, DataProviderContext dataProviderContext) where T : class, IData { SqlDataTypeStore sqlDataTypeStore = TryGetsqlDataTypeStore(typeof(T)); if (sqlDataTypeStore == null) throw new InvalidOperationException($"The interface '{typeof(T).FullName}' has not been configured"); var resultDataset = new List<T>(); using (var dataContext = CreateDataContext()) { foreach (IData data in dataset) { Verify.ArgumentCondition(data != null, "dataset", "Data set may not contain null values"); IData newData = sqlDataTypeStore.AddNew(data, dataProviderContext, dataContext); ((IEntity) newData).Commit(); CheckConstraints(newData); resultDataset.Add((T)newData); } SubmitChanges(dataContext); } return resultDataset; } public void Update(IEnumerable<IData> dataset) { using (DataContext dataContext = CreateDataContext()) { foreach (IData data in dataset) { Verify.ArgumentCondition(data != null, "dataset", "The data set shouldn't contain any null values."); // TODO: Check if it's necessury to make an optimization here ITable table = GetTable(dataContext, data); table.Attach(data); IEntity entity = (IEntity)data; entity.Commit(); } SubmitChanges(dataContext); } } public void Delete(IEnumerable<DataSourceId> dataSourceIds, DataProviderContext dataProivderContext) { DataContext dataContext = null; try { foreach (DataSourceId dataSourceId in dataSourceIds) { if (dataSourceId == null) throw new ArgumentException("dataSourceIds contains null values"); using (new DataScope(dataSourceId.DataScopeIdentifier, dataSourceId.LocaleScope)) { SqlDataTypeStore sqlDataTypeStore = TryGetsqlDataTypeStore(dataSourceId.InterfaceType); if (sqlDataTypeStore == null) throw new InvalidOperationException($"The interface '{dataSourceId.InterfaceType.FullName}' has not been configured"); IData data = sqlDataTypeStore.GetDataByDataId(dataSourceId.DataId, dataProivderContext); Verify.That(data != null, "Row has already been deleted"); if (dataContext == null) dataContext = CreateDataContext(); sqlDataTypeStore.RemoveData(data, dataContext); } } if (dataContext != null) { SubmitChanges(dataContext); } } finally { dataContext?.Dispose(); } } #endregion private SqlDataTypeStore TryGetsqlDataTypeStore(Type interfaceType) { Verify.ArgumentNotNull(interfaceType, "interfaceType"); SqlDataTypeStore result; return _sqlDataTypeStores.TryGetValue(interfaceType, out result) ? result : null; } private static ITable GetTable(DataContext dataContext, Object entity) { Verify.ArgumentNotNull(dataContext, "dataContext"); Verify.ArgumentNotNull(entity, "entity"); Type entityType = entity.GetType(); ITable table = dataContext.GetTable(entityType); Verify.IsNotNull(table, "Failed to find a table, related to '{0}' type", entityType.FullName); return table; } private static void CheckConstraints(IData data) { // DateTime.MinValue is not supported by SQL, since it has a different minimal value for a date if (data is IChangeHistory changeHistory && changeHistory.ChangeDate == DateTime.MinValue) { changeHistory.ChangeDate = DateTime.Now; } foreach(PropertyInfo dateTimeProperty in GetDateTimeProperties(data.DataSourceId.InterfaceType)) { object value = dateTimeProperty.GetValue(data, null); if(value == null) continue; DateTime dateTime = (DateTime) value; if(dateTime == DateTime.MinValue) { dateTimeProperty.SetValue(data, SqlDateTime.MinValue.Value, null); } } } private static IEnumerable<PropertyInfo> GetDateTimeProperties(Type interfaceType) { return _dateTimeProperties.GetOrAdd(interfaceType, type => { List<PropertyInfo> result = new List<PropertyInfo>(); foreach (PropertyInfo property in interfaceType.GetProperties()) { if ((property.PropertyType != typeof(DateTime) && property.PropertyType != typeof(DateTime?)) || property.GetSetMethod() == null) { continue; } result.Add(property); } foreach(Type baseInterface in interfaceType.GetInterfaces()) { if (baseInterface == typeof(IChangeHistory)) continue; result.AddRange(GetDateTimeProperties(baseInterface)); } return result; }); } /// <summary> /// Gets an instance of a DataContext. /// </summary> /// <returns></returns> internal DataContext GetDataContext() { string threadDataKey = "SqlDataContext" + _providerName; var threadData = ThreadDataManager.GetCurrentNotNull(); if (threadData.HasValue(threadDataKey)) { DataContext result = Verify.ResultNotNull(threadData[threadDataKey] as DataContext); // In a result of a flush, data context type can be changed if(result.GetType().GUID == DataContextClass.GUID) { return result; } } DataContext dataContext = CreateDataContext(); dataContext.ObjectTrackingEnabled = false; threadData.OnDispose += dataContext.Dispose; threadData.SetValue(threadDataKey, dataContext); if (_sqlLoggingContext.Enabled) { dataContext.Log = new SqlLoggerTextWriter(_sqlLoggingContext); } return dataContext; } private DataContext CreateDataContext() { IDbConnection connection = SqlConnectionManager.GetConnection(ConnectionString); DataContext dataContext = (DataContext)Activator.CreateInstance(DataContextClass, connection); if (_sqlLoggingContext.Enabled) { dataContext.Log = new SqlLoggerTextWriter(_sqlLoggingContext); } return dataContext; } internal static void SubmitChanges(DataContext dataContext) { dataContext.SubmitChanges(); } public void ForgetInterface(Type interfaceType) { _sqlDataTypeStores.Remove(interfaceType); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MediaFileProvider/MediaFile.cs ================================================ using System; using Composite.Data.Types; using Composite.Data; using Composite.Data.Plugins.DataProvider.Streams; using Composite.Data.Streams; using Newtonsoft.Json; namespace Composite.Plugins.Data.DataProviders.MediaFileProvider { [FileStreamManager(typeof(FileSystemFileStreamManager))] internal class MediaFile : FileSystemFileBase, IMediaFile { private string _keyPath; public MediaFile(IMediaFileData file, string storeId, DataSourceId dataSourceId, string filePath) { DataSourceId = dataSourceId; StoreId = storeId; this.Id = file.Id; this.FileName = file.FileName; this.FolderPath = file.FolderPath; this.Title = file.Title; this.Description = file.Description; this.Tags = file.Tags; this.MimeType = file.MimeType; this.Length = file.Length; this.IsReadOnly = false; this.Culture = file.CultureInfo; this.CreationTime = file.CreationTime; this.LastWriteTime = file.LastWriteTime; this.SystemPath = filePath; } [JsonConstructor] private MediaFile(Guid id,string fileName,string folderPath,string title,string description, string tags,string mimeType,int? length,bool isReadOnly,string culture,DateTime creationTime, DateTime lastWriteTime,string storeId, DataSourceId dataSourceId, string filePath) { DataSourceId = dataSourceId; StoreId = storeId; this.Id = id; this.FileName = fileName; this.FolderPath = folderPath; this.Title = title; this.Description = description; this.Tags = tags; this.MimeType = mimeType; this.Length = length; this.IsReadOnly = isReadOnly; this.Culture = culture; this.CreationTime = creationTime; this.LastWriteTime = lastWriteTime; this.SystemPath = filePath; } public Guid Id { get; internal set; } public string KeyPath => _keyPath ?? (_keyPath = this.GetKeyPath()); public string CompositePath { get { return this.GetCompositePath(); } set { /* Do nothing. Used for deserialization purpouses */ } } public string StoreId { get; set; } public string FolderPath { get; set; } public string FileName { get; set; } public string Title { get; set; } public string Description { get; set; } public string Tags { get; set; } public string Culture { get; set; } public string MimeType { get; set; } public int? Length { get; set; } public DateTime? CreationTime { get; set; } public DateTime? LastWriteTime { get; set; } public bool IsReadOnly { get; set; } public DataSourceId DataSourceId { get; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MediaFileProvider/MediaFileFolder.cs ================================================ using System; using Composite.Data.Types; using Composite.Data; using Newtonsoft.Json; namespace Composite.Plugins.Data.DataProviders.MediaFileProvider { internal sealed class MediaFileFolder : IMediaFileFolder { public MediaFileFolder(IMediaFolderData folder, string storeId, DataSourceId dataSourceId) { DataSourceId = dataSourceId; Id = folder.Id; Description = folder.Description; Title = folder.Title; StoreId = storeId; Path = folder.Path; } [JsonConstructor] private MediaFileFolder(Guid id,string description,string title,string path, string storeId, DataSourceId dataSourceId) { DataSourceId = dataSourceId; Id = id; Description = description; Title = title; StoreId = storeId; Path = path; } public Guid Id { get; private set; } public string KeyPath => this.GetKeyPath(); [JsonIgnore] public string CompositePath { get => this.GetCompositePath(); set => throw new NotImplementedException(); } public string StoreId { get; set; } public string Path { get; set; } public string Title { get; set; } public string Description { get; set; } public bool IsReadOnly { get; set; } public DataSourceId DataSourceId { get; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/MediaFileProvider/MediaFileProvider.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.IO; using System.Linq; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Routing; using Composite.Data; using Composite.Data.Plugins.DataProvider; using Composite.Data.Plugins.DataProvider.Streams; using Composite.Data.Types; using Composite.Plugins.Routing.MediaUrlProviders; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Data.DataProviders.MediaFileProvider { /// <summary> /// </summary> /// <exclude /> [ConfigurationElementType(typeof(MediaFileDataProviderData))] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class MediaFileProvider : IWritableDataProvider { /// <exclude /> public enum MediaElementType { /// <exclude /> File = 1, /// <exclude /> Folder = 2, /// <exclude /> Store = 3 } private DataProviderContext _context; private IMediaFileStore _store; private readonly string _storeId; private readonly string _storeTitle; private readonly string _storeDescription; internal static string _workingDirectory; // NOTE: this field is accessed via reflection as well. private readonly object _syncRoot = new object(); private IQueryable<IMediaFile> _mediaFilesCachedQuery; private IQueryable<IMediaFileFolder> _mediaFoldersCachedQuery; private readonly DefaultMediaUrlProvider _mediaUrlProvider; internal MediaFileProvider(string rootDirectory, string storeId, string storeDescription, string storeTitle) { _workingDirectory = PathUtil.Resolve(rootDirectory); if (!C1Directory.Exists(_workingDirectory)) { C1Directory.CreateDirectory(_workingDirectory); } _storeId = storeId; _storeTitle = storeTitle; _storeDescription = storeDescription; DataEventSystemFacade.SubscribeToStoreChanged<IMediaFileData>(ClearQueryCache, false); DataEventSystemFacade.SubscribeToStoreChanged<IMediaFolderData>(ClearQueryCache, false); _mediaUrlProvider = new DefaultMediaUrlProvider(storeId); MediaUrls.RegisterMediaUrlProvider(storeId, _mediaUrlProvider); } private void ClearQueryCache(object sender, StoreEventArgs storeEventArgs) { lock (_syncRoot) { _mediaFilesCachedQuery = null; _mediaFoldersCachedQuery = null; } } /// <exclude /> public DataProviderContext Context { set { _context = value; } } /// <exclude /> public void Update(IEnumerable<IData> dataset) { if (dataset.Any(data => data == null)) { throw new ArgumentException("Data in list to update must be non-null"); } foreach (IData data in dataset) { MediaDataId dataId = data.DataSourceId.DataId as MediaDataId; if (dataId == null) { throw new ArgumentException("Invalid IData"); } if (dataId.MediaType == MediaElementType.File) { UpdateMediaFile((IMediaFile) data); } else if (dataId.MediaType == MediaElementType.Folder) { UpdateMediaFileFolder((IMediaFileFolder) data); } else { throw new InvalidOperationException($"Unexpected media type '{dataId.MediaType}'"); } } } private void UpdateMediaFile(IMediaFile updatedFile) { Guid id = updatedFile.Id; IMediaFileData currentFileData = DataFacade.GetData<IMediaFileData>(x => x.Id == id).First(); if (updatedFile.FolderPath != currentFileData.FolderPath || updatedFile.FileName != currentFileData.FileName) { ValidateMediaFileData(updatedFile); } CopyFileData(updatedFile, currentFileData); currentFileData.LastWriteTime = DateTime.Now; using (Stream stream = updatedFile.GetReadStream()) { currentFileData.Length = (int)stream.Length; } TransactionFileSystemFileStreamManager.WriteFileToDisk(updatedFile); DataFacade.Update(currentFileData); } private void UpdateMediaFileFolder(IMediaFileFolder updatedFolder) { Guid mediaFolderId = updatedFolder.Id; IMediaFolderData currentFolderData = DataFacade.GetData<IMediaFolderData>(x => x.Id == mediaFolderId).First(); if (updatedFolder.Path != currentFolderData.Path) { ValidateFolderData(updatedFolder); } string oldPath = currentFolderData.Path; string oldPathWithSlash = oldPath + "/"; List<IMediaFolderData> foldersToUpdatePath = (from item in DataFacade.GetData<IMediaFolderData>() where item.Path.StartsWith(oldPathWithSlash) && item.Id != currentFolderData.Id select item).ToList(); if (foldersToUpdatePath.Count > 0) { foreach (IMediaFolderData item in foldersToUpdatePath) { item.Path = updatedFolder.Path + item.Path.Substring(oldPath.Length); } DataFacade.Update(foldersToUpdatePath); } List<IMediaFileData> filesToUpdatePath = (from item in DataFacade.GetData<IMediaFileData>() where item.FolderPath == oldPath || item.FolderPath.StartsWith(oldPathWithSlash) select item).ToList(); if (filesToUpdatePath.Count > 0) { foreach (IMediaFileData mediaFileData in filesToUpdatePath) { mediaFileData.FolderPath = updatedFolder.Path + mediaFileData.FolderPath.Substring(oldPath.Length); } DataFacade.Update(filesToUpdatePath); } CopyFolderData(updatedFolder, currentFolderData); DataFacade.Update(currentFolderData); } /// <exclude /> public List<T> AddNew<T>(IEnumerable<T> dataset) where T : class, IData { var result = new List<T>(); if (dataset.Any(data => data == null)) { throw new ArgumentException("Data in list to add must be non-null"); } CheckInterface(typeof(T)); foreach (IData data in dataset) { if (typeof(T) == typeof(IMediaFile)) { result.Add(AddMediaFile((IMediaFile) data) as T); } else if (typeof(T) == typeof(IMediaFileFolder)) { result.Add(AddMediaFileFolder( (IMediaFileFolder)data) as T); } } return result; } private IMediaFile AddMediaFile(IMediaFile mediaFile) { ValidateMediaFileData(mediaFile); IMediaFileData fileData = DataFacade.BuildNew<IMediaFileData>(); fileData.Id = Guid.NewGuid(); CopyFileData(mediaFile, fileData); fileData.LastWriteTime = fileData.CreationTime = DateTime.Now; IMediaFile internalMediaFile; using (Stream readStream = mediaFile.GetReadStream()) { Verify.IsNotNull(readStream, "GetReadStream returned null for type '{0}'", mediaFile.GetType()); fileData.Length = (int)readStream.Length; string internalPath = GetFilePath(fileData.Id); internalMediaFile = new MediaFile(fileData, Store.Id, _context.CreateDataSourceId( new MediaDataId { MediaType = MediaElementType.File, Id = fileData.Id }, typeof(IMediaFile)), internalPath); using (Stream writeStream = internalMediaFile.GetNewWriteStream()) { readStream.CopyTo(writeStream); } } TransactionFileSystemFileStreamManager.WriteFileToDisk(internalMediaFile); fileData = DataFacade.AddNew<IMediaFileData>(fileData); return internalMediaFile; } private MediaFileFolder AddMediaFileFolder(IMediaFileFolder mediaFolder) { ValidateFolderData(mediaFolder); var folderData = DataFacade.BuildNew<IMediaFolderData>(); folderData.Id = Guid.NewGuid(); CopyFolderData(mediaFolder, folderData); folderData = DataFacade.AddNew<IMediaFolderData>(folderData); return new MediaFileFolder(folderData, Store.Id, _context.CreateDataSourceId( new MediaDataId { MediaType = MediaElementType.Folder, Id = folderData.Id }, typeof(IMediaFileFolder))); } /// <exclude /> public void Delete(IEnumerable<DataSourceId> dataSourceIds) { if (dataSourceIds.Any(f => f == null)) throw new ArgumentException("DataSourceIds must be non-null"); foreach (DataSourceId dataSourceId in dataSourceIds) { MediaDataId dataId = dataSourceId.DataId as MediaDataId; if (dataId.MediaType == MediaElementType.Folder) { DeleteMediaFolder(dataId.Id); } else if (dataId.MediaType == MediaElementType.File) { DeleteMediaFile(dataId.Id); } else { throw new InvalidOperationException($"Unexpected media type '{dataId.MediaType}'"); } } } private void DeleteMediaFolder(Guid mediaFolderId) { IMediaFolderData folder = DataFacade.GetData<IMediaFolderData>(x => x.Id == mediaFolderId).First(); string folderPath = folder.Path; string innerElementsPathPrefix = $"{folderPath}/"; var files = (from item in DataFacade.GetData<IMediaFileData>() where item.FolderPath.StartsWith(innerElementsPathPrefix) || item.FolderPath == folderPath select item).ToList(); DeleteMediaFiles(files); DataFacade.Delete<IMediaFolderData>(x => x.Path.StartsWith(innerElementsPathPrefix)); DataFacade.Delete(folder); } /// <exclude /> public IEnumerable<Type> GetSupportedInterfaces() { return new [] { typeof(IMediaFile), typeof(IMediaFileFolder), typeof(IMediaFileStore) }; } /// <exclude /> public IQueryable<T> GetData<T>() where T : class, IData { CheckInterface(typeof(T)); if (typeof(T) == typeof(IMediaFile)) { return GetMediaFiles() as IQueryable<T>; } if (typeof(T) == typeof(IMediaFileFolder)) { return GetMediaFileFolders() as IQueryable<T>; } // an IMediaFileStore query return new[] { Store as T }.AsQueryable(); } private IQueryable<IMediaFile> GetMediaFiles() { IQueryable<IMediaFile> mediaFilesQuery = _mediaFilesCachedQuery; if (mediaFilesQuery == null) { lock (_syncRoot) { if (_mediaFilesCachedQuery == null) { var fileItems = new List<IMediaFile>(); IQueryable<IMediaFileData> files = DataFacade.GetData<IMediaFileData>(); // DDZ: now the whole list of media files is loaded to memory, should be rewritten to return // a proper IQueryable, similar to our VirtualImageFileQueryable var publicDataScope = DataScopeIdentifier.Public; foreach (IMediaFileData file in files) { string internalPath = GetFilePath(file.Id); fileItems.Add(new MediaFile(file, Store.Id, _context.CreateDataSourceId( new MediaDataId { MediaType = MediaElementType.File, Id = file.Id }, typeof(IMediaFile), publicDataScope, CultureInfo.InvariantCulture), internalPath)); } _mediaFilesCachedQuery = fileItems.AsQueryable(); } mediaFilesQuery = _mediaFilesCachedQuery; } } return mediaFilesQuery; } private IQueryable<IMediaFileFolder> GetMediaFileFolders() { IQueryable<IMediaFileFolder> mediaFoldersQuery = _mediaFoldersCachedQuery; if (mediaFoldersQuery == null) { lock (_syncRoot) { if (_mediaFoldersCachedQuery == null) { var mediaFolderItems = new List<IMediaFileFolder>(); IQueryable<IMediaFolderData> folders = DataFacade.GetData<IMediaFolderData>(); var publicDataScope = DataScopeIdentifier.Public; foreach (IMediaFolderData folder in folders) { var dataId = new MediaDataId { MediaType = MediaElementType.Folder, Id = folder.Id }; var dataSourceId = _context.CreateDataSourceId(dataId, typeof(IMediaFileFolder), publicDataScope, CultureInfo.InvariantCulture); mediaFolderItems.Add(new MediaFileFolder(folder, Store.Id, dataSourceId)); } _mediaFoldersCachedQuery = mediaFolderItems.AsQueryable(); } mediaFoldersQuery = _mediaFoldersCachedQuery; } } return mediaFoldersQuery; } /// <exclude /> public T GetData<T>(IDataId dataId) where T : class, IData { Verify.ArgumentNotNull(dataId, nameof(dataId)); CheckInterface(typeof(T)); MediaDataId mediaDataId = dataId as MediaDataId; if (mediaDataId == null) { return null; } if (mediaDataId.MediaType == MediaElementType.Folder) { if (typeof(T) != typeof(IMediaFileFolder)) { throw new ArgumentException("The dataId specifies a IMediaFileFolder, but the generic method was invoked with different type"); } var folder = DataFacade.GetData<IMediaFolderData>().FirstOrDefault(x => x.Id == mediaDataId.Id); if (folder == null) { return null; } return new MediaFileFolder(folder, Store.Id, _context.CreateDataSourceId(new MediaDataId { MediaType = MediaElementType.Folder, Id = folder.Id }, typeof(IMediaFileFolder))) as T; } if (mediaDataId.MediaType == MediaElementType.File) { if (typeof(T) != typeof(IMediaFile)) { throw new ArgumentException("The dataId specifies a IMediaFile, but the generic method was invoked with different type"); } IMediaFileData file = DataFacade.GetData<IMediaFileData>().FirstOrDefault(x => x.Id == mediaDataId.Id); if (file == null) { return null; } string internalPath = GetFilePath(file.Id); return new MediaFile(file, Store.Id, _context.CreateDataSourceId(new MediaDataId { MediaType = MediaElementType.File, Id = file.Id }, typeof(IMediaFile)), internalPath) as T; } return Store as T; } private IMediaFileStore Store { get { if (_store == null) { _store = new MediaFileStore(_storeId, _storeTitle, _storeDescription, _context.CreateDataSourceId( new MediaDataId { MediaType = MediaElementType.Store }, typeof(IMediaFileStore))); } return _store; } } private void CheckInterface(Type interfaceType) { if (!typeof(IMediaFile).IsAssignableFrom(interfaceType) && !typeof(IMediaFileFolder).IsAssignableFrom(interfaceType) && !typeof(IMediaFileStore).IsAssignableFrom(interfaceType)) { throw new ArgumentException($"Unexpected interface '{interfaceType}' - only '{typeof(IMediaFile)}, {typeof(IMediaFileFolder)} and {typeof(IMediaFileStore)}' are supported"); } } private void DeleteMediaFile(Guid id) { string fullPath = GetFilePath(id); if (C1File.Exists(fullPath)) { C1File.Delete(fullPath); } DataFacade.Delete<IMediaFileData>(x => x.Id == id); } private void DeleteMediaFiles(IList<IMediaFileData> mediaFiles) { foreach (var mediaFile in mediaFiles) { string fullPath = GetFilePath(mediaFile.Id); if (C1File.Exists(fullPath)) { C1File.Delete(fullPath); } } DataFacade.Delete<IMediaFileData>(mediaFiles); } private bool DoesFolderExists(string path) { return path == "/" || GetData<IMediaFileFolder>().Any(item => item.Path == path); } private bool DoesFileExists(string path, string name) { return GetData<IMediaFile>().Any(item => item.FolderPath == path && item.FileName == name); } private void CopyFileData(IMediaFile from, IMediaFileData to) { to.CultureInfo = from.Culture; to.Description = from.Description; to.FileName = from.FileName; to.Tags = from.Tags; to.FolderPath = from.FolderPath; to.Length = from.Length; to.MimeType = MimeTypeInfo.GetCanonical(from.MimeType); to.Title = from.Title; } private void CopyFolderData(IMediaFileFolder from, IMediaFolderData to) { to.Description = from.Description; to.Path = from.Path; to.Title = from.Title; } private void ValidateMediaFileData(IMediaFile mediaFile) { if (!mediaFile.FolderPath.IsCorrectFolderName('/')) { throw new ArgumentException("Invalid folder name"); } if (!DoesFolderExists(mediaFile.FolderPath)) { throw new ArgumentException("Could not find any parents folders on path " + mediaFile.FolderPath); } if (DoesFileExists(mediaFile.FolderPath, mediaFile.FileName)) { throw new ArgumentException("File " + mediaFile.FileName + " already exists on path " + mediaFile.FolderPath); } } private void ValidateFolderData(IMediaFileFolder mediaFolder) { if (!mediaFolder.Path.IsCorrectFolderName('/')) { throw new ArgumentException("Invalid folder name"); } if (!DoesFolderExists(mediaFolder.GetParentFolderPath())) { throw new ArgumentException("Could not find any parents folders on path " + mediaFolder.GetParentFolderPath()); } if (DoesFolderExists(mediaFolder.Path)) { throw new ArgumentException("Folder already exists on path " + mediaFolder.Path); } } private string GetFilePath(Guid mediaId) => Path.Combine(_workingDirectory, mediaId.ToString()); /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class MediaDataId : IDataId { /// <exclude /> public MediaElementType MediaType { get; set; } /// <exclude /> public Guid Id { get; set; } /// <exclude /> public override bool Equals(object obj) => obj is MediaDataId mediaId && mediaId.Id == Id; /// <exclude /> public override int GetHashCode() => Id.GetHashCode(); } private sealed class MediaFileStore : IMediaFileStore { private readonly DataSourceId _dataSourceId; public MediaFileStore(string id, string title, string description, DataSourceId dataSourceId) { Id = id; Title = title; Description = description; _dataSourceId = dataSourceId; } public string Id { get; } public string Title { get; } public string Description { get; } public bool IsReadOnly => false; public bool ProvidesMetadata => true; public DataSourceId DataSourceId => _dataSourceId; } } [Assembler(typeof(MediaFileProviderAssembler))] internal sealed class MediaFileDataProviderData : DataProviderData { private const string _rootDirectoryProperty = "rootDirectory"; [ConfigurationProperty(_rootDirectoryProperty, IsRequired = true)] public string RootDirectory { get { return (string)base[_rootDirectoryProperty]; } set { base[_rootDirectoryProperty] = value; } } private const string _dataProviderProperty = "dataProvider"; [ConfigurationProperty(_dataProviderProperty, IsRequired = false, DefaultValue = "")] public string DataProvider { get { return (string)base[_dataProviderProperty]; } set { base[_dataProviderProperty] = value; } } private const string _storeIdProperty = "storeId"; [ConfigurationProperty(_storeIdProperty, IsRequired = true)] public string StoreId { get { return (string)base[_storeIdProperty]; } set { base[_storeIdProperty] = value; } } private const string _storeDescriptionProperty = "storeDescription"; [ConfigurationProperty(_storeDescriptionProperty, IsRequired = true)] public string StoreDescription { get { return (string)base[_storeDescriptionProperty]; } set { base[_storeDescriptionProperty] = value; } } private const string _storeTitleProperty = "storeTitle"; [ConfigurationProperty(_storeTitleProperty, IsRequired = true)] public string StoreTitle { get { return (string)base[_storeTitleProperty]; } set { base[_storeTitleProperty] = value; } } } internal sealed class MediaFileProviderAssembler : IAssembler<IDataProvider, DataProviderData> { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IDataProvider Assemble(IBuilderContext context, DataProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { var configuration = objectConfiguration as MediaFileDataProviderData; if (configuration == null) throw new ArgumentException("Expected configuration to be of type MediaFileDataProviderData", "objectConfiguration"); return new MediaFileProvider(configuration.RootDirectory, configuration.StoreId, configuration.StoreDescription, configuration.StoreTitle); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/VirtualImageFileProvider/VirtualImageFile.cs ================================================ using System; using Composite.Data.Types; using Composite.Data; namespace Composite.Plugins.Data.DataProviders.VirtualImageFileProvider { internal sealed class VirtualImageFile : IImageFile { private IMediaFile _sourceFile; internal VirtualImageFile(IMediaFile sourceFile) { _sourceFile = sourceFile; } public string CompositePath { get { return this.GetCompositePath(); } set { throw new NotImplementedException(); } } public string FolderPath { get { return _sourceFile.FolderPath; } set { _sourceFile.FolderPath = value; ; } } public string FileName { get { return _sourceFile.FileName; } set { _sourceFile.FileName = value; ; } } public DataSourceId DataSourceId { get { return _sourceFile.DataSourceId; } } public string StoreId { get { return _sourceFile.StoreId; } set { _sourceFile.StoreId = value;; } } public string Title { get { return _sourceFile.Title; } set { _sourceFile.Title = value;; } } public string Description { get { return _sourceFile.Description; } set { _sourceFile.Description = value;; } } public string Tags { get { return _sourceFile.Tags; } set { _sourceFile.Tags = value; ; } } public string Culture { get { return _sourceFile.Culture; } set { _sourceFile.Culture = value;; } } public string MimeType { get { return _sourceFile.MimeType; } } public int? Length { get { return _sourceFile.Length; } } public DateTime? CreationTime { get { return _sourceFile.CreationTime; } } public DateTime? LastWriteTime { get { return _sourceFile.LastWriteTime; } } public bool IsReadOnly { get { return _sourceFile.IsReadOnly; } } public Guid Id { get { return _sourceFile.Id; } } public string KeyPath { get { return _sourceFile.KeyPath; } } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/VirtualImageFileProvider/VirtualImageFileProvider.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Composite.Core.Linq; using Composite.Data; using Composite.Data.Caching; using Composite.Data.Plugins.DataProvider; using Composite.Data.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Data.DataProviders.VirtualImageFileProvider { [ConfigurationElementType(typeof(NonConfigurableDataProvider))] internal sealed class VirtualImageFileProvider : IDataProvider { public DataProviderContext Context { set { ; } } public IEnumerable<Type> GetSupportedInterfaces() { return new List<Type> { typeof(IImageFile) }; } public IQueryable<T> GetData<T>() where T : class, IData { if (typeof(T) != typeof(IImageFile)) throw new InvalidOperationException( "Unsupported data interface" ); return new VirtualImageFileQueryable<T>( from mediaFile in DataFacade.GetData<IMediaFile>() where mediaFile.MimeType != null && mediaFile.MimeType.StartsWith("image") select new VirtualImageFile(mediaFile) as T); } public T GetData<T>(IDataId dataId) where T : class, IData { throw new NotImplementedException("Unexpected call. This provider does not produce its own data source id's"); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/VirtualImageFileProvider/VirtualImageFileQueryable.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using Composite.Core.Linq; namespace Composite.Plugins.Data.DataProviders.VirtualImageFileProvider { internal interface IVirtualImageFileQueryable { IQueryable Source { get; } } /// <summary> /// Moves the IMediaFile -> IImageFile convertion up in the tree, allowing data providers to handle IMedia queries more effectively /// </summary> internal class VirtualImageFileQueryable<T> : IQueryable<T>, IQueryProvider, IVirtualImageFileQueryable { private readonly IQueryable _source; private readonly Expression _currentExpression; private readonly Expression _initialExpression; public VirtualImageFileQueryable(IQueryable source) { _source = source; _initialExpression = Expression.Constant(this); _currentExpression = _initialExpression; } public VirtualImageFileQueryable(IQueryable source, Expression expression) { _source = source; _currentExpression = expression; } public IEnumerator<T> GetEnumerator() { foreach (var file in (this as IEnumerable)) { yield return (T)file; } } IEnumerator IEnumerable.GetEnumerator() { if (_currentExpression == _initialExpression) { return _source.GetEnumerator(); } var processedExpression = ProcessExpression(_currentExpression); IQueryable<T> queryable = (IQueryable<T>)_source.Provider.CreateQuery(processedExpression); return queryable.GetEnumerator(); } public Expression Expression { get { return _currentExpression ?? _initialExpression; } } public Type ElementType { get { return typeof(T); } } public IQueryProvider Provider { get { return this; } } public IQueryable<S> CreateQuery<S>(Expression expression) { Verify.ArgumentNotNull(expression, "expression"); Verify.ArgumentCondition(typeof(IQueryable<S>).IsAssignableFrom(expression.Type), "expression", "Incorrect expression type"); return new VirtualImageFileQueryable<S>(_source, expression); } public IQueryable CreateQuery(Expression expression) { if (_currentExpression == expression) return this; Type elementType = TypeHelpers.FindElementType(expression); Type multibleSourceQueryableType = typeof(VirtualImageFileQueryable<>).MakeGenericType(new[] { elementType }); return Activator.CreateInstance( multibleSourceQueryableType, new object[] { _source, expression }) as IQueryable; } public TResult Execute<TResult>(Expression expression) { var processedExpression = ProcessExpression(expression); return _source.Provider.Execute<TResult>(processedExpression); } public object Execute(Expression expression) { var processedExpression = ProcessExpression(expression); return _source.Provider.Execute(processedExpression); } private Expression ProcessExpression(Expression expression) { var visitor = new VirtualImageFileQueryableVisitor(); return visitor.Visit(expression); } public IQueryable Source { get { return _source; } } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/VirtualImageFileProvider/VirtualImageFileQueryableVisitor.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Core.Types; using Composite.Data.Types; namespace Composite.Plugins.Data.DataProviders.VirtualImageFileProvider { internal class VirtualImageFileQueryableVisitor: ExpressionVisitor { private static readonly MethodInfo Queryable_Count = typeof(Queryable).GetMethods().Single(x => x.Name == "Count" && x.IsGenericMethod && x.GetParameters().Count() == 1); private static readonly MethodInfo Queryable_Where = StaticReflection.GetGenericMethodInfo(() => System.Linq.Queryable.Where(null, (Expression<Func<int, bool>>)null)); private static readonly MethodInfo Queryable_Take = typeof(Queryable).GetMethods().Single(x => x.Name == "Take" && x.IsGenericMethod && x.GetParameters().Count() == 2); private static readonly MethodInfo Queryable_First = typeof(Queryable).GetMethods().Single(x => x.Name == "First" && x.IsGenericMethod && x.GetParameters().Count() == 1); private static readonly MethodInfo Queryable_FirstOrDefault = typeof(Queryable).GetMethods().Single(x => x.Name == "FirstOrDefault" && x.IsGenericMethod && x.GetParameters().Count() == 1); private static readonly MethodInfo Queryable_Single = typeof(Queryable).GetMethods().Single(x => x.Name == "Single" && x.IsGenericMethod && x.GetParameters().Count() == 1); private static readonly MethodInfo Queryable_SingleOrDefault = typeof(Queryable).GetMethods().Single(x => x.Name == "SingleOrDefault" && x.IsGenericMethod && x.GetParameters().Count() == 1); protected override Expression VisitConstant(ConstantExpression node) { if (node.Value is IVirtualImageFileQueryable) { return Visit((node.Value as IVirtualImageFileQueryable).Source.Expression); } return base.VisitConstant(node); } protected override Expression VisitMethodCall(MethodCallExpression m) { // Trying to convert trees like // IQueryable<IMediaFile>.Select(mediaFile => (new VirtualImageFile(mediaFile) As IImageFile)).METHOD([Condition]) // to // IQueryable<IMediaFile>.METHOD([Condition])[.Select(mediaFile => (new VirtualImageFile(mediaFile) As IImageFile)] if (m.Method.DeclaringType != typeof(Queryable) || !m.Method.IsGenericMethod || m.Method.GetGenericArguments()[0] != typeof(IImageFile)) { return base.VisitMethodCall(m); } var firstArgument = Visit(m.Arguments[0]); if (!(firstArgument is MethodCallExpression && (firstArgument as MethodCallExpression).Method.Name == "Select" && (firstArgument as MethodCallExpression).Method.GetGenericArguments()[0] == typeof(IMediaFile) && (firstArgument as MethodCallExpression).Method.GetGenericArguments()[1] == typeof(IImageFile))) { return base.VisitMethodCall(m); } var mediaFileExpression = (firstArgument as MethodCallExpression).Arguments[0]; var selectorMethod = (firstArgument as MethodCallExpression).Method; var selectorLambdaExpression = (firstArgument as MethodCallExpression).Arguments[1]; // Converting // IQueryable<IMediaFile>.Select(mediaFile => ...).Count([condition]) // IQueryable<IMediaFile>.Select(mediaFile => ...).Any([condition]) // IQueryable<IMediaFile>.Select(mediaFile => ...).All([condition]) // to // IQueryable<IMediaFile>.Count([condition]) // IQueryable<IMediaFile>.Any([condition]) // IQueryable<IMediaFile>.All([condition]) if (m.Method.Name == "Count" || m.Method.Name == "Any" || m.Method.Name == "All") { var mediaFileMethod = m.Method.GetGenericMethodDefinition().MakeGenericMethod(typeof (IMediaFile)); if (m.Arguments.Count == 1) { return base.Visit(Expression.Call(mediaFileMethod, mediaFileExpression)); } var condition = new ParameterTypeReplacer().Visit(m.Arguments[1]); return base.Visit(Expression.Call(mediaFileMethod, mediaFileExpression, condition)); } // Converting // IQueryable<IMediaFile>.Select(mediaFile => ....).Where(CONDITION) // to // IQueryable<IMediaFile>.Where(CONDITION).Select(mediaFile => ....) if (m.Method.Name == "Where" && m.Arguments[1] is UnaryExpression) { var Where_mediaFile = m.Method.GetGenericMethodDefinition().MakeGenericMethod(typeof(IMediaFile)); var convertedCondition = new ParameterTypeReplacer().Visit(m.Arguments[1]); // IQueryable<IMediaFile>.Where(CONDITION) var whereExpression = Expression.Call(Where_mediaFile, mediaFileExpression, convertedCondition); // IQueryable<IMediaFile>.Where(CONDITION).Select(mediaFile => ....) return base.Visit(Expression.Call(selectorMethod, whereExpression, selectorLambdaExpression)); } // Converting // IQueryable<IMediaFile>.Select(mediaFile => ....).Take(count) // to // IQueryable<IMediaFile>.Take(count).Select(mediaFile => ....) if (m.Method.Name == "Take" && m.Arguments[1] is ConstantExpression && (m.Arguments[1] as ConstantExpression).Value is int) { var Take_mediaFile = m.Method.GetGenericMethodDefinition().MakeGenericMethod(typeof(IMediaFile)); // IQueryable<IMediaFile>.Take(count) var takeExpression = Expression.Call(Take_mediaFile, mediaFileExpression, m.Arguments[1]); // IQueryable<IMediaFile>.Take(count).Select(mediaFile => ....) return base.Visit(Expression.Call(selectorMethod, takeExpression, selectorLambdaExpression)); } // Converting // IQueryable<IMediaFile>.Select(mediaFile => ....).First([predicate]) // IQueryable<IMediaFile>.Select(mediaFile => ....).FirstOrDefault([predicate]) // IQueryable<IMediaFile>.Select(mediaFile => ....).Single([predicate]) // IQueryable<IMediaFile>.Select(mediaFile => ....).SingleOrDefault([predicate]) // to // IQueryable<IMediaFile>[.Where(predicate)].Take(1).Select(mediaFile => ....).First() // IQueryable<IMediaFile>[.Where(predicate)].Take(1).Select(mediaFile => ....).FirstOrDefault() // IQueryable<IMediaFile>[.Where(predicate)].Take(2).Select(mediaFile => ....).Single() // IQueryable<IMediaFile>[.Where(predicate)].Take(2).Select(mediaFile => ....).SingleOrDefault() if ((m.Method.Name == "First" || m.Method.Name == "FirstOrDefault" || m.Method.Name == "Single" || m.Method.Name == "SingleOrDefault") && (m.Arguments.Count == 1 || (m.Arguments.Count == 2 && m.Arguments[1] is UnaryExpression))) { var predicate = m.Arguments.Count == 2 ? (m.Arguments[1] as UnaryExpression).Operand : null; // IQueryable<IMediaFile>[.Where(predicate)] var filteredMediaExpression = predicate != null ? Expression.Call(Queryable_Where.MakeGenericMethod(typeof (IMediaFile)), mediaFileExpression, ConvertPredicate(predicate)) : mediaFileExpression; bool isSingleQuery = m.Method.Name == "Single" || m.Method.Name == "SingleOrDefault"; // IQueryable<IMediaFile>[.Where(predicate)].Take(1) var takeExpression = Expression.Call(Queryable_Take.MakeGenericMethod(typeof (IMediaFile)), filteredMediaExpression, Expression.Constant(isSingleQuery ? 2 : 1)); // IQueryable<IMediaFile>[.Where(predicate)].Take(1).Select(mediaFile => ....) // IQueryable<IMediaFile>[.Where(predicate)].Take(2).Select(mediaFile => ....) var selector = Expression.Call(selectorMethod, takeExpression, selectorLambdaExpression); var method = isSingleQuery ? (m.Method.Name == "Single" ? Queryable_Single : Queryable_SingleOrDefault).MakeGenericMethod(typeof(IMediaFile)) : (m.Method.Name == "First" ? Queryable_First : Queryable_FirstOrDefault).MakeGenericMethod(typeof(IMediaFile)); // IQueryable<IMediaFile>[.Where(predicate)].Take(1).Select(mediaFile => ....).First() // IQueryable<IMediaFile>[.Where(predicate)].Take(1).Select(mediaFile => ....).FirstOrDefault() // IQueryable<IMediaFile>[.Where(predicate)].Take(2).Select(mediaFile => ....).Single() // IQueryable<IMediaFile>[.Where(predicate)].Take(2).Select(mediaFile => ....).SingleOrDefault() return base.Visit(Expression.Call(method, selector)); } return base.VisitMethodCall(m); } /// <summary> /// Converts predicates Expression<Func<IImage, bool>> to Expression<Func<IMediaFile, bool>> /// </summary> private static Expression ConvertPredicate(Expression predicate) { return new ParameterTypeReplacer().Visit(predicate); } /// <summary> /// Replace parameters of type <see cref="IImageFile" /> with parameters of type <see cref="IMediaFile" /> /// </summary> private sealed class ParameterTypeReplacer : ExpressionVisitor { readonly Dictionary<ParameterExpression, ParameterExpression> ParameterMap = new Dictionary<ParameterExpression, ParameterExpression>(); protected override Expression VisitParameter(ParameterExpression parameter) { if (parameter.Type == typeof (IImageFile)) { if (!ParameterMap.ContainsKey(parameter)) { ParameterMap.Add(parameter, Expression.Parameter(typeof (IMediaFile), parameter.Name)); } return base.VisitParameter(ParameterMap[parameter]); } return base.VisitParameter(parameter); } protected override Expression VisitLambda<T>(Expression<T> node) { if (typeof (T) != typeof (Func<IImageFile, bool>)) { return base.VisitLambda<T>(node); } return Expression.Lambda<Func<IMediaFile, bool>>(Visit(node.Body), Visit(node.Parameters[0]) as ParameterExpression); } } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/CodeGeneration/DataIdClassGenerator.cs ================================================ using System; using System.CodeDom; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Xml.Linq; using System.Collections.Generic; using Composite.Data; using Composite.Data.DynamicTypes; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider.CodeGeneration { internal sealed class DataIdClassGenerator { private readonly string _className; private readonly DataTypeDescriptor _dataTypeDescriptor; public DataIdClassGenerator(string className, DataTypeDescriptor dataTypeDescriptor) { _className = className; _dataTypeDescriptor = dataTypeDescriptor; } public CodeTypeDeclaration CreateClass() { var declaration = new CodeTypeDeclaration(_className) { IsClass = true, TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed }; declaration.BaseTypes.Add(typeof(IDataId)); declaration.CustomAttributes.Add( new CodeAttributeDeclaration( new CodeTypeReference(typeof(EditorBrowsableAttribute)), new CodeAttributeArgument( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(EditorBrowsableState)), EditorBrowsableState.Never.ToString() ) ) ) ); AddDefaultConstructor(declaration); AddConstructor(declaration); AddEqualsMethod(declaration); AddGetHashCodeMethod(declaration); foreach (DataFieldDescriptor field in _dataTypeDescriptor.PhysicalKeyFields) { AddProperty(declaration, field.Name, field.InstanceType); } return declaration; } internal Dictionary<string, Type> Properties { get { return _dataTypeDescriptor.PhysicalKeyFields.ToDictionary(field => field.Name, field => field.InstanceType); } } private static void AddDefaultConstructor(CodeTypeDeclaration declaration) { var defaultConstructor = new CodeConstructor {Attributes = MemberAttributes.Public | MemberAttributes.Final}; declaration.Members.Add(defaultConstructor); } private void AddConstructor(CodeTypeDeclaration declaration) { var constructor = new CodeConstructor {Attributes = MemberAttributes.Public | MemberAttributes.Final}; constructor.Parameters.Add(new CodeParameterDeclarationExpression( typeof(XElement), "element" )); foreach (var keyField in _dataTypeDescriptor.PhysicalKeyFields) { string propertyFieldName = MakePropertyFieldName(keyField.Name); string attributeVariableName = "attr" + keyField.Name; // CODEGEN: // XAttribute attr{fieldName} = element.Attribute(_{fieldName}XName); constructor.Statements.Add( new CodeVariableDeclarationStatement( typeof(XAttribute), attributeVariableName, new CodeMethodInvokeExpression( new CodeVariableReferenceExpression("element"), "Attribute", new CodeFieldReferenceExpression(null, MakeXNameFieldName(keyField.Name)) ))); // CODEGEN: // if(attr{fieldName} == null) { // throw new InvalidOperationException("Missing '{fieldName}' attribute in a data store file."); // } constructor.Statements.Add(new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression(attributeVariableName), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null) ), new CodeThrowExceptionStatement( new CodeObjectCreateExpression( typeof(InvalidOperationException), new CodePrimitiveExpression( $"Missing '{keyField.Name}' attribute in a data store file." )) ))); // CODEGEN: // _propertyId = (Guid) attrId; constructor.Statements.Add(new CodeAssignStatement( new CodeVariableReferenceExpression(propertyFieldName), new CodeCastExpression( keyField.InstanceType, new CodeVariableReferenceExpression(attributeVariableName) ) )); } declaration.Members.Add(constructor); } private static void AddProperty(CodeTypeDeclaration declaration, string name, Type type) { // CODEGEN: // public Guid Email // { // get { return this._propertyEmail; } // set { this._propertyEmail = value; } // } string propertyFieldName = MakePropertyFieldName(name); declaration.Members.Add(new CodeMemberField(type, propertyFieldName)); var property = new CodeMemberProperty { Name = name, Attributes = MemberAttributes.Public | MemberAttributes.Final, HasSet = true, HasGet = true, Type = new CodeTypeReference(type) }; property.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), propertyFieldName))); property.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), propertyFieldName), new CodeArgumentReferenceExpression("value"))); declaration.Members.Add(property); // CODEGEN: // private static readonly XName _EmailXName = "Email"; var xNameField = new CodeMemberField { Name = MakeXNameFieldName(name), Type = new CodeTypeReference(typeof (XName)), Attributes = MemberAttributes.Static | MemberAttributes.Private, InitExpression = new CodePrimitiveExpression(name) }; declaration.Members.Add(xNameField); } private void AddEqualsMethod(CodeTypeDeclaration declaration) { //Generates code like // public override bool Equals(object obj) // { // return obj != null // && typeof(TestDataId).IsAssignableFrom(obj.GetType()) // && obj.Equals(this.FullPath, (obj as FileSystemFileDataId1).FullPath) && .....; // } const string argumentName = "obj"; var argument = new CodeArgumentReferenceExpression(argumentName); var method = new CodeMemberMethod { Attributes = MemberAttributes.Public | MemberAttributes.Override, Name = nameof(object.Equals), ReturnType = new CodeTypeReference(typeof (bool)) }; method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), argumentName)); Verify.That(_dataTypeDescriptor.KeyPropertyNames.Count > 0, "A dynamic type should have at least one key property"); // CODEGEN: obj != null && typeof(TestDataId).IsAssignableFrom(obj.GetType()) CodeExpression condition = new CodeBinaryOperatorExpression( new CodeBinaryOperatorExpression( argument, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)), CodeBinaryOperatorType.BooleanAnd, new CodeMethodInvokeExpression( new CodeTypeOfExpression(new CodeTypeReference(_className)), nameof(Type.IsAssignableFrom), new CodeMethodInvokeExpression(argument, nameof(GetType)))); foreach (string keyPropertyName in _dataTypeDescriptor.PhysicalKeyFields.Select(f => f.Name)) { string propertyFieldName = MakePropertyFieldName(_dataTypeDescriptor.Fields[keyPropertyName].Name); CodeExpression newCondition = new CodeMethodInvokeExpression( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), propertyFieldName), nameof(object.Equals), new CodeFieldReferenceExpression( new CodeCastExpression(this._className, argument), propertyFieldName)); condition = new CodeBinaryOperatorExpression( condition, CodeBinaryOperatorType.BooleanAnd, newCondition); } method.Statements.Add(new CodeMethodReturnStatement(condition)); declaration.Members.Add(method); } private void AddGetHashCodeMethod(CodeTypeDeclaration declaration) { // Generates code like like // private int _hashcode; // // public override int GetHashCode() // { // if(_hashcode == 0) // { // _hashcode = _fullPath.GetHashCode() ^ ....; // if(_hashcode == 0) // { // _hashcode == -1; // } // // return _hashcode; // } const string HashCodeFieldName = "_hashcode"; declaration.Members.Add(new CodeMemberField(typeof(int), HashCodeFieldName)); var method = new CodeMemberMethod { Attributes = MemberAttributes.Public | MemberAttributes.Override, Name = nameof(GetHashCode), ReturnType = new CodeTypeReference(typeof (int)) }; Verify.That(_dataTypeDescriptor.KeyPropertyNames.Count > 0, "A dynamic type should have at least one key property"); CodeExpression hashCodeExpression = null; foreach (string keyPropertyName in _dataTypeDescriptor.PhysicalKeyFields.Select(f=>f.Name)) { string propertyFieldName = MakePropertyFieldName(_dataTypeDescriptor.Fields[keyPropertyName].Name); CodeExpression hashCodePart = new CodeMethodInvokeExpression( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), propertyFieldName), nameof(GetHashCode)); if (hashCodeExpression == null) { hashCodeExpression = hashCodePart; } else { hashCodeExpression = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(DataProviderHelperBase)), nameof(DataProviderHelperBase.Xor)), hashCodeExpression, hashCodePart); } } // "this.__hashcode" var hashCodeFieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), HashCodeFieldName); method.Statements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression(hashCodeFieldReference, CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(0)), new CodeAssignStatement(hashCodeFieldReference, hashCodeExpression), new CodeConditionStatement( new CodeBinaryOperatorExpression(hashCodeFieldReference, CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(0)), new CodeAssignStatement( hashCodeFieldReference, new CodePrimitiveExpression(-1))))); // "return __hashcode;" method.Statements.Add(new CodeMethodReturnStatement(hashCodeFieldReference)); declaration.Members.Add(method); } private static string MakePropertyFieldName(string name) => $"_property{name}"; private static string MakeXNameFieldName(string name) => $"_{name}XName"; } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/CodeGeneration/DataProviderHelperBase.cs ================================================ using System; using System.Globalization; using System.Linq.Expressions; using System.Reflection; using System.Xml.Linq; using Composite.Core.Collections.Generic; using Composite.Data; using System.Threading; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider.CodeGeneration { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class DataProviderHelperBase : IXmlDataProviderHelper { /// <exclude /> protected ConstructorInfo _idClassConstructor; /// <exclude /> protected ConstructorInfo _wrapperClassConstructor; /// <exclude /> protected Hashtable<Type, Hashtable<string, Delegate>> _selectFunctionCache = new Hashtable<Type, Hashtable<string, Delegate>>(); /// <exclude /> public abstract Type _InterfaceType { get; } /// <exclude /> public abstract Type _DataIdType { get; } /// <exclude /> public Func<XElement, T> CreateSelectFunction<T>(string providerName) where T : IData { Type type = typeof(T); var cache = _selectFunctionCache[typeof(T)]; if (cache == null) { lock (_selectFunctionCache) { cache = _selectFunctionCache[type]; if (cache == null) { cache = new Hashtable<string, Delegate>(); _selectFunctionCache.Add(type, cache); } } } CultureInfo cultureInfo = LocalizationScopeManager.MapByType(type); DataScopeIdentifier dataScopeIdentifier = DataScopeManager.MapByType(type); string cacheKey = cultureInfo + "|" + dataScopeIdentifier.Name; Delegate result = cache[cacheKey]; if (result == null) { lock (this) { result = cache[cacheKey]; if (result == null) { // element => new [WrapperClass](element, new DataSourceId(new [DataIdClass](element), providerName, type, dataScope, localizationScope)), element ParameterExpression parameterExpression = Expression.Parameter(typeof(XElement), "element"); result = Expression.Lambda<Func<XElement, T>>( Expression.New(_wrapperClassConstructor, new Expression[] { parameterExpression, Expression.New(GeneretedClassesMethodCache.DataSourceIdConstructor2, new Expression[] { Expression.New(_idClassConstructor, new Expression[] { parameterExpression }), Expression.Constant(providerName, typeof(string)), Expression.Constant(type, typeof(Type)), Expression.Constant(dataScopeIdentifier, typeof(DataScopeIdentifier)), Expression.Constant(cultureInfo, typeof(CultureInfo)) }) }), new[] { parameterExpression }).Compile(); cache.Add(cacheKey, result); } } } return (Func<XElement, T>)result; } /// <exclude /> public abstract IDataId CreateDataId(XElement xElement); /// <exclude /> public abstract void ValidateDataType(IData data); /// <exclude /> public abstract T CreateNewElement<T>(IData data, out XElement newElement, string elementName, string providerName) where T : IData; /// <summary> /// CodeDom does not support '^' operatior, so this method is used instead /// </summary> public static Int32 Xor(int a, int b) { return a ^ b; } /// <summary> /// Parses a decimal value, sets the correct precision. /// </summary> public static Decimal ParseDecimal(string value, int precision) { if(precision >= 1 || precision <= 4) { // DDZ: check if has to be done in "chinese" style for optimal permormance int comaIndex = value.IndexOf("."); if(comaIndex < 0) { value += "." + new string('0', precision); } else { int zerosToAdd = precision - (value.Length - comaIndex - 1); if(zerosToAdd > 0) { value += new string('0', zerosToAdd); } } } value = value.Replace(".", System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator); return Decimal.Parse(value); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/CodeGeneration/DataProviderHelperClassGenerator.cs ================================================ using System; using System.CodeDom; using System.ComponentModel; using System.Reflection; using System.Xml.Linq; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider.CodeGeneration { /// <summary> /// Creates a implementation of DataProviderHelperBase /// It does NOT depend on the data type to exist /// </summary> internal sealed class DataProviderHelperClassGenerator { private const string WrapperClassConstructorFieldName = "_wrapperClassConstructor"; private const string DataIdClassConstructorFieldName = "_idClassConstructor"; private readonly string _helperClassName; private readonly string _wrapperClassName; private readonly string _dataIdClassName; private string _interfaceName; private readonly DataTypeDescriptor _dataTypeDescriptor; public DataProviderHelperClassGenerator( string helperClassName, string wrapperClassName, string dataIdClassName, DataTypeDescriptor dataTypeDescriptor) { _helperClassName = helperClassName; _wrapperClassName = wrapperClassName; _dataIdClassName = dataIdClassName; _dataTypeDescriptor = dataTypeDescriptor; } public CodeTypeDeclaration CreateClass() { CodeTypeDeclaration declaration = new CodeTypeDeclaration(_helperClassName); declaration.IsClass = true; declaration.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed; declaration.BaseTypes.Add(typeof(DataProviderHelperBase)); declaration.CustomAttributes.Add( new CodeAttributeDeclaration( new CodeTypeReference(typeof(EditorBrowsableAttribute)), new CodeAttributeArgument( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(EditorBrowsableState)), EditorBrowsableState.Never.ToString() ) ) ) ); AddConstructor(declaration); AddInterfaceTypeProperty(declaration); AddDataIdTypeProperty(declaration); AddCreateDataIdFunctionMethod(declaration); AddValidateDataTypeMethod(declaration); AddCreateNewElementMethod(declaration); return declaration; } private void AddConstructor(CodeTypeDeclaration declaration) { CodeConstructor constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public | MemberAttributes.Final; constructor.Statements.Add(new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), WrapperClassConstructorFieldName ), new CodeArrayIndexerExpression( new CodeMethodInvokeExpression( new CodeTypeOfExpression( _wrapperClassName ), "GetConstructors", new CodeExpression[] { new CodeBinaryOperatorExpression( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(BindingFlags)), "Instance" ), CodeBinaryOperatorType.BitwiseOr, new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(BindingFlags)), "Public" ) ) } ), new CodeExpression[] { new CodePrimitiveExpression(0) } ) )); constructor.Statements.Add(new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), DataIdClassConstructorFieldName ), new CodeArrayIndexerExpression( new CodeMethodInvokeExpression( new CodeTypeOfExpression( _dataIdClassName ), "GetConstructors", new CodeExpression[] { new CodeBinaryOperatorExpression( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(BindingFlags)), "Instance" ), CodeBinaryOperatorType.BitwiseOr, new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(BindingFlags)), "Public" ) ) } ), new CodeExpression[] { new CodePrimitiveExpression(1) } ) )); declaration.Members.Add(constructor); } private void AddInterfaceTypeProperty(CodeTypeDeclaration declaration) { CodeMemberProperty property = new CodeMemberProperty(); property.Name = "_InterfaceType"; property.HasGet = true; property.HasSet = false; property.Type = new CodeTypeReference(typeof(Type)); property.Attributes = MemberAttributes.Public | MemberAttributes.Override; property.GetStatements.Add(new CodeMethodReturnStatement( new CodeTypeOfExpression(_dataTypeDescriptor.GetFullInterfaceName()) )); declaration.Members.Add(property); } private void AddDataIdTypeProperty(CodeTypeDeclaration declaration) { CodeMemberProperty property = new CodeMemberProperty(); property.Name = "_DataIdType"; property.HasGet = true; property.HasSet = false; property.Type = new CodeTypeReference(typeof(Type)); property.Attributes = MemberAttributes.Public | MemberAttributes.Override; property.GetStatements.Add(new CodeMethodReturnStatement( new CodeTypeOfExpression(_dataIdClassName) )); declaration.Members.Add(property); } private void AddCreateDataIdFunctionMethod(CodeTypeDeclaration declaration) { CodeMemberMethod method = new CodeMemberMethod(); method.Name = "CreateDataId"; method.ReturnType = new CodeTypeReference(typeof(IDataId)); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(XElement), "xElement")); method.Attributes = MemberAttributes.Public | MemberAttributes.Override; method.Statements.Add(new CodeMethodReturnStatement( new CodeObjectCreateExpression(this._dataIdClassName, new CodeArgumentReferenceExpression("xElement")))); declaration.Members.Add(method); } private static void AddValidateDataTypeMethod(CodeTypeDeclaration declaration) { CodeMemberMethod method = new CodeMemberMethod(); method.Name = "ValidateDataType"; method.ReturnType = new CodeTypeReference(typeof(void)); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IData), "data")); method.Attributes = MemberAttributes.Public | MemberAttributes.Override; declaration.Members.Add(method); } private void AddCreateNewElementMethod(CodeTypeDeclaration declaration) { CodeMemberMethod method = new CodeMemberMethod(); method.Name = "CreateNewElement"; CodeTypeParameter genericParameter = new CodeTypeParameter("T"); genericParameter.HasConstructorConstraint = false; method.TypeParameters.Add(genericParameter); method.ReturnType = new CodeTypeReference(genericParameter); method.ImplementationTypes.Add(typeof(IXmlDataProviderHelper)); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IData), "data")); CodeParameterDeclarationExpression parameter = new CodeParameterDeclarationExpression(typeof(XElement), "newElement"); parameter.Direction = FieldDirection.Out; method.Parameters.Add(parameter); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "elementName")); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "providerName")); method.Attributes = MemberAttributes.Public | MemberAttributes.Override; method.Statements.Add(new CodeVariableDeclarationStatement( InterfaceName, "xmlData")); method.Statements.Add(new CodeTryCatchFinallyStatement( new CodeStatement[] { new CodeAssignStatement( new CodeVariableReferenceExpression("xmlData"), new CodeCastExpression( InterfaceName, new CodeVariableReferenceExpression("data")) ) }, new CodeCatchClause[] { new CodeCatchClause("e", new CodeTypeReference(typeof(Exception)), new CodeStatement[] { new CodeThrowExceptionStatement( new CodeObjectCreateExpression( new CodeTypeReference(typeof(ArgumentException)), new CodeExpression[] { new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(string)), "Format", new CodeExpression[] { new CodePrimitiveExpression("The type ({0}) of the given data parameter does not match the type {1}"), new CodeMethodInvokeExpression( new CodeVariableReferenceExpression("data"), "GetType", new CodeExpression[] {} ), new CodeTypeOfExpression(InterfaceName) } ), new CodeVariableReferenceExpression("e") } ) ) }) } )); const string newElementVariableName = "newElement"; method.Statements.Add(new CodeAssignStatement( new CodeVariableReferenceExpression(newElementVariableName), new CodeObjectCreateExpression( typeof(XElement), new CodeVariableReferenceExpression("elementName") ) )); foreach (DataFieldDescriptor field in _dataTypeDescriptor.Fields) { method.Statements.Add(new CodeCommentStatement(string.Format("Interface Property {0}", field.Name))); CodeMethodInvokeExpression codeExpression = new CodeMethodInvokeExpression( new CodeVariableReferenceExpression(newElementVariableName), "Add", new CodeExpression[] { new CodeObjectCreateExpression( typeof(XAttribute), new CodeExpression[] { new CodePrimitiveExpression(field.Name), new CodePropertyReferenceExpression( new CodeVariableReferenceExpression("xmlData"), field.Name ) } ) } ); if ((field.InstanceType.IsGenericType) && (field.InstanceType.GetGenericTypeDefinition() == typeof(Nullable<>))) { method.Statements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression("xmlData"), field.Name ), "HasValue" ), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(true) ), new CodeStatement[] { new CodeExpressionStatement( codeExpression ) } )); } else if (field.InstanceType == typeof(string)) { method.Statements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression("xmlData"), field.Name ), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null) ), new CodeStatement[] { new CodeExpressionStatement( codeExpression ) } )); } else { method.Statements.Add(codeExpression); } } method.Statements.Add(new CodeCommentStatement("Done with properties")); method.Statements.Add(new CodeVariableDeclarationStatement( typeof(IData), "newData", new CodeObjectCreateExpression( _wrapperClassName, new CodeExpression[] { new CodeVariableReferenceExpression("newElement"), new CodeObjectCreateExpression( typeof(DataSourceId), new CodeExpression[] { new CodeObjectCreateExpression( _dataIdClassName, new CodeVariableReferenceExpression("newElement") ), new CodeVariableReferenceExpression("providerName"), new CodeTypeOfExpression(InterfaceName) } ) } ) )); method.Statements.Add(new CodeMethodReturnStatement( new CodeCastExpression( new CodeTypeReference(genericParameter), new CodeVariableReferenceExpression("newData") ) )); declaration.Members.Add(method); } private string InterfaceFullName { get { return TypeManager.GetRuntimeFullName(_dataTypeDescriptor.TypeManagerTypeName); } } private string InterfaceName { get { if (_interfaceName == null) { _interfaceName = InterfaceFullName; if (_interfaceName.IndexOf(',') >= 0) { _interfaceName = _interfaceName.Remove(_interfaceName.IndexOf(',')); } } return _interfaceName; } } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/CodeGeneration/DataWrapperClassGenerator.cs ================================================ using System; using System.CodeDom; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Xml.Linq; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider.CodeGeneration { internal sealed class DataWrapperClassGenerator { private readonly string _wrapperClassName; private readonly DataTypeDescriptor _dataTypeDescriptor; private string _interfaceName; private const string WrappedElementFieldName = "_element"; private const string DataSourceIdFieldName = "_dataSourceId"; private const string ElementMethodInfoFieldName = "_elementMethodInfo"; public DataWrapperClassGenerator(string wrapperClassName, DataTypeDescriptor dataTypeDescriptor) { _wrapperClassName = wrapperClassName; _dataTypeDescriptor = dataTypeDescriptor; } public CodeTypeDeclaration CreateClass() { var declaration = new CodeTypeDeclaration(_wrapperClassName) { IsClass = true, TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed }; declaration.BaseTypes.Add(InterfaceName); declaration.BaseTypes.Add(typeof(IXElementWrapper)); declaration.CustomAttributes.Add( new CodeAttributeDeclaration( new CodeTypeReference(typeof(EditorBrowsableAttribute)), new CodeAttributeArgument( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(EditorBrowsableState)), EditorBrowsableState.Never.ToString() ) ) ) ); declaration.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(XElement)), WrappedElementFieldName)); declaration.Members.Add(new CodeMemberField(typeof(DataSourceId), DataSourceIdFieldName)); var elementMethodInfoField = new CodeMemberField(typeof(MethodInfo), ElementMethodInfoFieldName) { Attributes = MemberAttributes.Static | MemberAttributes.Private }; declaration.Members.Add(elementMethodInfoField); elementMethodInfoField.InitExpression = new CodeMethodInvokeExpression( new CodeTypeOfExpression(typeof(XElement)), "GetMethod", new CodeExpression[] { new CodePrimitiveExpression("Element") } ); AddConstructor(declaration); AddCommitDataMethod(declaration); AddIDataSourceProperty(declaration); AddInterfaceProperties(declaration); return declaration; } private static void AddConstructor(CodeTypeDeclaration declaration) { const string parameterName = "element"; // CODEGEN: // public .ctor(XElement element, DataSourceId dataSourceId) { ... } var constructor = new CodeConstructor { Attributes = MemberAttributes.Public }; constructor.Parameters.Add(new CodeParameterDeclarationExpression( new CodeTypeReference(typeof(XElement)), parameterName )); constructor.Parameters.Add(new CodeParameterDeclarationExpression( typeof(DataSourceId), "dataSourceId" )); // CODEGEN: // this._element = element; constructor.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), WrappedElementFieldName ), new CodeArgumentReferenceExpression(parameterName) )); // CODEGEN: // this._dataSourceId = dataSourceId; constructor.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), DataSourceIdFieldName ), new CodeArgumentReferenceExpression("dataSourceId") )); declaration.Members.Add(constructor); } private void AddCommitDataMethod(CodeTypeDeclaration declaration) { // CODEGEN: // public void CommitData(XElement wrappedElement) { ... } var method = new CodeMemberMethod { Name = nameof(IXElementWrapper.CommitData), Attributes = MemberAttributes.Public | MemberAttributes.Final, ReturnType = new CodeTypeReference(typeof (void)) }; method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(XElement), "wrappedElement")); // CODEGEN: // this._element = wrappedElement; method.Statements.Add(new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), WrappedElementFieldName ), new CodeVariableReferenceExpression("wrappedElement") )); var statments = new List<CodeStatement>(); foreach (DataFieldDescriptor dataFieldDescriptor in _dataTypeDescriptor.Fields) { string fieldName = CreateNullableFieldName(dataFieldDescriptor); var newStatements = AddCommitDataMethodHelper( "attribute", new CodeFieldReferenceExpression(null, CreateXNameFieldName(dataFieldDescriptor)), new CodePropertyReferenceExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), fieldName ), nameof(ExtendedNullable<string>.Value) )); statments.Add(AddCommitDataMethodFinalHelper(dataFieldDescriptor, newStatements)); } method.Statements.AddRange(statments.ToArray()); declaration.Members.Add(method); } private static CodeStatement AddCommitDataMethodFinalHelper(DataFieldDescriptor dataFieldDescriptor, IEnumerable<CodeStatement> statements) { // CODEGEN: // if (this._isSet_email && this._emailNullable != null) { // [statements] // _isSet_email = false; // } string fieldName = CreateNullableFieldName(dataFieldDescriptor); // this._isSet_email var fieldIsSetFieldReference = new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), IsSetFieldName(dataFieldDescriptor) ); // this._emailNullable != null var expression2 = new CodeBinaryOperatorExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), fieldName ), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null) ); return new CodeConditionStatement( new CodeBinaryOperatorExpression( fieldIsSetFieldReference, CodeBinaryOperatorType.BooleanAnd, expression2), statements.Concat(new [] { // CODEGEN: // this._isSetEmail = false; new CodeAssignStatement( fieldIsSetFieldReference, new CodePrimitiveExpression(false) )}).ToArray() ); } private static CodeStatement[] AddCommitDataMethodHelper(string elementVariableName, CodeExpression attributeNameExpression, CodeExpression valueExpression) { var elementVariable = new CodeVariableReferenceExpression(elementVariableName); return new CodeStatement[] { new CodeVariableDeclarationStatement( typeof(XAttribute), elementVariableName, new CodeMethodInvokeExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), WrappedElementFieldName ), "Attribute", attributeNameExpression) ), new CodeConditionStatement( new CodeBinaryOperatorExpression( valueExpression, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null) ), new CodeStatement[] { new CodeConditionStatement( new CodeBinaryOperatorExpression( elementVariable, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null) ), new CodeStatement[] { new CodeAssignStatement( elementVariable, new CodeObjectCreateExpression( typeof(XAttribute), attributeNameExpression, valueExpression ) ), new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), WrappedElementFieldName ), "Add", elementVariable) ) }, new CodeStatement[] { new CodeExpressionStatement( new CodeMethodInvokeExpression( elementVariable, "SetValue", valueExpression) ), } ) }, // CODEGEN: // else if (attribute != null) // { // attribute.Remove(); // } new CodeStatement[] { new CodeConditionStatement( new CodeBinaryOperatorExpression( elementVariable, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null) ), new CodeExpressionStatement( new CodeMethodInvokeExpression( elementVariable, "Remove" ) ) ) } ) }; } private static void AddIDataSourceProperty(CodeTypeDeclaration declaration) { PropertyInfo info = typeof(IData).GetProperty("DataSourceId"); var property = new CodeMemberProperty { Attributes = MemberAttributes.Public | MemberAttributes.Final, Name = info.Name, HasGet = true, HasSet = false, Type = new CodeTypeReference(info.PropertyType) }; property.GetStatements.Add( new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), "_dataSourceId" ) )); declaration.Members.Add(property); } private void AddInterfaceProperties(CodeTypeDeclaration declaration) { foreach (DataFieldDescriptor dataFieldDescriptor in _dataTypeDescriptor.Fields) { string nullableFieldName = CreateNullableFieldName(dataFieldDescriptor); var nullableFieldReference = new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), nullableFieldName ); var nullableFieldValueReference = new CodePropertyReferenceExpression( nullableFieldReference, nameof(ExtendedNullable<string>.Value) ); // CODEGEN: // private ExtendedNullable<string> _emailNullable; var nullableType = new CodeTypeReference( typeof(ExtendedNullable<>).FullName, new[] { new CodeTypeReference(dataFieldDescriptor.InstanceType) } ); declaration.Members.Add(new CodeMemberField { Name = nullableFieldName, Type = nullableType }); // CODEGEN: // private bool _isSet_email; declaration.Members.Add(new CodeMemberField { Name = IsSetFieldName(dataFieldDescriptor), Type = new CodeTypeReference(typeof(bool)) }); // CODEGEN: // private static XName _pointsXName = "Points"; var xNameField = new CodeMemberField { Name = CreateXNameFieldName(dataFieldDescriptor), Type = new CodeTypeReference(typeof(XName)), Attributes = MemberAttributes.Static | MemberAttributes.Private, InitExpression = new CodePrimitiveExpression(dataFieldDescriptor.Name) }; declaration.Members.Add(xNameField); // CODEGEN: // public string Email { get {...} set { ...} } var property = new CodeMemberProperty { Attributes = MemberAttributes.Public | MemberAttributes.Final, Name = dataFieldDescriptor.Name, HasGet = true, HasSet = true, Type = new CodeTypeReference(dataFieldDescriptor.InstanceType) }; // CODEGEN: // if(this._emailNullable != null) { // return this._emailNullable.Value; // } property.GetStatements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( nullableFieldReference, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null) ), new CodeMethodReturnStatement( nullableFieldValueReference ) )); // XAttribute attribute = _element.Attribute(_{fieldName}XName); property.GetStatements.Add( new CodeVariableDeclarationStatement( typeof (XAttribute), "attribute", new CodeMethodInvokeExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), WrappedElementFieldName ), "Attribute", new CodeFieldReferenceExpression(null, CreateXNameFieldName(dataFieldDescriptor)) ))); // CODEGEN: // if (attribute == null) { // return null; // } // // or // // if (attribute == null) { // throw new InvalidOperationException("The element attribute 'Email' is missing from the xml file"); // } CodeStatement noAttributeReturnStatement; if (dataFieldDescriptor.InstanceType == typeof(string) || (dataFieldDescriptor.InstanceType.IsGenericType && dataFieldDescriptor.InstanceType.GetGenericTypeDefinition() == typeof(Nullable<>))) { noAttributeReturnStatement = new CodeMethodReturnStatement(new CodePrimitiveExpression(null)); } else { noAttributeReturnStatement = new CodeThrowExceptionStatement( new CodeObjectCreateExpression( typeof(InvalidOperationException), new CodePrimitiveExpression( $"The element attribute '{dataFieldDescriptor.Name}' is missing from the xml file" )) ); } property.GetStatements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("attribute"), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null) ), noAttributeReturnStatement )); CodeExpression valueExpression; if (!dataFieldDescriptor.StoreType.IsDecimal) { // ({Type}) attribute; valueExpression = new CodeCastExpression(dataFieldDescriptor.InstanceType, new CodeVariableReferenceExpression("attribute")); } else { // FixDecimal(attribute.Value, {decimal precision}); valueExpression = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeTypeReferenceExpression(typeof(DataProviderHelperBase)), nameof(DataProviderHelperBase.ParseDecimal)), new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("attribute"), "Value"), new CodePrimitiveExpression(dataFieldDescriptor.StoreType.NumericScale) ); } // CODEGEN: // Type value = ({Type}) attribute; property.GetStatements.Add( new CodeVariableDeclarationStatement( dataFieldDescriptor.InstanceType, "value", valueExpression)); // CODEGEN: // this._emailNullable = value; // Using the implicit cast to ExtendedEnumerable<> property.GetStatements.Add( new CodeAssignStatement( nullableFieldReference, new CodeVariableReferenceExpression("value"))); // CODEGEN: // return value; property.GetStatements.Add( new CodeMethodReturnStatement( new CodeVariableReferenceExpression("value"))); if (!dataFieldDescriptor.IsReadOnly) { // CODEGEN: // if(this.[fieldName] == null) { // this.[fieldName] = value; // } // else // { // // this._emailNullable.Value = value; // } property.SetStatements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( nullableFieldReference, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null) ), new CodeStatement[] { new CodeAssignStatement( nullableFieldReference, new CodePropertySetValueReferenceExpression()) }, new CodeStatement[] { new CodeAssignStatement( nullableFieldValueReference, new CodePropertySetValueReferenceExpression() ) })); // CODEGEN: // this._isSet_email = true; property.SetStatements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), IsSetFieldName(dataFieldDescriptor) ), new CodePrimitiveExpression(true) )); } declaration.Members.Add(property); } } private static string CreateNullableFieldName(DataFieldDescriptor dataFieldDescriptor) { return $"_{dataFieldDescriptor.Name.ToLowerInvariant()}Nullable"; } private static string CreateXNameFieldName(DataFieldDescriptor dataFieldDescriptor) { return $"_{dataFieldDescriptor.Name.ToLowerInvariant()}XName"; } private static string IsSetFieldName(DataFieldDescriptor dataFieldDescriptor) { return $"_isSet_{dataFieldDescriptor.Name.ToLowerInvariant()}"; } private string InterfaceFullName => TypeManager.GetRuntimeFullName(_dataTypeDescriptor.TypeManagerTypeName); private string InterfaceName { get { if (_interfaceName == null) { _interfaceName = InterfaceFullName; int commaOffset = _interfaceName.IndexOf(','); if (commaOffset >= 0) { _interfaceName = _interfaceName.Remove(commaOffset); } } return _interfaceName; } } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/CodeGeneration/GeneretedClassesMethodCache.cs ================================================ using System; using System.Linq; using System.Xml.Linq; using System.Reflection; using System.Collections.Generic; using Composite.Data; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider.CodeGeneration { internal static class GeneretedClassesMethodCache { private static MethodInfo _xElementElementMethod = typeof(XElement).GetMethod("Element"); private static MethodInfo _xElementAttributeMethod = typeof(XElement).GetMethod("Attribute"); private static ConstructorInfo _dataSourceIdConstructor = typeof(DataSourceId).GetConstructors(BindingFlags.Instance | BindingFlags.Public)[0]; private static ConstructorInfo _dataSourceIdConstructor2 = typeof(DataSourceId).GetConstructors(BindingFlags.Instance | BindingFlags.Public)[1]; private static MethodInfo _guidCompareToMethod = null; private static Dictionary<Type, MethodInfo> _explicitCastXElementMethodInfoCache = new Dictionary<Type, MethodInfo>(); private static Dictionary<Type, MethodInfo> _explicitCastXAttributeMethodInfoCache = new Dictionary<Type, MethodInfo>(); public static MethodInfo XElementElementMethod { get { return _xElementElementMethod; } } public static MethodInfo XElementAttributeMethod { get { return _xElementAttributeMethod; } } public static ConstructorInfo DataSourceIdConstructor { get { return _dataSourceIdConstructor; } } public static ConstructorInfo DataSourceIdConstructor2 { get { return _dataSourceIdConstructor2; } } public static MethodInfo GuidCompareTo { get { if (null == _guidCompareToMethod) { _guidCompareToMethod = (from mi in typeof(Guid).GetMethods() where mi.Name == "CompareTo" && mi.GetParameters()[0].ParameterType == typeof(Guid) select mi).First(); } return _guidCompareToMethod; } } public static MethodInfo GetExplicitCastXElement(Type type) { if (null == type) throw new ArgumentNullException("type"); MethodInfo methodInfo; if (false == _explicitCastXElementMethodInfoCache.TryGetValue(type, out methodInfo)) { methodInfo = (from member in typeof(XElement).GetMethods() where member.Name == "op_Explicit" && member.ReturnType == type select member).FirstOrDefault(); if (null == methodInfo) { if (null == methodInfo) throw new InvalidOperationException(string.Format("No explicit cast from {0} to {1} exists", typeof(XElement), type)); } _explicitCastXElementMethodInfoCache.Add(type, methodInfo); } return methodInfo; } public static MethodInfo GetExplicitCastXAttribute(Type type) { if (null == type) throw new ArgumentNullException("type"); MethodInfo methodInfo; if (false == _explicitCastXAttributeMethodInfoCache.TryGetValue(type, out methodInfo)) { methodInfo = (from member in typeof(XAttribute).GetMethods() where member.Name == "op_Explicit" && member.ReturnType == type select member).FirstOrDefault(); if (null == methodInfo) { if (null == methodInfo) throw new InvalidOperationException(string.Format("No explicit cast from {0} to {1} exists", typeof(XElement), type)); } _explicitCastXAttributeMethodInfoCache.Add(type, methodInfo); } return methodInfo; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/CodeGeneration/XmlDataProviderCodeBuilder.cs ================================================ using System; using System.CodeDom; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Xml; using System.Xml.Linq; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.Serialization.CodeGeneration; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.ProcessControlled; using Composite.Plugins.Data.DataProviders.XmlDataProvider.Foundation; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider.CodeGeneration { internal class XmlDataProviderCodeBuilder { private readonly CodeGenerationBuilder _codeGenerationBuilder; private readonly string _namespaceName; public XmlDataProviderCodeBuilder(string providerName, CodeGenerationBuilder codeGenerationBuilder) { _codeGenerationBuilder = codeGenerationBuilder; _namespaceName = NamesCreator.MakeNamespaceName(providerName); AddCodeNamespaces(); } internal void AddDataType(DataTypeDescriptor dataTypeDescriptor) { Type interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor); if (interfaceType == null) return; XmlProviderCodeGenerator codeGenerator = new XmlProviderCodeGenerator(dataTypeDescriptor, _namespaceName); IEnumerable<CodeTypeDeclaration> codeTypeDeclarations = codeGenerator.CreateCodeDOMs(); codeTypeDeclarations.ForEach(f => _codeGenerationBuilder.AddType(_namespaceName, f)); // Property serializer for entity tokens and more var keyPropertiesDictionary = new Dictionary<string, Type>(); var keyPropertiesList = new List<Tuple<string, Type>>(); foreach (var keyField in dataTypeDescriptor.PhysicalKeyFields) { Verify.That(!keyPropertiesDictionary.ContainsKey(keyField.Name), "Key field with name '{0}' already present. Data type: {1}. Check for multiple [KeyPropertyName(...)] attributes.", keyField.Name, dataTypeDescriptor.Namespace + "." + dataTypeDescriptor.Name); keyPropertiesDictionary.Add(keyField.Name, keyField.InstanceType); keyPropertiesList.Add(new Tuple<string, Type>(keyField.Name, keyField.InstanceType)); } PropertySerializerTypeCodeGenerator.AddPropertySerializerTypeCode(_codeGenerationBuilder, codeGenerator.DataIdClassFullName, keyPropertiesList); _codeGenerationBuilder.AddReference(interfaceType.Assembly); } private void AddCodeNamespaces() { _codeGenerationBuilder.AddReference(typeof(XElement).Assembly); _codeGenerationBuilder.AddReference(typeof(Exception).Assembly); _codeGenerationBuilder.AddReference(typeof(IQueryable).Assembly); _codeGenerationBuilder.AddReference(typeof(XName).Assembly); _codeGenerationBuilder.AddReference(typeof(XmlReader).Assembly); _codeGenerationBuilder.AddReference(typeof(EditorBrowsableAttribute).Assembly); _codeGenerationBuilder.AddReference(typeof(ExpressionCreator).Assembly); _codeGenerationBuilder.AddReference(typeof(ExtendedNullable<>).Assembly); _codeGenerationBuilder.AddReference(typeof(DataSourceId).Assembly); _codeGenerationBuilder.AddReference(typeof(IProcessControlled).Assembly); _codeGenerationBuilder.AddReference(typeof(XmlDataProvider).Assembly); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/CodeGeneration/XmlDataProviderCodeProvider.cs ================================================ using System.ComponentModel; using Composite.Core.Types; using Composite.Data.Foundation.PluginFacades; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider.CodeGeneration { /// <summary> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] internal class XmlDataProviderCodeProvider : ICodeProvider { public string ProviderName { get; private set; } public XmlDataProviderCodeProvider(string providerName) { ProviderName = providerName; } public void GetCodeToCompile(CodeGenerationBuilder builder) { XmlDataProvider xmlDataProvider = (XmlDataProvider)DataProviderPluginFacade.GetDataProvider(ProviderName); xmlDataProvider.BuildAllCode(builder); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/CodeGeneration/XmlProviderCodeGenerator.cs ================================================ using System.CodeDom; using System.Collections.Generic; using System.ComponentModel; using Composite.Data.DynamicTypes; using Composite.Plugins.Data.DataProviders.XmlDataProvider.Foundation; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider.CodeGeneration { /// <summary> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] internal class XmlProviderCodeGenerator { private readonly DataTypeDescriptor _dataTypeDescriptor; public string DataProviderHelperClassFullName { get; private set; } public string WrapperClassFullName { get; private set; } public string DataIdClassFullName { get; private set; } public XmlProviderCodeGenerator(DataTypeDescriptor dataTypeDescriptor, string namespaceName) { _dataTypeDescriptor = dataTypeDescriptor; DataProviderHelperClassFullName = namespaceName + "." + NamesCreator.MakeDataProviderHelperClassName(dataTypeDescriptor); WrapperClassFullName = namespaceName + "." + NamesCreator.MakeWrapperClassName(dataTypeDescriptor); DataIdClassFullName = namespaceName + "." + NamesCreator.MakeDataIdClassName(dataTypeDescriptor); } public IEnumerable<CodeTypeDeclaration> CreateCodeDOMs() { string dataProviderHelperClassName = NamesCreator.MakeDataProviderHelperClassName(_dataTypeDescriptor); string wrapperClassName = NamesCreator.MakeWrapperClassName(_dataTypeDescriptor); string dataIdClassName = NamesCreator.MakeDataIdClassName(_dataTypeDescriptor); DataProviderHelperClassGenerator classGenerator = new DataProviderHelperClassGenerator( dataProviderHelperClassName, wrapperClassName, dataIdClassName, _dataTypeDescriptor ); CodeTypeDeclaration dataHelperClassCodeTypeDeclaration = classGenerator.CreateClass(); yield return dataHelperClassCodeTypeDeclaration; DataIdClassGenerator dataIdClassGenerator = new DataIdClassGenerator(dataIdClassName, _dataTypeDescriptor); CodeTypeDeclaration dataIdClassCodeTypeDeclaration = dataIdClassGenerator.CreateClass(); yield return dataIdClassCodeTypeDeclaration; DataWrapperClassGenerator dataWrapperClassGenerator = new DataWrapperClassGenerator(wrapperClassName, _dataTypeDescriptor); CodeTypeDeclaration dataWrapperClassCodeTypeDeclaration = dataWrapperClassGenerator.CreateClass(); yield return dataWrapperClassCodeTypeDeclaration; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/Foundation/FileRecord.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Xml.Linq; using Composite.Core.Collections.Generic; using Composite.Data; using Composite.Data.Caching; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider.Foundation { internal class FileRecord { internal FileRecord() { _randomTempFileKey = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); } private readonly string _randomTempFileKey; public string FilePath; public string ElementName; public RecordSet RecordSet; public ICollection<XElement> ReadOnlyElementsList; public DateTime LastModified; public DateTime FileModificationDate; public CachedTable CachedTable; public bool Dirty = false; // Determines whether the inner XElement list is dirty public string TempFilePath { get { return string.Format("{0}.{1}.tmp", FilePath, _randomTempFileKey); } } } internal class RecordSet { public Hashtable<IDataId, XElement> Index; } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/Foundation/InterfaceConfigurationManipulator.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using Composite.Core; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Plugins.Data.DataProviders.Common; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider.Foundation { internal static class InterfaceConfigurationManipulator { private static readonly string LogTitle = typeof(InterfaceConfigurationManipulator).Name; /// <summary> /// Create an invariant store /// </summary> /// <param name="providerName"></param> /// <param name="dataTypeDescriptor"></param> public static void AddNew(string providerName, DataTypeDescriptor dataTypeDescriptor) { var xmlDataProviderConfiguration = new XmlDataProviderConfiguration(providerName); string interfaceType = dataTypeDescriptor.TypeManagerTypeName; if (interfaceType != null) { object key = xmlDataProviderConfiguration.Section.Interfaces.GetKey(dataTypeDescriptor); if (key != null) { Log.LogWarning(LogTitle, "Configuration file '{0}' already contains an interface type '{1} 'with id '{2}'. " + "Possibly there are multiple AppDomain-s running.", xmlDataProviderConfiguration.ConfigurationFilePath, dataTypeDescriptor, dataTypeDescriptor.DataTypeId); return; } } XmlProviderInterfaceConfigurationElement configurationElement = BuildXmlProviderInterfaceConfigurationElement(dataTypeDescriptor); XmlDataProviderStoreManipulator.CreateStore(providerName, configurationElement); xmlDataProviderConfiguration.Section.Interfaces.Add(configurationElement); xmlDataProviderConfiguration.Save(); } public static XmlProviderInterfaceConfigurationElement Change(UpdateDataTypeDescriptor updateDataTypeDescriptor) { DataTypeChangeDescriptor changeDescriptor = updateDataTypeDescriptor.CreateDataTypeChangeDescriptor(); var xmlDataProviderConfiguration = new XmlDataProviderConfiguration(updateDataTypeDescriptor.ProviderName); object key = xmlDataProviderConfiguration.Section.Interfaces.GetKey(changeDescriptor.OriginalType); var oldConfigurationElement = xmlDataProviderConfiguration.Section.Interfaces.Get(key); var newConfigurationElement = BuildXmlProviderInterfaceConfigurationElement(changeDescriptor.AlteredType, oldConfigurationElement); XmlDataProviderStoreManipulator.AlterStore(updateDataTypeDescriptor, oldConfigurationElement, newConfigurationElement); xmlDataProviderConfiguration.Section.Interfaces.Remove(key); xmlDataProviderConfiguration.Section.Interfaces.Add(newConfigurationElement); xmlDataProviderConfiguration.Save(); return newConfigurationElement; } public static void Remove(string providerName, DataTypeDescriptor dataTypeDescriptor) { XmlDataProviderConfiguration xmlDataProviderConfiguration = new XmlDataProviderConfiguration(providerName); object key = xmlDataProviderConfiguration.Section.Interfaces.GetKey(dataTypeDescriptor); if (key != null) { XmlProviderInterfaceConfigurationElement element = xmlDataProviderConfiguration.Section.Interfaces.Get(key); xmlDataProviderConfiguration.Section.Interfaces.Remove(key); xmlDataProviderConfiguration.Save(); XmlDataProviderStoreManipulator.DropStore(providerName, element); } } public static void AddLocale(string providerName, IEnumerable<Type> interfaceTypes, CultureInfo cultureInfo) { XmlDataProviderConfiguration xmlDataProviderConfiguration = new XmlDataProviderConfiguration(providerName); foreach (Type type in interfaceTypes) { if (!DataLocalizationFacade.IsLocalized(type)) { continue; } var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(type); object key = xmlDataProviderConfiguration.Section.Interfaces.GetKey(dataTypeDescriptor); var oldConfigurationElement = xmlDataProviderConfiguration.Section.Interfaces.Get(key); var newConfigurationElement = BuildXmlProviderInterfaceConfigurationElement(dataTypeDescriptor, cultureInfo, null, oldConfigurationElement); xmlDataProviderConfiguration.Section.Interfaces.Remove(key); xmlDataProviderConfiguration.Section.Interfaces.Add(newConfigurationElement); foreach (Dictionary<string, DataScopeConfigurationElement> filesByCulture in newConfigurationElement.DataScopes.Values) { XmlDataProviderStoreManipulator.CreateStore(providerName, filesByCulture[cultureInfo.Name]); } } xmlDataProviderConfiguration.Save(); } public static void RemoveLocale(string providerName, IEnumerable<Type> interfaceTypes, CultureInfo cultureInfo) { XmlDataProviderConfiguration xmlDataProviderConfiguration = new XmlDataProviderConfiguration(providerName); foreach (Type type in interfaceTypes) { if (DataLocalizationFacade.IsLocalizable(type)) { DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(type); object key = xmlDataProviderConfiguration.Section.Interfaces.GetKey(dataTypeDescriptor); bool configurationChanged = false; var oldConfigurationElement = xmlDataProviderConfiguration.Section.Interfaces.Get(key); foreach (Dictionary<string, DataScopeConfigurationElement> scopesByLanguage in oldConfigurationElement.DataScopes.Values) { if (scopesByLanguage.ContainsKey(cultureInfo.Name)) { XmlDataProviderStoreManipulator.DropStore(providerName, scopesByLanguage[cultureInfo.Name]); configurationChanged = true; } } if (configurationChanged) { var newConfigurationElement = BuildXmlProviderInterfaceConfigurationElement(dataTypeDescriptor, null, cultureInfo, oldConfigurationElement); xmlDataProviderConfiguration.Section.Interfaces.Remove(key); xmlDataProviderConfiguration.Section.Interfaces.Add(newConfigurationElement); } } } xmlDataProviderConfiguration.Save(); } private static XmlProviderInterfaceConfigurationElement BuildXmlProviderInterfaceConfigurationElement( DataTypeDescriptor dataTypeDescriptor, XmlProviderInterfaceConfigurationElement existingElement = null) { return BuildXmlProviderInterfaceConfigurationElement(dataTypeDescriptor, null, null, existingElement); } private static XmlProviderInterfaceConfigurationElement BuildXmlProviderInterfaceConfigurationElement( DataTypeDescriptor dataTypeDescriptor, CultureInfo addedCultureInfo, CultureInfo removedCultureInfo, XmlProviderInterfaceConfigurationElement existingElement) { var configurationElement = new XmlProviderInterfaceConfigurationElement { DataTypeId = dataTypeDescriptor.DataTypeId, IsGeneratedType = dataTypeDescriptor.IsCodeGenerated }; bool isLocalized = dataTypeDescriptor.Localizeable; foreach (DataScopeIdentifier dataScopeIdentifier in dataTypeDescriptor.DataScopes) { if (!isLocalized) { configurationElement.ConfigurationStores.Add(new DataScopeConfigurationElement { DataScope = dataScopeIdentifier.Name, CultureName = CultureInfo.InvariantCulture.Name, Filename = NamesCreator.MakeFileName(dataTypeDescriptor, dataScopeIdentifier, CultureInfo.InvariantCulture.Name), ElementName = NamesCreator.MakeElementName(dataTypeDescriptor) }); } if (isLocalized) { List<string> localizationNames = DataLocalizationFacade.ActiveLocalizationNames.ToList(); foreach (string cultureName in localizationNames) { if (removedCultureInfo != null && removedCultureInfo.Name == cultureName) continue; string existingFileName = null; string existingElementName = null; if (existingElement != null) { foreach (DataScopeConfigurationElement store in existingElement.ConfigurationStores) { if (store.DataScope == dataScopeIdentifier.Name && store.CultureName == cultureName) { existingFileName = store.Filename; existingElementName = store.ElementName; break; } } } configurationElement.ConfigurationStores.Add(new DataScopeConfigurationElement { DataScope = dataScopeIdentifier.Name, CultureName = cultureName, Filename = existingFileName ?? NamesCreator.MakeFileName(dataTypeDescriptor, dataScopeIdentifier, cultureName), ElementName = existingElementName ?? NamesCreator.MakeElementName(dataTypeDescriptor) }); } if (addedCultureInfo != null && !localizationNames.Contains(addedCultureInfo.Name)) { configurationElement.ConfigurationStores.Add(new DataScopeConfigurationElement { DataScope = dataScopeIdentifier.Name, CultureName = addedCultureInfo.Name, Filename = NamesCreator.MakeFileName(dataTypeDescriptor, dataScopeIdentifier, addedCultureInfo.Name), ElementName = NamesCreator.MakeElementName(dataTypeDescriptor) }); } } } configurationElement.ConfigurationDataIdProperties = new SimpleNameTypeConfigurationElementCollection(); foreach (DataFieldDescriptor field in dataTypeDescriptor.PhysicalKeyFields) { configurationElement.ConfigurationDataIdProperties.Add(field.Name, field.InstanceType); } configurationElement.ConfigurationPropertyNameMappings = new PropertyNameMappingConfigurationElementCollection(); configurationElement.ConfigurationPropertyInitializers = new SimpleNameTypeConfigurationElementCollection(); return configurationElement; } private sealed class XmlDataProviderConfiguration { readonly string _configurationFilePath; readonly C1Configuration _configuration; public XmlDataProviderConfiguration(string providerName) { _configurationFilePath = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.ConfigurationDirectory), string.Format("{0}.config", providerName)); _configuration = new C1Configuration(_configurationFilePath); this.Section = _configuration.GetSection(XmlDataProviderConfigurationSection.SectionName) as XmlDataProviderConfigurationSection; if (this.Section == null) { this.Section = new XmlDataProviderConfigurationSection(); _configuration.Sections.Add(XmlDataProviderConfigurationSection.SectionName, this.Section); } } public XmlDataProviderConfigurationSection Section { get; private set; } public string ConfigurationFilePath { get { return _configurationFilePath; } } public void Save() { _configuration.Save(); } } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/Foundation/NamesCreator.cs ================================================ using System; using Composite.Core.Extensions; using Composite.Data; using Composite.Data.DynamicTypes; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider.Foundation { internal static class NamesCreator { internal static string MakeFileName(DataTypeDescriptor dataTypeDescriptor, DataScopeIdentifier dataScopeIdentifier, string cultureName) { string typeFullName = StringExtensionMethods.CreateNamespace(dataTypeDescriptor.Namespace, dataTypeDescriptor.Name, '.'); string publicationScopePart = ""; switch (dataScopeIdentifier.Name) { case DataScopeIdentifier.PublicName: break; case DataScopeIdentifier.AdministratedName: publicationScopePart = "_" + PublicationScope.Unpublished; break; default: throw new InvalidOperationException($"Unsupported data scope identifier: '{dataScopeIdentifier.Name}'"); } string cultureNamePart = ""; if (cultureName != "") { cultureNamePart = "_" + cultureName; } return typeFullName + publicationScopePart + cultureNamePart + ".xml"; } internal static string MakeElementName(DataTypeDescriptor dataTypeDescriptor) { string name = dataTypeDescriptor.Name; if (name.StartsWith("I")) { name = name.Remove(0, 1); name = $"{name.Substring(0, 1).ToUpper()}{name.Remove(0, 1)}Elements"; } return name; } internal static string MakeWrapperClassName(DataTypeDescriptor dataTypeDescriptor) { return $"{MakeNiceTypeFullName(dataTypeDescriptor)}Wrapper"; } internal static string MakeDataIdClassName(DataTypeDescriptor dataTypeDescriptor) { return $"{MakeNiceTypeFullName(dataTypeDescriptor)}DataId"; } internal static string MakeDataProviderHelperClassName(DataTypeDescriptor dataTypeDescriptor) { return $"{MakeNiceTypeFullName(dataTypeDescriptor)}DataProviderHelper"; } internal static string MakeNamespaceName(string providerName) { return "CompositeGenerated." + providerName; } private static string MakeNiceTypeFullName(DataTypeDescriptor dataTypeDescriptor) { return dataTypeDescriptor.GetFullInterfaceName().Replace('.', '_').Replace('+', '_'); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/Foundation/TransactionRollbackHandler.cs ================================================ using System.Threading; using System.Transactions; using Composite.Core.Logging; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider.Foundation { internal class TransactionRollbackHandler : IEnlistmentNotification { private ThreadStart _onRollback; public TransactionRollbackHandler(ThreadStart onRollback) { _onRollback = onRollback; } public void Commit(Enlistment enlistment) { enlistment.Done(); } public void InDoubt(Enlistment enlistment) { enlistment.Done(); } public void Prepare(PreparingEnlistment preparingEnlistment) { preparingEnlistment.Prepared(); } public void Rollback(Enlistment enlistment) { _onRollback(); enlistment.Done(); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/Foundation/ValidationHelper.cs ================================================ using System; using System.Collections.Generic; using System.Reflection; using Composite.Data; using Composite.Data.Caching; using Composite.Data.DynamicTypes; using Composite.Core.Logging; using Composite.Core.Extensions; using Composite.Core.Types; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider.Foundation { internal static class ValidationHelper { private class ValidationInfo { public List<Pair<PropertyInfo, int>> MaxStringLengthByField; } private static readonly Cache<Type, ValidationInfo> _validationInfoCache = new Cache<Type, ValidationInfo>("XmlDataProvider.ValidationInfo", 200); private static readonly object[] EmptyParameterList = new object[0]; public static void Validate(IData datum) { Type type = datum.DataSourceId.InterfaceType; ValidationInfo info = _validationInfoCache.Get(type); if(info == null) { lock(_validationInfoCache) { info = _validationInfoCache.Get(type); if(info == null) { info = new ValidationInfo { MaxStringLengthByField = new List<Pair<PropertyInfo, int>>() }; foreach(PropertyInfo propertyInfo in type.GetProperties()) { if(propertyInfo.PropertyType != typeof(string)) continue; object[] attributes = propertyInfo.GetCustomAttributes(typeof(StoreFieldTypeAttribute), false); if(attributes.Length > 1) { LoggingService.LogError(typeof(ValidationHelper).Name, "Encoutered more than one '{0}' attrubute".FormatWith(typeof(StoreFieldTypeAttribute).FullName)); continue; } if (attributes.Length == 0) continue; var storeFieldTypeAttr = attributes[0] as StoreFieldTypeAttribute; StoreFieldType storeFieldType = storeFieldTypeAttr.StoreFieldType; if (storeFieldType.IsLargeString || !storeFieldType.IsString) { continue; } info.MaxStringLengthByField.Add(new Pair<PropertyInfo, int>(propertyInfo, storeFieldType.MaximumLength)); } _validationInfoCache.Add(type, info); } } } foreach(Pair<PropertyInfo, int> pair in info.MaxStringLengthByField) { string fieldValue = pair.First.GetValue(datum, EmptyParameterList) as string; if (fieldValue != null && fieldValue.Length > pair.Second) { Verify.ThrowInvalidOperationException("Constraint violation. Value for field '{0}' on data type '{1}' is longer than {2} symbols.".FormatWith(pair.First.Name, type.FullName, pair.Second)); } } } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/Foundation/XmlDataProviderDocumentCache.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Xml; using System.Xml.Linq; using Composite.C1Console.Events; using Composite.Core; using Composite.Core.Collections.Generic; using Composite.Core.IO; using Composite.Core.Xml; using Composite.Data; using Composite.Data.Plugins.DataProvider.Streams; using Composite.Data.Streams; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider.Foundation { internal static class XmlDataProviderDocumentCache { private static readonly string LogTitle = "XmlDataProvider"; private static readonly Hashtable<string, FileRecord> _cache = new Hashtable<string, FileRecord>(); private static HashSet<string> _watchedFiles = new HashSet<string>(); private static readonly object _cacheSyncRoot = new object(); private static readonly object _documentEditingSyncRoot = new object(); private static readonly List<KeyValuePair<string, Action>> _externalFileChangeActions = new List<KeyValuePair<string, Action>>(); static XmlDataProviderDocumentCache() { GlobalEventSystemFacade.SubscribeToFlushEvent(OnFlushEvent); } /// <summary> /// Register an action that will be invoked on external file changes (new file copied in or file edited by external process). /// On Flush system event registrations are cleared and you should reregister. /// </summary> /// <param name="filename">File path</param> /// <param name="action">Action to execute on external changes</param> internal static void RegisterExternalFileChangeAction(string filename, Action action) { string key = filename.ToLowerInvariant(); _externalFileChangeActions.Add(new KeyValuePair<string, Action>(key, action)); } public static object SyncRoot => _documentEditingSyncRoot; [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass", Justification = "This is what we want, handle broken saves")] public static FileRecord GetFileRecord(string filePath, string elementName, Func<XElement, IDataId> keyGetter) { string cacheKey = filePath.ToLowerInvariant(); FileRecord cachedData = _cache[cacheKey]; if (cachedData == null) { lock (_cacheSyncRoot) { cachedData = _cache[cacheKey]; if (cachedData == null) { cachedData = LoadFileRecordFromDisk(filePath, elementName, keyGetter); EnsureFileChangesSubscription(filePath); _cache.Add(cacheKey, cachedData); } } } return cachedData; } public static IEnumerable<XElement> GetElements(string filePath, string elementName, IXmlDataProviderHelper helper) { Verify.ArgumentNotNullOrEmpty(filePath, "filename"); Verify.ArgumentNotNullOrEmpty(elementName, "elementName"); return GetFileRecord(filePath, elementName, helper.CreateDataId).ReadOnlyElementsList; } public static void SaveChanges() { lock (_cacheSyncRoot) { var dirtyRecords = _cache.GetValues().Where(f => f.Dirty); if (!dirtyRecords.Any()) return; foreach (FileRecord record in dirtyRecords) { SaveChanges(record); } } } public static void ClearCache() { XmlDataProviderDocumentWriter.Flush(); _cache.Clear(); } public static IDisposable CreateEditingContext() { return new EditingContext(); } private static List<XElement> ExtractElements(XDocument xDocument) { IEnumerable<XElement> elements = xDocument.Root.Elements(); var result = new List<XElement>(elements.Count()); result.AddRange(elements); xDocument.Root.RemoveNodes(); return result; } private static void SaveChanges(FileRecord fileRecord) { fileRecord.LastModified = DateTime.Now; fileRecord.ReadOnlyElementsList = fileRecord.RecordSet.Index.GetValues(); fileRecord.CachedTable = null; fileRecord.Dirty = false; XmlDataProviderDocumentWriter.Save(fileRecord); } /// <summary> /// Fetches a list of files that contain data - both the stable file and tmp files. /// List is ordered with newest files first. /// </summary> /// <param name="filePath"></param> /// <returns></returns> private static IList<C1FileInfo> GetCandidateFiles(string filePath) { var files = new List<C1FileInfo>(); if (C1File.Exists(filePath)) { files.Add(new C1FileInfo(filePath)); } var tmpFilePaths = C1Directory.GetFiles( Path.GetDirectoryName(filePath), $"{Path.GetFileName(filePath)}.*.tmp"); foreach (string tmpFilePath in tmpFilePaths) { files.Add(new C1FileInfo(tmpFilePath)); } return files.OrderByDescending(f => f.LastWriteTime).ToList(); } private static void OnFlushEvent(FlushEventArgs args) { _externalFileChangeActions.Clear(); } private static void EnsureFileChangesSubscription(string filePath) { filePath = filePath.ToLowerInvariant(); if (_watchedFiles.Contains(filePath)) { return; } lock (_cacheSyncRoot) { if (_watchedFiles.Contains(filePath)) { return; } _watchedFiles.Add(filePath); FileChangeNotificator.Subscribe(filePath, OnFileExternallyChanged); } } private static void OnFileExternallyChanged(string filePath, FileChangeType changeType) { filePath = filePath.ToLowerInvariant(); var fileRecord = _cache[filePath]; if (fileRecord == null || fileRecord.FileModificationDate == DateTime.MinValue || C1File.GetLastWriteTime(filePath) == fileRecord.FileModificationDate) { // Ignoring this notification since it's very very probably caused by XmlDataProvider itself return; } lock (_documentEditingSyncRoot) { lock (_cacheSyncRoot) { fileRecord = _cache[filePath]; if (fileRecord == null || fileRecord.FileModificationDate == DateTime.MinValue || C1File.GetLastWriteTime(filePath) == fileRecord.FileModificationDate) { // Ignoring this notification since it's very very probably caused by XmlDataProvider itself return; } _cache.Remove(filePath); Log.LogVerbose(LogTitle, "File '{0}' changed by another process. Flushing cache.", filePath); if (_externalFileChangeActions.Any(f => f.Key == filePath)) { var actions = _externalFileChangeActions.Where(f => f.Key == filePath).Select(f => f.Value).ToList(); foreach (var action in actions) { action.Invoke(); } } else { Log.LogWarning(LogTitle, "File '{0}' has not been related to a scope - unable to raise store change event", filePath); } } } } /// <summary> /// Will pull up most recent from disk - if no good file is found an empty store will be constructed anyway /// </summary> /// <param name="filePath"></param> /// <param name="elementName"></param> /// <param name="keyGetter"></param> /// <returns></returns> private static FileRecord LoadFileRecordFromDisk(string filePath, string elementName, Func<XElement, IDataId> keyGetter) { XDocument dataDocument = null; C1FileInfo usedFile = null; IList<C1FileInfo> candidateFiles = GetCandidateFiles(filePath); string errorCause = ""; foreach (C1FileInfo candidateFile in candidateFiles) { bool tryLoad = true; bool retriedLoad = false; while (tryLoad && dataDocument == null) { dataDocument = TryLoad(candidateFile, ref errorCause); if (dataDocument == null) { if (retriedLoad && (DateTime.Now - candidateFile.LastWriteTime).TotalSeconds > 30) { tryLoad = false; } else { Thread.Sleep(250); // other processes/servers may be writing to this file at the moment. Patience young padawan! } retriedLoad = true; } } if (dataDocument != null) { usedFile = candidateFile; break; } } if (dataDocument == null) { dataDocument = new XDocument(new XElement("fallback")); Log.LogWarning(LogTitle, "Did not find a healthy XML document for '{0}' - creating an empty store. {1}", filePath, errorCause); } List<XElement> elements = ExtractElements(dataDocument); var index = new Hashtable<IDataId, XElement>(elements.Count); foreach (var element in elements) { IDataId id = keyGetter(element); if (!index.ContainsKey(id)) { index.Add(id, element); } else { Log.LogWarning(LogTitle, "Found multiple elements in '{0}' sharing same key - duplicates ignored.", filePath); } } if (usedFile != null) { // clean up old and unused files foreach (C1FileInfo file in candidateFiles.Where(f => f.LastWriteTime < usedFile.LastWriteTime)) { try { C1File.Move(file.FullName, file.FullName + ".ghost"); } catch (Exception) { Log.LogWarning(LogTitle, $"Failed to clean up ghost file '{filePath}'."); } } } DateTime lastModifiedFileDate = usedFile?.LastWriteTime ?? DateTime.Now; return new FileRecord { FilePath = filePath, ElementName = elementName, RecordSet = new RecordSet { Index = index }, ReadOnlyElementsList = elements, LastModified = DateTime.Now, FileModificationDate = lastModifiedFileDate }; } private static XDocument TryLoad(C1FileInfo candidateFile, ref string errorCause) { XDocument dataDocument = null; try { var xmlReaderSettings = new XmlReaderSettings { CheckCharacters = false }; using (XmlReader xmlReader = XmlReaderUtils.Create(candidateFile.FullName, xmlReaderSettings)) { dataDocument = XDocument.Load(xmlReader); } } catch (Exception ex) { errorCause = ex.Message; // broken file - should not stop us... } return dataDocument; } private class EditingContext : IDisposable { private readonly bool _entered; public EditingContext() { Monitor.Enter(SyncRoot, ref _entered); } public void Dispose() { if (_entered) { Monitor.Exit(SyncRoot); } #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// <exclude /> ~EditingContext() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/Foundation/XmlDataProviderDocumentWriter.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.Core.Extensions; using Composite.Core; using Composite.Core.IO; using System.IO; using System.Threading; using System.Xml; using Composite.C1Console.Events; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider.Foundation { internal static class XmlDataProviderDocumentWriter { private static readonly ConcurrentQueue<FileRecord> _dirtyRecords = new ConcurrentQueue<FileRecord>(); private static readonly Dictionary<string, Func<IEnumerable<XElement>, IOrderedEnumerable<XElement>>> _fileOrderers = new Dictionary<string, Func<IEnumerable<XElement>, IOrderedEnumerable<XElement>>>(); private static readonly object _flushEnterLock = new object(); private static readonly object _flushExecuteLock = new object(); private static DateTime _activeFlushActivityStart = DateTime.MinValue; private static readonly System.Timers.Timer _autoCommitTimer; private static readonly TimeSpan _updateFrequency = TimeSpan.FromMilliseconds(1000); private static readonly TimeSpan _fileIoDelay = TimeSpan.FromMilliseconds(10); // small pause between io operations to reduce asp.net appPool recycles due to FileWatcher buffer fills - edge case, but highly annoying private const int NumberOfRetries = 30; private static readonly string LogTitle = nameof(XmlDataProvider); private static bool _forceImmediateWrite; static XmlDataProviderDocumentWriter() { _autoCommitTimer = new System.Timers.Timer(_updateFrequency.TotalMilliseconds) { AutoReset = true }; _autoCommitTimer.Elapsed += OnAutoCommitTimer; _autoCommitTimer.Start(); GlobalEventSystemFacade.SubscribeToShutDownEvent(OnShutDownEvent); } private static void OnShutDownEvent(ShutDownEventArgs args) { _forceImmediateWrite = true; Flush(); } internal static void Save(FileRecord fileRecord) { _dirtyRecords.Enqueue(fileRecord); if (_forceImmediateWrite) { Flush(); } } internal static void RegisterFileOrderer(string filename, Func<IEnumerable<XElement>, IOrderedEnumerable<XElement>> orderer) { string key = filename.ToLowerInvariant(); if (_fileOrderers.ContainsKey(key)) { _fileOrderers.Remove(key); } _fileOrderers.Add(key, orderer); } private static bool TryGetFileOrderer(out Func<IEnumerable<XElement>, IOrderedEnumerable<XElement>> orderer, string filename) { string key = filename.ToLowerInvariant(); if (_fileOrderers.ContainsKey(key)) { orderer = _fileOrderers[key]; return true; } orderer = null; return false; } internal static void Flush() { lock (_flushEnterLock) { if (!_forceImmediateWrite && (DateTime.Now - _activeFlushActivityStart).TotalSeconds < 30) { return; } _activeFlushActivityStart = DateTime.Now; } FileRecord dirtyFileRecord; List<FileRecord> fileRecords = new List<FileRecord>(); lock (_flushExecuteLock) { while (_dirtyRecords.TryDequeue(out dirtyFileRecord)) { if (!fileRecords.Any(f => f.FilePath == dirtyFileRecord.FilePath)) { fileRecords.Add(dirtyFileRecord); } } foreach (var fileRecord in fileRecords) { try { DoSave(fileRecord); } catch (Exception ex) { if (ex is DirectoryNotFoundException) { Log.LogWarning(LogTitle, $"Failed to save file '{fileRecord.FilePath}' as the underlying directory does not exist."); continue; } Log.LogCritical(LogTitle, $"Failed to save data to the file: '{fileRecord.FilePath}'"); Log.LogError(LogTitle, ex); _dirtyRecords.Enqueue(fileRecord); } } } _activeFlushActivityStart = DateTime.MinValue; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass", Justification = "This is what we want, to handle broken saves")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotCallXmlWriterCreateWithPath:DoNotCallXmlWriterCreateWithPath", Justification = "This is what we want, to handle broken saves")] private static void DoSave(FileRecord fileRecord) { var root = new XElement(GetRootElementName(fileRecord.ElementName)); var xDocument = new XDocument(root); var recordSet = fileRecord.RecordSet; var elements = new List<XElement>(recordSet.Index.GetValues()); Func<IEnumerable<XElement>, IOrderedEnumerable<XElement>> orderer; if (TryGetFileOrderer(out orderer, fileRecord.FilePath)) { var orderedElements = orderer(elements); orderedElements.ForEach(root.Add); } else { elements.ForEach(root.Add); } Exception thrownException = null; // Writing the file in the "catch" block in order to prevent chance of corrupting the file by experiencing ThreadAbortException. try { } finally { try { // Saving to temp file and file move to prevent broken saves var xmlWriterSettings = new XmlWriterSettings { CheckCharacters = false, Indent = true }; using (XmlWriter xmlWriter = XmlWriter.Create(fileRecord.TempFilePath, xmlWriterSettings)) { xDocument.Save(xmlWriter); } Thread.Sleep(_fileIoDelay); bool failed = true; Exception lastException = null; for (int i = 0; i < NumberOfRetries; i++) { DateTime lastSuccessfulFileChange = fileRecord.FileModificationDate; try { fileRecord.FileModificationDate = DateTime.MinValue; File.Copy(fileRecord.TempFilePath, fileRecord.FilePath, true); failed = false; break; } catch (Exception ex) { fileRecord.FileModificationDate = lastSuccessfulFileChange; lastException = ex; Thread.Sleep(10 * (i + 1)); } } if (!failed) { Thread.Sleep(_fileIoDelay); File.Delete(fileRecord.TempFilePath); } else { Log.LogCritical(LogTitle, "Failed deleting the file: " + fileRecord.FilePath); if (lastException != null) throw lastException; throw new InvalidOperationException("Failed to delete a file, this code shouldn't be reachable"); } fileRecord.FileModificationDate = C1File.GetLastWriteTime(fileRecord.FilePath); } catch (Exception exception) { thrownException = exception; } } // ThreadAbortException should have a higher priority, and therefore we're doing rethrow in a separate block if (thrownException != null) throw thrownException; } internal static string GetRootElementName(string elementName) { return elementName + "Elements"; } private static void OnAutoCommitTimer(object sender, System.Timers.ElapsedEventArgs e) { Flush(); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/Foundation/XmlDataProviderStoreManipulator.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Xml.Linq; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Xml; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.Plugins.DataProvider; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.Types; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider.Foundation { internal static class XmlDataProviderStoreManipulator { public static void CreateStore(string providerName, XmlProviderInterfaceConfigurationElement configurationElement) { foreach (DataScopeConfigurationElement scopeElement in configurationElement.ConfigurationStores) { CreateStore(providerName, scopeElement); } } public static void AlterStore(UpdateDataTypeDescriptor updateDescriptor, XmlProviderInterfaceConfigurationElement oldConfigurationElement, XmlProviderInterfaceConfigurationElement newConfigurationElement) { DataTypeChangeDescriptor dataTypeChangeDescriptor = updateDescriptor.CreateDataTypeChangeDescriptor(); foreach (KeyValuePair<string, Type> kvp in oldConfigurationElement.PropertyInitializers) { newConfigurationElement.AddPropertyInitializer(kvp.Key, kvp.Value); } Dictionary<string, object> newFieldValues = new Dictionary<string, object>(); foreach (DataScopeIdentifier scopeIdentifier in dataTypeChangeDescriptor.AddedDataScopes) { foreach (DataScopeConfigurationElement dataScopeConfigurationElement in newConfigurationElement.DataScopes[scopeIdentifier.Name].Values) { CreateStore(updateDescriptor.ProviderName, dataScopeConfigurationElement); } } foreach (DataScopeIdentifier scopeIdentifier in dataTypeChangeDescriptor.ExistingDataScopes) { foreach (KeyValuePair<string, DataScopeConfigurationElement> fileForLanguage in oldConfigurationElement.DataScopes[scopeIdentifier.Name]) { string cultureName = fileForLanguage.Key; if (!newConfigurationElement.DataScopes[scopeIdentifier.Name].ContainsKey(cultureName)) { continue; } var oldDataScopeConfigurationElement = fileForLanguage.Value; var newDataScopeConfigurationElement = newConfigurationElement.DataScopes[scopeIdentifier.Name][cultureName]; newFieldValues = new Dictionary<string, object> { {"PublicationStatus", GenericPublishProcessController.Published} }; CopyData(updateDescriptor.ProviderName, dataTypeChangeDescriptor, oldDataScopeConfigurationElement, newDataScopeConfigurationElement, newFieldValues); } } if (updateDescriptor.PublicationAdded) { foreach (var fileByLanguage in oldConfigurationElement.DataScopes[DataScopeIdentifier.PublicName]) { var oldDataScopeConfigurationElement = fileByLanguage.Value; var newDataScopeConfigurationElement = newConfigurationElement.DataScopes[DataScopeIdentifier.AdministratedName][fileByLanguage.Key]; newFieldValues = new Dictionary<string, object> { {"PublicationStatus", GenericPublishProcessController.Published} }; CopyData(updateDescriptor.ProviderName, dataTypeChangeDescriptor, oldDataScopeConfigurationElement, newDataScopeConfigurationElement, newFieldValues, false); } } if (updateDescriptor.PublicationRemoved) { foreach (var fileByLanguage in oldConfigurationElement.DataScopes[DataScopeIdentifier.AdministratedName]) { var oldDataScopeConfigurationElement = fileByLanguage.Value; var newDataScopeConfigurationElement = newConfigurationElement.DataScopes[DataScopeIdentifier.PublicName][fileByLanguage.Key]; CopyData(updateDescriptor.ProviderName, dataTypeChangeDescriptor, oldDataScopeConfigurationElement, newDataScopeConfigurationElement, newFieldValues, false); } } bool oldTypeLocalized = updateDescriptor.OldDataTypeDescriptor.Localizeable; bool newTypeLocalized = updateDescriptor.NewDataTypeDescriptor.Localizeable; if (!oldTypeLocalized && newTypeLocalized) { foreach (var newStore in newConfigurationElement.DataScopes.Values.SelectMany(kvp => kvp.Values)) { CreateStore(updateDescriptor.ProviderName, newStore); } foreach (string dataScopeIdentifier in oldConfigurationElement.DataScopes.Keys) { var oldFilesByCulture = oldConfigurationElement.DataScopes[dataScopeIdentifier]; string invariantCultureKey = ""; if (oldFilesByCulture.ContainsKey(invariantCultureKey)) { var oldDataScopeConfigurationElement = oldFilesByCulture[invariantCultureKey]; if (updateDescriptor.LocalesToCopyTo != null) { foreach (CultureInfo locale in updateDescriptor.LocalesToCopyTo) { var newDataScopeConfigurationElement = newConfigurationElement.DataScopes[dataScopeIdentifier][locale.Name]; var nfv = new Dictionary<string, object>(newFieldValues) { {"SourceCultureName", locale.Name} }; CopyData(updateDescriptor.ProviderName, dataTypeChangeDescriptor, oldDataScopeConfigurationElement, newDataScopeConfigurationElement, nfv, false); } } DropStore(updateDescriptor.ProviderName, oldDataScopeConfigurationElement); } } } if (oldTypeLocalized && !newTypeLocalized) { foreach (var newStore in newConfigurationElement.DataScopes.Values.SelectMany(kvp => kvp.Values)) { CreateStore(updateDescriptor.ProviderName, newStore); } if (updateDescriptor.LocaleToCopyFrom != null) { foreach (string dataScopeIdentifier in oldConfigurationElement.DataScopes.Keys) { var oldDataScopeConfigurationElement = oldConfigurationElement.DataScopes[dataScopeIdentifier][updateDescriptor.LocaleToCopyFrom.Name]; var newDataScopeConfigurationElement = newConfigurationElement.DataScopes[dataScopeIdentifier][""]; CopyData(updateDescriptor.ProviderName, dataTypeChangeDescriptor, oldDataScopeConfigurationElement, newDataScopeConfigurationElement, newFieldValues, false); } } foreach (var oldStore in oldConfigurationElement.DataScopes.SelectMany(d => d.Value).Where(f => f.Key != "").Select(f => f.Value)) { DropStore(updateDescriptor.ProviderName, oldStore); } } foreach (DataScopeIdentifier scopeIdentifier in dataTypeChangeDescriptor.DeletedDataScopes) { foreach (DataScopeConfigurationElement dataScopeConfigurationElement in oldConfigurationElement.DataScopes[scopeIdentifier.Name].Values) { DropStore(updateDescriptor.ProviderName, dataScopeConfigurationElement); } } } private static void CopyData(string providerName, DataTypeChangeDescriptor dataTypeChangeDescriptor, DataScopeConfigurationElement oldDataScopeConfigurationElement, DataScopeConfigurationElement newDataScopeConfigurationElement, Dictionary<string, object> newFieldValues, bool deleteOldFile = true) { string oldFilename = ResolvePath(oldDataScopeConfigurationElement.Filename, providerName); string newFilename = ResolvePath(newDataScopeConfigurationElement.Filename, providerName); XDocument oldDocument = XDocumentUtils.Load(PathUtil.Resolve(oldFilename)); List<XElement> newElements = new List<XElement>(); bool addingVersionId = dataTypeChangeDescriptor.AddedFields.Any(f => f.Name == nameof(IVersioned.VersionId)) && dataTypeChangeDescriptor.AlteredType.SuperInterfaces.Any(s => s == typeof (IVersioned)); string versionIdSourceFieldName = null; if (addingVersionId) { if (dataTypeChangeDescriptor.AlteredType.DataTypeId == typeof(IPage).GetImmutableTypeId()) { versionIdSourceFieldName = nameof(IPage.Id); } else { versionIdSourceFieldName = dataTypeChangeDescriptor.AlteredType.Fields .Where(f => f.InstanceType == typeof(Guid) && (f.ForeignKeyReferenceTypeName?.Contains(typeof(IPage).FullName) ?? false)) .OrderByDescending(f => f.Name == nameof(IPageData.PageId)) .Select(f => f.Name) .FirstOrDefault(); } } foreach (XElement oldElement in oldDocument.Root.Elements()) { List<XAttribute> newChildAttributes = new List<XAttribute>(); foreach (XAttribute oldChildAttribute in oldElement.Attributes()) { var existingFieldInfo = GetExistingFieldInfo(dataTypeChangeDescriptor, oldChildAttribute.Name.LocalName); if (existingFieldInfo != null) { if (existingFieldInfo.OriginalField.Name != existingFieldInfo.AlteredField.Name) { XAttribute newChildAttribute = new XAttribute(existingFieldInfo.AlteredField.Name, oldChildAttribute.Value); newChildAttributes.Add(newChildAttribute); } else { newChildAttributes.Add(oldChildAttribute); } } // It may happen that some data were added before data descriptors are updated, in the case of using // [AutoUpdateable] attribute. else if (dataTypeChangeDescriptor.AddedFields.Any(addedField => addedField.Name == oldChildAttribute.Name)) { newChildAttributes.Add(oldChildAttribute); } } // Adding default value for fields that are NULL and become required foreach (var existingFieldInfo in dataTypeChangeDescriptor.ExistingFields) { bool fieldBecomeRequired = existingFieldInfo.OriginalField.IsNullable && !existingFieldInfo.AlteredField.IsNullable; string fieldName = existingFieldInfo.AlteredField.Name; if (fieldBecomeRequired && !newChildAttributes.Any(attr => attr.Name.LocalName == fieldName)) { newChildAttributes.Add(new XAttribute(fieldName, GetDefaultValue(existingFieldInfo.AlteredField))); } } foreach (DataFieldDescriptor fieldDescriptor in dataTypeChangeDescriptor.AddedFields) { if (addingVersionId && fieldDescriptor.Name == nameof(IVersioned.VersionId) && versionIdSourceFieldName != null) { if (!oldElement.Attributes().Any(a => a.Name.LocalName == nameof(IVersioned.VersionId))) { var sourceFieldValue = (Guid)oldElement.Attribute(versionIdSourceFieldName); newChildAttributes.Add(new XAttribute(fieldDescriptor.Name, sourceFieldValue)); } continue; } if (!fieldDescriptor.IsNullable && !newChildAttributes.Any(attr => attr.Name == fieldDescriptor.Name)) { object value; if (!newFieldValues.TryGetValue(fieldDescriptor.Name, out value)) { value = GetDefaultValue(fieldDescriptor); } newChildAttributes.Add(new XAttribute(fieldDescriptor.Name, value)); } else if (newFieldValues.ContainsKey(fieldDescriptor.Name)) { XAttribute attribute = newChildAttributes.SingleOrDefault(attr => attr.Name == fieldDescriptor.Name); attribute?.SetValue(newFieldValues[fieldDescriptor.Name]); } } XElement newElement = new XElement(newDataScopeConfigurationElement.ElementName, newChildAttributes); newElements.Add(newElement); } if (deleteOldFile) { C1File.Delete(oldFilename); } var newDocument = new XDocument( new XElement(XmlDataProviderDocumentWriter.GetRootElementName(newDataScopeConfigurationElement.ElementName), newElements)); XDocumentUtils.Save(newDocument, newFilename); } private static object GetDefaultValue(DataFieldDescriptor fieldDescriptor) { Verify.ArgumentNotNull(fieldDescriptor, "fieldDescriptor"); if (fieldDescriptor.DefaultValue != null) { return fieldDescriptor.DefaultValue.Value; } switch (fieldDescriptor.StoreType.PhysicalStoreType) { case PhysicalStoreFieldType.Boolean: return false; case PhysicalStoreFieldType.DateTime: return DateTime.Now; case PhysicalStoreFieldType.Integer: case PhysicalStoreFieldType.Long: case PhysicalStoreFieldType.Decimal: return 0m; case PhysicalStoreFieldType.Guid: return Guid.Empty; case PhysicalStoreFieldType.String: case PhysicalStoreFieldType.LargeString: return string.Empty; } throw new NotImplementedException("Supplied StoreFieldType contains an unsupported PhysicalStoreType '{0}'." .FormatWith(fieldDescriptor.StoreType.PhysicalStoreType)); } public static void DropStore(string providerName, XmlProviderInterfaceConfigurationElement configurationElement) { foreach (DataScopeConfigurationElement scopeElement in configurationElement.ConfigurationStores) { DropStore(providerName, scopeElement); } } internal static void CreateStore(string providerName, DataScopeConfigurationElement scopeElement) { string filename = ResolvePath(scopeElement.Filename, providerName); string directoryPath = Path.GetDirectoryName(filename); if (!C1Directory.Exists(directoryPath)) { C1Directory.CreateDirectory(directoryPath); } bool keepExistingFile = false; string rootLocalName = XmlDataProviderDocumentWriter.GetRootElementName(scopeElement.ElementName); string obsoleteRootElementName = scopeElement.ElementName + "s"; if (C1File.Exists(filename)) { try { XDocument existingDocument = XDocumentUtils.Load(filename); if (existingDocument.Root.Name.LocalName == rootLocalName || existingDocument.Root.Name.LocalName == obsoleteRootElementName) { keepExistingFile = true; } } catch (Exception) { keepExistingFile = false; } if (!keepExistingFile) { C1File.Delete(filename); } } if (!keepExistingFile) { var document = new XDocument(); document.Add(new XElement(rootLocalName)); XDocumentUtils.Save(document, filename); } } internal static void DropStore(string providerName, DataScopeConfigurationElement scopeElement) { string filename = ResolvePath(scopeElement.Filename, providerName); if (C1File.Exists(filename)) { C1File.Delete(filename); } } private static DataTypeChangeDescriptor.ExistingFieldInfo GetExistingFieldInfo(DataTypeChangeDescriptor dataTypeChangeDescriptor, string name) { return dataTypeChangeDescriptor.ExistingFields.FirstOrDefault(f => f.OriginalField.Name == name); } private static string ResolvePath(string filename, string providerName) { XmlDataProviderData providerConfiguration = GetProviderSettings(providerName); return PathUtil.Resolve(Path.Combine(providerConfiguration.StoreDirectory, filename)); } private static XmlDataProviderData GetProviderSettings(string providerName) { return (XmlDataProviderData)DataProviderConfigurationServices.GetDataProviderConfiguration(providerName); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/IXElementWrapper.cs ================================================ using System.Xml.Linq; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IXElementWrapper { /// <exclude /> void CommitData(XElement element); } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/IXmlDataProviderHelper.cs ================================================ using System; using System.Xml.Linq; using Composite.Data; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider { internal interface IXmlDataProviderHelper { Type _InterfaceType { get; } Type _DataIdType { get; } Func<XElement, T> CreateSelectFunction<T>(string providerName) where T : IData; IDataId CreateDataId(XElement xElement); void ValidateDataType(IData data); T CreateNewElement<T>(IData data, out XElement newElement, string elementName, string providerName) where T : IData; } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/XmlDataProvider.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using Composite.Core; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.Plugins.DataProvider; using Composite.Plugins.Data.DataProviders.Common; using Composite.Plugins.Data.DataProviders.XmlDataProvider.CodeGeneration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider { /// <summary> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] [ConfigurationElementType(typeof(XmlDataProviderData))] internal partial class XmlDataProvider : IWritableDataProvider, IDynamicDataProvider, IGeneratedTypesDataProvider, ILocalizedDataProvider, ISupportCachingDataProvider { private static readonly string LogTitle = typeof(XmlDataProvider).Name; private readonly string _fileStoreDirectory; private IEnumerable<XmlProviderInterfaceConfigurationElement> _dataTypeConfigurationElements; private XmlDataTypeStoresContainer _xmlDataTypeStoresContainer; private DataProviderContext _dataProviderContext; private readonly object _lock = new object(); public XmlDataProvider(string storeDirectory, IEnumerable<XmlProviderInterfaceConfigurationElement> dataTypeConfigurationElements) { if (storeDirectory == null) throw new ArgumentNullException("storeDirectory"); if (dataTypeConfigurationElements == null) throw new ArgumentNullException("dataTypeConfigurationElements"); _fileStoreDirectory = storeDirectory; _dataTypeConfigurationElements = dataTypeConfigurationElements; } public DataProviderContext Context { set { _dataProviderContext = value; CodeGenerationManager.AddAssemblyCodeProvider(new XmlDataProviderCodeProvider(_dataProviderContext.ProviderName)); InitializeExistingStores(); } } public IEnumerable<Type> GetSupportedInterfaces() { return _xmlDataTypeStoresContainer.SupportedInterfaces; } public IEnumerable<Type> GetKnownInterfaces() { return _xmlDataTypeStoresContainer.KnownInterfaces; } public IEnumerable<Type> GetGeneratedInterfaces() { return _xmlDataTypeStoresContainer.GeneratedInterfaces; } public bool AllowResultsWrapping { get { return false; } } internal void BuildAllCode(CodeGenerationBuilder codeGenerationBuilder) { var codeBuilder = new XmlDataProviderCodeBuilder(_dataProviderContext.ProviderName, codeGenerationBuilder); foreach (XmlProviderInterfaceConfigurationElement element in _dataTypeConfigurationElements) { if (element.DataTypeId == Guid.Empty) { continue; } Guid dataTypeId = element.DataTypeId; DataTypeDescriptor dataTypeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(dataTypeId); if (dataTypeDescriptor == null) { Log.LogError(LogTitle, "Failed to find interface by id '{0}'. Skipping code generation for that type", dataTypeId); continue; } if (!dataTypeDescriptor.ValidateRuntimeType()) { Log.LogError(LogTitle, "The non code generated interface type '{0}' was not found, skipping code generation for that type", dataTypeDescriptor); continue; } codeBuilder.AddDataType(dataTypeDescriptor); } } } internal sealed class XmlDataProviderAssembler : IAssembler<IDataProvider, DataProviderData> { private static readonly string LogTitle = typeof (XmlDataProviderAssembler).Name; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IDataProvider Assemble(IBuilderContext context, DataProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { string pathToConfigFile = PathUtil.Resolve(GlobalSettingsFacade.ConfigurationDirectory); return Assemble(context, objectConfiguration, configurationSource, reflectionCache, pathToConfigFile); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] internal IDataProvider Assemble(IBuilderContext context, DataProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache, string configurationFolderPath) { var data = (XmlDataProviderData)objectConfiguration; var configuration = new C1Configuration(Path.Combine(configurationFolderPath, string.Format("{0}.config", data.Name))); var section = configuration.GetSection(XmlDataProviderConfigurationSection.SectionName) as XmlDataProviderConfigurationSection; if (section == null) { section = new XmlDataProviderConfigurationSection(); configuration.Sections.Add(XmlDataProviderConfigurationSection.SectionName, section); configuration.Save(); } var dataTypeConfigurationElements = section.Interfaces.Cast<XmlProviderInterfaceConfigurationElement>().ToList(); return new XmlDataProvider(PathUtil.Resolve(data.StoreDirectory), dataTypeConfigurationElements); } } [Assembler(typeof(XmlDataProviderAssembler))] internal sealed class XmlDataProviderData : DataProviderData { private const string _storeDirectoryPropertyName = "storeDirectory"; [System.Configuration.ConfigurationProperty(_storeDirectoryPropertyName, IsRequired = true)] public string StoreDirectory { get { return (string)base[_storeDirectoryPropertyName]; } set { base[_storeDirectoryPropertyName] = value; } } } internal sealed class XmlDataProviderConfigurationSection : System.Configuration.ConfigurationSection { public const string SectionName = "Composite.Data.Plugins.XmlDataProviderConfiguration"; private const string _interfacesPropertyName = "Interfaces"; [System.Configuration.ConfigurationProperty(_interfacesPropertyName)] public XmlProviderInterfaceConfigurationElementCollection Interfaces { get { return (XmlProviderInterfaceConfigurationElementCollection)base[_interfacesPropertyName]; } set { base[_interfacesPropertyName] = value; } } } internal sealed class XmlProviderInterfaceConfigurationElementCollection : System.Configuration.ConfigurationElementCollection { internal void Add(XmlProviderInterfaceConfigurationElement element) { BaseAdd(element); } internal void Remove(object key) { BaseRemove(key); } protected override System.Configuration.ConfigurationElement CreateNewElement() { return new XmlProviderInterfaceConfigurationElement(); } protected override object GetElementKey(System.Configuration.ConfigurationElement element) { return ((XmlProviderInterfaceConfigurationElement)element).DataTypeId; } internal object GetKey(DataTypeDescriptor dataTypeDescriptor) { Guid dataTypeId = dataTypeDescriptor.DataTypeId; object[] allKeys = BaseGetAllKeys(); return allKeys.Contains(dataTypeId) ? dataTypeId : (object)null; } internal XmlProviderInterfaceConfigurationElement Get(object key) { return (XmlProviderInterfaceConfigurationElement)BaseGet(key); } } internal sealed class XmlProviderInterfaceConfigurationElement : System.Configuration.ConfigurationElement { public Dictionary<string, Dictionary<string, DataScopeConfigurationElement>> DataScopes { get { var scopes = new Dictionary<string, Dictionary<string, DataScopeConfigurationElement>>(); foreach (DataScopeConfigurationElement scopeElement in this.ConfigurationStores) { Dictionary<string, DataScopeConfigurationElement> dic; if (!scopes.TryGetValue(scopeElement.DataScope, out dic)) { dic = new Dictionary<string, DataScopeConfigurationElement>(); scopes.Add(scopeElement.DataScope, dic); } dic.Add(scopeElement.CultureName, scopeElement); } return scopes; } } public Dictionary<string, Type> DataIdProperties { get { return ConfigurationDataIdProperties.ToDictionary(e => e.Name, e => e.Type); } } public Dictionary<string, string> PropertyNameMappings { get { return ConfigurationPropertyNameMappings.ToDictionary(e => e.PropertyName, e => e.SourcePropertyName); } } public Dictionary<string, Type> PropertyInitializers { get { return ConfigurationPropertyInitializers.ToDictionary(e => e.Name, e => e.Type); } } public void AddPropertyInitializer(string name, Type type) { ConfigurationPropertyInitializers.Add(name, type); } private const string _dataTypeIdName = "dataTypeId"; [System.Configuration.ConfigurationProperty(_dataTypeIdName, IsRequired = true)] public Guid DataTypeId { get { return (Guid)base[_dataTypeIdName]; } set { base[_dataTypeIdName] = value; } } private const string _isGeneratedTypePropertyName = "isGeneratedType"; [System.Configuration.ConfigurationProperty(_isGeneratedTypePropertyName, IsRequired = true)] public bool IsGeneratedType { get { return (bool)base[_isGeneratedTypePropertyName]; } set { base[_isGeneratedTypePropertyName] = value; } } private const string _storesPropertyName = "Stores"; [System.Configuration.ConfigurationProperty(_storesPropertyName, IsRequired = false)] public DataScopeConfigurationElementCollection ConfigurationStores { get { return (DataScopeConfigurationElementCollection)base[_storesPropertyName]; } set { base[_storesPropertyName] = value; } } private const string _dataIdPropertiesPropertyName = "DataIdProperties"; [System.Configuration.ConfigurationProperty(_dataIdPropertiesPropertyName, IsRequired = true)] public SimpleNameTypeConfigurationElementCollection ConfigurationDataIdProperties { get { return (SimpleNameTypeConfigurationElementCollection)base[_dataIdPropertiesPropertyName]; } set { base[_dataIdPropertiesPropertyName] = value; } } private const string _propertyNameMappingsPropertyName = "PropertyNameMappings"; [System.Configuration.ConfigurationProperty(_propertyNameMappingsPropertyName)] public PropertyNameMappingConfigurationElementCollection ConfigurationPropertyNameMappings { get { return (PropertyNameMappingConfigurationElementCollection)base[_propertyNameMappingsPropertyName]; } set { base[_propertyNameMappingsPropertyName] = value; } } private const string _propertyInitializersPropertyName = "PropertyInitializers"; [System.Configuration.ConfigurationProperty(_propertyInitializersPropertyName)] public SimpleNameTypeConfigurationElementCollection ConfigurationPropertyInitializers { get { return (SimpleNameTypeConfigurationElementCollection)base[_propertyInitializersPropertyName]; } set { base[_propertyInitializersPropertyName] = value; } } } internal sealed class DataScopeConfigurationElement : System.Configuration.ConfigurationElement { private const string _dataScopePropertyName = "dataScope"; [System.Configuration.ConfigurationProperty(_dataScopePropertyName, IsRequired = true)] public string DataScope { get { return (string)base[_dataScopePropertyName]; } set { base[_dataScopePropertyName] = value; } } private const string _cultureNamePropertyName = "cultureName"; [System.Configuration.ConfigurationProperty(_cultureNamePropertyName, IsRequired = false, DefaultValue = "")] public string CultureName { get { return (string)base[_cultureNamePropertyName]; } set { base[_cultureNamePropertyName] = value; } } private const string _filenamePropertyName = "filename"; [System.Configuration.ConfigurationProperty(_filenamePropertyName, IsRequired = true)] public string Filename { get { return (string)base[_filenamePropertyName]; } set { base[_filenamePropertyName] = value; } } private const string _elementNamePropertyName = "elementName"; [System.Configuration.ConfigurationProperty(_elementNamePropertyName, IsRequired = true)] public string ElementName { get { return (string)base[_elementNamePropertyName]; } set { base[_elementNamePropertyName] = value; } } } internal sealed class DataScopeConfigurationElementCollection : System.Configuration.ConfigurationElementCollection, IEnumerable<DataScopeConfigurationElement> { internal void Add(DataScopeConfigurationElement element) { BaseAdd(element); } protected override System.Configuration.ConfigurationElement CreateNewElement() { return new DataScopeConfigurationElement(); } protected override object GetElementKey(System.Configuration.ConfigurationElement element) { DataScopeConfigurationElement castedElement = (DataScopeConfigurationElement)element; return string.Format("{0}.{1}", castedElement.DataScope, castedElement.CultureName); } IEnumerator<DataScopeConfigurationElement> IEnumerable<DataScopeConfigurationElement>.GetEnumerator() { return this.OfType<DataScopeConfigurationElement>().GetEnumerator(); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/XmlDataProvider_CRUD.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Transactions; using System.Xml.Linq; using Composite.Core; using Composite.Core.Collections.Generic; using Composite.Core.Threading; using Composite.Data; using Composite.Data.Caching; using Composite.Data.Foundation; using Composite.Plugins.Data.DataProviders.XmlDataProvider.Foundation; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider { internal partial class XmlDataProvider { public IQueryable<T> GetData<T>() where T : class, IData { CheckTransactionNotInAbortedState(); XmlDataTypeStore dataTypeStore = _xmlDataTypeStoresContainer.GetDataTypeStore(typeof(T)); var currentDataScope = DataScopeManager.MapByType(typeof(T)); if (!dataTypeStore.HasDataScopeName(currentDataScope)) return Enumerable.Empty<T>().AsQueryable(); var dataTypeStoreScope = dataTypeStore.GetDataScopeForType(typeof(T)); var fileRecord = XmlDataProviderDocumentCache.GetFileRecord( dataTypeStoreScope.Filename, dataTypeStoreScope.ElementName, dataTypeStore.Helper.CreateDataId); if (fileRecord.CachedTable == null) { ICollection<XElement> elements = fileRecord.ReadOnlyElementsList; Func<XElement, T> fun = dataTypeStore.Helper.CreateSelectFunction<T>(_dataProviderContext.ProviderName); var list = new List<T>(elements.Count); list.AddRange(elements.Select(fun)); fileRecord.CachedTable = new CachedTable<T>(list); } return new CachingQueryable<T>(fileRecord.CachedTable, () => fileRecord.CachedTable.Queryable); } public T GetData<T>(IDataId dataId) where T : class, IData { if (dataId == null) throw new ArgumentNullException("dataId"); XmlDataTypeStore dataTypeStore = _xmlDataTypeStoresContainer.GetDataTypeStore(typeof(T)); var dataTypeStoreScope = dataTypeStore.GetDataScopeForType(typeof(T)); var fileRecord = GetFileRecord(dataTypeStore, dataTypeStoreScope); XElement element = fileRecord.RecordSet.Index[dataId]; if (element == null) return null; Func<XElement, T> selectFun = dataTypeStore.Helper.CreateSelectFunction<T>(_dataProviderContext.ProviderName); return selectFun(element); } public void Update(IEnumerable<IData> dataset) { Verify.ArgumentNotNull(dataset, "dataset"); CheckTransactionNotInAbortedState(); using (XmlDataProviderDocumentCache.CreateEditingContext()) { var validatedFileRecords = new Dictionary<DataSourceId, FileRecord>(); var validatedElements = new Dictionary<DataSourceId, XElement>(); // verify phase foreach (IData wrappedData in dataset) { var data = DataWrappingFacade.UnWrap(wrappedData); Verify.ArgumentCondition(data != null, "dataset", "Collection contains a null element."); Verify.ArgumentCondition(data.DataSourceId != null, "dataset", "Collection contains a data item with DataSourceId null property."); ValidationHelper.Validate(data); XmlDataTypeStore dataTypeStore = _xmlDataTypeStoresContainer.GetDataTypeStore(data.DataSourceId.InterfaceType); var dataScope = data.DataSourceId.DataScopeIdentifier; var culture = data.DataSourceId.LocaleScope; var type = data.DataSourceId.InterfaceType; var dataTypeStoreScope = dataTypeStore.GetDataScope(dataScope, culture, type); dataTypeStore.Helper.ValidateDataType(data); if (null == data.DataSourceId) throw new ArgumentException("The DataSourceId property of the data argument must not be null", "data"); if (data.DataSourceId.ProviderName != _dataProviderContext.ProviderName) throw new ArgumentException("The data element does not belong to this provider", "data"); var fileRecord = GetFileRecord(dataTypeStore, dataTypeStoreScope); var index = fileRecord.RecordSet.Index; IDataId dataId = data.DataSourceId.DataId; XElement element = index[dataId]; if (element == null) { throw new ArgumentException($"Cannot update a data item, no data element corresponds to the given data id: '{dataId.Serialize(null)}'; Type: '{type}'; DataScope: '{dataScope}'; Culture: '{culture}'", nameof(dataset)); } IXElementWrapper wrapper = data as IXElementWrapper; Verify.ArgumentCondition(wrapper != null, nameof(dataset), $"The type of data was expected to be of type {typeof(IXElementWrapper)}"); XElement updatedElement = CreateUpdatedXElement(wrapper, element); validatedFileRecords.Add(data.DataSourceId, fileRecord); validatedElements.Add(data.DataSourceId, updatedElement); } foreach (var key in validatedElements.Keys) { FileRecord fileRecord = validatedFileRecords[key]; fileRecord.Dirty = true; fileRecord.RecordSet.Index[key.DataId] = validatedElements[key]; } XmlDataProviderDocumentCache.SaveChanges(); SubscribeToTransactionRollbackEvent(); } } public List<T> AddNew<T>(IEnumerable<T> dataset) where T : class, IData { Verify.ArgumentNotNull(dataset, "dataset"); CheckTransactionNotInAbortedState(); var resultList = new List<T>(); using (XmlDataProviderDocumentCache.CreateEditingContext()) { XmlDataTypeStore dataTypeStore = _xmlDataTypeStoresContainer.GetDataTypeStore(typeof(T)); var dataTypeStoreScope = dataTypeStore.GetDataScopeForType(typeof(T)); var fileRecord = GetFileRecord(dataTypeStore, dataTypeStoreScope); var validatedElements = new Dictionary<DataSourceId, XElement>(); // validating phase foreach (IData data in dataset) { Verify.ArgumentCondition(data != null, nameof(dataset), "The enumeration dataset may not contain nulls"); ValidationHelper.Validate(data); XElement newElement; T newData = dataTypeStore.Helper.CreateNewElement<T>(data, out newElement, dataTypeStoreScope.ElementName, _dataProviderContext.ProviderName); IDataId dataId = dataTypeStore.Helper.CreateDataId(newElement); XElement violatingElement = fileRecord.RecordSet.Index[dataId]; if (violatingElement != null) { throw new ArgumentException(nameof(dataset), "Key violation error. A data element with the same dataId is already added. Type: " + typeof(T).FullName); } validatedElements.Add(newData.DataSourceId, newElement); resultList.Add(newData); } // commit validated elements foreach (var key in validatedElements.Keys) { fileRecord.RecordSet.Index.Add(key.DataId, validatedElements[key]); fileRecord.Dirty = true; } XmlDataProviderDocumentCache.SaveChanges(); SubscribeToTransactionRollbackEvent(); } return resultList; } public void Delete(IEnumerable<DataSourceId> dataSourceIds) { Verify.ArgumentNotNull(dataSourceIds, "dataSourceIds"); CheckTransactionNotInAbortedState(); using (XmlDataProviderDocumentCache.CreateEditingContext()) { var validated = new Dictionary<DataSourceId, FileRecord>(); // verify phase foreach (DataSourceId dataSourceId in dataSourceIds) { Verify.ArgumentCondition(dataSourceId != null, nameof(dataSourceIds), "The enumeration may not contain null values"); XmlDataTypeStore dataTypeStore = _xmlDataTypeStoresContainer.GetDataTypeStore(dataSourceId.InterfaceType); var dataScope = dataSourceId.DataScopeIdentifier; var culture = dataSourceId.LocaleScope; var type = dataSourceId.InterfaceType; var dataId = dataSourceId.DataId; var dataTypeStoreScope = dataTypeStore.GetDataScope(dataScope, culture, type); if (dataTypeStore.Helper._DataIdType != dataId.GetType()) { throw new ArgumentException("Only data ids from this provider is allowed to be deleted on on the provider"); } var fileRecord = GetFileRecord(dataTypeStore, dataTypeStoreScope); var index = fileRecord.RecordSet.Index; if (!index.ContainsKey(dataId)) { throw new ArgumentException($"Cannot delete a data item, no data element corresponds to the given data id: '{dataId.Serialize(null)}'; Type: '{type}'; DataScope: '{dataScope}'; Culture: '{culture}'", nameof(dataSourceIds)); } validated.Add(dataSourceId, fileRecord); } // commit phase foreach (var dataSourceId in validated.Keys) { FileRecord fileRecord = validated[dataSourceId]; fileRecord.RecordSet.Index.Remove(dataSourceId.DataId); fileRecord.Dirty = true; } XmlDataProviderDocumentCache.SaveChanges(); SubscribeToTransactionRollbackEvent(); } } private static void CheckTransactionNotInAbortedState() { var transaction = Transaction.Current; if (transaction?.TransactionInformation.Status == TransactionStatus.Aborted) { Log.LogWarning(LogTitle, new TransactionException("Transaction is in aborted state")); } } private static void SubscribeToTransactionRollbackEvent() { var transaction = Transaction.Current; if (transaction == null) { return; } var currentThreadData = ThreadDataManager.GetCurrentNotNull(); Hashset<string> transactions; const string tlsKey = "XmlDataProvider enlisted transactions"; if (!currentThreadData.HasValue(tlsKey)) { transactions = new Hashset<string>(); currentThreadData.SetValue(tlsKey, transactions); } else { transactions = (Hashset<string>)currentThreadData[tlsKey]; } string transactionId = transaction.TransactionInformation.LocalIdentifier; if (transactions.Contains(transactionId)) { return; } transactions.Add(transactionId); ThreadStart logging = () => { var exception = new TransactionException("XML data provider does not support transaction's API, changes were not rolled back."); Log.LogWarning(LogTitle, exception); }; transaction.EnlistVolatile(new TransactionRollbackHandler(logging), EnlistmentOptions.None); } private static FileRecord GetFileRecord(XmlDataTypeStore dataTypeStore, XmlDataTypeStoreDataScope dataTypeStoreDataScope) { return XmlDataProviderDocumentCache.GetFileRecord(dataTypeStoreDataScope.Filename, dataTypeStoreDataScope.ElementName, dataTypeStore.Helper.CreateDataId); } private static XElement CreateUpdatedXElement(IXElementWrapper wrapper, XElement originalElement) { XElement result = new XElement(originalElement.Name); foreach (XAttribute attribute in originalElement.Attributes()) { result.Add(new XAttribute(attribute.Name, attribute.Value)); } wrapper.CommitData(result); return result; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/XmlDataProvider_Stores.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.IO; using System.Linq; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.Foundation; using Composite.Data.Foundation.CodeGeneration; using Composite.Plugins.Data.DataProviders.XmlDataProvider.CodeGeneration; using Composite.Plugins.Data.DataProviders.XmlDataProvider.Foundation; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider { internal partial class XmlDataProvider { public void CreateStores(IReadOnlyCollection<DataTypeDescriptor> dataTypeDescriptors) { var dataTypes = DataTypeTypesManager.GetDataTypes(dataTypeDescriptors); var storesToCreate = new List<GeneratedTypesInfo>(); foreach (var dataTypeDescriptor in dataTypeDescriptors) { Type interfaceType = dataTypes[dataTypeDescriptor.DataTypeId]; storesToCreate.Add(BuildGeneratedTypesInfo(dataTypeDescriptor, interfaceType)); } CompileMissingTypes(storesToCreate); foreach (var storeToCreate in storesToCreate) { var dataTypeDescriptor = storeToCreate.DataTypeDescriptor; InterfaceConfigurationManipulator.AddNew(_dataProviderContext.ProviderName, dataTypeDescriptor); var xmlDataTypeStoreCreator = new XmlDataTypeStoreCreator(_fileStoreDirectory); XmlDataTypeStore xmlDateTypeStore = xmlDataTypeStoreCreator.CreateStoreResult( dataTypeDescriptor, storeToCreate.DataProviderHelperClass, storeToCreate.DataIdClass, null); Type interfaceType = storeToCreate.InterfaceType; AddDataTypeStore(dataTypeDescriptor, interfaceType, xmlDateTypeStore); } } public void AlterStore(UpdateDataTypeDescriptor updateDataTypeDescriptor, bool forceCompile) { XmlDataProviderDocumentCache.ClearCache(); XmlProviderInterfaceConfigurationElement element = InterfaceConfigurationManipulator.Change(updateDataTypeDescriptor); if (forceCompile) { DataTypeDescriptor dataTypeDescriptor = updateDataTypeDescriptor.NewDataTypeDescriptor; Type dataProviderHelperType; Type dataIdClassType; bool typesExists = EnsureNeededTypes(dataTypeDescriptor, out dataProviderHelperType, out dataIdClassType, true); Verify.That(typesExists, "Could not find or code generated the type '{0}' or one of the needed helper types", dataTypeDescriptor.GetFullInterfaceName()); var xmlDataTypeStoreDataScopes = new List<XmlDataTypeStoreDataScope>(); foreach (DataScopeConfigurationElement dataScopeConfigurationElement in element.ConfigurationStores) { var xmlDataTypeStoreDataScope = new XmlDataTypeStoreDataScope { DataScopeName = dataScopeConfigurationElement.DataScope, CultureName = dataScopeConfigurationElement.CultureName, ElementName = dataScopeConfigurationElement.ElementName, Filename = Path.Combine(_fileStoreDirectory, dataScopeConfigurationElement.Filename) }; xmlDataTypeStoreDataScopes.Add(xmlDataTypeStoreDataScope); } var xmlDataTypeStoreCreator = new XmlDataTypeStoreCreator(_fileStoreDirectory); XmlDataTypeStore xmlDateTypeStore = xmlDataTypeStoreCreator.CreateStoreResult(dataTypeDescriptor, dataProviderHelperType, dataIdClassType, xmlDataTypeStoreDataScopes); Type interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor); UpdateDataTypeStore(dataTypeDescriptor, interfaceType, xmlDateTypeStore); } } public void DropStore(DataTypeDescriptor typeDescriptor) { XmlDataProviderDocumentCache.ClearCache(); InterfaceConfigurationManipulator.Remove(_dataProviderContext.ProviderName, typeDescriptor); _dataTypeConfigurationElements = _dataTypeConfigurationElements.Where(s => s.DataTypeId != typeDescriptor.DataTypeId).Evaluate(); } public void AddLocale(CultureInfo cultureInfo) { XmlDataProviderDocumentCache.ClearCache(); InterfaceConfigurationManipulator.AddLocale(_dataProviderContext.ProviderName, this.GetSupportedInterfaces(), cultureInfo); } public void RemoveLocale(CultureInfo cultureInfo) { XmlDataProviderDocumentCache.ClearCache(); InterfaceConfigurationManipulator.RemoveLocale(_dataProviderContext.ProviderName, this.GetSupportedInterfaces(), cultureInfo); } private static Exception NewConfigurationException(ConfigurationElement element, string message) { return new ConfigurationErrorsException(message, element.ElementInformation.Source, element.ElementInformation.LineNumber); } private void InitializeExistingStores() { var xmlDataTypeStoreCreator = new XmlDataTypeStoreCreator(_fileStoreDirectory); _xmlDataTypeStoresContainer = new XmlDataTypeStoresContainer(_dataProviderContext.ProviderName); var dataTypes = LoadDataTypes(_dataTypeConfigurationElements); var storesToLoad = new List<GeneratedTypesInfo>(); foreach (XmlProviderInterfaceConfigurationElement element in _dataTypeConfigurationElements) { var dataTypeDescriptor = GetDataTypeDescriptorNotNull(element); Type interfaceType = null; try { if (!dataTypes.TryGetValue(dataTypeDescriptor.DataTypeId, out interfaceType) || interfaceType == null) { Log.LogWarning(LogTitle, "The data interface type '{0}' does not exist and is not code generated. It will not be usable", dataTypeDescriptor.TypeManagerTypeName); continue; } storesToLoad.Add(BuildGeneratedTypesInfo(dataTypeDescriptor, interfaceType, element)); } catch (Exception ex) { if (interfaceType != null) { DataProviderRegistry.AddKnownDataType(interfaceType, _dataProviderContext.ProviderName); } Log.LogError(LogTitle, "Failed initialization for the datatype {{{0}}}, {1}", dataTypeDescriptor.DataTypeId, dataTypeDescriptor.TypeManagerTypeName); Log.LogError(LogTitle, ex); } } CompileMissingTypes(storesToLoad); foreach (var storeToLoad in storesToLoad) { try { var xmlDataTypeStoreDataScopes = new List<XmlDataTypeStoreDataScope>(); foreach (DataScopeConfigurationElement dataScopeConfigurationElement in storeToLoad.Element.ConfigurationStores) { var xmlDataTypeStoreDataScope = new XmlDataTypeStoreDataScope { DataScopeName = dataScopeConfigurationElement.DataScope, CultureName = dataScopeConfigurationElement.CultureName, ElementName = dataScopeConfigurationElement.ElementName, Filename = Path.Combine(_fileStoreDirectory, dataScopeConfigurationElement.Filename) }; xmlDataTypeStoreDataScopes.Add(xmlDataTypeStoreDataScope); } XmlDataTypeStore xmlDateTypeStore = xmlDataTypeStoreCreator.CreateStoreResult(storeToLoad.DataTypeDescriptor, storeToLoad.DataProviderHelperClass, storeToLoad.DataIdClass, xmlDataTypeStoreDataScopes); AddDataTypeStore(storeToLoad.DataTypeDescriptor, storeToLoad.InterfaceType, xmlDateTypeStore); } catch (Exception ex) { DataProviderRegistry.AddKnownDataType(storeToLoad.InterfaceType, _dataProviderContext.ProviderName); Log.LogError(LogTitle, "Failed initialization for the datatype {{{0}}}, {1}", storeToLoad.DataTypeDescriptor.DataTypeId, storeToLoad.DataTypeDescriptor.TypeManagerTypeName); Log.LogError(LogTitle, ex); } } } /// <summary> /// Loads all the data types referenced in the provider's configuration file. /// </summary> private static Dictionary<Guid, Type> LoadDataTypes(IEnumerable<XmlProviderInterfaceConfigurationElement> configurationElements) { var dataTypeDescriptors = new List<DataTypeDescriptor>(); foreach (XmlProviderInterfaceConfigurationElement element in configurationElements) { var dataTypeDescriptor = GetDataTypeDescriptorNotNull(element); dataTypeDescriptors.Add(dataTypeDescriptor); } return DataTypeTypesManager.GetDataTypes(dataTypeDescriptors); } private static DataTypeDescriptor GetDataTypeDescriptorNotNull(XmlProviderInterfaceConfigurationElement element) { Guid dataTypeId = element.DataTypeId; var dataTypeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(dataTypeId, true); if (dataTypeDescriptor == null) { throw NewConfigurationException(element, "Failed to get a DataTypeDescriptor by id '{0}'".FormatWith(dataTypeId)); } return dataTypeDescriptor; } private void AddDataTypeStore(DataTypeDescriptor dataTypeDescriptor, Type interfaceType, XmlDataTypeStore xmlDateTypeStore) { bool interfaceValidated = DataTypeValidationRegistry.Validate(interfaceType, dataTypeDescriptor); if (xmlDateTypeStore != null && interfaceValidated) { _xmlDataTypeStoresContainer.AddSupportedDataTypeStore(interfaceType, xmlDateTypeStore); DataProviderRegistry.AddNewDataType(interfaceType, _dataProviderContext.ProviderName); } else { _xmlDataTypeStoresContainer.AddKnownInterface(interfaceType); } } private void UpdateDataTypeStore(DataTypeDescriptor dataTypeDescriptor, Type interfaceType, XmlDataTypeStore xmlDateTypeStore) { _xmlDataTypeStoresContainer.UpdateSupportedDataTypeStore(interfaceType, xmlDateTypeStore); } private bool EnsureNeededTypes(DataTypeDescriptor dataTypeDescriptor, out Type dataProviderHelperType, out Type dataIdClassType, bool forceCompile = false) { lock (_lock) { // Getting the interface (ensuring that it exists) Type interfaceType = DataTypeTypesManager.GetDataType(dataTypeDescriptor); if (interfaceType == null) { dataProviderHelperType = null; dataIdClassType = null; return false; } string dataProviderHelperClassFullName, dataIdClassFullName; GetGeneratedClassNames(dataTypeDescriptor, out dataProviderHelperClassFullName, out dataIdClassFullName); dataProviderHelperType = TypeManager.TryGetType(dataProviderHelperClassFullName); dataIdClassType = TypeManager.TryGetType(dataIdClassFullName); if (!forceCompile) { forceCompile = CodeGenerationManager.IsRecompileNeeded(interfaceType, new[] { dataProviderHelperType, dataIdClassType }); } if (forceCompile) { var codeGenerationBuilder = new CodeGenerationBuilder(_dataProviderContext.ProviderName + ":" + dataTypeDescriptor.Name); // XmlDataProvider types var codeBuilder = new XmlDataProviderCodeBuilder(_dataProviderContext.ProviderName, codeGenerationBuilder); codeBuilder.AddDataType(dataTypeDescriptor); DataWrapperCodeGenerator.AddDataWrapperClassCode(codeGenerationBuilder, dataTypeDescriptor); IEnumerable<Type> types = CodeGenerationManager.CompileRuntimeTempTypes(codeGenerationBuilder, false); dataProviderHelperType = types.Single(f => f.FullName == dataProviderHelperClassFullName); dataIdClassType = types.Single(f => f.FullName == dataIdClassFullName); } return true; } } private void GetGeneratedClassNames(DataTypeDescriptor dataTypeDescriptor, out string dataProviderHelperClassFullName, out string dataIdClassFullName) { string namespaceName = NamesCreator.MakeNamespaceName(_dataProviderContext.ProviderName); dataProviderHelperClassFullName = namespaceName + "." + NamesCreator.MakeDataProviderHelperClassName(dataTypeDescriptor); dataIdClassFullName = namespaceName + "." + NamesCreator.MakeDataIdClassName(dataTypeDescriptor); } /// <summary> /// Builds a <see cref="GeneratedTypesInfo"/> object that describes information about helper types generation /// </summary> private GeneratedTypesInfo BuildGeneratedTypesInfo(DataTypeDescriptor dataTypeDescriptor, Type interfaceType, XmlProviderInterfaceConfigurationElement element = null) { string dataProviderHelperClassFullName, dataIdClassFullName; GetGeneratedClassNames(dataTypeDescriptor, out dataProviderHelperClassFullName, out dataIdClassFullName); Type dataProviderHelperClass = TypeManager.TryGetType(dataProviderHelperClassFullName); Type dataIdClass = TypeManager.TryGetType(dataIdClassFullName); bool compilationNeeded = CodeGenerationManager.IsRecompileNeeded(interfaceType, new[] { dataProviderHelperClass, dataIdClass }); return new GeneratedTypesInfo { Element = element, DataTypeDescriptor = dataTypeDescriptor, InterfaceType = interfaceType, DataIdClass = dataIdClass, DataIdClassName = dataIdClassFullName, DataProviderHelperClass = dataProviderHelperClass, DataProviderHelperClassName = dataProviderHelperClassFullName, CompilationNeeded = compilationNeeded }; } private void CompileMissingTypes(IList<GeneratedTypesInfo> typesInfo) { // Compiling missing classes if (typesInfo.Any(s => s.CompilationNeeded)) { var codeGenerationBuilder = new CodeGenerationBuilder(_dataProviderContext.ProviderName + ":DataId and helper classes"); var codeBuilder = new XmlDataProviderCodeBuilder(_dataProviderContext.ProviderName, codeGenerationBuilder); foreach (var storeToLoad in typesInfo.Where(s => s.CompilationNeeded)) { codeBuilder.AddDataType(storeToLoad.DataTypeDescriptor); // Compiling some other classes for optimization DataWrapperCodeGenerator.AddDataWrapperClassCode(codeGenerationBuilder, storeToLoad.DataTypeDescriptor); EmptyDataClassCodeGenerator.AddEmptyDataClassTypeCode(codeGenerationBuilder, storeToLoad.DataTypeDescriptor); } var types = CodeGenerationManager.CompileRuntimeTempTypes(codeGenerationBuilder, false).ToDictionary(type => type.FullName); foreach (var storeToLoad in typesInfo.Where(s => s.CompilationNeeded)) { storeToLoad.DataIdClass = types[storeToLoad.DataIdClassName]; storeToLoad.DataProviderHelperClass = types[storeToLoad.DataProviderHelperClassName]; } } } private class GeneratedTypesInfo { public XmlProviderInterfaceConfigurationElement Element; public DataTypeDescriptor DataTypeDescriptor; public Type InterfaceType; public Type DataProviderHelperClass; public Type DataIdClass; public string DataProviderHelperClassName; public string DataIdClassName; public bool CompilationNeeded; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/XmlDataTypeStore.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Plugins.Data.DataProviders.XmlDataProvider.Foundation; using System.Xml.Linq; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider { /// <summary> /// This class contains information used by the XmlDataProvider /// when handling CRUD operations. /// There exists one of these per data type. /// This class contains one entry per data-scope/locale-scope that contains /// the filename and element name. /// </summary> [DebuggerDisplay("{" + nameof(DataTypeDescriptor) + "}")] internal sealed class XmlDataTypeStore { private IXmlDataProviderHelper _helper; private readonly IEnumerable<XmlDataTypeStoreDataScope> _xmlDateTypeStoreDataScopes; public XmlDataTypeStore(DataTypeDescriptor dataTypeDescriptor, Type dataProviderHelperType, Type dataIdClassType, IEnumerable<XmlDataTypeStoreDataScope> xmlDateTypeStoreDataScopes, bool isGeneratedDataType) { DataTypeDescriptor = dataTypeDescriptor ?? throw new ArgumentNullException(nameof(dataTypeDescriptor)); DataProviderHelperType = dataProviderHelperType ?? throw new ArgumentNullException(nameof(dataProviderHelperType)); DataIdClassType = dataIdClassType ?? throw new ArgumentNullException(nameof(dataIdClassType)); IsGeneratedDataType = isGeneratedDataType; _xmlDateTypeStoreDataScopes = xmlDateTypeStoreDataScopes.Evaluate(); var ordering = new List<Func<XElement, IComparable>>(); foreach (string key in dataTypeDescriptor.KeyPropertyNames) { XName localKey = key; ordering.Add(f => (string)f.Attribute(localKey) ?? ""); } Func<IEnumerable<XElement>, IOrderedEnumerable<XElement>> orderer = f => ordering.Skip(1).Aggregate(f.OrderBy(ordering.First()), Enumerable.ThenBy); foreach (XmlDataTypeStoreDataScope xmlDataTypeStoreDataScope in _xmlDateTypeStoreDataScopes) { DataScopeIdentifier dataScopeIdentifier = DataScopeIdentifier.Deserialize(xmlDataTypeStoreDataScope.DataScopeName); CultureInfo culture = CultureInfo.CreateSpecificCulture(xmlDataTypeStoreDataScope.CultureName); Type dataType = dataTypeDescriptor.GetInterfaceType(); Action cacheFlush = () => DataEventSystemFacade.FireExternalStoreChangedEvent(dataType, dataScopeIdentifier.ToPublicationScope(), culture); XmlDataProviderDocumentCache.RegisterExternalFileChangeAction(xmlDataTypeStoreDataScope.Filename, cacheFlush); XmlDataProviderDocumentWriter.RegisterFileOrderer(xmlDataTypeStoreDataScope.Filename, orderer); } } public DataTypeDescriptor DataTypeDescriptor { get; } /// <summary> /// This is a implementation of <see cref="IXmlDataProviderHelper"/> and <see cref="Composite.Plugins.Data.DataProviders.XmlDataProvider.CodeGeneration.DataProviderHelperBase"/> /// </summary> public Type DataProviderHelperType { get; } public Type DataIdClassType { get; } public bool IsGeneratedDataType { get; } public bool HasDataScopeName(DataScopeIdentifier dataScopeIdentifier) { return _xmlDateTypeStoreDataScopes.Any(f => f.DataScopeName == dataScopeIdentifier.Name); } public XmlDataTypeStoreDataScope GetDataScopeForType(Type type) { var currentDataScope = DataScopeManager.MapByType(type); var culture = LocalizationScopeManager.MapByType(type); return GetDataScope(currentDataScope, culture, type); } public XmlDataTypeStoreDataScope GetDataScope(DataScopeIdentifier dataScope, CultureInfo culture, Type type) { string dataScopeName = dataScope.Name; Verify.That(HasDataScopeName(dataScope), "The store named '{0}' is not supported for data type '{1}'", dataScopeName, type); string cultureName = culture.Name; XmlDataTypeStoreDataScope dateTypeStoreDataScope = _xmlDateTypeStoreDataScopes.SingleOrDefault(f => f.DataScopeName == dataScopeName && f.CultureName == cultureName); if (dateTypeStoreDataScope == null) { if (culture.Equals(CultureInfo.InvariantCulture) && DataLocalizationFacade.IsLocalized(type)) { throw new InvalidOperationException($"Failed to get data for type '{type.FullName}', no localization scope is provided for a localized type."); } throw new InvalidOperationException("Failed to get '{0}' data for data scope ({1}, {2})" .FormatWith(type.FullName, dataScopeName, culture.Equals(CultureInfo.InvariantCulture) ? "invariant" : cultureName)); } return dateTypeStoreDataScope; } internal IEnumerable<XmlDataTypeStoreDataScope> XmlDataTypeStoreDataScopes => _xmlDateTypeStoreDataScopes; public IXmlDataProviderHelper Helper { get { if (_helper == null) { _helper = (IXmlDataProviderHelper)Activator.CreateInstance(this.DataProviderHelperType); } return _helper; } } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/XmlDataTypeStoreCreator.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Xml.Linq; using Composite.Core.Xml; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Plugins.Data.DataProviders.XmlDataProvider.Foundation; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider { internal class XmlDataTypeStoreCreator { private readonly string _fileStoreDirectory; /// <summary> /// </summary> /// <param name="fileStoreDirectory"></param> public XmlDataTypeStoreCreator(string fileStoreDirectory) { _fileStoreDirectory = fileStoreDirectory; } /// <summary> /// This class is used to create <see cref="XmlDataTypeStore"/>. /// Either for existing stores or for just newly created/added stores. /// There exist one store for each data type that the provider handles. /// While the <see cref="XmlDataTypeStore"/> is created, the input and /// configuration is validated. /// </summary> /// <param name="dataTypeDescriptor"></param> /// <param name="dataProviderHelperClassType">The runtime type for the generated implementation of <see cref="IXmlDataProviderHelper"/></param> /// <param name="dataIdClassType">The runtime type for the generated data id class.</param> /// <param name="xmlDataTypeStoreDataScopes">If this is null, default values will be created.</param> /// <returns> /// Returns a <see cref="XmlDataTypeStore"/> if it is valid, else null /// </returns> public XmlDataTypeStore CreateStoreResult(DataTypeDescriptor dataTypeDescriptor, Type dataProviderHelperClassType, Type dataIdClassType, IEnumerable<XmlDataTypeStoreDataScope> xmlDataTypeStoreDataScopes) { if (xmlDataTypeStoreDataScopes == null) { var defaultDataScopes = new List<XmlDataTypeStoreDataScope>(); IEnumerable<string> cultureNames; if (dataTypeDescriptor.Localizeable) { cultureNames = DataLocalizationFacade.ActiveLocalizationNames; } else { cultureNames = new[] { CultureInfo.InvariantCulture.Name }; } foreach (DataScopeIdentifier dataScopeIdentifier in dataTypeDescriptor.DataScopes.Distinct()) { foreach (string cultureName in cultureNames) { var defaultXmlDataTypeStoreDataScope = new XmlDataTypeStoreDataScope { DataScopeName = dataScopeIdentifier.Name, CultureName = cultureName, ElementName = NamesCreator.MakeElementName(dataTypeDescriptor), Filename = Path.Combine(_fileStoreDirectory, NamesCreator.MakeFileName(dataTypeDescriptor, dataScopeIdentifier, cultureName)) }; var document = new XDocument(new XElement(defaultXmlDataTypeStoreDataScope.ElementName)); document.SaveToFile(defaultXmlDataTypeStoreDataScope.Filename); defaultDataScopes.Add(defaultXmlDataTypeStoreDataScope); } } xmlDataTypeStoreDataScopes = defaultDataScopes; } return new XmlDataTypeStore(dataTypeDescriptor, dataProviderHelperClassType, dataIdClassType, xmlDataTypeStoreDataScopes, dataTypeDescriptor.IsCodeGenerated); } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/XmlDataTypeStoreDataScope.cs ================================================  namespace Composite.Plugins.Data.DataProviders.XmlDataProvider { internal sealed class XmlDataTypeStoreDataScope { internal string DataScopeName { get; set; } internal string CultureName { get; set; } internal string Filename { get; set; } internal string ElementName { get; set; } } } ================================================ FILE: Composite/Plugins/Data/DataProviders/XmlDataProvider/XmlDataTypeStoresContainer.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using Composite.Data; namespace Composite.Plugins.Data.DataProviders.XmlDataProvider { internal sealed class XmlDataTypeStoresContainer { private readonly string _providerName; private readonly List<Type> _supportedInterfaces = new List<Type>(); private readonly List<Type> _knownInterfaces = new List<Type>(); private readonly List<Type> _generatedInterfaces = new List<Type>(); // Data type -> XmlDataTypeStore private readonly Dictionary<Type, XmlDataTypeStore> _dataTypeStores = new Dictionary<Type, XmlDataTypeStore>(); public XmlDataTypeStoresContainer(string providerName) { _providerName = providerName; } /// <summary> /// All working data types /// </summary> public IEnumerable<Type> SupportedInterfaces => _supportedInterfaces; /// <summary> /// All data types, including non working due to config error or something else /// </summary> public IEnumerable<Type> KnownInterfaces => _knownInterfaces; /// <summary> /// All working generated data types /// </summary> public IEnumerable<Type> GeneratedInterfaces => _generatedInterfaces; public XmlDataTypeStore GetDataTypeStore(Type interfaceType) { XmlDataTypeStore result; if (!_dataTypeStores.TryGetValue(interfaceType, out result)) { throw new ArgumentException($"The interface type '{interfaceType}' is not supported by the XmlDataProvider named '{_providerName}"); } return result; } /// <summary> /// This method adds the support of the given data interface type to the xml data provider. /// </summary> /// <param name="interfaceType"></param> /// <param name="xmlDataTypeStore"></param> internal void AddSupportedDataTypeStore(Type interfaceType, XmlDataTypeStore xmlDataTypeStore) { Verify.That(!_dataTypeStores.ContainsKey(interfaceType), $"Interface type {interfaceType.FullName} has already been registered"); _dataTypeStores.Add(interfaceType, xmlDataTypeStore); _supportedInterfaces.Add(interfaceType); AddKnownInterface(interfaceType); if (xmlDataTypeStore.IsGeneratedDataType) { _generatedInterfaces.Add(interfaceType); } } internal void UpdateSupportedDataTypeStore(Type interfaceType, XmlDataTypeStore xmlDataTypeStore) { Guid typeId = interfaceType.GetImmutableTypeId(); Type type = _dataTypeStores.Where(f => f.Value.DataTypeDescriptor.DataTypeId == typeId).Select(f => f.Key).Single(); _dataTypeStores.Remove(type); _dataTypeStores.Add(interfaceType, xmlDataTypeStore); _supportedInterfaces.Remove(type); _supportedInterfaces.Add(interfaceType); _knownInterfaces.Remove(type); _knownInterfaces.Add(interfaceType); } internal void AddKnownInterface(Type interfaceType) { _knownInterfaces.Add(interfaceType); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/AllFunctionsElementProvider/AllFunctionsElementProvider.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Xml; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.C1Console.Forms.DataServices; using Composite.C1Console.Forms.Flows; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.Core.Types; using Composite.Functions; using Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Elements.ElementProviders.AllFunctionsElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ConfigurationElementType(typeof(AllFunctionsElementProviderData))] #pragma warning disable 612 internal sealed class AllFunctionsElementProvider : BaseFunctionProviderElementProvider.BaseFunctionProviderElementProvider, ICustomSearchElementProvider #pragma warning restore 612 { private const string FunctionsProviderType = "functions"; private const string WidgetFunctionsProviderType = "widgetFunctions"; public static readonly ResourceHandle DocumentFunctionsIcon = GetIconHandle("all-functions-generatedocumentation"); private static readonly ResourceHandle TestFunctionIcon = GetIconHandle("base-function-function"); private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); private readonly string _providerType; public AllFunctionsElementProvider(string providerType) { _providerType = providerType; if ((_providerType != FunctionsProviderType) && (_providerType != WidgetFunctionsProviderType)) { throw new ArgumentException(string.Format("The provider type should be 'functions' or 'widgetFunctions'"), providerType); } } protected override void OnContextSetted() { string providerName = GetContext().ProviderName; if (_providerType == FunctionsProviderType) { AuxiliarySecurityAncestorFacade.AddAuxiliaryAncestorProvider(typeof(StandardFunctionProviderEntityToken), new StandardFunctionAuxiliarySecurityAncestorProvider(providerName)); } else { AuxiliarySecurityAncestorFacade.AddAuxiliaryAncestorProvider(typeof(StandardWidgetFunctionProviderEntityToken), new StandardFunctionAuxiliarySecurityAncestorProvider(providerName)); } } protected override string RootFolderLabel { get { if (_providerType == FunctionsProviderType) { return StringResourceSystemFacade.GetString("Composite.Plugins.AllFunctionsElementProvider", "Plugins.AllFunctionsElementProvider.FunctionRootFolderLabel"); } else if (_providerType == WidgetFunctionsProviderType) { return StringResourceSystemFacade.GetString("Composite.Plugins.AllFunctionsElementProvider", "Plugins.AllFunctionsElementProvider.WidgetFunctionRootFolderLabel"); } else { throw new NotImplementedException(); } } } protected override string RootFolderToolTip { get { if (_providerType == FunctionsProviderType) { return StringResourceSystemFacade.GetString("Composite.Plugins.AllFunctionsElementProvider", "Plugins.AllFunctionsElementProvider.FunctionRootFolderToolTip"); } if (_providerType == WidgetFunctionsProviderType) { return StringResourceSystemFacade.GetString("Composite.Plugins.AllFunctionsElementProvider", "Plugins.AllFunctionsElementProvider.WidgetFunctionRootFolderToolTip"); } throw new NotImplementedException(); } } protected override IEnumerable<IFunctionTreeBuilderLeafInfo> OnGetFunctionInfos(SearchToken searchToken) { var castedSearchToken = (AllFunctionsElementProviderSearchToken)searchToken; string loweredKeyword = null; if (searchToken != null) { loweredKeyword = (searchToken.Keyword ?? string.Empty).ToLowerInvariant(); } foreach (string metaFunctionName in this.MetaFunctionNames.OrderBy(f => f)) { IMetaFunction metaFunction = this.GetMetaFunction(metaFunctionName); if (castedSearchToken == null) { yield return new AllFunctionsTreeBuilderLeafInfo { Name = metaFunction.Name, Namespace = metaFunction.Namespace, EntityToken = metaFunction.EntityToken }; continue; } if (!string.IsNullOrEmpty(loweredKeyword)) { if (!metaFunction.CompositeName().ToLowerInvariant().Contains(loweredKeyword)) { continue; } } bool shouldBeIncluded = true; if (!string.IsNullOrEmpty(castedSearchToken.AcceptableTypes) && castedSearchToken.AcceptableTypes != "__None__") { shouldBeIncluded = false; foreach (string typeKey in castedSearchToken.AcceptableTypes.Split(';')) { Type type = TypeManager.GetType(typeKey); // MAW: Negate that string is an IEnumerable - thats just plain stupid. if (type == typeof(IEnumerable) && metaFunction.ReturnType == typeof(String)) { continue; } if (type.IsAssignableFrom(metaFunction.ReturnType) || (metaFunction is IDowncastableFunction && (metaFunction as IDowncastableFunction).ReturnValueIsDowncastable && metaFunction.ReturnType.IsAssignableFrom(type))) { shouldBeIncluded = true; break; } if (metaFunction is IWidgetFunction && metaFunction.ReturnType.IsAssignableFrom(type)) { shouldBeIncluded = true; break; } } } if (shouldBeIncluded) { yield return new AllFunctionsTreeBuilderLeafInfo { Name = metaFunction.Name, Namespace = metaFunction.Namespace, EntityToken = metaFunction.EntityToken }; } } } protected override IEnumerable<ElementAction> OnGetFunctionActions(IFunctionTreeBuilderLeafInfo function) { string functionName = function.Namespace + "." + function.Name; IMetaFunction metaFunction = GetMetaFunction(functionName); bool isWidget = !(metaFunction is IFunction); if (!isWidget) { yield return CreateFunctionTesterAction(functionName); } yield return new ElementAction(new ActionHandle(new FunctionInfoActionToken(functionName, isWidget))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.AllFunctionsElementProvider", "AllFunctionsElementProvider.ViewFunctionInformation"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.AllFunctionsElementProvider", "AllFunctionsElementProvider.ViewFunctionInformationTooltip"), Disabled = false, Icon = CommonElementIcons.Search, ActionLocation = new ActionLocation { ActionType = ActionType.Other, ActionGroup = PrimaryActionGroup, IsInFolder = false, IsInToolbar = true } } }; } protected override IEnumerable<ElementAction> OnGetFolderActions() { yield return new ElementAction(new ActionHandle(new DocumentFunctionsActionToken())) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.AllFunctionsElementProvider", "AllFunctionsElementProvider.GenerateDocumentation"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.AllFunctionsElementProvider", "AllFunctionsElementProvider.GenerateDocumentationTooltip"), Icon = AllFunctionsElementProvider.DocumentFunctionsIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }; } private static ElementAction CreateFunctionTesterAction(string functionName = "") { WorkflowActionToken actionToken = new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Workflows.Plugins.Elements.ElementProviders.AllFunctionsElementProvider.FunctionTesterWorkflow")) { Payload = functionName }; return new ElementAction(new ActionHandle(actionToken)) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.AllFunctionsElementProvider", "AllFunctionsElementProvider.FunctionTester.Label"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.AllFunctionsElementProvider", "AllFunctionsElementProvider.FunctionTester.ToolTip"), Icon = TestFunctionIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }; } protected override IEnumerable<Type> OnGetEntityTokenTypes() { yield break; } protected override IFunctionTreeBuilderLeafInfo OnIsEntityOwner(EntityToken entityToken) { return null; } //protected override TreeLockBehavior OnGetTreeLockBehavior() //{ // return TreeLockBehavior.None; //} private sealed class AllFunctionsTreeBuilderLeafInfo : IFunctionTreeBuilderLeafInfo { public EntityToken EntityToken { get; internal set; } public string Name { get; internal set; } public string Namespace { get; internal set; } } public SearchToken GetNewSearchToken(EntityToken entityToken) { return new AllFunctionsElementProviderSearchToken(); } public XmlReader GetSearchFormDefinition(EntityToken entityToken) { IFormMarkupProvider markupProvider = new FormDefinitionFileMarkupProvider("/Administrative/AllFunctionsElementProviderSearchForm.xml"); return markupProvider.GetReader(); } public Dictionary<string, object> GetSearchFormBindings(EntityToken entityToken) { Dictionary<string, object> bindings = new Dictionary<string, object>(); Dictionary<string, string> types = new Dictionary<string, string>(); types.Add("__None__", "None"); foreach (Type type in this.MetaFunctionSupprtedTypes) { types.Add(TypeManager.SerializeType(type), type.Name); } bindings.Add("Types", types); return bindings; } private IEnumerable<string> MetaFunctionNames { get { switch (_providerType) { case FunctionsProviderType: return FunctionFacade.FunctionNames; case WidgetFunctionsProviderType: return FunctionFacade.WidgetFunctionNames; default: throw new NotImplementedException(); } } } private IMetaFunction GetMetaFunction(string metaFunctionName) { switch (_providerType) { case FunctionsProviderType: return FunctionFacade.GetFunction(metaFunctionName); case WidgetFunctionsProviderType: return FunctionFacade.GetWidgetFunction(metaFunctionName); default: throw new NotImplementedException(); } } private IEnumerable<Type> MetaFunctionSupprtedTypes { get { switch (_providerType) { case FunctionsProviderType: return FunctionFacade.FunctionSupportedTypes; case WidgetFunctionsProviderType: return FunctionFacade.WidgetFunctionSupportedTypes; default: throw new NotImplementedException(); } } } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class AllFunctionsElementProviderSearchToken : SearchToken { /// <exclude /> public static AllFunctionsElementProviderSearchToken Build(Type[] functionReturnValueAccetableTypes) { var token = new AllFunctionsElementProviderSearchToken(); var sb = new StringBuilder(); for (int i = 0; i < functionReturnValueAccetableTypes.Length; i++) { Type type = functionReturnValueAccetableTypes[i]; if (i > 0) { sb.Append(";"); } sb.Append(TypeManager.SerializeType(type)); } token.AcceptableTypes = sb.ToString(); return token; } /// <exclude /> public string AcceptableTypes { get; set; } } [Assembler(typeof(AllFunctionsElementProviderAssembler))] #pragma warning disable 612 internal sealed class AllFunctionsElementProviderData : HooklessElementProviderData #pragma warning restore 612 { private const string _providerTypePropertyName = "providerType"; [ConfigurationProperty(_providerTypePropertyName, IsRequired = true)] public string ProviderType { get { return (string)base[_providerTypePropertyName]; } set { base[_providerTypePropertyName] = value; } } } #pragma warning disable 612 internal sealed class AllFunctionsElementProviderAssembler : IAssembler<IHooklessElementProvider, HooklessElementProviderData> { public IHooklessElementProvider Assemble(IBuilderContext context, HooklessElementProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { #pragma warning restore 612 AllFunctionsElementProviderData data = (AllFunctionsElementProviderData)objectConfiguration; AllFunctionsElementProvider provider = new AllFunctionsElementProvider(data.ProviderType); return provider; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/AllFunctionsElementProvider/AllFunctionsProviderActionExecutor.cs ================================================ using System; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Core.ResourceSystem; using Composite.C1Console.Security; using Composite.Core.WebClient; using Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider; using Composite.Core.Collections; namespace Composite.Plugins.Elements.ElementProviders.AllFunctionsElementProvider { internal sealed class AllFunctionsProviderActionExecutor : IActionExecutor { public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { string functionNamePrefix = ""; if (entityToken.Id.IndexOf('.') > -1) { functionNamePrefix = entityToken.Id.Substring(entityToken.Id.IndexOf('.') + 1); } bool widgets = entityToken.Id.ToLower().Contains("widget"); string currentConsoleId = flowControllerServicesContainer.GetService<IManagementConsoleMessageService>().CurrentConsoleId; string url = UrlUtils.ResolveAdminUrl(string.Format("content/views/functiondoc/FunctionDocumentation.aspx?functionPrefix={0}&widgets={1}", functionNamePrefix, widgets)); ConsoleMessageQueueFacade.Enqueue(new OpenViewMessageQueueItem { Url = url, EntityToken = EntityTokenSerializer.Serialize(entityToken, true), ViewId = Guid.NewGuid().ToString(), ViewType = ViewType.Main, Label = "Documentation" }, currentConsoleId); return null; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/AllFunctionsElementProvider/DocumentFunctionsActionToken.cs ================================================ using Composite.C1Console.Security; using Composite.C1Console.Actions; using System.Collections.Generic; namespace Composite.Plugins.Elements.ElementProviders.AllFunctionsElementProvider { [ActionExecutor(typeof(AllFunctionsProviderActionExecutor))] internal sealed class DocumentFunctionsActionToken : ActionToken { private IEnumerable<PermissionType> _permissionTypes = new PermissionType[] { PermissionType.Read }; public override IEnumerable<PermissionType> PermissionTypes { get { return _permissionTypes; } } public override string Serialize() { return ""; } public static ActionToken Deserialize(string serializedData) { return new DocumentFunctionsActionToken(); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/AllFunctionsElementProvider/FunctionInfoActionExecutor.cs ================================================ using System; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.Core.WebClient; namespace Composite.Plugins.Elements.ElementProviders.AllFunctionsElementProvider { internal sealed class FunctionInfoActionExecutor : IActionExecutor { public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { FunctionInfoActionToken urlActionToken = (FunctionInfoActionToken)actionToken; string currentConsoleId = flowControllerServicesContainer.GetService<IManagementConsoleMessageService>().CurrentConsoleId; string url = UrlUtils.ResolveAdminUrl(@"content/views/functioninfo/ShowFunctionInfo.aspx"); url += "?Name=" + urlActionToken.FunctionName + "&IsWidget=" + urlActionToken.IsWidgetFunction; ConsoleMessageQueueFacade.Enqueue(new OpenViewMessageQueueItem { Url = url, Label = urlActionToken.FunctionName, ViewId = Guid.NewGuid().ToString(), ViewType = ViewType.Main }, currentConsoleId); return null; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/AllFunctionsElementProvider/FunctionInfoActionToken.cs ================================================ using System.Collections.Generic; using System.Text; using Composite.C1Console.Actions; using Composite.C1Console.Security; using Composite.Core.Serialization; namespace Composite.Plugins.Elements.ElementProviders.AllFunctionsElementProvider { [ActionExecutor(typeof(FunctionInfoActionExecutor))] internal sealed class FunctionInfoActionToken : ActionToken { private readonly IEnumerable<PermissionType> _permissionTypes = new[] { PermissionType.Add, PermissionType.Edit, PermissionType.Delete, PermissionType.Read, PermissionType.Administrate }; public string FunctionName { get; private set; } public bool IsWidgetFunction { get; private set; } public FunctionInfoActionToken(string functionName, bool isWidgetFunction = false) { this.FunctionName = functionName; this.IsWidgetFunction = isWidgetFunction; } public override IEnumerable<PermissionType> PermissionTypes { get { return _permissionTypes; } } public override string Serialize() { StringBuilder sb = new StringBuilder(); StringConversionServices.SerializeKeyValuePair(sb, "Name", this.FunctionName); StringConversionServices.SerializeKeyValuePair(sb, "IsWidget", this.IsWidgetFunction); return sb.ToString(); } public static ActionToken Deserialize(string serializedData) { Dictionary<string, string> dic = StringConversionServices.ParseKeyValueCollection(serializedData); string name = StringConversionServices.DeserializeValueString(dic["Name"]); bool isWidget = StringConversionServices.DeserializeValueBool(dic["IsWidget"]); return new FunctionInfoActionToken(name, isWidget); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/AllFunctionsElementProvider/StandardFunctionAuxiliarySecurityAncestorProvider.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Security; using Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider; namespace Composite.Plugins.Elements.ElementProviders.AllFunctionsElementProvider { internal class StandardFunctionAuxiliarySecurityAncestorProvider : IAuxiliarySecurityAncestorProvider { private readonly string _providerName; public StandardFunctionAuxiliarySecurityAncestorProvider(string providerName) { _providerName = providerName; } public Dictionary<EntityToken, IEnumerable<EntityToken>> GetParents(IEnumerable<EntityToken> entityTokens) { Dictionary<EntityToken, IEnumerable<EntityToken>> result = new Dictionary<EntityToken, IEnumerable<EntityToken>>(); foreach (EntityToken entityToken in entityTokens) { string functionName = entityToken.Id; int index = functionName.LastIndexOf('.'); string folderName = functionName.Remove(index); string id = BaseFunctionProviderElementProvider.BaseFunctionProviderElementProvider.CreateId(folderName, _providerName); EntityToken resultEntityToken = new BaseFunctionFolderElementEntityToken(id); if (!result.TryGetValue(entityToken, out IEnumerable<EntityToken> resultEntityTokens)) { resultEntityTokens = new List<EntityToken>(); result.Add(entityToken, resultEntityTokens); } (resultEntityTokens as List<EntityToken>).Add(resultEntityToken); } return result; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/BaseFunctionProviderElementProvider/BaseFunctionFolderElementEntityToken.cs ================================================ using System; using System.Linq; using System.Threading; using Composite.C1Console.Security; using Composite.Core.Extensions; using Newtonsoft.Json; namespace Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(BaseFunctionFolderElementEntityTokenSecurityAncestorProvider))] public sealed class BaseFunctionFolderElementEntityToken : EntityToken { private readonly string _id; private string _elementProviderName; private string _functionNamespace; /// <exclude /> public BaseFunctionFolderElementEntityToken(string elementProviderName, string functionNamespace) { Verify.ArgumentCondition(!elementProviderName.Contains('.'), "elementProviderName", "Function element provider name can't contain '.' symbol in its name"); if (functionNamespace == "") { _id = "ROOT:" + elementProviderName; } else { _id = "ROOT:{0}.{1}".FormatWith(elementProviderName, functionNamespace); } } /// <exclude /> public BaseFunctionFolderElementEntityToken(string id) { _id = id; } /// <exclude /> public override string Type { get { return ""; } } /// <exclude /> public override string Source { get { return ""; } } /// <exclude /> public override string Id { get { return _id; } } /// <exclude /> public override string Serialize() { return DoSerialize(); } /// <summary> /// Gets the function namespace. /// </summary> [JsonIgnore] public string FunctionNamespace { get { ParseId(); return _functionNamespace; } } /// <summary> /// Gets the name of the function provider. /// </summary> /// <value> /// The name of the function provider. /// </value> [JsonIgnore] public string ElementProviderName { get { ParseId(); return _elementProviderName; } } private void ParseId() { if(_elementProviderName != null) return; const string prefix = "ROOT:"; Verify.That(_id.StartsWith(prefix), "Id should start with prefix '{0}'", prefix); string providerAndNamespace = _id.Substring(prefix.Length); int pointOffset = providerAndNamespace.IndexOf('.'); if(pointOffset == -1) { _functionNamespace = null; Thread.MemoryBarrier(); _elementProviderName = providerAndNamespace; } else { _functionNamespace = providerAndNamespace.Substring(pointOffset + 1); Thread.MemoryBarrier(); _elementProviderName = providerAndNamespace.Substring(0, pointOffset); } } /// <exclude /> public static EntityToken Deserialize(string serializedData) { string type, source, id; EntityToken.DoDeserialize(serializedData, out type, out source, out id); return new BaseFunctionFolderElementEntityToken(id); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/BaseFunctionProviderElementProvider/BaseFunctionFolderElementEntityTokenExtensions.cs ================================================ namespace Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider { internal static class BaseFunctionFolderElementEntityTokenExtensions { public static string GetNamespace(this BaseFunctionFolderElementEntityToken entityToken) { int index = entityToken.Id.IndexOf('.'); if (index != -1) { return entityToken.Id.Remove(0, index + 1); } else { return entityToken.Id; } } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/BaseFunctionProviderElementProvider/BaseFunctionFolderElementEntityTokenSecurityAncestorProvider.cs ================================================ using System.Text; using System.Collections.Generic; using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider { internal sealed class BaseFunctionFolderElementEntityTokenSecurityAncestorProvider : ISecurityAncestorProvider { public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { BaseFunctionFolderElementEntityToken token = (BaseFunctionFolderElementEntityToken)entityToken; int index = token.Id.LastIndexOf('.'); if (index != -1) { return new EntityToken[] { new BaseFunctionFolderElementEntityToken(token.Id.Remove(index)) }; } else { return new EntityToken[] { }; } } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/BaseFunctionProviderElementProvider/BaseFunctionProviderElementProvider.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Core.Collections; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.Functions; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.C1Console.Security; using SR = Composite.Core.ResourceSystem.StringResourceSystemFacade; namespace Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class BaseFunctionProviderElementProvider : IHooklessElementProvider, IAuxiliarySecurityAncestorProvider { private ElementProviderContext _context; /// <exclude /> public static ResourceHandle Function { get { return GetIconHandle("base-function-function"); } } /// <exclude /> public static ResourceHandle FunctionError { get { return GetIconHandle("error"); } } /// <exclude /> protected virtual void OnContextSetted() { } /// <exclude /> protected abstract IEnumerable<IFunctionTreeBuilderLeafInfo> OnGetFunctionInfos(SearchToken searchToken); /// <exclude /> protected abstract IEnumerable<Type> OnGetEntityTokenTypes(); /// <exclude /> protected abstract IFunctionTreeBuilderLeafInfo OnIsEntityOwner(EntityToken entityToken); /// <exclude /> protected abstract string RootFolderLabel { get; } /// <exclude /> protected abstract string RootFolderToolTip { get; } /// <exclude /> protected virtual ResourceHandle FolderIcon { get { return CommonElementIcons.Folder; } } /// <exclude /> protected virtual ResourceHandle OpenFolderIcon { get { return CommonElementIcons.FolderOpen; } } /// <exclude /> protected virtual ResourceHandle EmptyFolderIcon { get { return CommonElementIcons.Folder; } } /// <exclude /> protected virtual ResourceHandle FunctionIcon { get { return CommonElementIcons.Data; } } /// <exclude /> protected virtual IEnumerable<ElementAction> OnGetFolderActions() { return null; } /// <exclude /> protected virtual IEnumerable<ElementAction> OnGetFunctionActions(IFunctionTreeBuilderLeafInfo function) { return null; } /// <exclude /> protected virtual TreeLockBehavior OnGetTreeLockBehavior() { return TreeLockBehavior.Normal; } /// <exclude /> public BaseFunctionProviderElementProvider() { foreach (Type entityTokenType in OnGetEntityTokenTypes()) { AuxiliarySecurityAncestorFacade.AddAuxiliaryAncestorProvider(entityTokenType, this); } } /// <exclude /> public ElementProviderContext Context { set { _context = value; OnContextSetted(); } } /// <exclude /> protected ElementProviderContext GetContext() { return _context; } /// <summary> /// Gets the name of the function provider. /// </summary> /// <value> /// The name of the function provider. /// </value> /// <exclude /> /// <exception cref="System.NotImplementedException"></exception> public virtual string FunctionProviderName { get { throw new NotImplementedException(); } } #region Element methods /// <exclude /> public IEnumerable<Element> GetRoots(SearchToken searchToken) { NamespaceTreeBuilder builder = new NamespaceTreeBuilder(OnGetFunctionInfos(searchToken).Cast<INamespaceTreeBuilderLeafInfo>()); bool hasChildren = (builder.RootFolder.SubFolders.Count != 0) || (builder.RootFolder.Leafs.Count != 0); Element element = new Element(_context.CreateElementHandle(new BaseFunctionFolderElementEntityToken(CreateId("", _context.ProviderName)))) { VisualData = new ElementVisualizedData() { Label = RootFolderLabel, ToolTip = RootFolderToolTip, HasChildren = hasChildren, Icon = hasChildren ? this.FolderIcon : this.EmptyFolderIcon, OpenedIcon = OpenFolderIcon } }; element.TreeLockBehavior = OnGetTreeLockBehavior(); IEnumerable<ElementAction> actions = OnGetFolderActions(); if (actions != null) { foreach (ElementAction action in actions) { element.AddAction(action); } } return new List<Element> { element }; } /// <exclude /> public IEnumerable<Element> GetChildren(EntityToken entityToken, SearchToken searchToken) { BaseFunctionFolderElementEntityToken castedEntityToken = (BaseFunctionFolderElementEntityToken)entityToken; string id = castedEntityToken.Id; int index = castedEntityToken.Id.IndexOf('.'); if (index != -1) { id = id.Remove(0, index + 1); } NamespaceTreeBuilder builder = new NamespaceTreeBuilder(OnGetFunctionInfos(searchToken).Cast<INamespaceTreeBuilderLeafInfo>()); NamespaceTreeBuilderFolder folderNode; if (castedEntityToken.Id == CreateId("", _context.ProviderName)) { folderNode = builder.RootFolder; } else { folderNode = builder.GetFolder(id); } List<Element> result = new List<Element>(); if (searchToken == null) { if (folderNode != null) { foreach (NamespaceTreeBuilderFolder node in folderNode.SubFolders.OrderBy(f => f.Name)) { Element element = CreateFolderElement(node); result.Add(element); } foreach (IFunctionTreeBuilderLeafInfo function in folderNode.Leafs) { Element element = CreateFunctionElement(function); element.PropertyBag.Add("ElementType", "application/x-composite-function"); element.PropertyBag.Add("ElementId", IMetaFunctionExtensionMethods.CompositeName(function.Namespace, function.Name)); result.Add(element); } } } else { if (folderNode != null) { foreach (NamespaceTreeBuilderFolder node in folderNode.SubFolders.OrderBy(f => f.Name)) { if (SubTreeContainsToken(node, searchToken)) { Element element = CreateFolderElement(node); result.Add(element); } } foreach (IFunctionTreeBuilderLeafInfo function in folderNode.Leafs) { if (searchToken.Keyword == null || function.Name.Contains(searchToken.Keyword)) { Element element = CreateFunctionElement(function); element.PropertyBag.Add("ElementType", "application/x-composite-function"); element.PropertyBag.Add("ElementId", IMetaFunctionExtensionMethods.CompositeName(function.Namespace, function.Name)); result.Add(element); } } } } return result; } private bool SubTreeContainsToken(NamespaceTreeBuilderFolder folder, SearchToken searchToken) { if (string.IsNullOrEmpty(searchToken.Keyword)) { return true; } if (folder.Name.Contains(searchToken.Keyword)) { return true; } foreach (INamespaceTreeBuilderLeafInfo leaf in folder.Leafs) { if (leaf.Name.Contains(searchToken.Keyword)) { return true; } } foreach (NamespaceTreeBuilderFolder subFolder in folder.SubFolders) { if (SubTreeContainsToken(subFolder, searchToken)) { return true; } } return false; } private Element CreateFolderElement(NamespaceTreeBuilderFolder node) { bool hasChildren = (node.SubFolders.Count != 0) || (node.Leafs.Count != 0); var element = new Element(_context.CreateElementHandle(new BaseFunctionFolderElementEntityToken(CreateId(node, _context.ProviderName)))) { VisualData = new ElementVisualizedData { Label = node.Name, ToolTip = node.Name, HasChildren = (node.SubFolders.Count != 0) || (node.Leafs.Count != 0), Icon = hasChildren ? this.FolderIcon : this.EmptyFolderIcon, OpenedIcon = this.OpenFolderIcon }, TreeLockBehavior = OnGetTreeLockBehavior() }; IEnumerable<ElementAction> actions = OnGetFolderActions(); if (actions != null) { foreach (ElementAction action in actions) { element.AddAction(action); } } return element; } private Element CreateFunctionElement(IFunctionTreeBuilderLeafInfo function) { IMetaFunction functionDetails; if (FunctionFacade.TryGetFunction(out functionDetails, string.Format("{0}.{1}", function.Namespace, function.Name), typeof(IFunction)) == false) { FunctionFacade.TryGetFunction(out functionDetails, string.Format("{0}.{1}", function.Namespace, function.Name), typeof(IWidgetFunction)); } string functionTooltip = (functionDetails == null || string.IsNullOrEmpty(functionDetails.Description) ? function.Name : StringResourceSystemFacade.ParseString(functionDetails.Description)); var intitializationInfo = functionDetails as IFunctionInitializationInfo; bool functionWerentLoadedCorrectly = intitializationInfo != null && !intitializationInfo.FunctionInitializedCorrectly; Element element = new Element(_context.CreateElementHandle(function.EntityToken)) { VisualData = new ElementVisualizedData() { Label = function.Name, ToolTip = functionTooltip, HasChildren = false, Icon = functionWerentLoadedCorrectly ? BaseFunctionProviderElementProvider.FunctionError : BaseFunctionProviderElementProvider.Function } }; element.TreeLockBehavior = OnGetTreeLockBehavior(); IEnumerable<ElementAction> actions = OnGetFunctionActions(function); if (actions != null) { foreach (ElementAction action in actions) { element.AddAction(action); } } return element; } /// <exclude /> public static string CreateId(NamespaceTreeBuilderFolder folderNode, string providerName) { if (folderNode.Namespace == "") { return CreateId(folderNode.Name, providerName); } return CreateId(string.Format("{0}.{1}", folderNode.Namespace, folderNode.Name), providerName); } /// <exclude /> public static string CreateId(string namespaceName, string providerName) { if (namespaceName == "") { return string.Format("ROOT:{0}", providerName); } return string.Format("ROOT:{0}.{1}", providerName, namespaceName); } #endregion /// <exclude /> public Dictionary<EntityToken, IEnumerable<EntityToken>> GetParents(IEnumerable<EntityToken> entityTokens) { Dictionary<EntityToken, IEnumerable<EntityToken>> result = new Dictionary<EntityToken, IEnumerable<EntityToken>>(); foreach (EntityToken entityToken in entityTokens) { IFunctionTreeBuilderLeafInfo functionTreeBuilderLeafInfo = OnIsEntityOwner(entityToken); if (functionTreeBuilderLeafInfo == null) continue; BaseFunctionFolderElementEntityToken parentEntityToken = new BaseFunctionFolderElementEntityToken(CreateId(functionTreeBuilderLeafInfo.Namespace, _context.ProviderName)); result.Add(entityToken, new EntityToken[] { parentEntityToken }); } return result; } /// <exclude /> protected static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/BaseFunctionProviderElementProvider/IFunctionTreeBuilderLeafInfo.cs ================================================ using Composite.C1Console.Security; using Composite.Core.Collections; namespace Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface IFunctionTreeBuilderLeafInfo : INamespaceTreeBuilderLeafInfo { /// <exclude /> EntityToken EntityToken { get; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/DeveloperApplicationProvider/DeveloperApplicationProvider.cs ================================================ using System.Collections.Generic; using System.IO; using System.Linq; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.C1Console.Security; using Composite.C1Console.Trees; using Composite.C1Console.Workflow; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Elements.ElementProviders.DeveloperApplicationProvider { [ConfigurationElementType(typeof(NonConfigurableHooklessElementProvider))] internal sealed class DeveloperApplicationProvider : IHooklessElementProvider, IAuxiliarySecurityAncestorProvider { private ElementProviderContext _context; private static ResourceHandle TreeDefinitionsRootIcon = GetIconHandle("developerapplication-treedefinitionroot"); private static ResourceHandle TreeDefinitionIcon = GetIconHandle("developerapplication-treedefinition"); private static ResourceHandle TreeDefinitionIconAdd = GetIconHandle("developerapplication-treedefinition-add"); private static ResourceHandle TreeDefinitionIconEdit = GetIconHandle("developerapplication-treedefinition-edit"); private static ResourceHandle TreeDefinitionIconDelete = GetIconHandle("developerapplication-treedefinition-delete"); public DeveloperApplicationProvider() { AuxiliarySecurityAncestorFacade.AddAuxiliaryAncestorProvider<DeveloperApplicationProviderEntityToken>(this); foreach (string treeDefinitionFilename in this.TreeDefinitionFilenames) { string filename = Path.GetFileName(treeDefinitionFilename); DeveloperApplicationProviderEntityToken entityToken = new DeveloperApplicationProviderEntityToken(DeveloperApplicationProviderEntityToken.TreeDefinitionId, filename); TreeFacade.AddCustomAttachmentPoint(filename, entityToken); } } public ElementProviderContext Context { set { _context = value; } } public IEnumerable<Element> GetRoots(SearchToken seachToken) { Element treeRootFolderElement = new Element(_context.CreateElementHandle(new DeveloperApplicationProviderEntityToken(DeveloperApplicationProviderEntityToken.TreeRootFolderId))) { VisualData = new ElementVisualizedData { Label = "Tree Definitions", ToolTip = "Tree Definitions", HasChildren = this.TreeDefinitionFilenames.Count() > 0, Icon = TreeDefinitionsRootIcon } }; treeRootFolderElement.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Trees.Workflows.AddTreeDefinitionWorkflow"), PermissionTypePredefined.Add))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeAddTreeDefinitionWorkflow.AddNew.Label"), ToolTip = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeAddTreeDefinitionWorkflow.AddNew.ToolTip"), Icon = TreeDefinitionIconAdd, Disabled = false, ActionLocation = ActionLocation.AddPrimaryActionLocation } }); yield return treeRootFolderElement; } public IEnumerable<Element> GetChildren(EntityToken entityToken, SearchToken seachToken) { if (entityToken.Id == DeveloperApplicationProviderEntityToken.TreeRootFolderId) { foreach (string treeDefinitionFilename in this.TreeDefinitionFilenames) { string filename = Path.GetFileName(treeDefinitionFilename); Element treeDefintionElement = new Element(_context.CreateElementHandle( new DeveloperApplicationProviderEntityToken(DeveloperApplicationProviderEntityToken.TreeDefinitionId, filename))) { VisualData = new ElementVisualizedData { Label = filename, ToolTip = filename, Icon = TreeDefinitionIcon } }; treeDefintionElement.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Trees.Workflows.DeleteTreeDefinitionWorkflow"), PermissionTypePredefined.Delete))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeDeleteTreeDefinitionWorkflow.Delete.Label"), ToolTip = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeDeleteTreeDefinitionWorkflow.Delete.ToolTip"), Icon = TreeDefinitionIconDelete, Disabled = false, ActionLocation = ActionLocation.DeletePrimaryActionLocation } }); treeDefintionElement.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Trees.Workflows.EditTreeDefinitionWorkflow"), PermissionTypePredefined.Edit))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeDeleteTreeDefinitionWorkflow.Edit.Label"), ToolTip = StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeDeleteTreeDefinitionWorkflow.Edit.ToolTip"), Icon = TreeDefinitionIconEdit, Disabled = false, ActionLocation = ActionLocation.EditPrimaryActionLocation } }); yield return treeDefintionElement; } yield break; } else if (entityToken.Id == DeveloperApplicationProviderEntityToken.TreeDefinitionId) { //DeveloperApplicationProviderEntityToken castedEntityToken = (DeveloperApplicationProviderEntityToken)entityToken; //foreach (Element element in TreeFacade.GetElementsByTreeId(castedEntityToken.Filename, entityToken, new Dictionary<string, string>())) //{ // yield return element; //} } yield break; } public Dictionary<EntityToken, IEnumerable<EntityToken>> GetParents(IEnumerable<EntityToken> entityTokens) { Dictionary<EntityToken, IEnumerable<EntityToken>> result = new Dictionary<EntityToken, IEnumerable<EntityToken>>(); foreach (EntityToken entityToken in entityTokens) { if (entityToken is DeveloperApplicationProviderEntityToken) { switch (entityToken.Id) { case DeveloperApplicationProviderEntityToken.TreeDefinitionId: result.Add(entityToken, new EntityToken[] { new DeveloperApplicationProviderEntityToken(DeveloperApplicationProviderEntityToken.TreeRootFolderId) }); break; } } } return result; } private IEnumerable<string> TreeDefinitionFilenames { get { return C1Directory.GetFiles(PathUtil.Resolve(GlobalSettingsFacade.TreeDefinitionsDirectory), "*.xml"); } } private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/DeveloperApplicationProvider/DeveloperApplicationProviderEntityToken.cs ================================================ using System.IO; using Composite.C1Console.Security; using Composite.C1Console.Security.SecurityAncestorProviders; using Composite.Core.Configuration; using Composite.Core.IO; using Newtonsoft.Json; namespace Composite.Plugins.Elements.ElementProviders.DeveloperApplicationProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(NoAncestorSecurityAncestorProvider))] public sealed class DeveloperApplicationProviderEntityToken : EntityToken { private string _id; private string _source; /// <exclude /> public const string TreeRootFolderId = "TreeFolder"; /// <exclude /> public const string TreeDefinitionId = "TreeDefinition"; /// <exclude /> public DeveloperApplicationProviderEntityToken(string id) :this(id, "") { } /// <exclude /> public DeveloperApplicationProviderEntityToken(string id, string source) { _id = id; _source = source; } /// <exclude /> public override string Type { get { return ""; } } /// <exclude /> public override string Source { get { return _source; } } /// <exclude /> public override string Id { get { return _id; } } /// <exclude /> [JsonIgnore] public string Filename { get { return this.Source; } } /// <exclude /> [JsonIgnore] public string FullTreePath { get { return Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.TreeDefinitionsDirectory), this.Filename); } } /// <exclude /> public override string Serialize() { return DoSerialize(); } /// <exclude /> public static EntityToken Deserialize(string serializedEntityToken) { string type, source, id; DoDeserialize(serializedEntityToken, out type, out source, out id); return new DeveloperApplicationProviderEntityToken(id, source); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/DeleteDataWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="DeleteDataWorkflow" Location="30; 30" Size="1164; 996" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="DeleteDataWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="DeleteDataWorkflow" EventHandlerName="cancelEventDrivenActivity"> <StateDesignerConnector.Segments> <ns0:Point X="202" Y="71" /> <ns0:Point X="911" Y="71" /> <ns0:Point X="911" Y="527" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="initialstateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initialstateActivity" EventHandlerName="initialStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="146" /> <ns0:Point X="361" Y="146" /> <ns0:Point X="361" Y="292" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="finializeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finializeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="742" Y="492" /> <ns0:Point X="911" Y="492" /> <ns0:Point X="911" Y="527" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finializeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finializeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1SventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="459" Y="357" /> <ns0:Point X="643" Y="357" /> <ns0:Point X="643" Y="451" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="463" Y="381" /> <ns0:Point X="911" Y="381" /> <ns0:Point X="911" Y="527" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initialstateActivity" Location="63; 105" Size="197; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="initialStateInitializationActivity" Location="71; 136"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="81; 198" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finializeStateActivity" Location="541; 451" Size="205; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="finalizeStateInitializationActivity" Location="537; 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="547; 210" /> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity" Location="547; 270" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="547; 330" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="831; 527" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="cancelEventDrivenActivity" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="step1StateActivity" Location="256; 292" Size="211; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="264; 323"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="confirmDialogFormActivity1" Location="274; 385" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1SventDrivenActivity_Finish" Location="264; 347"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="274; 409" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="274; 469" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="264; 371"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="274; 433" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="274; 493" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/EditFormWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="EditFormWorkflow" Location="30; 30" Size="1160; 645" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="EditFormWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="EditFormWorkflow" EventHandlerName="cancelEventDrivenActivity"> <StateDesignerConnector.Segments> <ns0:Point X="202" Y="71" /> <ns0:Point X="613" Y="71" /> <ns0:Point X="613" Y="103" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initialState" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="initialState" EventHandlerName="initialStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="146" /> <ns0:Point X="266" Y="146" /> <ns0:Point X="266" Y="247" /> <ns0:Point X="186" Y="247" /> <ns0:Point X="186" Y="259" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="saveStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="editStateActivity" SourceConnectionEdge="Right" TargetActivity="saveStateActivity" SourceActivity="editStateActivity" EventHandlerName="eventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="262" Y="324" /> <ns0:Point X="293" Y="324" /> <ns0:Point X="293" Y="289" /> <ns0:Point X="461" Y="289" /> <ns0:Point X="461" Y="297" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="saveStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="saveStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="560" Y="338" /> <ns0:Point X="570" Y="338" /> <ns0:Point X="570" Y="251" /> <ns0:Point X="186" Y="251" /> <ns0:Point X="186" Y="259" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initialState" Location="63; 105" Size="197; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initialStateInitializationActivity" Location="71; 136"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity" Location="81; 198" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="81; 258" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="editStateActivity" Location="92; 259" Size="189; 94" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="editStateInitializationActivity" Location="359; 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="documentFormActivity1" Location="369; 210" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_Save" Location="351; 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="saveHandleExternalEventActivity1" Location="361; 221" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="361; 281" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="saveStateActivity" Location="359; 297" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="finalizeStateInitializationActivity" Location="367; 328"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="saveCodeActivity" Location="377; 390" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="377; 450" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="533; 103" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="cancelEventDrivenActivity" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/GeneratedDataTypesElementDynamicActionTokens.cs ================================================ using Composite.C1Console.Actions; using Composite.C1Console.Actions.Data; using Composite.C1Console.Workflow; using Composite.Core.Application; using Composite.Data; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { /// <summary> /// Here we register default actions for generated data type elements /// </summary> [ApplicationStartup] public static class GeneratedDataTypesElementDynamicActionTokens { /// <exclude /> public static void OnBeforeInitialize() { } /// <exclude /> public static void OnInitialized(DataActionTokenResolver resolver) { resolver.RegisterDefault<IData>(ActionIdentifier.Edit, f => new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.EditDataWorkflow"))); resolver.RegisterDefault<IData>(ActionIdentifier.Delete, f => new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.DeleteDataWorkflow"))); resolver.RegisterDefault<IData>(ActionIdentifier.Duplicate, f => new DuplicateActionToken()); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/GeneratedDataTypesElementProvider.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Reflection; using System.Text; using Composite.C1Console.Actions; using Composite.C1Console.Actions.Data; using Composite.C1Console.Elements; using Composite.C1Console.Elements.ElementProviderHelpers.DataGroupingProviderHelper; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.Core.Serialization; using Composite.Core.Types; using Composite.Core.WebClient; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Plugins_GeneratedDataTypesElementProvider; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { #region ToXml internal sealed class DataTypeDescriptorToXmlActionExecutor : IActionExecutor { public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { GeneratedDataTypesElementProviderTypeEntityToken castedEntityToken = (GeneratedDataTypesElementProviderTypeEntityToken)entityToken; string currentConsoleId = flowControllerServicesContainer.GetService<IManagementConsoleMessageService>().CurrentConsoleId; string url = string.Format("{0}?TypeName={1}", UrlUtils.ResolveAdminUrl("content/views/datatypedescriptor/ToXml.aspx"), System.Web.HttpUtility.UrlEncode(castedEntityToken.SerializedTypeName)); ConsoleMessageQueueFacade.Enqueue( new OpenViewMessageQueueItem { EntityToken = EntityTokenSerializer.Serialize(entityToken, true), Url = url, ViewId = Guid.NewGuid().ToString(), ViewType = ViewType.Main, Label = GeneratedDataTypesElementProvider.GetText("DataTypeDescriptorToXmlLabel") }, currentConsoleId ); return null; } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ActionExecutor(typeof(DataTypeDescriptorToXmlActionExecutor))] public sealed class DataTypeDescriptorToXmlActionToken : ActionToken { private static readonly PermissionType[] _permissionTypes = { PermissionType.Administrate }; /// <exclude /> public override IEnumerable<PermissionType> PermissionTypes => _permissionTypes; /// <exclude /> public override string Serialize() { return "DataTypeDescriptorToXml"; } /// <exclude /> public static ActionToken Deserialize(string serializedData) { return new DataTypeDescriptorToXmlActionToken(); } } #endregion [ConfigurationElementType(typeof(GeneratedDataTypesElementProviderData))] internal sealed class GeneratedDataTypesElementProvider : IHooklessElementProvider, ILocaleAwareElementProvider { private static readonly string LogTitle = typeof (GeneratedDataTypesElementProvider).Name; private ElementProviderContext _providerContext; private readonly bool _websiteItemsView; private DataGroupingProviderHelper _dataGroupingProviderHelper; /// <exclude /> public static ResourceHandle RootOpen => GetIconHandle("generated-root-open"); /// <exclude /> public static ResourceHandle RootClosed => GetIconHandle("generated-root-closed"); /// <exclude /> public static ResourceHandle DynamicDataTypeIconOpen => GetIconHandle("generated-type-open"); /// <exclude /> public static ResourceHandle DynamicDataTypeIconClosed => GetIconHandle("generated-type-closed"); /// <exclude /> public static ResourceHandle InterfaceOpen => GetIconHandle("data-interface-open"); /// <exclude /> public static ResourceHandle InterfaceClosed => GetIconHandle("data-interface-closed"); /// <exclude /> public static ResourceHandle AddDataTypeIcon => GetIconHandle("generated-type-add"); /// <exclude /> public static ResourceHandle EditDataTypeIcon => GetIconHandle("generated-type-edit"); /// <exclude /> public static ResourceHandle DeleteDataTypeIcon => GetIconHandle("generated-type-delete"); /// <exclude /> public static ResourceHandle LocalizeDataTypeIcon => GetIconHandle("generated-type-localize"); /// <exclude /> public static ResourceHandle DelocalizeDataTypeIcon => GetIconHandle("generated-type-delocalize"); /// <exclude /> public static ResourceHandle AddDataIcon => GetIconHandle("generated-type-data-add"); /// <exclude /> public static ResourceHandle DuplicateDataIcon => GetIconHandle("copy"); /// <exclude /> public static ResourceHandle EditDataIcon => GetIconHandle("generated-type-data-edit"); /// <exclude /> public static ResourceHandle DeleteDataIcon => GetIconHandle("generated-type-data-delete"); /// <exclude /> public static ResourceHandle LocalizeDataIcon => GetIconHandle("generated-type-data-localize"); /// <exclude /> public static ResourceHandle ListUnpublishedItemsIcon = GetIconHandle("generated-type-list-unpublished-items"); /// <exclude /> public static ResourceHandle ShowincontentareaIcon = GetIconHandle("generated-type-showincontentarea"); /// <exclude /> public static ResourceHandle EditFormMarkupIcon => GetIconHandle("generated-type-form-markup-edit"); /// <exclude /> public static ResourceHandle ToXmlIcon => GetIconHandle("generated-type-to-xml"); /// <exclude /> public static readonly Dictionary<string, ResourceHandle> DataIconLookup; /// <exclude /> public static ResourceHandle ErrorIcon => GetIconHandle("error"); private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); private static readonly ActionGroup ViewActionGroup = new ActionGroup("View", ActionGroupPriority.PrimaryLow); private static readonly ActionGroup AppendedActionGroup = new ActionGroup("Develop", ActionGroupPriority.GeneralAppendMedium); private static readonly PermissionType[] _addNewInterfaceTypePermissionTypes = { PermissionType.Add }; private static readonly PermissionType[] _editInterfaceTypePermissionTypes = { PermissionType.Edit }; private static readonly PermissionType[] _editFormMarkupPermissionTypes = { PermissionType.Edit }; private static readonly PermissionType[] _deleteInterfaceTypePermissionTypes = { PermissionType.Delete }; private static readonly PermissionType[] _addNewDataPermissionTypes = { PermissionType.Add }; private static readonly PermissionType[] _editDataPermissionTypes = { PermissionType.Edit }; private static readonly PermissionType[] _deleteDataPermissionTypes = { PermissionType.Delete }; private static readonly PermissionType[] _localizeDataPermissionTypes = { PermissionType.Add }; /// <exclude /> static GeneratedDataTypesElementProvider() { DataIconLookup = new Dictionary<string, ResourceHandle> { {GenericPublishProcessController.Draft, DataIconFacade.DataDraftIcon}, {GenericPublishProcessController.AwaitingApproval, DataIconFacade.DataAwaitingApprovalIcon}, {GenericPublishProcessController.AwaitingPublication, DataIconFacade.DataAwaitingPublicationIcon}, {GenericPublishProcessController.Published, DataIconFacade.DataPublishedIcon} }; } /// <exclude /> public GeneratedDataTypesElementProvider(bool onlyShowGlobalDatas) { _websiteItemsView = onlyShowGlobalDatas; } /// <exclude /> public ElementProviderContext Context { set { _providerContext = value; _dataGroupingProviderHelper = new DataGroupingProviderHelper(_providerContext) { FolderOpenIcon = InterfaceOpen, FolderClosedIcon = InterfaceClosed, OnCreateLeafElement = GetElementFromData, OnCreateGhostedLeafElement = GetGhostedElementFromData, OnCreateDisabledLeafElement = GetDisabledElementFromData, OnAddActions = AddGroupFolderActions, OnGetRootParentEntityToken = GetRootParentEntityToken, OnOwnsType = type => { if (!type.IsGenerated() && !type.IsStaticDataType()) return false; if (PageFolderFacade.GetAllFolderTypes().Contains(type)) return false; if (PageMetaDataFacade.GetAllMetaDataTypes().Contains(type)) return false; return !_websiteItemsView || IsTypeWhiteListed(type); }, OnGetPayload = token => null }; } } /// <exclude /> public bool ContainsLocalizedData { get { return DataFacade.GetGeneratedInterfaces().Any(DataLocalizationFacade.IsLocalized); } } /// <exclude /> public IEnumerable<Element> GetRoots(SearchToken seachToken) { List<Element> roots = new List<Element>(); Element globalDataElement; if (_websiteItemsView) { globalDataElement = new Element(_providerContext.CreateElementHandle(new GeneratedDataTypesElementProviderRootEntityToken(_providerContext.ProviderName, GeneratedDataTypesElementProviderRootEntityToken.GlobalDataTypeFolderId))) { VisualData = new ElementVisualizedData { Label = Texts.GlobalDataFolderLabel_OnlyGlobalData, ToolTip = Texts.GlobalDataFolderToolTip_OnlyGlobalData, HasChildren = true, Icon = GeneratedDataTypesElementProvider.InterfaceClosed, OpenedIcon = GeneratedDataTypesElementProvider.InterfaceOpen } }; } else { globalDataElement = new Element(_providerContext.CreateElementHandle(new GeneratedDataTypesElementProviderRootEntityToken(_providerContext.ProviderName, GeneratedDataTypesElementProviderRootEntityToken.GlobalDataTypeFolderId))) { VisualData = new ElementVisualizedData { Label = Texts.GlobalDataFolderLabel, ToolTip = Texts.GlobalDataFolderToolTip, HasChildren = GlobalDataTypeFacade.GetAllGlobalDataTypes().Any() || DataFacade.GetAllKnownInterfaces().Any(t => t.IsStaticDataType()), Icon = GeneratedDataTypesElementProvider.RootClosed, OpenedIcon = GeneratedDataTypesElementProvider.RootOpen } }; } if (!_websiteItemsView) { globalDataElement.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.AddNewInterfaceTypeWorkflow"), _addNewInterfaceTypePermissionTypes) { Payload = _providerContext.ProviderName })) { VisualData = new ActionVisualizedData { Label = GetText("Add"), ToolTip = GetText("AddToolTip"), Icon = GeneratedDataTypesElementProvider.AddDataTypeIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); } if (_websiteItemsView) { globalDataElement.AddAction( new ElementAction(new ActionHandle(new ViewUnpublishedItemsActionToken())) { VisualData = new ActionVisualizedData { Label = GetText("ViewUnpublishedItems"), ToolTip = GetText("ViewUnpublishedItemsToolTip"), Icon = GeneratedDataTypesElementProvider.ListUnpublishedItemsIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = true, ActionGroup = ViewActionGroup } } }); } roots.Add(globalDataElement); if (!_websiteItemsView) { bool pageDataFolderHasChildren = PageFolderFacade.GetAllFolderTypes().Any(); var pageDataFolderElement = new Element(_providerContext.CreateElementHandle(new GeneratedDataTypesElementProviderRootEntityToken(_providerContext.ProviderName, GeneratedDataTypesElementProviderRootEntityToken.PageDataFolderTypeFolderId))) { VisualData = new ElementVisualizedData { Label = GetText("PageDataFolderDataFolderLabel"), ToolTip = GetText("PageDataFolderDataFolderToolTip"), HasChildren = pageDataFolderHasChildren, Icon = GeneratedDataTypesElementProvider.RootClosed, OpenedIcon = GeneratedDataTypesElementProvider.RootOpen } }; pageDataFolderElement.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.AddNewInterfaceTypeWorkflow"), _addNewInterfaceTypePermissionTypes) { Payload = TypeManager.SerializeType(typeof(IPage)) })) { VisualData = new ActionVisualizedData { Label = GetText("AddDataFolder"), ToolTip = GetText("AddDataFolderToolTip"), Icon = GeneratedDataTypesElementProvider.AddDataTypeIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); roots.Add(pageDataFolderElement); bool pageMetaDataHasChildren = PageMetaDataFacade.GetAllMetaDataTypes().Any(); var pageMetaDataElement = new Element(_providerContext.CreateElementHandle(new GeneratedDataTypesElementProviderRootEntityToken(_providerContext.ProviderName, GeneratedDataTypesElementProviderRootEntityToken.PageMetaDataTypeFolderId))) { VisualData = new ElementVisualizedData { Label = GetText("PageMetaDataFolderLabel"), ToolTip = GetText("PageMetaDataFolderToolTip"), HasChildren = pageMetaDataHasChildren, Icon = GeneratedDataTypesElementProvider.RootClosed, OpenedIcon = GeneratedDataTypesElementProvider.RootOpen } }; pageMetaDataElement.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.AddNewCompositionTypeWorkflow"), _addNewInterfaceTypePermissionTypes) { Payload = TypeManager.SerializeType(typeof(IPage)) })) { VisualData = new ActionVisualizedData { Label = GetText("AddMetaDataLabel"), ToolTip = GetText("AddMetaDataToolTip"), Icon = GeneratedDataTypesElementProvider.AddDataTypeIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); roots.Add(pageMetaDataElement); } return roots; } /// <exclude /> public IEnumerable<Element> GetForeignRoots(SearchToken searchToken) { return GetRoots(searchToken); } /// <exclude /> public IEnumerable<Element> GetChildren(EntityToken entityToken, SearchToken searchToken) { return GetChildren(entityToken, searchToken, false); } /// <exclude /> public IEnumerable<Element> GetForeignChildren(EntityToken entityToken, SearchToken searchToken) { return GetChildren(entityToken, searchToken, true); } private IEnumerable<Element> GetChildren(EntityToken entityToken, SearchToken searchToken, bool showForeignChildren) { if (entityToken is GeneratedDataTypesElementProviderRootEntityToken rootEntityToken) { return GetRootChildren(searchToken, rootEntityToken); } if (entityToken is GeneratedDataTypesElementProviderTypeEntityToken castedEntityToken) { string typeManagerName = castedEntityToken.SerializedTypeName; Type type = TypeManager.TryGetType(typeManagerName); if (type == null) { return Enumerable.Empty<Element>(); } // These are never shown in the tree if (typeof(IPageMetaData).IsAssignableFrom(type)) { return Enumerable.Empty<Element>(); } IEnumerable<Element> elements = _dataGroupingProviderHelper.GetRootGroupFolders(type, entityToken, showForeignChildren); return elements.ToList(); } if (entityToken is DataGroupingProviderHelperEntityToken dataGroupingEntityToken) { List<Element> elements = _dataGroupingProviderHelper .GetGroupChildren(dataGroupingEntityToken, showForeignChildren).ToList(); return elements; } if (entityToken is DataEntityToken) { return Enumerable.Empty<Element>(); } throw new InvalidOperationException("This code should not be reachable"); } private List<Element> GetRootChildren(SearchToken searchToken, GeneratedDataTypesElementProviderRootEntityToken entityToken) { if (entityToken.Id == GeneratedDataTypesElementProviderRootEntityToken.GlobalDataTypeFolderId) { return GetGlobalDataTypesElements(searchToken).OrderBy(f => f.VisualData.Label).ToList(); } if (entityToken.Id == GeneratedDataTypesElementProviderRootEntityToken.PageDataFolderTypeFolderId) { return GetPageFolderDataTypesElements(searchToken).OrderBy(f => f.VisualData.Label).ToList(); } if (entityToken.Id == GeneratedDataTypesElementProviderRootEntityToken.PageMetaDataTypeFolderId) { return GetPageMetaDataTypesElements(searchToken).OrderBy(f => f.VisualData.Label).ToList(); } throw new InvalidOperationException("This code should not be reachable"); } private List<Element> GetGlobalDataTypesElements(SearchToken searchToken) { List<Element> elements = new List<Element>(); IEnumerable<Type> interfaceList = DataFacade.GetAllInterfaces(UserType.Developer).Where(i => i.IsStaticDataType() || i.IsGenerated()); interfaceList = interfaceList.OrderBy(t => t.FullName); interfaceList = interfaceList.Except(PageFolderFacade.GetAllFolderTypes()); interfaceList = interfaceList.Except(PageMetaDataFacade.GetAllMetaDataTypes()); if (searchToken.IsValidKeyword()) { interfaceList = interfaceList.Where(x => x.FullName.ToLower().Contains(searchToken.Keyword.ToLower())).ToList(); } var interfaces = new Dictionary<Type, DataTypeDescriptor>(); foreach (var type in interfaceList) { DataTypeDescriptor dataTypeDescriptor; try { dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(type); } catch (Exception ex) { Log.LogError(LogTitle, ex); continue; } if (dataTypeDescriptor != null) { interfaces.Add(type, dataTypeDescriptor); } } IEnumerable<KeyValuePair<Type, DataTypeDescriptor>> sortedInterfaces = interfaces; if (_websiteItemsView) { sortedInterfaces = interfaces.OrderBy(f => f.Value.Title); } List<string> whiteList = DataFacade.GetData<IGeneratedTypeWhiteList>().Select(element => element.TypeManagerTypeName).ToList(); foreach (var kvp in sortedInterfaces) { Type type = kvp.Key; DataTypeDescriptor dataTypeDescriptor = kvp.Value; DataTypeDescriptor tempDescriptor; bool storeCreated = DynamicTypeManager.TryGetDataTypeDescriptor(type.GetImmutableTypeId(), out tempDescriptor); string typeName = TypeManager.SerializeType(type); if (_websiteItemsView && !whiteList.Contains(typeName)) { continue; } DataScopeIdentifier dataScopeIdentifier = DataScopeIdentifier.Public; if (typeof(IPublishControlled).IsAssignableFrom(type)) { dataScopeIdentifier = DataScopeIdentifier.Administrated; } Exception queryDataException = null; bool hasChildren = false; try { using (new DataScope(dataScopeIdentifier)) { hasChildren = storeCreated && DataFacade.GetData(type).Any(); if (!hasChildren && storeCreated && DataLocalizationFacade.IsLocalized(type)) { using (new DataScope(UserSettings.ForeignLocaleCultureInfo)) { hasChildren |= DataFacade.GetData(type).Any(); } } } } catch (Exception ex) { Log.LogError(LogTitle, ex); queryDataException = ex; } string label = type.FullName; if (_websiteItemsView) { label = dataTypeDescriptor.Title; } bool failedToLoad = queryDataException != null; bool isStaticType = type.IsStaticDataType(); var openIcon = _websiteItemsView || isStaticType ? InterfaceOpen : DynamicDataTypeIconOpen; var closedIcon = _websiteItemsView ||isStaticType ? InterfaceClosed : DynamicDataTypeIconClosed; var element = new Element(_providerContext.CreateElementHandle( new GeneratedDataTypesElementProviderTypeEntityToken(typeName, _providerContext.ProviderName, GeneratedDataTypesElementProviderRootEntityToken.GlobalDataTypeFolderId))) { VisualData = new ElementVisualizedData { Label = label, ToolTip = !failedToLoad ? label : GetNestedExceptionMessage(queryDataException), HasChildren = hasChildren, Icon = !failedToLoad ? closedIcon : ErrorIcon, OpenedIcon = !failedToLoad ? openIcon : ErrorIcon } }; if (storeCreated && !_websiteItemsView) { AddNonShowOnlyGlobalActions(type, typeName, element); } if (storeCreated) { element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.AddNewDataWorkflow"), _addNewDataPermissionTypes) { DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = GetText("AddData"), ToolTip = GetText("AddDataToolTip"), Icon = GeneratedDataTypesElementProvider.AddDataIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); } if (RuntimeInformation.IsDebugBuild) { element.AddAction( new ElementAction(new ActionHandle(new DataTypeDescriptorToXmlActionToken())) { VisualData = new ActionVisualizedData { Label = GetText("ToXmlLabel"), ToolTip = GetText("ToXmlToolTip"), Icon = GeneratedDataTypesElementProvider.ToXmlIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = AppendedActionGroup } } }); } // TODO: add "Create store" action elements.Add(element); } return elements; } private string GetNestedExceptionMessage(Exception queryDataException) { var ex = queryDataException; while (ex is TargetInvocationException) { ex = ex.InnerException; } return ex.Message; } private void AddNonShowOnlyGlobalActions(Type type, string typeName, Element element) { DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(type.GetImmutableTypeId()); bool isEditable = dataTypeDescriptor.IsCodeGenerated; if (DataLocalizationFacade.UseLocalization) { element.AddAction(GetChangeLocalizationElementAction(type, isEditable)); } element.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.EditInterfaceTypeWorkflow"), _editInterfaceTypePermissionTypes) { Payload = _providerContext.ProviderName })) { VisualData = new ActionVisualizedData { Label = GetText("Edit"), ToolTip = GetText("EditToolTip"), Icon = GeneratedDataTypesElementProvider.EditDataTypeIcon, Disabled = !isEditable, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); element.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.DeleteInterfaceTypeWorkflow"), _deleteInterfaceTypePermissionTypes) { Payload = _providerContext.ProviderName })) { VisualData = new ActionVisualizedData { Label = GetText("Delete"), ToolTip = GetText("DeleteToolTip"), Icon = GeneratedDataTypesElementProvider.DeleteDataTypeIcon, Disabled = !isEditable, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); element.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.EditFormWorkflow"), _editFormMarkupPermissionTypes) { Payload = _providerContext.ProviderName, DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = GetText("EditFormMarkup"), ToolTip = GetText("EditFormMarkupToolTip"), Icon = GeneratedDataTypesElementProvider.EditFormMarkupIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); bool exists = DataFacade.GetData<IGeneratedTypeWhiteList>().Any(f => f.TypeManagerTypeName == typeName); element.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType( exists == false ? "Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.AddTypeToWhiteListWorkflow" : "Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.RemoveTypeFromWhiteListWorkflow" ), _addNewInterfaceTypePermissionTypes) { DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = GetText("ShowInContent"), ToolTip = GetText("ShowInContentToolTip"), Icon = GeneratedDataTypesElementProvider.ShowincontentareaIcon, Disabled = false, ActionCheckedStatus = exists == false ? ActionCheckedStatus.Unchecked : ActionCheckedStatus.Checked, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = false, ActionGroup = PrimaryActionGroup } } }); } private static ElementAction GetChangeLocalizationElementAction(Type type, bool isEditable) { if (!DataLocalizationFacade.IsLocalized(type)) { return new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.EnableTypeLocalizationWorkflow"), _editInterfaceTypePermissionTypes))) { VisualData = new ActionVisualizedData { Label = GetText("EnableLocalization"), ToolTip = GetText("EnableLocalizationToolTip"), Icon = GeneratedDataTypesElementProvider.LocalizeDataTypeIcon, Disabled = !DataLocalizationFacade.ActiveLocalizationCultures.Any() || !isEditable, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }; } return new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.DisableTypeLocalizationWorkflow"), _editInterfaceTypePermissionTypes))) { VisualData = new ActionVisualizedData { Label = GetText("DisableLocalization"), ToolTip = GetText("DisableLocalizationToolTip"), Icon = GeneratedDataTypesElementProvider.DelocalizeDataTypeIcon, Disabled = !isEditable, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }; } private List<Element> GetPageFolderDataTypesElements(SearchToken searchToken) { var elements = new List<Element>(); IEnumerable<Type> types = PageFolderFacade.GetAllFolderTypes(); if (searchToken.IsValidKeyword()) { types = types.Where(x => x.FullName.ToLower().Contains(searchToken.Keyword.ToLower())); } foreach (Type type in types) { DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(type.GetImmutableTypeId()); bool isEditable = dataTypeDescriptor.IsCodeGenerated; string typeName = TypeManager.SerializeType(type); var element = new Element(_providerContext.CreateElementHandle(new GeneratedDataTypesElementProviderTypeEntityToken(typeName, _providerContext.ProviderName, GeneratedDataTypesElementProviderRootEntityToken.PageDataFolderTypeFolderId))) { VisualData = new ElementVisualizedData { Label = type.FullName, ToolTip = type.FullName, HasChildren = false, Icon = isEditable ? DynamicDataTypeIconClosed : InterfaceClosed, OpenedIcon = isEditable ? DynamicDataTypeIconOpen : InterfaceOpen } }; if (DataLocalizationFacade.UseLocalization) { element.AddAction(GetChangeLocalizationElementAction(type, true)); } element.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.EditInterfaceTypeWorkflow"), _editInterfaceTypePermissionTypes) { Payload = typeName })) { VisualData = new ActionVisualizedData { Label = GetText("EditDataFolderTypeLabel"), ToolTip = GetText("EditDataFolderTypeToolTip"), Icon = GeneratedDataTypesElementProvider.EditDataTypeIcon, Disabled = !isEditable, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); element.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.DeleteAggregationTypeWorkflow"), _deleteInterfaceTypePermissionTypes) { Payload = typeName })) { VisualData = new ActionVisualizedData { Label = GetText("DeleteDataFolderTypeLabel"), ToolTip = GetText("DeleteDataFolderTypeToolTip"), Icon = GeneratedDataTypesElementProvider.DeleteDataTypeIcon, Disabled = !isEditable, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); element.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.EditFormWorkflow"), _editFormMarkupPermissionTypes) { Payload = _providerContext.ProviderName, DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = GetText("EditFormMarkup"), ToolTip = GetText("EditFormMarkupToolTip"), Icon = GeneratedDataTypesElementProvider.EditFormMarkupIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); elements.Add(element); } return elements; } private List<Element> GetPageMetaDataTypesElements(SearchToken searchToken) { List<Element> elements = new List<Element>(); IEnumerable<Type> types = PageMetaDataFacade.GetAllMetaDataTypes(); if (searchToken.IsValidKeyword()) { types = types.Where(x => x.FullName.ToLower().Contains(searchToken.Keyword.ToLower())); } foreach (Type type in types) { DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(type.GetImmutableTypeId()); bool isEditable = dataTypeDescriptor.IsCodeGenerated; string typeName = TypeManager.SerializeType(type); Element element = new Element(_providerContext.CreateElementHandle(new GeneratedDataTypesElementProviderTypeEntityToken(typeName, _providerContext.ProviderName, GeneratedDataTypesElementProviderRootEntityToken.PageMetaDataTypeFolderId))) { VisualData = new ElementVisualizedData { Label = type.FullName, ToolTip = type.FullName, HasChildren = false, Icon = isEditable ? DynamicDataTypeIconClosed : InterfaceClosed, OpenedIcon = isEditable ? DynamicDataTypeIconOpen : InterfaceOpen } }; if (DataLocalizationFacade.UseLocalization) { element.AddAction(GetChangeLocalizationElementAction(type, isEditable)); } element.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.EditCompositionTypeWorkflow"), _editInterfaceTypePermissionTypes) { Payload = typeName })) { VisualData = new ActionVisualizedData { Label = GetText("EditMetaDataTypeLabel"), ToolTip = GetText("EditMetaDataTypeToolTip"), Icon = GeneratedDataTypesElementProvider.EditDataTypeIcon, Disabled = !isEditable, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); element.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.DeleteCompositionTypeWorkflow"), _deleteInterfaceTypePermissionTypes) { Payload = typeName })) { VisualData = new ActionVisualizedData { Label = GetText("DeleteMetaDataTypeLabel"), ToolTip = GetText("DeleteMetaDataTypeToolTip"), Icon = GeneratedDataTypesElementProvider.DeleteDataTypeIcon, Disabled = !isEditable, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); element.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.EditFormWorkflow"), _editFormMarkupPermissionTypes) { DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = GetText("EditFormMarkup"), ToolTip = GetText("EditFormMarkupToolTip"), Icon = GeneratedDataTypesElementProvider.EditFormMarkupIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); elements.Add(element); } return elements; } private Element GetElementFromData(IData data) { Type type = data.DataSourceId.InterfaceType; string label = data.GetLabel(true); Element element = new Element(_providerContext.CreateElementHandle(data.GetDataEntityToken())) { VisualData = new ElementVisualizedData { Label = label, ToolTip = label, HasChildren = false, Icon = (data is IPublishControlled ? DataIconLookup[((IPublishControlled)data).PublicationStatus] : DataIconFacade.DataPublishedIcon) } }; if (PageMetaDataFacade.GetAllMetaDataTypes().Contains(type) == false) { element.AddAction( new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.Edit, _editDataPermissionTypes))) { VisualData = new ActionVisualizedData { Label = GetText("EditData"), ToolTip = GetText("EditDataToolTip"), Icon = GeneratedDataTypesElementProvider.EditDataIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); element.AddAction( new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.Delete,_deleteDataPermissionTypes))) { VisualData = new ActionVisualizedData { Label = GetText("DeleteData"), ToolTip = GetText("DeleteDataToolTip"), Icon = GeneratedDataTypesElementProvider.DeleteDataIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); element.AddAction( new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.Duplicate, _addNewDataPermissionTypes))) { VisualData = new ActionVisualizedData { Label = GetText("DuplicateData"), ToolTip = GetText("DuplicateDataToolTip"), Icon = GeneratedDataTypesElementProvider.DuplicateDataIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); } return element; } private Element GetGhostedElementFromData(IData data) { string label = string.Format("{0} ({1})", data.GetLabel(true), DataLocalizationFacade.GetCultureTitle(UserSettings.ForeignLocaleCultureInfo)); Element element = new Element(_providerContext.CreateElementHandle(data.GetDataEntityToken())) { VisualData = new ElementVisualizedData { Label = label, ToolTip = label, HasChildren = false, Icon = DataIconFacade.DataGhostedIcon, IsDisabled = false } }; element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.LocalizeDataWorkflow"), _localizeDataPermissionTypes) { Payload = "Global" })) { VisualData = new ActionVisualizedData { Label = GetText("LocalizeData"), ToolTip = GetText("LocalizeDataToolTip"), Icon = GeneratedDataTypesElementProvider.LocalizeDataIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); return element; } private Element GetDisabledElementFromData(IData data) { string label = string.Format("{0} ({1})", data.GetLabel(true), DataLocalizationFacade.GetCultureTitle(UserSettings.ForeignLocaleCultureInfo)); Element element = new Element(_providerContext.CreateElementHandle(data.GetDataEntityToken())) { VisualData = new ElementVisualizedData { Label = label, ToolTip = GetText("DisabledData"), HasChildren = false, Icon = DataIconFacade.DataDisabledIcon, IsDisabled = true } }; return element; } private Element AddGroupFolderActions(Element element, PropertyInfoValueCollection propertyInfoValueCollection) { StringBuilder sb = new StringBuilder(); foreach (var kvp in propertyInfoValueCollection.PropertyValues) { string value = ValueTypeConverter.Convert<string>(kvp.Value); StringConversionServices.SerializeKeyValuePair<string>(sb, kvp.Key.Name, value); } element.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider.AddNewDataWorkflow"), _addNewDataPermissionTypes) { DoIgnoreEntityTokenLocking = true, Payload = sb.ToString() })) { VisualData = new ActionVisualizedData { Label = GetText("AddData"), ToolTip = GetText("AddDataToolTip"), Icon = GeneratedDataTypesElementProvider.AddDataIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); return element; } private static bool IsTypeWhiteListed(Type type) { string typeManagerTypeName = TypeManager.SerializeType(type); IEnumerable<IGeneratedTypeWhiteList> whileList = DataFacade.GetData<IGeneratedTypeWhiteList>(true); return whileList.Any(f => f.TypeManagerTypeName == typeManagerTypeName); } private EntityToken GetRootParentEntityToken(Type type, EntityToken entityToken) { bool isPageFolder = PageFolderFacade.GetAllFolderTypes().Contains(type); if (!isPageFolder) { if (_websiteItemsView && !IsTypeWhiteListed(type)) return null; return new GeneratedDataTypesElementProviderTypeEntityToken( TypeManager.SerializeType(type), _providerContext.ProviderName, GeneratedDataTypesElementProviderRootEntityToken.GlobalDataTypeFolderId ); } if (_websiteItemsView) return null; var groupingEntityToken = entityToken as DataGroupingProviderHelperEntityToken; if (groupingEntityToken != null && !groupingEntityToken.Payload.IsNullOrEmpty()) { // Grouping entity tokens with payload aren't attached to the data type folder in the 'Data' perspective return null; } return new GeneratedDataTypesElementProviderTypeEntityToken( TypeManager.SerializeType(type), _providerContext.ProviderName, GeneratedDataTypesElementProviderRootEntityToken.PageDataFolderTypeFolderId ); } private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } internal static string GetText(string key) { return StringResourceSystemFacade.GetString("Composite.Plugins.GeneratedDataTypesElementProvider", key); } } [Assembler(typeof(GeneratedDataTypesElementProviderAssembler))] internal sealed class GeneratedDataTypesElementProviderData : HooklessElementProviderData { private const string _onlyShowGlobalDatasPropertyName = "onlyShowGlobalDatas"; /// <exclude /> [ConfigurationProperty(_onlyShowGlobalDatasPropertyName, IsRequired = false, DefaultValue = false)] public bool OnlyShowGlobalDatas { get { return (bool)base[_onlyShowGlobalDatasPropertyName]; } set { base[_onlyShowGlobalDatasPropertyName] = value; } } } internal sealed class GeneratedDataTypesElementProviderAssembler : IAssembler<IHooklessElementProvider, HooklessElementProviderData> { public IHooklessElementProvider Assemble(IBuilderContext context, HooklessElementProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { var data = (GeneratedDataTypesElementProviderData)objectConfiguration; return new GeneratedDataTypesElementProvider(data.OnlyShowGlobalDatas); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/GeneratedDataTypesElementProviderRootEntityToken.cs ================================================ using System; using Composite.C1Console.Security; using Composite.C1Console.Security.SecurityAncestorProviders; using Newtonsoft.Json; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(NoAncestorSecurityAncestorProvider))] public sealed class GeneratedDataTypesElementProviderRootEntityToken : EntityToken { private string _source; private string _id; /// <exclude /> public GeneratedDataTypesElementProviderRootEntityToken(string providerName, string id) { _source = providerName; _id = id; } /// <exclude /> public override string Type { get { return ""; } } /// <exclude /> public override string Source { get { return _source; } } /// <exclude /> public override string Id { get { return _id; } } /// <exclude /> public override string Serialize() { return DoSerialize(); } /// <exclude /> public static EntityToken Deserialize(string serializedData) { string type, source, id; DoDeserialize(serializedData, out type, out source, out id); return new GeneratedDataTypesElementProviderRootEntityToken(source, id); } /// <exclude /> [JsonIgnore] public static string GlobalDataTypeFolderId { get { return "GlobalDataTypeFolder"; } } /// <exclude /> [Obsolete("Not used any more")] [JsonIgnore] public static string StaticGlobalDataTypeFolderId { get { return "StaticGlobalDataTypeFolder"; } } /// <exclude /> [JsonIgnore] public static string PageDataFolderTypeFolderId { get { return "PageDataFolderTypeFolder"; } } /// <exclude /> [JsonIgnore] public static string PageMetaDataTypeFolderId { get { return "PageMetaDataTypeFolder"; } } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/GeneratedDataTypesElementProviderSecurityAncestorProvider.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security; using Composite.Core.Types; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { internal sealed class GeneratedDataTypesElementProviderSecurityAncestorProvider : ISecurityAncestorProvider { public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { if (entityToken is GeneratedDataTypesElementProviderRootEntityToken) { yield break; } else if (entityToken is GeneratedDataTypesElementProviderTypeEntityToken) { GeneratedDataTypesElementProviderTypeEntityToken castedToken = entityToken as GeneratedDataTypesElementProviderTypeEntityToken; Type type = TypeManager.TryGetType(castedToken.SerializedTypeName); if (type != null) { yield return new GeneratedDataTypesElementProviderRootEntityToken(entityToken.Source, castedToken.Id); } else { yield return null; } } else { throw new NotImplementedException(); } } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/GeneratedDataTypesElementProviderTypeEntityToken.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security; using Composite.Core; using Composite.Core.Serialization; using Newtonsoft.Json; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(GeneratedDataTypesElementProviderSecurityAncestorProvider))] public sealed class GeneratedDataTypesElementProviderTypeEntityToken : EntityToken { private readonly string _providerName; /// <exclude /> [JsonConstructor] public GeneratedDataTypesElementProviderTypeEntityToken(string serializedTypeName, string source, string id) { Id = id; _providerName = source; this.SerializedTypeName = serializedTypeName; } /// <exclude /> public override string Type => "GeneratedDataTypesElementProvider"; /// <exclude /> public override string Source => _providerName; /// <exclude /> public override string Id { get; } /// <exclude /> public string SerializedTypeName { get; private set; } /// <exclude /> public override string Serialize() { return CompositeJsonSerializer.Serialize(this); } /// <exclude /> public static EntityToken Deserialize(string serializedEntityToken) { EntityToken entityToken; if (CompositeJsonSerializer.IsJsonSerialized(serializedEntityToken)) { entityToken = CompositeJsonSerializer .Deserialize<GeneratedDataTypesElementProviderTypeEntityToken>(serializedEntityToken); } else { entityToken = DeserializeLegacy(serializedEntityToken); Log.LogVerbose(nameof(GeneratedDataTypesElementProviderTypeEntityToken), entityToken.GetType().FullName); } return entityToken; } /// <exclude /> public static EntityToken DeserializeLegacy(string serializedEntityToken) { string type, source, id; Dictionary<string, string> dic; DoDeserialize(serializedEntityToken, out type, out source, out id, out dic); if (dic.ContainsKey("_SerializedTypeName_") == false) { throw new ArgumentException("The serializedEntityToken is not a serialized entity token", "serializedEntityToken"); } string serializedTypeName = StringConversionServices.DeserializeValueString(dic["_SerializedTypeName_"]); return new GeneratedDataTypesElementProviderTypeEntityToken(serializedTypeName, source, id); } /// <exclude /> public override bool Equals(object obj) { return base.Equals(obj) && (obj as GeneratedDataTypesElementProviderTypeEntityToken).SerializedTypeName == this.SerializedTypeName; } /// <exclude /> public override int GetHashCode() { if (this.HashCode == 0) { this.HashCode = GetType().GetHashCode() ^ this.Type.GetHashCode() ^ this.Source.GetHashCode() ^ this.Id.GetHashCode() ^ this.SerializedTypeName.GetHashCode(); } return this.HashCode; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/IGeneratedTypeWhiteList.cs ================================================ using Composite.Data.Hierarchy; using Composite.Data.Hierarchy.DataAncestorProviders; namespace Composite.Data.Types { /// <summary> /// Reference to a generated/static data type that has to be shown in the 'Content' perspective, under 'Website Items' element /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AutoUpdateble] [ImmutableTypeId("{C447589F-B6DE-4f52-A520-F20E05BA2DB5}")] [KeyPropertyName("TypeManagerTypeName")] [DataAncestorProvider(typeof(NoAncestorDataAncestorProvider))] [DataScope(DataScopeIdentifier.AdministratedName)] [Caching(CachingType.Full)] public interface IGeneratedTypeWhiteList : IData { /// <exclude /> [ImmutableFieldId("{60243CA2-7B4A-4982-A7CF-D7557FFE611E}")] [StoreFieldType(PhysicalStoreFieldType.String, 256)] string TypeManagerTypeName { get; set; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/ViewUnpublishedItemsActionToken.cs ================================================ using System.Collections.Generic; using System.Text; using System.Web; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.Core.ResourceSystem; using Composite.Core.WebClient; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { [ActionExecutor(typeof(ViewUnpublishedItemsActionExecutor))] internal sealed class ViewUnpublishedItemsActionToken : ActionToken { private static IEnumerable<PermissionType> _permissionType = new PermissionType[] { PermissionType.Read }; public ViewUnpublishedItemsActionToken() { } public override IEnumerable<PermissionType> PermissionTypes { get { return _permissionType; } } public override string Serialize() { return "ViewUnpublishedGlobalItems"; } public static ActionToken Deserialize(string serializedData) { return new ViewUnpublishedItemsActionToken(); } } internal sealed class ViewUnpublishedItemsActionExecutor : Composite.C1Console.Actions.IActionExecutor { public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { string documentTitle = StringResourceSystemFacade.GetString("Composite.Plugins.GeneratedDataTypesElementProvider", "ViewUnpublishedItems-document-title"); string description = StringResourceSystemFacade.GetString("Composite.Plugins.GeneratedDataTypesElementProvider", "ViewUnpublishedItems-document-description"); string emptyLabel = StringResourceSystemFacade.GetString("Composite.Plugins.GeneratedDataTypesElementProvider", "ViewUnpublishedItems-document-empty-label"); string url = string.Format("{0}?showglobaldata=true&title={1}&description={2}&emptyLabel={3}", UrlUtils.ResolveAdminUrl(string.Format("content/views/publishworkflowstatus/ViewUnpublishedItems.aspx")), HttpUtility.UrlEncode(documentTitle, Encoding.UTF8), HttpUtility.UrlEncode(description, Encoding.UTF8), HttpUtility.UrlEncode(emptyLabel, Encoding.UTF8)); IManagementConsoleMessageService consoleServices = flowControllerServicesContainer.GetService<IManagementConsoleMessageService>(); OpenViewMessageQueueItem openViewMsg = new OpenViewMessageQueueItem { EntityToken = EntityTokenSerializer.Serialize(entityToken, true), ViewId = "ViewUnpublishedGlobalItems", Label = documentTitle, Url = url, ViewType = ViewType.Main }; ConsoleMessageQueueFacade.Enqueue(openViewMsg, consoleServices.CurrentConsoleId); return null; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/LocalizationElementProvider/LocalizationElementProvider.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Composite.Core.Types; using Composite.Core.Localization; namespace Composite.Plugins.Elements.ElementProviders.LocalizationElementProvider { [ConfigurationElementType(typeof(NonConfigurableHooklessElementProvider))] internal sealed class LocalizationElementProvider : IHooklessElementProvider, IAuxiliarySecurityAncestorProvider { private ElementProviderContext _context; private static ResourceHandle RootClosedIcon = GetIconHandle("localization-element-closed-root"); private static ResourceHandle RootOpenedIcon = GetIconHandle("localization-element-opened-root"); private static ResourceHandle LocaleItemIcon = GetIconHandle("localization-element-localeitem"); private static ResourceHandle DefaultLocaleItemIcon = GetIconHandle("localization-element-defaultlocaleitem"); private static ResourceHandle AddSystemLocaleIcon = GetIconHandle("localization-addsystemlocale"); private static ResourceHandle EditSystemLocaleIcon = GetIconHandle("localization-editsystemlocale"); private static ResourceHandle SetAsDefaultIcon = GetIconHandle("localization-setasdefault"); private static ResourceHandle RemoveSystemLocaleIcon = GetIconHandle("localization-removesystemlocale"); private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); public LocalizationElementProvider() { AuxiliarySecurityAncestorFacade.AddAuxiliaryAncestorProvider<DataEntityToken>(this); } public ElementProviderContext Context { set { _context = value; } } public IEnumerable<Element> GetRoots(SearchToken seachToken) { Element element = new Element(_context.CreateElementHandle(new LocalizationElementProviderRootEntityToken())); element.VisualData = new ElementVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "ElementProvider.RootFolderLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "ElementProvider.RootFolderToolTip"), HasChildren = true, Icon = RootClosedIcon, OpenedIcon = RootOpenedIcon }; element.AddAction(new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.LocalizationElementProvider.AddSystemLocaleWorkflow"), new PermissionType[] { PermissionType.Administrate } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "AddSystemLocaleWorkflow.AddElementActionLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "AddSystemLocaleWorkflow.AddElementActionToolTip"), Icon = AddSystemLocaleIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); yield return element; } public IEnumerable<Element> GetChildren(EntityToken entityToken, SearchToken seachToken) { if ((entityToken is LocalizationElementProviderRootEntityToken) == false) throw new InvalidOperationException(); IEnumerable<ISystemActiveLocale> locales = DataFacade.GetData<ISystemActiveLocale>().ToList(); List<Element> elements = new List<Element>(); foreach (ISystemActiveLocale locale in locales) { bool isDefault = LocalizationFacade.IsDefaultLocale(locale.CultureName); ResourceHandle iconHandle = LocaleItemIcon; if (isDefault) { //lable = string.Format("{0} ({1})", lable, StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "ElementProvider.DefaultLabel")); iconHandle = DefaultLocaleItemIcon; } Element element = new Element(_context.CreateElementHandle(locale.GetDataEntityToken())); element.VisualData = new ElementVisualizedData { Label = DataLocalizationFacade.GetCultureTitle(new CultureInfo(locale.CultureName)), ToolTip = DataLocalizationFacade.GetCultureTitle(new CultureInfo(locale.CultureName)), HasChildren = false, Icon = iconHandle }; element.AddAction(new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.LocalizationElementProvider.EditSystemLocaleWorkflow"), new PermissionType[] { PermissionType.Administrate } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "EditSystemLocaleWorkflow.EditElementActionLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "EditSystemLocaleWorkflow.EditElementActionToolTip"), Icon = EditSystemLocaleIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); if (isDefault == false) { element.AddAction(new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.LocalizationElementProvider.DefineDefaultActiveLocaleWorkflow"), new PermissionType[] { PermissionType.Administrate } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "DefineDefaultActiveLocaleWorkflow.ElementActionLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "DefineDefaultActiveLocaleWorkflow.ElementActionToolTip"), Icon = SetAsDefaultIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); element.AddAction(new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.LocalizationElementProvider.RemoveSystemLocaleWorkflow"), new PermissionType[] { PermissionType.Administrate } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "RemoveSystemLocaleWorkflow.RemoveElementActionLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "RemoveSystemLocaleWorkflow.RemoveElementActionToolTip"), Icon = RemoveSystemLocaleIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); } elements.Add(element); } return elements.OrderBy(f => f.VisualData.Label); } public Dictionary<EntityToken, IEnumerable<EntityToken>> GetParents(IEnumerable<EntityToken> entityTokens) { Dictionary<EntityToken, IEnumerable<EntityToken>> result = new Dictionary<EntityToken, IEnumerable<EntityToken>>(); foreach (EntityToken entityToken in entityTokens) { DataEntityToken dataEntityToken = entityToken as DataEntityToken; Type type = dataEntityToken.InterfaceType; if (type != typeof(ISystemActiveLocale)) continue; LocalizationElementProviderRootEntityToken newEntityToken = new LocalizationElementProviderRootEntityToken(); result.Add(entityToken, new EntityToken[] { newEntityToken }); } return result; } private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/LocalizationElementProvider/LocalizationElementProviderRootEntityToken.cs ================================================ using Composite.C1Console.Security; using Composite.C1Console.Security.SecurityAncestorProviders; namespace Composite.Plugins.Elements.ElementProviders.LocalizationElementProvider { [SecurityAncestorProvider(typeof(NoAncestorSecurityAncestorProvider))] internal sealed class LocalizationElementProviderRootEntityToken : EntityToken { public override string Type { get { return ""; } } public override string Source { get { return ""; } } public override string Id { get { return "LocalizationElementProviderRootEntityToken"; } } public override string Serialize() { return DoSerialize(); } public static EntityToken Deserialize(string serializedEntityToken) { return new LocalizationElementProviderRootEntityToken(); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/EditMediaFileTextContentWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="EditMediaFileTextContentWorkflow" Location="30; 30" Size="1132; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="EditMediaFileTextContentWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="EditMediaFileTextContentWorkflow" EventHandlerName="cancelEventDrivenActivity"> <StateDesignerConnector.Segments> <ns0:Point X="202" Y="71" /> <ns0:Point X="613" Y="71" /> <ns0:Point X="613" Y="103" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initialState" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="initialState" EventHandlerName="initialStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="146" /> <ns0:Point X="266" Y="146" /> <ns0:Point X="266" Y="247" /> <ns0:Point X="186" Y="247" /> <ns0:Point X="186" Y="259" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="saveStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="editStateActivity" SourceConnectionEdge="Right" TargetActivity="saveStateActivity" SourceActivity="editStateActivity" EventHandlerName="eventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="262" Y="324" /> <ns0:Point X="293" Y="324" /> <ns0:Point X="293" Y="289" /> <ns0:Point X="461" Y="289" /> <ns0:Point X="461" Y="297" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="saveStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="saveStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="560" Y="338" /> <ns0:Point X="570" Y="338" /> <ns0:Point X="570" Y="251" /> <ns0:Point X="186" Y="251" /> <ns0:Point X="186" Y="259" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initialState" Location="63; 105" Size="197; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initialStateInitializationActivity" Location="521; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity" Location="531; 210" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="531; 270" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="editStateActivity" Location="92; 259" Size="189; 94" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="editStateInitializationActivity" Location="100; 290"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="documentFormActivity1" Location="110; 352" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_Save" Location="100; 314"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="saveHandleExternalEventActivity1" Location="110; 376" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="110; 436" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="saveStateActivity" Location="359; 297" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="finalizeStateInitializationActivity" Location="367; 328"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="saveCodeActivity" Location="377; 390" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="377; 450" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="533; 103" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="cancelEventDrivenActivity" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/MediaFileProviderElementProvider.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.C1Console.Actions; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Linq; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.Core.Routing; using Composite.Core.WebClient; using Composite.Data; using Composite.Data.Foundation.PluginFacades; using Composite.Data.Types; using Composite.Data.Types.StoreIdFilter; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { [ConfigurationElementType(typeof(MediaFileElementProviderData))] internal sealed class MediaFileProviderElementProvider : IHooklessElementProvider, IDragAndDropElementProvider, ILabeledPropertiesElementProvider, IAuxiliarySecurityAncestorProvider { private ElementProviderContext _context; private readonly bool _showOnlyImages; private string _rootLabel; private ResourceHandle FolderIcon => CommonElementIcons.Folder; private ResourceHandle OpenFolderIcon => CommonElementIcons.FolderOpen; private ResourceHandle EmptyFolderIcon => CommonElementIcons.FolderOpen; private static ResourceHandle ReadOnlyFolderOpen => GetIconHandle("media-read-only-folder-open"); private static ResourceHandle ReadOnlyFolderClosed => GetIconHandle("media-read-only-folder-closed"); public static ResourceHandle AddMediaFolder => GetIconHandle("media-add-media-folder"); public static ResourceHandle AddMediaFile => GetIconHandle("media-add-media-file"); public static ResourceHandle DownloadFile => GetIconHandle("media-download-file"); public static ResourceHandle ReplaceMediaFile => GetIconHandle("media-replace-media-file"); public static ResourceHandle UploadZipFile => GetIconHandle("media-upload-zip-file"); public static ResourceHandle EditImageFile => GetIconHandle("media-edit-image-file"); public static ResourceHandle EditMediaFolder => GetIconHandle("media-edit-media-folder"); public static ResourceHandle EditMediaFile => GetIconHandle("media-edit-media-file"); public static ResourceHandle DeleteMediaFolder => GetIconHandle("media-delete-media-folder"); public static ResourceHandle DeleteMediaFile => GetIconHandle("media-delete-media-file"); private static readonly ActionGroup PrimaryFolderActionGroup = new ActionGroup("Folder", ActionGroupPriority.PrimaryMedium); private static readonly ActionGroup PrimaryFileActionGroup = new ActionGroup("File", ActionGroupPriority.PrimaryMedium); private static readonly ActionGroup PrimaryFileToolsActionGroup = new ActionGroup("FileTools", ActionGroupPriority.PrimaryMedium); private static readonly Expression IgnoreCaseConstantExpression = Expression.Constant(StringComparison.OrdinalIgnoreCase, typeof(StringComparison)); private static readonly MethodInfo EndsWithMethodInfo = typeof(string).GetMethod("EndsWith", new[] { typeof(string), typeof(StringComparison) }); public MediaFileProviderElementProvider(MediaFileElementProviderData data) { _showOnlyImages = data.ShowOnlyImages; _rootLabel = data.RootLabel; AuxiliarySecurityAncestorFacade.AddAuxiliaryAncestorProvider<DataEntityToken>(this); } public ElementProviderContext Context { set { _context = value; } } public IEnumerable<Element> GetRoots(SearchToken seachToken) { var mediaStores = DataFacade.GetData<IMediaFileStore>(); var elements = new List<Element>(); foreach (IMediaFileStore store in mediaStores) { var element = new Element(_context.CreateElementHandle(new MediaRootFolderProviderEntityToken(store.Id))) { VisualData = new ElementVisualizedData() { Label = store.Title, ToolTip = GetResourceString("MediaFileProviderElementProvider.RootToolTip"), HasChildren = true, Icon = FolderIcon, OpenedIcon = OpenFolderIcon } }; element.PropertyBag.Add("ReadOnly", store.IsReadOnly.ToString()); element.PropertyBag.Add("ElementId", store.Id + ":/"); if(!store.IsReadOnly) { element.MovabilityInfo.AddDropType(typeof(IMediaFileFolder), store.Id); element.MovabilityInfo.AddDropType(typeof(IMediaFile), store.Id); element.MovabilityInfo.DragType = typeof(IMediaFileStore); element.AddAction( new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider.AddNewMediaFolderWorkflow"), new PermissionType[] { PermissionType.Add } ))) { VisualData = new ActionVisualizedData { Label = GetResourceString("MediaFileProviderElementProvider.AddMediaFolder"), ToolTip = GetResourceString("MediaFileProviderElementProvider.AddMediaFolderToolTip"), Icon = MediaFileProviderElementProvider.AddMediaFolder, Disabled = false, ActivePositions = ElementActionActivePosition.NavigatorTree | ElementActionActivePosition.SelectorTree, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFolderActionGroup } } }); element.AddAction( new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider.AddNewMediaFileWorkflow"), new PermissionType[] { PermissionType.Add } ))) { VisualData = new ActionVisualizedData { Label = GetResourceString("MediaFileProviderElementProvider.AddMediaFile"), ToolTip = GetResourceString("MediaFileProviderElementProvider.AddMediaFileToolTip"), Icon = MediaFileProviderElementProvider.AddMediaFile, Disabled = false, ActivePositions = ElementActionActivePosition.NavigatorTree | ElementActionActivePosition.SelectorTree, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFileActionGroup } } }); element.AddAction( new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider.AddMediaZipFileWorkflow"), new PermissionType[] { PermissionType.Add } ) { DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = GetResourceString("MediaFileProviderElementProvider.UploadZipFile"), ToolTip = GetResourceString("MediaFileProviderElementProvider.UploadZipFileToolTip"), Icon = MediaFileProviderElementProvider.UploadZipFile, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFileActionGroup } } }); } elements.Add(element); } return elements; } public IEnumerable<Element> GetChildren(EntityToken entityToken, SearchToken searchToken) { if (entityToken is MediaRootFolderProviderEntityToken) { return GetChildrenOnPath("/", entityToken.Id, searchToken); } var dataEntityToken = (DataEntityToken)entityToken; Verify.IsNotNull(dataEntityToken, "Unexpected entity token type '{0}'", entityToken.GetType()); if (dataEntityToken.InterfaceType == typeof (IMediaFile)) { return null; } if (dataEntityToken.InterfaceType == typeof (IMediaFileFolder)) { object data = dataEntityToken.Data; if (data == null) { return Enumerable.Empty<Element>(); } var folder = (IMediaFileFolder)data; return GetChildrenOnPath(folder.Path, folder.StoreId, searchToken); } throw new InvalidOperationException("Unexpected data entity token's interface type '{0}'".FormatWith(dataEntityToken.InterfaceType)); } public IEnumerable<LabeledProperty> GetLabeledProperties(EntityToken entityToken) { if (!(entityToken is DataEntityToken)) { throw new ArgumentException($"Got '{typeof (EntityToken)}' expected '{typeof (DataEntityToken)}'"); } var token = (DataEntityToken) entityToken; if (token.Data is IMediaFileFolder) { return GetFolderProperties((IMediaFileFolder) token.Data); } if (token.Data is IMediaFile) { return GetFileProperties((IMediaFile) token.Data); } throw new ArgumentException($"Unexpected type of data '{token.Data.GetType()}' in token"); } public Dictionary<EntityToken, IEnumerable<EntityToken>> GetParents(IEnumerable<EntityToken> entityTokens) { var result = new Dictionary<EntityToken, IEnumerable<EntityToken>>(); foreach (EntityToken entityToken in entityTokens) { var dataEntityToken = entityToken as DataEntityToken; Type type = dataEntityToken.InterfaceType; if (type != typeof(IMediaFile) && type != typeof(IMediaFileFolder)) continue; string storeId = null; IMediaFile mediaFile = dataEntityToken.Data as IMediaFile; if (mediaFile != null) { if (mediaFile.FolderPath != "/") continue; storeId = mediaFile.StoreId; } IMediaFileFolder mediaFileFolder = dataEntityToken.Data as IMediaFileFolder; if (mediaFileFolder != null) { if (!mediaFileFolder.Path.IsDirectChildOf("/", '/')) continue; storeId = mediaFileFolder.StoreId; } if(storeId == null) continue; var newEntityToken = new MediaRootFolderProviderEntityToken(storeId); result.Add(entityToken, new EntityToken[] { newEntityToken }); } return result; } private IEnumerable<LabeledProperty> GetFileProperties(IMediaFile file) { var propertyList = new LabeledPropertyList { {"StoreId", "Store ID", file.StoreId}, {"FolderPath", "Folder path", file.FolderPath}, {"FileName", "File name", file.FileName}, {"Title", "Description", file.Title}, {"Description", "Description", file.Description}, {"IsReadOnly", "Read only", file.IsReadOnly} }; if (file.Length.HasValue) propertyList.Add("Length", "Length (bytes)", file.Length.Value); if (file.LastWriteTime.HasValue) propertyList.Add("LastWriteTime", "Last write time", file.LastWriteTime.Value); if (file.CreationTime.HasValue) propertyList.Add("CreationTime", "Creation time", file.CreationTime.Value); if (file.MimeType.Length > 0) propertyList.Add("MimeType", "MIME type", file.MimeType); propertyList.Add("Culture", "Culture", file.Culture); if (file.MimeType.StartsWith("image")) { if (file.MimeType == MimeTypeInfo.Svg) { propertyList.Add("ImageFormat", "Image format", "svg"); } else { using (Stream fileStream = file.GetReadStream()) { var bitmap = new Bitmap(fileStream); propertyList.Add("ImageWidth", "Image width", bitmap.Width); propertyList.Add("ImageHeight", "Image height", bitmap.Height); string formatString = null; if (bitmap.RawFormat.Guid.CompareTo(ImageFormat.Gif.Guid) == 0) formatString = "gif"; if (bitmap.RawFormat.Guid.CompareTo(ImageFormat.Jpeg.Guid) == 0) formatString = "jpeg"; if (bitmap.RawFormat.Guid.CompareTo(ImageFormat.Png.Guid) == 0) formatString = "png"; if (bitmap.RawFormat.Guid.CompareTo(ImageFormat.Tiff.Guid) == 0) formatString = "tiff"; if (formatString != null) propertyList.Add("ImageFormat", "Image format", formatString); } } } return propertyList; } private IEnumerable<LabeledProperty> GetFolderProperties(IMediaFileFolder folder) { return new LabeledPropertyList { {"StoreId", "Store ID", folder.StoreId}, {"Path", "Path", folder.Path}, {"Title", "Title", folder.Title}, {"Description", "Description", folder.Description}, {"IsReadOnly", "Read only", folder.IsReadOnly} }; } private static bool DoesFileExist(string path, string name) { return (from item in DataFacade.GetData<IMediaFile>() where item.FolderPath == path && item.FileName == name select item).Any(); } public bool OnElementDraggedAndDropped(EntityToken draggedEntityToken, EntityToken newParentEntityToken, int dropIndex, DragAndDropType dragAndDropType, FlowControllerServicesContainer flowControllerServicesContainer) { IData draggedData = ((DataEntityToken)draggedEntityToken).Data; string path; if (newParentEntityToken is DataEntityToken) { path = ((IMediaFileFolder)((DataEntityToken)newParentEntityToken).Data).Path; } else if (newParentEntityToken is MediaRootFolderProviderEntityToken) { path = "/"; } else { throw new NotImplementedException(); } IMediaFile draggedFile = draggedData as IMediaFile; IMediaFileFolder draggedFolder = draggedData as IMediaFileFolder; string oldPath = null; string storeId = null; if (dragAndDropType == DragAndDropType.Move) { if (draggedFile != null) { if (DoesFileExist(path, draggedFile.FileName)) { var messageService = flowControllerServicesContainer.GetService<IManagementConsoleMessageService>(); messageService.ShowMessage(DialogType.Error, GetResourceString("MediaFileProviderElementProvider.ErrorMessageTitle"), GetResourceString("MediaFileProviderElementProvider.FileAlreadyExistsMessage").FormatWith(draggedFile.FileName, path)); return false; } oldPath = draggedFile.FolderPath; storeId = draggedFile.StoreId; draggedFile.FolderPath = path; DataFacade.Update(draggedFile); } else if (draggedFolder != null) { int index = draggedFolder.Path.LastIndexOf('/'); oldPath = draggedFolder.Path.Remove(index); storeId = draggedFolder.StoreId; string draggedFolderName = draggedFolder.Path.Remove(0, index + 1); string newPath = path; if (!path.EndsWith("/")) { newPath = $"{path}/"; } string targetPath = $"{newPath}{draggedFolderName}"; using (var scope = Composite.Data.Transactions.TransactionsFacade.CreateNewScope()) { draggedFolder.Path = targetPath; DataFacade.Update(draggedFolder); scope.Complete(); } } else { Verify.ThrowInvalidOperationException("Unexpected media data type."); } } else if (dragAndDropType == DragAndDropType.Copy) { if (draggedFile != null) { storeId = draggedFile.StoreId; IMediaFileStore store = DataFacade.GetData<IMediaFileStore>(x => x.Id == storeId).First(); StoreIdFilterQueryable<IMediaFile> fileQueryable = new StoreIdFilterQueryable<IMediaFile>(DataFacade.GetData<IMediaFile>(), storeId); List<string> fileNames = (from f in fileQueryable where f.StoreId == storeId && f.FolderPath == path select f.FileName).ToList(); var newWorkflowMediaFile = new WorkflowMediaFile(draggedFile) { FolderPath = path }; string draggedFilenamePre = draggedFile.FileName; string draggedFilenamePost = ""; int index = draggedFile.FileName.LastIndexOf('.'); if (index != -1) { draggedFilenamePre = draggedFile.FileName.Remove(index); draggedFilenamePost = draggedFile.FileName.Remove(0, index); } string newFilename = draggedFile.FileName; int counter = 1; while (fileNames.Contains(newFilename)) { newFilename = $"{draggedFilenamePre}({counter++}){draggedFilenamePost}"; } newWorkflowMediaFile.FileName = newFilename; using (Stream readStream = draggedFile.GetReadStream()) { using (Stream writeStream = newWorkflowMediaFile.GetNewWriteStream()) { readStream.CopyTo(writeStream); } } DataFacade.AddNew<IMediaFile>(newWorkflowMediaFile, store.DataSourceId.ProviderName); } else if (draggedFolder != null) { return false; } else { Verify.ThrowInvalidOperationException("Unexpected media data type."); } } else { Verify.ThrowInvalidOperationException("Unexpected copying mode."); } if (oldPath != null) { EntityToken entityToken = GetFolderByPath(oldPath, storeId); if (entityToken != null) { var oldFolderSpecificTreeRefresher = new SpecificTreeRefresher(flowControllerServicesContainer); oldFolderSpecificTreeRefresher.PostRefreshMesseges(entityToken); } } if (path != oldPath) { EntityToken entityToken = GetFolderByPath(path, storeId); if (entityToken != null) { var oldFolderSpecificTreeRefresher = new SpecificTreeRefresher(flowControllerServicesContainer); oldFolderSpecificTreeRefresher.PostRefreshMesseges(entityToken); } } return true; } private static StoreIdFilterQueryable<T> GetQuery<T>(string storeId) where T : class, IData { return new StoreIdFilterQueryable<T>(DataFacade.GetData<T>(), storeId); } private static EntityToken GetFolderByPath(string path, string storeId) { Verify.ArgumentNotNull(path, "path"); if (path == string.Empty || path == "/") { return new MediaRootFolderProviderEntityToken(storeId); } var queryable = new StoreIdFilterQueryable<IMediaFileFolder>(DataFacade.GetData<IMediaFileFolder>(), storeId); var folder = (from folderInfo in queryable where folderInfo.StoreId == storeId && folderInfo.Path == path select folderInfo).FirstOrDefault(); return folder?.GetDataEntityToken(); } private IEnumerable<Element> GetChildrenOnPath(string parentPath, string storeId, SearchToken searchToken) { bool showFiles = true; bool showFolders = true; string folderChainToShow = null; if(searchToken is MediaFileSearchToken) { var mediaSearchToken = searchToken as MediaFileSearchToken; string folderPath = mediaSearchToken.Folder; if(folderPath != null) { bool isUnderTargetFolder = parentPath.Length >= folderPath.Length; showFiles = isUnderTargetFolder; if (!isUnderTargetFolder) { // Filtering folders so we can see only ancestors "chain" folderChainToShow = folderPath + "/"; } showFolders = !(mediaSearchToken.HideSubfolders && parentPath == folderPath); } } IEnumerable<Element> result = null; if (showFolders) { var folderQueryable = GetQuery<IMediaFileFolder>(storeId); string parentPathPrefix = parentPath + (parentPath.EndsWith("/") ? "" : "/"); int parentPathPrefixLength = parentPath.Length; var childFolders = folderQueryable.Where(item => item.Path.StartsWith(parentPathPrefix) && item.Path.LastIndexOf('/') <= parentPathPrefixLength).Evaluate(); result = (from item in childFolders where folderChainToShow == null || folderChainToShow.StartsWith(item.Path + '/') orderby item.Path select CreateFolderElement(item)).ToList(); } if(showFiles) { Expression<Func<IMediaFile, bool>> predicate = BuildFilePredicate(searchToken); var fileQueryable = GetQuery<IMediaFile>(storeId); var files = (from item in fileQueryable where item.FolderPath == parentPath orderby item.FileName select item).Where(predicate).Evaluate().Select(CreateFileElement).ToList(); result = result?.Concat(files) ?? files; } return result != null ? result.Evaluate() : Enumerable.Empty<Element>(); } private Expression<Func<IMediaFile, bool>> BuildFilePredicate(SearchToken searchToken) { var predicates = new List<Expression<Func<IMediaFile, bool>>>(); if (_showOnlyImages) { predicates.Add(x => x.MimeType != null && x.MimeType.StartsWith("image")); } if (searchToken.IsValidKeyword()) { string keyword = searchToken.Keyword.ToLower(); predicates.Add(x => (x.Description != null && x.Description.ToLower().Contains(keyword)) || (x.FileName != null && x.FileName.ToLower().Contains(keyword)) || (x.Title != null && x.Title.ToLower().Contains(keyword))); } var mediaFileSearchToken = searchToken as MediaFileSearchToken; if (mediaFileSearchToken != null) { if (mediaFileSearchToken.MimeTypes != null && mediaFileSearchToken.MimeTypes.Length > 0) { var mimeTypes = new List<string>(mediaFileSearchToken.MimeTypes); predicates.Add(x => mimeTypes.Contains(x.MimeType)); } if (mediaFileSearchToken.Extensions != null && mediaFileSearchToken.Extensions.Length > 0) { ParameterExpression fileParameter = Expression.Parameter(typeof(IMediaFile), "file"); Expression body = null; foreach (string extension in mediaFileSearchToken.Extensions) { string suffix = extension.StartsWith(".") ? extension : "." + extension; // "file.FileName" Expression fileName = Expression.Property(fileParameter, typeof(IFile), "FileName"); // Building "file.FileName.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)" MethodCallExpression predicate = Expression.Call(fileName, EndsWithMethodInfo, Expression.Constant(suffix), IgnoreCaseConstantExpression); if (body == null) { // file => file.FileName.EndsWith(extension, StringComparison.OrdinalIgnoreCase); body = predicate; } else { // body = (.....) || file.FileName.EndsWith(extension, StringComparison.OrdinalIgnoreCase; body = Expression.OrElse(body, predicate); } } predicates.Add(Expression.Lambda<Func<IMediaFile, bool>>(body, fileParameter)); } } if (predicates.Count == 0) { return (x => true); } return AndPredicates(predicates); } private static Expression<Func<T, bool>> AndPredicates<T>(IEnumerable<Expression<Func<T, bool>>> predicates) where T: IData { var p = Expression.Parameter(typeof(IMediaFile)); Expression andBody = null; foreach (Expression<Func<T, bool>> predicate in predicates) { var conditionPart = Expression.Invoke(predicate, p); andBody = andBody == null ? conditionPart as Expression : Expression.And(andBody, conditionPart); } return Expression.Lambda<Func<T, bool>>(andBody, p); } private Element CreateFileElement(IMediaFile file) { var element = new Element(_context.CreateElementHandle(file.GetDataEntityToken())) { VisualData = new ElementVisualizedData { Label = file.FileName, ToolTip = GetResourceString("MediaFileProviderElementProvider.MediaFileItemToolTip"), HasChildren = false, Icon = this.MediaFileIcon(file.MimeType), OpenedIcon = this.MediaFileIcon(file.MimeType) } }; if (DataProviderPluginFacade.IsWriteableProvider(file.DataSourceId.ProviderName)) { element.MovabilityInfo.DragType = typeof(IMediaFile); element.MovabilityInfo.DragSubType = file.StoreId; } Verify.IsNotNull(file.FileName, "file.FileName is null. Media ID: {0}", file.Id); Verify.IsNotNull(file.FolderPath, "file.FolderPath is null. Media ID: {0}", file.Id); element.PropertyBag.Add("ElementId", file.StoreId + ":" + file.FolderPath.Combine(file.FileName, '/')); element.PropertyBag.Add("Uri", GetMediaUrl(file, true, false)); element.PropertyBag.Add("ElementType", file.MimeType); if (file.MimeType.StartsWith("image/")) { string previewImageUrl = UrlUtils.ResolvePublicUrl(MediaUrls.BuildUrl(file, UrlKind.Internal) + "?mw={width}&mh={height}"); DateTime? modificationTime = file.LastWriteTime ?? file.CreationTime; if (modificationTime != null) { previewImageUrl += "×tamp=" + modificationTime.GetHashCode(); } element.PropertyBag.Add("ListViewImage", previewImageUrl); element.PropertyBag.Add("DetailViewImage", previewImageUrl); } GetFileActions(file).ForEach(element.AddAction); return element; } internal static string GetMediaUrl(IMediaFile file, bool isInternal, bool downloadable) { return MediaUrlHelper.GetUrl(file, isInternal, downloadable); } private Element CreateFolderElement(IMediaFileFolder folder) { bool hasFolders = DataFacade.GetData<IMediaFileFolder>().Any(f => f.Path.StartsWith(folder.Path)); bool hasChildren = hasFolders; if(!hasChildren) { bool hasFiles = DataFacade.GetData<IMediaFile>().Any(file => file.FolderPath == folder.Path); hasChildren = hasFiles; } ResourceHandle icon = this.EmptyFolderIcon; ResourceHandle openIcon = this.OpenFolderIcon; if (hasChildren) { icon = this.FolderIcon; } if (folder.IsReadOnly) { icon = MediaFileProviderElementProvider.ReadOnlyFolderClosed; openIcon = MediaFileProviderElementProvider.ReadOnlyFolderOpen; } Element element = new Element(_context.CreateElementHandle(folder.GetDataEntityToken())) { VisualData = new ElementVisualizedData { Label = folder.Path.GetFolderName('/'), ToolTip = GetResourceString("MediaFileProviderElementProvider.OrganizedFilesAndFoldersToolTip"), HasChildren = hasChildren, Icon = icon, OpenedIcon = openIcon }, }; if (DataProviderPluginFacade.IsWriteableProvider(folder.DataSourceId.ProviderName)) { element.MovabilityInfo.AddDropType(typeof(IMediaFileFolder), folder.StoreId); element.MovabilityInfo.AddDropType(typeof(IMediaFile), folder.StoreId); element.MovabilityInfo.DragType = typeof(IMediaFileFolder); element.MovabilityInfo.DragSubType = folder.StoreId; } element.PropertyBag.Add("ReadOnly", folder.IsReadOnly.ToString()); element.PropertyBag.Add("ElementId", folder.StoreId + ":" + folder.Path); foreach (ElementAction action in GetFolderActions(folder)) { element.AddAction(action); } return element; } private IEnumerable<ElementAction> GetFileActions(IMediaFile file) { IList<ElementAction> fileActions = new List<ElementAction>(); //if (!file.IsReadOnly) //{ fileActions.Add( new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider.DeleteMediaFileWorkflow"), new PermissionType[] { PermissionType.Delete } ))) { VisualData = new ActionVisualizedData { Label = GetResourceString("MediaFileProviderElementProvider.DeleteMediaFile"), ToolTip = GetResourceString("MediaFileProviderElementProvider.DeleteMediaFileToolTip"), Icon = DeleteMediaFile, Disabled = file.IsReadOnly, ActivePositions = ElementActionActivePosition.NavigatorTree | ElementActionActivePosition.SelectorTree, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFileActionGroup } } }); fileActions.Add( new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider.EditMediaFileWorkflow"), new PermissionType[] { PermissionType.Edit } ))) { VisualData = new ActionVisualizedData { Label = GetResourceString("MediaFileProviderElementProvider.EditMediaFile"), ToolTip = GetResourceString("MediaFileProviderElementProvider.EditMediaFileToolTip"), Icon = EditMediaFile, Disabled = file.IsReadOnly, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFileActionGroup } } }); if (file.MimeType != null && MimeTypeInfo.IsTextFile(file.MimeType)) { fileActions.Add( new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider.EditMediaFileTextContentWorkflow"), new PermissionType[] { PermissionType.Edit } ))) { VisualData = new ActionVisualizedData { Label = GetResourceString("MediaFileProviderElementProvider.EditMediaFileTextContent"), ToolTip = GetResourceString("MediaFileProviderElementProvider.EditMediaFileTextContentToolTip"), Icon = CommonCommandIcons.Edit, Disabled = file.IsReadOnly, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFileToolsActionGroup } } }); } if (file.MimeType != null && file.MimeType.StartsWith("image")) { fileActions.Add( new ElementAction(new ActionHandle(new EditImageActionToken())) { VisualData = new ActionVisualizedData { Label = GetResourceString("MediaFileProviderElementProvider.EditImage"), ToolTip = GetResourceString("MediaFileProviderElementProvider.EditImageToolTip"), Icon = MediaFileProviderElementProvider.EditImageFile, Disabled = file.IsReadOnly, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFileToolsActionGroup } } }); } if (file.MimeType != null) { fileActions.Add( new ElementAction(new ActionHandle(new DownloadFileActionToken())) { VisualData = new ActionVisualizedData { Label = GetResourceString("MediaFileProviderElementProvider.Download"), ToolTip = GetResourceString("MediaFileProviderElementProvider.DownloadToolTip"), Icon = DownloadFile, Disabled = file.Length == 0, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFileToolsActionGroup } } }); } fileActions.Add( new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider.UploadNewMediaFileWorkflow"), new PermissionType[] { PermissionType.Edit } ))) { VisualData = new ActionVisualizedData { Label = GetResourceString("MediaFileProviderElementProvider.ChangeMediaFile"), ToolTip = GetResourceString("MediaFileProviderElementProvider.ChangeMediaFileToolTip"), Icon = MediaFileProviderElementProvider.ReplaceMediaFile, Disabled = file.IsReadOnly, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFileActionGroup } } }); //} return fileActions; } private IEnumerable<ElementAction> GetFolderActions(IMediaFileFolder folder) { IList<ElementAction> folderActions = new List<ElementAction>(); if (!folder.IsReadOnly) { folderActions.Add( new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider.AddNewMediaFolderWorkflow"), new PermissionType[] { PermissionType.Add } ))) { VisualData = new ActionVisualizedData { Label = GetResourceString("MediaFileProviderElementProvider.AddMediaFolder"), ToolTip = GetResourceString("MediaFileProviderElementProvider.AddMediaFolderToolTip"), Icon = MediaFileProviderElementProvider.AddMediaFolder, Disabled = false, ActivePositions = ElementActionActivePosition.NavigatorTree | ElementActionActivePosition.SelectorTree, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFolderActionGroup } } }); folderActions.Add( new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider.DeleteMediaFolderWorkflow"), new PermissionType[] { PermissionType.Delete } ))) { VisualData = new ActionVisualizedData { Label = GetResourceString("MediaFileProviderElementProvider.DeleteMediaFolder"), ToolTip = GetResourceString("MediaFileProviderElementProvider.DeleteMediaFolderToolTip"), Icon = DeleteMediaFolder, Disabled = false, ActivePositions = ElementActionActivePosition.NavigatorTree | ElementActionActivePosition.SelectorTree, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFolderActionGroup } } }); folderActions.Add( new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider.EditMediaFolderWorkflow"), new PermissionType[] { PermissionType.Edit } ))) { VisualData = new ActionVisualizedData { Label = GetResourceString("MediaFileProviderElementProvider.EditMediaFolder"), ToolTip = GetResourceString("MediaFileProviderElementProvider.EditMediaFolderToolTip"), Icon = EditMediaFolder, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFolderActionGroup } } }); folderActions.Add( new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider.AddNewMediaFileWorkflow"), new PermissionType[] { PermissionType.Add } ))) { VisualData = new ActionVisualizedData { Label = GetResourceString("MediaFileProviderElementProvider.AddMediaFile"), ToolTip = GetResourceString("MediaFileProviderElementProvider.AddMediaFileToolTip"), Icon = MediaFileProviderElementProvider.AddMediaFile, Disabled = false, ActivePositions = ElementActionActivePosition.NavigatorTree | ElementActionActivePosition.SelectorTree, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFileActionGroup } } }); folderActions.Add( new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider.AddMediaZipFileWorkflow"), new PermissionType[] { PermissionType.Add } ))) { VisualData = new ActionVisualizedData { Label = GetResourceString("MediaFileProviderElementProvider.UploadZipFile"), ToolTip = GetResourceString("MediaFileProviderElementProvider.UploadZipFileToolTip"), Icon = MediaFileProviderElementProvider.UploadZipFile, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFileActionGroup } } }); } return folderActions; } private static string GetResourceString(string key) { return StringResourceSystemFacade.GetString("Composite.Management", key); } private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } private ResourceHandle MediaFileIcon(string mimeType) { return MimeTypeInfo.GetResourceHandleFromMimeType(MimeTypeInfo.GetCanonical(mimeType)); } } internal sealed class EditImageActionExecutor : Composite.C1Console.Actions.IActionExecutor { public Composite.C1Console.Actions.FlowToken Execute(Composite.C1Console.Security.EntityToken entityToken, Composite.C1Console.Security.ActionToken actionToken, Composite.C1Console.Actions.FlowControllerServicesContainer flowControllerServicesContainer) { DataEntityToken token = (DataEntityToken)entityToken; IMediaFile mediaFile = (IMediaFile)token.Data; string currentConsoleId = flowControllerServicesContainer.GetService<IManagementConsoleMessageService>().CurrentConsoleId; string url = UrlUtils.ResolveAdminUrl(string.Format("content/views/editors/imageeditor/ImageEditor.aspx?src={0}&lastWriteTime={1}", System.Web.HttpUtility.UrlEncode(mediaFile.CompositePath), System.Web.HttpUtility.UrlEncode(mediaFile.LastWriteTime.ToString()))); Composite.C1Console.Events.ConsoleMessageQueueFacade.Enqueue( new Composite.C1Console.Events.OpenViewMessageQueueItem { EntityToken = EntityTokenSerializer.Serialize(entityToken, true), Url = url, ViewId = Guid.NewGuid().ToString(), ViewType = Composite.C1Console.Events.ViewType.Main }, currentConsoleId); return null; } } internal sealed class DownloadFileActionExecutor : IActionExecutor { public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { DataEntityToken token = (DataEntityToken)entityToken; IMediaFile mediaFile = (IMediaFile)token.Data; string currentConsoleId = flowControllerServicesContainer.GetService<IManagementConsoleMessageService>().CurrentConsoleId; string url = MediaFileProviderElementProvider.GetMediaUrl(mediaFile, false, true); ConsoleMessageQueueFacade.Enqueue(new DownloadFileMessageQueueItem(url), currentConsoleId); return null; } } [ActionExecutor(typeof(EditImageActionExecutor))] internal sealed class EditImageActionToken : ActionToken { private static readonly IEnumerable<PermissionType> _permissionTypes = new [] { PermissionType.Edit }; public override IEnumerable<PermissionType> PermissionTypes => _permissionTypes; public override string Serialize() => "EditImage"; public static ActionToken Deserialize(string serializedData) { return new EditImageActionToken(); } } [ActionExecutor(typeof(DownloadFileActionExecutor))] internal sealed class DownloadFileActionToken : ActionToken { private static readonly IEnumerable<PermissionType> _permissionTypes = new [] { PermissionType.Read }; public override IEnumerable<PermissionType> PermissionTypes => _permissionTypes; public override string Serialize() => "DownloadFile"; public static ActionToken Deserialize(string serializedData) { return new DownloadFileActionToken(); } } [Assembler(typeof(MediaFileElementProviderAssembler))] internal sealed class MediaFileElementProviderData : HooklessElementProviderData { private const string _showOnlyImagesProperty = "showOnlyImages"; [ConfigurationProperty(_showOnlyImagesProperty, IsRequired = true)] public bool ShowOnlyImages { get { return (bool)base[_showOnlyImagesProperty]; } set { base[_showOnlyImagesProperty] = value; } } private const string _rootLabel = "rootLabel"; [ConfigurationProperty(_rootLabel, IsRequired = true)] public string RootLabel { get { return (string)base[_rootLabel]; } set { base[_rootLabel] = value; } } } internal sealed class MediaFileElementProviderAssembler : IAssembler<IHooklessElementProvider, HooklessElementProviderData> { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IHooklessElementProvider Assemble(IBuilderContext context, HooklessElementProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new MediaFileProviderElementProvider(objectConfiguration as MediaFileElementProviderData); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/MediaFileProviderEntityTokenSecurityAncestorProvider.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { internal sealed class MediaFileProviderEntityTokenSecurityAncestorProvider : ISecurityAncestorProvider { public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { // ok since the only hook is on the root folder return null; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/MediaFileSearchToken.cs ================================================ using Composite.C1Console.Elements; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class MediaFileSearchToken : SearchToken { /// <exclude /> public string[] MimeTypes { get; set; } /// <exclude /> public string[] Extensions { get; set; } /// <exclude /> public string Folder { get; set; } /// <exclude /> public bool HideSubfolders { get; set; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/MediaRootFolderProviderEntityToken.cs ================================================ using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(MediaFileProviderEntityTokenSecurityAncestorProvider))] public sealed class MediaRootFolderProviderEntityToken : EntityToken { /// <exclude /> public MediaRootFolderProviderEntityToken(string parentFolder) { Verify.ArgumentNotNull(parentFolder, nameof(parentFolder)); Id = parentFolder; } /// <exclude /> public override string Type => ""; /// <exclude /> public override string Source => ""; /// <exclude /> public override string Id { get; } /// <exclude /> public override string Serialize() => DoSerialize(); /// <exclude /> public static EntityToken Deserialize(string serializedData) { string type, source, id; EntityToken.DoDeserialize(serializedData, out type, out source, out id); return new MediaRootFolderProviderEntityToken(id); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/WorkflowMediaFile.cs ================================================ using System; using Composite.Data; using Composite.Data.Plugins.DataProvider.Streams; using Composite.Data.Streams; using Composite.Data.Types; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [FileStreamManager(typeof(FileSystemFileStreamManager))] public sealed class WorkflowMediaFile : FileSystemFileBase, IMediaFile { /// <exclude /> public WorkflowMediaFile() { Title = string.Empty; Description = string.Empty; MimeType = string.Empty; Tags = string.Empty; DataSourceId = new DataSourceId(typeof(IMediaFile)); } /// <exclude /> public WorkflowMediaFile(IMediaFile file) { Id = file.Id; StoreId = file.StoreId; Title = file.Title; Culture = file.Culture; CreationTime = file.CreationTime; DataSourceId = file.DataSourceId; Description = file.Description; Tags = file.Tags; FileName = file.FileName; FolderPath = file.FolderPath; IsReadOnly = file.IsReadOnly; LastWriteTime = file.LastWriteTime; Length = file.Length; MimeType = file.MimeType; } /// <exclude /> public Guid Id { get; internal set; } /// <exclude /> public string KeyPath { get { return this.GetKeyPath(); } } /// <exclude /> public string CompositePath { get { return this.GetCompositePath(); } set { throw new InvalidOperationException(); } } /// <exclude /> public string StoreId { get; set; } /// <exclude /> public string Title { get; set; } /// <exclude /> public string Description { get; set; } /// <exclude /> public string Tags { get; set; } /// <exclude /> public string Culture { get; set; } /// <exclude /> public string MimeType { get; set; } /// <exclude /> public int? Length { get; set; } /// <exclude /> public DateTime? CreationTime { get; set; } /// <exclude /> public DateTime? LastWriteTime { get; set; } /// <exclude /> public bool IsReadOnly { get; set; } /// <exclude /> public string FolderPath { get; set; } /// <exclude /> public string FileName { get; set; } /// <exclude /> public DataSourceId DataSourceId { get; set; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/ZipMediaFileExtractor.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Data; using Composite.Data.Transactions; using Composite.Data.Types; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ZipMediaFileExtractor { private static readonly TimeSpan ExtrationTimeout = TimeSpan.FromMinutes(15); /// <exclude /> public static void AddZip(string providerName, string parentPath, Stream compressedStream, bool recreateDirStructure, bool overwrite) { Verify.ArgumentNotNullOrEmpty(providerName, nameof(providerName)); Verify.ArgumentNotNullOrEmpty(parentPath, nameof(parentPath)); IList<IMediaFile> files; IList<IMediaFileFolder> folders; Extract(parentPath, compressedStream, out folders, out files); if (recreateDirStructure) { var folderComparer = new FolderComparer(); var currentDirs = DataFacade.GetData<IMediaFileFolder>().Where(x => x.Path.StartsWith(parentPath)); folders = folders.Except(currentDirs, folderComparer).ToList(); DataFacade.AddNew<IMediaFileFolder>(folders, providerName); AddFiles(providerName, files, overwrite); } else { foreach (IMediaFile file in files) { file.FolderPath = parentPath; } AddFiles(providerName, files, overwrite); } } private static bool Exists(IMediaFile file) { return DataFacade.GetData<IMediaFile>().Any(x => x.FolderPath == file.FolderPath && x.FileName == file.FileName); } private static void AddFiles(string providerName, IEnumerable<IMediaFile> files, bool overwrite) { foreach (IMediaFile file in files) { using (var transactionScope = TransactionsFacade.CreateNewScope(ExtrationTimeout)) { EnsureFolderExistence(file.FolderPath); if (overwrite) { if (Exists(file)) { IMediaFile currentFile = DataFacade.GetData<IMediaFile>() .First(x => x.FolderPath == file.FolderPath && x.FileName == file.FileName); using (Stream readStream = file.GetReadStream()) { using (Stream writeStream = currentFile.GetNewWriteStream()) { readStream.CopyTo(writeStream); } } DataFacade.Update(currentFile); } else { DataFacade.AddNew<IMediaFile>(file, providerName); } } else { int counter = 0; string extension = Path.GetExtension(file.FileName); string name = file.FileName.GetNameWithoutExtension(); while (Exists(file)) { counter++; file.FileName = name + counter.ToString() + extension; } DataFacade.AddNew<IMediaFile>(file, providerName); } transactionScope.Complete(); } } } private static void EnsureFolderExistence(string folderPath) { // TODO: Implement } private static void Extract(string parentPath, Stream compressedStream, out IList<IMediaFileFolder> folders, out IList<IMediaFile> files) { folders = new List<IMediaFileFolder>(); files = new List<IMediaFile>(); using (var zipArchive = new ZipArchive(compressedStream)) { foreach (var entry in zipArchive.Entries) { if (entry.FullName.EndsWith("/")) { CreateFoldersRec(folders, parentPath, entry.FullName); } else { var directory = entry.FullName.GetDirectory('/'); string fileName = entry.Name; var mediaFile = new WorkflowMediaFile { FileName = fileName, Title = fileName.GetNameWithoutExtension(), FolderPath = parentPath.Combine(directory, '/'), CreationTime = DateTime.Now, Culture = C1Console.Users.UserSettings.ActiveLocaleCultureInfo.Name, LastWriteTime = DateTime.Now, MimeType = MimeTypeInfo.GetCanonicalFromExtension(Path.GetExtension(fileName)) }; int length = CopyZipData(entry.Open(), mediaFile); mediaFile.Length = length; files.Add(mediaFile); if (directory != "") { CreateFoldersRec(folders, parentPath, directory); } } } } folders = folders.Distinct(new FolderComparer()).Where(x => x.Path != string.Empty).OrderBy(x => x.Path.Length).ToList(); } private static void CreateFoldersRec(IList<IMediaFileFolder> folders, string parentPath, string directoryEntryName) { do { CreateFolder(folders, parentPath, directoryEntryName); directoryEntryName = ReduceFolderPath(directoryEntryName); } while (directoryEntryName != null); } private static void CreateFolder(IList<IMediaFileFolder> folders, string parentPath, string directoryEntryName) { IMediaFileFolder folder = DataFacade.BuildNew<IMediaFileFolder>(); folder.Title = directoryEntryName.GetFolderName('/'); folder.Path = parentPath.Combine(directoryEntryName, '/'); folders.Add(folder); } private static string ReduceFolderPath(string folderPath) { var offset = folderPath.LastIndexOf("/", folderPath.Length - 2, StringComparison.Ordinal); return (offset > 0) ? folderPath.Substring(0, offset) : null; } private static int CopyZipData(Stream from, WorkflowMediaFile mediaFile) { var fileSize = 0; using (var streamWriter = mediaFile.GetNewWriteStream()) { var data = new byte[2048]; while (true) { var size = @from.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); fileSize += size; } else { break; } } } return fileSize; } private class FolderComparer : IEqualityComparer<IMediaFileFolder> { public bool Equals(IMediaFileFolder x, IMediaFileFolder y) { return x.Path == y.Path; } public int GetHashCode(IMediaFileFolder obj) { return obj.Path.GetHashCode(); } } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/MethodBasedFunctionAttribute.cs ================================================ using System; namespace Composite.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] [Obsolete("The MethodBasedFunction attribute is no longer required and will be removed. Please remove this attribute from your class.", true)] public sealed class MethodBasedFunctionAttribute : Attribute { } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/MethodBasedFunctionProviderElementProvider.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.C1Console.Security; using Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider; using Composite.C1Console.Workflow; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider { [ConfigurationElementType(typeof(MethodBasedFunctionProviderElementProviderData))] internal sealed class MethodBasedFunctionProviderElementProvider : BaseFunctionProviderElementProvider.BaseFunctionProviderElementProvider { private string _providerName; public static ResourceHandle AddIcon { get { return GetIconHandle("method-based-function-add"); } } public static ResourceHandle EditIcon { get { return GetIconHandle("method-based-function-edit"); } } public static ResourceHandle DeleteIcon { get { return GetIconHandle("method-based-function-delete"); } } private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); public MethodBasedFunctionProviderElementProvider(string providerName) { _providerName = providerName; } protected override string RootFolderLabel { get { return StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "RootFolderLabel"); } } protected override string RootFolderToolTip { get { return StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "RootFolderToolTip"); } } protected override IEnumerable<IFunctionTreeBuilderLeafInfo> OnGetFunctionInfos(SearchToken searchToken) { if (searchToken.IsValidKeyword()) { string keyword = searchToken.Keyword.ToLowerInvariant(); return from function in DataFacade.GetData<IMethodBasedFunctionInfo>() where function.MethodName.ToLowerInvariant().Contains(keyword) || function.Namespace.ToLowerInvariant().Contains(keyword) || function.UserMethodName.ToLowerInvariant().Contains(keyword) select (IFunctionTreeBuilderLeafInfo)new MethodFunctionTreeBuilderLeafInfo(function); } else { IEnumerable<IFunctionTreeBuilderLeafInfo> methodBasedFunctions = from function in DataFacade.GetData<IMethodBasedFunctionInfo>() select (IFunctionTreeBuilderLeafInfo)new MethodFunctionTreeBuilderLeafInfo(function); IEnumerable<IFunctionTreeBuilderLeafInfo> editableMethodBasedFunctions = from function in DataFacade.GetData<IInlineFunction>() select (IFunctionTreeBuilderLeafInfo)new EditableMethodFunctionTreeBuilderLeafInfo(function); return methodBasedFunctions.Concat(editableMethodBasedFunctions).OrderBy(f => f.Name); } } protected override IEnumerable<Type> OnGetEntityTokenTypes() { yield return typeof(DataEntityToken); } protected override IFunctionTreeBuilderLeafInfo OnIsEntityOwner(EntityToken entityToken) { DataEntityToken dataEntityToken = entityToken as DataEntityToken; if (dataEntityToken == null) return null; if (dataEntityToken.InterfaceType == typeof(IMethodBasedFunctionInfo)) { return new MethodFunctionTreeBuilderLeafInfo(dataEntityToken.Data as IMethodBasedFunctionInfo); } else if (dataEntityToken.InterfaceType == typeof(IInlineFunction)) { return new EditableMethodFunctionTreeBuilderLeafInfo(dataEntityToken.Data as IInlineFunction); } return null; } protected override IEnumerable<ElementAction> OnGetFolderActions() { return new ElementAction[] { new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Workflows.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider.AddInlineFunctionWorkflow"), new PermissionType[] { PermissionType.Add } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "Create"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "CreateToolTip"), Icon = MethodBasedFunctionProviderElementProvider.AddIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }, new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider.AddNewMethodBasedFunctionWorkflow"), new PermissionType[] { PermissionType.Add } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "Add"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "AddToolTip"), Icon = MethodBasedFunctionProviderElementProvider.AddIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } } }; } protected override IEnumerable<ElementAction> OnGetFunctionActions(IFunctionTreeBuilderLeafInfo function) { if (function is MethodFunctionTreeBuilderLeafInfo) { return new ElementAction[] { new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider.EditMethodBasedFunctionWorkflow"), new PermissionType[] { PermissionType.Edit } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "Edit"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "EditToolTip"), Icon = MethodBasedFunctionProviderElementProvider.EditIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }, new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider.DeleteMethodBasedFunctionWorkflow"), new PermissionType[] { PermissionType.Delete } ) { Payload = GetContext().ProviderName })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "Delete"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "DeleteToolTip"), Icon = MethodBasedFunctionProviderElementProvider.DeleteIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } } }; } else if (function is EditableMethodFunctionTreeBuilderLeafInfo) { return new ElementAction[] { new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Workflows.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider.EditInlineFunctionWorkflow"), new PermissionType[] { PermissionType.Edit } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "Edit"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "EditToolTip"), Icon = MethodBasedFunctionProviderElementProvider.EditIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }, new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Workflows.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider.DeleteInlineFunctionWorkflow"), new PermissionType[] { PermissionType.Delete } ) { Payload = GetContext().ProviderName })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "Delete"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "DeleteToolTip"), Icon = MethodBasedFunctionProviderElementProvider.DeleteIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } } }; } throw new NotImplementedException(); } private sealed class MethodFunctionTreeBuilderLeafInfo : IFunctionTreeBuilderLeafInfo { private IMethodBasedFunctionInfo _function; public MethodFunctionTreeBuilderLeafInfo(IMethodBasedFunctionInfo function) { _function = function; } public string Name { get { return _function.UserMethodName; } } public string Namespace { get { return _function.Namespace; } } public EntityToken EntityToken { get { return _function.GetDataEntityToken(); } } } private sealed class EditableMethodFunctionTreeBuilderLeafInfo : IFunctionTreeBuilderLeafInfo { private IInlineFunction _function; public EditableMethodFunctionTreeBuilderLeafInfo(IInlineFunction function) { _function = function; } public string Name { get { return _function.Name; } } public string Namespace { get { return _function.Namespace; } } public EntityToken EntityToken { get { return _function.GetDataEntityToken(); } } } } [Assembler(typeof(MethodBasedFunctionProviderElementProviderAssembler))] internal sealed class MethodBasedFunctionProviderElementProviderData : HooklessElementProviderData { private const string _methodBasedFunctionProviderNameProperty = "methodBasedFunctionProviderName"; [ConfigurationProperty(_methodBasedFunctionProviderNameProperty, IsRequired = true)] public string MethodBasedFunctionProviderName { get { return (string)base[_methodBasedFunctionProviderNameProperty]; } set { base[_methodBasedFunctionProviderNameProperty] = value; } } } internal sealed class MethodBasedFunctionProviderElementProviderAssembler : IAssembler<IHooklessElementProvider, HooklessElementProviderData> { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IHooklessElementProvider Assemble(IBuilderContext context, HooklessElementProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { MethodBasedFunctionProviderElementProviderData data = (MethodBasedFunctionProviderElementProviderData)objectConfiguration; return new MethodBasedFunctionProviderElementProvider(data.MethodBasedFunctionProviderName); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PackageElementProvider/ClearServerCacheActionExecutor.cs ================================================ using Composite.C1Console.Actions; using Composite.Core.PackageSystem; using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { internal sealed class ClearServerCacheActionExecutor : IActionExecutor { public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { PackageServerFacade.ClearServerCache(); return null; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PackageElementProvider/ClearServerCacheActionToken.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Actions; using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { [ActionExecutor(typeof(ClearServerCacheActionExecutor))] internal sealed class ClearServerCacheActionToken : ActionToken { private static PermissionType[] _permissionTypes = new PermissionType[] { PermissionType.Administrate }; public override IEnumerable<PermissionType> PermissionTypes { get { return _permissionTypes; } } public override string Serialize() { return "PackageElementProvider.ClearServerCache"; } public static ActionToken Deserialize(string serializedData) { return new ClearServerCacheActionToken(); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PackageElementProvider/InstallLocalPackageWorkflow.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Forms.CoreUiControls; using Composite.Core.PackageSystem; using Composite.Core.ResourceSystem; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { /// <exclude /> [Obsolete("Is used while processing upgrade packages from C1 3.1 and older. To be removed once lower requirement for upgrade package is at least v3.2")] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class InstallLocalPackageWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { /// <exclude /> public InstallLocalPackageWorkflow() { InitializeComponent(); } private void WasFileSelected(object sender, System.Workflow.Activities.ConditionalEventArgs e) { UploadedFile uploadedFile = this.GetBinding<UploadedFile>("UploadedFile"); e.Result = uploadedFile.HasFile; } private void DidValidate(object sender, System.Workflow.Activities.ConditionalEventArgs e) { e.Result = this.BindingExist("Errors") == false; } private void initializeCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { this.UpdateBinding("LayoutLabel", StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallLocalPackage.ShowError.LayoutLabel")); this.UpdateBinding("TableCaption", StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallLocalPackage.ShowError.InfoTableCaption")); this.Bindings.Add("UploadedFile", new UploadedFile()); } private void step1CodeActivity_ValidateInstallation_ExecuteCode(object sender, EventArgs e) { try { UploadedFile uploadedFile = this.GetBinding<UploadedFile>("UploadedFile"); PackageManagerInstallProcess packageManagerInstallProcess = PackageManager.Install(uploadedFile.FileStream, true); if (packageManagerInstallProcess.PreInstallValidationResult.Count > 0) { this.UpdateBinding("Errors", WorkflowHelper.ValidationResultToBinding(packageManagerInstallProcess.PreInstallValidationResult)); } else { List<PackageFragmentValidationResult> validationResult = packageManagerInstallProcess.Validate(); if (validationResult.Count > 0) { this.UpdateBinding("LayoutLabel", StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallLocalPackage.ShowWarning.LayoutLabel")); this.UpdateBinding("TableCaption", StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallLocalPackage.ShowWarning.InfoTableCaption")); this.UpdateBinding("Errors", WorkflowHelper.ValidationResultToBinding(validationResult)); } else { this.Bindings.Add("PackageManagerInstallProcess", packageManagerInstallProcess); this.Bindings.Add("FlushOnCompletion", packageManagerInstallProcess.FlushOnCompletion); this.Bindings.Add("ReloadConsoleOnCompletion", packageManagerInstallProcess.ReloadConsoleOnCompletion); } } } catch (Exception ex) { this.UpdateBinding("Errors", new List<List<string>> { new List<string> { ex.Message, "" } }); } } private void step2CodeActivity_Install_ExecuteCode(object sender, EventArgs e) { try { PackageManagerInstallProcess packageManagerInstallProcess = this.GetBinding<PackageManagerInstallProcess>("PackageManagerInstallProcess"); List<PackageFragmentValidationResult> installResult = packageManagerInstallProcess.Install(); if (installResult.Count > 0) { this.UpdateBinding("Errors", WorkflowHelper.ValidationResultToBinding(installResult)); } } catch (Exception ex) { this.UpdateBinding("Errors", new List<List<string>> { new List<string> { ex.Message, "" } }); } } private void cleanupCodeActivity_Cleanup_ExecuteCode(object sender, EventArgs e) { PackageManagerInstallProcess packageManagerInstallProcess; if (this.TryGetBinding<PackageManagerInstallProcess>("PackageManagerInstallProcess", out packageManagerInstallProcess)) { packageManagerInstallProcess.CancelInstallation(); } } private void step3CodeActivity_RefreshTree_ExecuteCode(object sender, EventArgs e) { if (this.GetBinding<bool>("ReloadConsoleOnCompletion")) { ConsoleMessageQueueFacade.Enqueue(new RebootConsoleMessageQueueItem(), null); } if (this.GetBinding<bool>("FlushOnCompletion")) { GlobalEventSystemFacade.FlushTheSystem(); } SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(new PackageElementProviderRootEntityToken()); } private void showErrorCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { List<string> rowHeader = new List<string>(); rowHeader.Add(StringResourceSystemFacade.ParseString("${Composite.Plugins.PackageElementProvider, InstallLocalPackage.ShowError.MessageTitle}")); this.UpdateBinding("ErrorHeader", rowHeader); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PackageElementProvider/InstallLocalPackageWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { partial class InstallLocalPackageWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity5 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.step1If_DidValidate = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity2 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.cleanupCodeActivity_Cleanup = new System.Workflow.Activities.CodeActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.step3CodeActivity_RefreshTree = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step3WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.showErrorWizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.showErrorCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity11 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step2IfElseActivity_DidValidate = new System.Workflow.Activities.IfElseActivity(); this.step2CodeActivity_Install = new System.Workflow.Activities.CodeActivity(); this.nextHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.step2WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.step1CodeActivity_ValidateInstallation = new System.Workflow.Activities.CodeActivity(); this.nextHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.step1WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.cleanupStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step3EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step3StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.showErrorEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.showErrorStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step2EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step2EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step2StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.cleanupStateActivity = new System.Workflow.Activities.StateActivity(); this.step3StateActivity = new System.Workflow.Activities.StateActivity(); this.showErrorStateActivity = new System.Workflow.Activities.StateActivity(); this.step2StateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "showErrorStateActivity"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "step3StateActivity"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "showErrorStateActivity"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "step2StateActivity"; // // ifElseBranchActivity5 // this.ifElseBranchActivity5.Activities.Add(this.setStateActivity9); this.ifElseBranchActivity5.Name = "ifElseBranchActivity5"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity6); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DidValidate); this.ifElseBranchActivity4.Condition = codecondition1; this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity4); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // step1If_DidValidate // this.step1If_DidValidate.Activities.Add(this.setStateActivity3); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DidValidate); this.step1If_DidValidate.Condition = codecondition2; this.step1If_DidValidate.Name = "step1If_DidValidate"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity2 // this.closeCurrentViewActivity2.Name = "closeCurrentViewActivity2"; // // cleanupCodeActivity_Cleanup // this.cleanupCodeActivity_Cleanup.Name = "cleanupCodeActivity_Cleanup"; this.cleanupCodeActivity_Cleanup.ExecuteCode += new System.EventHandler(this.cleanupCodeActivity_Cleanup_ExecuteCode); // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // step3CodeActivity_RefreshTree // this.step3CodeActivity_RefreshTree.Name = "step3CodeActivity_RefreshTree"; this.step3CodeActivity_RefreshTree.ExecuteCode += new System.EventHandler(this.step3CodeActivity_RefreshTree_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // step3WizardFormActivity // this.step3WizardFormActivity.ContainerLabel = null; this.step3WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallLocalPackageStep3.xml"; this.step3WizardFormActivity.Name = "step3WizardFormActivity"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "finalStateActivity"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // showErrorWizardFormActivity // this.showErrorWizardFormActivity.ContainerLabel = null; this.showErrorWizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallLocalPackageShowError.xml"; this.showErrorWizardFormActivity.Name = "showErrorWizardFormActivity"; // // showErrorCodeActivity_Initialize // this.showErrorCodeActivity_Initialize.Name = "showErrorCodeActivity_Initialize"; this.showErrorCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.showErrorCodeActivity_Initialize_ExecuteCode); // // setStateActivity11 // this.setStateActivity11.Name = "setStateActivity11"; this.setStateActivity11.TargetStateName = "cleanupStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // step2IfElseActivity_DidValidate // this.step2IfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity4); this.step2IfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity5); this.step2IfElseActivity_DidValidate.Name = "step2IfElseActivity_DidValidate"; // // step2CodeActivity_Install // this.step2CodeActivity_Install.Name = "step2CodeActivity_Install"; this.step2CodeActivity_Install.ExecuteCode += new System.EventHandler(this.step2CodeActivity_Install_ExecuteCode); // // nextHandleExternalEventActivity2 // this.nextHandleExternalEventActivity2.EventName = "Next"; this.nextHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity2.Name = "nextHandleExternalEventActivity2"; // // step2WizardFormActivity // this.step2WizardFormActivity.ContainerLabel = null; this.step2WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallLocalPackageStep2.xml"; this.step2WizardFormActivity.Name = "step2WizardFormActivity"; // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "cleanupStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.step1If_DidValidate); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // step1CodeActivity_ValidateInstallation // this.step1CodeActivity_ValidateInstallation.Name = "step1CodeActivity_ValidateInstallation"; this.step1CodeActivity_ValidateInstallation.ExecuteCode += new System.EventHandler(this.step1CodeActivity_ValidateInstallation_ExecuteCode); // // nextHandleExternalEventActivity1 // this.nextHandleExternalEventActivity1.EventName = "Next"; this.nextHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity1.Name = "nextHandleExternalEventActivity1"; // // step1WizardFormActivity // this.step1WizardFormActivity.ContainerLabel = null; this.step1WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallLocalPackageStep1.xml"; this.step1WizardFormActivity.Name = "step1WizardFormActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // initializeCodeActivity_Initialize // this.initializeCodeActivity_Initialize.Name = "initializeCodeActivity_Initialize"; this.initializeCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_Initialize_ExecuteCode); // // cleanupStateInitializationActivity // this.cleanupStateInitializationActivity.Activities.Add(this.cleanupCodeActivity_Cleanup); this.cleanupStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity2); this.cleanupStateInitializationActivity.Activities.Add(this.setStateActivity5); this.cleanupStateInitializationActivity.Name = "cleanupStateInitializationActivity"; // // step3EventDrivenActivity_Finish // this.step3EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step3EventDrivenActivity_Finish.Activities.Add(this.closeCurrentViewActivity1); this.step3EventDrivenActivity_Finish.Activities.Add(this.step3CodeActivity_RefreshTree); this.step3EventDrivenActivity_Finish.Activities.Add(this.setStateActivity7); this.step3EventDrivenActivity_Finish.Name = "step3EventDrivenActivity_Finish"; // // step3StateInitializationActivity // this.step3StateInitializationActivity.Activities.Add(this.step3WizardFormActivity); this.step3StateInitializationActivity.Name = "step3StateInitializationActivity"; // // showErrorEventDrivenActivity_Finish // this.showErrorEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.showErrorEventDrivenActivity_Finish.Activities.Add(this.setStateActivity8); this.showErrorEventDrivenActivity_Finish.Name = "showErrorEventDrivenActivity_Finish"; // // showErrorStateInitializationActivity // this.showErrorStateInitializationActivity.Activities.Add(this.showErrorCodeActivity_Initialize); this.showErrorStateInitializationActivity.Activities.Add(this.showErrorWizardFormActivity); this.showErrorStateInitializationActivity.Name = "showErrorStateInitializationActivity"; // // step2EventDrivenActivity_Cancel // this.step2EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.step2EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity11); this.step2EventDrivenActivity_Cancel.Name = "step2EventDrivenActivity_Cancel"; // // step2EventDrivenActivity_Next // this.step2EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity2); this.step2EventDrivenActivity_Next.Activities.Add(this.step2CodeActivity_Install); this.step2EventDrivenActivity_Next.Activities.Add(this.step2IfElseActivity_DidValidate); this.step2EventDrivenActivity_Next.Name = "step2EventDrivenActivity_Next"; // // step2StateInitializationActivity // this.step2StateInitializationActivity.Activities.Add(this.step2WizardFormActivity); this.step2StateInitializationActivity.Name = "step2StateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity10); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Next // this.step1EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity1); this.step1EventDrivenActivity_Next.Activities.Add(this.step1CodeActivity_ValidateInstallation); this.step1EventDrivenActivity_Next.Activities.Add(this.ifElseActivity1); this.step1EventDrivenActivity_Next.Name = "step1EventDrivenActivity_Next"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1WizardFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_Initialize); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "cleanupStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // cleanupStateActivity // this.cleanupStateActivity.Activities.Add(this.cleanupStateInitializationActivity); this.cleanupStateActivity.Name = "cleanupStateActivity"; // // step3StateActivity // this.step3StateActivity.Activities.Add(this.step3StateInitializationActivity); this.step3StateActivity.Activities.Add(this.step3EventDrivenActivity_Finish); this.step3StateActivity.Name = "step3StateActivity"; // // showErrorStateActivity // this.showErrorStateActivity.Activities.Add(this.showErrorStateInitializationActivity); this.showErrorStateActivity.Activities.Add(this.showErrorEventDrivenActivity_Finish); this.showErrorStateActivity.Name = "showErrorStateActivity"; // // step2StateActivity // this.step2StateActivity.Activities.Add(this.step2StateInitializationActivity); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Next); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Cancel); this.step2StateActivity.Name = "step2StateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Next); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // InstallLocalPackageWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.step2StateActivity); this.Activities.Add(this.showErrorStateActivity); this.Activities.Add(this.step3StateActivity); this.Activities.Add(this.cleanupStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "InstallLocalPackageWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private Composite.C1Console.Workflow.Activities.WizardFormActivity step1WizardFormActivity; private EventDrivenActivity step1EventDrivenActivity_Next; private StateInitializationActivity step1StateInitializationActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity2; private CodeActivity initializeCodeActivity_Initialize; private CodeActivity step1CodeActivity_ValidateInstallation; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity3; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity step1If_DidValidate; private IfElseActivity ifElseActivity1; private Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity1; private StateActivity showErrorStateActivity; private StateActivity step2StateActivity; private Composite.C1Console.Workflow.Activities.WizardFormActivity step2WizardFormActivity; private StateInitializationActivity step2StateInitializationActivity; private CodeActivity step2CodeActivity_Install; private Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity2; private EventDrivenActivity step2EventDrivenActivity_Next; private Composite.C1Console.Workflow.Activities.WizardFormActivity step3WizardFormActivity; private StateInitializationActivity step3StateInitializationActivity; private StateActivity step3StateActivity; private SetStateActivity setStateActivity7; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity6; private EventDrivenActivity step3EventDrivenActivity_Finish; private EventDrivenActivity showErrorEventDrivenActivity_Finish; private StateInitializationActivity showErrorStateInitializationActivity; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private Composite.C1Console.Workflow.Activities.WizardFormActivity showErrorWizardFormActivity; private SetStateActivity setStateActivity8; private CodeActivity step3CodeActivity_RefreshTree; private SetStateActivity setStateActivity9; private IfElseBranchActivity ifElseBranchActivity5; private IfElseBranchActivity ifElseBranchActivity4; private IfElseActivity step2IfElseActivity_DidValidate; private CodeActivity showErrorCodeActivity_Initialize; private SetStateActivity setStateActivity5; private CodeActivity cleanupCodeActivity_Cleanup; private StateInitializationActivity cleanupStateInitializationActivity; private StateActivity cleanupStateActivity; private SetStateActivity setStateActivity11; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private SetStateActivity setStateActivity10; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step2EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Cancel; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity2; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PackageElementProvider/InstallRemotePackageWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.Core.Configuration; using Composite.Core.Logging; using Composite.Core.PackageSystem; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { /// <exclude /> [Obsolete("Is used while processing upgrade packages from C1 3.1 and older. To be removed once lower requirement for upgrade package is at least v3.2")] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class InstallRemotePackageWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { bool _packageIsFree = false; /// <exclude /> public InstallRemotePackageWorkflow() { InitializeComponent(); } private PackageDescription GetPackageDescription() { PackageElementProviderAvailablePackagesItemEntityToken castedEntityToken = (PackageElementProviderAvailablePackagesItemEntityToken)this.EntityToken; PackageDescription packageDescription = (from description in PackageSystemServices.GetFilteredAllAvailablePackages() where description.Id == castedEntityToken.PackageId select description).SingleOrDefault(); if (packageDescription == null) { this.UpdateBinding("ServerError", true); } return packageDescription; } private void IsPackageFree(object sender, ConditionalEventArgs e) { e.Result = _packageIsFree; } private void EulaAccepted(object sender, ConditionalEventArgs e) { e.Result = this.GetBinding<bool>("EulaAccepted"); } private void DidValidate(object sender, System.Workflow.Activities.ConditionalEventArgs e) { e.Result = this.BindingExist("Errors") == false; } private void initializeStateCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { this.UpdateBinding("LayoutLabel", StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallRemotePackage.ShowError.LayoutLabel")); this.UpdateBinding("TableCaption", StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallRemotePackage.ShowError.InfoTableCaption")); try { _packageIsFree = GetPackageDescription().IsFree; } catch (Exception ex) { LoggingService.LogVerbose("InstallRemotePackageWorkflowRGB(100, 100, 255)", ex.Message); this.UpdateBinding("Errors", new List<List<string>> { new List<string> { ex.Message, "" } }); } } private void step2StateStepcodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { try { if (this.BindingExist("EulaText") == false) { PackageDescription packageDescription = GetPackageDescription(); string eulaText = PackageSystemServices.GetEulaText(packageDescription); this.Bindings.Add("EulaText", eulaText); } if (this.BindingExist("EulaAccepted") == false) { this.Bindings.Add("EulaAccepted", false); } } catch (Exception ex) { this.UpdateBinding("Errors", new List<List<string>> { new List<string> { ex.Message, "" } }); } } private void step3CodeActivity_DownloadAndValidate_ExecuteCode(object sender, EventArgs e) { try { PackageDescription packageDescription = GetPackageDescription(); string packageServerSource = PackageSystemServices.GetPackageSourceNameByPackageId(packageDescription.Id, InstallationInformationFacade.InstallationId, UserSettings.CultureInfo); System.IO.Stream installFileStream = PackageServerFacade.GetInstallFileStream(packageDescription.PackageFileDownloadUrl); PackageManagerInstallProcess packageManagerInstallProcess = PackageManager.Install(installFileStream, false, packageServerSource); this.Bindings.Add("PackageManagerInstallProcess", packageManagerInstallProcess); this.Bindings.Add("FlushOnCompletion", packageManagerInstallProcess.FlushOnCompletion); this.Bindings.Add("ReloadConsoleOnCompletion", packageManagerInstallProcess.ReloadConsoleOnCompletion); if (packageManagerInstallProcess.PreInstallValidationResult.Count > 0) { this.UpdateBinding("Errors", WorkflowHelper.ValidationResultToBinding(packageManagerInstallProcess.PreInstallValidationResult)); } else { List<PackageFragmentValidationResult> validationResult = packageManagerInstallProcess.Validate(); if (validationResult.Count > 0) { this.UpdateBinding("LayoutLabel", StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallRemotePackage.ShowWarning.LayoutLabel")); this.UpdateBinding("TableCaption", StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallRemotePackage.ShowWarning.InfoTableCaption")); this.UpdateBinding("Errors", WorkflowHelper.ValidationResultToBinding(validationResult)); } else { this.UpdateBinding("Uninstallable", packageManagerInstallProcess.CanBeUninstalled == false); } } } catch (Exception ex) { this.UpdateBinding("Errors", new List<List<string>> { new List<string> { ex.Message, "" } }); } } private void showErrorCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { List<string> rowHeader = new List<string>(); rowHeader.Add(StringResourceSystemFacade.ParseString("${Composite.Plugins.PackageElementProvider, InstallRemotePackage.ShowError.MessageTitle}")); this.UpdateBinding("ErrorHeader", rowHeader); } private void step4CodeActivity_Install_ExecuteCode(object sender, EventArgs e) { PackageDescription packageDescription = GetPackageDescription(); PackageManagerInstallProcess packageManagerInstallProcess = this.GetBinding<PackageManagerInstallProcess>("PackageManagerInstallProcess"); bool installOk = false; string packageServerUrl = null; Exception exception = null; try { packageServerUrl = PackageSystemServices.GetPackageSourceNameByPackageId(packageDescription.Id, InstallationInformationFacade.InstallationId, UserSettings.CultureInfo); List<PackageFragmentValidationResult> installResult = packageManagerInstallProcess.Install(); if (installResult.Count > 0) { this.UpdateBinding("Errors", WorkflowHelper.ValidationResultToBinding(installResult)); } else { installOk = true; } } catch (Exception ex) { exception = ex; this.UpdateBinding("Errors", new List<List<string>> { new List<string> { ex.Message, "" } }); } try { if (installOk) { PackageServerFacade.RegisterPackageInstallationCompletion(packageServerUrl, InstallationInformationFacade.InstallationId, packageDescription.Id, UserSettings.Username, UserSettings.UserIPAddress.ToString()); } else { StringBuilder sb = new StringBuilder(); if (exception != null) { sb.Append(exception.ToString()); } else { List<List<string>> errors = this.GetBinding<List<List<string>>>("Errors"); foreach (List<string> list in errors) { sb.AppendLine(list[0]); } } PackageServerFacade.RegisterPackageInstallationFailure(packageServerUrl, InstallationInformationFacade.InstallationId, packageDescription.Id, UserSettings.Username, UserSettings.UserIPAddress.ToString(), sb.ToString()); } } catch (Exception ex) { LoggingService.LogWarning("InstallRemotePackageWorkflow", ex); } } private void cleanupCodeActivity_Cleanup_ExecuteCode(object sender, EventArgs e) { PackageManagerInstallProcess packageManagerInstallProcess; if (this.TryGetBinding<PackageManagerInstallProcess>("PackageManagerInstallProcess", out packageManagerInstallProcess)) { packageManagerInstallProcess.CancelInstallation(); } } private void step5CodeActivity_RefreshTree_ExecuteCode(object sender, EventArgs e) { if (this.GetBinding<bool>("ReloadConsoleOnCompletion")) { ConsoleMessageQueueFacade.Enqueue(new RebootConsoleMessageQueueItem(), null); } if (this.GetBinding<bool>("FlushOnCompletion")) { GlobalEventSystemFacade.FlushTheSystem(); } SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(new PackageElementProviderRootEntityToken()); if (this.GetBinding<bool>("ReloadConsoleOnCompletion") == false) { PackageElementProviderAvailablePackagesItemEntityToken castedEntityToken = (PackageElementProviderAvailablePackagesItemEntityToken)this.EntityToken; InstalledPackageInformation installedPackage = PackageManager.GetInstalledPackages().FirstOrDefault(f => f.Id == castedEntityToken.PackageId); var installedPackageEntityToken = new PackageElementProviderInstalledPackageItemEntityToken( installedPackage.Id, installedPackage.GroupName, installedPackage.IsLocalInstalled, installedPackage.CanBeUninstalled); ExecuteWorklow(installedPackageEntityToken, WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PackageElementProvider.ViewInstalledPackageInfoWorkflow")); } } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PackageElementProvider/InstallRemotePackageWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { partial class InstallRemotePackageWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition3 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition4 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition5 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition6 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity19 = new System.Workflow.Activities.SetStateActivity(); this.showFieldMessageActivity1 = new Composite.C1Console.Workflow.Activities.ShowFieldMessageActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity17 = new System.Workflow.Activities.SetStateActivity(); this.step2WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity18 = new System.Workflow.Activities.SetStateActivity(); this.initializeIfElseActivity_IsAddOnFree = new System.Workflow.Activities.IfElseActivity(); this.ifElseBranchActivity6 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity5 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity12 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity11 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity8 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity7 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity10 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity9 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity12 = new System.Workflow.Activities.SetStateActivity(); this.cleanupCodeActivity_Cleanup = new System.Workflow.Activities.CodeActivity(); this.setStateActivity11 = new System.Workflow.Activities.SetStateActivity(); this.step5CodeActivity_RefreshTree = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step5WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity16 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity5 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step4IfElseActivity_DidValidate = new System.Workflow.Activities.IfElseActivity(); this.step4CodeActivity_Install = new System.Workflow.Activities.CodeActivity(); this.nextHandleExternalEventActivity4 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.step4WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.showErrorWizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.showErrorCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity15 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity4 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step3IfElseActivity_DidValidate = new System.Workflow.Activities.IfElseActivity(); this.step3CodeActivity_DownloadAndValidate = new System.Workflow.Activities.CodeActivity(); this.nextHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.step3WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity14 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity2 = new System.Workflow.Activities.IfElseActivity(); this.nextHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.step2StateStepcodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity13 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.nextHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.step1WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.initializeIfElseActivity_DidValidate = new System.Workflow.Activities.IfElseActivity(); this.initializeStateCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.cleanupStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step5EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step5StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step4EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step4EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step4StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.showErrorEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.showErrorStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step3EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step3EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step3StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step2EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step2EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step2StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.cleanupStateActivity = new System.Workflow.Activities.StateActivity(); this.step5StateActivity = new System.Workflow.Activities.StateActivity(); this.step4StateActivity = new System.Workflow.Activities.StateActivity(); this.showErrorStateActivity = new System.Workflow.Activities.StateActivity(); this.step3StateActivity = new System.Workflow.Activities.StateActivity(); this.step2StateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "step1StateActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step2StateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity3); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity2); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsPackageFree); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "showErrorStateActivity"; // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "step5StateActivity"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "showErrorStateActivity"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "step4StateActivity"; // // setStateActivity19 // this.setStateActivity19.Name = "setStateActivity19"; this.setStateActivity19.TargetStateName = "step2StateActivity"; // // showFieldMessageActivity1 // this.showFieldMessageActivity1.FieldBindingPath = "EulaAccepted"; this.showFieldMessageActivity1.Message = "${Composite.Plugins.PackageElementProvider, InstallRemotePackage.Step2.AcceptMissin" + "g}"; this.showFieldMessageActivity1.Name = "showFieldMessageActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "step3StateActivity"; // // setStateActivity17 // this.setStateActivity17.Name = "setStateActivity17"; this.setStateActivity17.TargetStateName = "showErrorStateActivity"; // // step2WizardFormActivity // this.step2WizardFormActivity.ContainerLabel = null; this.step2WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallRemotePackageStep2.xml"; this.step2WizardFormActivity.Name = "step2WizardFormActivity"; // // setStateActivity18 // this.setStateActivity18.Name = "setStateActivity18"; this.setStateActivity18.TargetStateName = "showErrorStateActivity"; // // initializeIfElseActivity_IsAddOnFree // this.initializeIfElseActivity_IsAddOnFree.Activities.Add(this.ifElseBranchActivity1); this.initializeIfElseActivity_IsAddOnFree.Activities.Add(this.ifElseBranchActivity2); this.initializeIfElseActivity_IsAddOnFree.Name = "initializeIfElseActivity_IsAddOnFree"; // // ifElseBranchActivity6 // this.ifElseBranchActivity6.Activities.Add(this.setStateActivity10); this.ifElseBranchActivity6.Name = "ifElseBranchActivity6"; // // ifElseBranchActivity5 // this.ifElseBranchActivity5.Activities.Add(this.setStateActivity9); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DidValidate); this.ifElseBranchActivity5.Condition = codecondition2; this.ifElseBranchActivity5.Name = "ifElseBranchActivity5"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity7); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.setStateActivity6); codecondition3.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DidValidate); this.ifElseBranchActivity3.Condition = codecondition3; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // ifElseBranchActivity12 // this.ifElseBranchActivity12.Activities.Add(this.showFieldMessageActivity1); this.ifElseBranchActivity12.Activities.Add(this.setStateActivity19); this.ifElseBranchActivity12.Name = "ifElseBranchActivity12"; // // ifElseBranchActivity11 // this.ifElseBranchActivity11.Activities.Add(this.setStateActivity5); codecondition4.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.EulaAccepted); this.ifElseBranchActivity11.Condition = codecondition4; this.ifElseBranchActivity11.Name = "ifElseBranchActivity11"; // // ifElseBranchActivity8 // this.ifElseBranchActivity8.Activities.Add(this.setStateActivity17); this.ifElseBranchActivity8.Name = "ifElseBranchActivity8"; // // ifElseBranchActivity7 // this.ifElseBranchActivity7.Activities.Add(this.step2WizardFormActivity); codecondition5.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DidValidate); this.ifElseBranchActivity7.Condition = codecondition5; this.ifElseBranchActivity7.Name = "ifElseBranchActivity7"; // // ifElseBranchActivity10 // this.ifElseBranchActivity10.Activities.Add(this.setStateActivity18); this.ifElseBranchActivity10.Name = "ifElseBranchActivity10"; // // ifElseBranchActivity9 // this.ifElseBranchActivity9.Activities.Add(this.initializeIfElseActivity_IsAddOnFree); codecondition6.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DidValidate); this.ifElseBranchActivity9.Condition = codecondition6; this.ifElseBranchActivity9.Name = "ifElseBranchActivity9"; // // setStateActivity12 // this.setStateActivity12.Name = "setStateActivity12"; this.setStateActivity12.TargetStateName = "finalStateActivity"; // // cleanupCodeActivity_Cleanup // this.cleanupCodeActivity_Cleanup.Name = "cleanupCodeActivity_Cleanup"; this.cleanupCodeActivity_Cleanup.ExecuteCode += new System.EventHandler(this.cleanupCodeActivity_Cleanup_ExecuteCode); // // setStateActivity11 // this.setStateActivity11.Name = "setStateActivity11"; this.setStateActivity11.TargetStateName = "finalStateActivity"; // // step5CodeActivity_RefreshTree // this.step5CodeActivity_RefreshTree.Name = "step5CodeActivity_RefreshTree"; this.step5CodeActivity_RefreshTree.ExecuteCode += new System.EventHandler(this.step5CodeActivity_RefreshTree_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // step5WizardFormActivity // this.step5WizardFormActivity.ContainerLabel = null; this.step5WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallRemotePackageStep5.xml"; this.step5WizardFormActivity.Name = "step5WizardFormActivity"; // // setStateActivity16 // this.setStateActivity16.Name = "setStateActivity16"; this.setStateActivity16.TargetStateName = "cleanupStateActivity"; // // cancelHandleExternalEventActivity5 // this.cancelHandleExternalEventActivity5.EventName = "Cancel"; this.cancelHandleExternalEventActivity5.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity5.Name = "cancelHandleExternalEventActivity5"; // // step4IfElseActivity_DidValidate // this.step4IfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity5); this.step4IfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity6); this.step4IfElseActivity_DidValidate.Name = "step4IfElseActivity_DidValidate"; // // step4CodeActivity_Install // this.step4CodeActivity_Install.Name = "step4CodeActivity_Install"; this.step4CodeActivity_Install.ExecuteCode += new System.EventHandler(this.step4CodeActivity_Install_ExecuteCode); // // nextHandleExternalEventActivity4 // this.nextHandleExternalEventActivity4.EventName = "Next"; this.nextHandleExternalEventActivity4.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity4.Name = "nextHandleExternalEventActivity4"; // // step4WizardFormActivity // this.step4WizardFormActivity.ContainerLabel = null; this.step4WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallRemotePackageStep4.xml"; this.step4WizardFormActivity.Name = "step4WizardFormActivity"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "finalStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // showErrorWizardFormActivity // this.showErrorWizardFormActivity.ContainerLabel = null; this.showErrorWizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallRemotePackageShowError.xml"; this.showErrorWizardFormActivity.Name = "showErrorWizardFormActivity"; // // showErrorCodeActivity_Initialize // this.showErrorCodeActivity_Initialize.Name = "showErrorCodeActivity_Initialize"; this.showErrorCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.showErrorCodeActivity_Initialize_ExecuteCode); // // setStateActivity15 // this.setStateActivity15.Name = "setStateActivity15"; this.setStateActivity15.TargetStateName = "cleanupStateActivity"; // // cancelHandleExternalEventActivity4 // this.cancelHandleExternalEventActivity4.EventName = "Cancel"; this.cancelHandleExternalEventActivity4.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity4.Name = "cancelHandleExternalEventActivity4"; // // step3IfElseActivity_DidValidate // this.step3IfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity3); this.step3IfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity4); this.step3IfElseActivity_DidValidate.Name = "step3IfElseActivity_DidValidate"; // // step3CodeActivity_DownloadAndValidate // this.step3CodeActivity_DownloadAndValidate.Name = "step3CodeActivity_DownloadAndValidate"; this.step3CodeActivity_DownloadAndValidate.ExecuteCode += new System.EventHandler(this.step3CodeActivity_DownloadAndValidate_ExecuteCode); // // nextHandleExternalEventActivity3 // this.nextHandleExternalEventActivity3.EventName = "Next"; this.nextHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity3.Name = "nextHandleExternalEventActivity3"; // // step3WizardFormActivity // this.step3WizardFormActivity.ContainerLabel = null; this.step3WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallRemotePackageStep3.xml"; this.step3WizardFormActivity.Name = "step3WizardFormActivity"; // // setStateActivity14 // this.setStateActivity14.Name = "setStateActivity14"; this.setStateActivity14.TargetStateName = "cleanupStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // ifElseActivity2 // this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity11); this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity12); this.ifElseActivity2.Name = "ifElseActivity2"; // // nextHandleExternalEventActivity2 // this.nextHandleExternalEventActivity2.EventName = "Next"; this.nextHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity2.Name = "nextHandleExternalEventActivity2"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity7); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity8); this.ifElseActivity1.Name = "ifElseActivity1"; // // step2StateStepcodeActivity_Initialize // this.step2StateStepcodeActivity_Initialize.Name = "step2StateStepcodeActivity_Initialize"; this.step2StateStepcodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.step2StateStepcodeActivity_Initialize_ExecuteCode); // // setStateActivity13 // this.setStateActivity13.Name = "setStateActivity13"; this.setStateActivity13.TargetStateName = "cleanupStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "step2StateActivity"; // // nextHandleExternalEventActivity1 // this.nextHandleExternalEventActivity1.EventName = "Next"; this.nextHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity1.Name = "nextHandleExternalEventActivity1"; // // step1WizardFormActivity // this.step1WizardFormActivity.ContainerLabel = null; this.step1WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallRemotePackageStep1.xml"; this.step1WizardFormActivity.Name = "step1WizardFormActivity"; // // initializeIfElseActivity_DidValidate // this.initializeIfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity9); this.initializeIfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity10); this.initializeIfElseActivity_DidValidate.Name = "initializeIfElseActivity_DidValidate"; // // initializeStateCodeActivity_Initialize // this.initializeStateCodeActivity_Initialize.Name = "initializeStateCodeActivity_Initialize"; this.initializeStateCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeStateCodeActivity_Initialize_ExecuteCode); // // cleanupStateInitializationActivity // this.cleanupStateInitializationActivity.Activities.Add(this.cleanupCodeActivity_Cleanup); this.cleanupStateInitializationActivity.Activities.Add(this.setStateActivity12); this.cleanupStateInitializationActivity.Name = "cleanupStateInitializationActivity"; // // step5EventDrivenActivity_Finish // this.step5EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.step5EventDrivenActivity_Finish.Activities.Add(this.closeCurrentViewActivity1); this.step5EventDrivenActivity_Finish.Activities.Add(this.step5CodeActivity_RefreshTree); this.step5EventDrivenActivity_Finish.Activities.Add(this.setStateActivity11); this.step5EventDrivenActivity_Finish.Name = "step5EventDrivenActivity_Finish"; // // step5StateInitializationActivity // this.step5StateInitializationActivity.Activities.Add(this.step5WizardFormActivity); this.step5StateInitializationActivity.Name = "step5StateInitializationActivity"; // // step4EventDrivenActivity_Cancel // this.step4EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity5); this.step4EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity16); this.step4EventDrivenActivity_Cancel.Name = "step4EventDrivenActivity_Cancel"; // // step4EventDrivenActivity_Next // this.step4EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity4); this.step4EventDrivenActivity_Next.Activities.Add(this.step4CodeActivity_Install); this.step4EventDrivenActivity_Next.Activities.Add(this.step4IfElseActivity_DidValidate); this.step4EventDrivenActivity_Next.Name = "step4EventDrivenActivity_Next"; // // step4StateInitializationActivity // this.step4StateInitializationActivity.Activities.Add(this.step4WizardFormActivity); this.step4StateInitializationActivity.Name = "step4StateInitializationActivity"; // // showErrorEventDrivenActivity_Finish // this.showErrorEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.showErrorEventDrivenActivity_Finish.Activities.Add(this.setStateActivity8); this.showErrorEventDrivenActivity_Finish.Name = "showErrorEventDrivenActivity_Finish"; // // showErrorStateInitializationActivity // this.showErrorStateInitializationActivity.Activities.Add(this.showErrorCodeActivity_Initialize); this.showErrorStateInitializationActivity.Activities.Add(this.showErrorWizardFormActivity); this.showErrorStateInitializationActivity.Name = "showErrorStateInitializationActivity"; // // step3EventDrivenActivity_Cancel // this.step3EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity4); this.step3EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity15); this.step3EventDrivenActivity_Cancel.Name = "step3EventDrivenActivity_Cancel"; // // step3EventDrivenActivity_Next // this.step3EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity3); this.step3EventDrivenActivity_Next.Activities.Add(this.step3CodeActivity_DownloadAndValidate); this.step3EventDrivenActivity_Next.Activities.Add(this.step3IfElseActivity_DidValidate); this.step3EventDrivenActivity_Next.Name = "step3EventDrivenActivity_Next"; // // step3StateInitializationActivity // this.step3StateInitializationActivity.Activities.Add(this.step3WizardFormActivity); this.step3StateInitializationActivity.Name = "step3StateInitializationActivity"; // // step2EventDrivenActivity_Cancel // this.step2EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.step2EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity14); this.step2EventDrivenActivity_Cancel.Name = "step2EventDrivenActivity_Cancel"; // // step2EventDrivenActivity_Next // this.step2EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity2); this.step2EventDrivenActivity_Next.Activities.Add(this.ifElseActivity2); this.step2EventDrivenActivity_Next.Name = "step2EventDrivenActivity_Next"; // // step2StateInitializationActivity // this.step2StateInitializationActivity.Activities.Add(this.step2StateStepcodeActivity_Initialize); this.step2StateInitializationActivity.Activities.Add(this.ifElseActivity1); this.step2StateInitializationActivity.Name = "step2StateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity13); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Next // this.step1EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity1); this.step1EventDrivenActivity_Next.Activities.Add(this.setStateActivity4); this.step1EventDrivenActivity_Next.Name = "step1EventDrivenActivity_Next"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1WizardFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeStateCodeActivity_Initialize); this.initializeStateInitializationActivity.Activities.Add(this.initializeIfElseActivity_DidValidate); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "cleanupStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // cleanupStateActivity // this.cleanupStateActivity.Activities.Add(this.cleanupStateInitializationActivity); this.cleanupStateActivity.Name = "cleanupStateActivity"; // // step5StateActivity // this.step5StateActivity.Activities.Add(this.step5StateInitializationActivity); this.step5StateActivity.Activities.Add(this.step5EventDrivenActivity_Finish); this.step5StateActivity.Name = "step5StateActivity"; // // step4StateActivity // this.step4StateActivity.Activities.Add(this.step4StateInitializationActivity); this.step4StateActivity.Activities.Add(this.step4EventDrivenActivity_Next); this.step4StateActivity.Activities.Add(this.step4EventDrivenActivity_Cancel); this.step4StateActivity.Name = "step4StateActivity"; // // showErrorStateActivity // this.showErrorStateActivity.Activities.Add(this.showErrorStateInitializationActivity); this.showErrorStateActivity.Activities.Add(this.showErrorEventDrivenActivity_Finish); this.showErrorStateActivity.Name = "showErrorStateActivity"; // // step3StateActivity // this.step3StateActivity.Activities.Add(this.step3StateInitializationActivity); this.step3StateActivity.Activities.Add(this.step3EventDrivenActivity_Next); this.step3StateActivity.Activities.Add(this.step3EventDrivenActivity_Cancel); this.step3StateActivity.Name = "step3StateActivity"; // // step2StateActivity // this.step2StateActivity.Activities.Add(this.step2StateInitializationActivity); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Next); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Cancel); this.step2StateActivity.Name = "step2StateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Next); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // InstallRemotePackageWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.step2StateActivity); this.Activities.Add(this.step3StateActivity); this.Activities.Add(this.showErrorStateActivity); this.Activities.Add(this.step4StateActivity); this.Activities.Add(this.step5StateActivity); this.Activities.Add(this.cleanupStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "InstallRemotePackageWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private CodeActivity initializeStateCodeActivity_Initialize; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity initializeIfElseActivity_IsAddOnFree; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.WizardFormActivity step1WizardFormActivity; private StateInitializationActivity step2StateInitializationActivity; private StateInitializationActivity step1StateInitializationActivity; private StateActivity step2StateActivity; private StateActivity step1StateActivity; private C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity2; private C1Console.Workflow.Activities.WizardFormActivity step2WizardFormActivity; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity1; private EventDrivenActivity step2EventDrivenActivity_Next; private EventDrivenActivity step1EventDrivenActivity_Next; private CodeActivity step2StateStepcodeActivity_Initialize; private StateActivity showErrorStateActivity; private StateActivity step3StateActivity; private C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity3; private C1Console.Workflow.Activities.WizardFormActivity step3WizardFormActivity; private SetStateActivity setStateActivity5; private EventDrivenActivity step3EventDrivenActivity_Next; private StateInitializationActivity step3StateInitializationActivity; private CodeActivity step3CodeActivity_DownloadAndValidate; private SetStateActivity setStateActivity7; private SetStateActivity setStateActivity6; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity step3IfElseActivity_DidValidate; private StateActivity step4StateActivity; private C1Console.Workflow.Activities.WizardFormActivity step4WizardFormActivity; private StateInitializationActivity step4StateInitializationActivity; private C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity4; private EventDrivenActivity step4EventDrivenActivity_Next; private C1Console.Workflow.Activities.WizardFormActivity showErrorWizardFormActivity; private StateInitializationActivity showErrorStateInitializationActivity; private CodeActivity showErrorCodeActivity_Initialize; private CodeActivity step4CodeActivity_Install; private SetStateActivity setStateActivity10; private SetStateActivity setStateActivity9; private IfElseBranchActivity ifElseBranchActivity6; private IfElseBranchActivity ifElseBranchActivity5; private SetStateActivity setStateActivity11; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private IfElseActivity step4IfElseActivity_DidValidate; private SetStateActivity setStateActivity8; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private EventDrivenActivity step5EventDrivenActivity_Finish; private StateInitializationActivity step5StateInitializationActivity; private EventDrivenActivity showErrorEventDrivenActivity_Finish; private StateActivity step5StateActivity; private C1Console.Workflow.Activities.WizardFormActivity step5WizardFormActivity; private CodeActivity step5CodeActivity_RefreshTree; private SetStateActivity setStateActivity12; private CodeActivity cleanupCodeActivity_Cleanup; private StateInitializationActivity cleanupStateInitializationActivity; private StateActivity cleanupStateActivity; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private SetStateActivity setStateActivity14; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private SetStateActivity setStateActivity13; private EventDrivenActivity step3EventDrivenActivity_Cancel; private EventDrivenActivity step2EventDrivenActivity_Cancel; private SetStateActivity setStateActivity16; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity5; private SetStateActivity setStateActivity15; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity4; private EventDrivenActivity step4EventDrivenActivity_Cancel; private SetStateActivity setStateActivity17; private IfElseBranchActivity ifElseBranchActivity8; private IfElseBranchActivity ifElseBranchActivity7; private IfElseActivity ifElseActivity1; private SetStateActivity setStateActivity18; private IfElseBranchActivity ifElseBranchActivity10; private IfElseBranchActivity ifElseBranchActivity9; private IfElseActivity initializeIfElseActivity_DidValidate; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private IfElseBranchActivity ifElseBranchActivity12; private IfElseBranchActivity ifElseBranchActivity11; private IfElseActivity ifElseActivity2; private SetStateActivity setStateActivity19; private C1Console.Workflow.Activities.ShowFieldMessageActivity showFieldMessageActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PackageElementProvider/PackageElementProvider.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.Core.PackageSystem; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { [ConfigurationElementType(typeof(PackageElementProviderData))] internal sealed class PackageElementProvider : IHooklessElementProvider, IAuxiliarySecurityAncestorProvider { private ElementProviderContext _context; private static ResourceHandle RootClosedIcon = GetIconHandle("package-element-closed-root"); private static ResourceHandle RootOpenedIcon = GetIconHandle("package-element-opened-root"); private static ResourceHandle AvailablePackagesClosedIcon = GetIconHandle("package-element-closed-available"); private static ResourceHandle AvailablePackagesOpenedIcon = GetIconHandle("package-element-opened-available"); private static ResourceHandle InstalledPackagesClosedIcon = GetIconHandle("package-element-closed-installed"); private static ResourceHandle InstalledPackagesOpenedIcon = GetIconHandle("package-element-opened-installed"); private static ResourceHandle PackageSourcesClosedIcon = GetIconHandle("package-element-closed-sources"); private static ResourceHandle PackageSourcesOpenedIcon = GetIconHandle("package-element-opened-sources"); private static ResourceHandle PackageSourceItemClosedIcon = GetIconHandle("package-element-closed-sourceitem"); private static ResourceHandle AvailablePackagesGroupClosedIcon = GetIconHandle("package-element-closed-availablegroup"); private static ResourceHandle AvailablePackagesGroupOpenedIcon = GetIconHandle("package-element-opened-availablegroup"); private static ResourceHandle LocalPackagesClosedIcon = GetIconHandle("package-element-closed-local"); private static ResourceHandle LocalPackagesOpenedIcon = GetIconHandle("package-element-opened-local"); private static ResourceHandle InstalledPackagesGroupClosedIcon = GetIconHandle("package-element-closed-installedgroup"); private static ResourceHandle InstalledPackagesGroupOpenedIcon = GetIconHandle("package-element-opened-installedgroup"); private static ResourceHandle AvailablePackageItemIcon = GetIconHandle("package-element-closed-availableitem"); private static ResourceHandle AvailableCommercialPackageItemIcon = GetIconHandle("package-element-item-commercial"); private static ResourceHandle InstalledPackageItemIcon = GetIconHandle("package-element-closed-installeditem"); private static ResourceHandle InstalledCommercialPackageItemIcon = GetIconHandle("package-element-item-commercial"); private static ResourceHandle ClearServerCacheIcon = GetIconHandle("package-clear-servercache"); private static ResourceHandle ViewAvailableInformationIcon = GetIconHandle("package-view-availableinfo"); private static ResourceHandle ViewInstalledInformationIcon = GetIconHandle("package-view-installedinfo"); private static ResourceHandle InstallIcon = GetIconHandle("package-install-package"); private static ResourceHandle InstallLocalPackageIcon = GetIconHandle("package-install-local-package"); private static ResourceHandle AddPackageSourceIcon = GetIconHandle("package-add-source"); private static ResourceHandle DeletePackageSourceIcon = GetIconHandle("package-delete-source"); private static PermissionType[] ActionPermissions = { PermissionType.Administrate, PermissionType.Configure }; private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); public PackageElementProvider() { AuxiliarySecurityAncestorFacade.AddAuxiliaryAncestorProvider<DataEntityToken>(this); } public ElementProviderContext Context { set { _context = value; } } public IEnumerable<Element> GetRoots(SearchToken seachToken) { Element element = new Element(_context.CreateElementHandle(new PackageElementProviderRootEntityToken())); element.VisualData = new ElementVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "RootFolderLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "RootFolderToolTip"), HasChildren = true, Icon = RootClosedIcon, OpenedIcon = RootOpenedIcon }; AddInstallLocalPackageAction(element); yield return element; } private static void AddInstallLocalPackageAction(Element element) { element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PackageElementProvider.InstallLocalPackageWorkflow"), ActionPermissions))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallLocalPackageLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallLocalPackageToolTip"), Disabled = false, Icon = InstallLocalPackageIcon, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); } public IEnumerable<Element> GetChildren(EntityToken entityToken, SearchToken seachToken) { if (entityToken is PackageElementProviderRootEntityToken) { return GetRootChildren(seachToken); } if (entityToken is PackageElementProviderAvailablePackagesFolderEntityToken) { return GetAvailablePackagesFolderChildren(seachToken); } if (entityToken is PackageElementProviderAvailablePackagesGroupFolderEntityToken availableGroupEntityToken) { return GetAvailablePackageGroupFolderChildren(availableGroupEntityToken.GroupName, seachToken); } if (entityToken is PackageElementProviderInstalledPackageFolderEntityToken) { return GetInstalledPackageFolderChildren(seachToken); } if (entityToken is PackageElementProviderPackageSourcesFolderEntityToken) { return GetPackageSourcesFolderChildren(seachToken); } if (entityToken is PackageElementProviderInstalledPackageLocalPackagesFolderEntityToken) { return GetInstalledLocalPackagesFolderChildren(seachToken); } if (entityToken is PackageElementProviderInstalledPackageGroupFolderEntityToken installedGroupEntityToken) { return GetInstalledPackageGroupFolderChildren(installedGroupEntityToken.GroupName, seachToken); } throw new InvalidOperationException("Unexpected entity token type: " + entityToken.GetType()); } public Dictionary<EntityToken, IEnumerable<EntityToken>> GetParents(IEnumerable<EntityToken> entityTokens) { var result = new Dictionary<EntityToken, IEnumerable<EntityToken>>(); foreach (EntityToken entityToken in entityTokens) { var dataEntityToken = (DataEntityToken) entityToken ; Type type = dataEntityToken.InterfaceType; if (type != typeof(IPackageServerSource)) continue; var newEntityToken = new PackageElementProviderPackageSourcesFolderEntityToken(); result.Add(entityToken, new EntityToken[] { newEntityToken }); } return result; } private IEnumerable<Element> GetRootChildren(SearchToken seachToken) { Element availablePackagesElement = new Element(_context.CreateElementHandle(new PackageElementProviderAvailablePackagesFolderEntityToken())); availablePackagesElement.VisualData = new ElementVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "AvailablePackagesFolderLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "AvailablePackagesFolderToolTip"), HasChildren = true, Icon = AvailablePackagesClosedIcon, OpenedIcon = AvailablePackagesOpenedIcon }; availablePackagesElement.AddAction(new ElementAction(new ActionHandle(new ClearServerCacheActionToken())) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "ClearServerCacheLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "ClearServerCacheToolTip"), Disabled = false, Icon = ClearServerCacheIcon, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = false, ActionGroup = PrimaryActionGroup } } }); yield return availablePackagesElement; Element installedPackagesElement = new Element(_context.CreateElementHandle(new PackageElementProviderInstalledPackageFolderEntityToken())); installedPackagesElement.VisualData = new ElementVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstalledPackageFolderLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstalledPackageFolderToolTip"), HasChildren = true, Icon = InstalledPackagesClosedIcon, OpenedIcon = InstalledPackagesOpenedIcon }; yield return installedPackagesElement; Element packageSourcesElement = new Element(_context.CreateElementHandle(new PackageElementProviderPackageSourcesFolderEntityToken())); packageSourcesElement.VisualData = new ElementVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "PackageSourcesFolderLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "PackageSourcesFolderToolTip"), HasChildren = DataFacade.GetData<IPackageServerSource>().Any(), Icon = PackageSourcesClosedIcon, OpenedIcon = PackageSourcesOpenedIcon }; packageSourcesElement.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PackageElementProvider.AddPackageSourceWorkflow"), new PermissionType[] { PermissionType.Administrate }))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "AddPackageSourceLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "AddPackageSourceToolTip"), Disabled = false, Icon = AddPackageSourceIcon, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); yield return packageSourcesElement; } private IEnumerable<Element> GetAvailablePackagesFolderChildren(SearchToken seachToken) { IEnumerable<string> groupNames = (from description in PackageSystemServices.GetFilteredAllAvailablePackages() select description.GroupName).Distinct(); foreach (string groupName in groupNames.OrderBy(f=>f)) { Element element = new Element(_context.CreateElementHandle(new PackageElementProviderAvailablePackagesGroupFolderEntityToken(groupName))); element.VisualData = new ElementVisualizedData { Label = groupName, ToolTip = groupName, HasChildren = true, Icon = AvailablePackagesGroupClosedIcon, OpenedIcon = AvailablePackagesGroupOpenedIcon }; yield return element; } } private IEnumerable<Element> GetAvailablePackageGroupFolderChildren(string groupName, SearchToken seachToken) { IEnumerable<PackageDescription> packageDescriptions = (from description in PackageSystemServices.GetFilteredAllAvailablePackages() where description.GroupName == groupName orderby description.Name select description); foreach (PackageDescription packageDescription in packageDescriptions) { ResourceHandle packageIcon = (packageDescription.PriceAmmount > 0 || packageDescription.AvailableInSubscriptions.Any( f=>f.Purchasable ) ? AvailableCommercialPackageItemIcon : AvailablePackageItemIcon); Element element = new Element(_context.CreateElementHandle(new PackageElementProviderAvailablePackagesItemEntityToken( packageDescription.Id.ToString(), packageDescription.GroupName))); element.VisualData = new ElementVisualizedData { Label = packageDescription.Name, ToolTip = packageDescription.Name, HasChildren = false, Icon = packageIcon, }; if (!string.IsNullOrEmpty(packageDescription.ConsoleBrowserUrl)) { element.PropertyBag.Add("BrowserUrl", packageDescription.ConsoleBrowserUrl); element.PropertyBag.Add("BrowserToolingOn", "false"); } element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PackageElementProvider.ViewAvailablePackageInfoWorkflowWorkflow"), ActionPermissions))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "ViewAvailableInformationLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "ViewAvailableInformationToolTip"), Icon = ViewAvailableInformationIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PackageElementProvider.InstallRemotePackageWorkflow"), ActionPermissions))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallToolTip"), Icon = InstallIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); yield return element; } } private IEnumerable<Element> GetInstalledPackageFolderChildren(SearchToken seachToken) { bool hasLocalPackageChildren = (from info in PackageManager.GetInstalledPackages() where info.IsLocalInstalled select info.Name).FirstOrDefault() != null; Element localPackagesElement = new Element(_context.CreateElementHandle(new PackageElementProviderInstalledPackageLocalPackagesFolderEntityToken())); localPackagesElement.VisualData = new ElementVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "LocalPackagesFolderLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "LocalPackagesFolderToolTip"), HasChildren = hasLocalPackageChildren, Icon = LocalPackagesClosedIcon, OpenedIcon = LocalPackagesOpenedIcon }; AddInstallLocalPackageAction(localPackagesElement); yield return localPackagesElement; IEnumerable<string> groupNames = (from info in PackageManager.GetInstalledPackages() where info.IsLocalInstalled == false orderby info.GroupName select info.GroupName).Distinct(); foreach (string groupName in groupNames) { Element element = new Element(_context.CreateElementHandle(new PackageElementProviderInstalledPackageGroupFolderEntityToken(groupName))); element.VisualData = new ElementVisualizedData { Label = groupName, ToolTip = groupName, HasChildren = true, Icon = InstalledPackagesGroupClosedIcon, OpenedIcon = InstalledPackagesGroupOpenedIcon }; yield return element; } } private IEnumerable<Element> GetPackageSourcesFolderChildren(SearchToken seachToken) { List<IPackageServerSource> packageServerSources = (from a in DataFacade.GetData<IPackageServerSource>() orderby a.Url select a).ToList(); foreach (IPackageServerSource packageServerSource in packageServerSources) { var element = new Element(_context.CreateElementHandle(packageServerSource.GetDataEntityToken())) { VisualData = new ElementVisualizedData { Label = packageServerSource.Url, ToolTip = packageServerSource.Url, HasChildren = false, Icon = PackageSourceItemClosedIcon } }; element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PackageElementProvider.DeletePackageSourceWorkflow"), new PermissionType[] { PermissionType.Administrate }))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "DeletePackageSourceLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "DeletePackageSourceToolTip"), Icon = DeletePackageSourceIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); yield return element; } } private IEnumerable<Element> GetInstalledLocalPackagesFolderChildren(SearchToken seachToken) { return GetInstalledPackagesElements(package => package.IsLocalInstalled); } private IEnumerable<Element> GetInstalledPackageGroupFolderChildren(string groupName, SearchToken seachToken) { return GetInstalledPackagesElements(package => package.GroupName == groupName && !package.IsLocalInstalled); } private IEnumerable<Element> GetInstalledPackagesElements(Predicate<InstalledPackageInformation> filter) { IEnumerable<InstalledPackageInformation> installedPackageInformations = from info in PackageManager.GetInstalledPackages() where filter(info) orderby info.Name select info; var serverPackagesPreviewUrls = PackageSystemServices.GetAllAvailablePackages() .Where(p => !string.IsNullOrEmpty(p.ConsoleBrowserUrl)) .GroupBy(p => p.Id) .ToDictionary(group => group.Key, group => group.First().ConsoleBrowserUrl); foreach (var installedPackageInformation in installedPackageInformations) { var element = new Element(_context.CreateElementHandle(new PackageElementProviderInstalledPackageItemEntityToken( installedPackageInformation.Id, installedPackageInformation.GroupName, installedPackageInformation.IsLocalInstalled, installedPackageInformation.CanBeUninstalled))); if (serverPackagesPreviewUrls.TryGetValue(installedPackageInformation.Id, out var previewUrl)) { element.PropertyBag.Add("BrowserUrl", previewUrl); element.PropertyBag.Add("BrowserToolingOn", "false"); } element.VisualData = new ElementVisualizedData { Label = installedPackageInformation.Name, ToolTip = installedPackageInformation.Name, HasChildren = false, Icon = GetIconForPackageItem(installedPackageInformation.Id), }; element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PackageElementProvider.ViewInstalledPackageInfoWorkflow"), ActionPermissions))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "ViewInstalledInformationLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "ViewInstalledInformationToolTip"), Icon = ViewInstalledInformationIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); yield return element; } } private ResourceHandle GetIconForPackageItem(Guid packageId) { ResourceHandle icon = InstalledPackageItemIcon; PackageLicenseDefinition licenseDef = PackageLicenseHelper.GetLicenseDefinition(packageId); if (licenseDef != null && !licenseDef.Permanent) { icon = InstalledCommercialPackageItemIcon; } return icon; } private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } } [Assembler(typeof(NonConfigurableHooklessElementProviderAssembler))] internal sealed class PackageElementProviderData : HooklessElementProviderData { } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PackageElementProvider/PackageElementProviderAvailablePackagesFolderEntityToken.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { internal sealed class PackageElementProviderAvailablePackagesFolderEntityTokenAncestorProvider : ISecurityAncestorProvider { public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { if (entityToken == null) throw new ArgumentNullException("entityToken"); yield return new PackageElementProviderRootEntityToken(); } } /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(PackageElementProviderAvailablePackagesFolderEntityTokenAncestorProvider))] public sealed class PackageElementProviderAvailablePackagesFolderEntityToken : EntityToken { /// <exclude /> public override string Type { get { return ""; } } /// <exclude /> public override string Source { get { return ""; } } /// <exclude /> public override string Id { get { return "PackageElementProviderAvailablePackagesFolderEntityToken"; } } /// <exclude /> public override string Serialize() { return DoSerialize(); } /// <exclude /> public static EntityToken Deserialize(string serializedEntityToken) { return new PackageElementProviderAvailablePackagesFolderEntityToken(); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PackageElementProvider/PackageElementProviderAvailablePackagesGroupFolderEntityToken.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security; using Newtonsoft.Json; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { internal sealed class PackageElementProviderAvailablePackagesGroupFolderEntityTokenAncestorProvider : ISecurityAncestorProvider { public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { if (entityToken == null) throw new ArgumentNullException("entityToken"); yield return new PackageElementProviderAvailablePackagesFolderEntityToken(); } } [SecurityAncestorProvider(typeof(PackageElementProviderAvailablePackagesGroupFolderEntityTokenAncestorProvider))] internal sealed class PackageElementProviderAvailablePackagesGroupFolderEntityToken : EntityToken { public PackageElementProviderAvailablePackagesGroupFolderEntityToken(string groupName) { this.GroupName = groupName; } [JsonIgnore] public string GroupName { get; private set; } public override string Type { get { return ""; } } public override string Source { get { return ""; } } public override string Id { get { return this.GroupName; } } public override string Serialize() { return DoSerialize(); } public static EntityToken Deserialize(string serializedEntityToken) { string type, source, id; DoDeserialize(serializedEntityToken, out type, out source, out id); return new PackageElementProviderAvailablePackagesGroupFolderEntityToken(id); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PackageElementProvider/PackageElementProviderAvailablePackagesItemEntityToken.cs ================================================ using System; using System.Collections.Generic; using System.Text; using Composite.C1Console.Security; using Composite.Core; using Composite.Core.Serialization; using Newtonsoft.Json; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { internal sealed class PackageElementProviderAvailablePackagesItemEntityTokenAncestorProvider : ISecurityAncestorProvider { public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { var castedToken = (PackageElementProviderAvailablePackagesItemEntityToken) entityToken; yield return new PackageElementProviderAvailablePackagesGroupFolderEntityToken(castedToken.GroupName); } } /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(PackageElementProviderAvailablePackagesItemEntityTokenAncestorProvider))] public sealed class PackageElementProviderAvailablePackagesItemEntityToken : EntityToken { /// <exclude /> [JsonConstructor] public PackageElementProviderAvailablePackagesItemEntityToken(string id, string groupName) { Id = id; this.GroupName = groupName; } /// <exclude /> public string GroupName { get; private set; } /// <exclude /> public Guid PackageId => new Guid(this.Id); /// <exclude /> public override string Type => ""; /// <exclude /> public override string Source => ""; /// <exclude /> public override string Id { get; } /// <exclude /> public override string Serialize() { return CompositeJsonSerializer.Serialize(this); } /// <exclude /> public static EntityToken Deserialize(string serializedEntityToken) { EntityToken entityToken; if (CompositeJsonSerializer.IsJsonSerialized(serializedEntityToken)) { entityToken = CompositeJsonSerializer.Deserialize<PackageElementProviderAvailablePackagesItemEntityToken>(serializedEntityToken); } else { entityToken = DeserializeLegacy(serializedEntityToken); Log.LogVerbose(nameof(PackageElementProviderAvailablePackagesItemEntityToken), entityToken.GetType().FullName); } return entityToken; } /// <exclude /> public static EntityToken DeserializeLegacy(string serializedEntityToken) { string type, source, id; Dictionary<string, string> dic; DoDeserialize(serializedEntityToken, out type, out source, out id, out dic); if (!dic.ContainsKey("_GroupName_")) throw new ArgumentException("serializedEntityToken is of wrong format"); string groupName = StringConversionServices.DeserializeValueString(dic["_GroupName_"]); return new PackageElementProviderAvailablePackagesItemEntityToken(id, groupName); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PackageElementProvider/PackageElementProviderInstalledPackageFolderEntityToken.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { internal sealed class PackageElementProviderInstalledPackageFolderAncestorProvider : ISecurityAncestorProvider { public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { if (entityToken == null) throw new ArgumentNullException("entityToken"); yield return new PackageElementProviderRootEntityToken(); } } [SecurityAncestorProvider(typeof(PackageElementProviderInstalledPackageFolderAncestorProvider))] internal sealed class PackageElementProviderInstalledPackageFolderEntityToken : EntityToken { public override string Type { get { return ""; } } public override string Source { get { return ""; } } public override string Id { get { return "PackageElementProviderInstalledPackageFolderEntityToken"; } } public override string Serialize() { return DoSerialize(); } public static EntityToken Deserialize(string serializedEntityToken) { return new PackageElementProviderInstalledPackageFolderEntityToken(); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PackageElementProvider/PackageElementProviderInstalledPackageGroupFolderEntityToken.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security; using Newtonsoft.Json; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { internal sealed class PackageElementProviderInstalledPackageGroupFolderEntityTokenAncestorProvider : ISecurityAncestorProvider { public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { if (entityToken == null) throw new ArgumentNullException("entityToken"); yield return new PackageElementProviderInstalledPackageFolderEntityToken(); } } [SecurityAncestorProvider(typeof(PackageElementProviderInstalledPackageGroupFolderEntityTokenAncestorProvider))] internal sealed class PackageElementProviderInstalledPackageGroupFolderEntityToken : EntityToken { public PackageElementProviderInstalledPackageGroupFolderEntityToken(string groupName) { this.GroupName = groupName; } [JsonIgnore] public string GroupName { get; private set; } public override string Type { get { return ""; } } public override string Source { get { return ""; } } public override string Id { get { return this.GroupName; } } public override string Serialize() { return DoSerialize(); } public static EntityToken Deserialize(string serializedEntityToken) { string type, source, id; DoDeserialize(serializedEntityToken, out type, out source, out id); return new PackageElementProviderInstalledPackageGroupFolderEntityToken(id); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PackageElementProvider/PackageElementProviderInstalledPackageItemEntityToken.cs ================================================ using System; using System.Collections.Generic; using System.Text; using Composite.C1Console.Security; using Composite.Core.Serialization; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { internal sealed class PackageElementProviderInstalledPackageItemEntityTokenAncestorProvider : ISecurityAncestorProvider { public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { if (entityToken == null) throw new ArgumentNullException(nameof(entityToken)); var castedEntityToken = (PackageElementProviderInstalledPackageItemEntityToken)entityToken; if (castedEntityToken.IsLocalInstalled) { yield return new PackageElementProviderInstalledPackageLocalPackagesFolderEntityToken(); } else { yield return new PackageElementProviderInstalledPackageGroupFolderEntityToken(castedEntityToken.GroupName); } } } /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(PackageElementProviderInstalledPackageItemEntityTokenAncestorProvider))] public sealed class PackageElementProviderInstalledPackageItemEntityToken : EntityToken { /// <exclude /> public PackageElementProviderInstalledPackageItemEntityToken(Guid packageId, string groupName, bool isLocalInstalled, bool canBeUninstalled) { this.PackageId = packageId; this.GroupName = groupName; this.IsLocalInstalled = isLocalInstalled; this.CanBeUninstalled = canBeUninstalled; } /// <exclude /> public Guid PackageId { get; private set; } /// <exclude /> public string GroupName { get; private set; } /// <exclude /> public bool IsLocalInstalled { get; private set; } /// <exclude /> public bool CanBeUninstalled { get; private set; } /// <exclude /> public override string Type => ""; /// <exclude /> public override string Source => ""; /// <exclude /> public override string Id => this.PackageId.ToString(); /// <exclude /> public override string Serialize() { return CompositeJsonSerializer.Serialize(this); } /// <exclude /> public static EntityToken Deserialize(string serializedEntityToken) { return CompositeJsonSerializer .Deserialize<PackageElementProviderInstalledPackageItemEntityToken>(serializedEntityToken); } /// <exclude /> public override int GetHashCode() { return base.GetHashCode() ^ this.GroupName.GetHashCode() ^ this.CanBeUninstalled.GetHashCode(); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PackageElementProvider/PackageElementProviderInstalledPackageLocalPackagesFolderEntityToken.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { internal sealed class PackageElementProviderInstalledPackageLocalPackagesFolderEntityTokenAncestorProvider : ISecurityAncestorProvider { public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { if (entityToken == null) throw new ArgumentNullException("entityToken"); yield return new PackageElementProviderInstalledPackageFolderEntityToken(); } } [SecurityAncestorProvider(typeof(PackageElementProviderInstalledPackageLocalPackagesFolderEntityTokenAncestorProvider))] internal sealed class PackageElementProviderInstalledPackageLocalPackagesFolderEntityToken : EntityToken { public override string Type { get { return ""; } } public override string Source { get { return ""; } } public override string Id { get { return "PackageElementProviderInstalledPackageLocalPackagesFolderEntityToken"; } } public override string Serialize() { return DoSerialize(); } public static EntityToken Deserialize(string serializedEntityToken) { return new PackageElementProviderInstalledPackageLocalPackagesFolderEntityToken(); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PackageElementProvider/PackageElementProviderPackageSourcesFolderEntityToken.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { internal sealed class PackageElementProviderPackageSourcesFolderEntityTokenAncestorProvider : ISecurityAncestorProvider { public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { if (entityToken == null) throw new ArgumentNullException("entityToken"); yield return new PackageElementProviderRootEntityToken(); } } [SecurityAncestorProvider(typeof(PackageElementProviderPackageSourcesFolderEntityTokenAncestorProvider))] internal sealed class PackageElementProviderPackageSourcesFolderEntityToken : EntityToken { public override string Type { get { return ""; } } public override string Source { get { return ""; } } public override string Id { get { return "PackageElementProviderPackageSourcesFolderEntityToken"; } } public override string Serialize() { return DoSerialize(); } public static EntityToken Deserialize(string serializedEntityToken) { return new PackageElementProviderPackageSourcesFolderEntityToken(); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PackageElementProvider/PackageElementProviderPackageSourcesItemEntityToken.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { internal sealed class PackageElementProviderPackageSourcesItemEntityTokenAncestorProvider : ISecurityAncestorProvider { public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { if (entityToken == null) throw new ArgumentNullException("entityToken"); yield return new PackageElementProviderPackageSourcesFolderEntityToken(); } } [SecurityAncestorProvider(typeof(PackageElementProviderPackageSourcesItemEntityTokenAncestorProvider))] internal sealed class PackageElementProviderPackageSourcesItemEntityToken : EntityToken { string _id; public PackageElementProviderPackageSourcesItemEntityToken(Guid id) { _id = id.ToString(); } public override string Type { get { return ""; } } public override string Source { get { return ""; } } public override string Id { get { return _id; } } public override string Serialize() { return DoSerialize(); } public static EntityToken Deserialize(string serializedEntityToken) { string type, source, id; DoDeserialize(serializedEntityToken, out type, out source, out id); return new PackageElementProviderPackageSourcesItemEntityToken(new Guid(id)); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PackageElementProvider/PackageElementProviderRootEntityToken.cs ================================================ using Composite.C1Console.Security; using Composite.C1Console.Security.SecurityAncestorProviders; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(NoAncestorSecurityAncestorProvider))] public sealed class PackageElementProviderRootEntityToken : EntityToken { /// <exclude /> public override string Type { get { return ""; } } /// <exclude /> public override string Source { get { return ""; } } /// <exclude /> public override string Id { get { return "PackageElementProviderRootEntityToken"; } } /// <exclude /> public override string Serialize() { return DoSerialize(); } /// <exclude /> public static EntityToken Deserialize(string serializedEntityToken) { return new PackageElementProviderRootEntityToken(); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PackageElementProvider/WorkflowHelper.cs ================================================ using System.Collections.Generic; using System.Text; using Composite.Core.PackageSystem; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class WorkflowHelper { /// <exclude /> public static object ValidationResultToBinding(List<PackageFragmentValidationResult> packageFragmentValidationResults) { List<List<string>> rows = new List<List<string>>(); foreach (PackageFragmentValidationResult packageFragmentValidationResult in packageFragmentValidationResults) { StringBuilder sb = new StringBuilder(); if (packageFragmentValidationResult.XPath != null) { sb.AppendLine(packageFragmentValidationResult.Message); //sb.Append("XPath: "); //sb.Append(packageFragmentValidationResult.XPath); } else { sb.Append(packageFragmentValidationResult.Message); } List<string> row = new List<string>(); row.Add(sb.ToString()); rows.Add(row); } return rows; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PageElementProvider/LocalOrdering/DisplayLocalOrderingActionExecutor.cs ================================================ using System; using System.Web; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider.LocalOrdering { internal sealed class DisplayLocalOrderingActionExecutor : IActionExecutor { private static string BaseUrl = "/Website/Spikes/PageLocalOrdering/ShowLocalOrdering.aspx"; public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { string currentConsoleId = flowControllerServicesContainer.GetService<Composite.C1Console.Events.IManagementConsoleMessageService>().CurrentConsoleId; DisplayLocalOrderingActionToken castedActionToken = (DisplayLocalOrderingActionToken)actionToken; string url = string.Format("{0}?ParentPageId={1}", BaseUrl, HttpUtility.UrlEncode(castedActionToken.ParentPageId.ToString())); ConsoleMessageQueueFacade.Enqueue( new OpenViewMessageQueueItem { EntityToken = EntityTokenSerializer.Serialize(entityToken, true), Url = url, ViewId = Guid.NewGuid().ToString(), ViewType = ViewType.Main, Label = "Pages local orderings" }, currentConsoleId); return null; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PageElementProvider/LocalOrdering/DisplayLocalOrderingActionToken.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Actions; using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider.LocalOrdering { [ActionExecutor(typeof(DisplayLocalOrderingActionExecutor))] internal sealed class DisplayLocalOrderingActionToken : ActionToken { private static PermissionType[] _permissionTypes = new PermissionType[] { PermissionType.Administrate }; public DisplayLocalOrderingActionToken(Guid parentPageId) { this.ParentPageId = parentPageId; } public Guid ParentPageId { get; private set; } public override bool IgnoreEntityTokenLocking => true; public override IEnumerable<PermissionType> PermissionTypes { get { return _permissionTypes; } } public override string Serialize() { return this.ParentPageId.ToString(); } public static ActionToken Deserialize(string serializedData) { Guid parentPageId = new Guid(serializedData); return new DisplayLocalOrderingActionToken(parentPageId); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PageElementProvider/PageAddActionExecuter.cs ================================================ using Composite.C1Console.Actions; using Composite.C1Console.Actions.Data; using Composite.C1Console.Security; using Composite.Data; using Composite.Data.Types; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { /// <exclude /> public class PageAddActionExecuter : IActionExecutorSerializedParameters { /// <exclude /> public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { return Execute(EntityTokenSerializer.Serialize(entityToken), ActionTokenSerializer.Serialize(actionToken), actionToken, flowControllerServicesContainer); } /// <exclude /> public FlowToken Execute(string serializedEntityToken, string serializedActionToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { PageAddActionToken pageAddActionToken = (PageAddActionToken)actionToken; var newPage = DataFacade.BuildNew<IPage>(); newPage.PageTypeId = pageAddActionToken.PageTypeId; var action = DataActionTokenResolverFacade.Resolve(newPage, ((PageAddActionToken)actionToken).ActionIdentifier); return ActionExecutorFacade.Execute(EntityTokenSerializer.Deserialize(serializedEntityToken), action, flowControllerServicesContainer); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PageElementProvider/PageAddActionToken.cs ================================================ using System; using System.Collections.Generic; using System.Text; using Composite.C1Console.Actions; using Composite.C1Console.Actions.Data; using Composite.C1Console.Security; using Composite.Core.Serialization; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ActionExecutor(typeof(PageAddActionExecuter))] class PageAddActionToken : ProxyDataActionToken { private readonly Guid _pageTypeId; /// <exclude /> public PageAddActionToken(Guid pageTypeId, ActionIdentifier actionIdentifier) : base(actionIdentifier) { _pageTypeId = pageTypeId; } /// <exclude /> public PageAddActionToken(Guid pageTypeId, ActionIdentifier actionIdentifier, IEnumerable<PermissionType> permissionTypes) : base(actionIdentifier,permissionTypes) { _pageTypeId = pageTypeId; } /// <exclude /> public Guid PageTypeId => _pageTypeId; public override string Serialize() { StringBuilder stringBuilder = new StringBuilder(base.Serialize()); StringConversionServices.SerializeKeyValuePair(stringBuilder, "_PageTypeId_", _pageTypeId); return stringBuilder.ToString(); } /// <exclude /> public new static ActionToken Deserialize(string serializedData) { Dictionary<string, string> dic = StringConversionServices.ParseKeyValueCollection(serializedData); Guid pageTypeId = StringConversionServices.DeserializeValueGuid(dic["_PageTypeId_"]); var baseProxyDataActionToken = (ProxyDataActionToken)ProxyDataActionToken.Deserialize(serializedData); var result = new PageAddActionToken(pageTypeId, baseProxyDataActionToken.ActionIdentifier, baseProxyDataActionToken.PermissionTypes) { DoIgnoreEntityTokenLocking = baseProxyDataActionToken.IgnoreEntityTokenLocking }; return result; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PageElementProvider/PageElementDynamicActionTokens.cs ================================================ using Composite.C1Console.Actions; using Composite.C1Console.Actions.Data; using Composite.C1Console.Workflow; using Composite.Core.Application; using Composite.Core.Serialization; using Composite.Data.Types; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { /// <summary> /// Here we register default actions for page element providers /// </summary> [ApplicationStartup] public static class PageElementDynamicActionTokens { /// <exclude /> public static void OnBeforeInitialize() { } /// <exclude /> public static void OnInitialized(DataActionTokenResolver resolver) { resolver.RegisterDefault<IPage>(ActionIdentifier.Add, f => new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageElementProvider.AddNewPageWorkflow")) { DoIgnoreEntityTokenLocking = true, Payload = SerializerHandlerFacade.Serialize(f) }); resolver.RegisterDefault<IPage>(ActionIdentifier.Edit, f => new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageElementProvider.EditPageWorkflow"))); resolver.RegisterDefault<IPage>(ActionIdentifier.Delete, f => new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageElementProvider.DeletePageWorkflow"))); resolver.RegisterDefault<IPage>(ActionIdentifier.Duplicate, f => new DuplicateActionToken()); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PageElementProvider/PageElementProvider.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Actions.Data; using Composite.C1Console.Elements; using Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper; using Composite.C1Console.Elements.ElementProviderHelpers.DataGroupingProviderHelper; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.Parallelization; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.Data; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.Transactions; using Composite.Data.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { [ActionTokenProvider(GenericPublishProcessControllerActionTypeNames.UndoUnpublishedChanges, typeof(PageElementProviderActionTokenProvider))] [ConfigurationElementType(typeof(PageElementProviderData))] internal class PageElementProvider : IHooklessElementProvider, IDataExchangingElementProvider, IDragAndDropElementProvider, ILocaleAwareElementProvider, IAuxiliarySecurityAncestorProvider { private ElementProviderContext _context; private AssociatedDataElementProviderHelper<IPage> _pageAssociatedHelper; public static ResourceHandle DuplicatePage = GetIconHandle("copy"); public static ResourceHandle EditPage = GetIconHandle("page-edit-page"); public static ResourceHandle LocalizePage = GetIconHandle("page-localize-page"); public static ResourceHandle ManageHostNames = GetIconHandle("page-manage-host-names"); public static ResourceHandle AddPage = GetIconHandle("page-add-page"); public static ResourceHandle ListUnpublishedItems = GetIconHandle("page-list-unpublished-items"); public static ResourceHandle AddSubPage = GetIconHandle("page-add-sub-page"); public static ResourceHandle DeletePage = GetIconHandle("page-delete-page"); public static ResourceHandle PageDraft = GetIconHandle("page-draft"); public static ResourceHandle PageAwaitingApproval = GetIconHandle("page-awaiting-approval"); public static ResourceHandle PageAwaitingPublication = GetIconHandle("page-awaiting-publication"); public static ResourceHandle PagePublication = GetIconHandle("page-publication"); public static ResourceHandle PageGhosted = GetIconHandle("page-ghosted"); public static ResourceHandle PageDisabled = GetIconHandle("page-disabled"); public static ResourceHandle RootOpen = GetIconHandle("page-root-open"); public static ResourceHandle RootClosed = GetIconHandle("page-root-closed"); public static ResourceHandle ActivateLocalization = GetIconHandle("page-activatelocalization"); public static ResourceHandle DeactivateLocalization = GetIconHandle("page-deactivatelocalization"); public static ResourceHandle AddDataAssociationTypeIcon = GetIconHandle("dataassociation-add-association"); public static ResourceHandle EditDataAssociationTypeIcon = GetIconHandle("dataassociation-edit-association"); public static ResourceHandle RemoveDataAssociationTypeIcon = GetIconHandle("dataassociation-remove-association"); private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); private static readonly ActionGroup ViewActionGroup = new ActionGroup("View", ActionGroupPriority.PrimaryLow); private static readonly ActionGroup AppendedActionGroup = new ActionGroup("Common tasks", ActionGroupPriority.GeneralAppendMedium); private static readonly ActionGroup MetaDataAppendedActionGroup = new ActionGroup("Associated data", ActionGroupPriority.PrimaryMedium); internal static readonly List<PermissionType> AddWebsitePermissionTypes = new List<PermissionType> { PermissionType.Configure, PermissionType.Administrate }; internal static readonly List<PermissionType> EditPermissionTypes = new List<PermissionType> { PermissionType.Edit }; internal static readonly List<PermissionType> DuplicatePermissionTypes = new List<PermissionType> { PermissionType.Add }; internal static readonly List<PermissionType> LocalizePermissionTypes = new List<PermissionType> { PermissionType.Edit }; internal static readonly List<PermissionType> AddPermissionTypes = new List<PermissionType> { PermissionType.Add }; internal static readonly List<PermissionType> DeletePermissionTypes = new List<PermissionType> { PermissionType.Delete }; internal static readonly string DefaultConfigurationName = "PageElementProvider"; private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } public PageElementProvider() { AuxiliarySecurityAncestorFacade.AddAuxiliaryAncestorProvider<DataEntityToken>(this); DataEvents<IPageType>.OnStoreChanged += DataEvents_IPageType_OnStoreChanged; } public ElementProviderContext Context { set { _context = value; _pageAssociatedHelper = new AssociatedDataElementProviderHelper<IPage>( _context, new PageElementProviderEntityToken(_context.ProviderName), true); } } public bool ContainsLocalizedData => true; public IEnumerable<Element> GetRoots(SearchToken searchToken) { EntityToken entityToken = new PageElementProviderEntityToken(_context.ProviderName); if (UserValidationFacade.IsLoggedIn() && !DataLocalizationFacade.ActiveLocalizationCultures.Contains(UserSettings.ActiveLocaleCultureInfo)) { yield return new Element(_context.CreateElementHandle(entityToken)) { VisualData = new ElementVisualizedData { Label = "No website access: Missing permissions to any Data Language", Icon = PageElementProvider.DeactivateLocalization } }; yield break; } ICollection<Guid> pageIds = PageServices.GetChildrenIDs(Guid.Empty); var homePageIdFilter = (searchToken as PageSearchToken)?.HomePageId ?? Guid.Empty; if (homePageIdFilter != Guid.Empty) { pageIds = pageIds.Where(p => p == homePageIdFilter).ToList(); } 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 = pageIds.Count != 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 Content", //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; } public IEnumerable<Element> GetChildren(EntityToken entityToken, SearchToken searchToken) { if (UserValidationFacade.IsLoggedIn() && !DataLocalizationFacade.ActiveLocalizationCultures.Contains(UserSettings.ActiveLocaleCultureInfo)) { return Enumerable.Empty<Element>(); } if (entityToken is AssociatedDataElementProviderHelperEntityToken associatedData) { return _pageAssociatedHelper.GetChildren(associatedData, false); } if (entityToken is DataGroupingProviderHelperEntityToken dataGrouping) { return _pageAssociatedHelper.GetChildren(dataGrouping, false); } using (new DataScope(DataScopeIdentifier.Administrated)) { var allChildPages = GetChildrenPages(entityToken, searchToken); List<KeyValuePair<PageLocaleState, IPage>> childPages = IEnumerableExtensionMethods.ToList(allChildPages, f => new KeyValuePair<PageLocaleState, IPage>(PageLocaleState.Own, f)); List<Element> childPageElements = GetElements(childPages, entityToken is PageElementProviderEntityToken); return GetChildElements(entityToken, childPageElements); } } public IEnumerable<Element> GetForeignRoots(SearchToken searchToken) { return GetRoots(searchToken); } public IEnumerable<Element> GetForeignChildren(EntityToken entityToken, SearchToken searchToken) { if (entityToken is DataEntityToken dataEntityToken && dataEntityToken.Data == null) return Array.Empty<Element>(); if (UserValidationFacade.IsLoggedIn() && !DataLocalizationFacade.ActiveLocalizationCultures.Contains(UserSettings.ActiveLocaleCultureInfo)) { return Enumerable.Empty<Element>(); } if (entityToken is AssociatedDataElementProviderHelperEntityToken associatedData) { return _pageAssociatedHelper.GetChildren(associatedData, true); } if (entityToken is DataGroupingProviderHelperEntityToken dataGrouping) { return _pageAssociatedHelper.GetChildren(dataGrouping, 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, true); return GetChildElements(entityToken, childPageElements); } public Dictionary<EntityToken, IEnumerable<EntityToken>> GetParents(IEnumerable<EntityToken> entityTokens) { var result = new Dictionary<EntityToken, IEnumerable<EntityToken>>(); foreach (EntityToken entityToken in entityTokens) { var dataEntityToken = (DataEntityToken) entityToken; Type type = dataEntityToken.InterfaceType; if (type != typeof(IPage)) continue; Guid pageId = (Guid) dataEntityToken.DataSourceId.GetKeyValue(nameof(IPage.Id)); Guid parentPageId = PageManager.GetParentId(pageId); if (parentPageId != Guid.Empty) { if (!GlobalSettingsFacade.AllowChildPagesTranslationWithoutParent) continue; using (new DataScope(dataEntityToken.DataSourceId.LocaleScope)) { var parentPage = PageManager.GetPageById(parentPageId); if (parentPage != null) continue; } } result.Add(entityToken, new EntityToken[] { new PageElementProviderEntityToken(_context.ProviderName) }); } return result; } private IEnumerable<Element> GetChildElements(EntityToken entityToken, IEnumerable<Element> childPageElements) { Guid? itemId = GetParentPageId(entityToken); if (!itemId.HasValue) return new Element[] { }; List<Element> associatedChildElements; if (itemId.Value != Guid.Empty) { using (new DataScope(DataScopeIdentifier.Administrated)) { IPage page = PageManager.GetPageById(itemId.Value); if (page != null) // null => Foreign page { associatedChildElements = _pageAssociatedHelper.GetChildren(page, entityToken); } else { associatedChildElements = new List<Element>(); } } } else { associatedChildElements = new List<Element>(); } associatedChildElements.AddRange(childPageElements); return associatedChildElements; } private static Guid? GetParentPageId(EntityToken entityToken) { if (entityToken is PageElementProviderEntityToken) { return Guid.Empty; } if (entityToken is DataEntityToken dataEntityToken) { IPage parentPage = dataEntityToken.Data as IPage; return parentPage?.Id; } throw new NotImplementedException(); } private IEnumerable<IPage> GetChildrenPages(EntityToken entityToken, SearchToken searchToken) { var itemId = GetParentPageId(entityToken); if (!itemId.HasValue) return Enumerable.Empty<IPage>(); var parentPageId = itemId.Value; ICollection<IPage> pages; if (searchToken.IsValidKeyword()) { var keyword = searchToken.Keyword.ToLowerInvariant(); pages = GetPagesByKeyword(keyword, parentPageId); } else { pages = PageServices.GetChildren(parentPageId).Evaluate(); } if (parentPageId == Guid.Empty) { var homePageIdFilter = (searchToken as PageSearchToken)?.HomePageId ?? Guid.Empty; if (homePageIdFilter != Guid.Empty) { pages = pages.Where(p => p.Id == homePageIdFilter).ToList(); } } return OrderByVersions(pages); } private ICollection<IPage> GetPagesByKeyword(string keyword, Guid parentId) { var predicateItems = from page in DataFacade.GetData<IPage>() where (page.Description != null && page.Description.ToLowerInvariant().Contains(keyword)) || (page.Title != null && page.Title.ToLowerInvariant().Contains(keyword)) select new TreeNode { Key = page.Id, ParentKey = page.GetParentId() }; List<TreeNode> keyTree = DataFacade.GetData<IPage>().Select(x => new TreeNode { Key = x.Id, ParentKey = x.GetParentId() }).ToList(); IEnumerable<TreeNode> nodes = new List<TreeNode>(); foreach (TreeNode node in predicateItems) { nodes = nodes.Concat(GetAncestorPath(node, keyTree)).ToList(); } List<Guid> pageIds = nodes.Where(x => x.ParentKey == parentId).Select(x => x.Key).Distinct().ToList(); var pages = new List<IPage>(); foreach (var page in DataFacade.GetData<IPage>()) { if (pageIds.Contains(page.Id)) { pages.Add(page); } } return pages; } private IEnumerable<IPage> OrderByVersions(IEnumerable<IPage> pages) { return (from page in pages group page by page.Id into pageVersionGroups let versions = pageVersionGroups.ToList() let liveVersionName = versions.Count == 1 ? null : versions[0].GetLiveVersionName() select versions .OrderByVersions() .OrderByDescending(v => v.LocalizedVersionName() == liveVersionName)) .SelectMany(v => v); } private class TreeNode { public Guid Key { get; set; } public Guid ParentKey { get; set; } } private IList<TreeNode> GetAncestorPath(TreeNode key, IList<TreeNode> keys) { if (key.ParentKey == Guid.Empty) { return new List<TreeNode>() { key }; } var parent = keys.First(x => x.Key == key.ParentKey); IList<TreeNode> ancestors = GetAncestorPath(parent, keys); ancestors.Add(key); return ancestors; } 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 dataEntityToken) { IPage newParentPage = (IPage)dataEntityToken.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, false, false, true); 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; } private static int GetRealDropIndex(IPage draggedPage, Guid newParentPageId, int dropIndex) { if (dropIndex == 0) { return 0; } List<Guid> childPageIDs = PageManager.GetChildrenIDs(newParentPageId).ToList(); // Removing pages that does not belong to the same locale using (new DataScope(draggedPage.DataSourceId.PublicationScope, draggedPage.DataSourceId.LocaleScope)) { childPageIDs.RemoveAll(pageId => PageManager.GetPageById(pageId) == null); } if (childPageIDs.Count == 0) { return 0; } childPageIDs = childPageIDs.OrderBy(PageManager.GetLocalOrdering).ToList(); return PageManager.GetLocalOrdering(childPageIDs[Math.Min(childPageIDs.Count - 1, dropIndex - 1)]) + 1; } private enum PageLocaleState { Own, ForeignActive, ForeignDisabled } private List<Element> GetElements(List<KeyValuePair<PageLocaleState, IPage>> pages, bool rootPages, bool useForeign = false) { //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 unLocalizePageLabel = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.UnLocalizePage"); string unLocalizePageToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.UnLocalizePageToolTip"); 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 } } }); if (useForeign && GlobalSettingsFacade.AllowChildPagesTranslationWithoutParent) { // Delete Translation for the Page without deleting child pages and only displaying for foreign pages element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageElementProvider.UnLocalizePageWorkflow"), LocalizePermissionTypes))) { VisualData = new ActionVisualizedData { Label = unLocalizePageLabel, ToolTip = unLocalizePageToolTip, Icon = PageElementProvider.LocalizePage, 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 { if (GlobalSettingsFacade.AllowChildPagesTranslationWithoutParent) { 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); } private ElementVisualizedData MakeVisualData(IPage page, PageLocaleState pageLocaleState, string urlMappingName, bool isRootPage) { bool hasChildren = PageServices.GetChildrenCount(page.Id) > 0 || _pageAssociatedHelper.HasChildren(page); var visualizedElement = new ElementVisualizedData { HasChildren = hasChildren, Label = (isRootPage || string.IsNullOrWhiteSpace(page.MenuTitle)) ? page.Title : page.MenuTitle, ToolTip = page.Description, ElementBundle = page.Id.ToString(), BundleElementName = page.LocalizedVersionName() }; if (pageLocaleState == PageLocaleState.Own) { if (page.PublicationStatus == GenericPublishProcessController.Draft) { visualizedElement.Icon = PageElementProvider.PageDraft; visualizedElement.OpenedIcon = PageElementProvider.PageDraft; } else if (page.PublicationStatus == GenericPublishProcessController.AwaitingApproval) { visualizedElement.Icon = PageElementProvider.PageAwaitingApproval; visualizedElement.OpenedIcon = PageElementProvider.PageAwaitingApproval; } else if (page.PublicationStatus == GenericPublishProcessController.AwaitingPublication) { visualizedElement.Icon = PageElementProvider.PageAwaitingPublication; visualizedElement.OpenedIcon = PageElementProvider.PageAwaitingPublication; } else { visualizedElement.Icon = PageElementProvider.PagePublication; visualizedElement.OpenedIcon = PageElementProvider.PagePublication; } } else if (pageLocaleState == PageLocaleState.ForeignActive) { visualizedElement.Icon = PageElementProvider.PageGhosted; visualizedElement.OpenedIcon = PageElementProvider.PageGhosted; visualizedElement.IsDisabled = false; visualizedElement.Label = $"{visualizedElement.Label} ({urlMappingName})"; } else { visualizedElement.Icon = PageElementProvider.PageDisabled; visualizedElement.OpenedIcon = PageElementProvider.PageDisabled; visualizedElement.IsDisabled = true; visualizedElement.ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.DisabledPage"); visualizedElement.Label = $"{visualizedElement.Label} ({urlMappingName})"; } return visualizedElement; } private void DataEvents_IPageType_OnStoreChanged(object sender, StoreEventArgs storeEventArgs) { EntityToken entityToken = new PageElementProviderEntityToken(_context.ProviderName); var parents = HookingFacade.GetHookies(entityToken); if (parents != null) { foreach (var parentEntityToken in parents) { ConsoleMessageQueueFacade.Enqueue(new RefreshTreeMessageQueueItem { EntityToken = parentEntityToken }, null); } } } #region IDataExchangingElementProvider Members public object GetData(string name) { return "The page element provider here - you asked me for '" + name + "'"; } #endregion } // Not to used on elements. This is only for determin drag'n'drop security internal sealed class DragAndDropActionToken : ActionToken { private static readonly PermissionType[] _permissionTypes = { PermissionType.Administrate, PermissionType.Edit }; public override IEnumerable<PermissionType> PermissionTypes => _permissionTypes; } internal sealed class PageElementProviderAssembler : IAssembler<IHooklessElementProvider, HooklessElementProviderData> { public IHooklessElementProvider Assemble(IBuilderContext context, HooklessElementProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new PageElementProvider(); } } [Assembler(typeof(PageElementProviderAssembler))] internal sealed class PageElementProviderData : HooklessElementProviderData { } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PageElementProvider/PageElementProviderActionTokenProvider.cs ================================================ using Composite.Data; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Data.Types; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { internal sealed class PageElementProviderActionTokenProvider : IActionTokenProvider { public ActionToken GetActionToken(string actionTypeName, IData data) { switch (actionTypeName) { case GenericPublishProcessControllerActionTypeNames.UndoUnpublishedChanges: return data is IPage ? new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageElementProvider.UndoUnpublishedChangesWorkflow"), PageElementProvider.EditPermissionTypes) : null; default: return null; } } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PageElementProvider/PageElementProviderEntityToken.cs ================================================ using Composite.C1Console.Security; using Composite.C1Console.Security.SecurityAncestorProviders; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(NoAncestorSecurityAncestorProvider))] public sealed class PageElementProviderEntityToken : EntityToken { private string _source; /// <exclude /> public PageElementProviderEntityToken(string source) { _source = source; } /// <exclude /> public override string Type { get { return ""; } } /// <exclude /> public override string Source { get { return _source; } } /// <exclude /> public override string Id { get { return ""; } } /// <exclude /> public override string Serialize() { return DoSerialize(); } /// <exclude /> public static EntityToken Deserialize(string serializedData) { string type, source, id; DoDeserialize(serializedData, out type, out source, out id); return new PageElementProviderEntityToken(source); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PageElementProvider/PageSearchToken.cs ================================================ using System; using Composite.C1Console.Elements; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class PageSearchToken : SearchToken { /// <exclude /> public Guid? HomePageId { get; set; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PageElementProvider/ViewUnpublishedItemsActionToken.cs ================================================ using System.Collections.Generic; using System.Text; using System.Web; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.Core.ResourceSystem; using Composite.Core.WebClient; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { [ActionExecutor(typeof(ViewUnpublishedItemsActionExecutor))] internal sealed class ViewUnpublishedItemsActionToken : ActionToken { private static IEnumerable<PermissionType> _permissionType = new PermissionType[] { PermissionType.Read }; public ViewUnpublishedItemsActionToken() { } public override IEnumerable<PermissionType> PermissionTypes { get { return _permissionType; } } public override string Serialize() { return "ViewUnpublishedPageItems"; } public static ActionToken Deserialize(string serializedData) { return new ViewUnpublishedItemsActionToken(); } } internal sealed class ViewUnpublishedItemsActionExecutor : Composite.C1Console.Actions.IActionExecutor { public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { //string documentTitle = "Unpublished Pages and Page Folder Data"; //string description = "The list below display pages and page data which are currently being edited or are ready to be approved / published."; string documentTitle = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.ViewUnpublishedItems-document-title"); string description = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.ViewUnpublishedItems-document-description"); string emptyLabel = StringResourceSystemFacade.GetString("Composite.Plugins.GeneratedDataTypesElementProvider", "ViewUnpublishedItems-document-empty-label"); string url = string.Format("{0}?showpagedata=true&title={1}&description={2}&emptyLabel={3}", UrlUtils.ResolveAdminUrl(string.Format("content/views/publishworkflowstatus/ViewUnpublishedItems.aspx")), HttpUtility.UrlEncode(documentTitle, Encoding.UTF8), HttpUtility.UrlEncode(description, Encoding.UTF8), HttpUtility.UrlEncode(emptyLabel, Encoding.UTF8)); IManagementConsoleMessageService consoleServices = flowControllerServicesContainer.GetService<IManagementConsoleMessageService>(); OpenViewMessageQueueItem openViewMsg = new OpenViewMessageQueueItem { EntityToken = EntityTokenSerializer.Serialize(entityToken, true), ViewId = "ViewUnpublishedPageItems", Label = documentTitle, Url = url, ViewType = ViewType.Main }; ConsoleMessageQueueFacade.Enqueue(openViewMsg, consoleServices.CurrentConsoleId); return null; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PageTemplateElementProvider/PageTemplateElementProvider.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using Composite.C1Console.Workflow; using Composite.Core.IO; using Composite.Core.PageTemplates; using Composite.Core.PageTemplates.Foundation; using Composite.Core.PageTemplates.Foundation.PluginFacade; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.C1Console.Security; using Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using SR = Composite.Core.ResourceSystem.StringResourceSystemFacade; using FileElementProvider = Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider.WebsiteFileElementProvider; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { [ConfigurationElementType(typeof(PageTemplateElementProviderData))] internal sealed class PageTemplateElementProvider : IHooklessElementProvider, IAuxiliarySecurityAncestorProvider { private ElementProviderContext _context; public static ResourceHandle RootOpen { get { return GetIconHandle("page-template-root-open"); } } public static ResourceHandle RootClosed { get { return GetIconHandle("page-template-root-closed"); } } public static ResourceHandle DesignTemplate { get { return GetIconHandle("page-template-template"); } } public static ResourceHandle TemplateWithError { get { return GetIconHandle("error"); } } public static ResourceHandle AddTemplate { get { return GetIconHandle("page-template-add"); } } public static ResourceHandle EditTemplate { get { return GetIconHandle("page-template-edit"); } } public static ResourceHandle DeleteTemplate { get { return GetIconHandle("page-template-delete"); } } public static ResourceHandle FolderIcon { get { return GetIconHandle("folder"); } } private static readonly ActionGroup EditCodeFileActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); internal static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } public PageTemplateElementProvider() { AuxiliarySecurityAncestorFacade.AddAuxiliaryAncestorProvider<DataEntityToken>(this); } public ElementProviderContext Context { set { _context = value; } } public IEnumerable<Element> GetRoots(SearchToken searchToken) { Element element = new Element(_context.CreateElementHandle(new PageTemplateRootEntityToken())); bool hasChildren = PageTemplateFacade.GetPageTemplates().Any(); element.VisualData = new ElementVisualizedData { Label = SR.GetString("Composite.Plugins.PageTemplateElementProvider", "PageTemplateElementProvider.RootLabel"), ToolTip = SR.GetString("Composite.Plugins.PageTemplateElementProvider", "PageTemplateElementProvider.RootLabelToolTip"), HasChildren = hasChildren, Icon = PageTemplateElementProvider.RootClosed, OpenedIcon = PageTemplateElementProvider.RootOpen }; const string addTemplateWorkflowType = "Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider.AddNewPageTemplateWorkflow"; element.AddWorkflowAction(addTemplateWorkflowType, new[] { PermissionType.Add }, new ActionVisualizedData { Label = SR.GetString("Composite.Plugins.PageTemplateElementProvider", "PageTemplateElementProvider.AddTemplate"), ToolTip = SR.GetString("Composite.Plugins.PageTemplateElementProvider", "PageTemplateElementProvider.AddTemplateToolTip"), Icon = PageTemplateElementProvider.AddTemplate, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } }); foreach(var pageTemplateProviderName in PageTemplateProviderRegistry.ProviderNames) { var provider = PageTemplateProviderPluginFacade.GetProvider(pageTemplateProviderName); Verify.IsNotNull(provider, "Failed to get provider by name '{0}'", pageTemplateProviderName); IEnumerable<ElementAction> actions = provider.GetRootActions(); element.AddAction(actions); } return new [] { element }; } public IEnumerable<Element> GetChildren(EntityToken entityToken, SearchToken searchToken) { if (entityToken is SharedCodeFolderEntityToken) { return GetSharedCodeElements(searchToken); } if ((entityToken is PageTemplateRootEntityToken) == false) return new Element[] { }; bool sharedFilesExist = PageTemplateFacade.GetSharedFiles().Any(); IEnumerable<Element> result = sharedFilesExist ? new [] { GetSharedCodeElement()} : new Element[0]; var pageTemplates = PageTemplateFacade.GetPageTemplates(); if (searchToken.IsValidKeyword()) { string keyword = searchToken.Keyword.ToLowerInvariant(); pageTemplates = pageTemplates .Where(t => t.Title.IndexOf(keyword, StringComparison.InvariantCultureIgnoreCase) > 0); } pageTemplates = pageTemplates.OrderBy(template => template.Title).ToList(); return result.Concat( GetElements(pageTemplates) ); } private IEnumerable<Element> GetSharedCodeElements(SearchToken searchToken) { var result = new List<Element>(); foreach(SharedFile sharedFile in PageTemplateFacade.GetSharedFiles()) { string relativeFilePath = sharedFile.RelativeFilePath; string fullPath = relativeFilePath.StartsWith("~") ? PathUtil.Resolve(relativeFilePath) : relativeFilePath; var websiteFile = new WebsiteFile(fullPath); Element element = new Element(_context.CreateElementHandle(new SharedCodeFileEntityToken(relativeFilePath))) { VisualData = new ElementVisualizedData() { Label = websiteFile.FileName, ToolTip = websiteFile.FileName, HasChildren = false, Icon = FileElementProvider.WebsiteFileIcon(websiteFile.MimeType), OpenedIcon = FileElementProvider.WebsiteFileIcon(websiteFile.MimeType) } }; element.PropertyBag.Add("Uri", PathUtil.GetWebsitePath(websiteFile.FullPath)); element.PropertyBag.Add("ElementType", websiteFile.MimeType); // Adding "Edit" action for text-editable files if (sharedFile.DefaultEditAction && MimeTypeInfo.IsTextFile(websiteFile.MimeType)) { element.AddWorkflowAction( "Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider.EditSharedCodeFileWorkflow", new[] {PermissionType.Edit}, new ActionVisualizedData { Label = GetResourceString("EditSharedCodeFile.Label"), ToolTip = GetResourceString("EditSharedCodeFile.ToolTip"), Icon = CommonCommandIcons.Edit, Disabled = websiteFile.IsReadOnly, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = EditCodeFileActionGroup } }); } var customActions = sharedFile.GetActions(); foreach(var action in customActions) { element.AddAction(action); } result.Add(element); } return result; } public Dictionary<EntityToken, IEnumerable<EntityToken>> GetParents(IEnumerable<EntityToken> entityTokens) { Dictionary<EntityToken, IEnumerable<EntityToken>> result = new Dictionary<EntityToken, IEnumerable<EntityToken>>(); foreach (EntityToken entityToken in entityTokens) { DataEntityToken dataEntityToken = entityToken as DataEntityToken; Type type = dataEntityToken.InterfaceType; if (type != typeof(IXmlPageTemplate)) continue; PageTemplateRootEntityToken newEntityToken = new PageTemplateRootEntityToken(); result.Add(entityToken, new EntityToken[] { newEntityToken }); } return result; } private Element GetSharedCodeElement() { Element element = new Element(_context.CreateElementHandle(new SharedCodeFolderEntityToken())); element.VisualData = new ElementVisualizedData { Label = GetResourceString("PageTemplateElementProvider.SharedCodeFolder.Title"), ToolTip = GetResourceString("PageTemplateElementProvider.SharedCodeFolder.ToolTip"), HasChildren = true, Icon = FolderIcon, }; return element; } private static string GetResourceString(string key) { return SR.GetString("Composite.Plugins.PageTemplateElementProvider", key); } private IEnumerable<Element> GetElements(IEnumerable<PageTemplateDescriptor> pageTemplates) { List<Element> elements = new List<Element>(); foreach (PageTemplateDescriptor pageTemplate in pageTemplates) { var entityToken = pageTemplate.GetEntityToken(); Element element = new Element(_context.CreateElementHandle(entityToken)); element.VisualData = new ElementVisualizedData { Label = pageTemplate.Title, ToolTip = pageTemplate.Title, HasChildren = false, Icon = pageTemplate.IsValid ? DesignTemplate : TemplateWithError, }; IEnumerable<ElementAction> actions = pageTemplate.GetActions(); element.AddAction(actions); elements.Add(element); } return elements; } } [Assembler(typeof(NonConfigurableHooklessElementProviderAssembler))] internal sealed class PageTemplateElementProviderData : HooklessElementProviderData { } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PageTemplateElementProvider/PageTemplateRootEntityToken.cs ================================================ using Composite.C1Console.Security; using Composite.C1Console.Security.SecurityAncestorProviders; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { [SecurityAncestorProvider(typeof(NoAncestorSecurityAncestorProvider))] internal class PageTemplateRootEntityToken : EntityToken { public override string Type { get { return ""; } } public override string Source { get { return ""; } } public override string Id { get { return "PageTemplateRootEntityToken"; } } public override string Serialize() { return ""; } public static EntityToken Deserialize(string serializedData) { return new PageTemplateRootEntityToken(); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PageTemplateElementProvider/SharedCodeFileEntityToken.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { /// <summary> /// Represents an entity token for a shared code file /// </summary> [SecurityAncestorProvider(typeof(SharedCodeFileEntityToken.SharedCodeFileSecurityAncestorProvider))] public class SharedCodeFileEntityToken : EntityToken { private readonly string _virtualPath; /// <summary> /// Initializes a new instance of the <see cref="SharedCodeFileEntityToken"/> class. /// </summary> /// <param name="virtualPath">The relative file path.</param> public SharedCodeFileEntityToken(string virtualPath) { _virtualPath = virtualPath; } /// <exclude /> public override string Type { get { return "_"; } } /// <exclude /> public override string Source { get { return "_"; } } /// <exclude /> public override string Id { get { return "_"; } } /// <exclude /> public override string Serialize() { return _virtualPath; } /// <summary> /// Gets the relative file path. /// </summary> public string VirtualPath { get { return _virtualPath; } } /// <exclude /> public static EntityToken Deserialize(string serializedData) { return new SharedCodeFileEntityToken(serializedData); } /// <exclude /> public override bool Equals(object obj) { return base.Equals(obj) && (obj as SharedCodeFileEntityToken).VirtualPath == VirtualPath; } /// <exclude /> public override int GetHashCode() { return base.GetHashCode() ^ VirtualPath.GetHashCode(); } internal class SharedCodeFileSecurityAncestorProvider : ISecurityAncestorProvider { public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { return new[] { new SharedCodeFolderEntityToken() }; } } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PageTemplateElementProvider/SharedCodeFolderEntityToken.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { [SecurityAncestorProvider(typeof(SharedCodeFolderEntityToken.SharedCodeFolderSecurityAncestorProvider))] internal class SharedCodeFolderEntityToken : EntityToken { public override string Type { get { return "_"; } } public override string Source { get { return "_"; } } public override string Id { get { return "_"; } } public override string Serialize() { return ""; } public static EntityToken Deserialize(string serializedData) { return new SharedCodeFolderEntityToken(); } internal class SharedCodeFolderSecurityAncestorProvider : ISecurityAncestorProvider { public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { return new[] { new PageTemplateRootEntityToken() }; } } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PageTemplateFeatureElementProvider/PageTemplateFeatureElementProvider.cs ================================================ using System.Collections.Generic; using System.IO; using System.Linq; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.C1Console.Security; using Composite.C1Console.Trees; using Composite.C1Console.Workflow; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateFeatureElementProvider { [ConfigurationElementType(typeof(NonConfigurableHooklessElementProvider))] internal sealed class PageTemplateFeatureElementProvider : IHooklessElementProvider, IAuxiliarySecurityAncestorProvider { private ElementProviderContext _context; private static readonly ResourceHandle PageTemplateFeatureRootIcon = GetIconHandle("page-template-feature-root-closed"); private static readonly ResourceHandle PageTemplateFeatureRootIconOpen = GetIconHandle("page-template-feature-root-open"); private static readonly ResourceHandle PageTemplateFeatureIcon = GetIconHandle("page-template-feature-template"); private static readonly ResourceHandle PageTemplateFeatureIconAdd = GetIconHandle("page-template-feature-add"); private static readonly ResourceHandle PageTemplateFeatureIconEdit = GetIconHandle("page-template-feature-edit"); private static readonly ResourceHandle PageTemplateFeatureIconDelete = GetIconHandle("page-template-feature-delete"); private static readonly ActionGroup PrimaryFolderToolsActionGroup = new ActionGroup("FolderTools", ActionGroupPriority.PrimaryMedium); public PageTemplateFeatureElementProvider() { AuxiliarySecurityAncestorFacade.AddAuxiliaryAncestorProvider<PageTemplateFeatureEntityToken>(this); foreach (string pageTemplateFeratureFilename in this.PageTemplateFeatureFilenames) { string filename = Path.GetFileName(pageTemplateFeratureFilename); PageTemplateFeatureEntityToken entityToken = new PageTemplateFeatureEntityToken(PageTemplateFeatureEntityToken.FeatureId, filename); TreeFacade.AddCustomAttachmentPoint(filename, entityToken); } } public ElementProviderContext Context { set { _context = value; } } public IEnumerable<Element> GetRoots(SearchToken seachToken) { Element rootFolderElement = new Element(_context.CreateElementHandle(new PageTemplateFeatureEntityToken(PageTemplateFeatureEntityToken.RootFolderId))) { VisualData = new ElementVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "ElementProvider.RootLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "ElementProvider.RootToolTip"), HasChildren = this.PageTemplateFeatureFilenames.Any(), Icon = PageTemplateFeatureRootIcon, OpenedIcon = PageTemplateFeatureRootIconOpen } }; rootFolderElement.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageTemplateFeatureElementProvider.AddPageTemplateFeatureWorkflow"), PermissionTypePredefined.Add))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "ElementProvider.AddTemplateFeature"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "ElementProvider.AddTemplateFeatureToolTip"), Icon = PageTemplateFeatureIconAdd, Disabled = false, ActionLocation = ActionLocation.AddPrimaryActionLocation } }); yield return rootFolderElement; } public IEnumerable<Element> GetChildren(EntityToken entityToken, SearchToken seachToken) { if (entityToken.Id == PageTemplateFeatureEntityToken.RootFolderId) { foreach (string pageTemplateFeratureFilename in this.PageTemplateFeatureFilenames) { string filename = Path.GetFileName(pageTemplateFeratureFilename); string featureName = Path.GetFileNameWithoutExtension(filename); bool isHtml = Path.GetExtension(filename) == ".html"; Element featureElement = new Element(_context.CreateElementHandle( PageTemplateFeatureEntityToken.BuildFeatureEntityToken(featureName))) { VisualData = new ElementVisualizedData { Label = featureName, ToolTip = filename, Icon = PageTemplateFeatureIcon } }; featureElement.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageTemplateFeatureElementProvider.EditPageTemplateFeatureWorkflow"), PermissionTypePredefined.Edit))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "ElementProvider.EditTemplateFeature"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "ElementProvider.EditTemplateFeatureToolTip"), Icon = PageTemplateFeatureIconEdit, Disabled = false, ActionLocation = ActionLocation.EditPrimaryActionLocation } }); featureElement.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageTemplateFeatureElementProvider.DeletePageTemplateFeatureWorkflow"), PermissionTypePredefined.Delete))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "ElementProvider.DeleteTemplateFeature"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "ElementProvider.DeleteTemplateFeatureToolTip"), Icon = PageTemplateFeatureIconDelete, Disabled = false, ActionLocation = ActionLocation.DeletePrimaryActionLocation } }); featureElement.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageTemplateFeatureElementProvider.TogglePageTemplateFeatureEditorWorkflow"), PermissionTypePredefined.Edit))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "ElementProvider.EditVisually"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "ElementProvider.EditVisuallyToolTip"), Icon = PageTemplateFeatureIconEdit, Disabled = false, ActionCheckedStatus = isHtml ? ActionCheckedStatus.Checked : ActionCheckedStatus.Unchecked, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = false, ActionGroup = PrimaryFolderToolsActionGroup }, } }); yield return featureElement; } yield break; } yield break; } public Dictionary<EntityToken, IEnumerable<EntityToken>> GetParents(IEnumerable<EntityToken> entityTokens) { Dictionary<EntityToken, IEnumerable<EntityToken>> result = new Dictionary<EntityToken, IEnumerable<EntityToken>>(); foreach (EntityToken entityToken in entityTokens) { if (entityToken is PageTemplateFeatureEntityToken) { switch (entityToken.Id) { case PageTemplateFeatureEntityToken.FeatureId: result.Add(entityToken, new EntityToken[] { new PageTemplateFeatureEntityToken(PageTemplateFeatureEntityToken.RootFolderId) }); break; } } } return result; } private IEnumerable<string> PageTemplateFeatureFilenames { get { string featureDir = PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory); if (C1Directory.Exists(featureDir)) { var htmlFiles = C1Directory.GetFiles(featureDir, "*.html"); var xmlFiles = C1Directory.GetFiles(featureDir, "*.xml"); foreach (var fileName in htmlFiles.Concat(xmlFiles).OrderBy(f => f)) { yield return fileName; } } else { yield break; } } } private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/PageTemplateFeatureElementProvider/PageTemplateFeatureEntityToken.cs ================================================ using System.IO; using Composite.C1Console.Security; using Composite.C1Console.Security.SecurityAncestorProviders; using Composite.Core.Configuration; using Composite.Core.IO; using Newtonsoft.Json; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateFeatureElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(NoAncestorSecurityAncestorProvider))] public sealed class PageTemplateFeatureEntityToken : EntityToken { private string _id; private string _source; /// <exclude /> public const string RootFolderId = "FeatureRoot"; /// <exclude /> public const string FeatureId = "FeatureElement"; /// <exclude /> public PageTemplateFeatureEntityToken(string id) :this(id, "") { } /// <exclude /> public static PageTemplateFeatureEntityToken BuildFeatureEntityToken(string featureName) { return new PageTemplateFeatureEntityToken(FeatureId, featureName); } /// <exclude /> public PageTemplateFeatureEntityToken(string id, string source) { _id = id; _source = source; } /// <exclude /> public override string Type { get { return ""; } } /// <exclude /> public override string Source { get { return _source; } } /// <exclude /> public override string Id { get { return _id; } } /// <exclude /> [JsonIgnore] public string FeatureName { get { return this.Source; } } /// <exclude /> public override string Serialize() { return DoSerialize(); } /// <exclude /> public static EntityToken Deserialize(string serializedEntityToken) { string type, source, id; DoDeserialize(serializedEntityToken, out type, out source, out id); return new PageTemplateFeatureEntityToken(id, source); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/RazorFunctionElementProvider/RazorFunctionElementProvider.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using Composite.AspNet.Security; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Core.ResourceSystem; using Composite.Functions; using Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; using SR = Composite.Core.ResourceSystem.StringResourceSystemFacade; namespace Composite.Plugins.Elements.ElementProviders.RazorFunctionElementProvider { [ConfigurationElementType(typeof(RazorFunctionProviderElementProviderData))] internal class RazorFunctionElementProvider: BaseFunctionProviderElementProvider.BaseFunctionProviderElementProvider { private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); protected static ResourceHandle AddFunctionIcon { get { return GetIconHandle("razor-function-add"); } } protected static ResourceHandle EditFunctionIcon { get { return GetIconHandle("razor-function-edit"); } } protected static ResourceHandle DeleteFunctionIcon { get { return GetIconHandle("razor-function-delete"); } } private readonly string _functionProviderName; private readonly string _rootLabel; public RazorFunctionElementProvider(string functionProvider, string rootLabel) { _functionProviderName = functionProvider; _rootLabel = rootLabel; } public override string FunctionProviderName { get { return _functionProviderName; } } protected override IEnumerable<IFunctionTreeBuilderLeafInfo> OnGetFunctionInfos(SearchToken searchToken) { var functions = FunctionFacade.GetFunctionsByProvider(_functionProviderName); if(searchToken != null && !string.IsNullOrEmpty(searchToken.Keyword)) { string keyword = searchToken.Keyword.ToLowerInvariant(); functions = functions.Where(f => f.Namespace.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) > 0 || f.Name.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) > 0); } return functions.Select(f => new RazorFunctionTreeBuilderLeafInfo(f)); } protected override IEnumerable<Type> OnGetEntityTokenTypes() { return new [] { typeof(FileBasedFunctionEntityToken)}; } protected override IFunctionTreeBuilderLeafInfo OnIsEntityOwner(EntityToken entityToken) { if(entityToken is FileBasedFunctionEntityToken && entityToken.Source == _functionProviderName) { string functionFullName = entityToken.Id; IFunction function = FunctionFacade.GetFunctionsByProvider(_functionProviderName) .FirstOrDefault(func => func.Namespace + "." + func.Name == functionFullName); return function == null ? null : new RazorFunctionTreeBuilderLeafInfo(function); } return null; } /// <exclude /> protected override IEnumerable<ElementAction> OnGetFolderActions() { Type workflow = WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.RazorFunctionProviderElementProvider.AddNewRazorFunctionWorkflow"); return new[] { new ElementAction(new ActionHandle(new WorkflowActionToken(workflow, new [] { PermissionType.Add }))) { VisualData = new ActionVisualizedData { Label = GetText("AddNewRazorFunction.Label"), ToolTip = GetText("AddNewRazorFunction.ToolTip"), Icon = AddFunctionIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } } }; } /// <exclude /> protected override IEnumerable<ElementAction> OnGetFunctionActions(IFunctionTreeBuilderLeafInfo function) { var editWorkflow = WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.RazorFunctionProviderElementProvider.EditRazorFunctionWorkflow"); var deleteWorkflow = WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.RazorFunctionProviderElementProvider.DeleteRazorFunctionWorkflow"); return new [] { new ElementAction(new ActionHandle( new WorkflowActionToken( editWorkflow, new [] { PermissionType.Edit } ))) { VisualData = new ActionVisualizedData { Label = GetText("EditRazorFunction.Label"), ToolTip = GetText("EditRazorFunction.ToolTip"), Icon = EditFunctionIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }, new ElementAction(new ActionHandle( new WorkflowActionToken( deleteWorkflow, new [] { PermissionType.Delete } ){Payload = GetContext().ProviderName})) { VisualData = new ActionVisualizedData { Label = GetText("DeleteRazorFunction.Label"), ToolTip = GetText("DeleteRazorFunction.ToolTip"), Icon = DeleteFunctionIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } } }; } private sealed class RazorFunctionTreeBuilderLeafInfo : IFunctionTreeBuilderLeafInfo { private readonly IFunction _function; public RazorFunctionTreeBuilderLeafInfo(IFunction function) { _function = function; } public string Name { get { return _function.Name; } } public string Namespace { get { return _function.Namespace; } } public EntityToken EntityToken { get { return _function.EntityToken; } } } #region Configuration internal sealed class RazorFunctionElementProviderAssembler : IAssembler<IHooklessElementProvider, HooklessElementProviderData> { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IHooklessElementProvider Assemble(IBuilderContext context, HooklessElementProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { var data = (RazorFunctionProviderElementProviderData)objectConfiguration; return new RazorFunctionElementProvider(data.RazorFunctionProviderName, data.Label); } } [Assembler(typeof(RazorFunctionElementProviderAssembler))] internal sealed class RazorFunctionProviderElementProviderData : HooklessElementProviderData { private const string _razorFunctionProviderNameProperty = "razorFunctionProviderName"; [ConfigurationProperty(_razorFunctionProviderNameProperty, IsRequired = true)] public string RazorFunctionProviderName { get { return (string)base[_razorFunctionProviderNameProperty]; } set { base[_razorFunctionProviderNameProperty] = value; } } private const string _labelProperty = "label"; [ConfigurationProperty(_labelProperty, DefaultValue = null)] public string Label { get { return (string)base[_labelProperty]; } set { base[_labelProperty] = value; } } } #endregion Configuration protected override string RootFolderLabel { get { return !string.IsNullOrEmpty(_rootLabel) ? StringResourceSystemFacade.ParseString(_rootLabel) : GetText("RootElement.Label"); } } protected override string RootFolderToolTip { get { return GetText("RootElement.ToolTip"); } } private static string GetText(string stringId) { return StringResourceSystemFacade.GetString("Composite.Plugins.RazorFunction", stringId); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/SqlFunctionProviderElementProvider.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Composite.Core.Collections; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.C1Console.Security; using Composite.C1Console.Security.Cryptography; using Composite.C1Console.Workflow; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider { [ConfigurationElementType(typeof(SqlFunctionElementProviderData))] internal sealed class SqlFunctionElementProvider : IHooklessElementProvider, IDataExchangingElementProvider, IAuxiliarySecurityAncestorProvider { private ElementProviderContext _context; private ResourceHandle FolderIcon { get { return CommonElementIcons.Folder; } } private ResourceHandle OpenFolderIcon { get { return CommonElementIcons.FolderOpen; } } private ResourceHandle EmptyFolderIcon { get { return CommonElementIcons.Folder; } } private ResourceHandle XmlQueryInfoIcon { get { return CommonElementIcons.MimeTextXml; } } public static ResourceHandle Function { get { return GetIconHandle("sql-based-function"); } } public static ResourceHandle Connection { get { return GetIconHandle("sql-based-connection"); } } public static ResourceHandle AddConnection { get { return GetIconHandle("sql-based-connection-add"); } } public static ResourceHandle DeleteConnection { get { return GetIconHandle("sql-based-connection-delete"); } } public static ResourceHandle EditConnection { get { return GetIconHandle("sql-based-connection-edit"); } } public static ResourceHandle AddFunction { get { return GetIconHandle("sql-based-function-add"); } } public static ResourceHandle EditFunction { get { return GetIconHandle("sql-based-function-edit"); } } public static ResourceHandle DeleteFunction { get { return GetIconHandle("sql-based-function-delete"); } } private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } public SqlFunctionElementProvider() { AuxiliarySecurityAncestorFacade.AddAuxiliaryAncestorProvider<DataEntityToken>(this); } public ElementProviderContext Context { set { _context = value; } } #region Element methods public IEnumerable<Element> GetRoots(SearchToken seachToken) { var connections = DataFacade.GetData<ISqlConnection>(); List<Element> elements = new List<Element>(); bool hasChildren = connections.Any(); Element element = new Element(_context.CreateElementHandle(new SqlFunctionProviderRootEntityToken(_context.ProviderName, _context.ProviderName))) { VisualData = new ElementVisualizedData() { Label = StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", "SqlFunctionElementProvider.RootLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", "SqlFunctionElementProvider.RootLabelToolTip"), HasChildren = hasChildren, Icon = hasChildren ? this.FolderIcon : this.EmptyFolderIcon, OpenedIcon = OpenFolderIcon } }; element.AddAction( new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider.AddNewSqlConnectionWorkflow"), new PermissionType[] { PermissionType.Add } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", "SqlFunctionElementProvider.AddConnection"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", "SqlFunctionElementProvider.AddConnectionToolTip"), Icon = AddConnection, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); elements.Add(element); return elements; } public IEnumerable<Element> GetChildren(EntityToken entityToken, SearchToken searchToken) { if ((entityToken is SqlFunctionProviderRootEntityToken)) { return GetConnectionElements(); } else { return GetFunctionElements(entityToken, searchToken); } } private List<Element> GetConnectionElements() { var connections = DataFacade.GetData<ISqlConnection>(); var queries = DataFacade.GetData<ISqlFunctionInfo>(); List<Element> elements = new List<Element>(); foreach (ISqlConnection connection in connections) { int queryCount = queries.Where(x => x.ConnectionId == connection.Id).Count(); bool hasChildren = queryCount > 0; Element element = new Element(_context.CreateElementHandle(connection.GetDataEntityToken())) { VisualData = new ElementVisualizedData() { Label = connection.Name, ToolTip = connection.EncryptedConnectionString.Decrypt(), HasChildren = hasChildren, Icon = SqlFunctionElementProvider.Connection, OpenedIcon = SqlFunctionElementProvider.Connection } }; elements.Add(element); element.AddAction( new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider.EditSqlConnectionWorkflow"), new PermissionType[] { PermissionType.Edit } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", "SqlFunctionElementProvider.EditConnection"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", "SqlFunctionElementProvider.EditConnectionToolTip"), Icon = EditConnection, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); element.AddAction( new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider.DeleteSqlConnectionWorkflow"), new PermissionType[] { PermissionType.Delete } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", "SqlFunctionElementProvider.DeleteConnection"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", "SqlFunctionElementProvider.DeleteConnectionToolTip"), Icon = DeleteConnection, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); element.AddAction( new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider.AddNewSqlFunctionProviderWorkflow"), new PermissionType[] { PermissionType.Add } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", "SqlFunctionElementProvider.AddQuery"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", "SqlFunctionElementProvider.AddQueryToolTip"), Icon = AddConnection, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); } return elements; } private List<Element> GetFunctionElements(EntityToken entityToken, SearchToken searchToken) { Guid connectionId; string namespaceName; if ((entityToken is DataEntityToken)) { DataEntityToken dataEntityToken = (DataEntityToken)entityToken; if (dataEntityToken.Data is ISqlConnection) { connectionId = ((ISqlConnection)dataEntityToken.Data).Id; namespaceName = ""; } else { // stuff has been deleted and we are refreshed on a dead function folder return new List<Element>(); } } else if ((entityToken is SqlFunctionProviderFolderEntityToken)) { SqlFunctionProviderFolderEntityToken sqlFunctionProviderFolderEntityToken = (SqlFunctionProviderFolderEntityToken)entityToken; connectionId = new Guid(sqlFunctionProviderFolderEntityToken.ConnectionId); namespaceName = sqlFunctionProviderFolderEntityToken.Id; } else { throw new NotImplementedException(); } IEnumerable<ISqlFunctionInfo> sqlFunctionInfoes; if (searchToken.IsValidKeyword() == false) { sqlFunctionInfoes = from item in DataFacade.GetData<ISqlFunctionInfo>() where item.ConnectionId == connectionId select item; } else { string keyword = searchToken.Keyword.ToLower(); sqlFunctionInfoes = from item in DataFacade.GetData<ISqlFunctionInfo>() where item.ConnectionId == connectionId && (((item.Name != null) && (item.Name.ToLower().Contains(keyword))) || ((item.Namespace != null) && (item.Namespace.ToLower().Contains(keyword))) || ((item.Command != null) && (item.Command.ToLower().Contains(keyword)))) select item; } NamespaceTreeBuilder builder = new NamespaceTreeBuilder(sqlFunctionInfoes.Select(q => (INamespaceTreeBuilderLeafInfo)new SqlNamespaceTreeBuilderLeafInfo(q))); NamespaceTreeBuilderFolder folderNode; if (namespaceName == "") { folderNode = builder.RootFolder; } else { folderNode = builder.GetFolder(namespaceName); } List<Element> result = new List<Element>(); if (folderNode != null) { if (folderNode.SubFolders != null) { foreach (NamespaceTreeBuilderFolder node in folderNode.SubFolders) { Element element = CreateFolderElement(node, connectionId.ToString()); result.Add(element); } } if (folderNode.Leafs != null) { foreach (INamespaceTreeBuilderLeafInfo leafInfo in folderNode.Leafs) { Element element = CreateXmlFunctionInfoElement(leafInfo, connectionId.ToString()); result.Add(element); } } } return result; } private Element CreateFolderElement(NamespaceTreeBuilderFolder node, string connectionId) { bool hasChildren = (node.SubFolders.Count != 0) || (node.Leafs.Count != 0); var element = new Element(_context.CreateElementHandle(new SqlFunctionProviderFolderEntityToken(StringExtensionMethods.CreateNamespace(node.Namespace, node.Name, '.'), _context.ProviderName, connectionId))) { VisualData = new ElementVisualizedData { Label = node.Name, ToolTip = node.Name, HasChildren = (node.SubFolders.Count != 0) || (node.Leafs.Count != 0), Icon = hasChildren ? this.FolderIcon : this.EmptyFolderIcon, OpenedIcon = this.OpenFolderIcon } }; element.AddAction(new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider.AddNewSqlFunctionProviderWorkflow"), new PermissionType[] { PermissionType.Add } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", "SqlFunctionElementProvider.AddQuery"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", "SqlFunctionElementProvider.AddQueryToolTip"), Icon = SqlFunctionElementProvider.AddFunction, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); return element; } private Element CreateXmlFunctionInfoElement(INamespaceTreeBuilderLeafInfo leafInfo, string connectionId) { var element = new Element(_context.CreateElementHandle(((SqlNamespaceTreeBuilderLeafInfo)leafInfo).EntityToken)) { VisualData = new ElementVisualizedData { Label = leafInfo.Name, ToolTip = leafInfo.Name, HasChildren = false, Icon = SqlFunctionElementProvider.Function } }; element.AddAction( new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider.EditSqlFunctionProviderWorkflow"), new PermissionType[] { PermissionType.Edit } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", "SqlFunctionElementProvider.EditQuery"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", "SqlFunctionElementProvider.EditQueryToolTip"), Icon = SqlFunctionElementProvider.EditFunction, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); element.AddAction( new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider.DeleteSqlFunctionProviderWorkflow"), new PermissionType[] { PermissionType.Delete } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", "SqlFunctionElementProvider.DeleteQuery"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", "SqlFunctionElementProvider.DeleteQueryToolTip"), Icon = SqlFunctionElementProvider.DeleteFunction, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); return element; } #endregion public Dictionary<EntityToken, IEnumerable<EntityToken>> GetParents(IEnumerable<EntityToken> entityTokens) { var result = new Dictionary<EntityToken, IEnumerable<EntityToken>>(); foreach (EntityToken entityToken in entityTokens) { var dataEntityToken = entityToken as DataEntityToken; if (dataEntityToken.InterfaceType == typeof(ISqlFunctionInfo)) { ISqlFunctionInfo sqlFunctionInfo = dataEntityToken.Data as ISqlFunctionInfo; var parentEntityToken = new SqlFunctionProviderFolderEntityToken(sqlFunctionInfo.Namespace, _context.ProviderName, sqlFunctionInfo.ConnectionId.ToString()); result.Add(entityToken, new EntityToken[] { parentEntityToken }); } else if (dataEntityToken.InterfaceType == typeof(ISqlConnection)) { var parentEntityToken = new SqlFunctionProviderRootEntityToken(_context.ProviderName, _context.ProviderName); result.Add(entityToken, new EntityToken[] { parentEntityToken }); } } return result; } public object GetData(string name) { Guid connectionId = new Guid(name); IEnumerable<ISqlFunctionInfo> sqlFunctionInfoes = from functionInfo in DataFacade.GetData<ISqlFunctionInfo>() where functionInfo.ConnectionId == connectionId select functionInfo; return new NamespaceTreeBuilder(sqlFunctionInfoes.Select(q => (INamespaceTreeBuilderLeafInfo)new SqlNamespaceTreeBuilderLeafInfo(q))); } [DebuggerDisplay("Name = {Name}, Namespace = {Namespace}")] private sealed class SqlNamespaceTreeBuilderLeafInfo : INamespaceTreeBuilderLeafInfo { readonly ISqlFunctionInfo _sqlFunctionInfo; public SqlNamespaceTreeBuilderLeafInfo(ISqlFunctionInfo sqlFunctionInfo) { _sqlFunctionInfo = sqlFunctionInfo; } public string Name { get { return _sqlFunctionInfo.Name; } } public string Namespace { get { return _sqlFunctionInfo.Namespace; } } public EntityToken EntityToken { get { return _sqlFunctionInfo.GetDataEntityToken(); } } } } [Assembler(typeof(SqlFunctionElementProviderAssembler))] internal sealed class SqlFunctionElementProviderData : HooklessElementProviderData { } internal sealed class SqlFunctionElementProviderAssembler : IAssembler<IHooklessElementProvider, HooklessElementProviderData> { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IHooklessElementProvider Assemble(IBuilderContext context, HooklessElementProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new SqlFunctionElementProvider(); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/SqlFunctionProviderEntityTokenSecurityAncestorProvider.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Core.Collections; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Elements; using Composite.Core.Extensions; using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider { internal sealed class SqlFunctionProviderEntityTokenSecurityAncestorProvider : ISecurityAncestorProvider { public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { if ((entityToken is SqlFunctionProviderRootEntityToken)) { return new EntityToken[] { }; } else if ((entityToken is SqlFunctionProviderFolderEntityToken)) { SqlFunctionProviderFolderEntityToken token = entityToken as SqlFunctionProviderFolderEntityToken; NamespaceTreeBuilder builder = (NamespaceTreeBuilder)ElementFacade.GetData(new ElementProviderHandle(token.Source), token.ConnectionId); NamespaceTreeBuilderFolder folder = builder.FindFolder(f => StringExtensionMethods.CreateNamespace(f.Namespace, f.Name, '.') == token.Id); if (folder == null) { return null; } else { int idx = token.Id.LastIndexOf('.'); if (idx != -1) { return new EntityToken[] { new SqlFunctionProviderFolderEntityToken(token.Id.Remove(idx), token.Source, token.ConnectionId) }; } else { Guid id = new Guid(token.ConnectionId); ISqlConnection sqlConnection = DataFacade.GetData<ISqlConnection>(f => f.Id == id).SingleOrDefault(); if (sqlConnection == null) { return new EntityToken[] { }; } return new EntityToken[] { sqlConnection.GetDataEntityToken() }; } } } else { throw new NotImplementedException(); } } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/SqlFunctionProviderFolderEntityToken.cs ================================================ using System.Collections.Generic; using System.Text; using Composite.C1Console.Security; using Composite.Core.Serialization; namespace Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(SqlFunctionProviderEntityTokenSecurityAncestorProvider))] public sealed class SqlFunctionProviderFolderEntityToken : EntityToken { private string _id; private string _source; private string _connectionId; internal SqlFunctionProviderFolderEntityToken(string id, string source, string connectionId) { _id = id; _source = source; _connectionId = connectionId; } /// <exclude /> public override string Type { get { return ""; } } /// <exclude /> public override string Source { get { return _source; } } /// <exclude /> public override string Id { get { return _id; } } /// <exclude /> public string ConnectionId { get { return _connectionId; } } /// <exclude /> public override string Serialize() { StringBuilder builder = new StringBuilder(); StringConversionServices.SerializeKeyValuePair<string>(builder, "id", _id); StringConversionServices.SerializeKeyValuePair<string>(builder, "source", _source); StringConversionServices.SerializeKeyValuePair<string>(builder, "connectionId", _connectionId); return builder.ToString(); } /// <exclude /> public static EntityToken Deserialize(string serializedData) { IDictionary<string, string> result = StringConversionServices.ParseKeyValueCollection(serializedData); string id = StringConversionServices.DeserializeValueString(result["id"]); string source = StringConversionServices.DeserializeValueString(result["source"]); string connectionId = StringConversionServices.DeserializeValueString(result["connectionId"]); return new SqlFunctionProviderFolderEntityToken(id, source, connectionId); } /// <exclude /> public override bool Equals(object obj) { return base.Equals(obj) && (obj as SqlFunctionProviderFolderEntityToken).ConnectionId == this.ConnectionId; } /// <exclude /> public override int GetHashCode() { if (this.HashCode == 0) { this.HashCode = GetType().GetHashCode() ^ this.Type.GetHashCode() ^ this.Source.GetHashCode() ^ this.Id.GetHashCode() ^ this.ConnectionId.GetHashCode(); } return this.HashCode; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/SqlFunctionProviderRootEntityToken.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Text; using Composite.C1Console.Security; using Composite.Data; using Composite.Core.Types; using Composite.Core.Serialization; namespace Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider { [SecurityAncestorProvider(typeof(SqlFunctionProviderEntityTokenSecurityAncestorProvider))] internal sealed class SqlFunctionProviderRootEntityToken : EntityToken { private string _id; private string _source; internal SqlFunctionProviderRootEntityToken(string id, string source) { _id = id; _source = source; } public override string Type { get { return ""; } } public override string Source { get { return _source; } } public override string Id { get { return _id; } } public override string Serialize() { return DoSerialize(); } public static EntityToken Deserialize(string serializedData) { string type, source, id; EntityToken.DoDeserialize(serializedData, out type, out source, out id); return new SqlFunctionProviderRootEntityToken(id, source); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/UserControlFunctionElementProvider/UserControlFunctionElementProvider.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.Linq; using Composite.AspNet.Security; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Core.ResourceSystem; using Composite.Functions; using Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Plugins_UserControlFunction; namespace Composite.Plugins.Elements.ElementProviders.UserControlFunctionElementProvider { [ConfigurationElementType(typeof(UserControlFunctionProviderElementProviderData))] internal class UserControlFunctionElementProvider : BaseFunctionProviderElementProvider.BaseFunctionProviderElementProvider { private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); protected static ResourceHandle AddFunctionIcon { get { return GetIconHandle("usercontrol-function-add"); } } protected static ResourceHandle EditFunctionIcon { get { return GetIconHandle("usercontrol-function-edit"); } } protected static ResourceHandle DeleteFunctionIcon { get { return GetIconHandle("usercontrol-function-delete"); } } private readonly string _functionProviderName; private readonly string _rootLabel; public UserControlFunctionElementProvider(string functionProvider, string rootLabel) { _functionProviderName = functionProvider; _rootLabel = rootLabel; } public override string FunctionProviderName { get { return _functionProviderName; } } protected override IEnumerable<IFunctionTreeBuilderLeafInfo> OnGetFunctionInfos(SearchToken searchToken) { var functions = FunctionFacade.GetFunctionsByProvider(_functionProviderName); if (searchToken != null && !String.IsNullOrEmpty(searchToken.Keyword)) { string keyword = searchToken.Keyword.ToLowerInvariant(); functions = functions.Where(f => f.Namespace.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) > 0 || f.Name.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) > 0); } return functions.Select(f => new UserControlFunctionTreeBuilderLeafInfo(f)); } protected override IEnumerable<Type> OnGetEntityTokenTypes() { return new[] { typeof(FileBasedFunctionEntityToken) }; } protected override IFunctionTreeBuilderLeafInfo OnIsEntityOwner(EntityToken entityToken) { if (entityToken is FileBasedFunctionEntityToken && entityToken.Source == _functionProviderName) { string functionFullName = entityToken.Id; IFunction function = FunctionFacade.GetFunctionsByProvider(_functionProviderName) .FirstOrDefault(func => func.Namespace + "." + func.Name == functionFullName); return function == null ? null : new UserControlFunctionTreeBuilderLeafInfo(function); } return null; } private sealed class UserControlFunctionTreeBuilderLeafInfo : IFunctionTreeBuilderLeafInfo { private readonly IFunction _function; public UserControlFunctionTreeBuilderLeafInfo(IFunction function) { _function = function; } public string Name { get { return _function.Name; } } public string Namespace { get { return _function.Namespace; } } public EntityToken EntityToken { get { return _function.EntityToken; } } } /// <exclude /> protected override IEnumerable<ElementAction> OnGetFolderActions() { Type workflow = WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.UserControlFunctionProviderElementProvider.AddNewUserControlFunctionWorkflow"); return new [] { new ElementAction(new ActionHandle(new WorkflowActionToken(workflow, new [] { PermissionType.Add }))) { VisualData = new ActionVisualizedData { Label = Texts.AddNewUserControlFunction_Label, ToolTip = Texts.AddNewUserControlFunction_ToolTip, Icon = AddFunctionIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } } }; } /// <exclude /> protected override IEnumerable<ElementAction> OnGetFunctionActions(IFunctionTreeBuilderLeafInfo function) { var editWorkflow = WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.UserControlFunctionProviderElementProvider.EditUserControlFunctionWorkflow"); var deleteWorkflow = WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.UserControlFunctionProviderElementProvider.DeleteUserControlFunctionWorkflow"); return new ElementAction[] { new ElementAction(new ActionHandle( new WorkflowActionToken( editWorkflow, new [] { PermissionType.Edit } ))) { VisualData = new ActionVisualizedData { Label = Texts.EditUserControlFunction_Label, ToolTip = Texts.EditUserControlFunction_ToolTip, Icon = EditFunctionIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }, new ElementAction(new ActionHandle( new WorkflowActionToken( deleteWorkflow, new [] { PermissionType.Delete } ){Payload = GetContext().ProviderName})) { VisualData = new ActionVisualizedData { Label = Texts.DeleteUserControlFunction_Label, ToolTip = Texts.DeleteUserControlFunction_ToolTip, Icon = DeleteFunctionIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } } }; } #region Configuration internal sealed class UserControlFunctionElementProviderAssembler : IAssembler<IHooklessElementProvider, HooklessElementProviderData> { [SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IHooklessElementProvider Assemble(IBuilderContext context, HooklessElementProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { var data = (UserControlFunctionProviderElementProviderData)objectConfiguration; return new UserControlFunctionElementProvider(data.UserControlFunctionProviderName, data.Label); } } [Assembler(typeof(UserControlFunctionElementProviderAssembler))] internal sealed class UserControlFunctionProviderElementProviderData : HooklessElementProviderData { private const string _UserControlFunctionProviderNameProperty = "userControlFunctionProviderName"; [ConfigurationProperty(_UserControlFunctionProviderNameProperty, IsRequired = true)] public string UserControlFunctionProviderName { get { return (string)base[_UserControlFunctionProviderNameProperty]; } set { base[_UserControlFunctionProviderNameProperty] = value; } } private const string _labelProperty = "label"; [ConfigurationProperty(_labelProperty, DefaultValue = null)] public string Label { get { return (string)base[_labelProperty]; } set { base[_labelProperty] = value; } } } #endregion Configuration protected override string RootFolderLabel { get { return !string.IsNullOrEmpty(_rootLabel) ? StringResourceSystemFacade.ParseString(_rootLabel) : Texts.RootElement_Label; } } protected override string RootFolderToolTip { get { return Texts.RootElement_ToolTip; } } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/UserElementProvider/ActiveLocalesFormsHelper.cs ================================================ using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Xml.Linq; using Composite.Data; using Composite.C1Console.Forms; using Composite.Core.ResourceSystem; using Composite.Core.Xml; namespace Composite.Plugins.Elements.ElementProviders.UserElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ActiveLocalesFormsHelper { private List<XElement> _bindingElements = null; private XElement _fieldGroupElement = null; private static readonly string MultiKeySelectorOptionsBindingName = "ActiveLocalesFormsHelper_Options"; private static readonly string MultiKeySelectorSelectedBindingName = "ActiveLocalesFormsHelper_Selected"; /// <exclude /> public ActiveLocalesFormsHelper(string fieldLabel, string multiSelectLabel, string multiSelectHelp) { this.FieldLabel = fieldLabel; this.MultiSelectLabel = multiSelectLabel; this.MultiSelectHelp = multiSelectHelp; } /// <exclude /> public void UpdateWithNewBindings(Dictionary<string, object> bindings, IEnumerable<CultureInfo> userActiveLocales) { Dictionary<string, string> options = new Dictionary<string, string>(); foreach (CultureInfo cultureInfo in DataLocalizationFacade.ActiveLocalizationCultures) { options.Add( cultureInfo.Name, DataLocalizationFacade.GetCultureTitle(cultureInfo) ); } if (bindings.ContainsKey(MultiKeySelectorOptionsBindingName) == false) { bindings.Add(MultiKeySelectorOptionsBindingName, options); } else { bindings[MultiKeySelectorOptionsBindingName] = options; } if (bindings.ContainsKey(MultiKeySelectorSelectedBindingName) == false) { bindings.Add(MultiKeySelectorSelectedBindingName, userActiveLocales.Select(f => f.Name).ToList()); } else { bindings[MultiKeySelectorSelectedBindingName] = userActiveLocales.Select(f => f.Name).ToList(); } } /// <exclude /> public static string GetFieldBindingPath() { return MultiKeySelectorSelectedBindingName; } /// <exclude /> public static IEnumerable<CultureInfo> GetSelectedLocalesTypes(Dictionary<string, object> bindings) { List<string> cultureNames = (List<string>)bindings[MultiKeySelectorSelectedBindingName]; foreach (string cultureName in cultureNames) { yield return CultureInfo.CreateSpecificCulture(cultureName); } } /// <exclude /> public IEnumerable<XElement> GetBindingsMarkup() { if (_bindingElements == null) { CreateMarkup(); } return _bindingElements; } /// <exclude /> public XElement GetFormMarkup() { if (_fieldGroupElement == null) { CreateMarkup(); } return _fieldGroupElement; } /// <exclude /> public string FieldLabel { get; set; } /// <exclude /> public string MultiSelectLabel { get; set; } /// <exclude /> public string MultiSelectHelp { get; set; } private void CreateMarkup() { _bindingElements = new List<XElement>(); _bindingElements.Add( new XElement( Namespaces.BindingForms10 + FormKeyTagNames.Binding, new XAttribute("name", MultiKeySelectorOptionsBindingName), new XAttribute("type", typeof(Dictionary<string, string>)) )); _bindingElements.Add( new XElement( Namespaces.BindingForms10 + FormKeyTagNames.Binding, new XAttribute("name", MultiKeySelectorSelectedBindingName), new XAttribute("type", typeof(List<string>)) )); _fieldGroupElement = new XElement( Namespaces.BindingFormsStdUiControls10 + "FieldGroup", new XAttribute("Label", this.FieldLabel)); XElement multiKeySelectorElement = new XElement( Namespaces.BindingFormsStdUiControls10 + "MultiKeySelector", new XAttribute("Label", this.MultiSelectLabel), new XAttribute("Help", this.MultiSelectHelp), new XAttribute("OptionsKeyField", "Key"), new XAttribute("OptionsLabelField", "Value"), new XElement(Namespaces.BindingFormsStdUiControls10 + "MultiKeySelector.Options", new XElement(Namespaces.BindingForms10 + "read", new XAttribute("source", MultiKeySelectorOptionsBindingName) ) ), new XElement(Namespaces.BindingFormsStdUiControls10 + "MultiKeySelector.Selected", new XElement(Namespaces.BindingForms10 + "bind", new XAttribute("source", MultiKeySelectorSelectedBindingName) ) ) ); _fieldGroupElement.Add(multiKeySelectorElement); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/UserElementProvider/ActivePerspectiveFormsHelper.cs ================================================ using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.C1Console.Elements; using Composite.C1Console.Forms; using Composite.C1Console.Security; using Composite.Core.Xml; namespace Composite.Plugins.Elements.ElementProviders.UserElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class ActivePerspectiveFormsHelper { private readonly List<Element> _perspectiveElements; private List<XElement> _bindingElements; private XElement _fieldGroupElement; private static readonly string MultiKeySelectorOptionsBindingName = "ActivePerspectiveFormsHelper_Options"; private static readonly string MultiKeySelectorSelectedBindingName = "ActivePerspectiveFormsHelper_Selected"; /// <exclude /> public ActivePerspectiveFormsHelper(string fieldLabel, string multiSelectLabel, string multiSelectHelp) { this.FieldLabel = fieldLabel; this.MultiSelectLabel = multiSelectLabel; this.MultiSelectHelp = multiSelectHelp; _perspectiveElements = ElementFacade.GetPerspectiveElementsWithNoSecurity().ToList(); } /// <exclude /> public void UpdateWithNewBindings(Dictionary<string, object> bindings, IEnumerable<string> selectedSerializedEntityTokens) { var options = _perspectiveElements.ToDictionary( perspectiveElement => EntityTokenSerializer.Serialize(perspectiveElement.ElementHandle.EntityToken), perspectiveElement => perspectiveElement.VisualData.Label); bindings[MultiKeySelectorOptionsBindingName] = options; bindings[MultiKeySelectorSelectedBindingName] = selectedSerializedEntityTokens.ToList(); } /// <exclude /> public static IEnumerable<string> GetSelectedSerializedEntityTokens(Dictionary<string, object> bindings) { return (List<string>)bindings[MultiKeySelectorSelectedBindingName]; } /// <exclude /> public IEnumerable<XElement> GetBindingsMarkup() { if (_bindingElements == null) { CreateMarkup(); } return _bindingElements; } /// <exclude /> public XElement GetFormMarkup() { if (_fieldGroupElement == null) { CreateMarkup(); } return _fieldGroupElement; } /// <exclude /> public string FieldLabel { get; set; } /// <exclude /> public string MultiSelectLabel { get; set; } /// <exclude /> public string MultiSelectHelp { get; set; } private void CreateMarkup() { _bindingElements = new List<XElement>(); _bindingElements.Add( new XElement( Namespaces.BindingForms10 + FormKeyTagNames.Binding, new XAttribute("name", MultiKeySelectorOptionsBindingName), new XAttribute("type", typeof(Dictionary<string, string>)) )); _bindingElements.Add( new XElement( Namespaces.BindingForms10 + FormKeyTagNames.Binding, new XAttribute("name", MultiKeySelectorSelectedBindingName), new XAttribute("type", typeof(List<string>)) )); _fieldGroupElement = new XElement( Namespaces.BindingFormsStdUiControls10 + "FieldGroup", new XAttribute("Label", this.FieldLabel)); XElement multiKeySelectorElement = new XElement( Namespaces.BindingFormsStdUiControls10 + "MultiKeySelector", new XAttribute("Label", this.MultiSelectLabel), new XAttribute("Help", this.MultiSelectHelp), new XAttribute("OptionsKeyField", "Key"), new XAttribute("OptionsLabelField", "Value"), new XElement(Namespaces.BindingFormsStdUiControls10 + "MultiKeySelector.Options", new XElement(Namespaces.BindingForms10 + "read", new XAttribute("source", MultiKeySelectorOptionsBindingName) ) ), new XElement(Namespaces.BindingFormsStdUiControls10 + "MultiKeySelector.Selected", new XElement(Namespaces.BindingForms10 + "bind", new XAttribute("source", MultiKeySelectorSelectedBindingName) ) ) ); _fieldGroupElement.Add(multiKeySelectorElement); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/UserElementProvider/GlobalPermissionsFormsHelper.cs ================================================ using System.Linq; using System.Xml.Linq; using System.Collections.Generic; using Composite.C1Console.Security; using System; using Composite.Core.Xml; using Composite.C1Console.Forms; namespace Composite.Plugins.Elements.ElementProviders.UserElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class GlobalPermissionsFormsHelper { private List<XElement> _bindingElements = null; private XElement _fieldGroupElement = null; private static readonly string MultiKeySelectorOptionsBindingName = "GlobalPermissionsFormsHelper_Options"; private static readonly string MultiKeySelectorSelectedBindingName = "GlobalPermissionsFormsHelper_Selected"; /// <exclude /> public GlobalPermissionsFormsHelper(string fieldLabel, string multiSelectLabel, string multiSelectHelp) { this.FieldLabel = fieldLabel; this.MultiSelectLabel = multiSelectLabel; this.MultiSelectHelp = multiSelectHelp; } /// <exclude /> public void UpdateWithNewBindings(Dictionary<string, object> bindings, IEnumerable<PermissionType> selectedPermissionTypes) { Dictionary<string, string> options = new Dictionary<string, string>(); foreach (PermissionDescriptor permissionDescriptor in PermissionTypeFacade.GrantingPermissionDescriptors) { options.Add( permissionDescriptor.PermissionType.ToString(), permissionDescriptor.Label ); } if (bindings.ContainsKey(MultiKeySelectorOptionsBindingName) == false) { bindings.Add(MultiKeySelectorOptionsBindingName, options); } else { bindings[MultiKeySelectorOptionsBindingName] = options; } if (bindings.ContainsKey(MultiKeySelectorSelectedBindingName) == false) { bindings.Add(MultiKeySelectorSelectedBindingName, selectedPermissionTypes.Where(f => f != PermissionType.ClearPermissions).Select(f => f.ToString()).ToList()); } else { bindings[MultiKeySelectorSelectedBindingName] = selectedPermissionTypes.Where(f => f != PermissionType.ClearPermissions).Select(f => f.ToString()).ToList(); } } /// <exclude /> public static string GetFieldBindingPath() { return MultiKeySelectorSelectedBindingName; } /// <exclude /> public static IEnumerable<PermissionType> GetSelectedPermissionTypes(Dictionary<string, object> bindings) { List<string> serializedPermissionTypes = (List<string>)bindings[MultiKeySelectorSelectedBindingName]; foreach (string serializedPermissionType in serializedPermissionTypes) { yield return (PermissionType)Enum.Parse(typeof(PermissionType), serializedPermissionType); } } /// <exclude /> public IEnumerable<XElement> GetBindingsMarkup() { if (_bindingElements == null) { CreateMarkup(); } return _bindingElements; } /// <exclude /> public XElement GetFormMarkup() { if (_fieldGroupElement == null) { CreateMarkup(); } return _fieldGroupElement; } /// <exclude /> public string FieldLabel { get; set; } /// <exclude /> public string MultiSelectLabel { get; set; } /// <exclude /> public string MultiSelectHelp { get; set; } private void CreateMarkup() { _bindingElements = new List<XElement>(); _bindingElements.Add( new XElement( Namespaces.BindingForms10 + FormKeyTagNames.Binding, new XAttribute("name", MultiKeySelectorOptionsBindingName), new XAttribute("type", typeof(Dictionary<string, string>)) )); _bindingElements.Add( new XElement( Namespaces.BindingForms10 + FormKeyTagNames.Binding, new XAttribute("name", MultiKeySelectorSelectedBindingName), new XAttribute("type", typeof(List<string>)) )); _fieldGroupElement = new XElement( Namespaces.BindingFormsStdUiControls10 + "FieldGroup", new XAttribute("Label", this.FieldLabel)); XElement multiKeySelectorElement = new XElement( Namespaces.BindingFormsStdUiControls10 + "MultiKeySelector", new XAttribute("Label", this.MultiSelectLabel), new XAttribute("Help", this.MultiSelectHelp), new XAttribute("OptionsKeyField", "Key"), new XAttribute("OptionsLabelField", "Value"), new XElement(Namespaces.BindingFormsStdUiControls10 + "MultiKeySelector.Options", new XElement(Namespaces.BindingForms10 + "read", new XAttribute("source", MultiKeySelectorOptionsBindingName) ) ), new XElement(Namespaces.BindingFormsStdUiControls10 + "MultiKeySelector.Selected", new XElement(Namespaces.BindingForms10 + "bind", new XAttribute("source", MultiKeySelectorSelectedBindingName) ) ) ); _fieldGroupElement.Add(multiKeySelectorElement); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/UserElementProvider/UserElementProvider.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Plugins.Security.LoginProviderPlugins.DataBasedFormLoginProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Elements.ElementProviders.UserElementProvider { internal sealed class UserElementProvider : IHooklessElementProvider, IAuxiliarySecurityAncestorProvider { private ElementProviderContext _elementProviderContext; public static ResourceHandle RootOpenIcon { get { return GetIconHandle("users-rootfolder-open"); } } public static ResourceHandle RootClosedIcon { get { return GetIconHandle("users-rootfolder-closed"); } } public static ResourceHandle GroupOpenIcon { get { return GetIconHandle("users-group-open"); } } public static ResourceHandle GroupClosedIcon { get { return GetIconHandle("users-group-closed"); } } public static ResourceHandle UserIcon { get { return GetIconHandle("users-user"); } } public static ResourceHandle LockedUserIcon { get { return GetIconHandle("users-user-disabled"); } } public static ResourceHandle AddUserIcon { get { return GetIconHandle("users-adduser"); } } public static ResourceHandle EditUserIcon { get { return GetIconHandle("users-edituser"); } } public static ResourceHandle DeleteUserIcon { get { return GetIconHandle("users-deleteuser"); } } private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); private static readonly PermissionType[] AddNewUserPermissionTypes = new PermissionType[] { PermissionType.Administrate }; public UserElementProvider() { AuxiliarySecurityAncestorFacade.AddAuxiliaryAncestorProvider<DataEntityToken>(this); } public ElementProviderContext Context { set { _elementProviderContext = value; } } private class UserInfo { public IUser User { get; set; } public IUserFormLogin UserFormLogin { get; set; } } public IEnumerable<Element> GetRoots(SearchToken seachToken) { int userCount = (from user in DataFacade.GetData<IUser>() select user).Count(); Element element = new Element(_elementProviderContext.CreateElementHandle(new UserElementProviderEntityToken())) { VisualData = new ElementVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Management", "UserElementProvider.RootLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "UserElementProvider.RootToolTip"), HasChildren = userCount > 0, Icon = UserElementProvider.RootClosedIcon, OpenedIcon = UserElementProvider.RootOpenIcon } }; element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.UserElementProvider.AddNewUserWorkflow"), AddNewUserPermissionTypes))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Management", "UserElementProvider.AddUserLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "UserElementProvider.AddUserToolTip"), Icon = UserElementProvider.AddUserIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); yield return element; } public IEnumerable<Element> GetChildren(EntityToken entityToken, SearchToken seachToken) { if (entityToken is UserElementProviderEntityToken) { return GetGroupChildrenElements(seachToken); } if (entityToken is UserElementProviderGroupEntityToken) { return GetUsersChildrenElements(entityToken.Id, seachToken); } return new Element[] { }; } public Dictionary<EntityToken, IEnumerable<EntityToken>> GetParents(IEnumerable<EntityToken> entityTokens) { var result = new Dictionary<EntityToken, IEnumerable<EntityToken>>(); foreach (EntityToken entityToken in entityTokens) { var dataEntityToken = entityToken as DataEntityToken; Type type = dataEntityToken.InterfaceType; if (type != typeof(IUser)) continue; IUser user = dataEntityToken.Data as IUser; IUserFormLogin userFormLogin = user.GetUserFormLogin(); var newEntityToken = new UserElementProviderGroupEntityToken(userFormLogin.Folder); result.Add(entityToken, new EntityToken[] { newEntityToken }); } return result; } private IEnumerable<Element> GetGroupChildrenElements(SearchToken seachToken) { IEnumerable<string> groups; if (!seachToken.IsValidKeyword()) { groups = (from user in DataFacade.GetData<IUserFormLogin>() orderby user.Folder select user.Folder).Distinct().ToList(); } else { string keyword = seachToken.Keyword.ToLowerInvariant(); groups = (from userFormLogin in DataFacade.GetData<IUserFormLogin>().ToList() join user in DataFacade.GetData<IUser>().ToList() on userFormLogin.UserId equals user.Id where user.Username.ToLowerInvariant().Contains(keyword) orderby userFormLogin.Folder select userFormLogin.Folder).Distinct().ToList(); } var children = new List<Element>(); foreach (string group in groups) { var element = new Element(_elementProviderContext.CreateElementHandle(new UserElementProviderGroupEntityToken(group))) { VisualData = new ElementVisualizedData { Label = group, ToolTip = group, HasChildren = true, Icon = UserElementProvider.GroupClosedIcon, OpenedIcon = UserElementProvider.GroupOpenIcon } }; element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.UserElementProvider.AddNewUserWorkflow"), AddNewUserPermissionTypes))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Management", "UserElementProvider.AddUserLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "UserElementProvider.AddUserToolTip"), Icon = UserElementProvider.AddUserIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); children.Add(element); } return children; } private IEnumerable<Element> GetUsersChildrenElements(string folderName, SearchToken seachToken) { ICollection<UserInfo> users; if (!seachToken.IsValidKeyword()) { users = (from userFormLogin in DataFacade.GetData<IUserFormLogin>().ToList() join user in DataFacade.GetData<IUser>().ToList() on userFormLogin.UserId equals user.Id where userFormLogin.Folder == folderName orderby user.Username select new UserInfo { User = user, UserFormLogin = userFormLogin }).ToList(); } else { string keyword = seachToken.Keyword.ToLowerInvariant(); users = (from userFormLogin in DataFacade.GetData<IUserFormLogin>().ToList() join user in DataFacade.GetData<IUser>().ToList() on userFormLogin.UserId equals user.Id where userFormLogin.Folder == folderName && user.Username.ToLowerInvariant().Contains(keyword) orderby user.Username select new UserInfo { User = user, UserFormLogin = userFormLogin }).ToList(); } var children = new List<Element>(); foreach (var userInfo in users) { string label = userInfo.User.GetLabel(); var element = new Element(_elementProviderContext.CreateElementHandle(userInfo.User.GetDataEntityToken())) { VisualData = new ElementVisualizedData { Label = label, ToolTip = label, HasChildren = false, Icon = !userInfo.UserFormLogin.IsLocked ? UserIcon : LockedUserIcon, } }; // Making "Edit permissions" not show up on user elements - it's confusing :) element.ElementExternalActionAdding = ElementExternalActionAddingExtensions.Remove(element.ElementExternalActionAdding, ElementExternalActionAdding.AllowManageUserPermissions); element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.UserElementProvider.EditUserWorkflow"), new PermissionType[] { PermissionType.Administrate }))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Management", "UserElementProvider.EditUserLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "UserElementProvider.EditUserToolTip"), Icon = UserElementProvider.EditUserIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.UserElementProvider.DeleteUserWorkflow"), new PermissionType[] { PermissionType.Administrate }))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Management", "UserElementProvider.DeleteUserLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "UserElementProvider.DeleteUserToolTip"), Icon = UserElementProvider.DeleteUserIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); children.Add(element); } return children; } private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } } internal sealed class UserElementProviderAssembler : IAssembler<IHooklessElementProvider, HooklessElementProviderData> { public IHooklessElementProvider Assemble(IBuilderContext context, HooklessElementProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new UserElementProvider(); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/UserElementProvider/UserElementProviderEntityToken.cs ================================================ using Composite.C1Console.Security; using Composite.C1Console.Security.SecurityAncestorProviders; namespace Composite.Plugins.Elements.ElementProviders.UserElementProvider { [SecurityAncestorProvider(typeof(NoAncestorSecurityAncestorProvider))] internal sealed class UserElementProviderEntityToken : EntityToken { public override string Type { get { return ""; } } public override string Source { get { return ""; } } public override string Id { get { return "UserElementProviderEntityToken"; } } public override string Serialize() { return DoSerialize(); } public static EntityToken Deserialize(string serializedEntityToken) { return new UserElementProviderEntityToken(); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/UserElementProvider/UserElementProviderGroupEntityToken.cs ================================================ using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.UserElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(UserElementProviderGroupEntityTokenSecurityAncestorProvider))] public sealed class UserElementProviderGroupEntityToken : EntityToken { private string _id; /// <exclude /> public UserElementProviderGroupEntityToken(string id) { _id = id; } /// <exclude /> public override string Type { get { return ""; } } /// <exclude /> public override string Source { get { return ""; } } /// <exclude /> public override string Id { get { return _id; } } /// <exclude /> public override string Serialize() { return _id; } /// <exclude /> public static EntityToken Deserialize(string serializedData) { return new UserElementProviderGroupEntityToken(serializedData); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/UserElementProvider/UserElementProviderGroupEntityTokenSecurityAncestorProvider.cs ================================================ using Composite.C1Console.Security; using System.Collections.Generic; namespace Composite.Plugins.Elements.ElementProviders.UserElementProvider { internal sealed class UserElementProviderGroupEntityTokenSecurityAncestorProvider : ISecurityAncestorProvider { public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { yield return new UserElementProviderEntityToken(); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/UserElementProvider/UserGroupsFormsHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using Composite.Core.Xml; using Composite.C1Console.Forms; using Composite.Data.Types; using Composite.Data; namespace Composite.Plugins.Elements.ElementProviders.UserElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class UserGroupsFormsHelper { private List<XElement> _bindingElements = null; private XElement _fieldGroupElement = null; private static readonly string MultiKeySelectorOptionsBindingName = "UserGroupsFormsHelper_Options"; private static readonly string MultiKeySelectorSelectedBindingName = "UserGroupsFormsHelper_Selected"; /// <exclude /> public UserGroupsFormsHelper(string fieldLabel, string multiSelectHelp) { this.FieldLabel = fieldLabel; this.MultiSelectHelp = multiSelectHelp; } /// <exclude /> public void UpdateWithNewBindings(Dictionary<string, object> bindings, IEnumerable<Guid> selectedUserGroups) { Dictionary<Guid, string> options = new Dictionary<Guid, string>(); List<IUserGroup> userGroups = DataFacade.GetData<IUserGroup>().OrderBy(f => f.Name).ToList(); foreach (IUserGroup userGroup in userGroups) { options.Add(userGroup.Id, userGroup.Name); } if (bindings.ContainsKey(MultiKeySelectorOptionsBindingName) == false) { bindings.Add(MultiKeySelectorOptionsBindingName, options); } else { bindings[MultiKeySelectorOptionsBindingName] = options; } if (bindings.ContainsKey(MultiKeySelectorSelectedBindingName) == false) { bindings.Add(MultiKeySelectorSelectedBindingName, selectedUserGroups.ToList()); } else { bindings[MultiKeySelectorSelectedBindingName] = selectedUserGroups.ToList(); } } /// <exclude /> public static List<Guid> GetSelectedUserGroupIds(Dictionary<string, object> bindings) { return (List<Guid>)bindings[MultiKeySelectorSelectedBindingName]; } /// <exclude /> public IEnumerable<XElement> GetBindingsMarkup() { if (_bindingElements == null) { CreateMarkup(); } return _bindingElements; } /// <exclude /> public XElement GetFormMarkup() { if (_fieldGroupElement == null) { CreateMarkup(); } return _fieldGroupElement; } /// <exclude /> public string FieldLabel { get; set; } /// <exclude /> public string MultiSelectLabel { get; set; } /// <exclude /> public string MultiSelectHelp { get; set; } private void CreateMarkup() { _bindingElements = new List<XElement>(); _bindingElements.Add( new XElement( Namespaces.BindingForms10 + FormKeyTagNames.Binding, new XAttribute("name", MultiKeySelectorOptionsBindingName), new XAttribute("type", typeof(Dictionary<Guid, string>)) )); _bindingElements.Add( new XElement( Namespaces.BindingForms10 + FormKeyTagNames.Binding, new XAttribute("name", MultiKeySelectorSelectedBindingName), new XAttribute("type", typeof(List<Guid>)) )); _fieldGroupElement = new XElement( Namespaces.BindingFormsStdUiControls10 + "FieldGroup", new XAttribute("Label", this.FieldLabel)); XElement multiKeySelectorElement = new XElement( Namespaces.BindingFormsStdUiControls10 + "MultiKeySelector", new XAttribute("Help", this.MultiSelectHelp), new XAttribute("OptionsKeyField", "Key"), new XAttribute("OptionsLabelField", "Value"), new XElement(Namespaces.BindingFormsStdUiControls10 + "MultiKeySelector.Options", new XElement(Namespaces.BindingForms10 + "read", new XAttribute("source", MultiKeySelectorOptionsBindingName) ) ), new XElement(Namespaces.BindingFormsStdUiControls10 + "MultiKeySelector.Selected", new XElement(Namespaces.BindingForms10 + "bind", new XAttribute("source", MultiKeySelectorSelectedBindingName) ) ) ); _fieldGroupElement.Add(multiKeySelectorElement); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/UserGroupElementProvider/UserGroupElementProvider.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Data; using Composite.Core.Linq; using Composite.Data.Types; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.C1Console.Security; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Composite.C1Console.Workflow; using Composite.Core.Types; namespace Composite.Plugins.Elements.ElementProviders.UserGroupElementProvider { [ConfigurationElementType(typeof(NonConfigurableHooklessElementProvider))] internal sealed class UserGroupElementProvider : IHooklessElementProvider, IAuxiliarySecurityAncestorProvider { private ElementProviderContext _elementProviderContext; public static ResourceHandle RootOpenIcon { get { return GetIconHandle("usergroups-rootfolder-open"); } } public static ResourceHandle RootClosedIcon { get { return GetIconHandle("usergroups-rootfolder-closed"); } } public static ResourceHandle UserGroupIcon { get { return GetIconHandle("usergroups-usergroup"); } } public static ResourceHandle AddUserGroupIcon { get { return GetIconHandle("usergroups-addusergroup"); } } public static ResourceHandle EditUserGroupIcon { get { return GetIconHandle("usergroups-editusergroup"); } } public static ResourceHandle DeleteUserGroupIcon { get { return GetIconHandle("usergroups-deleteusergroup"); } } private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); private static readonly PermissionType[] AddNewUserGroupPermissionTypes = new PermissionType[] { PermissionType.Administrate }; private static readonly PermissionType[] EditUserGroupPermissionTypes = new PermissionType[] { PermissionType.Administrate }; private static readonly PermissionType[] DeleteUserGroupPermissionTypes = new PermissionType[] { PermissionType.Administrate }; public UserGroupElementProvider() { AuxiliarySecurityAncestorFacade.AddAuxiliaryAncestorProvider<DataEntityToken>(this); } public ElementProviderContext Context { set { _elementProviderContext = value; } } public IEnumerable<Element> GetRoots(SearchToken seachToken) { int userGroupCount = DataFacade.GetData<IUserGroup>().Count(); Element element = new Element(_elementProviderContext.CreateElementHandle(new UserGroupElementProviderRootEntityToken())) { VisualData = new ElementVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.UserGroupElementProvider", "UserGroupElementProvider.RootLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.UserGroupElementProvider", "UserGroupElementProvider.RootToolTip"), HasChildren = userGroupCount > 0, Icon = UserGroupElementProvider.RootClosedIcon, OpenedIcon = UserGroupElementProvider.RootOpenIcon } }; element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.UserGroupElementProvider.AddNewUserGroupWorkflow"), AddNewUserGroupPermissionTypes))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.UserGroupElementProvider", "UserGroupElementProvider.AddNewUserGroupLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.UserGroupElementProvider", "UserGroupElementProvider.AddNewUserGroupToolTip"), Icon = UserGroupElementProvider.AddUserGroupIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); yield return element; } public IEnumerable<Element> GetChildren(EntityToken entityToken, SearchToken seachToken) { if ((entityToken is UserGroupElementProviderRootEntityToken) == false) return new Element[] { }; IEnumerable<IUserGroup> userGroups = (from ug in DataFacade.GetData<IUserGroup>() orderby ug.Name select ug).Evaluate(); List<Element> elements = new List<Element>(); foreach (IUserGroup userGroup in userGroups) { Element element = new Element(_elementProviderContext.CreateElementHandle(userGroup.GetDataEntityToken())) { VisualData = new ElementVisualizedData { Label = userGroup.Name, ToolTip = userGroup.Name, HasChildren = false, Icon = UserGroupElementProvider.UserGroupIcon, OpenedIcon = UserGroupElementProvider.UserGroupIcon } }; element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.UserGroupElementProvider.EditUserGroupWorkflow"), EditUserGroupPermissionTypes))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.UserGroupElementProvider", "UserGroupElementProvider.EditUserGroupLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.UserGroupElementProvider", "UserGroupElementProvider.EditUserGroupToolTip"), Icon = UserGroupElementProvider.EditUserGroupIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.UserGroupElementProvider.DeleteUserGroupWorkflow"), DeleteUserGroupPermissionTypes))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.UserGroupElementProvider", "UserGroupElementProvider.DeleteUserGroupLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.UserGroupElementProvider", "UserGroupElementProvider.DeleteUserGroupToolTip"), Icon = UserGroupElementProvider.DeleteUserGroupIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); elements.Add(element); } return elements; } public Dictionary<EntityToken, IEnumerable<EntityToken>> GetParents(IEnumerable<EntityToken> entityTokens) { Dictionary<EntityToken, IEnumerable<EntityToken>> result = new Dictionary<EntityToken, IEnumerable<EntityToken>>(); foreach (EntityToken entityToken in entityTokens) { DataEntityToken dataEntityToken = entityToken as DataEntityToken; Type type = dataEntityToken.InterfaceType; if (type != typeof(IUserGroup)) continue; UserGroupElementProviderRootEntityToken newEntityToken = new UserGroupElementProviderRootEntityToken(); result.Add(entityToken, new EntityToken[] { newEntityToken }); } return result; } private List<EntityTokenHook> CreateHooks() { IEnumerable<EntityToken> userGroupsEntityTokens = from ug in DataFacade.GetData<IUserGroup>() select (EntityToken)ug.GetDataEntityToken(); EntityTokenHook hook = new EntityTokenHook(new UserGroupElementProviderRootEntityToken()); hook.AddHookies(userGroupsEntityTokens); return new List<EntityTokenHook> { hook }; } private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/UserGroupElementProvider/UserGroupElementProviderRootEntityToken.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.C1Console.Security; using Composite.C1Console.Security.SecurityAncestorProviders; namespace Composite.Plugins.Elements.ElementProviders.UserGroupElementProvider { [SecurityAncestorProvider(typeof(NoAncestorSecurityAncestorProvider))] internal sealed class UserGroupElementProviderRootEntityToken : EntityToken { public override string Type { get { return ""; } } public override string Source { get { return ""; } } public override string Id { get { return "UserGroupElementProviderRootEntityToken"; } } public override string Serialize() { return DoSerialize(); } public static EntityToken Deserialize(string serializedEntityToken) { return new UserGroupElementProviderRootEntityToken(); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/VirtualElementProvider/AttachProviderVirtualElement.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Elements.ElementProviders.VirtualElementProvider { [ConfigurationElementType(typeof(AttachProviderVirtualElement))] internal class AttachProviderVirtualElement : VirtualElementConfigurationElement { private const string _providerNameProperty = "providerName"; [ConfigurationProperty(_providerNameProperty, IsRequired = true)] public string ProviderName { get { return (string)base[_providerNameProperty]; } set { base[_providerNameProperty] = value; } } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/VirtualElementProvider/BaseElementConfigurationElement.cs ================================================ using System; using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Elements.ElementProviders.VirtualElementProvider { [Obsolete("Was replaced by VirtualElementConfigurationElement")] internal class BaseElementConfigurationElement : NameTypeConfigurationElement { private const string _idProperty = "id"; [ConfigurationProperty(_idProperty, IsRequired = true, IsKey = true)] public string Id { get { return (string)base[_idProperty]; } set { base[_idProperty] = value; } } private const string _orderProperty = "order"; [ConfigurationProperty(_orderProperty, IsRequired = true, IsKey = true)] public int Order { get { return (int)base[_orderProperty]; } set { base[_orderProperty] = value; } } private const string _parentIdProperty = "parentId"; [ConfigurationProperty(_parentIdProperty)] public string ParentId { get { return (string)base[_parentIdProperty]; } set { base[_parentIdProperty] = value; } } private const string _labelProperty = "label"; [ConfigurationProperty(_labelProperty, IsRequired = true)] public string Label { get { return (string)base[_labelProperty]; } set { base[_labelProperty] = value; } } private const string _tagProperty = "tag"; [ConfigurationProperty(_tagProperty, DefaultValue = null)] public string Tag { get { return (string)base[_tagProperty]; } set { base[_tagProperty] = value; } } private const string _closeFolderIconNameProperty = "closeFolderIconName"; [ConfigurationProperty(_closeFolderIconNameProperty)] public string CloseFolderIconName { get { return (string)base[_closeFolderIconNameProperty]; } set { base[_closeFolderIconNameProperty] = value; } } private const string _openFolderIconNameProperty = "openFolderIconName"; [ConfigurationProperty(_openFolderIconNameProperty)] public string OpenFolderIconName { get { return (string)base[_openFolderIconNameProperty]; } set { base[_openFolderIconNameProperty] = value; } } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/VirtualElementProvider/BaseElementNode.cs ================================================ using System.Collections.Generic; using System.Diagnostics; namespace Composite.Plugins.Elements.ElementProviders.VirtualElementProvider { [DebuggerDisplay("Id = {Id}, Label={Label}")] internal class BaseElementNode { private List<BaseElementNode> _children = new List<BaseElementNode>(); public string Id { get; set; } public string Label { get; set; } public string Tag { get; set; } public string OpenFolderIconName { get; set; } public string CloseFolderIconName { get; set; } public List<BaseElementNode> Children { get { return _children; } } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/VirtualElementProvider/FolderElementConfigurationElement.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using System.Configuration; namespace Composite.Plugins.Elements.ElementProviders.VirtualElementProvider { [Obsolete()] [ConfigurationElementType(typeof(FolderElementConfigurationElement))] internal sealed class FolderElementConfigurationElement : BaseElementConfigurationElement { } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/VirtualElementProvider/FolderElementNode.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Elements; namespace Composite.Plugins.Elements.ElementProviders.VirtualElementProvider { internal sealed class FolderElementNode : BaseElementNode { } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/VirtualElementProvider/PlaceholderVirtualElement.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Elements.ElementProviders.VirtualElementProvider { [ConfigurationElementType(typeof(PlaceholderVirtualElement))] internal class PlaceholderVirtualElement : SimpleVirtualElement { private const string _path = "path"; [ConfigurationProperty(_path)] public string Path { get { return (string)base[_path]; } set { base[_path] = value; } } private const string _IsTool = "IsTool"; [ConfigurationProperty(_IsTool)] public string IsTool { get { return (string)base[_IsTool]; } set { base[_IsTool] = value; } } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/VirtualElementProvider/ProviderHookingElementConfigurationElement.cs ================================================ using System; using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Elements.ElementProviders.VirtualElementProvider { [Obsolete()] [ConfigurationElementType(typeof(ProviderHookingElementConfigurationElement))] internal sealed class ProviderHookingElementConfigurationElement : BaseElementConfigurationElement { private const string _providerNameProperty = "providerName"; [ConfigurationProperty(_providerNameProperty, IsRequired = true)] public string ProviderName { get { return (string)base[_providerNameProperty]; } set { base[_providerNameProperty] = value; } } } /*[ConfigurationElementType(typeof(ProviderHookingElementConfigurationElement))] internal sealed class ProviderHookingElementConfigurationElement : BaseElementConfigurationElement { private const string _providerNameProperty = "providerName"; [ConfigurationProperty(_providerNameProperty, IsRequired = true)] public string ProviderName { get { return (string)base[_providerNameProperty]; } set { base[_providerNameProperty] = value; } } }*/ } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/VirtualElementProvider/ProviderHookingElementNode.cs ================================================ using System.Collections.Generic; namespace Composite.Plugins.Elements.ElementProviders.VirtualElementProvider { internal sealed class ProviderHookingElementNode : BaseElementNode { public ProviderHookingElementNode() { this.ProviderNames = new List<string>(); } public List<string> ProviderNames { get; set; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/VirtualElementProvider/SimpleVirtualElement.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Elements.ElementProviders.VirtualElementProvider { [ConfigurationElementType(typeof(SimpleVirtualElement))] internal class SimpleVirtualElement : VirtualElementConfigurationElement { private const string _labelProperty = "label"; [ConfigurationProperty(_labelProperty, IsRequired = true)] public string Label { get { return (string)base[_labelProperty]; } set { base[_labelProperty] = value; } } /// <summary> /// Used by the client js to filter perspective related elements /// </summary> private const string _tagProperty = "tag"; [ConfigurationProperty(_tagProperty, DefaultValue = null)] public string Tag { get { return (string)base[_tagProperty]; } set { base[_tagProperty] = value; } } private const string _closeFolderIconNameProperty = "closeFolderIconName"; [ConfigurationProperty(_closeFolderIconNameProperty, DefaultValue = null)] public string CloseFolderIconName { get { return (string)base[_closeFolderIconNameProperty]; } set { base[_closeFolderIconNameProperty] = value; } } private const string _openFolderIconNameProperty = "openFolderIconName"; [ConfigurationProperty(_openFolderIconNameProperty)] public string OpenFolderIconName { get { return (string)base[_openFolderIconNameProperty]; } set { base[_openFolderIconNameProperty] = value; } } private const string _elementsProperty = "Elements"; [ConfigurationProperty(_elementsProperty, IsRequired = true)] public NameTypeConfigurationElementCollection<VirtualElementConfigurationElement, VirtualElementConfigurationElement> Elements { get { return (NameTypeConfigurationElementCollection<VirtualElementConfigurationElement, VirtualElementConfigurationElement>)base[_elementsProperty]; } } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/VirtualElementProvider/VirtualElementConfigurationElement.cs ================================================ using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Elements.ElementProviders.VirtualElementProvider { internal class VirtualElementConfigurationElement : NameTypeConfigurationElement { } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/VirtualElementProvider/VirtualElementProvider.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web.Hosting; using Composite.C1Console.Actions; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Foundation; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.Search; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; using UserTexts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_C1Console_Users; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Management; namespace Composite.Plugins.Elements.ElementProviders.VirtualElementProvider { [ConfigurationElementType(typeof(VirtualElementProviderData))] #pragma warning disable 612 // There is no easy/fast way to make this hookless /MRJ internal sealed class VirtualElementProvider : IElementProvider, IDataExchangingElementProvider, ILocaleAwareElementProvider #pragma warning restore 612 { private static readonly string RootElementId = "ID01"; private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); private ElementProviderContext _context; private List<EntityTokenHook> _currentEntityTokenHooks; public static ResourceHandle ChangeOwnPasswordIcon => GetIconHandle("users-changeownpassword"); public static ResourceHandle ChangeOwnCultureIcon => GetIconHandle("users-changeownculture"); public static ResourceHandle SendMessageIcon => GetIconHandle("balloon"); public static ResourceHandle RebuildSearchIndexIcon => GetIconHandle("refresh"); public static ResourceHandle RestartApplicationIcon => GetIconHandle("restart-application"); public static ResourceHandle ManageSecurityIcon => GetIconHandle("security-manage-permissions"); public static ResourceHandle ChangeOwnActiveAndForeignLocaleIcon => GetIconHandle("localization-changelocale"); private static readonly string LogTitle = typeof (VirtualElementProvider).Name; private static readonly HashSet<string> _notLoadedVirtualElements = new HashSet<string>(); private readonly VirtualElementProviderData _configuration; public VirtualElementProvider(VirtualElementProviderData configuration) { _configuration = configuration; HookingFacade.SubscribeToNewElementProviderRootEntitiesEvent(OnNewElementProviderRootEntitiesEvent); } public ElementProviderContext Context { set { _context = value; } } public bool ContainsLocalizedData { get { return GetAttachedElementProviderNames(_configuration.Perspectives) .Any(providerName => ElementFacade.ContainsLocalizedData(new ElementProviderHandle(providerName))); } } public IEnumerable<Element> GetRoots(SearchToken seachToken) { EntityToken entityToken = new VirtualElementProviderEntityToken(_context.ProviderName, RootElementId); var root = new Element(_context.CreateElementHandle(entityToken)) { VisualData = new ElementVisualizedData { Label = "${Composite.Management, VirtualElementProviderElementProvider.ID01}", Icon = CommonElementIcons.Folder, OpenedIcon = CommonElementIcons.FolderOpen, ToolTip = "" }, TagValue = "Root" }; root.ElementExternalActionAdding = root.ElementExternalActionAdding.Remove(ElementExternalActionAdding.AllowGlobal); AddRootActions(root); return new [] { root }; } public IEnumerable<Element> GetForeignRoots(SearchToken seachToken) { // Expected that root note is a foldernode return GetRoots(seachToken); } private void AddRootActions(Element element) { // "User" actions element.AddAction(new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.C1Console.Users.Workflows.ChangeOwnForeignLocaleWorkflow"), new PermissionType[] { } ))) { VisualData = new ActionVisualizedData { Label = UserTexts.ChangeForeignLocaleWorkflow_ActionLabel, ToolTip = UserTexts.ChangeForeignLocaleWorkflow_ActionToolTip, Icon = VirtualElementProvider.ChangeOwnActiveAndForeignLocaleIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } }, TagValue = "User" }); element.AddAction(new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.C1Console.Users.Workflows.ChangeOwnCultureWorkflow"), new PermissionType[] { } ))) { VisualData = new ActionVisualizedData { Label = UserTexts.ChangeOwnCultureWorkflow_ElementActionLabel, ToolTip = UserTexts.ChangeOwnCultureWorkflow_ElementActionToolTip, Icon = VirtualElementProvider.ChangeOwnCultureIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } }, TagValue = "User" }); if (UserValidationFacade.CanSetUserPassword) { element.AddAction(new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.C1Console.Users.Workflows.ChangeOwnPasswordWorkflow"), new PermissionType[] { } ) { DoIgnoreEntityTokenLocking = true })) { VisualData = new ActionVisualizedData { Label = UserTexts.ChangeOwnPasswordWorkflow_ElementActionLabel, ToolTip = UserTexts.ChangeOwnPasswordWorkflow_ElementActionToolTip, Icon = VirtualElementProvider.ChangeOwnPasswordIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } }, TagValue = "User" }); } // Other actions string manageGlobalUserPermissionsLabel = StringResourceSystemFacade.GetString("Composite.Management", "ManageUserPermissions.ManageGlobalUserPermissionsLabel"); string manageUserPermissionsToolTip = StringResourceSystemFacade.GetString("Composite.Management", "ManageUserPermissions.ManageUserPermissionsToolTip"); element.AddAction(new ElementAction(new ActionHandle(new ManageUserPermissionsActionToken())) { VisualData = new ActionVisualizedData { Label = manageGlobalUserPermissionsLabel, ToolTip = manageUserPermissionsToolTip, Icon = ManageSecurityIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = false, ActionGroup = PrimaryActionGroup, ActionBundle = StringResourceSystemFacade.GetString("Composite.Management", "VirtualElementProviderElementProvider.RootActions.GlobalSetting") } } }); element.AddAction( new ElementAction( new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.C1Console.Tools.SetTimeZoneWorkflow")))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Management", "VirtualElementProviderElementProvider.RootActions.SetTimezoneLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "VirtualElementProviderElementProvider.RootActions.SetTimezoneTooltip"), Icon = VirtualElementProvider.ChangeOwnCultureIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = false, ActionGroup = PrimaryActionGroup, ActionBundle = StringResourceSystemFacade.GetString("Composite.Management", "VirtualElementProviderElementProvider.RootActions.GlobalSetting") } } }); element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Tools.SendMessageToConsolesWorkflow")))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Management", "VirtualElementProviderElementProvider.RootActions.SendMessageLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Management", "VirtualElementProviderElementProvider.RootActions.SendMessageTooltip"), Icon = VirtualElementProvider.SendMessageIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = false, ActionGroup = PrimaryActionGroup } } }); if (ServiceLocator.HasService(typeof (ISearchIndexUpdater))) { element.AddAction(new ElementAction(new RebuildSearchIndexActionToken()) { VisualData = new ActionVisualizedData { Label = Texts.VirtualElementProviderElementProvider_RootActions_RebuildSearchIndexLabel, ToolTip = Texts.VirtualElementProviderElementProvider_RootActions_RebuildSearchIndexTooltip, Icon = RebuildSearchIndexIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = false, ActionGroup = PrimaryActionGroup } } }); } element.AddAction(new ElementAction(new RestartApplicationActionToken()) { VisualData = new ActionVisualizedData { Label = Texts.VirtualElementProviderElementProvider_RootActions_RestartApplicationLabel, ToolTip = Texts.VirtualElementProviderElementProvider_RootActions_RestartApplicationTooltip, Icon = RestartApplicationIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = false, ActionGroup = PrimaryActionGroup } } }); } public IEnumerable<Element> GetChildren(EntityToken entityToken, SearchToken seachToken) { return GetChildren(entityToken, seachToken, false); } public IEnumerable<Element> GetForeignChildren(EntityToken entityToken, SearchToken seachToken) { return GetChildren(entityToken, seachToken, true); } private IEnumerable<Element> GetChildren(EntityToken entityToken, SearchToken seachToken, bool useForeign) { IEnumerable<VirtualElementConfigurationElement> elementNodes; if(entityToken.Id == RootElementId) { elementNodes = _configuration.Perspectives; } else { SimpleVirtualElement node = FindElementNode(entityToken.Id, _configuration.Perspectives); Verify.IsNotNull(node, "No corresponding node was found with the id '{0}'", entityToken.Id); elementNodes = node.Elements; } var result = new List<Element>(); foreach (var elementNode in elementNodes) { if (elementNode is SimpleVirtualElement) { Element createdElement; if(TryBuildElement(elementNode as SimpleVirtualElement, out createdElement)) { result.Add(createdElement); } continue; } if (elementNode is AttachProviderVirtualElement) { string providerName = (elementNode as AttachProviderVirtualElement).ProviderName; var providerHandle = new ElementProviderHandle(providerName); List<Element> elementsFromProvider; if (useForeign && ElementFacade.IsLocaleAwareElementProvider(providerHandle)) { elementsFromProvider = ElementFacade.GetForeignRoots(providerHandle, seachToken).ToList(); } else { elementsFromProvider = ElementFacade.GetRoots(providerHandle, seachToken).ToList(); } foreach (Element element in elementsFromProvider) { element.ElementExternalActionAdding = element.ElementExternalActionAdding.Remove(ElementExternalActionAdding.AllowGlobal); } result.AddRange(elementsFromProvider); continue; } throw new NotSupportedException(); } return result; } private bool TryBuildElement(SimpleVirtualElement simpleVirtualElement, out Element result) { try { result = CreateElement(simpleVirtualElement); } catch (ConfigurationErrorsException exception) { string elementName = simpleVirtualElement.Name ?? ""; lock (_notLoadedVirtualElements) { if (!_notLoadedVirtualElements.Contains(elementName)) { Log.LogError(LogTitle, "Failed to initialize virtual element/perspective. Label: '{0}', name: '{1}'\n" + "Remove the related configuration element from /App_Data/Composite/Composite.Config if it refers to a package that is no longer installed.", simpleVirtualElement.Label ?? "", elementName); Log.LogError(LogTitle, exception); _notLoadedVirtualElements.Add(elementName); } } result = null; } return result != null; } public List<EntityTokenHook> GetHooks() { return this.CurrentEntityTokenHooks; } public object GetData(string elementId) { string parentNodeId = GetParentNodeId(elementId, RootElementId, _configuration.Perspectives); if (parentNodeId == null) { return null; } return new VirtualElementProviderEntityToken(_context.ProviderName, parentNodeId); } private List<EntityTokenHook> CurrentEntityTokenHooks { get { if (_currentEntityTokenHooks == null) { var result = new List<EntityTokenHook>(); CreateHooks(result); _currentEntityTokenHooks = result; } return _currentEntityTokenHooks; } } private IEnumerable<string> GetAttachedElementProviderNames(IEnumerable<VirtualElementConfigurationElement> elements) { foreach (var virtualElement in elements) { if(virtualElement is AttachProviderVirtualElement) { yield return (virtualElement as AttachProviderVirtualElement).ProviderName; continue; } if (virtualElement is SimpleVirtualElement) { foreach (var providerName in GetAttachedElementProviderNames((virtualElement as SimpleVirtualElement).Elements)) { yield return providerName; } continue; } throw new NotSupportedException("Not supported VirtualElementConfigurationElement type"); } } private SimpleVirtualElement FindElementNode(string name, IEnumerable<VirtualElementConfigurationElement> elements) { foreach (var element in elements.OfType<SimpleVirtualElement>()) { if (element.Name == name) return element; SimpleVirtualElement foundNode = FindElementNode(name, element.Elements); if (foundNode != null) return foundNode; } return null; } private string GetParentNodeId(string name, string currentId, IEnumerable<VirtualElementConfigurationElement> elements) { foreach (var element in elements.OfType<SimpleVirtualElement>()) { if (element.Name == name) return currentId; string foundNode = GetParentNodeId(name, element.Name, element.Elements); if (foundNode != null) return foundNode; } return null; } private void CreateHooks(List<EntityTokenHook> foundHooks) { CreateHooks(RootElementId, _configuration.Perspectives, foundHooks); } private void CreateHooks(string parentId, IEnumerable<VirtualElementConfigurationElement> elements, List<EntityTokenHook> foundHooks) { var entityToken = new VirtualElementProviderEntityToken(_context.ProviderName, parentId); var entityTokenHook = new EntityTokenHook(entityToken); foreach (var attachProviderElement in elements.OfType<AttachProviderVirtualElement>()) { lock (_notLoadedVirtualElements) { if(_notLoadedVirtualElements.Contains(attachProviderElement.Name)) continue; } string providerName = attachProviderElement.ProviderName; var childElements = ElementFacade.GetRootsWithNoSecurity(new ElementProviderHandle(providerName), null).ToList(); foreach (Element childElement in childElements) { entityTokenHook.AddHookie(childElement.ElementHandle.EntityToken); } } foundHooks.Add(entityTokenHook); foreach (var simpleElement in elements.OfType<SimpleVirtualElement>()) { CreateHooks(simpleElement.Name, simpleElement.Elements, foundHooks); } } private Element CreateElement(SimpleVirtualElement simpleElementNode) { EntityToken entityToken = new VirtualElementProviderEntityToken(_context.ProviderName, simpleElementNode.Name); Element element = new Element(_context.CreateElementHandle(entityToken)) { TagValue = simpleElementNode.Tag, VisualData = new ElementVisualizedData { Label = StringResourceSystemFacade.ParseString(simpleElementNode.Label), HasChildren = true // fixing refresh problem easy way... was: HasChildren(baseElementNode) } }; Action<IEnumerable> collectProviders = null; // Recursively searching for attached providers var attachedProviders = new List<AttachProviderVirtualElement>(); collectProviders = currentElements => { attachedProviders.AddRange(currentElements.OfType<AttachProviderVirtualElement>()); currentElements.OfType<SimpleVirtualElement>().ForEach(e => collectProviders(e.Elements)); }; collectProviders(simpleElementNode.Elements); element.IsLocaleAware = attachedProviders.Any(provider => ElementFacade.ContainsLocalizedData(new ElementProviderHandle(provider.ProviderName))); if (element.VisualData.HasChildren) { ResourceHandle openHandle = IconResourceSystemFacade.GetResourceHandle(simpleElementNode.OpenFolderIconName); ResourceHandle closeHandle = IconResourceSystemFacade.GetResourceHandle(simpleElementNode.CloseFolderIconName); closeHandle = closeHandle ?? openHandle; openHandle = openHandle ?? closeHandle; if (openHandle == null) { openHandle = CommonElementIcons.Folder; closeHandle = CommonElementIcons.FolderOpen; } element.VisualData.Icon = openHandle; element.VisualData.OpenedIcon = closeHandle; } else { element.VisualData.Icon = CommonElementIcons.FolderDisabled; } var placeholderElementNode = simpleElementNode as PlaceholderVirtualElement; if (placeholderElementNode != null) { element.PropertyBag["Path"] = placeholderElementNode.Path; element.PropertyBag["IsTool"] = placeholderElementNode.IsTool; } return element; } private bool HasChildren(BaseElementNode baseElementNode) { if (baseElementNode is FolderElementNode) { return baseElementNode.Children.Count != 0; } if (baseElementNode is ProviderHookingElementNode) { return true; // Non-lazy check children //ProviderHookingElementNode proivderNode = (ProviderHookingElementNode)baseElementNode; //List<Element> children = ElementFacade.GetRoots(proivderNode.ProviderName); //return children.Count != 0; } throw new NotSupportedException(string.Format("The element node type '{0}' is not supported", baseElementNode.GetType())); } private void OnNewElementProviderRootEntitiesEvent(HookingFacadeEventArgs hookingFacadeEventArgs) { if (_currentEntityTokenHooks != null) { HookingFacade.RemoveHooks(this.CurrentEntityTokenHooks); } var newHooks = new List<EntityTokenHook>(); CreateHooks(newHooks); _currentEntityTokenHooks = newHooks; HookingFacade.AddHooks(this.CurrentEntityTokenHooks); } private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } } #pragma warning disable 612 internal sealed class VirtualElementProviderAssembler : IAssembler<IElementProvider, ElementProviderData> { public IElementProvider Assemble(IBuilderContext context, ElementProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) #pragma warning restore 612 { var configuration = (VirtualElementProviderData)objectConfiguration; return new VirtualElementProvider(configuration); } } [Assembler(typeof(VirtualElementProviderAssembler))] #pragma warning disable 612 internal sealed class VirtualElementProviderData : ElementProviderData #pragma warning restore 612 { private const string _perspectivesProperty = "Perspectives"; [ConfigurationProperty(_perspectivesProperty, IsRequired = true)] public NameTypeConfigurationElementCollection<VirtualElementConfigurationElement, VirtualElementConfigurationElement> Perspectives { get { return (NameTypeConfigurationElementCollection<VirtualElementConfigurationElement, VirtualElementConfigurationElement>)base[_perspectivesProperty]; } } } [ActionExecutor(typeof(RebuildSearchIndexActionExecutor))] internal sealed class RebuildSearchIndexActionToken : ActionToken { private static readonly IEnumerable<PermissionType> _permissionType = new [] { PermissionType.Administrate }; public override IEnumerable<PermissionType> PermissionTypes => _permissionType; public override string Serialize() => nameof(RebuildSearchIndexActionToken); public static ActionToken Deserialize(string serializedData) => new RebuildSearchIndexActionToken(); } [ActionExecutor(typeof(RestartApplicationActionExecutor))] internal sealed class RestartApplicationActionToken : ActionToken { private static readonly IEnumerable<PermissionType> _permissionType = new [] { PermissionType.Administrate }; public override IEnumerable<PermissionType> PermissionTypes => _permissionType; public override string Serialize() => nameof(RestartApplicationActionToken); public static ActionToken Deserialize(string serializedData) => new RestartApplicationActionToken(); } internal sealed class RebuildSearchIndexActionExecutor : IActionExecutor { public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { var service = ServiceLocator.GetService<ISearchIndexUpdater>(); service?.Rebuild(); return null; } } internal sealed class RestartApplicationActionExecutor : IActionExecutor { public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { HostingEnvironment.InitiateShutdown(); return null; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/VirtualElementProvider/VirtualElementProviderEntityToken.cs ================================================ using System; using Composite.C1Console.Security; using Composite.Core; using Composite.Core.Serialization; using Composite.Core.Types; using Newtonsoft.Json; namespace Composite.Plugins.Elements.ElementProviders.VirtualElementProvider { /// <summary> /// EntityTokon of elements created by <see cref="VirtualElementProvider"/> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(VirtualElementProviderSecurityAncestorProvider))] public sealed class VirtualElementProviderEntityToken : EntityToken { private string _type; /// <exclude /> public VirtualElementProviderEntityToken() { } /// <exclude /> [JsonConstructor] public VirtualElementProviderEntityToken(string source, string id) { Source = source; Id = id; } /// <exclude /> [JsonIgnore] public override string Type { get { if (_type == null) { _type= TypeManager.SerializeType(this.GetType()); } return _type; } } /// <exclude /> public override string Source { get; } /// <exclude /> public override string Id { get; } /// <exclude /> public override string Serialize() { return CompositeJsonSerializer.Serialize(this); } /// <exclude /> public static EntityToken Deserialize(string serializedEntityToken) { EntityToken entityToken; if (CompositeJsonSerializer.IsJsonSerialized(serializedEntityToken)) { entityToken = CompositeJsonSerializer.Deserialize<VirtualElementProviderEntityToken>(serializedEntityToken); } else { entityToken = DeserializeLegacy(serializedEntityToken); Log.LogVerbose(nameof(VirtualElementProviderEntityToken), entityToken.GetType().FullName); } return entityToken; } /// <exclude /> public static EntityToken DeserializeLegacy(string serializedEntityToken) { string type, source, id; EntityToken.DoDeserialize(serializedEntityToken, out type, out source, out id); return new VirtualElementProviderEntityToken(source, id); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/VirtualElementProvider/VirtualElementProviderSecurityAncestorProvider.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Security; using Composite.C1Console.Elements; namespace Composite.Plugins.Elements.ElementProviders.VirtualElementProvider { internal sealed class VirtualElementProviderSecurityAncestorProvider : ISecurityAncestorProvider { public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { VirtualElementProviderEntityToken virtualEntityToken = (VirtualElementProviderEntityToken)entityToken; List<EntityToken> parentEntityTokens = new List<EntityToken>(); VirtualElementProviderEntityToken parentToken = (VirtualElementProviderEntityToken)ElementFacade.GetData(new ElementProviderHandle(virtualEntityToken.Source), virtualEntityToken.Id); if (parentToken != null) { parentEntityTokens.Add(parentToken); } return parentEntityTokens; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/VisualFunctionProviderElementProvider/DeleteVisualFunctionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="DeleteWysiwygRenderingWorkflow" Location="30; 30" Size="1149; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity19" SourceStateName="DeleteWysiwygRenderingWorkflow" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="DeleteWysiwygRenderingWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="769" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="461" Y="412" /> <ns0:Point X="1058" Y="412" /> <ns0:Point X="1058" Y="769" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="457" Y="388" /> <ns0:Point X="646" Y="388" /> <ns0:Point X="646" Y="527" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="initializeActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="257" Y="142" /> <ns0:Point X="359" Y="142" /> <ns0:Point X="359" Y="323" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="745" Y="568" /> <ns0:Point X="1058" Y="568" /> <ns0:Point X="1058" Y="769" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="finishState" Location="978; 769" Size="160; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="initializeActivity" Location="51; 101" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="initializeStateInitializationActivity" Location="59; 132"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="69; 194" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <EventDrivenDesigner Size="150; 194" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 53" Name="setStateActivity19" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="step1StateActivity" Location="254; 323" Size="211; 102" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="529; 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="confirmDialogFormActivity1" Location="539; 210" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Finish" Location="521; 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="531; 221" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="531; 281" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="521; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="531; 245" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="531; 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="544; 527" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="finalizeStateInitializationActivity" Location="552; 558"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity" Location="562; 620" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="562; 680" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="562; 740" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite/Plugins/Elements/ElementProviders/VisualFunctionProviderElementProvider/EditVisualFunctionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="EditVisualFunctionWorkflow" Location="30; 30" Size="876; 539" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="EditVisualFunctionWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="EditVisualFunctionWorkflow" EventHandlerName="cancelEventDrivenActivity"> <StateDesignerConnector.Segments> <ns0:Point X="202" Y="71" /> <ns0:Point X="761" Y="71" /> <ns0:Point X="761" Y="118" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initialState" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="initialState" EventHandlerName="initialStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="146" /> <ns0:Point X="268" Y="146" /> <ns0:Point X="268" Y="276" /> <ns0:Point X="236" Y="276" /> <ns0:Point X="236" Y="288" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="saveStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="editStateActivity" SourceConnectionEdge="Right" TargetActivity="saveStateActivity" SourceActivity="editStateActivity" EventHandlerName="eventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="312" Y="353" /> <ns0:Point X="343" Y="353" /> <ns0:Point X="343" Y="315" /> <ns0:Point X="560" Y="315" /> <ns0:Point X="560" Y="323" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Bottom" SetStateName="noSaveSetStateActivity" SourceStateName="editStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="editStateActivity" EventHandlerName="eventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="312" Y="353" /> <ns0:Point X="340" Y="353" /> <ns0:Point X="340" Y="414" /> <ns0:Point X="236" Y="414" /> <ns0:Point X="236" Y="406" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Bottom" SetStateName="setStateActivity5" SourceStateName="editStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="editStateActivity" EventHandlerName="eventDrivenActivity_Preview"> <StateDesignerConnector.Segments> <ns0:Point X="327" Y="377" /> <ns0:Point X="340" Y="377" /> <ns0:Point X="340" Y="414" /> <ns0:Point X="236" Y="414" /> <ns0:Point X="236" Y="406" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Bottom" SetStateName="setStateActivity4" SourceStateName="saveStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="saveStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="659" Y="364" /> <ns0:Point X="668" Y="364" /> <ns0:Point X="668" Y="414" /> <ns0:Point X="236" Y="414" /> <ns0:Point X="236" Y="406" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initialState" Location="63; 105" Size="197; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initialStateInitializationActivity" Location="71; 136"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity" Location="81; 198" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="81; 258" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="editStateActivity" Location="142; 288" Size="189; 118" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="editStateInitializationActivity" Location="150; 319"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="documentFormActivity1" Location="160; 381" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="381; 435" Name="eventDrivenActivity_Save" Location="150; 343"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="saveHandleExternalEventActivity1" Location="275; 405" /> <IfElseDesigner Size="361; 294" Name="ifElseActivity1" Location="160; 465"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 194" Name="ifElseBranchActivity1" Location="179; 536"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="189; 634" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 194" Name="ifElseBranchActivity2" Location="352; 536"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="showFieldMessageActivity1" Location="362; 598" /> <SetStateDesigner Size="130; 53" Name="noSaveSetStateActivity" Location="362; 658" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 242" Name="eventDrivenActivity_Preview" Location="150; 367"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="previewHandleExternalEventActivity1" Location="160; 429" /> <CodeDesigner Size="130; 41" Name="editPreviewCodeActivity" Location="160; 489" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="160; 549" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="saveStateActivity" Location="458; 323" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="finalizeStateInitializationActivity" Location="466; 354"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="saveCodeActivity" Location="476; 416" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="476; 476" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="681; 118" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="cancelEventDrivenActivity" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite/Plugins/Elements/ElementProviders/VisualFunctionProviderElementProvider/VisualFunctionProviderElementProvider.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.C1Console.Security; using Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider; using Composite.C1Console.Workflow; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Elements.ElementProviders.VisualFunctionProviderElementProvider { [ConfigurationElementType(typeof(VisualFunctionProviderElementProviderData))] internal sealed class VisualFunctionProviderElementProvider : BaseFunctionProviderElementProvider.BaseFunctionProviderElementProvider { public static ResourceHandle AddFunction { get { return GetIconHandle("visual-function-add"); } } public static ResourceHandle EditFunction { get { return GetIconHandle("visual-function-edit"); } } public static ResourceHandle DeleteFunction { get { return GetIconHandle("visual-function-delete"); } } private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); public VisualFunctionProviderElementProvider() { } protected override string RootFolderLabel { get { return StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "VisualFunctionElementProvider.RootFolderLabel"); } } protected override string RootFolderToolTip { get { return StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "VisualFunctionElementProvider.RootFolderToolTip"); } } protected override IEnumerable<IFunctionTreeBuilderLeafInfo> OnGetFunctionInfos(SearchToken searchToken) { if (searchToken.IsValidKeyword() == false) { return from function in DataFacade.GetData<IVisualFunction>() select (IFunctionTreeBuilderLeafInfo)new VisualFunctionTreeBuilderLeafInfo(function); } else { string keyword = searchToken.Keyword.ToLowerInvariant(); return from function in DataFacade.GetData<IVisualFunction>() where function.Name.ToLowerInvariant().Contains(keyword) || function.Namespace.ToLowerInvariant().Contains(keyword) || function.TypeManagerName.ToLowerInvariant().Contains(keyword) select (IFunctionTreeBuilderLeafInfo)new VisualFunctionTreeBuilderLeafInfo(function); } } protected override IEnumerable<Type> OnGetEntityTokenTypes() { yield return typeof(DataEntityToken); } protected override IFunctionTreeBuilderLeafInfo OnIsEntityOwner(EntityToken entityToken) { DataEntityToken dataEntityToken = entityToken as DataEntityToken; if (dataEntityToken == null) return null; if (dataEntityToken.InterfaceType != typeof(IVisualFunction)) return null; return new VisualFunctionTreeBuilderLeafInfo(dataEntityToken.Data as IVisualFunction); } protected override IEnumerable<ElementAction> OnGetFolderActions() { return new ElementAction[] { new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.VisualFunctionProviderElementProvider.AddNewVisualFunctionWorkflow"), new PermissionType[] { PermissionType.Add } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "VisualFunctionElementProvider.AddNewLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "VisualFunctionElementProvider.AddNewToolTip"), Icon = VisualFunctionProviderElementProvider.AddFunction, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } } }; } protected override IEnumerable<ElementAction> OnGetFunctionActions(IFunctionTreeBuilderLeafInfo function) { return new ElementAction[] { new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.VisualFunctionProviderElementProvider.EditVisualFunctionWorkflow"), new PermissionType[] { PermissionType.Edit } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "VisualFunctionElementProvider.EditLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "VisualFunctionElementProvider.EditToolTip"), Icon = VisualFunctionProviderElementProvider.EditFunction, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }, new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.VisualFunctionProviderElementProvider.DeleteVisualFunctionWorkflow"), new PermissionType[] { PermissionType.Delete } ) { Payload = GetContext().ProviderName })) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "VisualFunctionElementProvider.DeleteLabel"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "VisualFunctionElementProvider.DeleteToolTip"), Icon = VisualFunctionProviderElementProvider.DeleteFunction, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } } }; } private sealed class VisualFunctionTreeBuilderLeafInfo : IFunctionTreeBuilderLeafInfo { private IVisualFunction _function; public VisualFunctionTreeBuilderLeafInfo(IVisualFunction function) { _function = function; } public string Name { get { return _function.Name; } } public string Namespace { get { return _function.Namespace; } } public EntityToken EntityToken { get { return _function.GetDataEntityToken(); } } } } [Assembler(typeof(VisualFunctionProviderElementProviderAssembler))] internal sealed class VisualFunctionProviderElementProviderData : HooklessElementProviderData { } internal sealed class VisualFunctionProviderElementProviderAssembler : IAssembler<IHooklessElementProvider, HooklessElementProviderData> { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IHooklessElementProvider Assemble(IBuilderContext context, HooklessElementProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new VisualFunctionProviderElementProvider(); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/WebsiteEntity.cs ================================================ namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class WebsiteEntity { /// <exclude /> public WebsiteEntity(string fullPath, bool isFolder) { this.FullPath = fullPath; this.IsFile = isFolder == false; this.IsFolder = isFolder; } /// <exclude /> public bool IsFile { get; private set; } /// <exclude /> public bool IsFolder { get; private set; } /// <exclude /> public string FullPath { get; private set; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/WebsiteFile.cs ================================================ using System.IO; using System.Text; using Composite.Core.IO; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class WebsiteFile : WebsiteEntity { private string _filename = null; private string _mimeTypeInfo = null; private bool? isReadOnly = null; /// <exclude /> public WebsiteFile(string fullPath) : base(fullPath, false) { } /// <exclude /> public string FileName { get { if (_filename == null) { _filename = Path.GetFileName(this.FullPath); } return _filename; } } /// <exclude /> public string MimeType { get { if (_mimeTypeInfo == null) { _mimeTypeInfo = MimeTypeInfo.GetCanonicalFromExtension(Path.GetExtension(this.FullPath)); } return _mimeTypeInfo; } } /// <exclude /> public string ReadAllText() { return C1File.ReadAllText(this.FullPath); } /// <exclude /> public bool IsReadOnly { get { if (isReadOnly.HasValue == false) { isReadOnly = (C1File.GetAttributes(this.FullPath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly; } return isReadOnly.Value; } } /// <exclude /> public void WriteAllText(string content) { // Default encode is Composite.Core.IO.StreamWriter.UTF8NoBOM, which is UTF8 without encoding signature C1File.WriteAllText(this.FullPath, content, Encoding.UTF8); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/WebsiteFileElementProvider.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.IO; using System.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Core; using Composite.Core.IO; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.Core.WebClient; using Composite.Data; using Composite.Data.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { [ConfigurationElementType(typeof(WebsiteFileElementProviderData))] internal sealed class WebsiteFileElementProvider : IHooklessElementProvider, IDataExchangingElementProvider { private ElementProviderContext _context; private readonly string _rootPath; private readonly string _rootLabel; private readonly string _folderWhiteListKeyName; private readonly List<string> _manageableKeyNames; private readonly List<string> _manageableKeyNameLabels; private static ResourceHandle FolderIcon => CommonElementIcons.Folder; private static ResourceHandle OpenFolderIcon => CommonElementIcons.FolderOpen; private static ResourceHandle EmptyFolderIcon => CommonElementIcons.FolderOpen; private static ResourceHandle ReadOnlyFolderOpen => GetIconHandle("website-read-only-folder-open"); private static ResourceHandle ReadOnlyFolderClosed => GetIconHandle("website-read-only-folder-closed"); private static ResourceHandle AddWebsiteFolder => GetIconHandle("website-add-website-folder"); private static ResourceHandle AddWebsiteFile => GetIconHandle("website-create-website-file"); private static ResourceHandle DeleteWebsiteFolder => GetIconHandle("website-delete-website-folder"); private static ResourceHandle DeleteWebsiteFile => GetIconHandle("website-delete-website-file"); private static ResourceHandle EditWebsiteFile => GetIconHandle("website-edit-website-file"); private static ResourceHandle UploadWebsiteFile => GetIconHandle("website-upload-website-file"); private static ResourceHandle UploadAndExtractZipFile => GetIconHandle("website-upload-zip-file"); private static ResourceHandle DownloadWebsiteFile => GetIconHandle("media-download-file"); private static ResourceHandle AddFolderToWhiteList => GetIconHandle("website-add-folder-to-whitelist"); private static ResourceHandle RemoveFolderFromWhiteList => GetIconHandle("website-remove-folder-from-whitelist"); private static readonly ActionGroup PrimaryFolderActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); private static readonly ActionGroup PrimaryFileActionGroup = new ActionGroup("File", ActionGroupPriority.PrimaryMedium); // private static readonly ActionGroup PrimaryFileToolsActionGroup = new ActionGroup("FileTools", ActionGroupPriority.PrimaryMedium); private static readonly ActionGroup PrimaryFolderToolsActionGroup = new ActionGroup("FolderTools", ActionGroupPriority.PrimaryMedium); private static readonly PermissionType[] _addNewWebsiteFolderPermissionTypes = { PermissionType.Add }; private static readonly PermissionType[] _addNewWebsiteFilePermissionTypes = { PermissionType.Add }; private static readonly PermissionType[] _uploadAndExtractZipFileWorkflow = { PermissionType.Add }; private static readonly PermissionType[] _deleteWebsiteFolderPermissionTypes = { PermissionType.Delete }; private static readonly PermissionType[] _deleteWebsiteFilePermissionTypes = { PermissionType.Delete }; private static readonly PermissionType[] _editWebsiteFilePermissionTypes = { PermissionType.Edit }; private static readonly PermissionType[] _uploadWebsiteFilePermissionTypes = { PermissionType.Add }; private static readonly PermissionType[] _changeWhiteListPermissionTypes = { PermissionType.Administrate }; public WebsiteFileElementProvider(WebsiteFileElementProviderData objectConfiguration) { _rootLabel = objectConfiguration.RootLabel; _folderWhiteListKeyName = objectConfiguration.FolderWhiteListKeyName; if (!string.IsNullOrEmpty(objectConfiguration.ManageableKeyNames)) { _manageableKeyNames = objectConfiguration.ManageableKeyNames.Split(',').ToList(); _manageableKeyNameLabels = StringResourceSystemFacade.SplitParseableStrings(objectConfiguration.ManageableKeyNameLabels, ',').ToList(); } else { _manageableKeyNames = new List<string>(); } _rootPath = Path.GetDirectoryName(PathUtil.BaseDirectory); } public ElementProviderContext Context { set => _context = value; } public IEnumerable<Element> GetRoots(SearchToken seachToken) { Element element = new Element(_context.CreateElementHandle(new WebsiteFileElementProviderRootEntityToken(_context.ProviderName, _rootPath))) { VisualData = new ElementVisualizedData() { Label = StringResourceSystemFacade.ParseString(_rootLabel), ToolTip = StringResourceSystemFacade.ParseString(_rootLabel), HasChildren = true, Icon = FolderIcon, OpenedIcon = OpenFolderIcon } }; //element.MovabilityInfo.AddDropType(typeof(WebsiteFolder)); //element.MovabilityInfo.AddDropType(typeof(WebsiteFile)); //List<IFolderWhiteList> myWhiteLists = DataFacade.GetData<IFolderWhiteList>(f => f.KeyName == _folderWhiteListKeyName).ToList(); if (string.IsNullOrEmpty(_folderWhiteListKeyName) || DataFacade.GetData<IFolderWhiteList>(f => f.KeyName == _folderWhiteListKeyName && f.TildeBasedPath == "~\\").Any()) { element.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider.AddNewWebsiteFolderWorkflow"), _addNewWebsiteFolderPermissionTypes))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "AddWebsiteFolderTitle"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "AddWebsiteFolderToolTip"), Icon = WebsiteFileElementProvider.AddWebsiteFolder, Disabled = false, ActivePositions = ElementActionActivePosition.NavigatorTree | ElementActionActivePosition.SelectorTree, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFolderActionGroup } } }); element.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider.AddNewWebsiteFileWorkflow"), _addNewWebsiteFilePermissionTypes))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "AddWebsiteFileTitle"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "AddWebsiteFileToolTip"), Icon = WebsiteFileElementProvider.AddWebsiteFile, Disabled = false, ActivePositions = ElementActionActivePosition.NavigatorTree | ElementActionActivePosition.SelectorTree, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFolderActionGroup } } }); element.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider.UploadWebsiteFileWorkflow"), _uploadWebsiteFilePermissionTypes))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "UploadWebsiteFileTitle"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "UploadWebsiteFileToolTip"), Icon = WebsiteFileElementProvider.UploadWebsiteFile, Disabled = false, ActivePositions = ElementActionActivePosition.NavigatorTree | ElementActionActivePosition.SelectorTree, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFolderActionGroup, ActionBundle = "Upload" } } }); element.AddAction( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider.UploadAndExtractZipFileWorkflow"), _uploadAndExtractZipFileWorkflow))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "UploadAndExtractZipFileTitle"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "UploadAndExtractZipFileToolTip"), Icon = WebsiteFileElementProvider.UploadAndExtractZipFile, Disabled = false, ActivePositions = ElementActionActivePosition.NavigatorTree | ElementActionActivePosition.SelectorTree, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFolderActionGroup, ActionBundle = "Upload" } } }); var actionsToAppend = new List<ElementAction>(); IEnumerable<IFolderWhiteList> manageableFolderWhiteLists = DataFacade.GetData<IFolderWhiteList>().ToList(); AppendFolderManagementActions( PathUtil.BaseDirectory, manageableFolderWhiteLists, actionsToAppend); element.AddAction(actionsToAppend); } yield return element; } public IEnumerable<Element> GetChildren(EntityToken entityToken, SearchToken searchToken) { if (entityToken is WebsiteFileElementProviderRootEntityToken) { return GetChildrenOnPath(_rootPath, searchToken); } if (entityToken is WebsiteFileElementProviderEntityToken websiteFileEntityToken) { string path = websiteFileEntityToken.Path; if (C1Directory.Exists(path)) { return GetChildrenOnPath(path, searchToken); } return new Element[] { }; } throw new NotImplementedException(); } public object GetData(string name) { return name == "RootPath" ? _rootPath : null; } private IEnumerable<Element> GetChildrenOnPath(string parentPath, SearchToken searchToken) { IEnumerable<WebsiteFolder> websiteFolders = GetFoldersOnPath(parentPath, searchToken); IEnumerable<WebsiteFile> websiteFiles = GetFilesOnPath(parentPath, searchToken); IEnumerable<Element> folders = CreateFolderElements(websiteFolders); IEnumerable<Element> files = CreateFileElements(websiteFiles); return folders.Concat(files).ToList(); } private IEnumerable<Element> CreateFileElements(IEnumerable<WebsiteFile> websiteFiles) { foreach (WebsiteFile websiteFile in websiteFiles) { var element = new Element(_context.CreateElementHandle(new WebsiteFileElementProviderEntityToken(_context.ProviderName, websiteFile.FullPath, _rootPath))) { VisualData = new ElementVisualizedData { Label = websiteFile.FileName, ToolTip = websiteFile.FileName, HasChildren = false, Icon = WebsiteFileIcon(websiteFile.MimeType), OpenedIcon = WebsiteFileIcon(websiteFile.MimeType) } }; element.PropertyBag.Add("Uri", PathUtil.GetWebsitePath(websiteFile.FullPath)); element.PropertyBag.Add("ElementType", websiteFile.MimeType); //element.MovabilityInfo.DragType = typeof(WebsiteFile); foreach (ElementAction action in GetFileActions(websiteFile)) { element.AddAction(action); } yield return element; } } private IEnumerable<Element> CreateFolderElements(IEnumerable<WebsiteFolder> websiteFolders) { IEnumerable<IFolderWhiteList> manageableFolderWhiteLists = DataFacade.GetData<IFolderWhiteList>().ToList(); IEnumerable<IFolderWhiteList> myWhiteLists = null; if (!string.IsNullOrEmpty(_folderWhiteListKeyName)) { myWhiteLists = DataFacade.GetData<IFolderWhiteList>(f=>f.KeyName==_folderWhiteListKeyName).ToList(); } foreach (WebsiteFolder websiteFolder in websiteFolders) { var element = new Element(_context.CreateElementHandle(new WebsiteFileElementProviderEntityToken(_context.ProviderName, websiteFolder.FullPath, _rootPath))) { VisualData = new ElementVisualizedData { Label = websiteFolder.FolderName, ToolTip = websiteFolder.FolderName, HasChildren = true, Icon = FolderIcon, OpenedIcon = OpenFolderIcon }, }; if (myWhiteLists == null || myWhiteLists.Any(f => websiteFolder.FullPath.StartsWith(f.GetFullPath()))) { foreach (ElementAction action in GetFolderActions(websiteFolder, manageableFolderWhiteLists)) { element.AddAction(action); } } yield return element; } } private IEnumerable<WebsiteFolder> GetFoldersOnPath(string parentPath, SearchToken searchToken) { IEnumerable<WebsiteFolder> folders = from folderPath in C1Directory.GetDirectories(parentPath) orderby folderPath select new WebsiteFolder(folderPath); if (searchToken.IsValidKeyword()) { folders = from folder in folders where folder.FolderName.ToLowerInvariant().Contains(searchToken.Keyword.ToLowerInvariant()) select folder; } if (!string.IsNullOrEmpty(_folderWhiteListKeyName)) { List<IFolderWhiteList> whiteList = DataFacade.GetData<IFolderWhiteList>().Where(f => f.KeyName == _folderWhiteListKeyName).ToList(); folders = from folder in folders.ToList() where whiteList.Any(f => folder.FullPath.StartsWith(f.GetFullPath()) || f.GetFullPath().StartsWith(folder.FullPath)) select folder; } return folders; } private IEnumerable<WebsiteFile> GetFilesOnPath(string parentPath, SearchToken searchToken) { if (!string.IsNullOrEmpty(_folderWhiteListKeyName)) { string parentTildaPath = IFolderWhiteListExtensions.GetTildePath(parentPath); // NOTE: linq2sql conversion doesn't support xxx.StartsWith(someParameter) construction, that's why we're using two ling statements to get the data bool isWhitelisted = (from path in ((from item in DataFacade.GetData<IFolderWhiteList>() where item.KeyName == _folderWhiteListKeyName select item.TildeBasedPath) as IEnumerable<string>) where parentTildaPath.StartsWith(path) select path).Any(); if (!isWhitelisted) { yield break; } } IEnumerable<WebsiteFile> files = from filename in Directory.GetFiles(parentPath) orderby filename select new WebsiteFile(filename); if (searchToken.IsValidKeyword()) { files = from file in files where file.FileName.ToLowerInvariant().Contains(searchToken.Keyword.ToLowerInvariant()) select file; } foreach (var file in files) yield return file; } private IEnumerable<ElementAction> GetFolderActions(WebsiteFolder websiteFolder, IEnumerable<IFolderWhiteList> manageableFolderWhiteLists) { IList<ElementAction> folderActions = new List<ElementAction>(); folderActions.Add( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider.AddNewWebsiteFolderWorkflow"), _addNewWebsiteFolderPermissionTypes))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "AddWebsiteFolderTitle"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "AddWebsiteFolderToolTip"), Icon = WebsiteFileElementProvider.AddWebsiteFolder, Disabled = false, ActivePositions = ElementActionActivePosition.NavigatorTree | ElementActionActivePosition.SelectorTree, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFolderActionGroup } } }); folderActions.Add( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider.AddNewWebsiteFileWorkflow"), _addNewWebsiteFilePermissionTypes))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "AddWebsiteFileTitle"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "AddWebsiteFileToolTip"), Icon = WebsiteFileElementProvider.AddWebsiteFile, Disabled = false, ActivePositions = ElementActionActivePosition.NavigatorTree | ElementActionActivePosition.SelectorTree, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFolderActionGroup } } }); folderActions.Add( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider.UploadWebsiteFileWorkflow"), _uploadWebsiteFilePermissionTypes))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "UploadWebsiteFileTitle"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "UploadWebsiteFileToolTip"), Icon = WebsiteFileElementProvider.UploadWebsiteFile, Disabled = false, ActivePositions = ElementActionActivePosition.NavigatorTree | ElementActionActivePosition.SelectorTree, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFolderActionGroup, ActionBundle = "Upload" } } }); folderActions.Add( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider.UploadAndExtractZipFileWorkflow"), _uploadAndExtractZipFileWorkflow))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "UploadAndExtractZipFileTitle"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "UploadAndExtractZipFileToolTip"), Icon = WebsiteFileElementProvider.UploadAndExtractZipFile, Disabled = false, ActivePositions = ElementActionActivePosition.NavigatorTree | ElementActionActivePosition.SelectorTree, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFolderActionGroup, ActionBundle = "Upload" } } }); if (IsDeleteActionAllowed(websiteFolder)) { folderActions.Add( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider.DeleteWebsiteFolderWorkflow"), _deleteWebsiteFolderPermissionTypes))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "DeleteWebsiteFolderTitle"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "DeleteWebsiteFolderToolTip"), Icon = DeleteWebsiteFolder, Disabled = false, ActivePositions = ElementActionActivePosition.NavigatorTree | ElementActionActivePosition.SelectorTree, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFileActionGroup } } }); } AppendFolderManagementActions(websiteFolder.FullPath, manageableFolderWhiteLists, folderActions); return folderActions; } private void AppendFolderManagementActions(string websiteFolderPath, IEnumerable<IFolderWhiteList> manageableFolderWhiteLists, IList<ElementAction> folderActions) { for (int i = 0; i < _manageableKeyNames.Count; i++) { string keyName = _manageableKeyNames[i]; string itemLabel = StringResourceSystemFacade.ParseString(_manageableKeyNameLabels[i]); ResourceHandle icon; string label; string tooltip; WorkflowActionToken workflowActionToken; ActionCheckedStatus checkedStatus; var tildeBasedPath = IFolderWhiteListExtensions.GetTildePath(websiteFolderPath); if (manageableFolderWhiteLists.Any(f => f.KeyName == keyName && f.TildeBasedPath == tildeBasedPath)) { workflowActionToken = new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider.RemoveWebsiteFolderFromWhiteListWorkflow"), _changeWhiteListPermissionTypes); label = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "RemoveFolderFromWhiteListTitle"); tooltip = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "RemoveFolderFromWhiteListToolTip"); icon = WebsiteFileElementProvider.RemoveFolderFromWhiteList; checkedStatus = ActionCheckedStatus.Checked; } else { workflowActionToken = new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider.AddWebsiteFolderToWhiteListWorkflow"), _changeWhiteListPermissionTypes); label = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "AddFolderToWhiteListTitle"); tooltip = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "AddFolderToWhiteListToolTip"); icon = WebsiteFileElementProvider.AddFolderToWhiteList; checkedStatus = ActionCheckedStatus.Unchecked; } label = string.Format(label, itemLabel); tooltip = string.Format(tooltip, itemLabel); workflowActionToken.Payload = keyName; folderActions.Add( new ElementAction(new ActionHandle(workflowActionToken)) { VisualData = new ActionVisualizedData { Label = label, ToolTip = tooltip, Icon = icon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Other, IsInFolder = false, IsInToolbar = false, ActionGroup = PrimaryFolderToolsActionGroup }, ActionCheckedStatus = checkedStatus } }); } } private IEnumerable<ElementAction> GetFileActions(WebsiteFile websiteFile) { IList<ElementAction> fileActions = new List<ElementAction>(); if (IsDeleteActionAllowed(websiteFile)) { fileActions.Add( new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider.DeleteWebsiteFileWorkflow"), _deleteWebsiteFilePermissionTypes))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "DeleteWebsiteFileTitle"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "DeleteWebsiteFileToolTip"), Icon = DeleteWebsiteFile, Disabled = websiteFile.IsReadOnly, ActivePositions = ElementActionActivePosition.NavigatorTree | ElementActionActivePosition.SelectorTree, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFileActionGroup } } }); } // Download fileActions.Add( new ElementAction(new ActionHandle(new DownloadFileActionToken())) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "DownloadFileTitle"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "DownloadFileToolTip"), Icon = DownloadWebsiteFile, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Add, // For sorting purpose IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFileActionGroup } } }); if (IsEditActionAllowed(websiteFile)) { fileActions.Add( new ElementAction(new ActionHandle( websiteFile.MimeType==MimeTypeInfo.Resx? (ActionToken) new UrlActionToken(websiteFile.FileName, EditWebsiteFile, UrlUtils.ResolvePublicUrl($"Composite/content/misc/editors/resxeditor/resxeditor.aspx?f={websiteFile.FullPath}"), _editWebsiteFilePermissionTypes): new WorkflowActionToken( WorkflowFacade.GetWorkflowType( "Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider.EditWebsiteFileTextContentWorkflow"), _editWebsiteFilePermissionTypes))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString( "Composite.Plugins.WebsiteFileElementProvider", "EditWebsiteFileTitle"), ToolTip = StringResourceSystemFacade.GetString( "Composite.Plugins.WebsiteFileElementProvider", "EditWebsiteFileToolTip"), Icon = EditWebsiteFile, Disabled = websiteFile.IsReadOnly, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFileActionGroup } } }); if (websiteFile.MimeType == MimeTypeInfo.Resx && !CultureInfo.GetCultures(CultureTypes.SpecificCultures). Any(f => f.Name != "" && websiteFile.FileName.EndsWith("." + f.Name + ".Resx", StringComparison.OrdinalIgnoreCase))) { var files = Directory.GetFiles(Path.GetDirectoryName(websiteFile.FullPath)); foreach (var cultureInfo in DataLocalizationFacade.ActiveLocalizationCultures) { if (!files.Any(f => cultureInfo.Name!="" && f.EndsWith("." + cultureInfo.Name + ".Resx", StringComparison.OrdinalIgnoreCase))) { fileActions.Add( new ElementAction(new ActionHandle( new UrlActionToken(websiteFile.FileName, EditWebsiteFile, UrlUtils.ResolvePublicUrl( $"Composite/content/misc/editors/resxeditor/resxeditor.aspx?f={websiteFile.FullPath}&t={cultureInfo.Name}"), _editWebsiteFilePermissionTypes) )) { VisualData = new ActionVisualizedData { Label = string.Format(StringResourceSystemFacade.GetString( "Composite.Web.SourceEditor", "ResxEditor.TranslateTo.Label"), cultureInfo.DisplayName), ToolTip = string.Format(StringResourceSystemFacade.GetString( "Composite.Web.SourceEditor", "ResxEditor.TranslateTo.Tooltip"), cultureInfo.DisplayName), Icon = EditWebsiteFile, Disabled = websiteFile.IsReadOnly, ActionLocation = new ActionLocation { ActionType = ActionType.Add, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFileActionGroup } } }); } } } } return fileActions; } private static bool IsDeleteActionAllowed(WebsiteEntity websiteEntity) { if (websiteEntity is WebsiteFile) { return true; //WebsiteFile websiteFile = websiteEntity as WebsiteFile; //string canonical = MimeTypeInfo.GetCanonical(websiteFile.MimeType); //return _editableMimeTypes.Contains(canonical); } if (websiteEntity is WebsiteFolder) { //return false; // Deleting a folder causes the webserver to restart... //if (Directory.GetFiles(websiteEntity.FullPath).Length > 0) return false; //if (Directory.GetDirectories(websiteEntity.FullPath).Length > 0) return false; return true; } throw new NotImplementedException(); } private static bool IsEditActionAllowed(WebsiteEntity websiteEntity) { if (websiteEntity is WebsiteFile websiteFile) { return MimeTypeInfo.IsTextFile(websiteFile.MimeType); } if (websiteEntity is WebsiteFolder) { return false; } throw new NotImplementedException(); } private static ResourceHandle GetIconHandle(string name) { return new ResourceHandle(BuildInIconProviderName.ProviderName, name); } internal static ResourceHandle WebsiteFileIcon(string mimeType) { return MimeTypeInfo.GetResourceHandleFromMimeType(MimeTypeInfo.GetCanonical(mimeType)); } } internal sealed class DownloadFileActionExecutor : IActionExecutor { public static string GetDownloadLink(WebsiteFileElementProviderEntityToken fileToken) { var urlString = new UrlBuilder(UrlUtils.AdminRootPath + "/services/Admin/DownloadFile.ashx"); string relativeFilePath = fileToken.Path.Substring(fileToken.RootPath.Length); urlString["file"] = relativeFilePath; urlString["provider"] = fileToken.Source; return urlString.ToString(); } public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { var fileToken = (WebsiteFileElementProviderEntityToken)entityToken; string downloadLink = GetDownloadLink(fileToken); string currentConsoleId = flowControllerServicesContainer.GetService<IManagementConsoleMessageService>().CurrentConsoleId; ConsoleMessageQueueFacade.Enqueue(new DownloadFileMessageQueueItem(downloadLink), currentConsoleId); return null; } } [ActionExecutor(typeof(DownloadFileActionExecutor))] internal sealed class DownloadFileActionToken : ActionToken { internal static readonly PermissionType[] RequiredPermissionTypes = { PermissionType.Administrate, PermissionType.Edit }; public override IEnumerable<PermissionType> PermissionTypes => RequiredPermissionTypes; public override string Serialize() => "DownloadFile"; public static ActionToken Deserialize(string serializedData) => new DownloadFileActionToken(); public override bool IgnoreEntityTokenLocking => true; } [Assembler(typeof(WebsiteFileElementProviderAssembler))] internal sealed class WebsiteFileElementProviderData : HooklessElementProviderData { private const string _rootLabel = "rootLabel"; [ConfigurationProperty(_rootLabel, IsRequired = true)] public string RootLabel { get { return (string)base[_rootLabel]; } set { base[_rootLabel] = value; } } private const string _folderWhiteListKeyName = "folderWhiteListKeyName"; /// <summary> /// If specified, the key to use when localitng "white listed" folders for this provider. /// When empty all folders are shown (no white-listing required) /// </summary> [ConfigurationProperty(_folderWhiteListKeyName, IsRequired = false, DefaultValue = "")] public string FolderWhiteListKeyName { get { return (string)base[_folderWhiteListKeyName]; } set { base[_folderWhiteListKeyName] = value; } } private const string _manageableKeyNames = "manageableKeyNames"; /// <summary> /// A comma seperated list of "key names" this provider should manage. In effect, this /// controls the folders in other providers that have the specified key name. /// </summary> [ConfigurationProperty(_manageableKeyNames, IsRequired = false, DefaultValue = "")] public string ManageableKeyNames { get { return (string)base[_manageableKeyNames]; } set { base[_manageableKeyNames] = value; } } private const string _manageableKeyNameLabels = "manageableKeyNameLabels"; /// <summary> /// A comma seperated list of strings that denote what is managed by the respective "key name" /// specified for ManageableKeyNames (in the same order). Used for humans to build command labels. /// </summary> [ConfigurationProperty(_manageableKeyNameLabels, IsRequired = false, DefaultValue = "")] public string ManageableKeyNameLabels { get { return (string)base[_manageableKeyNameLabels]; } set { base[_manageableKeyNameLabels] = value; } } } internal sealed class WebsiteFileElementProviderAssembler : IAssembler<IHooklessElementProvider, HooklessElementProviderData> { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IHooklessElementProvider Assemble(IBuilderContext context, HooklessElementProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new WebsiteFileElementProvider(objectConfiguration as WebsiteFileElementProviderData); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/WebsiteFileElementProviderEntityToken.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Security; using Composite.Core; using Composite.Core.IO; using Composite.Core.Serialization; using Newtonsoft.Json; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(WebsiteFileProviderEntityTokenSecurityAncestorProvider))] public sealed class WebsiteFileElementProviderEntityToken : EntityToken { private static readonly string BaseDirectory; private readonly string _relativePath; static WebsiteFileElementProviderEntityToken() { string baseDirectory = PathUtil.BaseDirectory; if(baseDirectory.EndsWith("\\")) { baseDirectory = baseDirectory.Substring(0, baseDirectory.Length - 1); } BaseDirectory = baseDirectory; } /// <exclude /> [JsonConstructor] public WebsiteFileElementProviderEntityToken(string providerName, string path, string rootPath) { Verify.ArgumentNotNull(path, "path"); Verify.ArgumentNotNull(rootPath, "rootPath"); Verify.ArgumentCondition(path.StartsWith(rootPath, StringComparison.OrdinalIgnoreCase), "path", "Path should start with root path"); Verify.That(rootPath.StartsWith(BaseDirectory, StringComparison.OrdinalIgnoreCase), "Path does not belong to the website"); _relativePath = path.Substring(BaseDirectory.Length); this.Path = path; this.RootPath = rootPath; ProviderName = providerName; } /// <exclude /> public string ProviderName { get; } /// <exclude /> public override string Type => ""; /// <exclude /> public override string Source => ProviderName; /// <exclude /> public override string Id => _relativePath; /// <exclude /> public override string Serialize() { return CompositeJsonSerializer.Serialize(this); } /// <exclude /> public static EntityToken Deserialize(string serializedData) { EntityToken entityToken; if (CompositeJsonSerializer.IsJsonSerialized(serializedData)) { entityToken = CompositeJsonSerializer.Deserialize<WebsiteFileElementProviderEntityToken>(serializedData); } else { entityToken = DeserializeLegacy(serializedData); Log.LogVerbose(nameof(WebsiteFileElementProviderEntityToken), entityToken.GetType().FullName); } return entityToken; } /// <exclude /> public static EntityToken DeserializeLegacy(string serializedData) { Dictionary<string, string> dic; string type, source, id; EntityToken.DoDeserialize(serializedData, out type, out source, out id, out dic); // Backward compatibility if (dic.ContainsKey("RootPath")) { string rootPath = StringConversionServices.DeserializeValueString(dic["RootPath"]); return new WebsiteFileElementProviderEntityToken(source, id, rootPath); } string relativeRootPath = StringConversionServices.DeserializeValueString(dic["root"]); return new WebsiteFileElementProviderEntityToken(source, BaseDirectory + id, BaseDirectory + relativeRootPath); } /// <exclude /> public string Path { get; private set; } private string RelativeRootPath => RootPath.Substring(BaseDirectory.Length); [JsonProperty] internal string RootPath { get; private set; } internal bool IsRoot => this.Path == this.RootPath; /// <exclude /> public override bool Equals(object obj) { return base.Equals(obj) && (obj as WebsiteFileElementProviderEntityToken).RootPath == this.RootPath; } /// <exclude /> public override int GetHashCode() { if (this.HashCode == 0) { this.HashCode = GetType().GetHashCode() ^ this.Type.GetHashCode() ^ this.Source.GetHashCode() ^ this.Id.GetHashCode() ^ this.RelativeRootPath.GetHashCode(); } return this.HashCode; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/WebsiteFileElementProviderRootEntityToken.cs ================================================ using Composite.C1Console.Security; using Composite.C1Console.Security.SecurityAncestorProviders; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityAncestorProvider(typeof(NoAncestorSecurityAncestorProvider))] public sealed class WebsiteFileElementProviderRootEntityToken : EntityToken { /// <exclude /> public WebsiteFileElementProviderRootEntityToken(string providerName, string rootPath) { ProviderName = providerName; RootPath = rootPath; } /// <exclude /> internal string ProviderName { get; private set; } internal string RootPath { get; private set; } /// <exclude /> public override string Type { get { return ""; } } /// <exclude /> public override string Source { get { return ProviderName; } } /// <exclude /> public override string Id { get { return ""; } } /// <exclude /> public override string Serialize() { return string.Format("{0}${1}", ProviderName, RootPath); } /// <exclude /> public static EntityToken Deserialize(string serializedData) { if (serializedData.IndexOf('$')>0) { var parts = serializedData.Split('$'); return new WebsiteFileElementProviderRootEntityToken(parts[0], parts[1]); } else { return new WebsiteFileElementProviderRootEntityToken(serializedData, ""); } } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/WebsiteFileEntityTokenSecurityAncestorProvider.cs ================================================ using System.Collections.Generic; using System.IO; using Composite.C1Console.Security; using Composite.Core.IO; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { internal sealed class WebsiteFileProviderEntityTokenSecurityAncestorProvider : ISecurityAncestorProvider { public IEnumerable<EntityToken> GetParents(EntityToken entityToken) { WebsiteFileElementProviderEntityToken castedEntityToken = (WebsiteFileElementProviderEntityToken)entityToken; if ((C1File.Exists(castedEntityToken.Path) == false) && (C1Directory.Exists(castedEntityToken.Path) == false)) { return null; } string newFolderPath = Path.GetDirectoryName(castedEntityToken.Path); string rootFolder = castedEntityToken.RootPath; if (newFolderPath != rootFolder) { Verify.That(newFolderPath.Length > rootFolder.Length, "File/folder path '{0}' does not much root folder '{1}'", newFolderPath, rootFolder); return new EntityToken[] { new WebsiteFileElementProviderEntityToken(castedEntityToken.Source, newFolderPath, castedEntityToken.RootPath) }; } return new EntityToken[] { new WebsiteFileElementProviderRootEntityToken(castedEntityToken.Source, castedEntityToken.RootPath) }; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/WebsiteFileSearchToken.cs ================================================ using Composite.C1Console.Elements; using System.Collections.Generic; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { internal class WebsiteFileSearchToken : SearchToken { public string[] MimeTypes { get; set; } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/WebsiteFolder.cs ================================================ using System.IO; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { internal sealed class WebsiteFolder : WebsiteEntity { private string _folderName = null; public WebsiteFolder(string fullPath) : base(fullPath, true) { } public string FolderName { get { if (_folderName == null) { _folderName = Path.GetFileName(this.FullPath); } return _folderName; } } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/XsltBasedFunctionProviderElementProvider/DeleteXsltFunctionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="DeleteXsltFunctionWorkflow" Location="30; 30" Size="1149; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="DeleteXsltFunctionWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="DeleteXsltFunctionWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="806" Y="71" /> <ns0:Point X="806" Y="197" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Bottom" SetStateName="setStateActivity1" SourceStateName="deleteStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="deleteStateActivity" EventHandlerName="deleteStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="548" Y="219" /> <ns0:Point X="564" Y="219" /> <ns0:Point X="564" Y="285" /> <ns0:Point X="806" Y="285" /> <ns0:Point X="806" Y="277" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="deleteStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Bottom" SetStateName="setStateActivity3" SourceStateName="confirmStateActivity" SourceConnectionEdge="Right" TargetActivity="deleteStateActivity" SourceActivity="confirmStateActivity" EventHandlerName="confirm_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="195" Y="306" /> <ns0:Point X="451" Y="306" /> <ns0:Point X="451" Y="258" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Bottom" SetStateName="setStateActivity4" SourceStateName="confirmStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="confirmStateActivity" EventHandlerName="confirm_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="199" Y="330" /> <ns0:Point X="806" Y="330" /> <ns0:Point X="806" Y="277" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="deleteStateActivity" Location="351; 178" Size="201; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="deleteStateInitializationActivity" Location="529; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="codeActivity1" Location="539; 210" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="539; 270" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="539; 330" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="726; 197" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="confirmStateActivity" Location="78; 241" Size="175; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="stateInitializationActivity1" Location="86; 272"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="confirmDialogFormActivity1" Location="96; 334" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="confirm_Finish" Location="86; 296"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity2" Location="96; 358" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="96; 418" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="confirm_Cancel" Location="86; 320"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="96; 382" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="96; 442" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite/Plugins/Elements/ElementProviders/XsltBasedFunctionProviderElementProvider/EditXsltFunctionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="EditXsltFunctionWorkflow" Location="30; 30" Size="1149; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="EditXsltFunctionWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="EditXsltFunctionWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="822" Y="71" /> <ns0:Point X="822" Y="109" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="269" Y="146" /> <ns0:Point X="317" Y="146" /> <ns0:Point X="317" Y="432" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="validateStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="editStateActivity" SourceConnectionEdge="Right" TargetActivity="validateStateActivity" SourceActivity="editStateActivity" EventHandlerName="saveEventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="406" Y="497" /> <ns0:Point X="433" Y="497" /> <ns0:Point X="433" Y="319" /> <ns0:Point X="578" Y="319" /> <ns0:Point X="578" Y="327" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Bottom" SetStateName="setStateActivity4" SourceStateName="editStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="editStateActivity" EventHandlerName="editEventDrivenActivity_Preview"> <StateDesignerConnector.Segments> <ns0:Point X="417" Y="521" /> <ns0:Point X="429" Y="521" /> <ns0:Point X="429" Y="558" /> <ns0:Point X="317" Y="558" /> <ns0:Point X="317" Y="550" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="saveStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="saveStateActivity" EventHandlerName="saveStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="970" Y="637" /> <ns0:Point X="981" Y="637" /> <ns0:Point X="981" Y="424" /> <ns0:Point X="317" Y="424" /> <ns0:Point X="317" Y="432" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="saveStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="validateStateActivity" SourceConnectionEdge="Right" TargetActivity="saveStateActivity" SourceActivity="validateStateActivity" EventHandlerName="validateInitializeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="669" Y="368" /> <ns0:Point X="877" Y="368" /> <ns0:Point X="877" Y="596" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Bottom" SetStateName="setStateActivity7" SourceStateName="validateStateActivity" SourceConnectionEdge="Left" TargetActivity="editStateActivity" SourceActivity="validateStateActivity" EventHandlerName="validateInitializeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="487" Y="368" /> <ns0:Point X="471" Y="368" /> <ns0:Point X="471" Y="560" /> <ns0:Point X="317" Y="560" /> <ns0:Point X="317" Y="550" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initializeStateActivity" Location="63; 105" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initializeStateInitializationActivity" Location="71; 136"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity" Location="81; 198" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="81; 258" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="editStateActivity" Location="213; 432" Size="208; 118" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="editStateInitializationActivity" Location="221; 463"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="documentFormActivity1" Location="231; 525" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="saveEventDrivenActivity_Save" Location="221; 487"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="saveHandleExternalEventActivity1" Location="231; 549" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="231; 609" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 242" Name="editEventDrivenActivity_Preview" Location="221; 511"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="previewHandleExternalEventActivity1" Location="231; 573" /> <CodeDesigner Size="130; 41" Name="editPreviewActivity" Location="231; 633" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="231; 693" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="saveStateActivity" Location="781; 596" Size="193; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="saveStateInitializationActivity" Location="789; 627"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="saveCodeActivity" Location="799; 689" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="799; 749" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="742; 109" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="validateStateActivity" Location="483; 327" Size="190; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 303" Name="validateInitializeStateActivity" Location="491; 358"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="361; 222" Name="ifElseActivity1" Location="501; 420"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity1" Location="520; 491"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="530; 553" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity2" Location="693; 491"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="703; 553" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite/Plugins/Elements/ElementProviders/XsltBasedFunctionProviderElementProvider/FlowUiQueryMarkupHelper.cs ================================================ using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; using Composite.Functions; namespace Composite.Plugins.Elements.ElementProviders.XsltBasedFunctionProviderElementProvider { internal static class FlowUiQueryMarkupHelper { private static readonly XNamespace ui = "http://www.w3.org/1999/xhtml"; public static void ParseXml(string theXml, out IEnumerable<KeyValuePair<string, string>> queries, out ILookup<string, KeyValuePair<string, string>> parameterLookup) { XDocument document = XDocument.Parse(theXml); queries = from nodes in document.Descendants(ui + "treenode") where (string)nodes.Attribute("binding") == "QueryTreeNodeBinding" select new KeyValuePair<string, string>((string)nodes.Attribute("localname"), (string)nodes.Attribute("ElementId")); var paramList = from nodes in document.Descendants(ui + "treenode") where (string)nodes.Attribute("binding") == "QueryParamTreeNodeBinding" select new { QueryLocalName = (string)nodes.Parent.Attribute("localname"), Name = (string)nodes.Attribute("paramname"), Value = (string)nodes.Attribute("paramvalue") }; parameterLookup = paramList.ToLookup(f => f.QueryLocalName, f => new KeyValuePair<string, string>(f.Name, f.Value)); } public static string BuildXml(IEnumerable<KeyValuePair<string, string>> queries, ILookup<string, KeyValuePair<string, string>> parameters) { var usedQueryInfos = from query in queries select new { LocalName = query.Key, QueryInfo = FunctionFacade.GetFunction(query.Value) }; var paramsDictionary = parameters.ToDictionary(f => f.Key); XElement rootElement = new XElement(ui + "treebody"); foreach (var namedQueryInfo in usedQueryInfos.OrderBy(f => f.QueryInfo.Namespace + f.QueryInfo.Name + f.LocalName)) { IFunction queryInfo = namedQueryInfo.QueryInfo; XElement currentNamespaceFolder = rootElement; if (string.IsNullOrEmpty(queryInfo.Namespace) == false) { string piecemealNamespace = ""; foreach (string namespaceSegment in queryInfo.Namespace.Split('.')) { if (string.IsNullOrEmpty(piecemealNamespace) == false) piecemealNamespace = piecemealNamespace + "."; piecemealNamespace = piecemealNamespace + namespaceSegment; XElement existingFolder = (from folderElement in rootElement.Descendants(ui + "treenode") where (string)folderElement.Attribute("binding") == "QueryFolderTreeNodeBinding" && (string)folderElement.Attribute("ElementId") == piecemealNamespace select folderElement).FirstOrDefault(); if (existingFolder == null) { XElement subFolder = new XElement(ui + "treenode", new XAttribute("binding", "QueryFolderTreeNodeBinding"), new XAttribute("ElementId", piecemealNamespace), new XAttribute("label", namespaceSegment)); currentNamespaceFolder.Add(subFolder); currentNamespaceFolder = subFolder; } else { currentNamespaceFolder = existingFolder; } } } IGrouping<string, KeyValuePair<string, string>> currentQueryParams; bool hasParams = paramsDictionary.TryGetValue(namedQueryInfo.LocalName, out currentQueryParams); currentNamespaceFolder.Add( new XElement(ui + "treenode", new XAttribute("binding", "QueryTreeNodeBinding"), new XAttribute("queryname", queryInfo.Name), new XAttribute("localname", namedQueryInfo.LocalName), new XAttribute("ElementId", queryInfo.CompositeName()), from parameter in queryInfo.ParameterProfiles orderby parameter.Name select new XElement(ui + "treenode", new XAttribute("binding", "QueryParamTreeNodeBinding"), new XAttribute("paramname", parameter.Name), new XAttribute("hasvalue", hasParams && currentQueryParams.Count(f => f.Key == parameter.Name) == 1), (hasParams && currentQueryParams.Count(f => f.Key == parameter.Name && f.Value != null) == 1 ? new XAttribute("paramvalue", currentQueryParams.First(f => f.Key == parameter.Name).Value) : null)))); } XmlDocument output = new XmlDocument(); output.LoadXml(rootElement.ToString()); XmlNamespaceManager namespaceManager = new XmlNamespaceManager(output.NameTable); namespaceManager.AddNamespace("ui", ui.ToString()); XmlNodeList allNodes = output.SelectNodes("//*"); foreach (XmlNode node in allNodes) { node.Prefix = "ui"; } output.DocumentElement.RemoveAttribute("xmlns"); return IndentedOuterXml(output); } public static string IndentedOuterXml(XmlNode node) { StringWriter stringWriter = new StringWriter(); XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter); xmlTextWriter.Formatting = Formatting.Indented; node.WriteTo(xmlTextWriter); return stringWriter.ToString(); } } } ================================================ FILE: Composite/Plugins/Elements/ElementProviders/XsltBasedFunctionProviderElementProvider/XsltBasedFunctionProviderElementProvider.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Elements; using Composite.C1Console.Elements.Plugins.ElementProvider; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.C1Console.Security; using Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider; using Composite.C1Console.Workflow; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Elements.ElementProviders.XsltBasedFunctionProviderElementProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ConfigurationElementType(typeof(XsltBasedFunctionProviderElementProviderData))] public sealed class XsltBasedFunctionProviderElementProvider : BaseFunctionProviderElementProvider.BaseFunctionProviderElementProvider { private string _providerName; private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); /// <exclude /> public static ResourceHandle AddFunction { get { return GetIconHandle("xslt-based-function-add"); } } /// <exclude /> public static ResourceHandle EditFunction { get { return GetIconHandle("xslt-based-function-edit"); } } /// <exclude /> public static ResourceHandle DeleteFunction { get { return GetIconHandle("xslt-based-function-delete"); } } /// <exclude /> public XsltBasedFunctionProviderElementProvider(string providerName) { _providerName = providerName; } /// <exclude /> protected override string RootFolderLabel { get { return StringResourceSystemFacade.GetString("Composite.Plugins.XsltBasedFunction", "Plugins.XsltBasedFunctionProviderElementProvider.RootFolderLabel"); } } /// <exclude /> protected override string RootFolderToolTip { get { return StringResourceSystemFacade.GetString("Composite.Plugins.XsltBasedFunction", "Plugins.XsltBasedFunctionProviderElementProvider.RootFolderToolTip"); } } /// <exclude /> protected override IEnumerable<IFunctionTreeBuilderLeafInfo> OnGetFunctionInfos(SearchToken searchToken) { if (searchToken.IsValidKeyword() == false) { return from function in DataFacade.GetData<IXsltFunction>() orderby function.Name select (IFunctionTreeBuilderLeafInfo)new XsltFunctionTreeBuilderLeafInfo(function); } else { string keyword = searchToken.Keyword.ToLowerInvariant(); return from function in DataFacade.GetData<IXsltFunction>() where function.Name.ToLowerInvariant().Contains(keyword) || function.Namespace.ToLowerInvariant().Contains(keyword) orderby function.Name select (IFunctionTreeBuilderLeafInfo)new XsltFunctionTreeBuilderLeafInfo(function); } } /// <exclude /> protected override IEnumerable<Type> OnGetEntityTokenTypes() { yield return typeof(DataEntityToken); } /// <exclude /> protected override IFunctionTreeBuilderLeafInfo OnIsEntityOwner(EntityToken entityToken) { DataEntityToken dataEntityToken = entityToken as DataEntityToken; if (dataEntityToken == null) return null; if (dataEntityToken.InterfaceType != typeof(IXsltFunction)) return null; return new XsltFunctionTreeBuilderLeafInfo(dataEntityToken.Data as IXsltFunction); } /// <exclude /> protected override IEnumerable<ElementAction> OnGetFolderActions() { return new ElementAction[] { new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.XsltBasedFunctionProviderElementProvider.AddNewXsltFunctionWorkflow"), new PermissionType[] { PermissionType.Add } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.XsltBasedFunction", "XsltBasedFunctionProviderElementProvider.Add"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.XsltBasedFunction", "XsltBasedFunctionProviderElementProvider.AddToolTip"), Icon = XsltBasedFunctionProviderElementProvider.AddFunction, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } } }; } /// <exclude /> protected override IEnumerable<ElementAction> OnGetFunctionActions(IFunctionTreeBuilderLeafInfo function) { return new ElementAction[] { new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.XsltBasedFunctionProviderElementProvider.EditXsltFunctionWorkflow"), new PermissionType[] { PermissionType.Edit } ))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.XsltBasedFunction", "XsltBasedFunctionProviderElementProvider.Edit"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.XsltBasedFunction", "XsltBasedFunctionProviderElementProvider.EditToolTip"), Icon = XsltBasedFunctionProviderElementProvider.EditFunction, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }, new ElementAction(new ActionHandle( new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.XsltBasedFunctionProviderElementProvider.DeleteXsltFunctionWorkflow"), new PermissionType[] { PermissionType.Delete } ){Payload = GetContext().ProviderName})) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.XsltBasedFunction", "XsltBasedFunctionProviderElementProvider.Delete"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.XsltBasedFunction", "XsltBasedFunctionProviderElementProvider.DeleteToolTip"), Icon = XsltBasedFunctionProviderElementProvider.DeleteFunction, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } } }; } private sealed class XsltFunctionTreeBuilderLeafInfo : IFunctionTreeBuilderLeafInfo { private IXsltFunction _function; public XsltFunctionTreeBuilderLeafInfo(IXsltFunction function) { _function = function; } public string Name { get { return _function.Name; } } public string Namespace { get { return _function.Namespace; } } public EntityToken EntityToken { get { return _function.GetDataEntityToken(); } } } } [Assembler(typeof(XsltBasedFunctionProviderElementProviderAssembler))] internal sealed class XsltBasedFunctionProviderElementProviderData : HooklessElementProviderData { private const string _codeDomQueryResultProviderNameProperty = "XsltBasedFunctionProviderName"; [ConfigurationProperty(_codeDomQueryResultProviderNameProperty, IsRequired = true)] public string XsltBasedFunctionProviderName { get { return (string)base[_codeDomQueryResultProviderNameProperty]; } set { base[_codeDomQueryResultProviderNameProperty] = value; } } } internal sealed class XsltBasedFunctionProviderElementProviderAssembler : IAssembler<IHooklessElementProvider, HooklessElementProviderData> { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public IHooklessElementProvider Assemble(IBuilderContext context, HooklessElementProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { XsltBasedFunctionProviderElementProviderData data = (XsltBasedFunctionProviderElementProviderData)objectConfiguration; return new XsltBasedFunctionProviderElementProvider(data.XsltBasedFunctionProviderName); } } } ================================================ FILE: Composite/Plugins/Elements/UrlToEntityToken/DataUrlToEntityTokenMapper.cs ================================================ using System.Linq; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.Core.Extensions; using Composite.Core.Routing; using Composite.Data; using Composite.Data.Types; namespace Composite.Plugins.Elements.UrlToEntityToken { internal class DataUrlToEntityTokenMapper : IUrlToEntityTokenMapper { public string TryGetUrl(EntityToken entityToken) { var dataEntityToken = entityToken as DataEntityToken; var data = dataEntityToken?.Data; if (data == null) { return null; } PageUrlData pageUrlData; var page = data as IPage; if (page != null) { pageUrlData = new PageUrlData(page); } else { pageUrlData = DataUrls.TryGetPageUrlData(data.ToDataReference()); } return pageUrlData != null ? GetPagePreviewUrl(pageUrlData) : null; } public BrowserViewSettings TryGetBrowserViewSettings(EntityToken entityToken, bool showPublishedView) { var dataEntityToken = entityToken as DataEntityToken; if (dataEntityToken == null) { return null; } if (showPublishedView) { using (new DataScope(PublicationScope.Published)) { if (dataEntityToken.DataSourceId.PublicationScope == PublicationScope.Unpublished && DataFacade.GetSupportedDataScopes(dataEntityToken.InterfaceType) .Contains(DataScopeIdentifier.Public)) { var data = dataEntityToken.Data; if (data != null) { var key = data.GetUniqueKey(); var publicData = DataFacade.TryGetDataVersionsByUniqueKey(dataEntityToken.InterfaceType, key).FirstOrDefault(); if (publicData != null) { entityToken = publicData.GetDataEntityToken(); } else { return null; } } } } } string url = TryGetUrl(entityToken); return url == null ? null : new BrowserViewSettings { Url = url, ToolingOn = true }; } private static string GetPagePreviewUrl(PageUrlData pageUrlData) { var urlSpace = new UrlSpace {ForceRelativeUrls = true}; return PageUrls.BuildUrl(pageUrlData, UrlKind.Public, urlSpace) ?? PageUrls.BuildUrl(pageUrlData, UrlKind.Renderer, urlSpace); } public EntityToken TryGetEntityToken(string url) { UrlKind urlKind; PageUrlData pageUrlData = PageUrls.ParseUrl(url, out urlKind); if (pageUrlData == null) return null; if (pageUrlData.PublicationScope == PublicationScope.Published) { pageUrlData.PublicationScope = PublicationScope.Unpublished; } if (!string.IsNullOrEmpty(pageUrlData.PathInfo) || pageUrlData.HasQueryParameters) { IData data; var dataReference = DataUrls.TryGetData(pageUrlData); if (dataReference != null && (data = dataReference.Data) != null) { return data.GetDataEntityToken(); } } IPage page = pageUrlData.GetPage(); return page?.GetDataEntityToken(); } } } ================================================ FILE: Composite/Plugins/Elements/UrlToEntityToken/MediaUrlToEntityTokenMapper.cs ================================================ using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.Core; using Composite.Core.IO; using Composite.Core.Routing; using Composite.Data; using Composite.Data.Types; namespace Composite.Plugins.Elements.UrlToEntityToken { internal class MediaUrlToEntityTokenMapper : IUrlToEntityTokenMapper { public string TryGetUrl(EntityToken entityToken) => null; public BrowserViewSettings TryGetBrowserViewSettings(EntityToken entityToken, bool showPublishedView) { if (!(entityToken is DataEntityToken dataEntityToken) || dataEntityToken.InterfaceType != typeof(IMediaFile)) { return null; } var file = (IMediaFile) dataEntityToken.Data; if(file == null || !MimeTypeInfo.IsBrowserPreviewableFile(file.MimeType)) { return null; } string url = MediaUrls.BuildUrl(file); var urlBuilder = new UrlBuilder(url) { ["download"] = "false" }; return new BrowserViewSettings { Url = urlBuilder.ToString(), ToolingOn = false }; } public EntityToken TryGetEntityToken(string url) => null; } } ================================================ FILE: Composite/Plugins/Elements/UrlToEntityToken/ServerLogUrlToEntityTokenMapper.cs ================================================ using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.C1Console.Trees; using Composite.Core.WebClient; namespace Composite.Plugins.Elements.UrlToEntityToken { internal class ServerLogUrlToEntityTokenMapper: IUrlToEntityTokenMapper { public string TryGetUrl(EntityToken entityToken) { return null; } public BrowserViewSettings TryGetBrowserViewSettings(EntityToken entityToken, bool showPublishedView) { var castedEntityToken = entityToken as TreeSimpleElementEntityToken; if (castedEntityToken == null || castedEntityToken.Id != "system.server.log") { return null; } return new BrowserViewSettings { Url = UrlUtils.Combine(UrlUtils.AdminRootPath, "/content/views/log/log.aspx?browserView=true"), ToolingOn = false }; } public EntityToken TryGetEntityToken(string url) { return null; } } } ================================================ FILE: Composite/Plugins/Elements/UrlToEntityToken/WebsiteFileUrlToEntityTokenMapper.cs ================================================ using System; using System.IO; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.Core; using Composite.Core.IO; using Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider; namespace Composite.Plugins.Elements.UrlToEntityToken { internal class WebsiteFileUrlToEntityTokenMapper : IUrlToEntityTokenMapper { public string TryGetUrl(EntityToken entityToken) => null; public BrowserViewSettings TryGetBrowserViewSettings(EntityToken entityToken, bool showPublishedView) { if (!(entityToken is WebsiteFileElementProviderEntityToken fileEntityToken)) { return null; } var filePath = fileEntityToken.RootPath + fileEntityToken.Id; if (!File.Exists(filePath) || !UserHasRightToDownload(entityToken)) return null; var fileInfo = new FileInfo(filePath); if(!FilePreviewable(fileInfo)) { return null; } var downloadLink = DownloadFileActionExecutor.GetDownloadLink(fileEntityToken); var urlBuilder = new UrlBuilder(downloadLink) { ["preview"] = "true" }; return new BrowserViewSettings { Url = urlBuilder, ToolingOn = false }; } private bool UserHasRightToDownload(EntityToken file) { var userToken = UserValidationFacade.GetUserToken(); var userPermissionDefinitions = PermissionTypeFacade.GetUserPermissionDefinitions(userToken.Username); var userGroupPermissionDefinitions = PermissionTypeFacade.GetUserGroupPermissionDefinitions(userToken.Username); var requiredPermissions = DownloadFileActionToken.RequiredPermissionTypes; return SecurityResolver.Resolve(userToken, requiredPermissions, file, userPermissionDefinitions, userGroupPermissionDefinitions) == SecurityResult.Allowed; } private bool FilePreviewable(FileInfo fileInfo) { if (string.IsNullOrEmpty(fileInfo.Extension)) return false; string mimeType = MimeTypeInfo.GetCanonicalFromExtension(fileInfo.Extension); if (string.IsNullOrEmpty(mimeType)) return false; return MimeTypeInfo.IsBrowserPreviewableFile(mimeType) || (MimeTypeInfo.IsTextFile(mimeType) && fileInfo.Length < 1 << 20 /* 1 MB */) || fileInfo.Extension.Equals(".dll", StringComparison.OrdinalIgnoreCase); } public EntityToken TryGetEntityToken(string url) => null; } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/CustomUiControls/TemplatedPageContentEditorUiControlFactory.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.Foundation; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Core.WebClient; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.CustomUiControls { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class PageContentEditorTemplateUserControlBase : UserControl { /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public Guid PageId { get; set; } /// <exclude /> public Guid TemplateId { get; set; } /// <exclude /> public List<KeyValuePair<Guid, string>> SelectableTemplateIds { get; set; } /// <exclude /> public Dictionary<string, string> NamedXhtmlFragments { get; set; } /// <exclude /> public string FormControlLabel { get; set; } /// <exclude /> public string ClassConfigurationName { get; set; } /// <exclude /> public Guid PageTypeId { get; set; } } internal sealed class TemplatedPageContentEditorUiControl : UiControl, IWebUiControl { [FormsProperty()] [BindableProperty()] public Guid PageId { get; set; } [FormsProperty()] [BindableProperty()] public Guid TemplateId { get; set; } [FormsProperty()] [BindableProperty()] public List<KeyValuePair<Guid, string>> SelectableTemplateIds { get; set; } [FormsProperty()] [BindableProperty()] public Dictionary<string, string> NamedXhtmlFragments { get; set; } [FormsProperty()] public string ClassConfigurationName { get; set; } [FormsProperty()] public Guid PageTypeId { get; set; } private Type _userControlType; private PageContentEditorTemplateUserControlBase _userControl; internal TemplatedPageContentEditorUiControl(Type userControlType) { _userControlType = userControlType; this.SelectableTemplateIds = new List<KeyValuePair<Guid, string>>(); this.NamedXhtmlFragments = new Dictionary<string, string>(); } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.SelectableTemplateIds = new List<KeyValuePair<Guid, string>>(); this.NamedXhtmlFragments = _userControl.NamedXhtmlFragments; this.TemplateId = _userControl.TemplateId; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<PageContentEditorTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.TemplateId = this.TemplateId; _userControl.SelectableTemplateIds = this.SelectableTemplateIds; _userControl.NamedXhtmlFragments = this.NamedXhtmlFragments; _userControl.ClassConfigurationName = this.ClassConfigurationName; _userControl.PageId = this.PageId; _userControl.PageTypeId = this.PageTypeId; return _userControl; } public bool IsFullWidthControl { get { return true; } } public string ClientName { get { return _userControl.GetDataFieldClientName(); } } } [ConfigurationElementType(typeof(TemplatedPageContentEditorUiControlFactoryData))] internal sealed class TemplatedPageContentEditorUiControlFactory : IUiControlFactory { private TemplatedPageContentEditorUiControlFactoryData _data; private Type _cachedUserControlType = null; public TemplatedPageContentEditorUiControlFactory(TemplatedPageContentEditorUiControlFactoryData data) { _data = data; if (_data.CacheCompiledUserControlType) { _cachedUserControlType = BuildManagerHelper.GetCompiledType(_data.UserControlVirtualPath); } } public IUiControl CreateControl() { Type userControlType = _cachedUserControlType; if (userControlType == null && System.Web.HttpContext.Current != null) { userControlType = BuildManagerHelper.GetCompiledType(_data.UserControlVirtualPath); } TemplatedPageContentEditorUiControl control = new TemplatedPageContentEditorUiControl(userControlType); control.ClassConfigurationName = _data.ClassConfigurationName; return control; } } [Assembler(typeof(TemplatedPageContentEditorUiControlFactoryAssembler))] internal sealed class TemplatedPageContentEditorUiControlFactoryData : UiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } private const string _classConfigurationNamePropertyName = "ClassConfigurationName"; [ConfigurationProperty(_classConfigurationNamePropertyName, IsRequired = false, DefaultValue = "common")] public string ClassConfigurationName { get { return (string)base[_classConfigurationNamePropertyName]; } set { base[_classConfigurationNamePropertyName] = value; } } } internal sealed class TemplatedPageContentEditorUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedPageContentEditorUiControlFactory(objectConfiguration as TemplatedPageContentEditorUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/Foundation/UserControlUtils.cs ================================================ using System.Web.UI; using System; using System.Web; namespace Composite.Plugins.Forms.WebChannel.Foundation { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class UserControlUtils { /// <exclude /> public static TBase ActivateAsUserControl<TBase>(this Type userControlType, string uniqueUserControlId) where TBase : UserControl { if (userControlType == null) throw new ArgumentNullException("userControlType"); if (typeof(TBase).IsAssignableFrom(userControlType) == false) throw new ArgumentException("The specified type '" + userControlType.FullName + "' must inherit from generic argument " + typeof(TBase).FullName, "userControlType"); Page currentPage = HttpContext.Current.Handler as Page; if (currentPage == null) throw new InvalidOperationException("The Current HttpContext Handler must be a System.Web.Ui.Page"); Control templateControl = currentPage.LoadControl(userControlType, null); templateControl.ID = uniqueUserControlId; return (TBase)templateControl; } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiContainerFactories/Base/BaseTemplatedUiContainerFactory.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.C1Console.Forms; using Composite.Core.Logging; using Composite.C1Console.Forms.Flows.Plugins.UiContainerFactory; using Composite.C1Console.Forms.Flows; using Composite.Core.WebClient; namespace Composite.Plugins.Forms.WebChannel.UiContainerFactories.Base { internal abstract class BaseTemplatedUiContainerFactory : IUiContainerFactory { private ITemplatedUiContainerFactoryData _data; private Type _cachedUserControlType = null; private object _lock = new object(); protected BaseTemplatedUiContainerFactory(ITemplatedUiContainerFactoryData data) { _data = data; } protected Type UserControlType { get { return this.CachedUserControlType; } } private Type CachedUserControlType { get { lock (_lock) { if (_cachedUserControlType == null || _data.CacheCompiledUserControlType == false) { using (DebugLoggingScope.CompletionTime(this.GetType(), string.Format("getting compiled '{0}'", _data.UserControlVirtualPath, TimeSpan.FromMilliseconds(25)))) { _cachedUserControlType = BuildManagerHelper.GetCompiledType(_data.UserControlVirtualPath); } } return _cachedUserControlType; } } } public abstract IUiContainer CreateContainer(); } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiContainerFactories/Base/ITemplatedUiContainerFactoryData.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; namespace Composite.Plugins.Forms.WebChannel.UiContainerFactories.Base { internal interface ITemplatedUiContainerFactoryData { string UserControlVirtualPath { get; set; } bool CacheCompiledUserControlType { get; set; } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiContainerFactories/TemplatedUiContainer.cs ================================================ using System; using System.Collections.Generic; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.Foundation; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Composite.Plugins.Forms.WebChannel.UiControlFactories; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Forms.WebChannel.UiContainerFactories { internal class TemplatedUiContainer : IWebUiContainer { private readonly Type _templateUserControlType; private readonly string _templateFormVirtualPath; private TemplatedExecutionContainer _webDocument; internal TemplatedUiContainer(Type templateUserControlType, string templateFormVirtualPath) { _templateUserControlType = templateUserControlType; _templateFormVirtualPath = templateFormVirtualPath; } public IUiControl Render( IUiControl innerForm, IUiControl customToolbarItems, IFormChannelIdentifier channel, IDictionary<string, object> eventHandlerBindings, string containerLabel, string containerLabelField, string containerTooltip, ResourceHandle containerIcon) { if (!string.IsNullOrEmpty(_templateFormVirtualPath)) { var document = new WebEmbeddedFormUiControl(channel) { FormPath = _templateFormVirtualPath, Bindings = new Dictionary<string, object>(eventHandlerBindings) {{"Form", innerForm}} }; if (customToolbarItems != null) { document.Bindings.Add("CustomToolbarItems", customToolbarItems); } _webDocument = new TemplatedExecutionContainer(document, _templateUserControlType, containerLabel, containerLabelField, containerTooltip, containerIcon); } else { _webDocument = new TemplatedExecutionContainer((IWebUiControl)innerForm, _templateUserControlType, containerLabel, containerLabelField, containerTooltip, containerIcon); } return _webDocument; } public void ShowFieldMessages(Dictionary<string, string> clientIDPathedMessages) { _webDocument.ShowFieldMessages( clientIDPathedMessages); } } internal class TemplatedExecutionContainer : UiControl, IWebUiControl { readonly IWebUiControl _form; readonly Type _templateUserControlType; readonly string _containerLabel; readonly string _containerTooltip; readonly string _containerLabelField; readonly ResourceHandle _containerIcon; Control _messagePlaceHolder; TemplatedUiContainerBase _templateControl; public TemplatedExecutionContainer( IWebUiControl form, Type templateUserControlType, string containerLabel, string containerLabelField, string containerTooltip, ResourceHandle containerIcon) { _form = form; _templateUserControlType = templateUserControlType; _containerLabel = containerLabel; _containerLabelField = containerLabelField; _containerTooltip = containerTooltip; _containerIcon = containerIcon; } internal Control GetMessagePlaceHolder() { if (_messagePlaceHolder == null) throw new InvalidOperationException("MessagePlaceHolder has not been initialized. The place holder will not exist before BuildWebControl() has been called"); return _messagePlaceHolder; } public override void BindStateToControlProperties() { _form.BindStateToControlProperties(); } public Control BuildWebControl() { _templateControl = _templateUserControlType.ActivateAsUserControl<TemplatedUiContainerBase>(this.UiControlID); Control formPlaceHolder = _templateControl.GetFormPlaceHolder(); _messagePlaceHolder = _templateControl.GetMessagePlaceHolder(); _templateControl.SetContainerTitle(_containerLabel); _templateControl.SetContainerTitleField(_containerLabelField); _templateControl.SetContainerTooltip(_containerTooltip); _templateControl.SetContainerIcon(_containerIcon); _templateControl.SetWebUiControlRef(_form); formPlaceHolder.Controls.Add(_form.BuildWebControl()); return _templateControl; } public void InitializeViewState() { _form.InitializeViewState(); } public bool IsFullWidthControl { get { throw new Exception("I am the root page!"); } } public string ClientName { get { return null; } } internal void ShowFieldMessages(Dictionary<string, string> clientIDPathedMessages) { _templateControl.ShowFieldMessages(clientIDPathedMessages);; } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiContainerFactories/TemplatedUiContainerBase.cs ================================================ using System; using System.Web.UI; using System.Collections.Generic; using Composite.C1Console.Forms.DataServices.UiControls; using Composite.C1Console.Forms.WebChannel; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; using Composite.Core.WebClient.FlowMediators.FormFlowRendering; using Composite.Plugins.Forms.WebChannel.UiControlFactories; using System.Web.UI.HtmlControls; using System.Linq; namespace Composite.Plugins.Forms.WebChannel.UiContainerFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class TemplatedUiContainerBase : UserControl { private IWebUiControl _webUiControl; private string _titleField; /// <exclude /> public abstract Control GetFormPlaceHolder(); /// <exclude /> public abstract Control GetMessagePlaceHolder(); /// <exclude /> public abstract void SetContainerTitle(string title); /// <exclude /> public virtual void SetContainerTooltip(string tooltip) { } /// <exclude /> public void SetContainerTitleField(string titleField) { _titleField = titleField; } /// <exclude /> public string GetTitleFieldControlId() { IWebUiControl container = GetContainer(); if (_titleField.IsNullOrEmpty() || container == null) return string.Empty; var mappings = new Dictionary<string, string>(); FormFlowUiDefinitionRenderer.ResolveBindingPathToClientIDMappings(container, mappings); string clientId = mappings.ContainsKey(_titleField) ? mappings[_titleField] : ""; return clientId; } /// <exclude /> public abstract void SetContainerIcon(ResourceHandle icon); internal void SetWebUiControlRef(IWebUiControl webUiControl) { _webUiControl = webUiControl; } /// <exclude /> protected override void OnInit(System.EventArgs e) { base.OnInit(e); if (!this.IsPostBack) { _webUiControl.InitializeViewState(); return; } } /// <exclude /> protected override void OnPreRender(EventArgs e) { // Initializing lazy controls after PageLoad so the processed Post data will be overwritten if (IsPostBack) { if (_webUiControl is EmbeddedFormUiControl) { var container = GetContainer(); container?.InitializeLazyBindedControls(); } } base.OnPreRender(e); } private TemplatedContainerUiControl GetContainer() { var container = (_webUiControl as EmbeddedFormUiControl).CompiledUiControl as TemplatedContainerUiControl; return container; } /// <exclude /> public abstract void ShowFieldMessages(Dictionary<string, string> clientIDPathedMessages); } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiContainerFactories/TemplatedUiContainerFactory.cs ================================================ using System.Configuration; using Composite.C1Console.Forms.Flows; using Composite.C1Console.Forms.Flows.Plugins.UiContainerFactory; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiContainerFactories { [ConfigurationElementType(typeof(TemplatedUiContainerFactoryData))] internal sealed class TemplatedUiContainerFactory : Base.BaseTemplatedUiContainerFactory { private TemplatedUiContainerFactoryData _data; public TemplatedUiContainerFactory(TemplatedUiContainerFactoryData data) : base(data) { _data = data; } public override IUiContainer CreateContainer() { return new TemplatedUiContainer(this.UserControlType, _data.TemplateFormVirtualPath); } } [Assembler(typeof(TemplatedUiContainerFactoryAssembler))] internal sealed class TemplatedUiContainerFactoryData : UiContainerFactoryData, Base.ITemplatedUiContainerFactoryData { private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedUiContainerFactoryAssembler : IAssembler<IUiContainerFactory, UiContainerFactoryData> { public IUiContainerFactory Assemble(IBuilderContext context, UiContainerFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedUiContainerFactory(objectConfiguration as TemplatedUiContainerFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/Base/BaseTemplatedUiControlFactory.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms; using Composite.Core.Logging; using Composite.Core.WebClient; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories.Base { internal abstract class BaseTemplatedUiControlFactory : IUiControlFactory { private ITemplatedUiControlFactoryData _data; private Type _cachedUserControlType = null; private object _lock = new object(); protected BaseTemplatedUiControlFactory(ITemplatedUiControlFactoryData data) { _data = data; } protected Type UserControlType { get { return this.CachedUserControlType; } } private Type CachedUserControlType { get { lock (_lock) { if (_cachedUserControlType == null || _data.CacheCompiledUserControlType == false) { using (DebugLoggingScope.CompletionTime(this.GetType(), string.Format("getting compiled '{0}'", _data.UserControlVirtualPath), TimeSpan.FromMilliseconds(25))) { _cachedUserControlType = BuildManagerHelper.GetCompiledType(_data.UserControlVirtualPath); } } return _cachedUserControlType; } } } public abstract IUiControl CreateControl(); } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/Base/ITemplatedUiControlFactoryData.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.C1Console.Forms.Plugins.UiControlFactory; using System.Configuration; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories.Base { internal interface ITemplatedUiControlFactoryData { string UserControlVirtualPath { get; set; } bool CacheCompiledUserControlType { get; set; } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/Base/UserControlBase.cs ================================================ using System.Web.UI; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories.Base { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class UserControlBase : UserControl { /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public string FormControlLabel { get; set; } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedBoolSelectorUiControlFactory.cs ================================================ using System; using System.Collections.Specialized; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class BoolSelectorTemplateUserControlBase : UserControl, IPostBackDataHandler { /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public bool IsTrue { get; set; } /// <exclude /> public string FormControlLabel { get; set; } /// <exclude /> public string TrueLabel { get; set; } /// <exclude /> public string FalseLabel { get; set; } /// <exclude /> public EventHandler SelectionChangedEventHandler { get; set; } /// <summary> /// When implemented by a class, processes postback data for an ASP.NET server control. /// </summary> /// <param name="postDataKey"></param> /// <param name="postCollection"></param> /// <returns></returns> public virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) { return false; } /// <summary> /// When implemented by a class, signals the server control to notify the ASP.NET application that the state of the control has changed. /// </summary> public virtual void RaisePostDataChangedEvent() { } } internal sealed class TemplatedBoolSelectorUiControl : BoolSelectorUiControl, IWebUiControl { private readonly Type _userControlType; private BoolSelectorTemplateUserControlBase _userControl; internal TemplatedBoolSelectorUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.IsTrue = _userControl.IsTrue; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<BoolSelectorTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.IsTrue = this.IsTrue; _userControl.TrueLabel = this.TrueLabel; _userControl.FalseLabel = this.FalseLabel; _userControl.SelectionChangedEventHandler += this.SelectionChangedEventHandler; return _userControl; } public bool IsFullWidthControl => false; public string ClientName => _userControl.GetDataFieldClientName(); } [ConfigurationElementType(typeof(TemplatedBoolSelectorUiControlFactoryData))] internal sealed class TemplatedBoolSelectorUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedBoolSelectorUiControlFactory(TemplatedBoolSelectorUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { var control = new TemplatedBoolSelectorUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedBoolSelectorUiControlFactoryAssembler))] internal sealed class TemplatedBoolSelectorUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedBoolSelectorUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedBoolSelectorUiControlFactory(objectConfiguration as TemplatedBoolSelectorUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedButtonUiControlFactory.cs ================================================ using System; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ButtonTemplateUserControlBase : UserControl { private string _formControlLabel; private EventHandler _clickEventHandler; /// <exclude /> public EventHandler FormControlClickEventHandler { get { return _clickEventHandler; } set { _clickEventHandler = value; } } /// <exclude /> public string FormControlLabel { get { return _formControlLabel; } set { _formControlLabel = value; } } } internal sealed class TemplatedButtonUiControl : ButtonUiControl, IWebUiControl { private Type _userControlType; internal TemplatedButtonUiControl(Type userControlType) { _userControlType = userControlType; } public void InitializeViewState() { } public Control BuildWebControl() { ButtonTemplateUserControlBase userControl = _userControlType.ActivateAsUserControl<ButtonTemplateUserControlBase>(this.UiControlID); userControl.FormControlLabel = this.Label; userControl.FormControlClickEventHandler += this.ClickEventHandler; return userControl; } public bool IsFullWidthControl { get { return false; } } public string ClientName { get { return null; } } } [ConfigurationElementType(typeof(TemplatedButtonUiControlFactoryData))] internal sealed class TemplatedButtonUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedButtonUiControlFactory(TemplatedButtonUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { TemplatedButtonUiControl control = new TemplatedButtonUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedButtonUiControlFactoryAssembler))] internal sealed class TemplatedButtonUiControlFactoryData : ButtonUiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedButtonUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedButtonUiControlFactory(objectConfiguration as TemplatedButtonUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedCheckBoxUiControlFactory.cs ================================================ using System; using System.Collections.Specialized; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class CheckBoxTemplateUserControlBase : UserControl, IPostBackDataHandler { /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public bool Checked { get; set; } /// <exclude /> public string FormControlLabel { get; set; } /// <exclude /> public string ItemLabel { get; set; } /// <exclude /> public EventHandler CheckedChangedEventHandler { get; set; } /// <summary> /// When implemented by a class, processes postback data for an ASP.NET server control. /// </summary> /// <param name="postDataKey"></param> /// <param name="postCollection"></param> /// <returns></returns> public virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) { return false; } /// <summary> /// When implemented by a class, signals the server control to notify the ASP.NET application that the state of the control has changed. /// </summary> public virtual void RaisePostDataChangedEvent() { } } internal sealed class TemplatedCheckBoxUiControl : CheckBoxUiControl, IWebUiControl { private readonly Type _userControlType; private CheckBoxTemplateUserControlBase _userControl; internal TemplatedCheckBoxUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.Checked = _userControl.Checked; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<CheckBoxTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.Checked = this.Checked; _userControl.ItemLabel = this.ItemLabel; _userControl.CheckedChangedEventHandler += this.CheckedChangedEventHandler; return _userControl; } public bool IsFullWidthControl => false; public string ClientName => _userControl.GetDataFieldClientName(); } [ConfigurationElementType(typeof(TemplatedCheckBoxUiControlFactoryData))] internal sealed class TemplatedCheckBoxUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedCheckBoxUiControlFactory(TemplatedCheckBoxUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { var control = new TemplatedCheckBoxUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedCheckBoxUiControlFactoryAssembler))] internal sealed class TemplatedCheckBoxUiControlFactoryData : CheckBoxUiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedCheckBoxUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedCheckBoxUiControlFactory(objectConfiguration as TemplatedCheckBoxUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedContainerUiControlFactory.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web.UI; using Composite.Core; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// Use this as base type for User Controls that render a Forms UiControl Container. /// Access details about child elements through the FormControlDefinitions property. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ContainerTemplateUserControlBase : UserControl { private readonly List<FormControlDefinition> _formControlDefinitions = new List<FormControlDefinition>(); private readonly Dictionary<string, object> _settings = new Dictionary<string, object>(); internal List<LazyLoadedContainerInfo> LazyLoadedChildControlIDs { get; set; } /// <exclude /> public string Label { get; set; } /// <exclude /> public string Help { get; set; } /// <exclude /> public int PreSelectedIndex { get; set; } /// <exclude /> public Dictionary<string, object> Settings { get { return _settings; } } /// <exclude /> public List<FormControlDefinition> FormControlDefinitions { get { return _formControlDefinitions; } } internal void AddFormControlDefinition(string label, Control formControl, string help, bool isFullWidthControl) { if (label == null) label = ""; string toolTip = label; var definition = new FormControlDefinition(label, toolTip, formControl, help, isFullWidthControl); _formControlDefinitions.Add(definition); } /// <exclude /> protected void RegisterLazyChildControl(int childIndex, string postBackName) { if (this.LazyLoadedChildControlIDs == null) { this.LazyLoadedChildControlIDs = new List<LazyLoadedContainerInfo>(); } this.LazyLoadedChildControlIDs.Add(new LazyLoadedContainerInfo { ChildIndex = childIndex, PostBackName = postBackName }); } #region support classes /// <exclude /> public class FormControlDefinition { private string _label; private string _toolTip; private Control _formControl; private string _help; private bool _isFullWidthControl; internal FormControlDefinition(string label, string toolTip, Control formControl, string help, bool isFullWidthControl) { _label = label ?? ""; _toolTip = toolTip; _formControl = formControl; _help = help; _isFullWidthControl = isFullWidthControl; } /// <exclude /> public bool IsFullWidthControl { get { return _isFullWidthControl; } } /// <exclude /> public string Help { get { return _help; } } /// <exclude /> public string ToolTip { get { return _toolTip; } } /// <exclude /> public string Label { get { return _label; } } /// <exclude /> public Control FormControl { get { return _formControl; } } } internal class LazyLoadedContainerInfo { public int ChildIndex { get; set; } public string PostBackName { get; set; } } #endregion } internal sealed class TemplatedTabbedContainerUiControl : TemplatedContainerUiControl, ITabbedContainerUiControl { internal TemplatedTabbedContainerUiControl(Type userControlType) : base( userControlType ) { this.PreSelectedIndex = 0; } [FormsProperty()] public int PreSelectedIndex { get; set; } } internal class TemplatedContainerUiControl : ContainerUiControlBase, IWebUiControl { private Type _userControlType; private ContainerTemplateUserControlBase _userControl; internal TemplatedContainerUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { int childIndex = 0; foreach (IUiControl childControl in this.UiControls) { if (ControlIsActive(childIndex)) { childControl.BindStateToControlProperties(); } else { IWebUiControl childWebUIControl = (childControl as IWebUiControl); Verify.IsNotNull(childWebUIControl, "Child control has to inherit '{0}' interface", typeof(IWebUiControl).FullName); childWebUIControl.InitializeViewState(); } childIndex++; } } private bool ControlIsActive(int childIndex) { if (_userControl.LazyLoadedChildControlIDs != null) { var lazyInfo = _userControl.LazyLoadedChildControlIDs.FirstOrDefault(f => f.ChildIndex == childIndex); if (lazyInfo != null) { string lazyContainerActivated = _userControl.Request[lazyInfo.PostBackName]; if (lazyContainerActivated == "false") { return false; } if (lazyContainerActivated != "true") { Log.LogWarning("UiControlContainer", "Posibility of data corruption detected. Unexpected lazy bound state information from client. Expected 'true' or 'false', got '{0}' for post back field '{1}'. Will try to bind on child controls.", lazyContainerActivated, lazyInfo.PostBackName); } } } return true; } public void InitializeViewState() { foreach (IUiControl tab in this.UiControls) { IWebUiControl WebUiChild = tab as IWebUiControl; WebUiChild.InitializeViewState(); } } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<ContainerTemplateUserControlBase>(this.UiControlID); _userControl.Label = this.Label; _userControl.Help = this.Help; if (this is ITabbedContainerUiControl) { _userControl.PreSelectedIndex = ((ITabbedContainerUiControl)this).PreSelectedIndex; } else { _userControl.PreSelectedIndex = -1; } foreach (IUiControl tab in this.UiControls) { IWebUiControl WebUiChild = tab as IWebUiControl; Control WebChild = WebUiChild.BuildWebControl(); _userControl.AddFormControlDefinition(tab.Label, WebChild, tab.Help, WebUiChild.IsFullWidthControl); } return _userControl; } public bool IsFullWidthControl { get; internal set; } public string ClientName { get { return null; } } public override void InitializeLazyBindedControls() { int childIndex = 0; foreach (IUiControl childControl in this.UiControls) { if (ControlIsActive(childIndex)) { if (childControl is TemplatedContainerUiControl) { (childControl as TemplatedContainerUiControl).InitializeLazyBindedControls(); } } else { IWebUiControl childWebUIControl = (childControl as IWebUiControl); Verify.IsNotNull(childWebUIControl, "Child control has to inherit '{0}' interface", typeof(IWebUiControl).FullName); childWebUIControl.InitializeViewState(); } childIndex++; } } } [ConfigurationElementType(typeof(TemplatedContainerUiControlFactoryData))] internal sealed class TemplatedContainerUiControlFactory : Base.BaseTemplatedUiControlFactory { private TemplatedContainerUiControlFactoryData _data; public TemplatedContainerUiControlFactory(TemplatedContainerUiControlFactoryData data) : base(data) { _data = data; } public override IUiControl CreateControl() { TemplatedContainerUiControl control; if (_data.IsTabbedContainer) { control = new TemplatedTabbedContainerUiControl(this.UserControlType); } else { control = new TemplatedContainerUiControl(this.UserControlType); } control.IsFullWidthControl = _data.IsFullWidthControl; return control; } } [Assembler(typeof(TemplatedContainerUiControlFactoryAssembler))] internal sealed class TemplatedContainerUiControlFactoryData : ContainerUiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; private const string _isTabbedContainerPropertyName = "IsTabbedContainer"; private const string _isFullWidthControlPropertyName = "IsFullWidthControl"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } [ConfigurationProperty(_isTabbedContainerPropertyName, IsRequired = false, DefaultValue = false)] public bool IsTabbedContainer { get { return (bool)base[_isTabbedContainerPropertyName]; } set { base[_isTabbedContainerPropertyName] = value; } } [ConfigurationProperty(_isFullWidthControlPropertyName, IsRequired = false, DefaultValue = false)] public bool IsFullWidthControl { get { return (bool)base[_isFullWidthControlPropertyName]; } set { base[_isFullWidthControlPropertyName] = value; } } } internal sealed class TemplatedContainerUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedContainerUiControlFactory(objectConfiguration as TemplatedContainerUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedDataReferenceSelectorUiControlFactory.cs ================================================ using System; using System.Configuration; using System.Web.UI; using Composite.Data; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Composite.Plugins.Forms.WebChannel.UiControlFactories.Base; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class DataReferenceSelectorTemplateUserControlBase : UserControlBase { /// <exclude /> public IDataReference Selected { get; set; } /// <exclude /> public Type DataType { get; set; } } internal sealed class TemplatedDataReferenceSelectorUiControl : DataReferenceSelectorUiControl, IWebUiControl { private Type _userControlType; private DataReferenceSelectorTemplateUserControlBase _userControl; internal TemplatedDataReferenceSelectorUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.Selected = _userControl.Selected; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<DataReferenceSelectorTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.Selected = this.Selected as IDataReference; _userControl.DataType = this.DataType; return _userControl; } public bool IsFullWidthControl { get { return false; } } public string ClientName { get { return _userControl.GetDataFieldClientName(); } } } [ConfigurationElementType(typeof(TemplatedDataReferenceSelectorUiControlFactoryData))] internal sealed class TemplatedDataReferenceSelectorUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedDataReferenceSelectorUiControlFactory(TemplatedDataReferenceSelectorUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { TemplatedDataReferenceSelectorUiControl control = new TemplatedDataReferenceSelectorUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedDataReferenceSelectorUiControlFactoryAssembler))] internal sealed class TemplatedDataReferenceSelectorUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedDataReferenceSelectorUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedDataReferenceSelectorUiControlFactory(objectConfiguration as TemplatedDataReferenceSelectorUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedDataReferenceTreeSelectorUiControlFactory.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Web.UI; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Composite.Plugins.Forms.WebChannel.UiControlFactories.Base; using Composite.Data.Validation.ClientValidationRules; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class DataReferenceTreeSelectorTemplateUserControlBase : UserControlBase { /// <exclude /> public string Selected { get; set; } /// <exclude /> public Type DataType { get; set; } /// <exclude /> public bool NullValueAllowed { get; set; } /// <summary> /// Defines which kind of dialog and data provider elements are to be shown /// </summary> public string Handle { get; set; } /// <exclude /> public string SearchToken { get; set; } /// <exclude /> public string RootEntityToken { get; set; } /// <exclude /> public List<ClientValidationRule> ClientValidationRules { get; set; } } internal sealed class TemplatedDataReferenceTreeSelectorUiControl : DataReferenceTreeSelectorUiControl, IWebUiControl { private Type _userControlType; private DataReferenceTreeSelectorTemplateUserControlBase _userControl; internal TemplatedDataReferenceTreeSelectorUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.Selected = _userControl.Selected; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<DataReferenceTreeSelectorTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.Selected = this.Selected; _userControl.NullValueAllowed = this.NullValueAllowed; _userControl.DataType = this.DataType; _userControl.Handle = this.Handle; _userControl.SearchToken = this.SearchToken; _userControl.RootEntityToken = this.RootEntityToken; _userControl.ClientValidationRules = this.ClientValidationRules; return _userControl; } public bool IsFullWidthControl { get { return false; } } public string ClientName { get { return _userControl.GetDataFieldClientName(); } } } [ConfigurationElementType(typeof(TemplatedDataReferenceTreeSelectorUiControlFactoryData))] internal sealed class TemplatedDataReferenceTreeSelectorUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedDataReferenceTreeSelectorUiControlFactory(TemplatedDataReferenceTreeSelectorUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { TemplatedDataReferenceTreeSelectorUiControl control = new TemplatedDataReferenceTreeSelectorUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedDataReferenceTreeSelectorUiControlFactoryAssembler))] internal sealed class TemplatedDataReferenceTreeSelectorUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedDataReferenceTreeSelectorUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedDataReferenceTreeSelectorUiControlFactory(objectConfiguration as TemplatedDataReferenceTreeSelectorUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedDateTimeSelectorUiControlFactory.cs ================================================ using System; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class DateTimeSelectorTemplateUserControlBase : UserControl { private string _formControlLabel; private DateTime? _date; /// <exclude /> public abstract void BindStateToProperties(); /// <exclude /> public abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public DateTime? Date { get { return _date; } set { _date = value; } } /// <exclude /> public bool IsValid { get; set; } /// <exclude /> public string ValidationError { get; set; } /// <exclude /> public bool ReadOnly { get; set; } /// <exclude /> public bool ShowHours { get; set; } /// <exclude /> public bool Required { get; set; } /// <exclude /> public string FormControlLabel { get { return _formControlLabel; } set { _formControlLabel = value; } } } internal sealed class TemplatedDateTimeSelectorUiControl : DateTimeSelectorUiControl, IWebUiControl, IValidatingUiControl { private readonly Type _userControlType; private DateTimeSelectorTemplateUserControlBase _userControl; internal TemplatedDateTimeSelectorUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.Date = _userControl.Date; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<DateTimeSelectorTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.Date = this.Date; _userControl.ReadOnly = this.ReadOnly; _userControl.ShowHours = this.ShowHours; _userControl.IsValid = true; _userControl.Required = this.Required; return _userControl; } public bool IsFullWidthControl => false; public string ClientName => _userControl.GetDataFieldClientName(); public bool IsValid => _userControl.IsValid; public bool ShowHours { get; set; } public string ValidationError => _userControl.ValidationError; } [ConfigurationElementType(typeof(TemplatedDateTimeSelectorUiControlFactoryData))] internal sealed class TemplatedDateTimeSelectorUiControlFactory : Base.BaseTemplatedUiControlFactory { private readonly bool _showHours; public TemplatedDateTimeSelectorUiControlFactory(TemplatedDateTimeSelectorUiControlFactoryData data) : base(data) { _showHours = data.ShowHours; } public override IUiControl CreateControl() { return new TemplatedDateTimeSelectorUiControl(this.UserControlType) { ShowHours = _showHours }; } } [Assembler(typeof(TemplatedDateTimeSelectorUiControlFactoryAssembler))] internal sealed class TemplatedDateTimeSelectorUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; private const string _showHoursPropertyName = "showHours"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } [ConfigurationProperty(_showHoursPropertyName, IsRequired = true)] public bool ShowHours { get { return (bool)base[_showHoursPropertyName]; } set { base[_showHoursPropertyName] = value; } } } internal sealed class TemplatedDateTimeSelectorUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedDateTimeSelectorUiControlFactory(objectConfiguration as TemplatedDateTimeSelectorUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedDoubleSelectorUiControlFactory.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; using Composite.C1Console.Forms.Foundation; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class TemplatedDoubleKeySelectorUserControlBase : UserControl { private List<KeyLabelPair> _options = null; /// <exclude /> public object FirstKey { get; set; } /// <exclude /> public object SecondKey { get; set; } /// <exclude /> public IEnumerable<Tuple<object, object, string>> Options { get; set; } /// <exclude /> public bool Required { get; set; } /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void InitializeWebViewState() { this.InitializeViewState(); } internal void BindStateToControlProperties() { this.BindStateToProperties(); } /// <exclude /> protected List<KeyLabelPair> GetOptions() { if (_options == null) { _options = new List<KeyLabelPair>(); foreach (var tuple in Options) { _options.Add(new KeyLabelPair(GetKey(tuple), tuple.Item3)); } } return _options; } /// <exclude /> protected string GetKey(Tuple<object, object, string> tuple) { return GetKey(tuple.Item1, tuple.Item2); } /// <exclude /> protected string GetKey(object firstKey, object secondKey) { return (firstKey ?? "null") + "|" + (secondKey ?? "null"); } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class TemplatedDoubleKeySelectorUiControl : UiControl, IWebUiControl { private Type _userControlType; private TemplatedDoubleKeySelectorUserControlBase _userControl; /// <exclude /> [BindableProperty] public object FirstKey { get; set; } /// <exclude /> [BindableProperty] public object SecondKey { get; set; } /// <exclude /> [FormsProperty] public IEnumerable<Tuple<object, object, string>> Options { get; set; } /// <exclude /> [FormsProperty] public bool Required { get; set; } /*[BindableProperty()] [FormsProperty()] public object Selected { get; set; }*/ /// <exclude /> public TemplatedDoubleKeySelectorUiControl(Type userControlType) { _userControlType = userControlType; } /// <exclude /> public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); FirstKey = _userControl.FirstKey; SecondKey = _userControl.SecondKey; } /// <exclude /> public void InitializeViewState() { _userControl.InitializeWebViewState(); } /// <exclude /> public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<TemplatedDoubleKeySelectorUserControlBase>(this.UiControlID); _userControl.FirstKey = this.FirstKey; _userControl.SecondKey = this.SecondKey; _userControl.Options = this.Options; _userControl.Required = this.Required; return _userControl; } /// <exclude /> public bool IsFullWidthControl { get { return false; } } /// <exclude /> public string ClientName { get { return _userControl.GetDataFieldClientName(); } } } [ConfigurationElementType(typeof(TemplatedDoubleKeySelectorUiControlFactoryData))] internal sealed class TemplatedDoubleKeySelectorUiControlFactory : Base.BaseTemplatedUiControlFactory { private TemplatedDoubleKeySelectorUiControlFactoryData _data; public TemplatedDoubleKeySelectorUiControlFactory(TemplatedDoubleKeySelectorUiControlFactoryData data) : base(data) { _data = data; } public override IUiControl CreateControl() { return new TemplatedDoubleKeySelectorUiControl(this.UserControlType); } } [Assembler(typeof(TemplatedDoubleKeySelectorUiControlFactoryAssembler))] internal sealed class TemplatedDoubleKeySelectorUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedDoubleKeySelectorUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedDoubleKeySelectorUiControlFactory(objectConfiguration as TemplatedDoubleKeySelectorUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedEnumSelectorUiControlFactory.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class EnumSelectorTemplateUserControlBase : UserControl { private string _formControlLabel; private string _selected; private TemplatedEnumSelectorUiControl _typeOptionsProxy; /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } internal void SetTypeOptionsProxy(TemplatedEnumSelectorUiControl proxy) { _typeOptionsProxy = proxy; } /// <exclude /> public string Selected { get { return _selected; } set { _selected = value; } } /// <exclude /> public string FormControlLabel { get { return _formControlLabel; } set { _formControlLabel = value; } } /// <exclude /> public IEnumerable<string> Options { get { return _typeOptionsProxy.FetchOptions(); } } } internal sealed class TemplatedEnumSelectorUiControl : EnumSelectorUiControl, IWebUiControl { private Type _userControlType; private EnumSelectorTemplateUserControlBase _userControl; internal TemplatedEnumSelectorUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.Selected = _userControl.Selected; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<EnumSelectorTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.Selected = this.Selected; _userControl.SetTypeOptionsProxy(this); return _userControl; } internal IEnumerable<string> FetchOptions() { return Enum.GetNames(base.EnumType); } public bool IsFullWidthControl { get { return false; } } public string ClientName { get { return _userControl.GetDataFieldClientName(); } } } [ConfigurationElementType(typeof(TemplatedEnumSelectorUiControlFactoryData))] internal sealed class TemplatedEnumSelectorUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedEnumSelectorUiControlFactory(TemplatedEnumSelectorUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { TemplatedEnumSelectorUiControl control = new TemplatedEnumSelectorUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedEnumSelectorUiControlFactoryAssembler))] internal sealed class TemplatedEnumSelectorUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedEnumSelectorUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedEnumSelectorUiControlFactory(objectConfiguration as TemplatedEnumSelectorUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedFileUploadUiControlFactory.cs ================================================ using System; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class FileUploadTemplateUserControlBase : UserControl { /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public UploadedFile UploadedFile { get; set; } /// <exclude /> public string FormControlLabel { get; set; } } internal sealed class TemplatedFileUploadUiControl : FileUploadUiControl, IWebUiControl { private Type _userControlType; private FileUploadTemplateUserControlBase _userControl; internal TemplatedFileUploadUiControl(Type userControlType) { _userControlType = userControlType; } /// <exclude /> public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.UploadedFile = _userControl.UploadedFile; } /// <exclude /> public void InitializeViewState() { _userControl.InitializeWebViewState(); } /// <exclude /> public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<FileUploadTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.UploadedFile = this.UploadedFile; return _userControl; } /// <exclude /> public bool IsFullWidthControl { get { return false; } } /// <exclude /> public string ClientName { get { return _userControl.GetDataFieldClientName(); } } } [ConfigurationElementType(typeof(TemplatedFileUploadUiControlFactoryData))] internal sealed class TemplatedFileUploadUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedFileUploadUiControlFactory(TemplatedFileUploadUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { TemplatedFileUploadUiControl control = new TemplatedFileUploadUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedFileUploadUiControlFactoryAssembler))] internal sealed class TemplatedFileUploadUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedFileUploadUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedFileUploadUiControlFactory(objectConfiguration as TemplatedFileUploadUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedFontIconSelectorUiControlFactory.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Composite.Data.Validation.ClientValidationRules; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class FontIconSelectorTemplateUserControlBase : UserControl { /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public string SelectedClassName { get; set; } /// <exclude /> public Dictionary<string,string> ClassNameOptions { get; set; } /// <exclude /> public string ClassNamePrefix { get; set; } /// <exclude /> public string StylesheetPath { get; set; } /// <exclude /> public string FormControlLabel { get; set; } /// <exclude /> public bool Required { get; set; } /// <exclude /> public List<ClientValidationRule> ClientValidationRules { get; set; } } internal sealed class TemplatedFontIconSelectorUiControl : FontIconSelectorUiControl, IWebUiControl { private Type _userControlType; private FontIconSelectorTemplateUserControlBase _userControl; internal TemplatedFontIconSelectorUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.SelectedClassName = _userControl.SelectedClassName; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<FontIconSelectorTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.SelectedClassName = this.SelectedClassName; _userControl.ClientValidationRules = this.ClientValidationRules; _userControl.StylesheetPath = this.StylesheetPath; _userControl.ClassNamePrefix = this.ClassNamePrefix; _userControl.Required = this.Required; if (this.ClassNameOptions is string) { _userControl.ClassNameOptions = ((string)this.ClassNameOptions).Split(',').ToDictionary(f=>f); } else { if (this.ClassNameOptions is IEnumerable<string>) { _userControl.ClassNameOptions = ((IEnumerable<string>)this.ClassNameOptions).ToDictionary(f => f); } else { if (this.ClassNameOptions is Dictionary<string,string>) { _userControl.ClassNameOptions = (Dictionary<string, string>)this.ClassNameOptions; } else { throw new NotImplementedException("ClassNameOptions should be either a (comma seperated) string, a IEnumerable<string> or a Dictionary<string,string>."); } } } return _userControl; } public bool IsFullWidthControl { get { return false; } } public string ClientName { get { return _userControl.GetDataFieldClientName(); } } } [ConfigurationElementType(typeof(TemplatedFontIconSelectorUiControlFactoryData))] internal sealed class TemplatedFontIconSelectorUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedFontIconSelectorUiControlFactory(TemplatedFontIconSelectorUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { TemplatedFontIconSelectorUiControl control = new TemplatedFontIconSelectorUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedFontIconSelectorUiControlFactoryAssembler))] internal sealed class TemplatedFontIconSelectorUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedFontIconSelectorUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedFontIconSelectorUiControlFactory(objectConfiguration as TemplatedFontIconSelectorUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedFunctionParameterDesignerUiControlFactory.cs ================================================ using System; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class FunctionParameterDesignerTemplateUserControlBase : UserControl { /// <exclude /> public abstract string SessionStateProvider { get; set; } /// <exclude /> public abstract Guid SessionStateId { get; set; } } internal sealed class TemplatedFunctionParameterDesignerUiControl : FunctionParameterDesignerUiControl, IWebUiControl { private Type _userControlType; private FunctionParameterDesignerTemplateUserControlBase _userControl; private string _sessionStateProvider; private Guid _sessionStateId; internal TemplatedFunctionParameterDesignerUiControl(Type userControlType) { _userControlType = userControlType; } public void InitializeViewState() { } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<FunctionParameterDesignerTemplateUserControlBase>(this.UiControlID); _userControl.SessionStateProvider = _sessionStateProvider; _userControl.SessionStateId = _sessionStateId; return _userControl; } public override string SessionStateProvider { get { return _sessionStateProvider; } set { _sessionStateProvider = value; } } public override Guid SessionStateId { get { return _sessionStateId; } set { _sessionStateId = value; } } public bool IsFullWidthControl { get { return true; } } public string ClientName { get { return null; /* _userControl.GetDataFieldClientName(); */ } } } [ConfigurationElementType(typeof(TemplatedFunctionParameterDesignerUiControlFactoryData))] internal sealed class TemplatedFunctionParameterDesignerUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedFunctionParameterDesignerUiControlFactory(TemplatedFunctionParameterDesignerUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { return new TemplatedFunctionParameterDesignerUiControl(this.UserControlType); } } [Assembler(typeof(TemplatedFunctionParameterDesignerUiControlFactoryAssembler))] internal sealed class TemplatedFunctionParameterDesignerUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedFunctionParameterDesignerUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedFunctionParameterDesignerUiControlFactory(objectConfiguration as TemplatedFunctionParameterDesignerUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedHeadingUiControlFactory.cs ================================================ using System; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class HeadingTemplateUserControlBase : UserControl { private string _formControlLabel; /// <exclude /> protected abstract void InitializeViewState(); internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public string Title { get; set; } /// <exclude /> public string Description { get; set; } /// <exclude /> public string FormControlLabel { get { return _formControlLabel; } set { _formControlLabel = value; } } } internal sealed class TemplatedHeadingUiControl : HeadingUiControl, IWebUiControl { private Type _userControlType; private HeadingTemplateUserControlBase _userControl; internal TemplatedHeadingUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<HeadingTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.Title = this.Title; _userControl.Description = this.Description; return _userControl; } public bool IsFullWidthControl { get { return false; } } public string ClientName { get { return null; } } } [ConfigurationElementType(typeof(TemplatedHeadingUiControlFactoryData))] internal sealed class TemplatedHeadingUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedHeadingUiControlFactory(TemplatedHeadingUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { TemplatedHeadingUiControl control = new TemplatedHeadingUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedHeadingUiControlFactoryAssembler))] internal sealed class TemplatedHeadingUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedHeadingUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext conHeading, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedHeadingUiControlFactory(objectConfiguration as TemplatedHeadingUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedHierarchicalSelectorUiControlFactory.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class HierarchicalSelectorTemplateUserControlBase : UserControl { /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public IEnumerable<object> SelectedKeys { get; set; } /// <exclude /> public IEnumerable<SelectionTreeNode> TreeNodes { get; set; } /// <exclude /> public bool AutoSelectChildren { get; set; } /// <exclude /> public bool AutoSelectParents { get; set; } /// <exclude /> public bool Required { get; set; } } internal sealed class TemplatedHierarchicalSelectorUiControl : HierarchicalSelectorUiControl, IWebUiControl { private readonly Type _userControlType; private HierarchicalSelectorTemplateUserControlBase _userControl; internal TemplatedHierarchicalSelectorUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.SelectedKeys = _userControl.SelectedKeys; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<HierarchicalSelectorTemplateUserControlBase>(this.UiControlID); _userControl.SelectedKeys = this.SelectedKeys; _userControl.TreeNodes = this.TreeNodes; _userControl.AutoSelectChildren = this.AutoSelectChildren; _userControl.AutoSelectParents = this.AutoSelectParents; _userControl.Required = this.Required; return _userControl; } public bool IsFullWidthControl => false; public string ClientName => _userControl.GetDataFieldClientName(); } [ConfigurationElementType(typeof(TemplatedHierarchicalSelectorUiControlFactoryData))] internal sealed class TemplatedHierarchicalSelectorUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedHierarchicalSelectorUiControlFactory(TemplatedHierarchicalSelectorUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { var control = new TemplatedHierarchicalSelectorUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedHierarchicalSelectorUiControlFactoryAssembler))] internal sealed class TemplatedHierarchicalSelectorUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedHierarchicalSelectorUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedHierarchicalSelectorUiControlFactory( objectConfiguration as TemplatedHierarchicalSelectorUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedHtmlBlobUiControlFactory.cs ================================================ using System; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class HtmlBlobTemplateUserControlBase : UserControl { private string _html; /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public string Html { get { return _html; } set { _html = value; } } } internal sealed class TemplatedHtmlBlobUiControl : HtmlBlobUiControl, IWebUiControl { private Type _userControlType; private HtmlBlobTemplateUserControlBase _userControl; internal TemplatedHtmlBlobUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.Html = _userControl.Html; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<HtmlBlobTemplateUserControlBase>(this.UiControlID); _userControl.Html = this.Html; return _userControl; } public bool IsFullWidthControl { get { return true; } } public string ClientName { get { return null; } } } [ConfigurationElementType(typeof(TemplatedHtmlBlobUiControlFactoryData))] internal sealed class TemplatedHtmlBlobUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedHtmlBlobUiControlFactory(TemplatedHtmlBlobUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { TemplatedHtmlBlobUiControl control = new TemplatedHtmlBlobUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedHtmlBlobUiControlFactoryAssembler))] internal sealed class TemplatedHtmlBlobUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedHtmlBlobUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedHtmlBlobUiControlFactory(objectConfiguration as TemplatedHtmlBlobUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedInfoTableUiControlFactory.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class InfoTableTemplateUserControlBase : UserControl { /// <exclude /> protected abstract void InitializeViewState(); internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public List<string> Headers { get; set; } /// <exclude /> public List<List<string>> Rows { get; set; } /// <exclude /> public string Caption { get; set; } /// <exclude /> public bool Border { get; set; } /// <exclude /> public string FormControlLabel { get; set; } } internal sealed class TemplatedInfoTableUiControl : InfoTableUiControl, IWebUiControl { private Type _userControlType; private InfoTableTemplateUserControlBase _userControl; internal TemplatedInfoTableUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<InfoTableTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.Headers = this.Headers; _userControl.Rows = this.Rows; _userControl.Caption = this.Caption; _userControl.Border = this.Border; return _userControl; } public bool IsFullWidthControl { get { return false; } } public string ClientName { get { return null; } } } [ConfigurationElementType(typeof(TemplatedInfoTableUiControlFactoryData))] internal sealed class TemplatedInfoTableUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedInfoTableUiControlFactory(TemplatedInfoTableUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { TemplatedInfoTableUiControl control = new TemplatedInfoTableUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedInfoTableUiControlFactoryAssembler))] internal sealed class TemplatedInfoTableUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedInfoTableUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedInfoTableUiControlFactory(objectConfiguration as TemplatedInfoTableUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedMultiContentXhtmlEditorUiControlFactory.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Core.WebClient; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class MultiContentXhtmlEditorTemplateUserControlBase : UserControl { /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public string DefaultPlaceholderId { get; set; } /// <exclude /> public Dictionary<string, string> PlaceholderDefinitions { get; set; } /// <exclude /> public Dictionary<string, string> PlaceholderContainerClasses { get; set; } /// <exclude /> public Dictionary<string,string> NamedXhtmlFragments { get; set; } /// <exclude /> public string FormControlLabel { get; set; } /// <exclude /> public IEnumerable<Type> EmbedableFieldsTypes { get; set; } /// <exclude /> public string ClassConfigurationName { get; set; } } internal sealed class TemplatedMultiContentXhtmlEditorUiControl : MultiContentXhtmlEditorUiControl, IWebUiControl { private Type _userControlType; private MultiContentXhtmlEditorTemplateUserControlBase _userControl; internal TemplatedMultiContentXhtmlEditorUiControl(Type userControlType) { _userControlType = userControlType; this.NamedXhtmlFragments = new Dictionary<string, string>(); this.PlaceholderDefinitions = new Dictionary<string, string>(); this.PlaceholderContainerClasses = new Dictionary<string, string>(); } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.NamedXhtmlFragments = _userControl.NamedXhtmlFragments; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<MultiContentXhtmlEditorTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.EmbedableFieldsTypes = this.EmbedableFieldsTypes; _userControl.DefaultPlaceholderId = this.DefaultPlaceholderId; _userControl.PlaceholderDefinitions = this.PlaceholderDefinitions; _userControl.PlaceholderContainerClasses = this.PlaceholderContainerClasses; _userControl.NamedXhtmlFragments = this.NamedXhtmlFragments; _userControl.ClassConfigurationName = this.ClassConfigurationName; return _userControl; } public bool IsFullWidthControl { get { return true; } } public string ClientName { get { return _userControl.GetDataFieldClientName(); } } } [ConfigurationElementType(typeof(TemplatedMultiContentXhtmlEditorUiControlFactoryData))] internal sealed class TemplatedMultiContentXhtmlEditorUiControlFactory : IUiControlFactory { private TemplatedMultiContentXhtmlEditorUiControlFactoryData _data; private Type _cachedUserControlType = null; public TemplatedMultiContentXhtmlEditorUiControlFactory(TemplatedMultiContentXhtmlEditorUiControlFactoryData data) { _data = data; if (_data.CacheCompiledUserControlType) { _cachedUserControlType = BuildManagerHelper.GetCompiledType(_data.UserControlVirtualPath); } } public IUiControl CreateControl() { Type userControlType = _cachedUserControlType; if (userControlType == null && System.Web.HttpContext.Current!=null) { userControlType = BuildManagerHelper.GetCompiledType(_data.UserControlVirtualPath); } TemplatedMultiContentXhtmlEditorUiControl control = new TemplatedMultiContentXhtmlEditorUiControl(userControlType); control.ClassConfigurationName = _data.ClassConfigurationName; return control; } } [Assembler(typeof(TemplatedMultiContentXhtmlEditorUiControlFactoryAssembler))] internal sealed class TemplatedMultiContentXhtmlEditorUiControlFactoryData : UiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } private const string _classConfigurationNamePropertyName = "ClassConfigurationName"; [ConfigurationProperty(_classConfigurationNamePropertyName, IsRequired = false, DefaultValue = "common")] public string ClassConfigurationName { get { return (string)base[_classConfigurationNamePropertyName]; } set { base[_classConfigurationNamePropertyName] = value; } } } internal sealed class TemplatedMultiContentXhtmlEditorUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedMultiContentXhtmlEditorUiControlFactory(objectConfiguration as TemplatedMultiContentXhtmlEditorUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedNamedFunctionCallsDesignerUiControlFactory.cs ================================================ using System; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class FunctionCallsDesignerTemplateUserControlBase : UserControl { /// <exclude /> public abstract string SessionStateProvider { get; set; } /// <exclude /> public abstract Guid SessionStateId { get; set; } } internal sealed class TemplatedFunctionCallsDesignerUiControl : FunctionCallsDesignerUiControl, IWebUiControl { private Type _userControlType; private FunctionCallsDesignerTemplateUserControlBase _userControl; private string _sessionStateProvider; private Guid _sessionStateId; internal TemplatedFunctionCallsDesignerUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { } public void InitializeViewState() { } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<FunctionCallsDesignerTemplateUserControlBase>(this.UiControlID); _userControl.SessionStateProvider = _sessionStateProvider; _userControl.SessionStateId = _sessionStateId; return _userControl; } public override string SessionStateProvider { get { return _sessionStateProvider; } set { _sessionStateProvider = value; } } public override Guid SessionStateId { get { return _sessionStateId; } set { _sessionStateId = value; } } public bool IsFullWidthControl { get { return true; } } public string ClientName { get { return null; /* _userControl.GetDataFieldClientName(); */ } } } [ConfigurationElementType(typeof(TemplatedFunctionCallsDesignerUiControlFactoryData))] internal sealed class TemplatedFunctionCallsDesignerUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedFunctionCallsDesignerUiControlFactory(TemplatedFunctionCallsDesignerUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { TemplatedFunctionCallsDesignerUiControl control = new TemplatedFunctionCallsDesignerUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedFunctionCallsDesignerUiControlFactoryAssembler))] internal sealed class TemplatedFunctionCallsDesignerUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedFunctionCallsDesignerUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedFunctionCallsDesignerUiControlFactory(objectConfiguration as TemplatedFunctionCallsDesignerUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedPageReferenceSelectorUiControlFactory.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Composite.Plugins.Forms.WebChannel.UiControlFactories.Base; using Composite.Data.Validation.ClientValidationRules; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; using Composite.Data.Types; using Composite.Data; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class PageReferenceSelectorTemplateUserControlBase : UserControlBase { private DataReference<IPage> _selected; /// <exclude /> public DataReference<IPage> Selected { get { return _selected; } set { _selected = value; } } /// <exclude /> public List<ClientValidationRule> ClientValidationRules { get; set; } } internal sealed class TemplatedPageReferenceSelectorUiControl : PageReferenceSelectorUiControl, IWebUiControl { private Type _userControlType; private PageReferenceSelectorTemplateUserControlBase _userControl; internal TemplatedPageReferenceSelectorUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.Selected = _userControl.Selected; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<PageReferenceSelectorTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.Selected = this.Selected; _userControl.ClientValidationRules = this.ClientValidationRules; return _userControl; } public bool IsFullWidthControl { get { return false; } } public string ClientName { get { return _userControl.GetDataFieldClientName(); } } } [ConfigurationElementType(typeof(TemplatedPageReferenceSelectorUiControlFactoryData))] internal sealed class TemplatedPageReferenceSelectorUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedPageReferenceSelectorUiControlFactory(TemplatedPageReferenceSelectorUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { TemplatedPageReferenceSelectorUiControl control = new TemplatedPageReferenceSelectorUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedPageReferenceSelectorUiControlFactoryAssembler))] internal sealed class TemplatedPageReferenceSelectorUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedPageReferenceSelectorUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedPageReferenceSelectorUiControlFactory(objectConfiguration as TemplatedPageReferenceSelectorUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedPreviewTabPanelUiControlFactory.cs ================================================ using System; using System.Configuration; using System.Web.UI; using System.Web.UI.WebControls; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// Use this as base type for User Controls that render a Forms UiControl PreviewTabPanel. /// Access details about child elements through the FormControlDefinitions property. /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class PreviewTabPanelTemplateUserControlBase : UserControl, IClickableTabPanelControl { private string _formControlLabel; private EventHandler _clickEventHandler; /// <exclude /> public EventHandler FormControlClickEventHandler { get { return _clickEventHandler; } set { _clickEventHandler = value; } } /// <exclude /> public string FormControlLabel { get { return _formControlLabel; } set { _formControlLabel = value; } } /// <exclude /> public string CustomTabId { get; set; } /// <exclude /> public Control EventControl { get; set; } } internal sealed class TemplatedPreviewTabPanelUiControl : ButtonUiControl, IWebUiControl { private Type _userControlType; private string _clientTabId; internal TemplatedPreviewTabPanelUiControl(Type userControlType, string clientTabId) { _userControlType = userControlType; _clientTabId = clientTabId; } public void InitializeViewState() { } public Control BuildWebControl() { PreviewTabPanelTemplateUserControlBase userControl = _userControlType.ActivateAsUserControl<PreviewTabPanelTemplateUserControlBase>(this.UiControlID); userControl.FormControlLabel = this.Label; userControl.FormControlClickEventHandler += this.ClickEventHandler; userControl.CustomTabId = _clientTabId; LinkButton shadowLinkButton = new LinkButton(); shadowLinkButton.Style.Add( "display", "none" ); shadowLinkButton.ID = "Preview"; shadowLinkButton.Text = "Preview"; shadowLinkButton.Click += this.ClickEventHandler; userControl.EventControl = shadowLinkButton; return userControl; } public bool IsFullWidthControl { get { return true; } } public string ClientName { get { return null; } } } [ConfigurationElementType(typeof(TemplatedPreviewTabPanelUiControlFactoryData))] internal sealed class TemplatedPreviewTabPanelUiControlFactory : Base.BaseTemplatedUiControlFactory { private TemplatedPreviewTabPanelUiControlFactoryData _data; public TemplatedPreviewTabPanelUiControlFactory(TemplatedPreviewTabPanelUiControlFactoryData data) : base(data) { _data = data; } public override IUiControl CreateControl() { TemplatedPreviewTabPanelUiControl control = new TemplatedPreviewTabPanelUiControl(this.UserControlType,_data.ClientTabId); return control; } } [Assembler(typeof(TemplatedPreviewTabPanelUiControlFactoryAssembler))] internal sealed class TemplatedPreviewTabPanelUiControlFactoryData : ButtonUiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _clientTabIdPropertyName = "ClientTabId"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_clientTabIdPropertyName, IsRequired = true)] public string ClientTabId { get { return (string)base[_clientTabIdPropertyName]; } set { base[_clientTabIdPropertyName] = value; } } [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedPreviewTabPanelUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedPreviewTabPanelUiControlFactory(objectConfiguration as TemplatedPreviewTabPanelUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedQueryCallDefinitionsEditorUiControlFactory.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class QueryCallDefinitionsEditorTemplateUserControlBase : UserControl { private string _formControlLabel; /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public IEnumerable<KeyValuePair<string, Guid>> Queries { get; set; } /// <exclude /> public ILookup<string, KeyValuePair<string, string>> Parameters { get; set; } /// <exclude /> public string UserProvidedPreviewXml { get; set; } /// <exclude /> public string FormControlLabel { get { return _formControlLabel; } set { _formControlLabel = value; } } } internal sealed class TemplatedQueryCallDefinitionsEditorUiControl : QueryCallDefinitionsEditorUiControl, IWebUiControl { private Type _userControlType; private QueryCallDefinitionsEditorTemplateUserControlBase _userControl; internal TemplatedQueryCallDefinitionsEditorUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.Queries = _userControl.Queries; this.Parameters = _userControl.Parameters; this.UserProvidedPreviewXml = _userControl.UserProvidedPreviewXml; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<QueryCallDefinitionsEditorTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.Queries = this.Queries; _userControl.Parameters = this.Parameters; return _userControl; } public bool IsFullWidthControl { get { return true; } } public string ClientName { get { return _userControl.GetDataFieldClientName(); } } } [ConfigurationElementType(typeof(TemplatedQueryCallDefinitionsEditorUiControlFactoryData))] internal sealed class TemplatedQueryCallDefinitionsEditorUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedQueryCallDefinitionsEditorUiControlFactory(TemplatedQueryCallDefinitionsEditorUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { TemplatedQueryCallDefinitionsEditorUiControl control = new TemplatedQueryCallDefinitionsEditorUiControl(base.UserControlType); return control; } } [Assembler(typeof(TemplatedQueryCallDefinitionsEditorUiControlFactoryAssembler))] internal sealed class TemplatedQueryCallDefinitionsEditorUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedQueryCallDefinitionsEditorUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedQueryCallDefinitionsEditorUiControlFactory(objectConfiguration as TemplatedQueryCallDefinitionsEditorUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedSaveButtonUiControlFactory.cs ================================================ using System; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class SaveButtonTemplateUserControlBase : UserControl { private string _formControlLabel; private EventHandler _saveEventHandler; private EventHandler _saveAndPublishEventHandler; /// <exclude /> public EventHandler SaveEventHandler { get { return _saveEventHandler; } set { _saveEventHandler = value; } } /// <exclude /> public EventHandler SaveAndPublishEventHandler { get { return _saveAndPublishEventHandler; } set { _saveAndPublishEventHandler = value; } } /// <exclude /> public string FormControlLabel { get { return _formControlLabel; } set { _formControlLabel = value; } } } internal sealed class TemplatedSaveButtonUiControl : SaveButtonUiControl, IWebUiControl { private Type _userControlType; internal TemplatedSaveButtonUiControl(Type userControlType) { _userControlType = userControlType; } public void InitializeViewState() { } public Control BuildWebControl() { SaveButtonTemplateUserControlBase userControl = _userControlType.ActivateAsUserControl<SaveButtonTemplateUserControlBase>(this.UiControlID); userControl.FormControlLabel = this.Label; userControl.SaveEventHandler += this.SaveEventHandler; userControl.SaveAndPublishEventHandler += this.SaveAndPublishEventHandler; return userControl; } public bool IsFullWidthControl { get { return false; } } public string ClientName { get { return null; } } } [ConfigurationElementType(typeof(TemplatedSaveButtonUiControlFactoryData))] internal sealed class TemplatedSaveButtonUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedSaveButtonUiControlFactory(TemplatedSaveButtonUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { TemplatedSaveButtonUiControl control = new TemplatedSaveButtonUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedSaveButtonUiControlFactoryAssembler))] internal sealed class TemplatedSaveButtonUiControlFactoryData : ButtonUiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedSaveButtonUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedSaveButtonUiControlFactory(objectConfiguration as TemplatedSaveButtonUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedSelectorUiControlFactory.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Reflection; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Core.Extensions; using Composite.Plugins.Forms.WebChannel.Foundation; using Composite.Core.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; using System.Xml.Linq; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <exclude /> public class KeyLabelPair { /// <exclude /> public KeyLabelPair(string key, string label) { this.Key = key; this.Label = label; } /// <exclude /> public string Key { get; set; } /// <exclude /> public string Label { get; set; } } ///////////////////////////////// /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class SelectorTemplateUserControlBase : UserControl { private Dictionary<string, object> _selectorObjects; private List<KeyLabelPair> _keyLabelPairList; private List<string> _selectedAsStrings; private const string _noneSelectionKey = "***C1.NONE***"; private const string _noneSelectionLabel = "<NONE>"; /// <summary> /// To be overridden in the controls /// </summary> public abstract void BindStateToProperties(); /// <exclude /> public abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); /// <exclude /> public string FormControlLabel { get; set; } /// <exclude /> public bool Required { get; set; } /// <summary> /// When the selection is not required, the property will define if a "no selection" option should be added. /// </summary> public bool ProvideNoSelectionOption { get; set; } /// <exclude /> public bool CompactMode { get; set; } /// <exclude /> public bool ReadOnly { get; set; } /// <exclude /> public string OptionsKeyField { get; set; } /// <exclude /> public string OptionsLabelField { get; set; } /// <exclude /> public IEnumerable Options { get; set; } internal SelectorBindingType BindingType { get; set; } /// <exclude /> public EventHandler SelectedIndexChangedEventHandler { get; set; } /// <exclude /> public void BindStateToControlProperties() { InitializeSelectorElements(); this.BindStateToProperties(); if (_selectedAsStrings != null) { SetSelectedObjectsFromStringList(_selectedAsStrings); } else { this.SelectedObjects = new List<object>(); ; } } internal void SetSelectedObjectsFromStringList(IEnumerable<string> selectedAsStrings) { Verify.IsFalse(selectedAsStrings.Any(s => s == null), "One of the selected keys is null"); InitializeSelectorElements(); this.SelectedObjects = new List<object>(); bool bindToObject = (this.BindingType == SelectorBindingType.BindToObject) || (this.BindingType == SelectorBindingType.BindToKeyFieldValue && (this.OptionsKeyField == "." || this.OptionsKeyField == "")); if (bindToObject) { foreach (string selectedAsString in selectedAsStrings) { if (_selectorObjects.ContainsKey(selectedAsString)) { this.SelectedObjects.Add(_selectorObjects[selectedAsString]); } else if(selectedAsString != _noneSelectionKey) { // ComboBox this.SelectedObjects.Add(selectedAsString); } } return; } if (this.BindingType == SelectorBindingType.BindToKeyFieldValue) { foreach (string selectedAsString in selectedAsStrings) { if (selectedAsString == _noneSelectionKey) { continue; } if (!_selectorObjects.ContainsKey(selectedAsString)) { // ComboBox SelectedObjects.Add(selectedAsString); continue; } object key; var @object = _selectorObjects[selectedAsString]; if (@object is XElement) { key = (@object as XElement).Attribute(this.OptionsKeyField).Value; } else { PropertyInfo keyPropertyInfo = @object.GetType().GetProperty(this.OptionsKeyField); key = keyPropertyInfo.GetValue(@object, null); } this.SelectedObjects.Add(key); } return; } throw new InvalidOperationException("Unknown binding type"); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public IEnumerable<string> SelectedKeys { get { if (this.SelectedObjects != null && this.SelectedObjects.Count > 0) { _selectedAsStrings = new List<string>(); switch (this.BindingType) { case SelectorBindingType.BindToObject: if (this.OptionsKeyField == "." || this.OptionsKeyField == "") { foreach (object selectedObject in this.SelectedObjects) { _selectedAsStrings.Add(selectedObject.ToString()); } } else { var objectType = this.SelectedObjects.First().GetType(); PropertyInfo keyPropertyInfo = objectType.GetProperty(this.OptionsKeyField); if (keyPropertyInfo == null) { throw new InvalidOperationException($"Malformed Selection configuration. The Selected binding type '{objectType}' does not have a property named '{this.OptionsKeyField}'"); } foreach (object selectedObject in this.SelectedObjects) { string selectedObjectKey = keyPropertyInfo.GetValue(selectedObject, null).ToString(); if (_selectorObjects.ContainsKey(selectedObjectKey)) { _selectedAsStrings.Add(selectedObjectKey); } } } break; case SelectorBindingType.BindToKeyFieldValue: foreach (object selectedObject in this.SelectedObjects) { if (selectedObject != null) _selectedAsStrings.Add(selectedObject.ToString()); } break; default: throw new NotImplementedException("Unknown SelectorBindingType"); } return _selectedAsStrings; } return new List<string>(); } set { _selectedAsStrings = new List<string>(value); } } /// <exclude /> public List<object> SelectedObjects { get; set; } /// <exclude /> protected List<KeyLabelPair> GetOptions() { InitializeSelectorElements(); return _keyLabelPairList; } private void InitializeSelectorElements() { if (_selectorObjects != null) return; if (Options is IEnumerable<XElement>) { Verify.That(OptionsKeyField != "" && OptionsKeyField != ".", "Key attribute name is not defined"); Verify.That(OptionsLabelField != "" && OptionsLabelField != ".", "Label attribute name is not defined"); } else { Verify.IsNotNull(OptionsKeyField, $"{nameof(OptionsKeyField)} is null"); Verify.IsNotNull(OptionsLabelField, $"{nameof(OptionsLabelField)} is null"); } _selectorObjects = new Dictionary<string, object>(); _keyLabelPairList = new List<KeyLabelPair>(); if (!Required && ProvideNoSelectionOption) { _keyLabelPairList.Add(new KeyLabelPair(_noneSelectionKey, _noneSelectionLabel)); } PropertyInfo keyPropertyInfo = null; PropertyInfo labelPropertyInfo = null; Type lastOptionObjectType = null; IEnumerator optionsEnumerator = Options.GetEnumerator(); while (optionsEnumerator.MoveNext()) { object optionObject = optionsEnumerator.Current; string label, uniqueKey; if (Options is IEnumerable<XElement>) { XElement element = (XElement) optionObject; var keyAttr = element.Attribute(this.OptionsKeyField); var labelAttr = element.Attribute(this.OptionsLabelField); Verify.IsNotNull(keyAttr, "XElement missing attribute '{0}'", this.OptionsKeyField); Verify.IsNotNull(labelAttr, "XElement missing attribute '{0}'", this.OptionsLabelField); uniqueKey = keyAttr.Value; label = labelAttr.Value; } else { object keyObject = GetPropertyValue(optionObject, this.OptionsKeyField, ref lastOptionObjectType, ref keyPropertyInfo); object labelObject = GetPropertyValue(optionObject, this.OptionsLabelField, ref lastOptionObjectType, ref labelPropertyInfo); // TODO: ValueTypeConverter.Convert<string>(keyObject) should be used uniqueKey = (keyObject is Type) ? TypeManager.SerializeType((Type)keyObject) : keyObject.ToString(); label = labelObject.ToString(); } _keyLabelPairList.Add(new KeyLabelPair(uniqueKey, label)); Verify.IsFalse(_selectorObjects.ContainsKey(uniqueKey), "Key '{0}' appears more than one time".FormatWith(uniqueKey ?? string.Empty)); _selectorObjects.Add(uniqueKey, optionObject); } } private object GetPropertyValue(object @object, string propertyName, ref Type lastOptionObjectType, ref PropertyInfo lastUsedPropertyInfo) { if (propertyName == "." || propertyName == "") { return @object; } if (@object.GetType() != lastOptionObjectType) { lastOptionObjectType = @object.GetType(); lastUsedPropertyInfo = null; } if (lastUsedPropertyInfo == null) { lastUsedPropertyInfo = lastOptionObjectType.GetProperty(propertyName); Verify.IsNotNull(lastUsedPropertyInfo, "Malformed Selection configuration. The Selected binding type '{0}' does not have a property named '{1}", @object.GetType().FullName, propertyName); } return (lastUsedPropertyInfo.GetValue(@object, null) ?? "(null)").ToString(); } /// <exclude /> public class KeyLabelPair { /// <exclude /> public KeyLabelPair(string key, string label) { this.Key = key; this.Label = label; } /// <exclude /> public string Key { get; set; } /// <exclude /> public string Label { get; set; } } } internal sealed class TemplatedSelectorUiControl : SelectorUiControl, IWebUiControl { private readonly Type _userControlType; private SelectorTemplateUserControlBase _userControl; internal TemplatedSelectorUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); if (_userControl.SelectedObjects.Any()) { if (_userControl.SelectedObjects.Count() > 1) throw new InvalidOperationException("Multiple elements selected. This was not expedted."); this.Selected = _userControl.SelectedObjects.First(); } else { this.Selected = null; } } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<SelectorTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.SelectedIndexChangedEventHandler += this.SelectedIndexChangedEventHandler; _userControl.SelectedObjects = new List<object> { this.Selected }; _userControl.Options = this.Options; _userControl.OptionsLabelField = this.OptionsLabelField; _userControl.OptionsKeyField = this.OptionsKeyField; _userControl.BindingType = this.BindingType; _userControl.Required = this.Required; _userControl.ReadOnly = this.ReadOnly; _userControl.ProvideNoSelectionOption = true; return _userControl; } public bool IsFullWidthControl => false; public string ClientName => _userControl.GetDataFieldClientName(); } internal sealed class TemplatedMultiSelectorUiControl : MultiSelectorUiControl, IWebUiControl { private readonly Type _userControlType; private SelectorTemplateUserControlBase _userControl; internal TemplatedMultiSelectorUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); if (this.Selected is IList) { IList listCopy = (IList)Activator.CreateInstance(this.Selected.GetType()); foreach (object selectedElement in _userControl.SelectedObjects) { listCopy.Add(selectedElement); } this.Selected = listCopy; } else { this.Selected = _userControl.SelectedObjects; this.SelectedAsString = string.Join(",", _userControl.SelectedKeys.ToArray()); // add code here that populate SelectedAsString } } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<SelectorTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.Options = this.Options; _userControl.OptionsLabelField = this.OptionsLabelField; _userControl.OptionsKeyField = this.OptionsKeyField; _userControl.BindingType = this.BindingType; _userControl.Required = this.Required; _userControl.CompactMode = this.CompactMode; _userControl.SelectedObjects = new List<object>(); if (this.Selected != null) { if (!string.IsNullOrEmpty(this.SelectedAsString)) { throw new InvalidOperationException("Binding properties 'Selected' and 'SelectedAsString' can not be set at the same time."); } foreach (object obj in this.Selected) { _userControl.SelectedObjects.Add(obj); } } else { if (!string.IsNullOrEmpty(this.SelectedAsString)) { _userControl.SetSelectedObjectsFromStringList(this.SelectedAsString.Split(',')); } } return _userControl; } public bool IsFullWidthControl => false; public string ClientName => _userControl.GetDataFieldClientName(); } [ConfigurationElementType(typeof(TemplatedSelectorUiControlFactoryData))] internal sealed class TemplatedSelectorUiControlFactory : Base.BaseTemplatedUiControlFactory { private TemplatedSelectorUiControlFactoryData _data; public TemplatedSelectorUiControlFactory(TemplatedSelectorUiControlFactoryData data) : base(data) { _data = data; } public override IUiControl CreateControl() { if (!_data.MultiSelector) { TemplatedSelectorUiControl control = new TemplatedSelectorUiControl(this.UserControlType); control.BindingType = _data.BindingType; return control; } else { TemplatedMultiSelectorUiControl control = new TemplatedMultiSelectorUiControl(this.UserControlType); control.BindingType = _data.BindingType; return control; } } } [Assembler(typeof(TemplatedSelectorUiControlFactoryAssembler))] internal sealed class TemplatedSelectorUiControlFactoryData : SelectorUiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; private const string _multiSelectorPropertyName = "MultiSelector"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } [ConfigurationProperty(_multiSelectorPropertyName, IsRequired = false, DefaultValue = false)] public bool MultiSelector { get { return (bool)base[_multiSelectorPropertyName]; } set { base[_multiSelectorPropertyName] = value; } } } internal sealed class TemplatedSelectorUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedSelectorUiControlFactory(objectConfiguration as TemplatedSelectorUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedSvgIconSelectorUiControlFactory.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text.RegularExpressions; using System.Web.UI; using System.Xml.Linq; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Core; using Composite.Core.IO; using Composite.Plugins.Forms.WebChannel.Foundation; using Composite.Data.Validation.ClientValidationRules; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class SvgIconSelectorTemplateUserControlBase : UserControl { /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public string Selected { get; set; } /// <exclude /> public Dictionary<string,string> SvgIdsOptions { get; set; } /// <exclude /> public string SvgSpritePath { get; set; } /// <exclude /> public string FormControlLabel { get; set; } /// <exclude /> public bool Required { get; set; } /// <exclude /> public List<ClientValidationRule> ClientValidationRules { get; set; } } internal sealed class TemplatedSvgIconSelectorUiControl : SvgIconSelectorUiControl, IWebUiControl { private Type _userControlType; private SvgIconSelectorTemplateUserControlBase _userControl; internal TemplatedSvgIconSelectorUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.Selected = _userControl.Selected; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<SvgIconSelectorTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.Selected = this.Selected; _userControl.ClientValidationRules = this.ClientValidationRules; _userControl.SvgSpritePath = this.SvgSpritePath; _userControl.Required = this.Required; _userControl.SvgIdsOptions = new Dictionary<string, string>(); var pathToSvg = System.Web.HttpContext.Current.Server.MapPath(this.SvgSpritePath); if (C1File.Exists(pathToSvg)) { var xd = XDocument.Load(pathToSvg); XNamespace ns = "http://www.w3.org/2000/svg"; if (xd.Root != null) { foreach (var el in xd.Root.Element(ns+ "defs").Elements(ns + "g")) { var idAttr = el.Attribute("id"); if (idAttr != null) { if (!_userControl.SvgIdsOptions.ContainsKey(idAttr.Value)) { _userControl.SvgIdsOptions.Add(idAttr.Value, idAttr.Value); } } } } } return _userControl; } public bool IsFullWidthControl { get { return false; } } public string ClientName { get { return _userControl.GetDataFieldClientName(); } } } [ConfigurationElementType(typeof(TemplatedSvgIconSelectorUiControlFactoryData))] internal sealed class TemplatedSvgIconSelectorUiControlFactory : Base.BaseTemplatedUiControlFactory { private string _configuredSvgSpritePath; public TemplatedSvgIconSelectorUiControlFactory(TemplatedSvgIconSelectorUiControlFactoryData data) : base(data) { _configuredSvgSpritePath = data.SvgSpritePath; } public override IUiControl CreateControl() { TemplatedSvgIconSelectorUiControl control = new TemplatedSvgIconSelectorUiControl(this.UserControlType); control.SvgSpritePath = _configuredSvgSpritePath; return control; } } [Assembler(typeof(TemplatedSvgIconSelectorUiControlFactoryAssembler))] internal sealed class TemplatedSvgIconSelectorUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _svgSpritePathPropertyName = "svgSpritePath"; private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_svgSpritePathPropertyName, IsRequired = false)] public string SvgSpritePath { get { return (string)base[_svgSpritePathPropertyName]; } set { base[_svgSpritePathPropertyName] = value; } } [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedSvgIconSelectorUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedSvgIconSelectorUiControlFactory(objectConfiguration as TemplatedSvgIconSelectorUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedTextEditorUiControlFactory.cs ================================================ using System; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; using System.Text.RegularExpressions; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class TextEditorTemplateUserControlBase : UserControl { private string _formControlLabel; private string _text; /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public string Text { get { return _text; } set { _text = value; } } /// <exclude /> public string FormControlLabel { get { return _formControlLabel; } set { _formControlLabel = value; } } /// <exclude /> public string MimeType { get; set; } } internal sealed class TemplatedTextEditorUiControl : TextEditorUiControl, IWebUiControl { private Type _userControlType; private TextEditorTemplateUserControlBase _userControl; internal TemplatedTextEditorUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.Text = NormalizeLineFeeds(_userControl.Text); } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<TextEditorTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.Text = NormalizeLineFeeds(this.Text); _userControl.MimeType = this.MimeType; return _userControl; } public bool IsFullWidthControl { get { return true; } } public string ClientName { get { return _userControl.GetDataFieldClientName(); } } private string NormalizeLineFeeds(string originalString) { return Regex.Replace(originalString, @"\r\n|\n\r|\n|\r", "\r\n"); } } [ConfigurationElementType(typeof(TemplatedTextEditorUiControlFactoryData))] internal sealed class TemplatedTextEditorUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedTextEditorUiControlFactory(TemplatedTextEditorUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { TemplatedTextEditorUiControl control = new TemplatedTextEditorUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedTextEditorUiControlFactoryAssembler))] internal sealed class TemplatedTextEditorUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedTextEditorUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedTextEditorUiControlFactory(objectConfiguration as TemplatedTextEditorUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedTextInputUiControlFactory.cs ================================================ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Composite.Data.Validation.ClientValidationRules; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class TextInputTemplateUserControlBase : UserControl, IPostBackDataHandler { /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public string Text { get; set; } /// <exclude /> public string FormControlLabel { get; set; } /// <exclude /> public bool Required { get; set; } /// <exclude /> public bool SpellCheck { get; set; } = true; /// <exclude /> public List<ClientValidationRule> ClientValidationRules { get; set; } /// <exclude /> public TextBoxType Type { get; set; } /// <summary> /// When implemented by a class, processes postback data for an ASP.NET server control. /// </summary> /// <param name="postDataKey"></param> /// <param name="postCollection"></param> /// <returns></returns> public virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) { return false; } /// <summary> /// When implemented by a class, signals the server control to notify the ASP.NET application that the state of the control has changed. /// </summary> public virtual void RaisePostDataChangedEvent() { } } internal sealed class TemplatedTextInputUiControl : TextInputUiControl, IWebUiControl { private readonly Type _userControlType; private TextInputTemplateUserControlBase _userControl; internal TemplatedTextInputUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.Text = _userControl.Text; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<TextInputTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.Text = this.Text; _userControl.ClientValidationRules = this.ClientValidationRules; _userControl.Type = this.Type; _userControl.Required = this.Required; _userControl.SpellCheck = this.SpellCheck; return _userControl; } public bool IsFullWidthControl => false; public string ClientName => _userControl.GetDataFieldClientName(); } [ConfigurationElementType(typeof(TemplatedTextInputUiControlFactoryData))] internal sealed class TemplatedTextInputUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedTextInputUiControlFactory(TemplatedTextInputUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { var control = new TemplatedTextInputUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedTextInputUiControlFactoryAssembler))] internal sealed class TemplatedTextInputUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedTextInputUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedTextInputUiControlFactory(objectConfiguration as TemplatedTextInputUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedTextUiControlFactory.cs ================================================ using System; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class TextTemplateUserControlBase : UserControl { private string _formControlLabel; private string _text; /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public string Text { get { return _text; } set { _text = value; } } /// <exclude /> public string FormControlLabel { get { return _formControlLabel; } set { _formControlLabel = value; } } } internal sealed class TemplatedTextUiControl : TextUiControl, IWebUiControl { private Type _userControlType; private TextTemplateUserControlBase _userControl; internal TemplatedTextUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.Text = _userControl.Text; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<TextTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.Text = this.Text; return _userControl; } public bool IsFullWidthControl { get { return false; } } public string ClientName { get { return null; } } } [ConfigurationElementType(typeof(TemplatedTextUiControlFactoryData))] internal sealed class TemplatedTextUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedTextUiControlFactory(TemplatedTextUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { TemplatedTextUiControl control = new TemplatedTextUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedTextUiControlFactoryAssembler))] internal sealed class TemplatedTextUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedTextUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedTextUiControlFactory(objectConfiguration as TemplatedTextUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedToolbarButtonUiControlFactory.cs ================================================ using System; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ToolbarButtonTemplateUserControlBase : UserControl { /// <exclude /> public EventHandler FormControlClickEventHandler { get; set; } /// <exclude /> public string FormControlLabel { get; set; } /// <exclude /> public string FormControlHelp { get; set; } /// <exclude /> public string FormControlIconHandle { get; set; } /// <exclude /> public string FormControlDisabledIconHandle { get; set; } /// <exclude /> public string FormControlLaunchUrl { get; set; } /// <exclude /> public bool FormControlIsDisabled { get; set; } /// <exclude /> public bool FormControlSaveBehaviour { get; set; } } internal sealed class TemplatedToolbarButtonUiControl : ToolbarButtonUiControl, IWebUiControl { private Type _userControlType; internal TemplatedToolbarButtonUiControl(Type userControlType) { _userControlType = userControlType; } public void InitializeViewState() { } public Control BuildWebControl() { ToolbarButtonTemplateUserControlBase userControl = _userControlType.ActivateAsUserControl<ToolbarButtonTemplateUserControlBase>(this.UiControlID); userControl.FormControlLabel = this.Label; userControl.FormControlClickEventHandler += this.ClickEventHandler; userControl.FormControlHelp = this.Help; userControl.FormControlIconHandle = this.IconHandle; userControl.FormControlDisabledIconHandle = this.DisabledIconHandle; userControl.FormControlLaunchUrl = this.LaunchUrl; userControl.FormControlSaveBehaviour = this.SaveBehaviour; userControl.FormControlIsDisabled = this.IsDisabled; return userControl; } public bool IsFullWidthControl { get { return false; } } public string ClientName { get { return null; } } } [ConfigurationElementType(typeof(TemplatedToolbarButtonUiControlFactoryData))] internal sealed class TemplatedToolbarButtonUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedToolbarButtonUiControlFactory(TemplatedToolbarButtonUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { TemplatedToolbarButtonUiControl control = new TemplatedToolbarButtonUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedToolbarButtonUiControlFactoryAssembler))] internal sealed class TemplatedToolbarButtonUiControlFactoryData : ToolbarButtonUiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedToolbarButtonUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedToolbarButtonUiControlFactory(objectConfiguration as TemplatedToolbarButtonUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedTreelSelectorUiControlFactory.cs ================================================ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class TreeSelectorTemplateUserControlBase : UserControl, IPostBackDataHandler { /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public string SelectedKey { get; set; } /// <exclude /> public string ElementProvider { get; set; } /// <exclude /> public string SelectableElementPropertyName { get; set; } /// <exclude /> public string SelectableElementPropertyValue { get; set; } /// <exclude /> public string SelectableElementReturnValue { get; set; } /// <exclude /> public string SerializedSearchToken { get; set; } /// <exclude /> public bool Required { get; set; } /// <summary> /// When implemented by a class, processes postback data for an ASP.NET server control. /// </summary> /// <param name="postDataKey"></param> /// <param name="postCollection"></param> /// <returns></returns> public virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) { return false; } /// <summary> /// When implemented by a class, signals the server control to notify the ASP.NET application that the state of the control has changed. /// </summary> public virtual void RaisePostDataChangedEvent() { } } internal sealed class TemplatedTreeSelectorUiControl : TreeSelectorUiControl, IWebUiControl { private readonly Type _userControlType; private TreeSelectorTemplateUserControlBase _userControl; internal TemplatedTreeSelectorUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.SelectedKey = _userControl.SelectedKey; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<TreeSelectorTemplateUserControlBase>(this.UiControlID); _userControl.SelectedKey = this.SelectedKey; _userControl.ElementProvider = this.ElementProvider; _userControl.SelectableElementReturnValue = this.SelectableElementReturnValue; _userControl.SelectableElementPropertyName = string.IsNullOrEmpty(this.SelectableElementPropertyName) ? this.SelectableElementReturnValue : this.SelectableElementPropertyName; _userControl.SelectableElementPropertyValue = this.SelectableElementPropertyValue; _userControl.SerializedSearchToken = this.SerializedSearchToken; _userControl.Required = this.Required; return _userControl; } public bool IsFullWidthControl => false; public string ClientName => _userControl.GetDataFieldClientName(); } [ConfigurationElementType(typeof(TemplatedTreeSelectorUiControlFactoryData))] internal sealed class TemplatedTreeSelectorUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedTreeSelectorUiControlFactory(TemplatedTreeSelectorUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { var control = new TemplatedTreeSelectorUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedTreeSelectorUiControlFactoryAssembler))] internal sealed class TemplatedTreeSelectorUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedTreeSelectorUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedTreeSelectorUiControlFactory( objectConfiguration as TemplatedTreeSelectorUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedTypeFieldDesignerUiControlFactory.cs.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Web.UI; using Composite.Data.DynamicTypes; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class TypeFieldDesignerTemplateUserControlBase : UserControl { /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public IEnumerable<DataFieldDescriptor> Fields { get; set; } /// <exclude /> public string KeyFieldName { get; set; } /// <exclude /> public string LabelFieldName { get; set; } /// <exclude /> public string FormControlLabel { get; set; } /// <exclude /> public bool KeyFieldReadOnly { get; set; } /// <exclude /> public bool IsSearchable { get; set; } } internal sealed class TemplatedTypeFieldDesignerUiControl : TypeFieldDesignerUiControl, IWebUiControl { private readonly Type _userControlType; private TypeFieldDesignerTemplateUserControlBase _userControl; internal TemplatedTypeFieldDesignerUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.Fields = _userControl.Fields; this.KeyFieldName = _userControl.KeyFieldName; this.LabelFieldName = _userControl.LabelFieldName; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<TypeFieldDesignerTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.Fields = this.Fields; _userControl.KeyFieldName = KeyFieldName; _userControl.LabelFieldName = this.LabelFieldName; _userControl.KeyFieldReadOnly = KeyFieldReadOnly; _userControl.IsSearchable = IsSearchable; return _userControl; } public bool IsFullWidthControl { get { return true; } } public string ClientName { get { return _userControl.GetDataFieldClientName(); } } } [ConfigurationElementType(typeof(TemplatedTypeFieldDesignerUiControlFactoryData))] internal sealed class TemplatedTypeFieldDesignerUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedTypeFieldDesignerUiControlFactory(TemplatedTypeFieldDesignerUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { var control = new TemplatedTypeFieldDesignerUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedTypeFieldDesignerUiControlFactoryAssembler))] internal sealed class TemplatedTypeFieldDesignerUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedTypeFieldDesignerUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedTypeFieldDesignerUiControlFactory(objectConfiguration as TemplatedTypeFieldDesignerUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedTypeSelectorUiControlFactory.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class TypeSelectorTemplateUserControlBase : UserControl { private string _formControlLabel; private Type _selectedType; private TemplatedTypeSelectorUiControl _typeOptionsProxy; /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } internal void SetTypeOptionsProxy(TemplatedTypeSelectorUiControl proxy) { _typeOptionsProxy = proxy; } /// <exclude /> public Type SelectedType { get { return _selectedType; } set { _selectedType = value; } } /// <exclude /> public string FormControlLabel { get { return _formControlLabel; } set { _formControlLabel = value; } } /// <exclude /> public IEnumerable<Type> TypeOptions { get { return _typeOptionsProxy.FetchTypeOptions(); } } } internal sealed class TemplatedTypeSelectorUiControl : TypeSelectorUiControl, IWebUiControl { private Type _userControlType; private TypeSelectorTemplateUserControlBase _userControl; internal TemplatedTypeSelectorUiControl(Type userControlType) { _userControlType = userControlType; } /// <exclude /> public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.SelectedType = _userControl.SelectedType; } /// <exclude /> public void InitializeViewState() { _userControl.InitializeWebViewState(); } /// <exclude /> public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<TypeSelectorTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.SelectedType = this.SelectedType; _userControl.SetTypeOptionsProxy(this); return _userControl; } internal IEnumerable<Type> FetchTypeOptions() { return base.GetTypeOptions(); } /// <exclude /> public bool IsFullWidthControl { get { return false; } } /// <exclude /> public string ClientName { get { return _userControl.GetDataFieldClientName(); } } } [ConfigurationElementType(typeof(TemplatedTypeSelectorUiControlFactoryData))] internal sealed class TemplatedTypeSelectorUiControlFactory : Base.BaseTemplatedUiControlFactory { public TemplatedTypeSelectorUiControlFactory(TemplatedTypeSelectorUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { TemplatedTypeSelectorUiControl control = new TemplatedTypeSelectorUiControl(this.UserControlType); return control; } } [Assembler(typeof(TemplatedTypeSelectorUiControlFactoryAssembler))] internal sealed class TemplatedTypeSelectorUiControlFactoryData : TypeSelectorUiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedTypeSelectorUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedTypeSelectorUiControlFactory(objectConfiguration as TemplatedTypeSelectorUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/TemplatedXhtmlEditorUiControlFactory.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.C1Console.RichContent.ContainerClasses; using Composite.Plugins.Forms.WebChannel.Foundation; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class XhtmlEditorTemplateUserControlBase : UserControl { private string _formControlLabel; private string _xhtml; /// <exclude /> protected abstract void BindStateToProperties(); /// <exclude /> protected abstract void InitializeViewState(); /// <exclude /> public abstract string GetDataFieldClientName(); internal void BindStateToControlProperties() { this.BindStateToProperties(); } internal void InitializeWebViewState() { this.InitializeViewState(); } /// <exclude /> public string Xhtml { get { return _xhtml; } set { _xhtml = value; } } /// <exclude /> public string FormControlLabel { get { return _formControlLabel; } set { _formControlLabel = value; } } /// <exclude /> public IEnumerable<Type> EmbedableFieldsTypes { get; set; } /// <exclude /> public string ClassConfigurationName { get; set; } /// <exclude /> public string ContainerClasses { get; set; } /// <exclude /> public Guid PreviewPageId { get; set; } /// <exclude /> public Guid PreviewTemplateId { get; set; } /// <exclude /> public string PreviewPlaceholder { get; set; } } internal sealed class TemplatedXhtmlEditorUiControl : XhtmlEditorUiControl, IWebUiControl { private readonly Type _userControlType; private XhtmlEditorTemplateUserControlBase _userControl; internal TemplatedXhtmlEditorUiControl(Type userControlType) { _userControlType = userControlType; } public override void BindStateToControlProperties() { _userControl.BindStateToControlProperties(); this.Xhtml = _userControl.Xhtml; } public void InitializeViewState() { _userControl.InitializeWebViewState(); } public Control BuildWebControl() { _userControl = _userControlType.ActivateAsUserControl<XhtmlEditorTemplateUserControlBase>(this.UiControlID); _userControl.FormControlLabel = this.Label; _userControl.Xhtml = this.Xhtml; _userControl.EmbedableFieldsTypes = this.EmbedableFieldsTypes; _userControl.ClassConfigurationName = this.ClassConfigurationName; _userControl.ContainerClasses = ContainerClassManager.NormalizeClassNamesString(this.ContainerClasses); _userControl.PreviewPageId = PreviewPageId; _userControl.PreviewTemplateId = PreviewTemplateId; _userControl.PreviewPlaceholder = PreviewPlaceholder; return _userControl; } public bool IsFullWidthControl { get { return true; } } public string ClientName { get { return _userControl.GetDataFieldClientName(); } } } [ConfigurationElementType(typeof(TemplatedXhtmlEditorUiControlFactoryData))] internal sealed class TemplatedXhtmlEditorUiControlFactory : Base.BaseTemplatedUiControlFactory { private TemplatedXhtmlEditorUiControlFactoryData _data; public TemplatedXhtmlEditorUiControlFactory(TemplatedXhtmlEditorUiControlFactoryData data) : base(data) { _data = data; } public override IUiControl CreateControl() { TemplatedXhtmlEditorUiControl control = new TemplatedXhtmlEditorUiControl(this.UserControlType); control.ClassConfigurationName = _data.ClassConfigurationName; control.ContainerClasses = _data.ContainerClasses; return control; } } [Assembler(typeof(TemplatedXhtmlEditorUiControlFactoryAssembler))] internal sealed class TemplatedXhtmlEditorUiControlFactoryData : XhtmlEditorUiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class TemplatedXhtmlEditorUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new TemplatedXhtmlEditorUiControlFactory(objectConfiguration as TemplatedXhtmlEditorUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/UserControlBasedUiControlFactory.cs ================================================ using System.Collections.Generic; using System.Configuration; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Composite.Plugins.Forms.WebChannel.Foundation; using Composite.Data.Validation.ClientValidationRules; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class UserControlBasedUiControl : UserControl, IWebUiControl, IValidatingUiControl { private string _uiControlId = "IdNotSet"; /// <exclude /> public virtual Control BuildWebControl() { return this; } /// <exclude /> public abstract void InitializeViewState(); /// <exclude /> public abstract void BindStateToControlProperties(); /// <exclude /> public string ClientName { get; set; } /// <exclude /> public bool IsFullWidthControl { get; set; } /// <exclude /> public string UiControlID { get { return _uiControlId; } set { _uiControlId = value; this.ID = _uiControlId; } } /// <exclude /> public IFormChannelIdentifier UiControlChannel { get; set; } /// <exclude /> public string Label { get; set; } /// <exclude /> public string Help { get; set; } /// <exclude /> public List<ClientValidationRule> ClientValidationRules { get; set; } /// <exclude /> public List<string> SourceBindingPaths { get; set; } /// <exclude /> public virtual bool IsValid { get; set; } /// <exclude /> public virtual string ValidationError { get; set; } } [ConfigurationElementType(typeof(UserControlBasedUiControlFactoryData))] internal sealed class UserControlBasedUiControlFactory : Base.BaseTemplatedUiControlFactory { public UserControlBasedUiControlFactory(UserControlBasedUiControlFactoryData data) : base(data) { } public override IUiControl CreateControl() { UserControlBasedUiControl userControlBasedUiControl = this.UserControlType.ActivateAsUserControl<UserControlBasedUiControl>(null); userControlBasedUiControl.IsValid = true; return userControlBasedUiControl; } } [Assembler(typeof(UserControlBasedUiControlFactoryAssembler))] internal sealed class UserControlBasedUiControlFactoryData : UiControlFactoryData, Base.ITemplatedUiControlFactoryData { private const string _userControlVirtualPathPropertyName = "userControlVirtualPath"; private const string _cacheCompiledUserControlTypePropertyName = "cacheCompiledUserControlType"; [ConfigurationProperty(_userControlVirtualPathPropertyName, IsRequired = true)] public string UserControlVirtualPath { get { return (string)base[_userControlVirtualPathPropertyName]; } set { base[_userControlVirtualPathPropertyName] = value; } } [ConfigurationProperty(_cacheCompiledUserControlTypePropertyName, IsRequired = false, DefaultValue = true)] public bool CacheCompiledUserControlType { get { return (bool)base[_cacheCompiledUserControlTypePropertyName]; } set { base[_cacheCompiledUserControlTypePropertyName] = value; } } } internal sealed class UserControlBasedUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new UserControlBasedUiControlFactory(objectConfiguration as UserControlBasedUiControlFactoryData); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/WebDebugUiControlFactory.cs ================================================ using System.Web.UI; using System.Web.UI.WebControls; using Composite.C1Console.Forms; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { internal sealed class WebDebugUiControl : DebugUiControl, IWebUiControl { private Panel _panel; public Control BuildWebControl() { _panel = new Panel(); _panel.CssClass = "debugPanel"; Label xpathLabel = new Label(); xpathLabel.Text = string.Format("XPath: {0}", this.SourceElementXPath); xpathLabel.CssClass = "debugPanelHeader"; AddControl(xpathLabel); Control control = (this.UiControl as IWebUiControl).BuildWebControl(); AddControl(control); return _panel; } public void InitializeViewState() { (this.UiControl as IWebUiControl).InitializeViewState(); } private void AddControl(Control control) { _panel.Controls.Add(control); } public override void BindStateToControlProperties() { this.UiControl.BindStateToControlProperties(); } public bool IsFullWidthControl { get { return false; } } public string ClientName { get { return null; } } } [ConfigurationElementType(typeof(WebDebugUiControlFactoryData))] internal sealed class WebDebugUiControlFactory : IUiControlFactory { public IUiControl CreateControl() { return new WebDebugUiControl(); } } [Assembler(typeof(WebDebugUiControlFactoryAssembler))] internal sealed class WebDebugUiControlFactoryData : DebugUiControlFactoryData { } internal sealed class WebDebugUiControlFactoryAssembler : IAssembler<IUiControlFactory, UiControlFactoryData> { public IUiControlFactory Assemble(IBuilderContext context, UiControlFactoryData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new WebDebugUiControlFactory(); } } } ================================================ FILE: Composite/Plugins/Forms/WebChannel/UiControlFactories/WebEmbeddedFormUiControlFactory.cs ================================================ using System.IO; using System.Web.UI; using Composite.C1Console.Forms; using Composite.C1Console.Forms.DataServices.UiControls; using Composite.C1Console.Forms.Plugins.UiControlFactory; using Composite.C1Console.Forms.WebChannel; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.Forms.WebChannel.UiControlFactories { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Composite.C1Console.Forms.ControlValueProperty("Bindings")] public class WebEmbeddedFormUiControl : EmbeddedFormUiControl, IWebUiControl { internal WebEmbeddedFormUiControl() { } /// <exclude /> public WebEmbeddedFormUiControl(IFormChannelIdentifier channel) { this.UiControlChannel = channel; } /// <exclude /> public void InitializeViewState() { ((IWebUiControl)this.CompiledUiControl).InitializeViewState(); } /// <exclude /> public Control BuildWebControl() { Control _formControl = ((IWebUiControl)this.CompiledUiControl).BuildWebControl(); _formControl.ID = Path.GetFileNameWithoutExtension(this.FormPath); ; return _formControl; } /// <exclude /> public bool IsFullWidthControl { get { return false; } } /// <exclude /> public string ClientName { get { return null; } } } [ConfigurationElementType(typeof(WebEmbeddedFormUiControlFactoryData))] internal sealed class WebEmbeddedFormUiControlFactory : IUiControlFactory { public IUiControl CreateControl() { return new WebEmbeddedFormUiControl(); } } [Assembler(typeof(NonConfigurableUiControlFactoryAssembler))] internal sealed class WebEmbeddedFormUiControlFactoryData : UiControlFactoryData { } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/CodeBasedFunctionProvider/CodeBasedFunction.cs ================================================ using System; using System.Collections.Generic; using System.Reflection; using Composite.C1Console.Security; using Composite.Core; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.MethodBasedFunctionProvider; using Microsoft.Extensions.DependencyInjection; namespace Composite.Plugins.Functions.FunctionProviders.CodeBasedFunctionProvider { internal class CodeBasedFunction : MethodBasedFunction { public static CodeBasedFunction Create(Type type, string methodName, string userNamespace, string userMethodName, string description) { var methodInfo = GetMethodInfo(type, methodName, userNamespace, userMethodName, out _); return methodInfo == null ? null : new CodeBasedFunction(type, methodInfo, userNamespace, userMethodName, description); } protected CodeBasedFunction(Type type, MethodInfo methodInfo, string userNamespace, string userMethodName, string description) : base(typeof(CodeBasedFunction).Name) { Name = userMethodName; Namespace = userNamespace; Type = type; MethodInfo = methodInfo; Description = description; } public override string Description { get; } protected override MethodInfo MethodInfo { get; } public override string Name { get; } public override string Namespace { get; } private Type Type { get; } public override EntityToken EntityToken => new CodeBasedFunctionEntityToken(this); public override object Execute(ParameterList parameters, FunctionContextContainer context) { var arguments = new List<object>(); foreach (ParameterProfile paramProfile in ParameterProfiles) { arguments.Add(parameters.GetParameter(paramProfile.Name, paramProfile.Type)); } var instance = MethodInfo.IsStatic ? null : ActivatorUtilities.GetServiceOrCreateInstance(ServiceLocator.ServiceProvider, Type); return MethodInfo.Invoke(instance, arguments.ToArray()); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/CodeBasedFunctionProvider/CodeBasedFunctionEntityToken.cs ================================================ using Composite.C1Console.Security; using Composite.Functions; namespace Composite.Plugins.Functions.FunctionProviders.CodeBasedFunctionProvider { [SecurityAncestorProvider(typeof(StandardFunctionSecurityAncestorProvider))] internal class CodeBasedFunctionEntityToken : EntityToken { internal CodeBasedFunctionEntityToken(CodeBasedFunction function) { Id = $"{function.Namespace}.{function.Name}"; } public CodeBasedFunctionEntityToken(string fullName) { Id = fullName; } public override string Id { get; } public static EntityToken Deserialize(string serializedData) { DoDeserialize(serializedData, out _, out _, out var id); return new CodeBasedFunctionEntityToken(id); } public override string Serialize() => DoSerialize(); public override string Source => string.Empty; public override string Type => string.Empty; } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/CodeBasedFunctionProvider/CodeBasedFunctionProvider.cs ================================================ using System.Collections.Generic; using Composite.Functions; using Composite.Functions.Plugins.FunctionProvider; namespace Composite.Plugins.Functions.FunctionProviders.CodeBasedFunctionProvider { internal class CodeBasedFunctionProvider : IFunctionProvider { private static FunctionNotifier _functionNotifier; public FunctionNotifier FunctionNotifier { set => _functionNotifier = value; } public IEnumerable<IFunction> Functions => CodeBasedFunctionRegistry.Functions; internal static void Reload() { // Can be called before function provider initialization _functionNotifier?.FunctionsUpdated(); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/CodeBasedFunctionProvider/CodeBasedFunctionRegistry.cs ================================================ using System.Collections.Concurrent; using System.Linq; using Composite.Functions; using Microsoft.Extensions.DependencyInjection; namespace Composite.Plugins.Functions.FunctionProviders.CodeBasedFunctionProvider { /// <summary> /// This class allows to register methods from external assemblies as C1 functions. /// To register own method for C1 usage: /// 1. Register a suitable dependency in an appropriate way in case it is needed /// an object for a method call (recommended) <see cref="IServiceCollection"/> /// For example: /// <code> /// public static void ConfigureServices(IServiceCollection collection) /// { /// collection.AddSingleTon(typeof(YourServiceType)); /// } /// </code> /// 2. Register needed method as C1 function with RegisterMethod call <see cref="RegisterMethod{T}(string, string, string)"/> /// </summary> public static class CodeBasedFunctionRegistry { internal static readonly ConcurrentBag<IFunction> Functions = new ConcurrentBag<IFunction>(); /// <summary> /// Provided to register methods from external assemblies as C1 functions /// </summary> /// <typeparam name="T">Type of a class, which contains the needed method</typeparam> /// <param name="methodName">Name of the method to be registered</param> /// <param name="userMethodFullName"> /// Set up custom method full name for displaying in C1. /// For example: TestNamespace.TestClassName.TestMethodName /// </param> /// <param name="description">Can be provided a custom description for the method</param> public static void RegisterMethod<T>(string methodName, string userMethodFullName = null, string description = null) where T : class { var type = typeof(T); string userNamespace, userMethodName; if (string.IsNullOrWhiteSpace(userMethodFullName)) { userMethodName = methodName; userNamespace = type.Namespace; } else { ParseFunctionName(userMethodFullName, out userNamespace, out userMethodName); } var function = CodeBasedFunction.Create(type, methodName, userNamespace, userMethodName, description); Functions.Add(function); CodeBasedFunctionProvider.Reload(); } private static void ParseFunctionName(string userMethodFullName, out string userNamespace, out string userMethodName) { string[] parts = userMethodFullName.Split(new[] { '.' }); Verify.That(parts.Length > 1, "Missing a function namespace in full function name '{0}'", userMethodFullName); Verify.IsFalse(parts.Any(string.IsNullOrWhiteSpace), "Empty full name parts are not allowed"); userNamespace = string.Join(".", parts.Take(parts.Length - 1)); userMethodName = parts.Last(); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/FileBasedFunctionProvider/FileBasedFunction.cs ================================================ using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Web; using Composite.AspNet.Security; using Composite.C1Console.Security; using Composite.Core.IO; using Composite.Core.Xml; using Composite.Functions; using Composite.Core.Extensions; namespace Composite.Plugins.Functions.FunctionProviders.FileBasedFunctionProvider { internal abstract class FileBasedFunction<T> : IFunction where T : FileBasedFunction<T> { private readonly FileBasedFunctionProvider<T> _provider; internal string VirtualPath { get; private set; } protected IDictionary<string, FunctionParameter> Parameters { get; set; } public string Namespace { get; private set; } public string Name { get; private set; } public Type ReturnType { get; private set; } public virtual string Description { get; private set; } public EntityToken EntityToken { get { return new FileBasedFunctionEntityToken(_provider.Name, String.Join(".", Namespace, Name)); } } protected abstract void InitializeParameters(); public virtual IEnumerable<ParameterProfile> ParameterProfiles { get { if (Parameters == null) { lock (this) { if (Parameters == null) { try { InitializeParameters(); } catch (HttpException ex) { EmbedSourceCodeInformation(ex); throw; } Verify.IsNotNull(Parameters, "Parameters collection is null"); } } } foreach (var param in Parameters.Values) { BaseValueProvider defaultValueProvider = new NoValueValueProvider(); WidgetFunctionProvider widgetProvider = param.WidgetProvider; string label = param.Name; bool isRequired = true; string helpText = String.Empty; bool hideInSimpleView = false; if (param.Attribute != null) { if (!param.Attribute.Label.IsNullOrEmpty()) { label = param.Attribute.Label; } if (!param.Attribute.Help.IsNullOrEmpty()) { helpText = param.Attribute.Help; } isRequired = !param.Attribute.HasDefaultValue; if (!isRequired) { defaultValueProvider = new ConstantValueProvider(param.Attribute.DefaultValue); } hideInSimpleView = param.Attribute.HideInSimpleView; } if (widgetProvider == null) { widgetProvider = StandardWidgetFunctions.GetDefaultWidgetFunctionProviderByType(param.Type, isRequired); } yield return new ParameterProfile(param.Name, param.Type, isRequired, defaultValueProvider, widgetProvider, label, new HelpDefinition(helpText), hideInSimpleView); } } } protected FileBasedFunction(string ns, string name, string description, IDictionary<string, FunctionParameter> parameters, Type returnType, string virtualPath, FileBasedFunctionProvider<T> provider) :this(ns, name, description, returnType, virtualPath, provider) { Parameters = parameters; } protected FileBasedFunction(string ns, string name, string description, Type returnType, string virtualPath, FileBasedFunctionProvider<T> provider) { _provider = provider; Namespace = ns; Name = name; Description = description; ReturnType = returnType; VirtualPath = virtualPath; } protected void EmbedSourceCodeInformation(HttpException ex) { if (ex is HttpParseException) { EmbedSourceCodeInformation(ex as HttpParseException); } else if (ex is HttpCompileException) { EmbedSourceCodeInformation(ex as HttpCompileException); } } private void EmbedSourceCodeInformation(HttpParseException ex) { // Not showing source code of not related files if (!ex.FileName.StartsWith(PathUtil.Resolve(VirtualPath), StringComparison.OrdinalIgnoreCase)) { return; } string[] sourceCode = C1File.ReadAllLines(ex.FileName); XhtmlErrorFormatter.EmbedSourceCodeInformation(ex, sourceCode, ex.Line); } private void EmbedSourceCodeInformation(HttpCompileException ex) { var compilationErrors = ex.Results.Errors; if (!compilationErrors.HasErrors) { return; } CompilerError firstError = null; for (int i = 0; i < compilationErrors.Count; i++) { if (!compilationErrors[i].IsWarning) { firstError = compilationErrors[i]; break; } } Verify.IsNotNull(firstError, "Failed to finding an error in the compiler results."); // Not showing source code of not related files if (!firstError.FileName.StartsWith(PathUtil.Resolve(VirtualPath), StringComparison.OrdinalIgnoreCase)) { return; } string[] sourceCode = C1File.ReadAllLines(firstError.FileName); XhtmlErrorFormatter.EmbedSourceCodeInformation(ex, sourceCode, firstError.Line); } public abstract object Execute(ParameterList parameters, FunctionContextContainer context); } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/FileBasedFunctionProvider/FileBasedFunctionProvider.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Web.Hosting; using Composite.Core; using Composite.Core.Caching; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Types; using Composite.Functions; using Composite.Functions.Plugins.FunctionProvider; using Composite.Core.Application; using Composite.Core.Configuration; namespace Composite.Plugins.Functions.FunctionProviders.FileBasedFunctionProvider { internal abstract class FileBasedFunctionProvider<FunctionType> : IFunctionProvider where FunctionType : FileBasedFunction<FunctionType> { static readonly FileRelatedDataCache<CachedFunctionInformation> _functionInfoCache = new FileRelatedDataCache<CachedFunctionInformation>( "Functions", "fileBasedFunction", CachedFunctionInformation.Serialize, CachedFunctionInformation.Deserialize); private static readonly string LogTitle = "FileBasedFunctionProvider"; private static readonly object _lock = new object(); private const int FunctionReloadDelayMilliseconds = 200; private readonly C1FileSystemWatcher _watcher; private DateTime? _lastFunctionReloadTime = DateTime.Now; private readonly string _name; protected abstract string FileExtension { get; } protected abstract string DefaultFunctionNamespace { get; } public FunctionNotifier FunctionNotifier { private get; set; } public string VirtualPath { get; private set; } public string PhysicalPath { get; private set; } public string Name { get { return _name; } } /// <summary> /// </summary> /// <exclude /> public IEnumerable<IFunction> Functions { get { var returnList = new List<IFunction>(); if (!C1Directory.Exists(PhysicalPath) || !(SystemSetupFacade.IsSystemFirstTimeInitialized && !SystemSetupFacade.SetupIsRunning)) { return returnList; } var files = new C1DirectoryInfo(PhysicalPath) .GetFiles("*." + FileExtension, SearchOption.AllDirectories) .Where(f => !f.Name.StartsWith("_", StringComparison.Ordinal)); foreach (var file in files) { string filePath = file.FullName; string @namespace = ExtractFunctionNamespace(file.FullName); string name = Path.GetFileNameWithoutExtension(file.Name); var virtualPath = CombineVirtualPath(VirtualPath, @namespace.Replace(".", "/"), name + "." + FileExtension); if(@namespace == string.Empty) { @namespace = DefaultFunctionNamespace; } string fullFunctionName = @namespace + "." + name; IFunction function; try { CachedFunctionInformation cachedFunctionInfo; if (!_functionInfoCache.Get(fullFunctionName, filePath, out cachedFunctionInfo)) { function = InstantiateFunction(virtualPath, @namespace, name); // Not caching functions that failed to load var initializationInfo = function as IFunctionInitializationInfo; bool functionFailedToCompile = initializationInfo != null && !initializationInfo.FunctionInitializedCorrectly; if ((function == null && !HostingEnvironment.ApplicationHost.ShutdownInitiated()) || (function != null && !functionFailedToCompile)) { _functionInfoCache.Add(fullFunctionName, filePath, function != null ? new CachedFunctionInformation(function) : null); } } else { if (cachedFunctionInfo == null) { continue; } function = InstantiateFunctionFromCache(virtualPath, @namespace, name, cachedFunctionInfo.ReturnType, cachedFunctionInfo.Description, cachedFunctionInfo.PreventCaching); } } catch (ThreadAbortException) { throw; } catch (Exception ex) { // supressing error messages while in offline mode - we are installing stuff here. if (ApplicationOnlineHandlerFacade.IsApplicationOnline && !HostingEnvironment.ApplicationHost.ShutdownInitiated()) { Log.LogError(LogTitle, "Error instantiating function {0} ", @namespace + "." + name); Log.LogError(LogTitle, ex); } returnList.Add(new NotLoadedFileBasedFunction<FunctionType>(this, @namespace, name, virtualPath, ex)); continue; } if (function == null) { continue; } returnList.Add(function); } return returnList; } } private static string CombineVirtualPath(params string[] parts) { return string.Join("/", parts).Replace('\\', '/').Replace("///", "/").Replace("//", "/"); } private string ExtractFunctionNamespace(string filePath) { Verify.That(filePath.StartsWith(PhysicalPath, StringComparison.OrdinalIgnoreCase), "File path should start with folder path"); string directoryPath = Path.GetDirectoryName(filePath); string relativeDirectoryPath = directoryPath.Substring(PhysicalPath.Length); return string.Join(".", relativeDirectoryPath.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)); } protected FileBasedFunctionProvider(string name, string folder) { _name = name; VirtualPath = folder; PhysicalPath = PathUtil.Resolve(VirtualPath); if (!C1Directory.Exists(PhysicalPath)) { return; } string folderToWatch = PhysicalPath; try { if (ReparsePointUtils.DirectoryIsReparsePoint(folderToWatch)) { folderToWatch = ReparsePointUtils.GetDirectoryReparsePointTarget(folderToWatch); } _watcher = new C1FileSystemWatcher(folderToWatch, "*") { IncludeSubdirectories = true }; _watcher.Created += Watcher_OnChanged; _watcher.Deleted += Watcher_OnChanged; _watcher.Changed += Watcher_OnChanged; _watcher.Renamed += Watcher_OnChanged; _watcher.EnableRaisingEvents = true; } catch (Exception ex) { Log.LogWarning(LogTitle, "Failed to create a file system watcher for path '{0}'", folderToWatch); Log.LogWarning(LogTitle, ex); } } /// <summary> /// Instantiates the function from the file. /// </summary> /// <param name="virtualPath">The virtual path.</param> /// <param name="namespace">The namespace.</param> /// <param name="name">The name.</param> /// <returns></returns> protected abstract IFunction InstantiateFunction(string virtualPath, string @namespace, string name); /// <summary> /// Instantiates the function from the file and additional cached information. /// </summary> /// <param name="virtualPath">The virtual path.</param> /// <param name="namespace">The namespace.</param> /// <param name="name">The name.</param> /// <param name="returnType">Cached value of return type.</param> /// <param name="cachedDescription">Cached value of the description.</param> /// <param name="preventCaching">Cached PreventFunctionOutputCache property value.</param> /// <returns></returns> protected virtual IFunction InstantiateFunctionFromCache( string virtualPath, string @namespace, string name, Type returnType, string cachedDescription, bool preventCaching) { return InstantiateFunction(virtualPath, @namespace, name); } protected abstract bool HandleChange(string path); public void ReloadFunctions() { Thread.Sleep(FunctionReloadDelayMilliseconds); try { FunctionNotifier.FunctionsUpdated(); } catch (ThreadAbortException) { throw; } catch(Exception ex) { Log.LogError(LogTitle, "Failed to reload functions"); Log.LogError(LogTitle, ex); } } private void Watcher_OnChanged(object sender, FileSystemEventArgs e) { if (SystemSetupFacade.SetupIsRunning) { return; } // Reloading functions only after a certain delay as otherwise edited in VS function won't be loaded if files are accessed through a network drive if (FunctionNotifier != null && HandleChange(e.FullPath)) { var timeSpan = DateTime.Now - _lastFunctionReloadTime.Value; if (timeSpan.TotalMilliseconds < FunctionReloadDelayMilliseconds) { return; } lock (_lock) { var now = DateTime.Now; timeSpan = now - _lastFunctionReloadTime.Value; if (timeSpan.TotalMilliseconds < FunctionReloadDelayMilliseconds) { return; } _lastFunctionReloadTime = now; new Thread(ReloadFunctions).Start(); } } } private class CachedFunctionInformation { public Type ReturnType { get; private set; } public string Description { get; private set; } public bool PreventCaching { get; private set; } private CachedFunctionInformation() {} public CachedFunctionInformation(IFunction function) { ReturnType = function.ReturnType; Description = function.Description; PreventCaching = function is IDynamicFunction dynamicFunction && dynamicFunction.PreventFunctionOutputCaching; } public static void Serialize(CachedFunctionInformation data, string filePath) { var lines = new List<string>(); if (data != null) { lines.Add(TypeManager.SerializeType(data.ReturnType)); lines.Add(data.PreventCaching.ToString()); lines.AddRange(data.Description.Split(new [] { Environment.NewLine }, StringSplitOptions.None)); } C1File.WriteAllLines(filePath, lines); } public static CachedFunctionInformation Deserialize(string filePath) { var lines = C1File.ReadAllLines(filePath); if (lines == null || lines.Length == 0) { return null; } Type type = TypeManager.TryGetType(lines[0]); if (type == null) return null; bool preventCaching = bool.Parse(lines[1]); string description = string.Join(Environment.NewLine, lines.Skip(2)); return new CachedFunctionInformation { Description = description, PreventCaching = preventCaching, ReturnType = type }; } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/FileBasedFunctionProvider/FunctionBasedFunctionProviderHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.Core; using Composite.Core.Extensions; using Composite.Functions; namespace Composite.Plugins.Functions.FunctionProviders.FileBasedFunctionProvider { /// <summary> /// Helper class for developing implementations of FileBasedFunctionProvider /// </summary> public static class FunctionBasedFunctionProviderHelper { private static readonly string LogTitle = typeof(FunctionBasedFunctionProviderHelper).FullName; /// <summary> /// Gets the function description from the <see cref="FunctionAttribute" />. /// </summary> /// <param name="functionName">Name of the function.</param> /// <param name="functionObject">The object that represents a function.</param> /// <returns></returns> public static string GetDescription(string functionName, object functionObject) { var attr = functionObject.GetType() .GetCustomAttributes(typeof(FunctionAttribute), false) .Cast<FunctionAttribute>() .FirstOrDefault(); if (attr != null) { return attr.Description; } return String.Format("A {0} function", functionName); } /// <summary> /// Extracts the function paramteres from an object that represents a function. /// </summary> /// <param name="functionObject">The object that represents a function.</param> /// <param name="baseFunctionType">Type of the base function.</param> /// <param name="filePath">Physical file location of the file behind the function, used for logging.</param> /// <returns></returns> public static IDictionary<string, FunctionParameter> GetParameters(object functionObject, Type baseFunctionType, string filePath) { var functionParameters = new Dictionary<string, FunctionParameter>(); IDictionary<string, WidgetFunctionProvider> parameterWidgets = GetParameterWidgets(functionObject); var type = functionObject.GetType(); while (type != baseFunctionType && type != null) { var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.DeclaredOnly); foreach (var property in properties) { // Skipping overriden base properties if (property.GetAccessors()[0].GetBaseDefinition().DeclaringType == baseFunctionType) continue; // Skipping private setters if (property.GetSetMethod(false) == null) continue; // Skipping explicitly ignored attributes if (property.GetCustomAttributes(typeof(FunctionParameterIgnoreAttribute), false).Any()) continue; var propType = property.PropertyType; var name = property.Name; FunctionParameterAttribute attr = null; var attributes = property.GetCustomAttributes(typeof(FunctionParameterAttribute), false).Cast<FunctionParameterAttribute>().ToList(); if (attributes.Count > 1) { Log.LogWarning(LogTitle, "More than one '{0}' attribute defined on property '{1}'. Location: '{2}'" .FormatWith(typeof(FunctionParameterAttribute).Name, name, filePath)); } else { attr = attributes.FirstOrDefault(); } WidgetFunctionProvider attibuteBasedWidgetProvider = null; WidgetFunctionProvider methodBasedWidgetProvider = null; if (attr != null && attr.HasWidgetMarkup) { try { attibuteBasedWidgetProvider = attr.GetWidgetFunctionProvider(type, property); } catch (Exception ex) { Log.LogWarning(LogTitle, "Failed to get widget function provider for parameter property {0}. Location: '{1}'" .FormatWith(property.Name, filePath)); Log.LogWarning(LogTitle, ex); } } parameterWidgets.TryGetValue(name, out methodBasedWidgetProvider); if (methodBasedWidgetProvider!=null && attibuteBasedWidgetProvider!=null) { Log.LogWarning(LogTitle, "Widget for property {0} is defined in both {1} attribute and in {2}() method. Remove one of the definitions. Location: '{3}'" .FormatWith(property.Name, nameof(FunctionParameterAttribute), nameof(IParameterWidgetsProvider.GetParameterWidgets), filePath)); } if (!functionParameters.ContainsKey(name)) { functionParameters.Add(name, new FunctionParameter(name, propType, attr, attibuteBasedWidgetProvider ?? methodBasedWidgetProvider)); } } type = type.BaseType; } return functionParameters; } private static IDictionary<string, WidgetFunctionProvider> GetParameterWidgets(object functionObject) { var widgetsProvider = functionObject as IParameterWidgetsProvider; IDictionary<string, WidgetFunctionProvider> parameterWidgets = widgetsProvider != null ? widgetsProvider.GetParameterWidgets() : null; return parameterWidgets ?? new Dictionary<string, WidgetFunctionProvider>(); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/FileBasedFunctionProvider/FunctionParameter.cs ================================================ using System; using System.Reflection; using Composite.Core.Extensions; using Composite.Functions; namespace Composite.Plugins.Functions.FunctionProviders.FileBasedFunctionProvider { /// <summary> /// Represents a function parameter /// </summary> public class FunctionParameter { /// <summary> /// Gets the parameter name. /// </summary> public string Name { get; private set; } /// <summary> /// Gets the parameter type. /// </summary> public Type Type { get; private set; } /// <summary> /// Gets the widget provider. /// </summary> public WidgetFunctionProvider WidgetProvider { get; private set; } /// <summary> /// Gets the function parameter attribute. /// </summary> /// <value> /// The attribute. /// </value> public FunctionParameterAttribute Attribute { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="FunctionParameter"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="type">The type.</param> /// <param name="functionParameterAttribute">The function parameter attribute.</param> /// <param name="widgetProvider">The widget provider.</param> public FunctionParameter(string name, Type type, FunctionParameterAttribute functionParameterAttribute, WidgetFunctionProvider widgetProvider) { Name = name; Type = type; Attribute = functionParameterAttribute; WidgetProvider = widgetProvider; } /// <summary> /// Sets the parameter value. /// </summary> /// <param name="functionObject">The function object.</param> /// <param name="parameterValue">The parameter value.</param> public void SetValue(object functionObject, object parameterValue) { GetParameterProperty(functionObject.GetType(), Name).SetValue(functionObject, parameterValue, null); } private static PropertyInfo GetParameterProperty(Type type, string propertyName) { var bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty | BindingFlags.DeclaredOnly; Type currentType = type; while (currentType != typeof(Type)) { var property = currentType.GetProperty(propertyName, bindingFlags); if (property != null) return property; currentType = currentType.BaseType; } throw new InvalidOperationException("Failed to find parameter property '{0}' on type '{1}'".FormatWith(propertyName, type.FullName)); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/FileBasedFunctionProvider/IParameterWidgetsProvider.cs ================================================ using System.Collections.Generic; using Composite.Functions; namespace Composite.Plugins.Functions.FunctionProviders.FileBasedFunctionProvider { /// <exclude /> public interface IParameterWidgetsProvider { /// <exclude /> IDictionary<string, WidgetFunctionProvider> GetParameterWidgets(); } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/FileBasedFunctionProvider/NotLoadedFileBasedFunction.cs ================================================ using System; using System.Collections.Generic; using System.Web; using System.Web.Hosting; using Composite.Core.Extensions; using Composite.Functions; namespace Composite.Plugins.Functions.FunctionProviders.FileBasedFunctionProvider { internal class NotLoadedFileBasedFunction<T> : FileBasedFunction<T>, IFunctionInitializationInfo where T : FileBasedFunction<T> { private readonly Exception _exception; public NotLoadedFileBasedFunction( FileBasedFunctionProvider<T> provider, string @namespace, string functionName, string virtualPath, Exception exception): base(@namespace, functionName, string.Empty, null, typeof(void), virtualPath, provider) { _exception = exception; } public override string Description { get { return (_exception != null) ? RemoveApplicationPath(_exception.Message) : base.Description; } } private static string RemoveApplicationPath(string compilationErrorMessage) { if (compilationErrorMessage.StartsWith(HostingEnvironment.ApplicationPhysicalPath, StringComparison.OrdinalIgnoreCase)) { return compilationErrorMessage.Substring(HostingEnvironment.ApplicationPhysicalPath.Length - 1); } return compilationErrorMessage; } override public object Execute(ParameterList parameters, FunctionContextContainer context) { if (_exception is HttpException) { EmbedSourceCodeInformation(_exception as HttpException); } throw new InvalidOperationException("Failed to load function '{0}'".FormatWith(this.CompositeName()), _exception); } Type IMetaFunction.ReturnType { get { return typeof(void); } } protected override void InitializeParameters() { Parameters = new Dictionary<string, FunctionParameter>(); } IEnumerable<ParameterProfile> IMetaFunction.ParameterProfiles { get { return new ParameterProfile[0]; } } bool IFunctionInitializationInfo.FunctionInitializedCorrectly { get { return false; } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/MethodBasedFunctionProvider/MethodBasedDefaultValueAttribute.cs ================================================ using System; namespace Composite.Plugins.Functions.FunctionProviders.MethodBasedFunctionProvider { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public sealed class MethodBasedDefaultValueAttribute : Attribute { /// <exclude /> public MethodBasedDefaultValueAttribute(string parameterName, object defaultValue) { this.ParameterName = parameterName; this.DefaultValue = defaultValue; } /// <exclude /> public string ParameterName { get; private set; } /// <exclude /> public object DefaultValue { get; private set; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/MethodBasedFunctionProvider/MethodBasedFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web.Hosting; using Composite.C1Console.Security; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.Types; using Composite.Data; using Composite.Data.Types; using Composite.Functions; namespace Composite.Plugins.Functions.FunctionProviders.MethodBasedFunctionProvider { internal class MethodBasedFunction : IFunction { private static string LogTitle; private readonly IMethodBasedFunctionInfo _methodBasedFunctionInfo; private readonly Type _type; private readonly MethodInfo _methodInfo; private volatile IList<ParameterProfile> _parameterProfile; private string _functionDescription; private object _object; protected MethodBasedFunction(string logTitle) { LogTitle = logTitle; } protected MethodBasedFunction(IMethodBasedFunctionInfo info, Type type, MethodInfo methodInfo) : this(typeof(MethodBasedFunction).Name) { _methodBasedFunctionInfo = info; _type = type; _methodInfo = methodInfo; } public static MethodBasedFunction Create(IMethodBasedFunctionInfo info) { Type type = TypeManager.TryGetType(info.Type); string errorMessage; if (type == null) { errorMessage = "Could not find the type '{0}'".FormatWith(info.Type); // Skipping error log while package installation, the type/method may be available after restart if (!HostingEnvironment.ApplicationHost.ShutdownInitiated()) { Log.LogError(LogTitle, GetErrorMessage(info) + errorMessage); } return new NotLoadedMethodBasedFunction(info, errorMessage); } MethodInfo methodInfo = GetMethodInfo(type, info.MethodName, info.Namespace, info.UserMethodName, out errorMessage); return methodInfo == null ? new NotLoadedMethodBasedFunction(info, errorMessage) : new MethodBasedFunction(info, type, methodInfo); } protected static MethodInfo GetMethodInfo(Type type, string methodName, string @namespace, string userMethodName, out string errorMessage) { MethodInfo methodInfo = type.GetMethods().FirstOrDefault(mi => mi.Name == methodName); errorMessage = null; if (methodInfo == null) { errorMessage = "Could not find the method '{0}' on the the type '{1}'".FormatWith(methodName, type.Name); // Skipping error log while package installation, the type/method may be available after restart if (!HostingEnvironment.ApplicationHost.ShutdownInitiated()) { Log.LogError(LogTitle, GetErrorMessage(@namespace, userMethodName) + errorMessage); } } return methodInfo; } private static string GetErrorMessage(string @namespace, string userMethodName) { return "Failed to initialize function '{0}.{1}'. ".FormatWith(@namespace, userMethodName); } private static string GetErrorMessage(IMethodBasedFunctionInfo info) { return "Failed to initialize function '{0}.{1}'. ".FormatWith(info.Namespace, info.UserMethodName); } public virtual object Execute(ParameterList parameters, FunctionContextContainer context) { IList<object> arguments = new List<object>(); foreach (ParameterProfile paramProfile in ParameterProfiles) { arguments.Add(parameters.GetParameter(paramProfile.Name, paramProfile.Type)); } object @object = this.MethodInfo.IsStatic ? null : this.Object; return this.MethodInfo.Invoke(@object, arguments.ToArray()); } public virtual string Name { get { return _methodBasedFunctionInfo.UserMethodName; } } public virtual string Namespace { get { return _methodBasedFunctionInfo.Namespace; } } public virtual string Description { get { if (string.IsNullOrEmpty(_functionDescription)) { _functionDescription = this.MethodInfo.GetCustomAttributes(typeof(FunctionAttribute), true).Select(f => ((FunctionAttribute)f).Description).FirstOrDefault(); if (string.IsNullOrEmpty(_functionDescription)) { return string.Format("This is a static method call to the function '{0}' on '{1}'.", _methodBasedFunctionInfo.MethodName, _methodBasedFunctionInfo.Type); } } return _functionDescription; } } public Type ReturnType { get { return MethodInfo.ReturnType; } } public IEnumerable<ParameterProfile> ParameterProfiles { get { if (_parameterProfile == null) { lock (this) { if (_parameterProfile == null) { _parameterProfile = InitializeParamteres(); } } } return _parameterProfile; } } private IList<ParameterProfile> InitializeParamteres() { ParameterInfo[] parameterInfos = this.MethodInfo.GetParameters(); var defaultValues = new Dictionary<string, object>(); var labels = new Dictionary<string, string>(); var helpTexts = new Dictionary<string, string>(); var widgetProviders = new Dictionary<string, WidgetFunctionProvider>(); var parametersToHideInSimpleView = new HashSet<string>(); foreach (object obj in this.MethodInfo.GetCustomAttributes(typeof (MethodBasedDefaultValueAttribute), true)) { MethodBasedDefaultValueAttribute attribute = (MethodBasedDefaultValueAttribute) obj; defaultValues.Add(attribute.ParameterName, attribute.DefaultValue); } // Run through obsolete FunctionParameterDescriptionAttribute #pragma warning disable 612,618 foreach ( object obj in this.MethodInfo.GetCustomAttributes(typeof (FunctionParameterDescriptionAttribute), true)) { FunctionParameterDescriptionAttribute attribute = (FunctionParameterDescriptionAttribute) obj; if (attribute.HasDefaultValue && !defaultValues.ContainsKey(attribute.ParameterName)) defaultValues.Add(attribute.ParameterName, attribute.DefaultValue); labels.Add(attribute.ParameterName, attribute.ParameterLabel); helpTexts.Add(attribute.ParameterName, attribute.ParameterHelpText); } #pragma warning restore 612,618 // Run trhough new and improved FunctionParameterAttribute. Many may exist for one parameter. foreach (object obj in this.MethodInfo.GetCustomAttributes(typeof (FunctionParameterAttribute), true)) { var attribute = (FunctionParameterAttribute) obj; Verify.That(attribute.HasName, "All [FunctionParameter(...)] definitions on the method '{0}' must have 'Name' specified.", this.MethodInfo.Name); string parameterName = attribute.Name; if (attribute.HasDefaultValue && !defaultValues.ContainsKey(parameterName)) defaultValues.Add(parameterName, attribute.DefaultValue); if (attribute.HasLabel && !labels.ContainsKey(parameterName)) labels.Add(parameterName, attribute.Label); if (attribute.HasHelp && !helpTexts.ContainsKey(parameterName)) helpTexts.Add(parameterName, attribute.Help); if (attribute.HasWidgetMarkup && !widgetProviders.ContainsKey(parameterName)) { try { var widgetFunctionProvider = attribute.GetWidgetFunctionProvider(null, null); widgetProviders.Add(parameterName, widgetFunctionProvider); } catch (Exception ex) { string errText = "Failed to set Widget Markup for parameter '{0}' on method '{1}'. {2}" .FormatWith(parameterName, this.MethodInfo.Name, ex.Message); throw new InvalidOperationException(errText); } } if (attribute.HideInSimpleView) { parametersToHideInSimpleView.Add(parameterName); } } var result = new List<ParameterProfile>(); foreach (ParameterInfo parameterInfo in parameterInfos) { string parameterName = parameterInfo.Name; BaseValueProvider valueProvider; object defaultValue = null; if (defaultValues.TryGetValue(parameterName, out defaultValue)) { valueProvider = new ConstantValueProvider(defaultValue); } else { valueProvider = new NoValueValueProvider(); } bool isRequired = !defaultValues.ContainsKey(parameterName); string parameterLabel = parameterInfo.Name; if (labels.ContainsKey(parameterName)) parameterLabel = labels[parameterName]; string parameterHelpText = ""; if (helpTexts.ContainsKey(parameterName)) parameterHelpText = helpTexts[parameterName]; WidgetFunctionProvider widgetFunctionProvider = (widgetProviders.ContainsKey(parameterName) ? widgetProviders[parameterName] : StandardWidgetFunctions.GetDefaultWidgetFunctionProviderByType(parameterInfo.ParameterType)); bool hideInSimpleView = parametersToHideInSimpleView.Contains(parameterName); result.Add(new ParameterProfile(parameterName, parameterInfo.ParameterType, isRequired, valueProvider, widgetFunctionProvider, parameterLabel, new HelpDefinition(parameterHelpText), hideInSimpleView)); } return result; } protected virtual MethodInfo MethodInfo { get { return _methodInfo; } } private object Object { get { if (_object == null) { _object = Activator.CreateInstance(_type); } return _object; } } public virtual EntityToken EntityToken { get { return _methodBasedFunctionInfo.GetDataEntityToken(); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/MethodBasedFunctionProvider/MethodBasedFunctionProvider.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Threading; using Composite.Core; using Composite.Core.Caching; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.Threading; using Composite.Core.Types; using Composite.Data; using Composite.Data.Types; using Composite.Functions; using Composite.Functions.Inline; using Composite.Functions.Plugins.FunctionProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.Functions.FunctionProviders.MethodBasedFunctionProvider { [ConfigurationElementType(typeof(MethodBasedFunctionProviderData))] internal sealed class MethodBasedFunctionProvider : IFunctionProvider { static readonly FileRelatedDataCache<Type> _inlineFunctionReturnTypeCache = new FileRelatedDataCache<Type>( "Functions", "inlineFuncReturnType", (type, filePath) => C1File.WriteAllText(filePath, TypeManager.SerializeType(type)), (filePath) => TypeManager.TryGetType(C1File.ReadAllText(filePath))); private static readonly string LogTitle = typeof (MethodBasedFunctionProvider).Name; private FunctionNotifier _functionNotifier; public MethodBasedFunctionProvider() { var events = ChangeEventsSingleton.Instance; lock (events.SyncRoot) { events.DataChangedEvent += OnDataChanged; events.FileChangedEvent += CodeFileDirectoryWatcher_Changed; } } public FunctionNotifier FunctionNotifier { set { _functionNotifier = value; } } public IEnumerable<IFunction> Functions { get { IList<IFunction> result = new List<IFunction>(); var methodBasedFunctionInfos = DataFacade.GetData<IMethodBasedFunctionInfo>(); foreach (IMethodBasedFunctionInfo info in methodBasedFunctionInfos) { IFunction methodBasedFunction = MethodBasedFunction.Create(info); if (methodBasedFunction == null) continue; result.Add(methodBasedFunction); } var editableMethodBasedFunctionInfos = DataFacade.GetData<IInlineFunction>(); foreach (IInlineFunction info in editableMethodBasedFunctionInfos) { Type cachedReturnType = GetCachedReturnType(info); IFunction inlineFunction; if (cachedReturnType != null) { inlineFunction = new LazyInitializedInlineFunction(info, cachedReturnType); } else { inlineFunction = InlineFunction.Create(info); if (!(inlineFunction is NotLoadedInlineFunction)) { AddReturnTypeToCache(info, inlineFunction.ReturnType); } } result.Add(inlineFunction); } return result; } } private void AddReturnTypeToCache(IInlineFunction info, Type type) { string functionName = info.Namespace + "." + info.Name; string filePath = info.GetSourceFilePath(); _inlineFunctionReturnTypeCache.Add(functionName, filePath, type); } private Type GetCachedReturnType(IInlineFunction info) { string functionName = info.Namespace + "." + info.Name; string filePath = info.GetSourceFilePath(); Type type; if(!_inlineFunctionReturnTypeCache.Get(functionName, filePath, out type)) { return null; } return type; } private void OnDataChanged(object sender, EventArgs eventArgs) { // Checking for null since it is possible that event will be raised before the provider is fully initialized if (_functionNotifier != null) { _functionNotifier.FunctionsUpdated(); } } void CodeFileDirectoryWatcher_Changed(object sender, FileSystemEventArgs e) { // Checking for null since it is possible that event will be raised before the provider is fully initialized if (_functionNotifier != null) { _functionNotifier.FunctionsUpdated(); } } private sealed class ChangeEventsSingleton { public readonly object SyncRoot = new object(); public event EventHandler DataChangedEvent; public event FileSystemEventHandler FileChangedEvent; private readonly C1FileSystemWatcher _codeDirectoryFileSystemWatcher; private DateTime _lastWriteHandleTime = DateTime.MinValue; private object _fileUpdateLock = new object(); private ChangeEventsSingleton() { DataEventSystemFacade.SubscribeToStoreChanged<IMethodBasedFunctionInfo>(OnDataChanged, true); DataEventSystemFacade.SubscribeToDataDeleted<IInlineFunction>(OnDataChanged, true); DataEventSystemFacade.SubscribeToStoreChanged<IInlineFunction>(OnStoreChanged, true); string folderToWatch = PathUtil.Resolve(GlobalSettingsFacade.InlineCSharpFunctionDirectory); DirectoryUtils.EnsureDirectoryExists(folderToWatch); _codeDirectoryFileSystemWatcher = new C1FileSystemWatcher(folderToWatch) { NotifyFilter = NotifyFilters.LastWrite, EnableRaisingEvents = true, IncludeSubdirectories = true }; _codeDirectoryFileSystemWatcher.Changed += OnFileWatcherEvent; } void OnFileWatcherEvent(object sender, FileSystemEventArgs e) { FileSystemEventHandler hander = FileChangedEvent; if (hander != null) { lock (_fileUpdateLock) { bool fileExists = true; if (fileExists) { // Supress multiple events fireing by observing last write time DateTime writeTime = C1File.GetLastWriteTime(e.FullPath); if (_lastWriteHandleTime < writeTime) { _lastWriteHandleTime = writeTime; try { using (ThreadDataManager.EnsureInitialize()) { hander(sender, e); } } catch (ThreadAbortException) { } catch (Exception ex) { Log.LogWarning(LogTitle, "Failed to reload functions on file watcher event"); Log.LogError(LogTitle, ex); } } } } } } private void OnStoreChanged(object sender, StoreEventArgs storeEventArgs) { if (!storeEventArgs.DataEventsFired) { EventHandler hander = DataChangedEvent; if (hander != null) { hander(sender, storeEventArgs); } } } private void OnDataChanged(object sender, EventArgs eventArgs) { EventHandler hander = DataChangedEvent; if (hander != null) { hander(sender, eventArgs); } } public static ChangeEventsSingleton Instance { get { return Nested.InstanceInt; } } class Nested { static Nested() { // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit } internal static readonly ChangeEventsSingleton InstanceInt = new ChangeEventsSingleton(); } } } [Assembler(typeof(NonConfigurableFunctionProviderAssembler))] internal sealed class MethodBasedFunctionProviderData : FunctionProviderData { } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/MethodBasedFunctionProvider/NotLoadedMethodBasedFunction.cs ================================================ using System; using System.Collections.Generic; using Composite.Data.Types; using Composite.Functions; namespace Composite.Plugins.Functions.FunctionProviders.MethodBasedFunctionProvider { internal class NotLoadedMethodBasedFunction : MethodBasedFunction, IFunction, IFunctionInitializationInfo { private readonly string _errorMessage; public NotLoadedMethodBasedFunction(IMethodBasedFunctionInfo functionInfo, string errorMessage) : base(functionInfo, null, null) { _errorMessage = errorMessage; } public override string Description { get { return _errorMessage; } } object IFunction.Execute(ParameterList parameters, FunctionContextContainer context) { throw new InvalidOperationException(_errorMessage); } Type IMetaFunction.ReturnType { get { return typeof(void); } } IEnumerable<ParameterProfile> IMetaFunction.ParameterProfiles { get { return new ParameterProfile[0]; } } bool IFunctionInitializationInfo.FunctionInitializedCorrectly { get { return false; } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/RazorFunctionProvider/RazorBasedFunction.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Web.WebPages; using Composite.AspNet.Razor; using Composite.Core.IO; using Composite.Core.WebClient; using Composite.Core.Xml; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.FileBasedFunctionProvider; namespace Composite.Plugins.Functions.FunctionProviders.RazorFunctionProvider { [DebuggerDisplay("Razor function: {Namespace + '.' + Name}")] internal class RazorBasedFunction : FileBasedFunction<RazorBasedFunction>, IDynamicFunction { public RazorBasedFunction(string ns, string name, string description, IDictionary<string, FunctionParameter> parameters, Type returnType, string virtualPath, bool preventCaching, FileBasedFunctionProvider<RazorBasedFunction> provider) : base(ns, name, description, parameters, returnType, virtualPath, provider) { PreventFunctionOutputCaching = preventCaching; } public RazorBasedFunction(string ns, string name, string description, Type returnType, string virtualPath, bool preventCaching, FileBasedFunctionProvider<RazorBasedFunction> provider) : base(ns, name, description, returnType, virtualPath, provider) { PreventFunctionOutputCaching = preventCaching; } protected override void InitializeParameters() { WebPageBase razorPage = null; try { using (BuildManagerHelper.DisableUrlMetadataCachingScope()) { razorPage = WebPage.CreateInstanceFromVirtualPath(VirtualPath); } var razorFunction = razorPage as RazorFunction; if (razorFunction == null) { throw new InvalidOperationException($"Failed to initialize function from cache. Path: '{VirtualPath}'"); } Parameters = FunctionBasedFunctionProviderHelper.GetParameters(razorFunction, typeof (RazorFunction), VirtualPath); PreventFunctionOutputCaching = razorFunction.PreventFunctionOutputCaching; } finally { (razorPage as IDisposable)?.Dispose(); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { void SetParametersAction(WebPageBase webPageBase) { foreach (var param in parameters.AllParameterNames) { var parameter = Parameters[param]; object parameterValue = parameters.GetParameter(param); parameter.SetValue(webPageBase, parameterValue); } } try { return RazorHelper.ExecuteRazorPage(VirtualPath, SetParametersAction, ReturnType, context); } catch (Exception ex) { EmbedExecutionExceptionSourceCode(ex); throw; } } private void EmbedExecutionExceptionSourceCode(Exception ex) { if (ex is ThreadAbortException || ex is StackOverflowException || ex is OutOfMemoryException || ex is ThreadInterruptedException) { return; } var stackTrace = new StackTrace(ex, true); string fullFilePath = PathUtil.Resolve(VirtualPath); foreach (var frame in stackTrace.GetFrames()) { string fileName = frame.GetFileName(); if (fileName != null && fileName.StartsWith(fullFilePath, StringComparison.InvariantCultureIgnoreCase)) { var sourceCode = C1File.ReadAllLines(fileName); XhtmlErrorFormatter.EmbedSourceCodeInformation(ex, sourceCode, frame.GetFileLineNumber()); return; } } } /// <exclude /> public bool PreventFunctionOutputCaching { get; protected set; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/RazorFunctionProvider/RazorFunctionProvider.cs ================================================ using System; using System.Web.Hosting; using System.Web.WebPages; using Composite.AspNet.Razor; using Composite.Core; using Composite.Core.WebClient; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.FileBasedFunctionProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Functions.FunctionProviders.RazorFunctionProvider { [ConfigurationElementType(typeof(RazorFunctionProviderData))] internal class RazorFunctionProvider : FileBasedFunctionProvider<RazorBasedFunction> { protected override string FileExtension => "cshtml"; protected override string DefaultFunctionNamespace => "Razor"; public RazorFunctionProvider(string name, string folder) : base(name, folder) { } protected override IFunction InstantiateFunction(string virtualPath, string @namespace, string name) { if (!HostingEnvironment.IsHosted) { return null; } WebPageBase razorPage; using (BuildManagerHelper.DisableUrlMetadataCachingScope()) { razorPage = WebPage.CreateInstanceFromVirtualPath(virtualPath); } if (!(razorPage is RazorFunction razorFunction)) { Log.LogWarning(nameof(RazorFunctionProvider), $"Razor page '{virtualPath}' does not inherit from the base class for razor functions '{typeof(RazorFunction).FullName}' and will be ignored"); return null; } try { var functionParameters = FunctionBasedFunctionProviderHelper.GetParameters( razorFunction, typeof(RazorFunction), virtualPath); return new RazorBasedFunction(@namespace, name, razorFunction.FunctionDescription, functionParameters, razorFunction.FunctionReturnType, virtualPath, razorFunction.PreventFunctionOutputCaching, this); } finally { razorFunction.Dispose(); } } protected override IFunction InstantiateFunctionFromCache(string virtualPath, string @namespace, string name, Type returnType, string cachedDescription, bool preventCaching) { if (returnType != null) { return new RazorBasedFunction(@namespace, name, cachedDescription, returnType, virtualPath, preventCaching, this); } return InstantiateFunction(virtualPath, @namespace, name); } protected override bool HandleChange(string path) { return path.EndsWith(FileExtension); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/RazorFunctionProvider/RazorFunctionProviderAssembler.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; using Composite.Functions.Plugins.FunctionProvider; namespace Composite.Plugins.Functions.FunctionProviders.RazorFunctionProvider { internal class RazorFunctionProviderAssembler : IAssembler<IFunctionProvider, FunctionProviderData> { IFunctionProvider IAssembler<IFunctionProvider, FunctionProviderData>.Assemble(IBuilderContext context, FunctionProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { var data = objectConfiguration as RazorFunctionProviderData; if (data == null) { throw new ArgumentException("Expected configuration to be of type RazorFunctionProviderData", "objectConfiguration"); } return new RazorFunctionProvider(data.Name, data.Directory); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/RazorFunctionProvider/RazorFunctionProviderData.cs ================================================ using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Composite.Functions.Plugins.FunctionProvider; namespace Composite.Plugins.Functions.FunctionProviders.RazorFunctionProvider { [Assembler(typeof(RazorFunctionProviderAssembler))] internal class RazorFunctionProviderData : FunctionProviderData { [ConfigurationProperty("directory", IsRequired = false, DefaultValue = "~/App_Data/Razor")] public string Directory { get { return (string)base["directory"]; } set { base["directory"] = value; } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/SqlFunctionProvider/SqlFunction.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Linq; using Composite.C1Console.Security; using Composite.C1Console.Security.Cryptography; using Composite.Core.Caching; using Composite.Core.Extensions; using Composite.Core.Sql; using Composite.Core.Types; using Composite.Data; using Composite.Data.Types; using Composite.Functions; using Composite.Functions.ManagedParameters; namespace Composite.Plugins.Functions.FunctionProviders.SqlFunctionProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class SqlFunction : IFunction { ISqlFunctionInfo _functionInfo; IEnumerable<ParameterProfile> _parameterProfiles; private object _lock = new object(); /// <exclude /> public SqlFunction(ISqlFunctionInfo functionInfo, IEnumerable<ParameterProfile> parameterProfiles) : this(functionInfo) { _parameterProfiles = parameterProfiles; } /// <exclude /> public SqlFunction(ISqlFunctionInfo functionInfo) { _functionInfo = functionInfo; Updated = true; } private bool Updated { get { return RequestLifetimeCache.HasKey(this); } set { Verify.IsTrue(value, "Only 'true' value can be assigned to this property."); RequestLifetimeCache.Add(this, true); } } /// <exclude /> public object Execute(ParameterList parameters, FunctionContextContainer context) { EnsureUpdated(); Dictionary<string, object> sqlParameters = new Dictionary<string, object>(); foreach (ParameterProfile profile in ParameterProfiles) { object value = parameters.GetParameter(profile.Name); sqlParameters.Add(profile.Name, value); } ISqlConnection sqlConnection = GetConnection(); string connectionString = sqlConnection.EncryptedConnectionString.Decrypt(); Verify.That(!connectionString.IsNullOrEmpty(), "Connection string is empty"); string result = null; if (sqlConnection.IsMsSql) { result = RunSequel(connectionString, sqlParameters); } else { result = RunOleDbSequel(connectionString, sqlParameters); } return BuidlXElement(result); } /// <exclude /> public string Name { get { return _functionInfo.Name; } } /// <exclude /> public string Namespace { get { return _functionInfo.Namespace; } } /// <exclude /> public string Description { get { return _functionInfo.Description; } } /// <exclude /> public Type ReturnType { get { return typeof(XElement); } } /// <exclude /> public IEnumerable<ParameterProfile> ParameterProfiles { get { lock (_lock) { if (_parameterProfiles == null) { _parameterProfiles = ManagedParameterManager.GetParameterProfiles(_functionInfo.Id); } } return _parameterProfiles; } } private ISqlConnection GetConnection() { Guid connectionId = _functionInfo.ConnectionId; var connection = (from item in DataFacade.GetData<ISqlConnection>() where item.Id == connectionId select item).FirstOrDefault(); if (connection == null) { throw new ArgumentException("Could not find connection information for query", "queryId"); } return connection; } private static XElement BuidlXElement(string item) { string result = "<root>" + item + "</root>"; StringReader reader = new StringReader(result); return XElement.Load(reader); } private ISqlFunctionInfo GetQuery(Guid xmlQueryId) { var sqlQuery = (from item in DataFacade.GetData<ISqlFunctionInfo>() where item.Id == xmlQueryId select item).FirstOrDefault(); return sqlQuery; } private class ConvertedQuery { public string Query { get; set; } public IDictionary<string, object> Parameters { get; set; } } private static ConvertedQuery ConvertToMSSqlSyntax(ISqlFunctionInfo queryInfo, IDictionary<string, object> parameterNames) { ConvertedQuery convertedQuery = new ConvertedQuery(); StringBuilder builder = new StringBuilder(); foreach (string name in parameterNames.Keys) { builder.Append(name); builder.Append("|"); } builder.Remove(builder.Length - 1, 1); string regExp = builder.ToString(); MatchCollection collection = new Regex(regExp).Matches(queryInfo.Command); IDictionary<string, object> oleDbParams = new Dictionary<string, object>(); int i = 1; foreach (Match match in collection) { oleDbParams.Add("@sp" + i, parameterNames[match.Value.Trim()]); i++; } convertedQuery.Parameters = oleDbParams; convertedQuery.Query = queryInfo.Command; foreach (string name in parameterNames.Keys) { convertedQuery.Query = convertedQuery.Query.Replace(name, "?"); } return convertedQuery; } private static bool ShouldConvert(ISqlFunctionInfo info, IDictionary<string, object> parameters) { if (info.IsStoredProcedure) { return false; } if (parameters.Count == 0) { return false; } return true; } private string RunOleDbSequel(string connectionString, IDictionary<string, object> parameters) { string query = _functionInfo.Command; IDictionary<string, object> queryParameters = parameters; if (ShouldConvert(_functionInfo, parameters)) { ConvertedQuery convertedQuery = ConvertToMSSqlSyntax(_functionInfo, parameters); query = convertedQuery.Query; queryParameters = convertedQuery.Parameters; } DataSet dataSet = null; string result = string.Empty; using (OleDbConnection connection = new OleDbConnection(connectionString)) { using (OleDbCommand command = new OleDbCommand(query, connection)) { if (_functionInfo.IsStoredProcedure) { command.CommandType = CommandType.StoredProcedure; } else { command.CommandType = CommandType.Text; } foreach (KeyValuePair<string, object> parm in queryParameters) { command.Parameters.Add(new OleDbParameter(parm.Key, parm.Value)); } connection.Open(); if (_functionInfo.IsQuery) { dataSet = new DataSet(); using (OleDbDataAdapter adapter = new OleDbDataAdapter()) { adapter.SelectCommand = command; adapter.Fill(dataSet); if (dataSet != null && !dataSet.HasChanges()) { StringWriter writer = new StringWriter(); dataSet.WriteXml(writer); result = writer.ToString(); } } } else { command.ExecuteNonQuery(); } } } return result; } private string RunSequel(string connectionString, IDictionary<string, object> parameters) { XmlReader reader = null; DataSet dataSet = null; string result = string.Empty; var connection = SqlConnectionManager.GetConnection(connectionString); using (SqlCommand command = new SqlCommand(_functionInfo.Command, connection)) { if (_functionInfo.IsStoredProcedure) { command.CommandType = CommandType.StoredProcedure; } else { command.CommandType = CommandType.Text; } foreach (KeyValuePair<string, object> parm in parameters) { command.Parameters.Add(new SqlParameter(parm.Key, parm.Value)); } if (_functionInfo.IsQuery) { if (_functionInfo.ReturnsXml) { reader = command.ExecuteXmlReader(); StringBuilder builder = new StringBuilder(); reader.Read(); while (!reader.EOF) { builder.Append(reader.ReadOuterXml()); } result = builder.ToString(); } else { dataSet = new DataSet(); using (SqlDataAdapter adapter = new SqlDataAdapter()) { adapter.SelectCommand = command; adapter.Fill(dataSet); if (dataSet != null && !dataSet.HasChanges()) { StringWriter writer = new StringWriter(); dataSet.WriteXml(writer); result = writer.ToString(); } } } } else { command.ExecuteNonQuery(); } } return result; } private void EnsureUpdated() { if (Updated) return; ISqlFunctionInfo oldValue = _functionInfo; _functionInfo = (ISqlFunctionInfo) DataFacade.GetDataFromDataSourceId(_functionInfo.DataSourceId, true); Verify.That(_functionInfo != null, "Failed to get function '{0}'", oldValue.Name); Updated = true; } /// <exclude /> public EntityToken EntityToken { get { return _functionInfo.GetDataEntityToken(); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/SqlFunctionProvider/SqlFunctionProvider.cs ================================================ using System.Collections.Generic; using Composite.Data; using Composite.Data.Types; using Composite.Functions; using Composite.Functions.Plugins.FunctionProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Functions.FunctionProviders.SqlFunctionProvider { [ConfigurationElementType(typeof(SqlFunctionProviderData))] internal sealed class SqlFunctionProvider : IFunctionProvider { private FunctionNotifier _functionNotifier; public SqlFunctionProvider() { DataEventSystemFacade.SubscribeToStoreChanged<ISqlFunctionInfo>(OnDataChanged, false); } public FunctionNotifier FunctionNotifier { set { _functionNotifier = value; } } public IEnumerable<IFunction> Functions { get { IEnumerable<ISqlFunctionInfo> functionInfos = DataFacade.GetData<ISqlFunctionInfo>(); IList<IFunction> functions = new List<IFunction>(); foreach (ISqlFunctionInfo function in functionInfos) { functions.Add(new SqlFunction(function)); } return functions; } } private void OnDataChanged(object sender, StoreEventArgs storeEventArgs) { _functionNotifier.FunctionsUpdated(); } } [Assembler(typeof(SqlFunctionProviderAssembler))] internal sealed class SqlFunctionProviderData : FunctionProviderData { } internal sealed class SqlFunctionProviderAssembler : IAssembler<IFunctionProvider, FunctionProviderData> { public IFunctionProvider Assemble(IBuilderContext context, FunctionProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new SqlFunctionProvider(); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/AspNet/LoadUserControlFunction.cs ================================================ using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.AspNet { internal sealed class LoadUserControlFunction : StandardFunctionBase { public LoadUserControlFunction(EntityTokenFactory entityTokenFactory) : base("LoadUserControl", "Composite.AspNet", typeof(UserControl), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield return new StandardFunctionParameterProfile( "Path", typeof(string), true, new NoValueValueProvider(), StandardWidgetFunctions.TextBoxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { string path = parameters.GetParameter<string>("Path"); Page currentPage = HttpContext.Current.Handler as Page; if (currentPage == null) throw new InvalidOperationException("The Current HttpContext Handler must be a System.Web.Ui.Page"); return currentPage.LoadControl(path); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Constant/BooleanFunction.cs ================================================ using System; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Constant { internal sealed class BooleanFunction : StandardFunctionBase { public BooleanFunction(EntityTokenFactory entityTokenFactory) : base("Boolean", "Composite.Constant", typeof(bool), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.GetBoolSelectorWidget("True", "False"); yield return new StandardFunctionParameterProfile( "Constant", typeof(bool), true, new ConstantValueProvider(false), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { return parameters.GetParameter<bool>("Constant"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Constant/DateTimeFunction.cs ================================================ using System; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Constant { internal sealed class DateTimeFunction : StandardFunctionBase { public DateTimeFunction(EntityTokenFactory entityTokenFactory) : base("DateTime", "Composite.Constant", typeof(DateTime), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider dateSelectorWidget = StandardWidgetFunctions.DateTimeSelectorWidget; yield return new StandardFunctionParameterProfile( "Constant", typeof(DateTime), true, new ConstantValueProvider(DateTime.Now), dateSelectorWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { return parameters.GetParameter<DateTime>("Constant"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Constant/DecimalFunction.cs ================================================ using System; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Constant { internal sealed class DecimalFunction : StandardFunctionBase { public DecimalFunction(EntityTokenFactory entityTokenFactory) : base("Decimal", "Composite.Constant", typeof(decimal), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.DecimalTextBoxWidget; yield return new StandardFunctionParameterProfile( "Constant", typeof(decimal), true, new ConstantValueProvider(new decimal(0)), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { return parameters.GetParameter<decimal>("Constant"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Constant/GuidFunction.cs ================================================ using System; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Constant { internal sealed class GuidFunction : StandardFunctionBase { public GuidFunction(EntityTokenFactory entityTokenFactory) : base("Guid", "Composite.Constant", typeof(Guid), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.GuidTextBoxWidget; yield return new StandardFunctionParameterProfile( "Constant", typeof(Guid), true, new ConstantValueProvider(Guid.Empty), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { return new Guid(parameters.GetParameter<string>("Constant")); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Constant/IntegerFunction.cs ================================================ using System; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Constant { internal sealed class IntegerFunction : StandardFunctionBase { public IntegerFunction(EntityTokenFactory entityTokenFactory) : base("Integer", "Composite.Constant", typeof(int), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.IntegerTextBoxWidget; yield return new StandardFunctionParameterProfile( "Constant", typeof(int), true, new ConstantValueProvider(0), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { return parameters.GetParameter<int>("Constant"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Constant/StringFunction.cs ================================================ using System; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Constant { internal sealed class StringFunction : StandardFunctionBase { public StringFunction(EntityTokenFactory entityTokenFactory) : base("String", "Composite.Constant", typeof(string), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextAreaWidget; yield return new StandardFunctionParameterProfile("Constant", typeof(string), false, new ConstantValueProvider(""), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { return parameters.GetParameter<string>("Constant"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Constant/XhtmlDocumentFunction.cs ================================================ using System; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; using Composite.Core.Xml; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Constant { internal sealed class XhtmlDocumentFunction : StandardFunctionBase { public XhtmlDocumentFunction(EntityTokenFactory entityTokenFactory) : base("XhtmlDocument", "Composite.Constant", typeof(XhtmlDocument), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider editorWidget = StandardWidgetFunctions.VisualXhtmlDocumentEditorWidget; yield return new StandardFunctionParameterProfile("Constant", typeof(XhtmlDocument), true, new NoValueValueProvider(), editorWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { return parameters.GetParameter<XhtmlDocument>("Constant"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Foundation/DowncastableStandardFunctionBase.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Functions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation { internal abstract class DowncastableStandardFunctionBase : StandardFunctionBase, IDowncastableFunction { public DowncastableStandardFunctionBase(string name, string namespaceName, Type returnType, EntityTokenFactory entityTokenFactory) : base(name,namespaceName, returnType, entityTokenFactory) { } public bool ReturnValueIsDowncastable { get { return true; } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Foundation/EntityTokenFactory.cs ================================================ using Composite.C1Console.Security; using Composite.Functions; using Composite.Core.Extensions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class EntityTokenFactory { private readonly string _providerName; /// <exclude /> public EntityTokenFactory(string providerName) { _providerName = providerName; } internal EntityToken CreateEntityToken(IMetaFunction function) { string id = StringExtensionMethods.CreateNamespace(function.Namespace, function.Name, '.'); return new StandardFunctionProviderEntityToken(_providerName, id ); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Foundation/StandardFunctionBase.cs ================================================ using System; using System.Collections.Generic; using Composite.Functions; using Composite.C1Console.Security; using Composite.Core.Logging; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation { internal abstract class StandardFunctionBase : IFunction { private EntityTokenFactory _entityTokenFactory; internal StandardFunctionBase(string name, string namespaceName, Type returnType, EntityTokenFactory entityTokenFactory) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name"); if (string.IsNullOrEmpty(namespaceName)) throw new ArgumentNullException("namespaceName"); if (entityTokenFactory == null) throw new ArgumentNullException("entityTokenFactory"); this.Namespace = namespaceName; this.Name = name; this.ReturnType = returnType; _entityTokenFactory = entityTokenFactory; this.ResourceHandleNameStem = string.Format("{0}.{1}", this.Namespace, this.Name); } public string Name { get; private set; } public string Namespace { get; protected set; } public string Description { get { return LocalizationToken("description"); } } public Type ReturnType { get; private set; } public IEnumerable<ParameterProfile> ParameterProfiles { get { foreach (StandardFunctionParameterProfile param in this.StandardFunctionParameterProfiles) { string labelString; string helpString; if (string.IsNullOrEmpty(param.CustomLabel) == false) { labelString = param.CustomLabel; } else { labelString = LocalizationToken(string.Format("param.{0}.label", param.Name)); } if (string.IsNullOrEmpty(param.CustomHelpText) == false) { helpString = param.CustomHelpText; } else { helpString = LocalizationToken(string.Format("param.{0}.help", param.Name)); } yield return new ParameterProfile(param.Name, param.Type, param.IsRequired, param.FallbackValueProvider, param.WidgetFunctionProvider, labelString, new HelpDefinition(helpString)); } } } protected virtual IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield break; } } public abstract object Execute(ParameterList parameters, FunctionContextContainer context); public EntityToken EntityToken { get { return _entityTokenFactory.CreateEntityToken(this); } } private string LocalizationToken(string functionLocalPart) { return string.Format( "${{Composite.Plugins.StandardFunctions,{0}.{1}}}", this.ResourceHandleNameStem, functionLocalPart ); } public string ResourceHandleNameStem {get; protected set; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Foundation/StandardFunctionParameterProfile.cs ================================================ using System; using Composite.Functions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation { internal sealed class StandardFunctionParameterProfile { public StandardFunctionParameterProfile( string name, Type type, bool isRequired, BaseValueProvider fallbackValueProvider, WidgetFunctionProvider widgetFunctionProvider) { this.Name = name; this.Type = type; this.IsRequired = isRequired; this.FallbackValueProvider = fallbackValueProvider; this.WidgetFunctionProvider = widgetFunctionProvider; } public StandardFunctionParameterProfile( string name, Type type, bool isRequired, BaseValueProvider fallbackValueProvider, WidgetFunctionProvider widgetFunctionProvider, string customResourceHandleNamespace) : this( name,type,isRequired,fallbackValueProvider, widgetFunctionProvider) { this.CustomResourceHandleNamespace = customResourceHandleNamespace; } public string Name { get; private set; } public Type Type{ get; private set; } public bool IsRequired{ get; private set; } public BaseValueProvider FallbackValueProvider{ get; private set; } public WidgetFunctionProvider WidgetFunctionProvider{ get; private set; } public string CustomLabel { get; set; } public string CustomHelpText { get; set; } public string CustomResourceHandleNamespace { get; private set; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/IDataGenerated/AddDataInstance.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Xml.Linq; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.IDataGenerated { internal sealed class AddDataInstance<T> : StandardFunctionBase where T : class, IData { private List<StandardFunctionParameterProfile> _parameterProfiles = null; public AddDataInstance(EntityTokenFactory entityTokenFactory) : base("AddDataInstance", typeof(T).FullName, typeof(void), entityTokenFactory) { this.ResourceHandleNameStem = "Composite.IDataGenerated.AddDataInstance"; } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { if (_parameterProfiles == null) { _parameterProfiles = new List<StandardFunctionParameterProfile>(); DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(typeof(T)); foreach (DataFieldDescriptor dataFieldDescriptor in dataTypeDescriptor.Fields) { string helpText = dataFieldDescriptor.Name; if (dataFieldDescriptor.FormRenderingProfile != null && !string.IsNullOrWhiteSpace(dataFieldDescriptor.FormRenderingProfile.HelpText)) { helpText = dataFieldDescriptor.FormRenderingProfile.HelpText; } bool isGuidKeyField = dataTypeDescriptor.KeyPropertyNames.Contains(dataFieldDescriptor.Name) && (dataFieldDescriptor.InstanceType == typeof(Guid)); bool isRequried = dataFieldDescriptor.DefaultValue == null; if (isGuidKeyField) { isRequried = false; } _parameterProfiles.Add(new StandardFunctionParameterProfile( dataFieldDescriptor.Name, dataFieldDescriptor.InstanceType, isRequried, DataInstanceHelper.GetFallbackValueProvider(dataFieldDescriptor, isGuidKeyField), DataInstanceHelper.GetWidgetFunctionProvider(dataFieldDescriptor) ) { CustomLabel = dataFieldDescriptor.Name, CustomHelpText = helpText }); } } return _parameterProfiles; } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { T data = DataFacade.BuildNew<T>(); List<PropertyInfo> typePropertites = typeof(T).GetPropertiesRecursively(); foreach (string parameterName in parameters.AllParameterNames) { PropertyInfo propertyInfo = typePropertites.Where(f => f.Name == parameterName).Single(); propertyInfo.SetValue(data, parameters.GetParameter(parameterName, propertyInfo.PropertyType), null); } AssignMissingGuidKeyValues(parameters, data); DataFacade.AddNew<T>(data); return null; } private static void AssignMissingGuidKeyValues(ParameterList parameters, T data) { foreach (PropertyInfo keyPropertyInfo in typeof(T).GetKeyProperties()) { if (keyPropertyInfo.PropertyType != typeof(Guid)) continue; if (parameters.AllParameterNames.Contains(keyPropertyInfo.Name)) continue; keyPropertyInfo.SetValue(data, Guid.NewGuid(), null); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/IDataGenerated/DataInstanceHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Functions; using Composite.Data.DynamicTypes; using System.Xml.Linq; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.IDataGenerated { internal static class DataInstanceHelper { public static BaseValueProvider GetFallbackValueProvider(DataFieldDescriptor dataFieldDescriptor, bool isKeyProperty) { if (dataFieldDescriptor.DefaultValue != null) { return new ConstantValueProvider(dataFieldDescriptor.DefaultValue.Value); } Type instanceType = GetInstanceType(dataFieldDescriptor); if (instanceType == typeof(int)) { return new ConstantValueProvider(0); } else if (instanceType == typeof(decimal)) { return new ConstantValueProvider(0.0); } else if (instanceType == typeof(bool)) { return new ConstantValueProvider(false); } else if (instanceType == typeof(string)) { return new ConstantValueProvider(""); } else if (instanceType == typeof(Guid)) { if (isKeyProperty) { return new ConstantValueProvider(Guid.NewGuid()); } else { return new ConstantValueProvider(Guid.Empty); } } else if (instanceType == typeof(DateTime)) { return new ConstantValueProvider(DateTime.Now); } else { return new ConstantValueProvider(""); } } public static WidgetFunctionProvider GetWidgetFunctionProvider(DataFieldDescriptor dataFieldDescriptor) { if ((dataFieldDescriptor.FormRenderingProfile != null) && (string.IsNullOrEmpty(dataFieldDescriptor.FormRenderingProfile.WidgetFunctionMarkup) == false)) { WidgetFunctionProvider widgetFunctionProvider = new WidgetFunctionProvider(XElement.Parse(dataFieldDescriptor.FormRenderingProfile.WidgetFunctionMarkup)); return widgetFunctionProvider; } else { return StandardWidgetFunctions.GetDefaultWidgetFunctionProviderByType(dataFieldDescriptor.InstanceType); } } public static Type GetInstanceType(DataFieldDescriptor dataFieldDescriptor) { Type instanceType = dataFieldDescriptor.InstanceType; if (instanceType.IsGenericType && instanceType.GetGenericTypeDefinition() == typeof(Nullable<>)) { instanceType = instanceType.GetGenericArguments().First(); } return instanceType; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/IDataGenerated/DeleteDataInstance.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Core.Linq; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.IDataGenerated { internal sealed class DeleteDataInstance<T> : StandardFunctionBase where T : class, IData { private List<StandardFunctionParameterProfile> _parameterProfiles = null; public DeleteDataInstance(EntityTokenFactory entityTokenFactory) : base("DeleteDataInstance", typeof(T).FullName, typeof(void), entityTokenFactory) { this.ResourceHandleNameStem = "Composite.IDataGenerated.DeleteDataInstance"; } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { if (_parameterProfiles == null) { _parameterProfiles = new List<StandardFunctionParameterProfile>(); Expression<Func<T, bool>> defaultFilter = DataFacade.GetEmptyPredicate<T>(); _parameterProfiles.Add(new StandardFunctionParameterProfile( "Filter", typeof(Expression<Func<T, bool>>), false, new ConstantValueProvider(defaultFilter), null )); } return _parameterProfiles; } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { Expression<Func<T, bool>> filter = parameters.GetParameter<Expression<Func<T, bool>>>("Filter"); DataFacade.Delete<T>(filter); return null; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/IDataGenerated/Filter/ActivePageReferenceFilter.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Data.Caching; using Composite.Data.Foundation; using Composite.Data.Types; using Composite.Functions; using Composite.Core.Linq.ExpressionVisitors; using Composite.Core.WebClient.Renderings.Page; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Data; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Pages; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.IDataGenerated.Filter { internal sealed class ActivePageReferenceFilter<T> : StandardFunctionBase { private static readonly ParameterExpression _parameterExpression = Expression.Parameter(typeof(T), "data"); private static readonly Expression _foreignKeyPropertyExpression; static ActivePageReferenceFilter() { PropertyInfo foreignKeyPropertyInfo = DataAssociationRegistry.GetForeignKeyPropertyInfo(typeof(IPage), typeof(T)); _foreignKeyPropertyExpression = Expression.Property(_parameterExpression, foreignKeyPropertyInfo); } public ActivePageReferenceFilter(EntityTokenFactory entityTokenFactory) : base("ActivePageReferenceFilter", typeof(T).FullName, typeof(Expression<Func<T, bool>>), entityTokenFactory) { this.ResourceHandleNameStem = "Composite.IDataGenerated.Filter.ActivePageReferenceFilter"; } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider associationDropDown = StandardWidgetFunctions.DropDownList( this.GetType(), "PageAssociationRestrictions", "Key", "Value", false, true); yield return new StandardFunctionParameterProfile( "SitemapScope", typeof(SitemapScope), false, new ConstantValueProvider(SitemapScope.Current), associationDropDown); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { SitemapScope SitemapScope; Expression filter; if (parameters.TryGetParameter<SitemapScope>("SitemapScope", out SitemapScope) == false) { SitemapScope = SitemapScope.Current; } switch (SitemapScope) { case SitemapScope.Current: Guid currentPageId = PageRenderer.CurrentPageId; filter = Expression.Equal(_foreignKeyPropertyExpression, Expression.Constant(currentPageId)); break; case SitemapScope.All: filter = Expression.Constant(true); break; default: Guid pageId = PageRenderer.CurrentPageId; IEnumerable<Guid> pageIds = new FilterWrapper( pageId, SitemapScope, TableVersion.Get(typeof(IPageStructure)), PageStructureInfo.GetAssociatedPageIds(pageId, SitemapScope)); Expression<Func<Guid, bool>> containsExpression = f => pageIds.Contains(f); filter = Expression.Invoke(containsExpression, _foreignKeyPropertyExpression); break; } return Expression.Lambda<Func<T, bool>>(filter, new ParameterExpression[] { _parameterExpression }); } public static IEnumerable<KeyValuePair<SitemapScope, string>> PageAssociationRestrictions() { return SitemapXmlFunction.PageAssociationRestrictions(); } private class FilterWrapper : CacheKeyBuilderExpressionVisitor.ICacheKeyProvider, IEnumerable<Guid> { private Guid _pageId; private SitemapScope _associationScope; private int _tableVersion; private IEnumerable<Guid> _innerEnumerator; public FilterWrapper(Guid pageId, SitemapScope associationScope, int tableVersion, IEnumerable<Guid> innerEnumerator) { _pageId = pageId; _associationScope = associationScope; _tableVersion = tableVersion; _innerEnumerator = innerEnumerator; } public string GetCacheKey() { return "APRFilter" + GetRootForSelectionScope() + _associationScope + _tableVersion; } private Guid GetRootForSelectionScope() { switch (_associationScope) { case SitemapScope.All: return Guid.Empty; case SitemapScope.Parent: return PageManager.GetParentId(_pageId); case SitemapScope.Level1: case SitemapScope.Level1AndSiblings: case SitemapScope.Level1AndDescendants: return GetPageOnLevel(1); case SitemapScope.Level2: case SitemapScope.Level2AndSiblings: case SitemapScope.Level2AndDescendants: return GetPageOnLevel(2); case SitemapScope.Level3: case SitemapScope.Level3AndSiblings: case SitemapScope.Level3AndDescendants: return GetPageOnLevel(3); case SitemapScope.Level4: case SitemapScope.Level4AndSiblings: case SitemapScope.Level4AndDescendants: return GetPageOnLevel(4); } return _pageId; } private Guid GetPageOnLevel(int level) { var ancestorsChain = new List<Guid>(); Guid currentPage = _pageId; while(currentPage != Guid.Empty && ancestorsChain.Count < 1000) { ancestorsChain.Add(currentPage); currentPage = PageManager.GetParentId(currentPage); } if (level > ancestorsChain.Count) return Guid.Empty; return ancestorsChain[ancestorsChain.Count - level]; } public IEnumerator<Guid> GetEnumerator() { return _innerEnumerator.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _innerEnumerator.GetEnumerator(); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/IDataGenerated/Filter/CompoundFilter.cs ================================================ using System; using System.Collections.Generic; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Functions; using Composite.Data; using System.Linq.Expressions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.IDataGenerated.Filter { internal sealed class CompoundFilter<T> : StandardFunctionBase, ICompoundFunction where T : class, IData { private static readonly ParameterExpression _dataItem = Expression.Parameter(typeof(T), "data"); public CompoundFilter(EntityTokenFactory entityTokenFactory) : base("CompoundFilter", typeof(T).FullName, typeof(Expression<Func<T, bool>>), entityTokenFactory) { this.ResourceHandleNameStem = "Composite.IDataGenerated.Filter.CompoundFilter"; } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider isAndQuerySelector = StandardWidgetFunctions.GetBoolSelectorWidget("And query", "Or Query"); yield return new StandardFunctionParameterProfile( "IsAndQuery", typeof(bool), false, new ConstantValueProvider(true), isAndQuerySelector); yield return new StandardFunctionParameterProfile( "Left", typeof(Expression<Func<T, bool>>), true, new NoValueValueProvider(), null); yield return new StandardFunctionParameterProfile( "Right", typeof(Expression<Func<T, bool>>), true, new NoValueValueProvider(), null); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { bool isAndQuery = parameters.GetParameter<bool>("IsAndQuery"); Expression<Func<T, bool>> left = parameters.GetParameter<Expression<Func<T, bool>>>("Left"); Expression<Func<T, bool>> right = parameters.GetParameter<Expression<Func<T, bool>>>("Right"); Expression compound; if (isAndQuery) { Expression leftFilter = Expression.Invoke(left, _dataItem); Expression rightFilter = Expression.Invoke(right, _dataItem); compound = Expression.And(leftFilter, rightFilter); } else { Expression leftFilter = Expression.Invoke(left, _dataItem); Expression rightFilter = Expression.Invoke(right, _dataItem); compound = Expression.Or(leftFilter, rightFilter); } Expression<Func<T, bool>> lambdaExpression = Expression.Lambda<Func<T, bool>>(compound, new ParameterExpression[] { _dataItem }); return lambdaExpression; } public bool AllowRecursiveCall { get { return true; } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/IDataGenerated/Filter/DataReferenceFilter.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.IDataGenerated.Filter.Foundation; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Functions; using Composite.Data; using System.Reflection; using System.Linq.Expressions; using Composite.Core.WebClient.Renderings.Page; using Composite.Data.Types; using System.Xml.Linq; using Composite.Core.Linq; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.IDataGenerated.Filter { internal sealed class DataReferenceFilter<T> : StandardFunctionBase where T : class, IData { private static readonly ParameterExpression _dataItem = Expression.Parameter(typeof(T), "data"); public DataReferenceFilter(EntityTokenFactory entityTokenFactory) : base("DataReferenceFilter", typeof(T).FullName, typeof(Expression<Func<T, bool>>), entityTokenFactory) { this.ResourceHandleNameStem = "Composite.IDataGenerated.Filter.DataReferenceFilter"; } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider referenceSelector = StandardWidgetFunctions.GetDataReferenceWidget<T>(); yield return new StandardFunctionParameterProfile( "DataReference", typeof(DataReference<T>), true, new NoValueValueProvider(), referenceSelector); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { DataReference<T> dataReference = parameters.GetParameter<DataReference<T>>("DataReference"); return dataReference.GetPredicateExpression(); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/IDataGenerated/Filter/FieldPredicatesFilter.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Functions; using Composite.Data; using System.Reflection; using System.Linq.Expressions; using Composite.Core.Linq; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.IDataGenerated.Filter { internal sealed class FieldPredicatesFilter<T> : StandardFunctionBase where T : class, IData { //private static readonly ParameterExpression _dataItem = Expression.Parameter(typeof(T), "data"); public FieldPredicatesFilter(EntityTokenFactory entityTokenFactory) : base("FieldPredicatesFilter", typeof(T).FullName, typeof(Expression<Func<T, bool>>), entityTokenFactory) { this.ResourceHandleNameStem = "Composite.IDataGenerated.Filter.FieldPredicatesFilter"; } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { foreach (PropertyInfo propertyInfo in typeof(T).GetAllProperties()) { if (propertyInfo.DeclaringType != typeof(IData) && propertyInfo.DeclaringType != typeof(object)) { Type[] funcGenericArgs = new Type[] { propertyInfo.PropertyType, typeof(bool) }; Type parameterType = typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(funcGenericArgs)); var param = new StandardFunctionParameterProfile( propertyInfo.Name, parameterType, false, new ConstantValueProvider(null), null); param.CustomLabel = propertyInfo.Name + " filter"; param.CustomHelpText = "Specify a criteria that this field must meet or use the default value (no criteria)"; yield return param; } } } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { ParameterExpression parameterExpression = Expression.Parameter(typeof(T), "data"); Expression allRequirements = null; foreach (string parameterName in parameters.AllParameterNames) { object predicateObject = parameters.GetParameter(parameterName); if (predicateObject == null) continue; Expression propertyExpression = Expression.Property(parameterExpression, GetProperty(parameterName)); LambdaExpression predicate = (LambdaExpression)predicateObject; Expression predicateBody = predicate.Body; ParameterExpressionSwitcher parameterExpressionSwitcher = new ParameterExpressionSwitcher(predicate.Parameters[0], propertyExpression); Expression newPredicateBody = parameterExpressionSwitcher.Visit(predicateBody); allRequirements = allRequirements.NestedAnd(newPredicateBody); } if (allRequirements == null) { allRequirements = Expression.Constant(true); } Expression lambdaExpression = Expression.Lambda<Func<T, bool>>(allRequirements, parameterExpression); return lambdaExpression; } private PropertyInfo GetProperty(string fieldName) { PropertyInfo fieldPropertyInfo = typeof(T).GetAllProperties().Single(f => f.Name == fieldName); return fieldPropertyInfo; } private sealed class ParameterExpressionSwitcher : ExpressionVisitor { private readonly Expression _oldParameter; private readonly Expression _newParameterExpression; public ParameterExpressionSwitcher(Expression oldParameter, Expression newParameterExpression) { _oldParameter = oldParameter; _newParameterExpression = newParameterExpression; } protected override Expression VisitParameter(ParameterExpression node) { if(object.ReferenceEquals(node, _oldParameter)) { return _newParameterExpression; } return node; } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/IDataGenerated/Filter/Foundation/ListPropertyNamesHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Collections; using Composite.Core.Types; using Composite.Data; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.IDataGenerated.Filter.Foundation { internal static class ListPropertyNamesHelper { public static IEnumerable GetOptionsWithReferences(string typeManagerName) { Type t = TypeManager.GetType(typeManagerName); IEnumerable<ForeignPropertyInfo> foreignKeyProperties = DataReferenceFacade.GetForeignKeyProperties(t); List<PropertyInfo> properties = t.GetPropertiesRecursively(f=>f.DeclaringType!=typeof(IData)); List<string> result = new List<string>(); foreach (PropertyInfo propertyInfo in properties) { result.Add( propertyInfo.Name); ForeignPropertyInfo foreignKeyInfo = foreignKeyProperties.FirstOrDefault(f=>f.SourcePropertyName==propertyInfo.Name); if (foreignKeyInfo!=null) { List<PropertyInfo> foreignProperties = foreignKeyInfo.TargetType.GetPropertiesRecursively(f=>f.DeclaringType!=typeof(IData)); foreach (PropertyInfo foreignPropertyInfo in foreignProperties) { string foreignKey = string.Format("{0}.{1}", propertyInfo.Name, foreignPropertyInfo.Name ); result.Add( foreignKey); } } } return result; } public static IEnumerable GetOptions(string typeManagerName) { Type t = TypeManager.GetType(typeManagerName); List<PropertyInfo> properties = t.GetPropertiesRecursively(); List<string> result = new List<string>(); result.AddRange( from property in properties where property.DeclaringType != typeof(IData) select property.Name); return result; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/IDataGenerated/GetDataReference.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.IDataGenerated; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Functions; using Composite.Data; using System.Reflection; using System.Linq.Expressions; using Composite.Core.WebClient.Renderings.Page; using Composite.Data.Types; using System.Xml.Linq; using Composite.Core.Linq; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.IDataGenerated { internal sealed class GetDataReference<T> : StandardFunctionBase where T : class, IData { private static readonly ParameterExpression _dataItem = Expression.Parameter(typeof(T), "data"); public GetDataReference(EntityTokenFactory entityTokenFactory) : base("GetDataReference", typeof(T).FullName, typeof(DataReference<T>), entityTokenFactory) { this.ResourceHandleNameStem = "Composite.IDataGenerated.GetDataReference"; } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { var keyPropertyInfo = DataAttributeFacade.GetKeyProperties(typeof(T)).Single(); WidgetFunctionProvider referenceSelector = StandardWidgetFunctions.GetDataReferenceWidget<T>(); yield return new StandardFunctionParameterProfile( "KeyValue", keyPropertyInfo.PropertyType, true, new NoValueValueProvider(), referenceSelector); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { object keyValue = parameters.GetParameter("KeyValue"); return new DataReference<T>(keyValue); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/IDataGenerated/GetNullableDataReference.cs ================================================ using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Composite.Data; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.IDataGenerated { internal sealed class GetNullableDataReference<T> : StandardFunctionBase where T : class, IData { private static readonly ParameterExpression _dataItem = Expression.Parameter(typeof(T), "data"); public GetNullableDataReference(EntityTokenFactory entityTokenFactory) : base("GetNullableDataReference", typeof(T).FullName, typeof(NullableDataReference<T>), entityTokenFactory) { this.ResourceHandleNameStem = "Composite.IDataGenerated.GetNullableDataReference"; } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { var keyPropertyInfo = DataAttributeFacade.GetKeyProperties(typeof(T)).Single(); WidgetFunctionProvider referenceSelector = StandardWidgetFunctions.GetNullableDataReferenceWidget<T>(); yield return new StandardFunctionParameterProfile( "KeyValue", keyPropertyInfo.PropertyType, false, new ConstantValueProvider(new NullableDataReference<T>()), referenceSelector); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { object keyValue = parameters.GetParameter("KeyValue"); return new NullableDataReference<T>(keyValue); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/IDataGenerated/GetXml.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Xml.Linq; using Composite.Core.Caching; using Composite.Data; using Composite.Data.Caching; using Composite.Functions; using Composite.Core.Linq; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.IDataGenerated.Filter.Foundation; using Composite.Core.Types; using Composite.Core.Extensions; using Composite.Core.Collections.Generic; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.IDataGenerated { internal class GetXmlCacheRecord { public int Version; public IEnumerable<XElement> Result; } internal class QueryInfo { public IEnumerable<Type> ReferencedDataTypes; public bool HasPublishableReference; public bool HasLocalizableReference; } internal sealed class GetXml<T> : StandardFunctionBase where T : class, IData { private static readonly ICache<string, GetXmlCacheRecord> ResultCache = CacheManager.Get<string, GetXmlCacheRecord>("GetXml results", new CacheSettings(CacheType.Mixed) { Size = 2500 }); private static readonly Hashtable<string, QueryInfo> _queryInfoTable = new Hashtable<string, QueryInfo>(); private List<string> _propertyNames; private List<PropertyInfo> _propertyInfos; private object _lock = new object(); public GetXml(EntityTokenFactory entityTokenFactory) : base("Get" + typeof(T).Name + "Xml", typeof(T).FullName, typeof(IEnumerable<XElement>), entityTokenFactory) { this.ResourceHandleNameStem = "Composite.IDataGenerated.GetXml"; } private List<PropertyInfo> GetPropertyInfos() { if (_propertyInfos == null) { lock (_lock) { if (_propertyInfos == null) { var result = new List<PropertyInfo>(typeof (T).GetKeyProperties()); PropertyInfo labelPropertyInfo = typeof (T).GetLabelPropertyInfo(); if (!result.Any(f => f.Name == labelPropertyInfo.Name)) { result.Add(labelPropertyInfo); } _propertyInfos = result; } } } return _propertyInfos; } private List<string> GetPropertyNames() { List<string> result = _propertyNames; if (result == null) { lock (_lock) { result = _propertyNames; if (result == null) { result = GetPropertyInfos().Select(f => f.Name).ToList(); _propertyNames = result; } } } return result; } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider orderBySelector = StandardWidgetFunctions.DropDownList( typeof(ListPropertyNamesHelper), "GetOptions", TypeManager.SerializeType(typeof(T)), false, true, true); WidgetFunctionProvider propertyNamesSelector = StandardWidgetFunctions.DropDownList( typeof(ListPropertyNamesHelper), "GetOptionsWithReferences", TypeManager.SerializeType(typeof(T)), true, true, true); yield return new StandardFunctionParameterProfile( "PropertyNames", typeof(IEnumerable<string>), true, new ConstantValueProvider(GetPropertyNames()), propertyNamesSelector); Expression<Func<T, bool>> defaultFilter = DataFacade.GetEmptyPredicate<T>(); yield return new StandardFunctionParameterProfile( "Filter", typeof(Expression<Func<T, bool>>), false, new ConstantValueProvider(defaultFilter), null); yield return new StandardFunctionParameterProfile( "OrderByField", typeof(string), false, new ConstantValueProvider(""), orderBySelector); yield return new StandardFunctionParameterProfile( "OrderAscending", typeof(bool), false, new ConstantValueProvider(true), StandardWidgetFunctions.GetBoolSelectorWidget("Order ascending (a-z)", "Order descending (z-a)")); yield return new StandardFunctionParameterProfile( "PageSize", typeof(int), false, new ConstantValueProvider(1000), StandardWidgetFunctions.IntegerTextBoxWidget); yield return new StandardFunctionParameterProfile( "PageNumber", typeof(int), false, new ConstantValueProvider(1), StandardWidgetFunctions.IntegerTextBoxWidget); yield return new StandardFunctionParameterProfile( "ShowReferencesInline", typeof(bool), false, new ConstantValueProvider(true), StandardWidgetFunctions.GetBoolSelectorWidget("Yes, show reference type data as attributes", "No, show as XML elements")); yield return new StandardFunctionParameterProfile( "IncludePagingInfo", typeof(bool), false, new ConstantValueProvider(false), StandardWidgetFunctions.GetBoolSelectorWidget("Yes, add item/page count details", "No, do not calculate paging info")); var randomizedParam = new StandardFunctionParameterProfile( "Randomized", typeof(bool), false, new ConstantValueProvider(false), StandardWidgetFunctions.GetBoolSelectorWidget("Yes, randomize selection. Use the 'Page size' for number of random elements.", "No, behave consistently")); yield return randomizedParam; var elementNameParam = new StandardFunctionParameterProfile( "ElementName", typeof(string), false, new ConstantValueProvider(typeof(T).Name), StandardWidgetFunctions.TextBoxWidget); elementNameParam.CustomHelpText = string.Format("The name of the XML element. The detault is '{0}'", typeof(T).Name); yield return elementNameParam; var elementNamespaceParam = new StandardFunctionParameterProfile( "ElementNamespace", typeof(XNamespace), false, new ConstantValueProvider(XNamespace.None), StandardWidgetFunctions.TextBoxWidget); elementNamespaceParam.CustomHelpText = string.Format("The namespace the XML element belongs to. The detault is '{0}'", XNamespace.None); yield return elementNamespaceParam; WidgetFunctionProvider cachePriorityDropDown = StandardWidgetFunctions.DropDownList( this.GetType(), "GetCachePriorities", "Key", "Value", false, true); yield return new StandardFunctionParameterProfile( "CachePriority", typeof(GetXmlCachePriority), false, new ConstantValueProvider(GetXmlCachePriority.Default), cachePriorityDropDown); } } /// <summary> /// To be called though reflection /// </summary> /// <returns></returns> public static IEnumerable<KeyValuePair<GetXmlCachePriority, string>> GetCachePriorities() { yield return new KeyValuePair<GetXmlCachePriority, string>(GetXmlCachePriority.Disabled, "Disabled"); yield return new KeyValuePair<GetXmlCachePriority, string>(GetXmlCachePriority.Default, "Default"); } public override object Execute(ParameterList parameters, FunctionContextContainer context) { List<string> propertyNames = parameters.GetParameter<IEnumerable<string>>("PropertyNames").ToList(); Expression<Func<T, bool>> filter = parameters.GetParameter<Expression<Func<T, bool>>>("Filter"); string elementName = parameters.GetParameter<string>("ElementName"); string namespaceString = parameters.GetParameter<string>("ElementNamespace"); string orderByField = parameters.GetParameter<string>("OrderByField"); bool orderAscending = parameters.GetParameter<bool>("OrderAscending"); int pageSize = parameters.GetParameter<int>("PageSize"); int pageNumber = parameters.GetParameter<int>("PageNumber"); bool showReferencesInline = parameters.GetParameter<bool>("ShowReferencesInline"); bool includePagingInfo = parameters.GetParameter<bool>("IncludePagingInfo"); bool randomized = parameters.GetParameter<bool>("Randomized"); GetXmlCachePriority cachePriority = parameters.GetParameter<GetXmlCachePriority>("CachePriority"); int queryVersion = 0; bool cachingEnabled = cachePriority != GetXmlCachePriority.Disabled; string cacheKey = null; if (cachingEnabled) { cacheKey = GetCacheKey(propertyNames, filter, elementName, namespaceString, orderByField, orderAscending, pageSize, pageNumber, showReferencesInline, includePagingInfo, randomized); if (cacheKey != null) { queryVersion = GetQueryVersion(propertyNames); GetXmlCacheRecord cacheRecord = ResultCache.Get(cacheKey); if (cacheRecord != null && cacheRecord.Version == queryVersion) { return cacheRecord.Result; } } } XNamespace elementNamespace = (string.IsNullOrEmpty(namespaceString) ? XNamespace.None : namespaceString); LambdaExpression orderByExpression; if (string.IsNullOrEmpty(orderByField)) { orderByField = propertyNames.FirstOrDefault(f => f.Contains(".") == false); if (!randomized && !orderByField.IsNullOrEmpty()) { orderByExpression = DataToXElements<T>.GetOrderByPropertyNameExpression(orderByField); } else { orderByExpression = DataFacade.GetEmptyPredicate<T>(); } } else { orderByExpression = DataToXElements<T>.GetOrderByPropertyNameExpression(orderByField); } IEnumerable<XElement> result = DataToXElements<T>.GetXElements( filter, orderByExpression, orderAscending, pageSize, pageNumber, propertyNames, elementNamespace, elementName, showReferencesInline, includePagingInfo, randomized); if (cachingEnabled && cacheKey != null) { result = result.ToList(); ResultCache.Add(cacheKey, new GetXmlCacheRecord { Result = result, Version = queryVersion }); } return result; } private static QueryInfo GetQueryInfo(IEnumerable<string> propertyNames) { string key = string.Join("|", propertyNames); QueryInfo queryInfo = _queryInfoTable[key]; if (queryInfo != null) return queryInfo; lock (_queryInfoTable) { queryInfo = _queryInfoTable[key]; if (queryInfo != null) return queryInfo; queryInfo = new QueryInfo(); queryInfo.HasLocalizableReference = DataLocalizationFacade.IsLocalized(typeof(T)); queryInfo.HasPublishableReference = DataFacade.GetSupportedDataScopes(typeof(T)).Count() > 1; List<Type> relatedTypesList = new List<Type>(); foreach (string propertyName in propertyNames.Where(f => f.Contains("."))) { string foreignKeyPropertyName = propertyName.Substring(0, propertyName.IndexOf(".")); ForeignPropertyInfo keyInfo = DataReferenceFacade.GetForeignKeyPropertyInfo(typeof(T), foreignKeyPropertyName); Type targetType = keyInfo.TargetType; if (!relatedTypesList.Contains(targetType)) { relatedTypesList.Add(targetType); } queryInfo.HasLocalizableReference = queryInfo.HasLocalizableReference || DataLocalizationFacade.IsLocalized(targetType); queryInfo.HasPublishableReference = queryInfo.HasPublishableReference || (DataFacade.GetSupportedDataScopes(targetType).Count() > 1); } queryInfo.ReferencedDataTypes = relatedTypesList; _queryInfoTable.Add(key, queryInfo); return queryInfo; } } private static int GetQueryVersion(IEnumerable<string> propertyNames) { int result = TableVersion.Get(typeof(T)); QueryInfo queryInfo = GetQueryInfo(propertyNames); foreach (Type t in queryInfo.ReferencedDataTypes) { result += TableVersion.Get(t); } return result; } private static string GetCacheKey(List<string> propertyNames, Expression filter, string elementName, string namespaceString, string orderByField, bool orderAscending, int pageSize, int pageNumber, bool showReferencesInline, bool includePagingInfo, bool randomized) { if (randomized) return null; string filterKey = string.Empty; if (filter != null) { filterKey = filter.BuildCacheKey(); if (filterKey == null) return null; } var result = new StringBuilder(); result.Append(typeof(T).FullName).Append(','); QueryInfo qi = GetQueryInfo(propertyNames); if (qi.HasPublishableReference) { var currentDataScope = DataScopeManager.CurrentDataScope; if (currentDataScope != null) { result.Append(currentDataScope.ToString()).Append(','); } } if (qi.HasLocalizableReference) { var languageScope = LocalizationScopeManager.CurrentLocalizationScope; if (languageScope != null) { result.Append(languageScope.ToString()).Append(','); } } result.Append(string.Join("*", propertyNames)).Append("|"); result.Append(elementName ?? string.Empty).Append(','); result.Append(namespaceString ?? string.Empty).Append(','); result.Append(orderByField ?? string.Empty).Append(','); result.Append(orderAscending ? '1' : '0').Append(','); result.Append(pageSize).Append(','); result.Append(pageNumber).Append(','); result.Append(showReferencesInline ? '1' : '0'); result.Append(includePagingInfo ? '1' : '0').Append('|'); result.Append(filterKey); return result.ToString(); } } internal static class DataToXElements<T> where T : class, IData { private static readonly Dictionary<Type, IOrderByTypeFixer<T>> __orderByTypeFixers = new Dictionary<Type, IOrderByTypeFixer<T>>(); private static readonly object _lock = new object(); public static LambdaExpression GetOrderByPropertyNameExpression(string propertyName) { PropertyInfo orderByPropertyInfo = typeof(T).GetDataPropertyRecursivly(propertyName); IOrderByTypeFixer<T> orderByFixer = GetOrderByTypeFixer(orderByPropertyInfo); return orderByFixer.GetOrderByPropertyNameExpression(orderByPropertyInfo); } public static IEnumerable<XElement> GetXElements( Expression<Func<T, bool>> filter, LambdaExpression orderBy, bool orderAscending, int coreElementItemsPerPage, int coreElementPageNumber, IEnumerable<string> propertyNames, XNamespace elementNamespace, string elementNameString, bool showReferencesInline, bool showPagingInfo, bool randomized) { List<string> propertyNameList = new List<string>(propertyNames); List<string> autoAppendedPropertyNames = new List<string>(); List<string> referencedIdAttrubuteNames = new List<string>(); XName coreElementName = elementNamespace + elementNameString; Dictionary<string, List<string>> referencesLookup = new Dictionary<string, List<string>>(); foreach (string referencePropertyName in propertyNameList.Where(f => f.Contains("."))) { string[] referenceElements = referencePropertyName.Split('.'); if (referenceElements.Length != 2) throw new InvalidOperationException(string.Format("Property names with a dot must have exactly one dot - failed to parse '{0}'", referencePropertyName)); if (referencesLookup.ContainsKey(referenceElements[0]) == false) referencesLookup.Add(referenceElements[0], new List<string>()); referencesLookup[referenceElements[0]].Add(referenceElements[1]); } // rewrite with linq if (showReferencesInline) { // Ensure keys are included foreach (string referencePropertyName in referencesLookup.Keys) { if (propertyNameList.Contains(referencePropertyName) == false) { propertyNameList.Add(referencePropertyName); autoAppendedPropertyNames.Add(referencePropertyName); } } } var result = new List<XElement>(); Expression<Func<T, XElement>> xelementSelector = XElementSelectHelper<T>.BuildXElementSelector(propertyNameList.Where(f => f.IndexOf('.') == -1).ToList(), coreElementName); // TODO: handle case of the default sorting (by predicate element => true) IOrderByTypeFixer<T> orderByTypeFixer = GetOrderByTypeFixer(orderBy); IQueryable<T> coreDataItems = orderByTypeFixer.GetCastedIQueryable(filter, orderBy, orderAscending, coreElementItemsPerPage, coreElementPageNumber, randomized); if (randomized && referencesLookup.Any()) { // performance hit! make elegant when time permits. coreDataItems = coreDataItems.ToList().AsQueryable(); } // Perf. optimization if (coreDataItems.IsEnumerableQuery()) { Func<T, XElement> compiledExpression = XElementSelectHelper<T>.GetCompiledFunction(xelementSelector); result.AddRange(Enumerable.Select(coreDataItems, compiledExpression)); } else { result.AddRange(coreDataItems.Select(xelementSelector)); } var referencedResults = new List<XElement>(); // int referencedCoreElementCount = (orderByIsDeterministic ? coreElementItemsPerPage : int.MaxValue); foreach (string referencePropertyName in referencesLookup.Keys) { IReferencedDataHelper<T> fixer = ReferencedDataHelperBuilder<T>.Build(referencePropertyName); string propertyNamePrefix = (showReferencesInline ? referencePropertyName + "." : ""); if (showReferencesInline) { if (referencesLookup[referencePropertyName].Contains(fixer.TargetTypeKeyPropertyName) == false) { referencesLookup[referencePropertyName].Add(fixer.TargetTypeKeyPropertyName); autoAppendedPropertyNames.Add(propertyNamePrefix + fixer.TargetTypeKeyPropertyName); } referencedIdAttrubuteNames.Add(propertyNamePrefix + fixer.TargetTypeKeyPropertyName); } XName referenceElementName = elementNamespace + referencePropertyName; IEnumerable<XElement> referencesXml = fixer.GetReferencedXElements(coreDataItems, referencesLookup[referencePropertyName], referenceElementName, propertyNamePrefix); referencedResults.AddRange(referencesXml); } if (showReferencesInline) { Dictionary<string, IEnumerable<XElement>> referencedElementsLookup = new Dictionary<string, IEnumerable<XElement>>(); Dictionary<string, Func<string, XAttribute>> referencedElementLocatorLookup = new Dictionary<string, Func<string, XAttribute>>(); foreach (string referencePropertyName in referencesLookup.Keys) { XName referenceElementName = elementNamespace + referencePropertyName; IEnumerable<XElement> referenceElements = referencedResults.Where(f => f.Name == referenceElementName); referencedElementsLookup.Add(referencePropertyName, referenceElements); string idPropertyName = referencedIdAttrubuteNames.First(g => g.StartsWith(referencePropertyName + ".")); IEnumerable<XElement> referencedElements = referencedElementsLookup[referencePropertyName]; Func<string, XAttribute> locateByKeyFunc = f => referencedElements.Attributes(idPropertyName).FirstOrDefault(g => g.Value == f); referencedElementLocatorLookup.Add(referencePropertyName, locateByKeyFunc); } foreach (XElement coreElement in result.Where(f => f.Name == coreElementName)) { foreach (string referencePropertyName in referencesLookup.Keys) { XAttribute referenceAttribute = coreElement.Attribute(referencePropertyName); if (referenceAttribute == null) continue; // Handles non-references string keyValue = referenceAttribute.Value; Func<string, XAttribute> fetcher = referencedElementLocatorLookup[referencePropertyName]; XAttribute matchingKeyAttribute = fetcher(keyValue); if (matchingKeyAttribute != null) { XElement referenced = matchingKeyAttribute.Parent; coreElement.Add(referenced.Attributes()); } } coreElement.Attributes().Where(f => autoAppendedPropertyNames.Contains(f.Name.LocalName)).Remove(); yield return coreElement; } } else { foreach (XElement anyElement in result) { yield return anyElement; } foreach (XElement anyElement in referencedResults) { yield return anyElement; } } if (showPagingInfo) { int totalItemCount = DataFacade.GetData<T>(filter).Count(); // TODO: there shoudn't be a query int firstShownElementNumber = ((coreElementPageNumber - 1) * coreElementItemsPerPage) + 1; int lastShownElementNumber = Math.Min(totalItemCount, firstShownElementNumber + (coreElementItemsPerPage - 1)); int shownItemsCount = Math.Max(0, (lastShownElementNumber - firstShownElementNumber) + 1); int totelPageCount = (int)Math.Ceiling((((double)totalItemCount) / ((double)coreElementItemsPerPage))); XElement pagingInfo = new XElement(elementNamespace + "PagingInfo", new XAttribute("CurrentPageNumber", coreElementPageNumber), new XAttribute("TotalPageCount", totelPageCount), new XAttribute("TotalItemCount", totalItemCount), new XAttribute("ShownItemsCount", shownItemsCount), new XAttribute("MaximumItemsPerPage", coreElementItemsPerPage) ); if (shownItemsCount > 0) { pagingInfo.Add( new XAttribute("CurrentItemNumberStart", firstShownElementNumber), new XAttribute("CurrentItemNumberEnd", lastShownElementNumber) ); } yield return pagingInfo; } } private static IOrderByTypeFixer<T> GetOrderByTypeFixer(LambdaExpression orderByExpression) { Type expressionType = orderByExpression.GetType(); Type[] expressionTypeGenericArguments = expressionType.GetGenericArguments(); Type[] funcGenericArguments = expressionTypeGenericArguments[0].GetGenericArguments(); Type orderByT = funcGenericArguments[1]; return GetByTypeFixerImpl(orderByT); } private static DataToXElements<T>.IOrderByTypeFixer<T> GetByTypeFixerImpl(Type orderByT) { IOrderByTypeFixer<T> result; lock (_lock) { if (__orderByTypeFixers.TryGetValue(orderByT, out result) == false) { Type[] genericArgs = new Type[] { typeof(T), orderByT }; result = (IOrderByTypeFixer<T>)Activator.CreateInstance(typeof(OrderByTypeFixer<>).MakeGenericType(genericArgs), null); ; __orderByTypeFixers.Add(orderByT, result); } } return result; } private static IOrderByTypeFixer<T> GetOrderByTypeFixer(PropertyInfo orderByPropertyInfo) { return GetByTypeFixerImpl(orderByPropertyInfo.PropertyType); } private interface IOrderByTypeFixer<T2> { IQueryable<T2> GetCastedIQueryable(Expression<Func<T2, bool>> filter, LambdaExpression orderBy, bool orderAscending, int coreElementItemsPerPage, int coreElementPageNumber, bool randomized); LambdaExpression GetOrderByPropertyNameExpression(PropertyInfo orderByPropertyInfo); } private class OrderByTypeFixer<OrderKeyT> : IOrderByTypeFixer<T> { private static readonly Hashtable<object, object> _compiledExpressions = new Hashtable<object, object>(); private static Func<T, OrderKeyT> CompileExpression(Expression<Func<T, OrderKeyT>> expression) { object result; if (!_compiledExpressions.TryGetValue(expression, out result)) { lock (_compiledExpressions) { if (!_compiledExpressions.TryGetValue(expression, out result)) { result = expression.Compile(); _compiledExpressions.Add(expression, result); } } } return result as Func<T, OrderKeyT>; } public IQueryable<T> GetCastedIQueryable(Expression<Func<T, bool>> filter, LambdaExpression orderBy, bool orderAscending, int coreElementItemsPerPage, int coreElementPageNumber, bool randomized) { // TODO: Handle the case when there's no sorting in a proper way Expression<Func<T, OrderKeyT>> orderByCasted = (Expression<Func<T, OrderKeyT>>)orderBy; IQueryable<T> allDataItemsOrdered = DataFacade.GetData<T>(filter); if (randomized) { // TODO: optimize for EnumerableQuery instances IQueryable<T> randomizedItems = allDataItemsOrdered.TakeRandom(coreElementItemsPerPage); if (orderBy != DataFacade.GetEmptyPredicate<T>()) { randomizedItems = (orderAscending ? randomizedItems.OrderBy(orderByCasted) : randomizedItems.OrderByDescending(orderByCasted)); } return randomizedItems; } if (allDataItemsOrdered.IsEnumerableQuery()) { Func<T, OrderKeyT> orderByFunc = CompileExpression(orderByCasted); allDataItemsOrdered = (orderAscending ? allDataItemsOrdered.OrderBy(orderByFunc) : allDataItemsOrdered.OrderByDescending(orderByFunc)) .AsQueryable(); } else { allDataItemsOrdered = (orderAscending ? allDataItemsOrdered.OrderBy(orderByCasted) : allDataItemsOrdered.OrderByDescending(orderByCasted)); } IQueryable<T> coreDataItems = allDataItemsOrdered; if (coreElementPageNumber > 1) { coreDataItems = coreDataItems.Skip((coreElementPageNumber - 1) * coreElementItemsPerPage); } coreDataItems = coreDataItems.Take(coreElementItemsPerPage); return coreDataItems; } public LambdaExpression GetOrderByPropertyNameExpression(PropertyInfo orderByPropertyInfo) { ParameterExpression sourceItem = Expression.Parameter(typeof(T), "source"); Expression propertySelector = Expression.Convert(LambdaExpression.Property(sourceItem, orderByPropertyInfo), typeof(OrderKeyT)); Expression<Func<T, OrderKeyT>> orderByExpression = Expression.Lambda<Func<T, OrderKeyT>>(propertySelector, new ParameterExpression[] { sourceItem }); return orderByExpression; } } } internal static class ReferencedDataHelperBuilder<SOURCE> where SOURCE : class, IData { private static readonly Hashtable<string, IReferencedDataHelper<SOURCE>> __preBuildHelpers = new Hashtable<string, IReferencedDataHelper<SOURCE>>(); private static readonly object _lock = new object(); public static IReferencedDataHelper<SOURCE> Build(string foreignKeyPropertyName) { IReferencedDataHelper<SOURCE> result; if (__preBuildHelpers.TryGetValue(foreignKeyPropertyName, out result) == false) { lock (_lock) { if (__preBuildHelpers.TryGetValue(foreignKeyPropertyName, out result) == false) { result = BuildImpl(foreignKeyPropertyName); __preBuildHelpers.Add(foreignKeyPropertyName, result); } } } return result; } private static IReferencedDataHelper<SOURCE> BuildImpl(string foreignKeyPropertyName) { Type sourceType = typeof(SOURCE); ForeignPropertyInfo keyInfo = DataReferenceFacade.GetForeignKeyPropertyInfo(sourceType, foreignKeyPropertyName); Type destinationType = keyInfo.TargetType; PropertyInfo sourceKeyPropertyInfo = sourceType.GetDataPropertyRecursivly(foreignKeyPropertyName); PropertyInfo destinationKeyPropertyInfo = destinationType.GetSingleKeyProperty(); Type keyFieldType = destinationKeyPropertyInfo.PropertyType; Type[] genericArgs = new Type[] { typeof(SOURCE), destinationType, keyFieldType }; return (IReferencedDataHelper<SOURCE>)Activator.CreateInstance(typeof(ReferencedDataHelper<,,>).MakeGenericType(genericArgs), sourceKeyPropertyInfo, destinationKeyPropertyInfo); } } internal interface IReferencedDataHelper<SOURCE> where SOURCE : class, IData { IEnumerable<XElement> GetReferencedXElements(IQueryable<SOURCE> sourceTypeIqueryable, List<string> destinationPropertyNames, XName elementName, string propertyNamePrefix); string TargetTypeKeyPropertyName { get; } } internal class ReferencedDataHelper<SOURCE, DEST, KEY> : IReferencedDataHelper<SOURCE> where SOURCE : class, IData where DEST : class, IData { private readonly ParameterExpression _sourceItem = Expression.Parameter(typeof(SOURCE), "source"); private readonly ParameterExpression _destinationItem = Expression.Parameter(typeof(DEST), "destination"); private readonly PropertyInfo _sourceKeyPropertyInfo; private readonly PropertyInfo _destinationKeyPropertyInfo; private Expression<Func<SOURCE, KEY>> SourceForeignKeyPropertySelector { get; set; } private Expression<Func<SOURCE, bool>> SourceForeignWhereExpression { get; set; } public ReferencedDataHelper(PropertyInfo sourceKeyPropertyInfo, PropertyInfo destinationKeyPropertyInfo) { _sourceKeyPropertyInfo = sourceKeyPropertyInfo; _destinationKeyPropertyInfo = destinationKeyPropertyInfo; this.TargetTypeKeyPropertyName = _destinationKeyPropertyInfo.Name; Expression foreignKeyFieldSelect; if ((_sourceKeyPropertyInfo.PropertyType.IsGenericType) && (_sourceKeyPropertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))) { PropertyInfo hasValuePropertyInfo = _sourceKeyPropertyInfo.PropertyType.GetProperty("HasValue"); PropertyInfo valuePropertyInfo = _sourceKeyPropertyInfo.PropertyType.GetProperty("Value"); Expression hasValuePropertyExpression = Expression.Property(Expression.Property(_sourceItem, _sourceKeyPropertyInfo), hasValuePropertyInfo); Expression valuePropertyExpression = Expression.Property(Expression.Property(_sourceItem, _sourceKeyPropertyInfo), valuePropertyInfo); Expression equalExpression = Expression.Equal(hasValuePropertyExpression, Expression.Constant(true)); foreignKeyFieldSelect = Expression.Property(Expression.Property(_sourceItem, _sourceKeyPropertyInfo), valuePropertyInfo); this.SourceForeignWhereExpression = Expression.Lambda<Func<SOURCE, bool>>(equalExpression, new ParameterExpression[] { _sourceItem }); } else { foreignKeyFieldSelect = LambdaExpression.Property(_sourceItem, _sourceKeyPropertyInfo); } this.SourceForeignKeyPropertySelector = Expression.Lambda<Func<SOURCE, KEY>>(foreignKeyFieldSelect, new ParameterExpression[] { _sourceItem }); } public string TargetTypeKeyPropertyName { get; private set; } public IEnumerable<XElement> GetReferencedXElements(IQueryable<SOURCE> sourceTypeIqueryable, List<string> destinationPropertyNames, XName elementName, string propertyNamePrefix) { IQueryable<DEST> data = GetReferencedQueryable(sourceTypeIqueryable); Expression<Func<DEST, XElement>> xelementSelector = XElementSelectHelper<DEST>.BuildXElementSelector(destinationPropertyNames, elementName, propertyNamePrefix); return data.Select(xelementSelector); } public IQueryable<DEST> GetReferencedQueryable(IQueryable<SOURCE> sourceTypeIqueryable) { if (this.SourceForeignWhereExpression != null) { // Handle Nullable<> sourceTypeIqueryable = sourceTypeIqueryable.Where(this.SourceForeignWhereExpression); } List<KEY> keys = sourceTypeIqueryable.Select(this.SourceForeignKeyPropertySelector).Distinct().ToList(); // Build "key is in list" expression Expression destinationKeyFieldSelect = LambdaExpression.Property(_destinationItem, _destinationKeyPropertyInfo); Expression<Func<KEY, bool>> containsExpression = f => keys.Contains(f); Expression destinationFilter = Expression.Invoke(containsExpression, destinationKeyFieldSelect); var lambdaExpression = Expression.Lambda<Func<DEST, bool>>(destinationFilter, new ParameterExpression[] { _destinationItem }); // Return queryable return DataFacade.GetData<DEST>(lambdaExpression); } } internal static class XElementSelectHelper<T> { private static readonly Hashtable<string, Expression<Func<T, XElement>>> __preBuildSelectors = new Hashtable<string, Expression<Func<T, XElement>>>(); private static readonly Hashtable<Expression<Func<T, XElement>>, Func<T, XElement>> _compiledExpressions = new Hashtable<Expression<Func<T, XElement>>, Func<T, XElement>>(); public static readonly object _syncRoot = new object(); public static Func<T, XElement> GetCompiledFunction(Expression<Func<T, XElement>> xelementSelector) { Func<T, XElement> result; if (!_compiledExpressions.TryGetValue(xelementSelector, out result)) { lock (_syncRoot) { if (!_compiledExpressions.TryGetValue(xelementSelector, out result)) { result = xelementSelector.Compile(); _compiledExpressions.Add(xelementSelector, result); } } } return result; } public static Expression<Func<T, XElement>> BuildXElementSelector(List<string> fieldNames, XName elementName) { return BuildXElementSelector(fieldNames, elementName, ""); } public static Expression<Func<T, XElement>> BuildXElementSelector(List<string> fieldNames, XName elementName, string propertyNamePrefix) { Expression<Func<T, XElement>> result; string lookupKey = string.Format("{0}//{1}//{2}", string.Join(",", fieldNames.ToArray()), elementName, propertyNamePrefix); if (__preBuildSelectors.TryGetValue(lookupKey, out result) == false) { lock (_syncRoot) { if (__preBuildSelectors.TryGetValue(lookupKey, out result) == false) { result = BuildXElementSelectorImpl(fieldNames, elementName, propertyNamePrefix); __preBuildSelectors.Add(lookupKey, result); } } } return result; } private static Expression<Func<T, XElement>> BuildXElementSelectorImpl(List<string> fieldNames, XName elementName, string propertyNamePrefix) { ParameterExpression _sourceItem = Expression.Parameter(typeof(T), "data"); ConstructorInfo xElementConstructorInfo = typeof(XElement).GetConstructor(new Type[] { typeof(XName), typeof(object[]) }); ConstructorInfo xAttributeConstructorInfo = typeof(XAttribute).GetConstructor(new Type[] { typeof(XName), typeof(object) }); List<Expression> xattributeNewExpressions = new List<Expression>(); foreach (string fieldName in fieldNames) { PropertyInfo fieldPropertyInfo = typeof(T).GetPropertiesRecursively(f => f.DeclaringType != typeof(IData)).Where(prop => prop.Name == fieldName).SingleOrDefault(); if (fieldPropertyInfo == null) throw new InvalidOperationException(string.Format("The type '{0}' does have a property named '{1}'", typeof(T), fieldName)); Expression attributeNameExpression = Expression.Constant(XName.Get(propertyNamePrefix + fieldName)); Expression attributeValueExpression = Expression.Convert(LambdaExpression.Property(_sourceItem, fieldPropertyInfo), typeof(object)); Expression xattributeNewExpression = Expression.New(xAttributeConstructorInfo, new Expression[] { attributeNameExpression, attributeValueExpression }); // Return "null" instead of "new XAttribute( 'xxx', null )" Expression notNullCheck = Expression.NotEqual(attributeValueExpression, Expression.Constant(null)); Expression nullChecked = Expression.Condition(notNullCheck, Expression.Convert(xattributeNewExpression, typeof(object)), Expression.Constant(null)); xattributeNewExpressions.Add(nullChecked); //xattributeNewExpression); } Expression xattributeArrayExpression = Expression.NewArrayInit(typeof(object), xattributeNewExpressions); Expression elementNameExpression = Expression.Constant(elementName); Expression[] xelementConstructorArguments = new Expression[] { elementNameExpression, xattributeArrayExpression }; Expression xelementNewExpression = Expression.New(xElementConstructorInfo, xelementConstructorArguments); Expression<Func<T, XElement>> lambdaExpression = Expression.Lambda<Func<T, XElement>>(xelementNewExpression, new ParameterExpression[] { _sourceItem }); return lambdaExpression; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/IDataGenerated/GetXmlCachePriority.cs ================================================ namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.IDataGenerated { internal enum GetXmlCachePriority { Disabled = 0, Default = 1 } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/IDataGenerated/UpdateDataInstance.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Core.Linq; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.IDataGenerated { internal sealed class UpdateDataInstance<T> : StandardFunctionBase where T : class, IData { private List<StandardFunctionParameterProfile> _parameterProfiles = null; public UpdateDataInstance(EntityTokenFactory entityTokenFactory) : base("UpdateDataInstance", typeof(T).FullName, typeof(void), entityTokenFactory) { this.ResourceHandleNameStem = "Composite.IDataGenerated.UpdateDataInstance"; } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { if (_parameterProfiles == null) { _parameterProfiles = new List<StandardFunctionParameterProfile>(); DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(typeof(T)); foreach (DataFieldDescriptor dataFieldDescriptor in dataTypeDescriptor.Fields) { if (dataTypeDescriptor.KeyPropertyNames.Contains(dataFieldDescriptor.Name)) continue; string helpText = dataFieldDescriptor.Name; if (dataFieldDescriptor.FormRenderingProfile != null && !string.IsNullOrWhiteSpace(dataFieldDescriptor.FormRenderingProfile.HelpText)) { helpText = dataFieldDescriptor.FormRenderingProfile.HelpText; } _parameterProfiles.Add(new StandardFunctionParameterProfile( dataFieldDescriptor.Name, dataFieldDescriptor.InstanceType, false, DataInstanceHelper.GetFallbackValueProvider(dataFieldDescriptor, false), DataInstanceHelper.GetWidgetFunctionProvider(dataFieldDescriptor) ) { CustomLabel = dataFieldDescriptor.Name, CustomHelpText = helpText }); } Expression<Func<T, bool>> defaultFilter = DataFacade.GetEmptyPredicate<T>(); _parameterProfiles.Add(new StandardFunctionParameterProfile( "Filter", typeof(Expression<Func<T, bool>>), false, new ConstantValueProvider(defaultFilter), null )); } return _parameterProfiles; } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { Expression<Func<T, bool>> filter = parameters.GetParameter<Expression<Func<T, bool>>>("Filter"); List<PropertyInfo> typePropertites = typeof(T).GetPropertiesRecursively(); List<Tuple<PropertyInfo, object>> newValues = new List<Tuple<PropertyInfo, object>>(); foreach (string parameterName in parameters.AllParameterNames.Where(f => f != "Filter")) { if (parameters.IsDefaultValue(parameterName)) continue; PropertyInfo propertyInfo = typePropertites.Where(f => f.Name == parameterName).Single(); object value = parameters.GetParameter(parameterName, propertyInfo.PropertyType); newValues.Add(new Tuple<PropertyInfo, object>(propertyInfo, value)); } IEnumerable<T> datas = DataFacade.GetData<T>(filter).Evaluate(); foreach (T data in datas) { foreach (Tuple<PropertyInfo, object> newValue in newValues) { newValue.Item1.SetValue(data, newValue.Item2, null); } } DataFacade.Update(datas); return null; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Mail/SendMailFunction.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Mail; using System.Web; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Logging; using Composite.Data; using Composite.Data.Types; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Mail { internal class SendMailFunction : StandardFunctionBase { private static readonly string LogTitle = "SendMailFunction"; private static readonly string CompositeMediaAttachmentPrefix = "Composite/"; public SendMailFunction(EntityTokenFactory entityTokenFactory) : base("SendMail", "Composite.Mail", typeof(bool), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { string from = parameters.GetParameter<string>("From"); string to = parameters.GetParameter<string>("To"); string subject = parameters.GetParameter<string>("Subject"); string body = parameters.GetParameter<string>("Body"); bool isHtml = parameters.GetParameter<bool>("IsHtml"); string replyTo = parameters.GetParameter<string>("ReplyTo"); string cc = parameters.GetParameter<string>("CC"); string bcc = parameters.GetParameter<string>("BCC"); string attachment = parameters.GetParameter<string>("Attachment") ?? string.Empty; string attachmentFromMedia = parameters.GetParameter<string>("AttachmentFromMedia") ?? string.Empty; if(!attachmentFromMedia.IsNullOrEmpty()) { attachment += "|" + CompositeMediaAttachmentPrefix + attachmentFromMedia; } return SendMail(subject, body, isHtml, from, to, replyTo, cc, bcc, attachment); } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextAreaWidget; WidgetFunctionProvider boolWidget = StandardWidgetFunctions.GetBoolSelectorWidget("True", "False"); yield return new StandardFunctionParameterProfile("From", typeof(string), true, new ConstantValueProvider(""), textboxWidget); yield return new StandardFunctionParameterProfile("To", typeof(string), true, new ConstantValueProvider(""), textboxWidget); yield return new StandardFunctionParameterProfile("Subject", typeof(string), true, new ConstantValueProvider(""), textboxWidget); yield return new StandardFunctionParameterProfile("Body", typeof(string), true, new ConstantValueProvider(""), textboxWidget); yield return new StandardFunctionParameterProfile("IsHtml", typeof(bool), true, new ConstantValueProvider(false), boolWidget); yield return new StandardFunctionParameterProfile("ReplyTo", typeof(string), false, new ConstantValueProvider(""), textboxWidget); yield return new StandardFunctionParameterProfile("CC", typeof(string), false, new ConstantValueProvider(""), textboxWidget); yield return new StandardFunctionParameterProfile("BCC", typeof(string), false, new ConstantValueProvider(""), textboxWidget); yield return new StandardFunctionParameterProfile("Attachment", typeof(string), false, new ConstantValueProvider(""), textboxWidget); WidgetFunctionProvider mediaSelectionWidget = StandardWidgetFunctions.GetDataReferenceWidget(typeof (IMediaFile)); yield return new StandardFunctionParameterProfile("AttachmentFromMedia", typeof(string), false, new ConstantValueProvider(""), mediaSelectionWidget); } } public static bool SendMail(string subject, string body, bool isHtml, string from, string to) { return SendMail(subject, body, isHtml, from, to, null, null, null, null); } public static bool SendMail(string subject, string body, bool isHtml, string from, string to, string replyTo, string cc, string bcc, string attachmentsList) { var toDispose = new List<IDisposable>(); try { MailMessage mailMessage = new MailMessage(from, to) { Body = body, Subject = subject, IsBodyHtml = isHtml }; if (!cc.IsNullOrEmpty()) { mailMessage.CC.Add(cc); } if (!bcc.IsNullOrEmpty()) { mailMessage.Bcc.Add(bcc); } if (!replyTo.IsNullOrEmpty()) { mailMessage.ReplyToList.Add(new MailAddress(replyTo)); } toDispose.Add(mailMessage); if(!ParseAttachmentList(attachmentsList, mailMessage.Attachments, toDispose)) { return false; } var mailer = ServiceLocator.GetService<IMailer>(); mailer.Send(mailMessage); return true; } catch (Exception ex) { LoggingService.LogWarning(LogTitle, ex); return false; } finally { foreach (IDisposable obj in toDispose) { obj.Dispose(); } } } private static bool ParseAttachmentList(string attachmentList, AttachmentCollection result, IList<IDisposable> toDispose) { if (attachmentList.IsNullOrEmpty()) return true; foreach (var atmStr in attachmentList.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)) { string line = atmStr.Trim(); if (line.IsNullOrEmpty()) continue; string attachmentName; string filePath; string mimeType; if (line.Contains(",")) { int comaIndex = line.IndexOf(','); mimeType = line.Substring(comaIndex + 1); line = line.Substring(0, comaIndex).Trim(); } else { mimeType = null; } if (line.Contains("=")) { int equalSignIndex = line.IndexOf('='); attachmentName = line.Substring(0, equalSignIndex).Trim(); filePath = line.Substring(equalSignIndex + 1).Trim(); } else { attachmentName = null; filePath = line; } // Checking whether the file is from Composite media database if (filePath.StartsWith(CompositeMediaAttachmentPrefix)) { string compositePath = filePath.Substring(CompositeMediaAttachmentPrefix.Length); string storeId = compositePath.Substring(0, compositePath.IndexOf(':')); IMediaFile mediaFile; try { mediaFile = DataFacade.GetData<IMediaFile>(f => f.StoreId == storeId && f.CompositePath == compositePath).FirstOrDefault(); } catch (Exception e) { LoggingService.LogWarning(LogTitle, "Media file '{0}' cannot be found.".FormatWith(compositePath)); LoggingService.LogError(LogTitle, e); return false; } Stream readStream = mediaFile.GetReadStream(); result.Add(new Attachment(readStream, attachmentName ?? mediaFile.Title, mimeType ?? mediaFile.MimeType)); continue; } // File is a file on disk if (!filePath.Contains(@":\") && HttpContext.Current != null) { filePath = HttpContext.Current.Server.MapPath(filePath); } if (!C1File.Exists(filePath)) { LoggingService.LogWarning(LogTitle, "Cannot create an attachment. File '{0}' does not exists". FormatWith(filePath)); return false; } Attachment attachment; if (mimeType.IsNullOrEmpty()) { if (attachmentName.IsNullOrEmpty()) { attachment = new Attachment(filePath); } else { attachment = new Attachment(C1File.OpenRead(filePath), attachmentName); } } else { if (attachmentName.IsNullOrEmpty()) { attachment = new Attachment(filePath, mimeType); } else { attachment = new Attachment(C1File.OpenRead(filePath), attachmentName, mimeType); } } result.Add(attachment); } return true; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Media/MediaFolderFilterFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Composite.Data; using Composite.Data.Types; using Composite.Core.Extensions; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Media { internal sealed class MediaFolderFilterFunction<TMedia> : StandardFunctionBase where TMedia : IMediaFile { private static readonly MethodInfo MethodInfoGetFolderPath = typeof(IFile).GetProperty("FolderPath").GetGetMethod(); private static readonly MethodInfo MethodInfoStringStartsWith = typeof(string).GetMethod("StartsWith", new[] { typeof(string) }); public MediaFolderFilterFunction(EntityTokenFactory entityTokenFactory) : base("MediaFolderFilter", typeof(TMedia).FullName, typeof(Expression<Func<TMedia, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield return new StandardFunctionParameterProfile( "MediaFolder", typeof(DataReference<IMediaFileFolder>), false, new ConstantValueProvider(null), StandardWidgetFunctions.GetDataReferenceWidget<IMediaFileFolder>()); WidgetFunctionProvider widget = StandardWidgetFunctions.GetBoolSelectorWidget("True", "False"); yield return new StandardFunctionParameterProfile( "IncludeSubfolders", typeof(bool), false, new ConstantValueProvider(false), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { var mediaFolderReference = parameters.GetParameter<DataReference<IMediaFileFolder>>("MediaFolder"); Verify.ArgumentNotNull(mediaFolderReference, "mediaFolderReference"); bool includeSubfolders = parameters.GetParameter<bool>("IncludeSubfolders"); IMediaFileFolder mediaFolder = GetMediaFolder(mediaFolderReference); if (mediaFolder == null) { return (Expression<Func<TMedia, bool>>)(f => false); } string mediaFolderPath = mediaFolder.Path; string mediaFolderPathWithSlash = mediaFolder.Path + "/"; if (includeSubfolders) { //return (Expression<Func<TMedia, bool>>) // (image => image.FolderPath == mediaFolderPath // || image.FolderPath.StartsWith(mediaFolderPathWithSlash)); var imageParam = Expression.Parameter(typeof(TMedia), "image"); var orElse = Expression.OrElse( Expression.Equal(Expression.Property(imageParam, MethodInfoGetFolderPath), Expression.Constant(mediaFolderPath)), Expression.Call(Expression.Property(imageParam, MethodInfoGetFolderPath), MethodInfoStringStartsWith, new Expression[] { Expression.Constant(mediaFolderPathWithSlash) })); return Expression.Lambda<Func<TMedia, bool>>(orElse, imageParam); } // return (Expression<Func<TMedia, bool>>)(imageParam1 => imageParam1.FolderPath == mediaFolderPath); var imageParam1 = Expression.Parameter(typeof(TMedia), "image"); return Expression.Lambda<Func<TMedia, bool>>( Expression.Equal(Expression.Property(imageParam1, MethodInfoGetFolderPath), Expression.Constant(mediaFolderPath)), imageParam1); } private static IMediaFileFolder GetMediaFolder(DataReference<IMediaFileFolder> mediaFolderReference) { string mediaFolderKeyPath = mediaFolderReference.KeyValue as string; using (new DataScope(DataScopeIdentifier.Public)) { var query = DataFacade.GetData<IMediaFileFolder>(); if (query.IsEnumerableQuery()) { return query.AsEnumerable().Where(mf => mf.KeyPath == mediaFolderKeyPath).FirstOrDefault(); } return query.Where(mf => mf.KeyPath == mediaFolderKeyPath).FirstOrDefault(); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Pages/GetForeignPageInfoFunction.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using System.Xml.Linq; using Composite.Core.Routing; using Composite.Data; using Composite.Data.Types; using Composite.Functions; using Composite.Core.WebClient.Renderings.Page; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Pages { /// <summary> /// Gets information about current page in all the languages. /// </summary> internal class GetForeignPageInfoFunction: StandardFunctionBase { public GetForeignPageInfoFunction(EntityTokenFactory entityTokenFactory) : base("GetForeignPageInfo", "Composite.Pages", typeof(IEnumerable<XElement>), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { return ExecuteInternal(); } private static IEnumerable<XElement> ExecuteInternal() { // Grab all active languages... foreach (CultureInfo culture in DataLocalizationFacade.ActiveLocalizationCultures) { XElement annotatedMatch; // enter the 'data scope' of the next language using (new DataScope(culture)) { // fetch sitemap element for current page - if any IPage match = PageManager.GetPageById(PageRenderer.CurrentPageId); if (match == null) { continue; } annotatedMatch = new XElement("LanguageVersion" , new XAttribute("Culture", culture.Name) , new XAttribute("CurrentCulture", culture.Equals(Thread.CurrentThread.CurrentCulture)) , new XAttribute("Id", match.Id) , new XAttribute("Title", match.Title) , (match.MenuTitle == null ? null : new XAttribute("MenuTitle", match.MenuTitle)) , new XAttribute("UrlTitle", match.UrlTitle) , new XAttribute("Description", match.Description) , new XAttribute("URL", PageUrls.BuildUrl(match)) ); } yield return annotatedMatch; } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Pages/GetPageIdFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using Composite.C1Console.Actions; using Composite.C1Console.Workflow.Activities; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.Routing.Pages; using Composite.Core.WebClient.FlowMediators.FormFlowRendering; using Composite.Core.WebClient.Renderings.Page; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Security; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Pages { internal sealed class GetPageIdFunction : StandardFunctionBase { public GetPageIdFunction(EntityTokenFactory entityTokenFactory) : base("GetPageId", "Composite.Pages", typeof(Guid), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (!parameters.TryGetParameter<SitemapScope>(nameof(SitemapScope), out var sitemapScope)) { sitemapScope = SitemapScope.Current; } var pageId = GetCurrentPageId(); switch (sitemapScope) { case SitemapScope.Current: return pageId; case SitemapScope.Parent: case SitemapScope.Level1: case SitemapScope.Level2: case SitemapScope.Level3: case SitemapScope.Level4: var pageIds = PageStructureInfo.GetAssociatedPageIds(pageId, sitemapScope); return pageIds.FirstOrDefault(); default: throw new NotImplementedException("Unhandled SitemapScope type: " + sitemapScope.ToString()); } } private Guid GetCurrentPageId() { return GetCurrentPageIdFromPageRenderer() ?? GetCurrentPageIdFromPageUrlData() ?? GetCurrentPageIdFromHttpContext() ?? GetCurrentPageIdFromFormFlow() ?? Guid.Empty; } private Guid? GetCurrentPageIdFromPageRenderer() { var pageId = PageRenderer.CurrentPageId; return pageId == Guid.Empty ? (Guid?)null : pageId; } private Guid? GetCurrentPageIdFromPageUrlData() { var pageId = C1PageRoute.PageUrlData?.PageId; return pageId == Guid.Empty ? null : pageId; } private Guid? GetCurrentPageIdFromHttpContext() { var entityToken = HttpContext.Current?.Items[ActionExecutorFacade.HttpContextItem_EntityToken]; return GetPageIdFromEntityToken(entityToken as EntityToken); } private Guid? GetCurrentPageIdFromFormFlow() { var currentFormTreeCompiler = FormFlowUiDefinitionRenderer.CurrentFormTreeCompiler; if (currentFormTreeCompiler.BindingObjects.TryGetValue(FormsWorkflow.EntityTokenKey, out var entityToken)) { return GetPageIdFromEntityToken(entityToken as EntityToken); } return null; } private Guid? GetPageIdFromEntityToken(EntityToken entityToken) { if (entityToken is null) { return null; } Guid pageId = Guid.Empty; if (entityToken is DataEntityToken dataEntityToken) { //appears while adding a metadata element if (dataEntityToken.Data is IPage page) { pageId = page.Id; } //appears while editing a datafolder element else if (dataEntityToken.Data is IPageRelatedData pageRelatedData) { pageId = pageRelatedData.PageId; } } //appears while adding a datafolder element else if (typeof(IPage).IsAssignableFrom(Type.GetType(entityToken.Type, throwOnError: false))) { Guid.TryParse(entityToken?.Id, out pageId); } return pageId == Guid.Empty ? null : (Guid?)pageId; } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider associationDropDown = StandardWidgetFunctions.DropDownList( this.GetType(), "PageAssociationRestrictions", "Key", "Value", false, true); yield return new StandardFunctionParameterProfile( nameof(SitemapScope), typeof(SitemapScope), false, new ConstantValueProvider(SitemapScope.Current), associationDropDown); } } public static IEnumerable<KeyValuePair<SitemapScope, string>> PageAssociationRestrictions() { yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Current, "Current page"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Parent, "Parent page"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level1, "Level 1 page (homepage)"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level2, "Level 2 page"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level3, "Level 3 page"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level4, "Level 4 page"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Pages/SitemapFunction.cs ================================================ using System.Xml; using System.Xml.Linq; using System.Xml.Xsl; using Composite.Core.WebClient.Renderings.Page; using Composite.Core.Xml; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Pages { internal sealed class SitemapFunction : StandardFunctionBase { #region XSLT constants const string _sitemapXslTemplate = @"<?xml version=""1.0"" encoding=""UTF-8""?> <xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" exclude-result-prefixes=""xsl"" xmlns=""http://www.w3.org/1999/xhtml""> <xsl:template match=""/""> <html> <head> <style id=""CompositePagesXhtmlSitemapStyle""> ul#Sitemap, ul#Sitemap ul { list-style: none; margin: 0; padding: 0; } ul#Sitemap ul { margin-left: 0.8em; } ul#Sitemap li { padding: 0; } #Sitemap a { text-decoration: none; } #Sitemap a.sitemapCurrentPage { font-weight: bold; } #Sitemap a.sitemapOpenPage { font-style: italic; } </style> </head> <body> <ul id=""Sitemap""> <xsl:apply-templates select=""/sitemap/Page"" /> </ul> </body> </html> </xsl:template> <xsl:template match=""Page[@MenuTitle]""> <li> <xsl:apply-templates mode=""classAttribute"" select=""."" /> <a href=""{@URL}""> <xsl:apply-templates mode=""classAttribute"" select=""."" /> <xsl:value-of select=""@MenuTitle"" /> </a> <xsl:if test=""count(Page)>0""> <ul> <xsl:apply-templates select=""Page"" /> </ul> </xsl:if> </li> </xsl:template> <xsl:template mode=""classAttribute"" match=""Page""> <xsl:choose> <xsl:when test=""@iscurrent='true'""> <xsl:attribute name=""class"">sitemapCurrentPage</xsl:attribute> </xsl:when> <xsl:when test=""@isopen='true'""> <xsl:attribute name=""class"">sitemapOpenPage</xsl:attribute> </xsl:when> </xsl:choose> </xsl:template> </xsl:stylesheet> "; #endregion private static object _lock = new object(); private static XslCompiledTransform xslt = null; private static XslCompiledTransform GetCompiledXslt() { lock (_lock) { if (xslt == null) { xslt = new XslCompiledTransform(); XElement xsltSource = XElement.Parse(_sitemapXslTemplate); xslt.Load(xsltSource.CreateReader()); } return xslt; } } private EntityTokenFactory _entityTokenFactory; public SitemapFunction(EntityTokenFactory entityTokenFactory) : base("QuickSitemap", "Composite.Pages", typeof(XhtmlDocument), entityTokenFactory) { _entityTokenFactory = entityTokenFactory; } public override object Execute(ParameterList parameters, FunctionContextContainer context) { XDocument xmlSitemap = new XDocument( new XElement("sitemap", PageStructureInfo.GetSiteMapWithActivePageAnnotations())); XDocument xhtmlSitemap = new XDocument(); using (XmlWriter writer = xhtmlSitemap.CreateWriter()) { GetCompiledXslt().Transform(xmlSitemap.CreateReader(), writer); } return new XhtmlDocument(xhtmlSitemap); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Pages/SitemapXmlFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using Composite.Functions; using Composite.C1Console.Security; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; using Composite.Core.WebClient.Renderings.Page; using Composite.Data; using Composite.Data.Types; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Pages { internal sealed class SitemapXmlFunction : StandardFunctionBase { public SitemapXmlFunction(EntityTokenFactory entityTokenFactory) : base("SitemapXml", "Composite.Pages", typeof(IEnumerable<XElement>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider associationDropDown = StandardWidgetFunctions.DropDownList( this.GetType(), "PageAssociationRestrictions", "Key", "Value", false, true); yield return new StandardFunctionParameterProfile( "SourcePage", typeof(DataReference<IPage>), false, new ConstantValueProvider(null), StandardWidgetFunctions.GetDataReferenceWidget<IPage>()); yield return new StandardFunctionParameterProfile( "SitemapScope", typeof(SitemapScope), false, new ConstantValueProvider(SitemapScope.All), associationDropDown); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { SitemapScope SitemapScope = parameters.GetParameter<SitemapScope>("SitemapScope"); DataReference<IPage> pageReference = parameters.GetParameter<DataReference<IPage>>("SourcePage"); Guid pageId; if (pageReference != null && pageReference.IsSet) { pageId = (Guid)pageReference.KeyValue; } else { pageId = PageRenderer.CurrentPageId; } return PageStructureInfo.GetSitemapByScope(SitemapScope, pageId); } public static IEnumerable<KeyValuePair<SitemapScope, string>> PageAssociationRestrictions() { yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Current, "Current page"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.All, "All pages (no filter)"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.AncestorsAndCurrent, "Ancestors and current (breadcrumb)"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Ancestors, "Ancestor pages"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Parent, "Parent page"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Descendants, "Descendant pages"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.DescendantsAndCurrent, "Current and descendant pages"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Children, "Child pages"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Siblings, "Sibling pages"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level1, "Level 1 page (homepage)"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level1AndDescendants, "Level 1 and descendant pages (current site)"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level1AndSiblings, "Level 1 and sibling pages (all homepages)"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level2, "Level 2 page"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level2AndDescendants, "Level 2 and descendant pages"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level2AndSiblings, "Level 2 and sibling pages (site main areas)"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level3, "Level 3 page"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level3AndDescendants, "Level 3 and descendant pages"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level3AndSiblings, "Level 3 and sibling pages"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level4, "Level 4 page"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level4AndDescendants, "Level 4 and descendant pages"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level4AndSiblings, "Level 4 and sibling pages"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/StandardFunctionProvider.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Data; using Composite.Data.Types; using Composite.Functions; using Composite.Functions.Plugins.FunctionProvider; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.IDataGenerated; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.IDataGenerated.Filter; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; using Composite.Data.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider { [ConfigurationElementType(typeof(StandardFunctionProviderData))] internal class StandardFunctionProvider : IDynamicTypeFunctionProvider { private EntityTokenFactory _entityTokenFactory; private List<IFunction> _standardStaticTypeFunctions = null; private List<IFunction> _standardDynamicTypeFunctions = null; public StandardFunctionProvider(string providerName) { _entityTokenFactory = new EntityTokenFactory(providerName); } public FunctionNotifier FunctionNotifier { set {} // List is static } public IEnumerable<IFunction> Functions { get { if (_standardStaticTypeFunctions == null) { InitializeStaticTypeFunctions(); } foreach (IFunction function in _standardStaticTypeFunctions) { yield return function; } } } public IEnumerable<IFunction> DynamicTypeDependentFunctions { get { if (_standardDynamicTypeFunctions == null) { InitializeDynamicTypeFunctions(); } foreach (IFunction function in _standardDynamicTypeFunctions) { yield return function; } } } private void InitializeStaticTypeFunctions() { _standardStaticTypeFunctions = new List<IFunction>(); // constant _standardStaticTypeFunctions.Add(new Constant.StringFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Constant.DateTimeFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Constant.BooleanFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Constant.DecimalFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Constant.IntegerFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Constant.GuidFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Constant.XhtmlDocumentFunction(_entityTokenFactory)); // web _standardStaticTypeFunctions.Add(new Web.Client.BrowserPlatformFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Client.BrowserStringFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Client.BrowserTypeFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Client.BrowserVersionFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Client.EcmaScriptVersionFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Client.IsCrawlerFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Client.IsMobileDeviceFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Html.Template.CommonMetaTagsFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Html.Template.LangAttributeFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Html.Template.PageTemplateFeatureFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Html.Template.HtmlTitleValueFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Html.Template.MetaDescriptionValueFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Request.CookieValueFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Request.SessionVariableFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Request.FormPostValueFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Request.FormPostBoolValueFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Request.FormPostDecimalValueFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Request.FormPostGuidValueFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Request.FormPostIntegerValueFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Request.FormPostXmlFormattedDateTimeValueFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Request.QueryStringValueFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Request.QueryStringBoolValueFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Request.QueryStringDecimalValueFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Request.QueryStringGuidValueFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Request.QueryStringIntegerValueFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Request.QueryStringXmlFormattedDateTimeValueFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Request.PathInfoFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Request.PathInfoIntFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Request.PathInfoGuidFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Request.RegisterPathInfoUsageFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Response.RedirectFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Response.SetCookieValueFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Response.SetServerPageCacheDuration(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Response.SetSessionVariableFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Server.ApplicationPath(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Server.ApplicationVariableFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Web.Server.ServerVariableFunction(_entityTokenFactory)); // date _standardStaticTypeFunctions.Add(new Utils.Date.NowFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Date.AddDaysFunction(_entityTokenFactory)); // guid _standardStaticTypeFunctions.Add(new Utils.GuidFunctions.NewGuid(_entityTokenFactory)); // globalization _standardStaticTypeFunctions.Add(new Utils.Globalization.CurrentCulture(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Globalization.AllCultures(_entityTokenFactory)); // validation _standardStaticTypeFunctions.Add(new Utils.Validation.RegexValidationFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Validation.StringLengthValidationFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Validation.NotNullValidationFunction<string>(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Validation.NotNullValidationFunction<int>(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Validation.NotNullValidationFunction<decimal>(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Validation.NotNullValidationFunction<DateTime>(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Validation.NotNullValidationFunction<Guid>(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Validation.IntegerRangeValidationFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Validation.DecimalPrecisionValidationFunction(_entityTokenFactory)); // xml _standardStaticTypeFunctions.Add(new Xml.LoadFileFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Xml.LoadXhtmlFileFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Xml.LoadUrlFunction(_entityTokenFactory)); // caching _standardStaticTypeFunctions.Add(new Utils.Caching.PageObjectCacheFunction(_entityTokenFactory)); // compare _standardStaticTypeFunctions.Add(new Utils.Compare.AreEqualFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Compare.IsLessThanFunction(_entityTokenFactory)); // configuration _standardStaticTypeFunctions.Add(new Utils.Configuration.AppSettingsValueFunction(_entityTokenFactory)); // parameters _standardStaticTypeFunctions.Add(new Utils.GetInputParameterFunction(_entityTokenFactory)); // parse string to object _standardStaticTypeFunctions.Add(new Utils.ParseStringToObjectFunction(_entityTokenFactory)); // string _standardStaticTypeFunctions.Add(new Utils.String.Join(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.String.JoinTwo(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.String.Split(_entityTokenFactory)); // int _standardStaticTypeFunctions.Add(new Utils.Integer.Sum(_entityTokenFactory)); // XsltExtensions _standardStaticTypeFunctions.Add(new Xslt.Extensions.DateFormattingXsltExtensionsFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Xslt.Extensions.GlobalizationXsltExtensionsFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Xslt.Extensions.MarkupParserXsltExtensionsFunction(_entityTokenFactory)); // AspNet _standardStaticTypeFunctions.Add(new AspNet.LoadUserControlFunction(_entityTokenFactory)); // Mail _standardStaticTypeFunctions.Add(new Mail.SendMailFunction(_entityTokenFactory)); // Media _standardStaticTypeFunctions.Add(new Media.MediaFolderFilterFunction<IMediaFile>(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Media.MediaFolderFilterFunction<IImageFile>(_entityTokenFactory)); // Utils.Predicates _standardStaticTypeFunctions.Add(new Utils.Predicates.StringContainsPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.StringEqualsPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.StringStartsWithPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.StringEndsWithPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.StringNoValuePredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.StringInListPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.StringInCommaSeparatedListPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.DateTimeLessThanPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.DateTimeGreaterThanPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.DateTimeEqualsPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.IntegerLessThanPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.IntegerGreaterThanPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.IntegerEqualsPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.DecimalLessThanPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.DecimalGreaterThanPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.DecimalEqualsPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.BoolEqualsPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.GuidEqualsPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.GuidInCommaSeparatedListPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.NullableBoolEqualsPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.NullableBoolNoValuePredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.NullableDateTimeEqualsPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.NullableDateTimeGreaterThanPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.NullableDateTimeLessThanPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.NullableDateTimeNoValuePredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.NullableDecimalEqualsPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.NullableDecimalNoValuePredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.NullableGuidEqualsPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.NullableGuidNoValuePredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.NullableIntegerEqualsPredicateFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Predicates.NullableIntegerNoValuePredicateFunction(_entityTokenFactory)); // Utils.Dictionary _standardStaticTypeFunctions.Add(new Utils.Dictionary.XElementsToDictionaryFunction(_entityTokenFactory)); _standardStaticTypeFunctions.Add(new Utils.Dictionary.EnumerableToDictionary(_entityTokenFactory)); } private void InitializeDynamicTypeFunctions() { _standardDynamicTypeFunctions = new List<IFunction>(); // pages _standardDynamicTypeFunctions.Add(new Pages.SitemapXmlFunction(_entityTokenFactory)); _standardDynamicTypeFunctions.Add(new Pages.SitemapFunction(_entityTokenFactory)); _standardDynamicTypeFunctions.Add(new Pages.GetPageIdFunction(_entityTokenFactory)); _standardDynamicTypeFunctions.Add(new Pages.GetForeignPageInfoFunction(_entityTokenFactory)); // data.filter List<Type> dataInterfaces = DataFacade.GetAllKnownInterfaces(UserType.Developer); object[] args = new object[] { _entityTokenFactory }; _standardDynamicTypeFunctions.AddRange( from t in dataInterfaces where DataAssociationRegistry.IsAssociationType(t) select (IFunction)Activator.CreateInstance(typeof(ActivePageReferenceFilter<>).MakeGenericType(t), args)); _standardDynamicTypeFunctions.AddRange( from t in dataInterfaces select (IFunction)Activator.CreateInstance(typeof(FieldPredicatesFilter<>).MakeGenericType(t), args)); _standardDynamicTypeFunctions.AddRange( from t in dataInterfaces select (IFunction)Activator.CreateInstance(typeof(CompoundFilter<>).MakeGenericType(t), args)); _standardDynamicTypeFunctions.AddRange( from t in dataInterfaces select (IFunction)Activator.CreateInstance(typeof(DataReferenceFilter<>).MakeGenericType(t), args)); _standardDynamicTypeFunctions.AddRange( from t in dataInterfaces select (IFunction)Activator.CreateInstance(typeof(GetXml<>).MakeGenericType(t), args)); _standardDynamicTypeFunctions.AddRange( from t in dataInterfaces where DataAttributeFacade.GetKeyPropertyNames(t).Count == 1 select (IFunction)Activator.CreateInstance(typeof(GetDataReference<>).MakeGenericType(t), args)); _standardDynamicTypeFunctions.AddRange( from t in dataInterfaces where DataAttributeFacade.GetKeyPropertyNames(t).Count == 1 select (IFunction)Activator.CreateInstance(typeof(GetNullableDataReference<>).MakeGenericType(t), args)); _standardDynamicTypeFunctions.AddRange( from t in dataInterfaces select (IFunction)Activator.CreateInstance(typeof(AddDataInstance<>).MakeGenericType(t), args)); _standardDynamicTypeFunctions.AddRange( from t in dataInterfaces select (IFunction)Activator.CreateInstance(typeof(UpdateDataInstance<>).MakeGenericType(t), args)); _standardDynamicTypeFunctions.AddRange( from t in dataInterfaces select (IFunction)Activator.CreateInstance(typeof(DeleteDataInstance<>).MakeGenericType(t), args)); } } [Assembler(typeof(StandardFunctionProviderAssembler))] internal sealed class StandardFunctionProviderData : FunctionProviderData { } internal sealed class StandardFunctionProviderAssembler : IAssembler<IFunctionProvider, FunctionProviderData> { public IFunctionProvider Assemble(IBuilderContext context, FunctionProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new StandardFunctionProvider(objectConfiguration.Name); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/StandardFunctionProviderEntityToken.cs ================================================ using Composite.C1Console.Security; using Composite.C1Console.Security.SecurityAncestorProviders; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider { [SecurityAncestorProvider(typeof(NoAncestorSecurityAncestorProvider))] internal sealed class StandardFunctionProviderEntityToken : EntityToken { private string _id; private string _source; public StandardFunctionProviderEntityToken(string source, string id) { _source = source; _id = id; } public override string Type { get { return ""; } } public override string Source { get { return _source; } } public override string Id { get { return _id; } } public override string Serialize() { return DoSerialize(); } public static EntityToken Deserialize(string serializedEntityToken) { string type, source, id; DoDeserialize(serializedEntityToken, out type, out source, out id); return new StandardFunctionProviderEntityToken(source, id); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Caching/PageObjectCacheFunction.cs ================================================ using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Linq; using System.Web; using System.Xml.Linq; using Composite.Core; using Composite.Core.Linq; using Composite.Core.WebClient.Renderings.Page; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Data; using System.Threading; using Composite.Core.Xml; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Caching { internal sealed class PageObjectCacheFunction : DowncastableStandardFunctionBase { private static readonly XName FunctionXName = Namespaces.Function10 + "function"; private const string C1Name = "PageObjectCache"; private const string C1Namespace = "Composite.Utils.Caching"; public static string FunctionName { get; } = $"{C1Namespace}.{C1Name}"; public PageObjectCacheFunction(EntityTokenFactory entityTokenFactory) : base(C1Name, C1Namespace, typeof(object), entityTokenFactory) { } public class ParameterNames { public static readonly string ObjectToCache = nameof(ObjectToCache); public static readonly string ObjectCacheId = nameof(ObjectCacheId); public static readonly string SitemapScope = nameof(SitemapScope); public static readonly string SecondsToCache = nameof(SecondsToCache); public static readonly string LanguageSpecific = nameof(LanguageSpecific); } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider associationDropDown = StandardWidgetFunctions.DropDownList( this.GetType(), nameof(PageAssociationRestrictions), "Key", "Value", false, true); var textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( ParameterNames.ObjectToCache, typeof(object), true, new NoValueValueProvider(), null); yield return new StandardFunctionParameterProfile( ParameterNames.ObjectCacheId, typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( ParameterNames.SitemapScope, typeof(SitemapScope), false, new ConstantValueProvider(SitemapScope.Level1), associationDropDown); yield return new StandardFunctionParameterProfile( ParameterNames.SecondsToCache, typeof(int), false, new ConstantValueProvider(60), textboxWidget); yield return new StandardFunctionParameterProfile( ParameterNames.LanguageSpecific, typeof(bool), false, new ConstantValueProvider(true), StandardWidgetFunctions.GetBoolSelectorWidget("Language specific content", "Share across all languages")); } } readonly ConcurrentDictionary<string, object> _lockCollection = new ConcurrentDictionary<string, object>(); static bool _potentialKeysLeakLogged = false; public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (DataScopeManager.CurrentDataScope.Name != DataScopeIdentifier.PublicName) { return parameters.GetParameter<object>(ParameterNames.ObjectToCache); } var cache = HttpRuntime.Cache; string cacheKey = BuildCacheKey(parameters); object result = cache.Get(cacheKey); if (result == null) { var lockObject = _lockCollection.GetOrAdd(cacheKey, key => new object()); lock (lockObject) { if(_lockCollection.Count > 50000 && !_potentialKeysLeakLogged) { _potentialKeysLeakLogged = true; Log.LogWarning(nameof(PageObjectCacheFunction), "Potential memory leak in the locks collection"); } result = cache.Get(cacheKey); if (result == null) { result = parameters.GetParameter<object>(ParameterNames.ObjectToCache); if (result != null) { result = EvaluateLazyResult(result, context); int secondsToCache = parameters.GetParameter<int>(ParameterNames.SecondsToCache); cache.Add( cacheKey, result, null, DateTime.Now.AddSeconds(secondsToCache), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null); } } } } return result; } private static object EvaluateLazyResult(object result, FunctionContextContainer context) { if (result is XDocument document) { PageRenderer.ExecuteEmbeddedFunctions(document.Root, context); return result; } if (result is IEnumerable<XNode> xNodes) { return EvaluateLazyResult(xNodes, context); } return result; } private static object EvaluateLazyResult(IEnumerable<XNode> xNodes, FunctionContextContainer context) { var resultList = new List<object>(); // Attaching the result to be cached to an XElement, so the cached XObject-s will not be later attached to // an XDocument and causing a bigger memory leak. var tempParent = new XElement("t"); foreach (var node in xNodes.Evaluate()) { node.Remove(); if (node is XElement element) { if (element.Name == FunctionXName) { var functionTreeNode = (FunctionRuntimeTreeNode)FunctionTreeBuilder.Build(element); var functionCallResult = functionTreeNode.GetValue(context); if (functionCallResult != null) { if (functionCallResult is XDocument document) { functionCallResult = document.Root; } resultList.Add(functionCallResult); if (functionCallResult is XObject || functionCallResult is IEnumerable<XObject>) { tempParent.Add(functionCallResult); } } } else { PageRenderer.ExecuteEmbeddedFunctions(element, context); resultList.Add(element); tempParent.Add(element); } } else { resultList.Add(node); tempParent.Add(node); } } return resultList.ToArray(); } private static string BuildCacheKey(ParameterList parameters) { string cacheKey = parameters.GetParameter<string>(ParameterNames.ObjectCacheId); bool languageSpecific = parameters.GetParameter<bool>(ParameterNames.LanguageSpecific); if (languageSpecific) { cacheKey = $"{cacheKey}:{Thread.CurrentThread.CurrentCulture}"; } SitemapScope SitemapScope = parameters.GetParameter<SitemapScope>(ParameterNames.SitemapScope); if (SitemapScope != SitemapScope.All) { Guid associatedPageId = PageStructureInfo.GetAssociatedPageIds(PageRenderer.CurrentPageId, SitemapScope).FirstOrDefault(); associatedPageId = (associatedPageId == Guid.Empty ? PageRenderer.CurrentPageId : associatedPageId); cacheKey = $"{cacheKey}:{associatedPageId}"; } return cacheKey; } public static IEnumerable<KeyValuePair<SitemapScope, string>> PageAssociationRestrictions() { yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Current, "Current page"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.All, "All pages (use everywhere)"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Parent, "Parent page"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level1, "Level 1 page (this website)"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level2, "Level 2 page"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level3, "Level 3 page"); yield return new KeyValuePair<SitemapScope, string>(SitemapScope.Level4, "Level 4 page"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Compare/AreEqualFunction.cs ================================================ using System.Collections.Generic; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Compare { internal sealed class AreEqualFunction : StandardFunctionBase { public AreEqualFunction(EntityTokenFactory entityTokenFactory) : base("AreEqual", "Composite.Utils.Compare", typeof(bool), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { object valueA = parameters.GetParameter<object>("ValueA"); object valueB = parameters.GetParameter<object>("ValueB"); return valueA.Equals(valueB); } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield return new StandardFunctionParameterProfile( "ValueA", typeof(object), true, new NoValueValueProvider(), null); yield return new StandardFunctionParameterProfile( "ValueB", typeof(object), true, new NoValueValueProvider(), null); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Compare/IsLessThanFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.C1Console.Security; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Compare { internal sealed class IsLessThanFunction : StandardFunctionBase { public IsLessThanFunction(EntityTokenFactory entityTokenFactory) : base("IsLessThan", "Composite.Utils.Compare", typeof(bool), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { IComparable valueA = parameters.GetParameter<IComparable>("ValueA"); IComparable valueB = parameters.GetParameter<IComparable>("ValueB"); return valueA.CompareTo(valueB); } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield return new StandardFunctionParameterProfile( "ValueA", typeof(object), true, new NoValueValueProvider(), null); yield return new StandardFunctionParameterProfile( "ValueB", typeof(object), true, new NoValueValueProvider(), null); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Configuration/AppSettingsValueFunction.cs ================================================ using System.Collections.Generic; using System.Configuration; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Configuration { internal sealed class AppSettingsValueFunction : StandardFunctionBase { public AppSettingsValueFunction(EntityTokenFactory entityTokenFactory) : base("AppSettingsValue", "Composite.Utils.Configuration", typeof(string), entityTokenFactory) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationManagerClass:DoNotUseConfigurationManagerClass", Justification = "This works for now, but might have to be fixed")] public override object Execute(ParameterList parameters, FunctionContextContainer context) { string keyName = parameters.GetParameter<string>("KeyName"); return ConfigurationManager.AppSettings[keyName]; } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield return new StandardFunctionParameterProfile( "KeyName", typeof(string), true, new NoValueValueProvider(), StandardWidgetFunctions.TextBoxWidget); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Date/AddDaysFunction.cs ================================================ using System; using Composite.Functions; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Date { internal sealed class AddDaysFunction : StandardFunctionBase { public AddDaysFunction(EntityTokenFactory entityTokenFactory) : base("AddDays", "Composite.Utils.Date", typeof(DateTime), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.IntegerTextBoxWidget; yield return new StandardFunctionParameterProfile( "DaysToAdd", typeof(double), true, new ConstantValueProvider((double)0), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { double daysToAdd = parameters.GetParameter<double>("DaysToAdd"); return DateTime.Now.AddDays(daysToAdd); ; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Date/NowFunction.cs ================================================ using System; using Composite.Functions; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Date { internal sealed class NowFunction : StandardFunctionBase { public NowFunction(EntityTokenFactory entityTokenFactory) : base("Now", "Composite.Utils.Date", typeof(DateTime), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { return DateTime.Now; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Dictionary/EnumerableToDictionary.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using System.Collections; using Composite.Functions; using System.Reflection; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Dictionary { internal class EnumerableToDictionary : StandardFunctionBase { public EnumerableToDictionary(EntityTokenFactory entityTokenFactory) : base("EnumerableToDictionary", "Composite.Utils.Dictionary", typeof(IDictionary), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { IEnumerable elements = parameters.GetParameter<IEnumerable>("Elements"); string keyPropertyName = parameters.GetParameter<string>("KeyPropertyName"); string valuePropertyName = parameters.GetParameter<string>("ValuePropertyName"); Dictionary<string, string> resultDictionary = new Dictionary<string, string>(); PropertyInfo keyPropertyInfo = null; PropertyInfo valuePropertyInfo = null; foreach (object element in elements) { if (keyPropertyInfo == null) { keyPropertyInfo = element.GetType().GetProperty(keyPropertyName); } if (valuePropertyInfo == null) { valuePropertyInfo = element.GetType().GetProperty(valuePropertyName); } string keyValue = keyPropertyInfo.GetValue(element, null).ToString(); string valueValue = valuePropertyInfo.GetValue(element, null).ToString(); resultDictionary.Add(keyValue, valueValue); } return resultDictionary; } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "Elements", typeof(IEnumerable), true, new NoValueValueProvider(), null); yield return new StandardFunctionParameterProfile( "KeyPropertyName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "ValuePropertyName", typeof(string), true, new NoValueValueProvider(), textboxWidget); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Dictionary/XElementsToDictionaryFunction.cs ================================================ using System.Collections; using System.Collections.Generic; using System.Xml.Linq; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Dictionary { internal class XElementsToDictionaryFunction : StandardFunctionBase { public XElementsToDictionaryFunction(EntityTokenFactory entityTokenFactory) : base("XElementsToDictionary", "Composite.Utils.Dictionary", typeof(IDictionary), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { IEnumerable<XElement> elements = parameters.GetParameter<IEnumerable<XElement>>("XElements"); string keyAttributeName = parameters.GetParameter<string>("KeyAttributeName"); string valueAttributeName = parameters.GetParameter<string>("ValueAttributeName"); Dictionary<string, string> resultDictionary = new Dictionary<string, string>(); foreach (XElement element in elements) { XAttribute keyAttribute = element.Attribute(keyAttributeName); XAttribute valueAttribute = element.Attribute(valueAttributeName); string keyValue = keyAttribute != null ? keyAttribute.Value : null; string valueValue = valueAttribute != null ? valueAttribute.Value : null; resultDictionary.Add(keyValue, valueValue); } return resultDictionary; } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "XElements", typeof(IEnumerable<XElement>), true, new NoValueValueProvider(), null); yield return new StandardFunctionParameterProfile( "KeyAttributeName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "ValueAttributeName", typeof(string), true, new NoValueValueProvider(), textboxWidget); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/GetInputParameterFunction.cs ================================================ using System; using System.Collections.Generic; using Composite.Functions; using Composite.C1Console.Security; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils { internal sealed class GetInputParameterFunction : DowncastableStandardFunctionBase { public GetInputParameterFunction(EntityTokenFactory entityTokenFactory) : base("GetInputParameter", "Composite.Utils", typeof(object), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "InputParameterName", typeof(string), true, new NoValueValueProvider(), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { string parameterName = parameters.GetParameter<string>("InputParameterName"); return context.GetParameterValue(parameterName, typeof(object)); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Globalization/AllCultures.cs ================================================ using System; using System.Linq; using Composite.Functions; using System.Collections.Generic; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using System.Globalization; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Globalization { internal sealed class AllCultures : StandardFunctionBase { public AllCultures(EntityTokenFactory entityTokenFactory) : base("AllCultures", "Composite.Utils.Globalization", typeof(IEnumerable<CultureInfo>), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { return GetCultures(); } private IEnumerable<CultureInfo> GetCultures() { foreach (CultureInfo info in CultureInfo.GetCultures(CultureTypes.SpecificCultures).OrderBy( f=>f.DisplayName)) { yield return info; } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Globalization/CurrentCulture.cs ================================================ using System; using Composite.Functions; using System.Collections.Generic; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using System.Globalization; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Globalization { internal sealed class CurrentCulture : StandardFunctionBase { public CurrentCulture(EntityTokenFactory entityTokenFactory) : base("CurrentCulture", "Composite.Utils.Globalization", typeof(CultureInfo), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { return System.Threading.Thread.CurrentThread.CurrentCulture; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Guid/NewGuid.cs ================================================ using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.GuidFunctions { internal sealed class NewGuid : StandardFunctionBase { public NewGuid(EntityTokenFactory entityTokenFactory) : base("NewGuid", "Composite.Utils.Guid", typeof(System.Guid), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { return System.Guid.NewGuid(); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Integer/IntSum.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Text; using Composite.Functions; using Composite.C1Console.Security; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Integer { internal sealed class Sum : StandardFunctionBase { public Sum(EntityTokenFactory entityTokenFactory) : base("Sum", "Composite.Utils.Integer", typeof(int), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { IEnumerable<int> ints = parameters.GetParameter<IEnumerable<int>>("Ints"); return ints.Sum(); } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield return new StandardFunctionParameterProfile( "Ints", typeof(IEnumerable<int>), true, new NoValueValueProvider(), null); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/ParseStringToObject.cs ================================================ using System; using System.Collections.Generic; using Composite.Functions; using Composite.C1Console.Security; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils { internal sealed class ParseStringToObjectFunction : DowncastableStandardFunctionBase { public ParseStringToObjectFunction(EntityTokenFactory entityTokenFactory) : base("ParseStringToObject", "Composite.Utils", typeof(object), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "StringToParse", typeof(string), true, new NoValueValueProvider(), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { string stringToParse = parameters.GetParameter<string>("StringToParse"); return stringToParse; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/BoolEqualsPredicateFunction.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; using System.Linq.Expressions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class BoolEqualsPredicateFunction : StandardFunctionBase { public BoolEqualsPredicateFunction(EntityTokenFactory entityTokenFactory) : base("BoolEquals", "Composite.Utils.Predicates", typeof(Expression<Func<bool, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.GetBoolSelectorWidget("True", "False"); yield return new StandardFunctionParameterProfile( "Value", typeof(bool), true, new NoValueValueProvider(), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { bool value = parameters.GetParameter<bool>("Value"); Expression<Func<bool, bool>> predicate = f => f == value; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/DateTimeEqualsPredicateFunction.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; using System.Linq.Expressions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class DateTimeEqualsPredicateFunction : StandardFunctionBase { public DateTimeEqualsPredicateFunction(EntityTokenFactory entityTokenFactory) : base("DateTimeEquals", "Composite.Utils.Predicates", typeof(Expression<Func<DateTime, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.DateTimeSelectorWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(DateTime), true, new NoValueValueProvider(), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { DateTime value = parameters.GetParameter<DateTime>("Value"); Expression<Func<DateTime,bool>> predicate = f=>f == value; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/DateTimeGreaterThanPredicateFunction.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; using System.Linq.Expressions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class DateTimeGreaterThanPredicateFunction : StandardFunctionBase { public DateTimeGreaterThanPredicateFunction(EntityTokenFactory entityTokenFactory) : base("DateTimeGreaterThan", "Composite.Utils.Predicates", typeof(Expression<Func<DateTime, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.DateTimeSelectorWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(DateTime), true, new NoValueValueProvider(), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { DateTime value = parameters.GetParameter<DateTime>("Value"); Expression<Func<DateTime,bool>> predicate = f=>f > value; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/DateTimeLessThanPredicateFunction.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; using System.Linq.Expressions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class DateTimeLessThanPredicateFunction : StandardFunctionBase { public DateTimeLessThanPredicateFunction(EntityTokenFactory entityTokenFactory) : base("DateTimeLessThan", "Composite.Utils.Predicates", typeof(Expression<Func<DateTime, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.DateTimeSelectorWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(DateTime), true, new NoValueValueProvider(), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { DateTime value = parameters.GetParameter<DateTime>("Value"); Expression<Func<DateTime,bool>> predicate = f=>f < value; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/DecimalEqualsPredicateFunction.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; using System.Linq.Expressions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class DecimalEqualsPredicateFunction : StandardFunctionBase { public DecimalEqualsPredicateFunction(EntityTokenFactory entityTokenFactory) : base("DecimalEquals", "Composite.Utils.Predicates", typeof(Expression<Func<decimal, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.DecimalTextBoxWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(decimal), true, new NoValueValueProvider(), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { decimal value = parameters.GetParameter<decimal>("Value"); Expression<Func<decimal,bool>> predicate = f=>f == value; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/DecimalGreaterThanPredicateFunction.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; using System.Linq.Expressions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class DecimalGreaterThanPredicateFunction : StandardFunctionBase { public DecimalGreaterThanPredicateFunction(EntityTokenFactory entityTokenFactory) : base("DecimalGreaterThan", "Composite.Utils.Predicates", typeof(Expression<Func<decimal, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.DecimalTextBoxWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(decimal), true, new NoValueValueProvider(), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { decimal value = parameters.GetParameter<decimal>("Value"); Expression<Func<decimal,bool>> predicate = f=>f > value; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/DecimalLessThanPredicateFunction.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; using System.Linq.Expressions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class DecimalLessThanPredicateFunction : StandardFunctionBase { public DecimalLessThanPredicateFunction(EntityTokenFactory entityTokenFactory) : base("DecimalLessThan", "Composite.Utils.Predicates", typeof(Expression<Func<decimal, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.DecimalTextBoxWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(decimal), true, new NoValueValueProvider(), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { decimal value = parameters.GetParameter<decimal>("Value"); Expression<Func<decimal, bool>> predicate = f => f < value; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/GuidEqualsPredicateFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class GuidEqualsPredicateFunction : StandardFunctionBase { public GuidEqualsPredicateFunction(EntityTokenFactory entityTokenFactory) : base("GuidEquals", "Composite.Utils.Predicates", typeof(Expression<Func<Guid, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(Guid), true, new NoValueValueProvider(), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { Guid value = parameters.GetParameter<Guid>("Value"); // Expression<Func<Guid, bool>> predicate = f => f == value; // DDZ: in order to get a correct debug information, not using labmda syntax while building an expression ParameterExpression parameter = Expression.Parameter(typeof(Guid), "f"); return Expression.Lambda<Func<Guid, bool>>(Expression.Equal(parameter, Expression.Constant(value)), parameter); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/GuidInCommaSeparatedListPredicateFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using Composite.Core.Linq; using Composite.Core.Extensions; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class GuidInCommaSeparatedListPredicateFunction : StandardFunctionBase { public GuidInCommaSeparatedListPredicateFunction(EntityTokenFactory entityTokenFactory) : base("GuidInCommaSeparatedList", "Composite.Utils.Predicates", typeof(Expression<Func<Guid, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "CommaSeparatedGuids", typeof(string), true, new NoValueValueProvider(), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { string commaSeparatedSearchTerms = parameters.GetParameter<string>("CommaSeparatedGuids"); if (!commaSeparatedSearchTerms.IsNullOrEmpty()) { ParameterExpression parameter = Expression.Parameter(typeof(Guid), "g"); IEnumerable<string> guidStrings = commaSeparatedSearchTerms.Split(','); Expression body = null; foreach (string guidString in guidStrings) { Guid temp = new Guid(guidString.Trim()); Expression part = Expression.Equal(parameter, Expression.Constant(temp)); body = body.NestedOr(part); } if(body != null) { return Expression.Lambda<Func<Guid, bool>>(body, parameter); } } return (Expression<Func<Guid, bool>>) (f => false); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/IntegerEqualsPredicateFunction.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; using System.Linq.Expressions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class IntegerEqualsPredicateFunction : StandardFunctionBase { public IntegerEqualsPredicateFunction(EntityTokenFactory entityTokenFactory) : base("IntegerEquals", "Composite.Utils.Predicates", typeof(Expression<Func<int, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.IntegerTextBoxWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(int), true, new NoValueValueProvider(), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { int value = parameters.GetParameter<int>("Value"); Expression<Func<int,bool>> predicate = f=>f == value; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/IntegerGreaterThanPredicateFunction.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; using System.Linq.Expressions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class IntegerGreaterThanPredicateFunction : StandardFunctionBase { public IntegerGreaterThanPredicateFunction(EntityTokenFactory entityTokenFactory) : base("IntegerGreaterThan", "Composite.Utils.Predicates", typeof(Expression<Func<int, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.IntegerTextBoxWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(int), true, new NoValueValueProvider(), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { int value = parameters.GetParameter<int>("Value"); Expression<Func<int,bool>> predicate = f=>f > value; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/IntegerLessThanPredicateFunction.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; using System.Linq.Expressions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class IntegerLessThanPredicateFunction : StandardFunctionBase { public IntegerLessThanPredicateFunction(EntityTokenFactory entityTokenFactory) : base("IntegerLessThan", "Composite.Utils.Predicates", typeof(Expression<Func<int, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.IntegerTextBoxWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(int), true, new NoValueValueProvider(), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { int value = parameters.GetParameter<int>("Value"); Expression<Func<int,bool>> predicate = f=>f < value; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/NullableBoolEqualsPredicateFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class NullableBoolEqualsPredicateFunction : StandardFunctionBase { public NullableBoolEqualsPredicateFunction(EntityTokenFactory entityTokenFactory) : base("NullableBoolEquals", "Composite.Utils.Predicates", typeof(Expression<Func<bool?, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.GetBoolSelectorWidget("True", "False"); yield return new StandardFunctionParameterProfile( "Value", typeof(bool), true, new NoValueValueProvider(), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { bool value = parameters.GetParameter<bool>("Value"); Expression<Func<bool?, bool>> predicate = f => f.HasValue && f.Value == value; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/NullableBoolNoValuePredicateFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class NullableBoolNoValuePredicateFunction : StandardFunctionBase { public NullableBoolNoValuePredicateFunction(EntityTokenFactory entityTokenFactory) : base("NullableBoolNoValue", "Composite.Utils.Predicates", typeof(Expression<Func<bool?, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield break; } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { Expression<Func<bool?, bool>> predicate = f => f.HasValue == false; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/NullableDateTimeEqualsPredicateFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class NullableDateTimeEqualsPredicateFunction : StandardFunctionBase { public NullableDateTimeEqualsPredicateFunction(EntityTokenFactory entityTokenFactory) : base("NullableDateTimeEquals", "Composite.Utils.Predicates", typeof(Expression<Func<DateTime?, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.DateTimeSelectorWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(DateTime), true, new NoValueValueProvider(), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { DateTime value = parameters.GetParameter<DateTime>("Value"); Expression<Func<DateTime?, bool>> predicate = f => f.HasValue && f.Value == value; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/NullableDateTimeGreaterThanPredicateFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class NullableDateTimeGreaterThanPredicateFunction : StandardFunctionBase { public NullableDateTimeGreaterThanPredicateFunction(EntityTokenFactory entityTokenFactory) : base("NullableDateTimeGreaterThan", "Composite.Utils.Predicates", typeof(Expression<Func<DateTime?, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.DateTimeSelectorWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(DateTime), true, new NoValueValueProvider(), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { DateTime value = parameters.GetParameter<DateTime>("Value"); Expression<Func<DateTime?, bool>> predicate = f => f.HasValue && f.Value > value; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/NullableDateTimeLessThanPredicateFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class NullableDateTimeLessThanPredicateFunction : StandardFunctionBase { public NullableDateTimeLessThanPredicateFunction(EntityTokenFactory entityTokenFactory) : base("NullableDateTimeLessThan", "Composite.Utils.Predicates", typeof(Expression<Func<DateTime?, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.DateTimeSelectorWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(DateTime), true, new NoValueValueProvider(), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { DateTime value = parameters.GetParameter<DateTime>("Value"); Expression<Func<DateTime?, bool>> predicate = f => f.HasValue && f.Value < value; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/NullableDateTimeNoValuePredicateFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class NullableDateTimeNoValuePredicateFunction : StandardFunctionBase { public NullableDateTimeNoValuePredicateFunction(EntityTokenFactory entityTokenFactory) : base("NullableDateTimeNoValue", "Composite.Utils.Predicates", typeof(Expression<Func<DateTime?, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield break; } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { Expression<Func<DateTime?, bool>> predicate = f => f.HasValue == false; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/NullableDecimalEqualsPredicateFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class NullableDecimalEqualsPredicateFunction : StandardFunctionBase { public NullableDecimalEqualsPredicateFunction(EntityTokenFactory entityTokenFactory) : base("NullableDecimalEquals", "Composite.Utils.Predicates", typeof(Expression<Func<decimal?, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.DecimalTextBoxWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(decimal), true, new NoValueValueProvider(), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { decimal value = parameters.GetParameter<decimal>("Value"); Expression<Func<decimal?, bool>> predicate = f => f.HasValue && f.Value == value; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/NullableDecimalNoValuePredicateFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class NullableDecimalNoValuePredicateFunction : StandardFunctionBase { public NullableDecimalNoValuePredicateFunction(EntityTokenFactory entityTokenFactory) : base("NullableDecimalNoValue", "Composite.Utils.Predicates", typeof(Expression<Func<decimal?, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield break; } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { Expression<Func<decimal?, bool>> predicate = f => f.HasValue == false; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/NullableGuidEqualsPredicateFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class NullableGuidEqualsPredicateFunction : StandardFunctionBase { public NullableGuidEqualsPredicateFunction(EntityTokenFactory entityTokenFactory) : base("NullableGuidEquals", "Composite.Utils.Predicates", typeof(Expression<Func<Guid?, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(Guid), true, new NoValueValueProvider(), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { Guid? value = parameters.GetParameter<Guid?>("Value"); // Expression<Func<Guid?, bool>> predicate = f => f == value; var f = Expression.Parameter(typeof(Guid?), "f"); var body = Expression.Equal(f, Expression.Constant(value, typeof (Guid?))); return Expression.Lambda(body, f); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/NullableGuidNoValuePredicateFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class NullableGuidNoValuePredicateFunction : StandardFunctionBase { public NullableGuidNoValuePredicateFunction(EntityTokenFactory entityTokenFactory) : base("NullableGuidNoValue", "Composite.Utils.Predicates", typeof(Expression<Func<Guid?, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield break; } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { Expression<Func<Guid?, bool>> predicate = f => f.HasValue == false; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/NullableIntegerEqualsPredicateFunction.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; using System.Linq.Expressions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class NullableIntegerEqualsPredicateFunction : StandardFunctionBase { public NullableIntegerEqualsPredicateFunction(EntityTokenFactory entityTokenFactory) : base("NullableIntegerEquals", "Composite.Utils.Predicates", typeof(Expression<Func<int?, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider widget = StandardWidgetFunctions.IntegerTextBoxWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(int), true, new NoValueValueProvider(), widget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { int value = parameters.GetParameter<int>("Value"); Expression<Func<int?, bool>> predicate = f => f.HasValue && f.Value == value; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/NullableIntegerNoValuePredicateFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class NullableIntegerNoValuePredicateFunction : StandardFunctionBase { public NullableIntegerNoValuePredicateFunction(EntityTokenFactory entityTokenFactory) : base("NullableIntegerNoValue", "Composite.Utils.Predicates", typeof(Expression<Func<int?, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield break; } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { Expression<Func<int?, bool>> predicate = f => f.HasValue == false; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/StringContainsPredicateFunction.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; using System.Linq.Expressions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class StringContainsPredicateFunction : StandardFunctionBase { public StringContainsPredicateFunction(EntityTokenFactory entityTokenFactory) : base("StringContains", "Composite.Utils.Predicates", typeof(Expression<Func<string, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(string), true, new ConstantValueProvider(""), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { string valueToFind = parameters.GetParameter<string>("Value"); Expression<Func<string,bool>> predicate = f=>f.Contains(valueToFind); return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/StringEndsWithPredicateFunction.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; using System.Linq.Expressions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class StringEndsWithPredicateFunction : StandardFunctionBase { public StringEndsWithPredicateFunction(EntityTokenFactory entityTokenFactory) : base("StringEndsWith", "Composite.Utils.Predicates", typeof(Expression<Func<string, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(string), true, new ConstantValueProvider(""), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { string valueToFind = parameters.GetParameter<string>("Value"); Expression<Func<string,bool>> predicate = f=>f.EndsWith(valueToFind); return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/StringEqualsPredicateFunction.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; using System.Linq.Expressions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class StringEqualsPredicateFunction : StandardFunctionBase { public StringEqualsPredicateFunction(EntityTokenFactory entityTokenFactory) : base("StringEquals", "Composite.Utils.Predicates", typeof(Expression<Func<string, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(string), true, new ConstantValueProvider(""), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { string value = parameters.GetParameter<string>("Value"); Expression<Func<string, bool>> predicate = f => f == value; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/StringInCommaSeparatedListPredicateFunction.cs ================================================ using System; using System.Collections.Generic; using System.Reflection; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.Extensions; using System.Linq.Expressions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class StringInCommaSeparatedListPredicateFunction : StandardFunctionBase { private static readonly MethodInfo _stringCompareMethodInfo; static StringInCommaSeparatedListPredicateFunction() { _stringCompareMethodInfo = typeof(string).GetMethod("Compare", new[] { typeof(string), typeof(string), typeof(StringComparison) }); } public StringInCommaSeparatedListPredicateFunction(EntityTokenFactory entityTokenFactory) : base("StringInCommaSeparatedList", "Composite.Utils.Predicates", typeof(Expression<Func<string, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "CommaSeparatedSearchTerms", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "IgnoreCase", typeof(bool), false, new ConstantValueProvider(true), StandardWidgetFunctions.GetBoolSelectorWidget("Ignore case", "Match case")); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { Expression<Func<string, bool>> emptyPredicate = f => false; string commaSeparatedSearchTerms = parameters.GetParameter<string>("CommaSeparatedSearchTerms"); if (commaSeparatedSearchTerms.IsNullOrEmpty()) { return emptyPredicate; } bool ignoreCase = parameters.GetParameter<bool>("IgnoreCase"); string[] searchTerms = commaSeparatedSearchTerms.Split(new [] {','}/*, StringSplitOptions.RemoveEmptyEntries*/); if (searchTerms.Length == 0) { return emptyPredicate; } StringComparison stringComparison = (ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture); var parameterExpression = Expression.Parameter(typeof(string), "p"); Expression body = null; foreach (string searchTerm in searchTerms) { string termTrimmed = searchTerm.Trim(); // string.Compare(p, termTrimmed, stringComparison) == 0 // string.Compare() is supported by linq2sql Expression condition = Expression.Equal(Expression.Call( _stringCompareMethodInfo, parameterExpression, Expression.Constant(termTrimmed), Expression.Constant(stringComparison)), Expression.Constant(0)); body = body == null ? condition : Expression.Or(body, condition); } Verify.IsNotNull(body, "Expression body is null"); return Expression.Lambda<Func<string, bool>>(body, parameterExpression); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/StringInListPredicateFunction.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.Extensions; using System.Linq.Expressions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class StringInListPredicateFunction : StandardFunctionBase { public StringInListPredicateFunction(EntityTokenFactory entityTokenFactory) : base("StringInList", "Composite.Utils.Predicates", typeof(Expression<Func<string, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield return new StandardFunctionParameterProfile( "SearchTerms", typeof(IEnumerable<string>), true, new NoValueValueProvider(), null); yield return new StandardFunctionParameterProfile( "IgnoreCase", typeof(bool), false, new ConstantValueProvider(true), StandardWidgetFunctions.GetBoolSelectorWidget("Ignore case", "Match case")); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { IEnumerable<string> searchTerms = parameters.GetParameter<IEnumerable<string>>("SearchTerms"); bool ignoreCase = parameters.GetParameter<bool>("IgnoreCase"); StringComparison stringComparison = (ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture); Expression<Func<string, bool>> predicate = f => false; foreach (string searchTerm in searchTerms) { string temp = searchTerm.Trim(); predicate = predicate.Or(c => c.Equals(temp, stringComparison)); } return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/StringNoValuePredicateFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq.Expressions; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class StringNoValuePredicateFunction : StandardFunctionBase { public StringNoValuePredicateFunction(EntityTokenFactory entityTokenFactory) : base("StringNoValue", "Composite.Utils.Predicates", typeof(Expression<Func<string, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield break; } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { Expression<Func<string, bool>> predicate = f => f == null; return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Predicates/StringStartsWithPredicateFunction.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; using System.Linq.Expressions; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Predicates { internal sealed class StringStartsWithPredicateFunction : StandardFunctionBase { public StringStartsWithPredicateFunction(EntityTokenFactory entityTokenFactory) : base("StringStartsWith", "Composite.Utils.Predicates", typeof(Expression<Func<string, bool>>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "Value", typeof(string), true, new ConstantValueProvider(""), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { string valueToFind = parameters.GetParameter<string>("Value"); Expression<Func<string, bool>> predicate = f => f.StartsWith(valueToFind); return predicate; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/String/Format.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.String { internal sealed class Format : StandardFunctionBase, ICompoundFunction { public Format(EntityTokenFactory entityTokenFactory) : base("Format", "Composite.Utils.String", typeof(string), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { string format = parameters.GetParameter<string>("Format"); var formatParameters = new object[5]; formatParameters[0] = parameters.GetParameter<string>("Parameter1"); Verify.IsNotNull(formatParameters[0], "Parameter1 is null"); formatParameters[1] = parameters.GetParameter<string>("Parameter2"); formatParameters[2] = parameters.GetParameter<string>("Parameter3"); formatParameters[3] = parameters.GetParameter<string>("Parameter4"); formatParameters[4] = parameters.GetParameter<string>("Parameter5"); return string.Format(format, formatParameters); } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "FormatString", typeof(IEnumerable<string>), true, new NoValueValueProvider(), null); yield return new StandardFunctionParameterProfile( "Parameter1", typeof(string), true, new ConstantValueProvider(null), textboxWidget); yield return new StandardFunctionParameterProfile( "Parameter2", typeof(string), false, new ConstantValueProvider(null), textboxWidget); yield return new StandardFunctionParameterProfile( "Parameter3", typeof(string), false, new ConstantValueProvider(null), textboxWidget); yield return new StandardFunctionParameterProfile( "Parameter4", typeof(string), false, new ConstantValueProvider(null), textboxWidget); yield return new StandardFunctionParameterProfile( "Parameter5", typeof(string), false, new ConstantValueProvider(null), textboxWidget); } } public bool AllowRecursiveCall { get { return true; } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/String/Join.cs ================================================ using System; using System.Collections.Generic; using System.Text; using System.Linq; using Composite.Functions; using Composite.C1Console.Security; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.String { internal sealed class Join : StandardFunctionBase { public Join(EntityTokenFactory entityTokenFactory) : base("Join", "Composite.Utils.String", typeof(string), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { IEnumerable<string> strings = parameters.GetParameter<IEnumerable<string>>("Strings"); string separator = parameters.GetParameter<string>("Separator"); return string.Join(separator, strings.ToArray()); } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "Strings", typeof(IEnumerable<string>), true, new NoValueValueProvider(),null); yield return new StandardFunctionParameterProfile( "Separator", typeof(string), false, new ConstantValueProvider(""), textboxWidget); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/String/JoinTwo.cs ================================================ using System; using System.Collections.Generic; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.String { internal sealed class JoinTwo : StandardFunctionBase, ICompoundFunction { public JoinTwo(EntityTokenFactory entityTokenFactory) : base("JoinTwo", "Composite.Utils.String", typeof(string), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { string stringA = parameters.GetParameter<string>("StringA"); string stringB = parameters.GetParameter<string>("StringB"); string separator = parameters.GetParameter<string>("Separator"); return stringA + separator + stringB; } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "StringA", typeof(string), true, new ConstantValueProvider(""), textboxWidget); yield return new StandardFunctionParameterProfile( "StringB", typeof(string), true, new ConstantValueProvider(""), textboxWidget); yield return new StandardFunctionParameterProfile( "Separator", typeof(string), false, new ConstantValueProvider(""), textboxWidget); } } public bool AllowRecursiveCall { get { return true; } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/String/Split.cs ================================================ using System; using System.Collections.Generic; using System.Text; using Composite.Functions; using Composite.C1Console.Security; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.String { internal sealed class Split : StandardFunctionBase { public Split(EntityTokenFactory entityTokenFactory) : base("Split", "Composite.Utils.String", typeof(IEnumerable<string>), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { string stringToSplit = parameters.GetParameter<string>("String"); string[] separator = new string[] { parameters.GetParameter<string>("Separator") }; var resultArray = stringToSplit.Split(separator, StringSplitOptions.RemoveEmptyEntries); return new List<string>(resultArray); } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "String", typeof(string), true, new ConstantValueProvider(""), textboxWidget); yield return new StandardFunctionParameterProfile( "Separator", typeof(string), false, new ConstantValueProvider(","), textboxWidget); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Validation/DecimalPrecisionValidationFunction.cs ================================================ using System.CodeDom; using System.Collections.Generic; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Data.Validation; using Composite.Data.Validation.Validators; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Validation { internal sealed class DecimalPrecisionValidationFunction : StandardFunctionBase { public DecimalPrecisionValidationFunction(EntityTokenFactory entityTokenFactory) : base("DecimalPrecisionValidation", "Composite.Utils.Validation", typeof(PropertyValidatorBuilder<decimal>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.IntegerTextBoxWidget; yield return new StandardFunctionParameterProfile( "MaxDigits", typeof(int), true, new NoValueValueProvider(), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { var codeAttributeDeclaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(DecimalPrecisionValidatorAttribute))); int maxDigits = parameters.GetParameter<int>("MaxDigits"); codeAttributeDeclaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(maxDigits))); return new ConstructorBasedPropertyValidatorBuilder<decimal>(codeAttributeDeclaration, new DecimalPrecisionValidatorAttribute(28, maxDigits)); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Validation/IntegerRangeValidationFunction.cs ================================================ using System.CodeDom; using System.Collections.Generic; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Data.Validation; using Composite.Data.Validation.Validators; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Validation { internal sealed class IntegerRangeValidationFunction : StandardFunctionBase { public IntegerRangeValidationFunction(EntityTokenFactory entityTokenFactory) : base("IntegerRangeValidation", "Composite.Utils.Validation", typeof(PropertyValidatorBuilder<int>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield return new StandardFunctionParameterProfile( "min", typeof(int), true, new NoValueValueProvider(), StandardWidgetFunctions.IntegerTextBoxWidget); yield return new StandardFunctionParameterProfile( "max", typeof(int), true, new NoValueValueProvider(), StandardWidgetFunctions.IntegerTextBoxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { var codeAttributeDeclaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(IntegerRangeValidatorAttribute))); int min = parameters.GetParameter<int>("min"); int max = parameters.GetParameter<int>("max"); codeAttributeDeclaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(min))); codeAttributeDeclaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(max))); return new ConstructorBasedPropertyValidatorBuilder<int>(codeAttributeDeclaration, new IntegerRangeValidatorAttribute(min, max)); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Validation/NotNullValidationFunction.cs ================================================ using System.CodeDom; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Data.Validation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Validation { internal sealed class NotNullValidationFunction<T> : StandardFunctionBase { public NotNullValidationFunction(EntityTokenFactory entityTokenFactory) : base(typeof(T).Name + "NotNullValidation", "Composite.Utils.Validation", typeof(PropertyValidatorBuilder<T>), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { var codeAttributeDeclaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidatorAttribute))); return new ConstructorBasedPropertyValidatorBuilder<string>(codeAttributeDeclaration, new Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidatorAttribute()); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Validation/PasswordValidationFunction.cs ================================================ using System.CodeDom; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Data.Validation; using Composite.Data.Validation.Validators; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Validation { internal sealed class PasswordValidationValidationFunction : StandardFunctionBase { public PasswordValidationValidationFunction(EntityTokenFactory entityTokenFactory) : base("PasswordValidation", "Composite.Utils.Validation", typeof(PropertyValidatorBuilder<string>), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { var codeAttributeDeclaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(StringSizeValidatorAttribute))); return new ConstructorBasedPropertyValidatorBuilder<string>(codeAttributeDeclaration, new PasswordValidatorAttribute()); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Validation/RegexValidationFunction.cs ================================================ using System.CodeDom; using System.Collections.Generic; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Data.Validation; using Composite.Data.Validation.Validators; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Validation { internal sealed class RegexValidationFunction : StandardFunctionBase { public RegexValidationFunction(EntityTokenFactory entityTokenFactory) : base("RegularExpressionValidation", "Composite.Utils.Validation", typeof(PropertyValidatorBuilder<string>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield return new StandardFunctionParameterProfile( "pattern", typeof(string), true, new NoValueValueProvider(), StandardWidgetFunctions.TextBoxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { var codeAttributeDeclaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(RegexValidatorAttribute))); string pattern = parameters.GetParameter<string>("pattern"); codeAttributeDeclaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(pattern))); return new ConstructorBasedPropertyValidatorBuilder<string>(codeAttributeDeclaration, new RegexValidatorAttribute(pattern)); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Utils/Validation/StringLengthValidationFunction.cs ================================================ using Composite.Functions; using System.Collections.Generic; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using System.CodeDom; using Composite.Data.Validation; using Composite.Data.Validation.Validators; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Utils.Validation { internal sealed class StringLengthValidationFunction : StandardFunctionBase { public StringLengthValidationFunction(EntityTokenFactory entityTokenFactory) : base("StringLengthValidation", "Composite.Utils.Validation", typeof(PropertyValidatorBuilder<string>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield return new StandardFunctionParameterProfile( "min", typeof(int), true, new NoValueValueProvider(), StandardWidgetFunctions.IntegerTextBoxWidget); yield return new StandardFunctionParameterProfile( "max", typeof(int), true, new NoValueValueProvider(), StandardWidgetFunctions.IntegerTextBoxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { var codeAttributeDeclaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(StringSizeValidatorAttribute))); int min = parameters.GetParameter<int>("min"); int max = parameters.GetParameter<int>("max"); codeAttributeDeclaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(min))); codeAttributeDeclaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(max))); return new ConstructorBasedPropertyValidatorBuilder<string>(codeAttributeDeclaration, new StringSizeValidatorAttribute(min, max)); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Client/BrowserPlatformFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Functions; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Client { internal sealed class BrowserPlatformFunction : StandardFunctionBase { public BrowserPlatformFunction(EntityTokenFactory entityTokenFactory) : base("BrowserPlatform", "Composite.Web.Client", typeof(string), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { return HttpContext.Current.Request.Browser.Platform; } return null; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Client/BrowserStringFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Functions; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Client { internal sealed class BrowserStringFunction : StandardFunctionBase { public BrowserStringFunction(EntityTokenFactory entityTokenFactory) : base("BrowserString", "Composite.Web.Client", typeof(string), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { return HttpContext.Current.Request.Browser.Browser; } return null; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Client/BrowserTypeFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Functions; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Client { internal sealed class BrowserTypeFunction : StandardFunctionBase { public BrowserTypeFunction(EntityTokenFactory entityTokenFactory) : base("BrowserType", "Composite.Web.Client", typeof(string), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { return HttpContext.Current.Request.Browser.Type; } return null; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Client/BrowserVersionFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Functions; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Client { internal sealed class BrowserVersionFunction : StandardFunctionBase { public BrowserVersionFunction(EntityTokenFactory entityTokenFactory) : base("BrowserVersion", "Composite.Web.Client", typeof(string), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { return HttpContext.Current.Request.Browser.Version; } return null; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Client/EcmaScriptVersionFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Functions; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Client { internal sealed class EcmaScriptVersionFunction : StandardFunctionBase { public EcmaScriptVersionFunction(EntityTokenFactory entityTokenFactory) : base("EcmaScriptVersion", "Composite.Web.Client", typeof(string), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { return HttpContext.Current.Request.Browser.EcmaScriptVersion; } return null; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Client/IsCrawlerFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Functions; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Client { internal sealed class IsCrawlerFunction : StandardFunctionBase { public IsCrawlerFunction(EntityTokenFactory entityTokenFactory) : base("IsCrawler", "Composite.Web.Client", typeof(bool), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { return HttpContext.Current.Request.Browser.Crawler; } return false; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Client/IsMobileDeviceFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Functions; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Client { internal sealed class IsMobileDeviceFunction : StandardFunctionBase { public IsMobileDeviceFunction(EntityTokenFactory entityTokenFactory) : base("IsMobileDevice", "Composite.Web.Client", typeof(bool), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { return HttpContext.Current.Request.Browser.IsMobileDevice; } return false; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Html/Template/CommonMetaTagsFunction.cs ================================================ using System.Collections.Generic; using System.Threading; using System.Xml.Linq; using Composite.Core.Xml; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Html.Template { internal sealed class CommonMetaTagsFunction : StandardFunctionBase { public CommonMetaTagsFunction(EntityTokenFactory entityTokenFactory) : base("CommonMetaTags", "Composite.Web.Html.Template", typeof(IEnumerable<XElement>), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider showGeneratorWidget = StandardWidgetFunctions.GetBoolSelectorWidget("Yes, show C1 CMS Foundation support!", "No, please hide this..."); yield return new StandardFunctionParameterProfile( "ContentType", typeof(string), false, new ConstantValueProvider("text/html; charset=utf-8"), StandardWidgetFunctions.TextBoxWidget); yield return new StandardFunctionParameterProfile( "Designer", typeof(string), false, new ConstantValueProvider(""), StandardWidgetFunctions.TextBoxWidget); yield return new StandardFunctionParameterProfile( "ShowGenerator", typeof(bool), false, new ConstantValueProvider(true), showGeneratorWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { var metaTags = new List<XElement>(); string contentType = parameters.GetParameter<string>("ContentType"); string designer = parameters.GetParameter<string>("Designer"); bool showGenerator = parameters.GetParameter<bool>("ShowGenerator"); if (!string.IsNullOrWhiteSpace(contentType)) { metaTags.Add(new XElement(Namespaces.Xhtml + "meta", new XAttribute("http-equiv", "Content-Type"), new XAttribute("content", contentType))); } if (!string.IsNullOrWhiteSpace(designer)) { metaTags.Add(new XElement(Namespaces.Xhtml + "meta", new XAttribute("name", "Designer"), new XAttribute("content", designer))); } if (showGenerator) { metaTags.Add(new XElement(Namespaces.Xhtml + "meta", new XAttribute("name", "Generator"), new XAttribute("content", "C1 CMS Foundation - Free Open Source from Orckestra and https://github.com/Orckestra/C1-CMS-Foundation"))); } return metaTags; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Html/Template/HtmlTitleValueFunction.cs ================================================ using System.Collections.Generic; using System.Web; using System.Web.UI; using Composite.Data; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Html.Template { internal sealed class HtmlTitleValueFunction : StandardFunctionBase { public HtmlTitleValueFunction(EntityTokenFactory entityTokenFactory) : base("HtmlTitleValue", "Composite.Web.Html.Template", typeof(Control), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextAreaWidget; yield return new StandardFunctionParameterProfile("PrefixToRemove", typeof(string), false, new ConstantValueProvider(""), textboxWidget); yield return new StandardFunctionParameterProfile("PostfixToRemove", typeof(string), false, new ConstantValueProvider(""), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { return new TitleControl { PrefixToRemove = parameters.GetParameter<string>("PrefixToRemove"), PostfixToRemove = parameters.GetParameter<string>("PostfixToRemove") }; } private class TitleControl : Control { public string PrefixToRemove { get; set; } public string PostfixToRemove { get; set; } protected override void Render(HtmlTextWriter writer) { string pageTitle = this.Page.Title; if (string.IsNullOrWhiteSpace(pageTitle) && SiteMap.CurrentNode != null) { pageTitle = SiteMap.CurrentNode.Title; } if (string.IsNullOrWhiteSpace(pageTitle)) { using (DataConnection connection = new DataConnection()) { pageTitle = connection.SitemapNavigator.CurrentPageNode.Title; } } pageTitle = pageTitle.Trim(); if (!string.IsNullOrEmpty(this.PrefixToRemove) && pageTitle.StartsWith(this.PrefixToRemove)) { pageTitle = pageTitle.Remove(0, this.PrefixToRemove.Length); } if (!string.IsNullOrEmpty(this.PostfixToRemove) && pageTitle.EndsWith(this.PostfixToRemove)) { pageTitle = pageTitle.Remove(pageTitle.Length - PostfixToRemove.Length); } writer.Write(pageTitle); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Html/Template/LangAttributeFunction.cs ================================================ using System.Threading; using System.Xml.Linq; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Html.Template { internal sealed class LangAttributeFunction : StandardFunctionBase { public LangAttributeFunction(EntityTokenFactory entityTokenFactory) : base("LangAttribute", "Composite.Web.Html.Template", typeof(XAttribute), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { return new XAttribute("lang", Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Html/Template/MetaDescriptionValueFunction.cs ================================================ using System.Web; using System.Web.UI; using Composite.Data; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using System.Xml.Linq; using System.Collections.Generic; using Composite.Core.Xml; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Html.Template { internal sealed class MetaDescriptionValueFunction : StandardFunctionBase { public MetaDescriptionValueFunction(EntityTokenFactory entityTokenFactory) : base("MetaDescriptionValue", "Composite.Web.Html.Template", typeof(Control), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextAreaWidget; yield return new StandardFunctionParameterProfile("Element", typeof(XElement), false, new ConstantValueProvider(null), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { return new DescriptionControl(parameters.GetParameter<XElement>("Element")); } private class DescriptionControl : Control { private XElement _element = null; public DescriptionControl(XElement element) { _element = element; } protected override void Render(HtmlTextWriter writer) { string description = Page.Header.Description; if (string.IsNullOrWhiteSpace(description) && SiteMap.CurrentNode != null) { description = SiteMap.CurrentNode.Description; } if (string.IsNullOrWhiteSpace(description)) { using (DataConnection connection = new DataConnection()) { description = connection.SitemapNavigator.CurrentPageNode.Description; } } if (string.IsNullOrWhiteSpace(description)) return; if (_element != null) { _element.Add(description); string commonNs = string.Format(" xmlns=\"{0}\"", Namespaces.Xhtml ); string raw = _element.ToString().Replace(commonNs, ""); writer.Write(raw); } else { writer.WriteEncodedText(description); } } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Html/Template/PageTemplateFeatureFunction.cs ================================================ using System.Collections.Generic; using Composite.Core.WebClient.Renderings.Page; using Composite.Core.Xml; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.WebClient.Renderings.Template; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Html.Template { internal sealed class PageTemplateFeatureFunction : StandardFunctionBase { public PageTemplateFeatureFunction(EntityTokenFactory entityTokenFactory) : base("PageTemplateFeature", "Composite.Web.Html.Template", typeof(XhtmlDocument), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider featureNameSelector = StandardWidgetFunctions.DropDownList( this.GetType(), nameof(FeatureNames), false, true); yield return new StandardFunctionParameterProfile( "FeatureName", typeof(string), true, new NoValueValueProvider(), featureNameSelector); } } public static IEnumerable<string> FeatureNames() { return PageTemplateFeatureFacade.FeatureNames; } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (PageRenderer.RenderingReason == RenderingReason.BuildSearchIndex) { return null; } string featureName = parameters.GetParameter<string>("FeatureName"); return PageTemplateFeatureFacade.GetPageTemplateFeature(featureName); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Request/CookieValueFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Functions; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Request { internal sealed class CookieValueFunction : StandardFunctionBase { public CookieValueFunction(EntityTokenFactory entityTokenFactory) : base("CookieValue", "Composite.Web.Request", typeof(string), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "CookieName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "FallbackValue", typeof(string), false, new ConstantValueProvider(""), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { HttpCookie cookie = HttpContext.Current.Request.Cookies[parameters.GetParameter<string>("CookieName")]; if (cookie != null) { string result = HttpContext.Current.Request.Cookies[parameters.GetParameter<string>("CookieName")].Value; if (result != null) return result; } } return parameters.GetParameter<string>("FallbackValue"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Request/FormPostBoolValueFunction.cs ================================================ using System; using Composite.Functions; using System.Collections.Generic; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Request { internal sealed class FormPostBoolValueFunction : StandardFunctionBase { public FormPostBoolValueFunction(EntityTokenFactory entityTokenFactory) : base("FormPostBoolValue", "Composite.Web.Request", typeof(bool), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; WidgetFunctionProvider fallbackWidget = StandardWidgetFunctions.GetBoolSelectorWidget("True", "False"); yield return new StandardFunctionParameterProfile( "ParameterName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "FallbackValue", typeof(bool), false, new ConstantValueProvider(false), fallbackWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { string result = HttpContext.Current.Request.Form[parameters.GetParameter<string>("ParameterName")]; if (result != null) { switch (result.ToLowerInvariant()) { case "0": case "false": return false; case "1": case "true": return true; default: return bool.Parse(result); } } } return parameters.GetParameter<bool>("FallbackValue"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Request/FormPostDecimalValueFunction.cs ================================================ using System; using Composite.Functions; using System.Collections.Generic; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Request { internal sealed class FormPostDecimalValueFunction : StandardFunctionBase { public FormPostDecimalValueFunction(EntityTokenFactory entityTokenFactory) : base("FormPostDecimalValue", "Composite.Web.Request", typeof(decimal), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; WidgetFunctionProvider decimalTextboxWidget = StandardWidgetFunctions.DecimalTextBoxWidget; yield return new StandardFunctionParameterProfile( "ParameterName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "FallbackValue", typeof(decimal), false, new ConstantValueProvider((decimal)0), decimalTextboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { string result = HttpContext.Current.Request.Form[parameters.GetParameter<string>("ParameterName")]; if (result != null) return decimal.Parse(result); } return parameters.GetParameter<decimal>("FallbackValue"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Request/FormPostGuidValueFunction.cs ================================================ using System; using Composite.Functions; using System.Collections.Generic; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Request { internal sealed class FormPostGuidValueFunction : StandardFunctionBase { public FormPostGuidValueFunction(EntityTokenFactory entityTokenFactory) : base("FormPostGuidValue", "Composite.Web.Request", typeof(Guid), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "ParameterName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "FallbackValue", typeof(Guid), false, new ConstantValueProvider(Guid.Empty), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { string result = HttpContext.Current.Request.Form[parameters.GetParameter<string>("ParameterName")]; if (result != null) return new Guid(result); } return parameters.GetParameter<Guid>("FallbackValue"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Request/FormPostIntegerValueFunction.cs ================================================ using System; using Composite.Functions; using System.Collections.Generic; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Request { internal sealed class FormPostIntegerValueFunction : StandardFunctionBase { public FormPostIntegerValueFunction(EntityTokenFactory entityTokenFactory) : base("FormPostIntegerValue", "Composite.Web.Request", typeof(int), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; WidgetFunctionProvider integerTextboxWidget = StandardWidgetFunctions.IntegerTextBoxWidget; yield return new StandardFunctionParameterProfile( "ParameterName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "FallbackValue", typeof(int), false, new ConstantValueProvider(0), integerTextboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { string result = HttpContext.Current.Request.Form[parameters.GetParameter<string>("ParameterName")]; if (result != null) return Int32.Parse(result); } return parameters.GetParameter<int>("FallbackValue"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Request/FormPostValueFunction.cs ================================================ using System; using Composite.Functions; using System.Collections.Generic; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Request { internal sealed class FormPostValueFunction : StandardFunctionBase { public FormPostValueFunction(EntityTokenFactory entityTokenFactory) : base("FormPostValue", "Composite.Web.Request", typeof(string), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "ParameterName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "FallbackValue", typeof(string), false, new ConstantValueProvider(""), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { string result = HttpContext.Current.Request.Form[parameters.GetParameter<string>("ParameterName")]; if (result != null) return result; } return parameters.GetParameter<string>("FallbackValue"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Request/FormPostXmlFormattedDateTimeValueFunction.cs ================================================ using System; using Composite.Functions; using System.Collections.Generic; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; using Composite.Functions.Foundation; using System.Xml; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Request { internal sealed class FormPostXmlFormattedDateTimeValueFunction : StandardFunctionBase { public FormPostXmlFormattedDateTimeValueFunction(EntityTokenFactory entityTokenFactory) : base("FormPostXmlFormattedDateTimeValue", "Composite.Web.Request", typeof(DateTime), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; WidgetFunctionProvider fallbackWidget = StandardWidgetFunctions.DateTimeSelectorWidget; yield return new StandardFunctionParameterProfile( "ParameterName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "FallbackValue", typeof(DateTime), true, new NoValueValueProvider(), fallbackWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { string result = HttpContext.Current.Request.Form[parameters.GetParameter<string>("ParameterName")]; return XmlConvert.ToDateTime(result, XmlDateTimeSerializationMode.Local); } return parameters.GetParameter<DateTime>("FallbackValue"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Request/PathInfoFunction.cs ================================================ using System; using System.Collections.Generic; using Composite.Core.Extensions; using Composite.Core.Routing.Pages; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Request { internal sealed class PathInfoFunction : StandardFunctionBase { public PathInfoFunction(EntityTokenFactory entityTokenFactory) : base("PathInfo", "Composite.Web.Request", typeof(string), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider segmentDropDown = StandardWidgetFunctions.DropDownList( typeof(PathInfoFunction), "SegmentSelectorOptionsFull", "Key", "Value", false, true); yield return new StandardFunctionParameterProfile( "Segment", typeof(int), true, new ConstantValueProvider("-1"), segmentDropDown); yield return new StandardFunctionParameterProfile( "AutoApprove", typeof(bool), false, new ConstantValueProvider(true), StandardWidgetFunctions.CheckBoxWidget); yield return new StandardFunctionParameterProfile( "FallbackValue", typeof(string), false, new ConstantValueProvider(""), StandardWidgetFunctions.TextBoxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { int segment = (int)parameters.GetParameter("Segment"); bool autoApprove = (bool)parameters.GetParameter("AutoApprove"); string result = GetPathInfoSegment(segment); if (autoApprove && !result.IsNullOrEmpty()) { C1PageRoute.RegisterPathInfoUsage(); } return result ?? parameters.GetParameter<string>("FallbackValue"); } public static IEnumerable<KeyValuePair<int, string>> SegmentSelectorOptions() { return new[] { new KeyValuePair<int, string>(0, "0 "), // Additional space is intentional new KeyValuePair<int, string>(1, "1"), new KeyValuePair<int, string>(2, "2"), new KeyValuePair<int, string>(3, "3"), new KeyValuePair<int, string>(4, "4"), new KeyValuePair<int, string>(5, "5") }; } public static IEnumerable<KeyValuePair<int, string>> SegmentSelectorOptionsFull() { yield return new KeyValuePair<int, string>(-1, "-1"); foreach (var option in SegmentSelectorOptions()) { yield return option; } } internal static string GetPathInfoSegment(int segment) { string pathInfo = C1PageRoute.GetPathInfo(); if (segment == -1) { return pathInfo; } string[] segments = (pathInfo ?? string.Empty).Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (segments.Length > segment) { return segments[segment]; } return null; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Request/PathInfoGuidFunction.cs ================================================ using System; using System.Collections.Generic; using Composite.Functions; using Composite.Core.Routing.Pages; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Request { internal sealed class PathInfoGuidFunction : StandardFunctionBase { public PathInfoGuidFunction(EntityTokenFactory entityTokenFactory) : base("PathInfoGuid", "Composite.Web.Request", typeof(Guid), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider segmentDropDown = StandardWidgetFunctions.DropDownList( typeof(PathInfoFunction), "SegmentSelectorOptions", "Key", "Value", false, true); yield return new StandardFunctionParameterProfile( "Segment", typeof(int?), true, new ConstantValueProvider(0), segmentDropDown); yield return new StandardFunctionParameterProfile( "AutoApprove", typeof(bool), false, new ConstantValueProvider(true), StandardWidgetFunctions.CheckBoxWidget); yield return new StandardFunctionParameterProfile( "FallbackValue", typeof(Guid), false, new ConstantValueProvider(Guid.Empty), StandardWidgetFunctions.TextBoxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { int segment = (int)parameters.GetParameter("Segment"); bool autoApprove = (bool)parameters.GetParameter("AutoApprove"); string value = PathInfoFunction.GetPathInfoSegment(segment); Guid guidValue; if (string.IsNullOrEmpty(value) || !Guid.TryParse(value, out guidValue)) { return parameters.GetParameter<Guid>("FallbackValue"); } if (autoApprove) { C1PageRoute.RegisterPathInfoUsage(); } return guidValue; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Request/PathInfoIntFunction.cs ================================================ using System; using System.Collections.Generic; using Composite.Functions; using Composite.Core.Routing.Pages; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Request { internal sealed class PathInfoIntFunction : StandardFunctionBase { public PathInfoIntFunction(EntityTokenFactory entityTokenFactory) : base("PathInfoInt", "Composite.Web.Request", typeof(int), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider segmentDropDown = StandardWidgetFunctions.DropDownList( typeof(PathInfoFunction), "SegmentSelectorOptions", "Key", "Value", false, true); yield return new StandardFunctionParameterProfile( "Segment", typeof(int), true, new ConstantValueProvider(0), segmentDropDown); yield return new StandardFunctionParameterProfile( "AutoApprove", typeof(bool), false, new ConstantValueProvider(true), StandardWidgetFunctions.CheckBoxWidget); yield return new StandardFunctionParameterProfile( "FallbackValue", typeof(int), false, new ConstantValueProvider(0), StandardWidgetFunctions.IntegerTextBoxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { int segment = (int)parameters.GetParameter("Segment"); bool autoApprove = (bool)parameters.GetParameter("AutoApprove"); string value = PathInfoFunction.GetPathInfoSegment(segment); int intValue; if(string.IsNullOrEmpty(value) || !int.TryParse(value, out intValue)) { return parameters.GetParameter<int>("FallbackValue"); } if (autoApprove) { C1PageRoute.RegisterPathInfoUsage(); } return intValue; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Request/QueryStringBoolValueFunction.cs ================================================ using System; using Composite.Functions; using System.Collections.Generic; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Request { internal sealed class QueryStringBoolValueFunction : StandardFunctionBase { public QueryStringBoolValueFunction(EntityTokenFactory entityTokenFactory) : base("QueryStringBoolValue", "Composite.Web.Request", typeof(bool), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; WidgetFunctionProvider fallbackWidget = StandardWidgetFunctions.GetBoolSelectorWidget("True", "False"); yield return new StandardFunctionParameterProfile( "ParameterName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "FallbackValue", typeof(bool), false, new ConstantValueProvider(false), fallbackWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { string result = HttpContext.Current.Request.QueryString[parameters.GetParameter<string>("ParameterName")]; if (result != null) { switch (result.ToLowerInvariant()) { case "0": case "false": return false; case "1": case "true": return true; default: return bool.Parse(result); } } } return parameters.GetParameter<bool>("FallbackValue"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Request/QueryStringDecimalValueFunction.cs ================================================ using System; using Composite.Functions; using System.Collections.Generic; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Request { internal sealed class QueryStringDecimalValueFunction : StandardFunctionBase { public QueryStringDecimalValueFunction(EntityTokenFactory entityTokenFactory) : base("QueryStringDecimalValue", "Composite.Web.Request", typeof(decimal), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; WidgetFunctionProvider decimalTextboxWidget = StandardWidgetFunctions.DecimalTextBoxWidget; yield return new StandardFunctionParameterProfile( "ParameterName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "FallbackValue", typeof(decimal), false, new ConstantValueProvider((decimal)0), decimalTextboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { string result = HttpContext.Current.Request.QueryString[parameters.GetParameter<string>("ParameterName")]; if (result != null) return decimal.Parse(result); } return parameters.GetParameter<decimal>("FallbackValue"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Request/QueryStringGuidValueFunction.cs ================================================ using System; using Composite.Functions; using System.Collections.Generic; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Request { internal sealed class QueryStringGuidValueFunction : StandardFunctionBase { public QueryStringGuidValueFunction(EntityTokenFactory entityTokenFactory) : base("QueryStringGuidValue", "Composite.Web.Request", typeof(Guid), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "ParameterName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "FallbackValue", typeof(Guid), false, new ConstantValueProvider(Guid.Empty), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { string result = HttpContext.Current.Request.QueryString[parameters.GetParameter<string>("ParameterName")]; if (result != null) return new Guid(result); } return parameters.GetParameter<Guid>("FallbackValue"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Request/QueryStringIntegerValueFunction.cs ================================================ using System; using Composite.Functions; using System.Collections.Generic; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Request { internal sealed class QueryStringIntegerValueFunction : StandardFunctionBase { public QueryStringIntegerValueFunction(EntityTokenFactory entityTokenFactory) : base("QueryStringIntegerValue", "Composite.Web.Request", typeof(int), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; WidgetFunctionProvider integerTextboxWidget = StandardWidgetFunctions.IntegerTextBoxWidget; yield return new StandardFunctionParameterProfile( "ParameterName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "FallbackValue", typeof(int), false, new ConstantValueProvider(0), integerTextboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { string result = HttpContext.Current.Request.QueryString[parameters.GetParameter<string>("ParameterName")]; if (result != null) return Int32.Parse(result); } return parameters.GetParameter<int>("FallbackValue"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Request/QueryStringValueFunction.cs ================================================ using System; using Composite.Functions; using System.Collections.Generic; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Request { internal sealed class QueryStringValueFunction : StandardFunctionBase { public QueryStringValueFunction(EntityTokenFactory entityTokenFactory) : base("QueryStringValue", "Composite.Web.Request", typeof(string), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "ParameterName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "FallbackValue", typeof(string), false, new ConstantValueProvider(""), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { var httpContext = HttpContext.Current; if (httpContext != null && httpContext.Request != null) { string parameterName = parameters.GetParameter<string>("ParameterName"); string result = httpContext.Request.QueryString[parameterName]; if (result != null) return result; } return parameters.GetParameter<string>("FallbackValue"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Request/QueryStringXmlFormattedDateTimeValueFunction.cs ================================================ using System; using Composite.Functions; using System.Collections.Generic; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using System.Xml; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Request { internal sealed class QueryStringXmlFormattedDateTimeValueFunction : StandardFunctionBase { public QueryStringXmlFormattedDateTimeValueFunction(EntityTokenFactory entityTokenFactory) : base("QueryStringXmlFormattedDateTimeValue", "Composite.Web.Request", typeof(DateTime), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; WidgetFunctionProvider fallbackWidget = StandardWidgetFunctions.DateTimeSelectorWidget; yield return new StandardFunctionParameterProfile( "ParameterName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "FallbackValue", typeof(DateTime), true, new NoValueValueProvider(), fallbackWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { var httpContext = HttpContext.Current; if (httpContext != null && httpContext.Request != null) { string result = httpContext.Request.QueryString[parameters.GetParameter<string>("ParameterName")]; if(!string.IsNullOrEmpty(result)) { return XmlConvert.ToDateTime(result, XmlDateTimeSerializationMode.Local); } } return parameters.GetParameter<DateTime>("FallbackValue"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Request/RegisterPathInfoUsageFunction.cs ================================================ using System; using System.Collections.Generic; using Composite.Functions; using Composite.Core.Routing.Pages; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Request { internal sealed class RegisterPathInfoUsageFunction : StandardFunctionBase { public RegisterPathInfoUsageFunction(EntityTokenFactory entityTokenFactory) : base("RegisterPathInfoUsage", "Composite.Web.Request", typeof(void), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield break; } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { C1PageRoute.RegisterPathInfoUsage(); return null; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Request/SessionVariableFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Functions; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Request { internal sealed class SessionVariableFunction : StandardFunctionBase { public SessionVariableFunction(EntityTokenFactory entityTokenFactory) : base("SessionVariable", "Composite.Web.Request", typeof(string), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "VariableName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "FallbackValue", typeof(string), false, new ConstantValueProvider(""), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { object result = HttpContext.Current.Session[parameters.GetParameter<string>("VariableName")]; if (result != null) return result.ToString(); } return parameters.GetParameter<string>("FallbackValue"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Response/RedirectFunction.cs ================================================ using System; using System.Collections.Generic; using System.Web; using Composite.Core.WebClient; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Response { internal sealed class RedirectFunction : StandardFunctionBase { public RedirectFunction(EntityTokenFactory entityTokenFactory) : base("Redirect", "Composite.Web.Response", typeof(void), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { var urlComboBoxWidget = StandardWidgetFunctions.UrlComboBoxWidget; yield return new StandardFunctionParameterProfile( "Url", typeof(string), true, new NoValueValueProvider(), urlComboBoxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { var httpContext = HttpContext.Current; if (httpContext == null) { return null; } string url = parameters.GetParameter<string>("Url"); if (!UrlUtils.IsAdminConsoleRequest(httpContext)) { httpContext.Response.Redirect(url, false); } return null; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Response/SetCookieValueFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Functions; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Response { internal sealed class SetCookieValueFunction : StandardFunctionBase { public SetCookieValueFunction(EntityTokenFactory entityTokenFactory) : base("SetCookieValue", "Composite.Web.Response", typeof(string), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "CookieName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "Value", typeof(string), true, new ConstantValueProvider(""), textboxWidget); yield return new StandardFunctionParameterProfile( "Expires", typeof(DateTime), false, new ConstantValueProvider(DateTime.MinValue), null); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { string cookieName = parameters.GetParameter<string>("CookieName"); string value = parameters.GetParameter<string>("Value"); DateTime expires = parameters.GetParameter<DateTime>("Expires"); HttpContext.Current.Response.Cookies[cookieName].Value = value; HttpContext.Current.Response.Cookies[cookieName].Expires = expires; // DateTime.MinValue = session cookie } return null; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Response/SetServerPageCacheDuration.cs ================================================ using System; using System.Collections.Generic; using System.Web; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Response { internal sealed class SetServerPageCacheDuration : StandardFunctionBase { private const string ParameterName_MaxSeconds = "MaxSeconds"; public SetServerPageCacheDuration(EntityTokenFactory entityTokenFactory) : base("SetServerPageCacheDuration", "Composite.Web.Response", typeof(void), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { yield return new StandardFunctionParameterProfile( ParameterName_MaxSeconds, typeof(int), true, new ConstantValueProvider(0), StandardWidgetFunctions.TextBoxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { var httpContext = HttpContext.Current; if (httpContext?.Response == null) return null; var cache = httpContext.Response.Cache; int maxSeconds = parameters.GetParameter<int>(ParameterName_MaxSeconds); if (maxSeconds <= 0) { cache.SetCacheability(HttpCacheability.NoCache); cache.SetNoServerCaching(); cache.SetNoStore(); } else { cache.SetExpires(DateTime.Now.AddSeconds(maxSeconds)); cache.SetMaxAge(TimeSpan.FromSeconds(maxSeconds)); } return null; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Response/SetSessionVariableFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Functions; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Response { internal sealed class SetSessionVariableFunction : StandardFunctionBase { public SetSessionVariableFunction(EntityTokenFactory entityTokenFactory) : base("SetSessionVariable", "Composite.Web.Response", typeof(string), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "VariableName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "Value", typeof(string), true, new ConstantValueProvider(""), textboxWidget ); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { HttpContext.Current.Session[parameters.GetParameter<string>("VariableName")] = parameters.GetParameter<string>("Value"); } return null; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Server/ApplicationPath.cs ================================================ using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using System.Web; using System; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Server { internal sealed class ApplicationPath : StandardFunctionBase { public ApplicationPath(EntityTokenFactory entityTokenFactory) : base("ApplicationPath", "Composite.Web.Server", typeof(string), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { var httpContext = HttpContext.Current; if (httpContext == null || httpContext.Request == null) { throw new InvalidOperationException("Unable to access 'HttpContext.Current.Request' - object is null"); } string appPath = httpContext.Request.ApplicationPath; if (appPath.EndsWith("/")) { appPath = appPath.Substring(0, appPath.Length - 1); } return appPath; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Server/ApplicationVariableFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Functions; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Server { internal sealed class ApplicationVariableFunction : StandardFunctionBase { public ApplicationVariableFunction(EntityTokenFactory entityTokenFactory) : base("ApplicationVariable", "Composite.Web.Server", typeof(string), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "VariableName", typeof(string), true, new NoValueValueProvider(), textboxWidget); yield return new StandardFunctionParameterProfile( "FallbackValue", typeof(string), false, new ConstantValueProvider(""), textboxWidget); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { string result = HttpContext.Current.Application[parameters.GetParameter<string>("VariableName")].ToString(); if (result != null) return result; } return parameters.GetParameter<string>("FallbackValue"); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Web/Server/ServerVariableFunction.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.Functions; using System.Web; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Web.Server { internal sealed class ServerVariableFunction : StandardFunctionBase { public ServerVariableFunction(EntityTokenFactory entityTokenFactory) : base("ServerVariable", "Composite.Web.Server", typeof(string), entityTokenFactory) { } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider serverVariableNameSelector = StandardWidgetFunctions.DropDownList( this.GetType(), "ServerVariableNames", false, true); yield return new StandardFunctionParameterProfile( "VariableName", typeof(string), true, new ConstantValueProvider("PATH_INFO"), serverVariableNameSelector); } } public override object Execute(ParameterList parameters, FunctionContextContainer context) { if (HttpContext.Current != null && HttpContext.Current.Request != null) { return HttpContext.Current.Request.ServerVariables[parameters.GetParameter<string>("VariableName")]; } return null; } public static IEnumerable<string> ServerVariableNames() { yield return "ALL_HTTP"; yield return "ALL_RAW"; yield return "APPL_MD_PATH"; yield return "APPL_PHYSICAL_PATH"; yield return "AUTH_PASSWORD"; yield return "AUTH_TYPE"; yield return "AUTH_USER"; yield return "CERT_COOKIE"; yield return "CERT_FLAGS"; yield return "CERT_ISSUER"; yield return "CERT_KEYSIZE"; yield return "CERT_SECRETKEYSIZE"; yield return "CERT_SERIALNUMBER"; yield return "CERT_SERVER_ISSUER"; yield return "CERT_SERVER_SUBJECT"; yield return "CERT_SUBJECT"; yield return "CONTENT_LENGTH"; yield return "CONTENT_TYPE"; yield return "GATEWAY_INTERFACE"; yield return "HTTP_ACCEPT"; yield return "HTTP_ACCEPT_LANGUAGE"; yield return "HTTP_COOKIE"; yield return "HTTP_HOST"; yield return "HTTP_REFERER"; yield return "HTTP_USER_AGENT"; yield return "HTTPS"; yield return "HTTPS_KEYSIZE"; yield return "HTTPS_SECRETKEYSIZE"; yield return "HTTPS_SERVER_ISSUER"; yield return "HTTPS_SERVER_SUBJECT"; yield return "INSTANCE_ID"; yield return "INSTANCE_META_PATH"; yield return "LOCAL_ADDR"; yield return "LOGON_USER"; yield return "PATH_INFO"; yield return "PATH_TRANSLATED"; yield return "QUERY_STRING"; yield return "REMOTE_ADDR"; yield return "REMOTE_HOST"; yield return "REMOTE_USER"; yield return "REQUEST_METHOD"; yield return "SCRIPT_NAME"; yield return "SERVER_NAME"; yield return "SERVER_PORT"; yield return "SERVER_PORT_SECURE"; yield return "SERVER_PROTOCOL"; yield return "SERVER_SOFTWARE"; yield return "URL"; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Xml/LoadFileFunction.cs ================================================ using System.Collections.Generic; using System.Xml; using System.Xml.Linq; using Composite.Core.IO; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using System.IO; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Xml { internal sealed class LoadFileFunction : StandardFunctionBase { public LoadFileFunction(EntityTokenFactory entityTokenFactory) : base("LoadFile", "Composite.Xml", typeof(XElement), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { string relativePath = parameters.GetParameter<string>("RelativePath"); string path = Path.Combine(PathUtil.Resolve("~"), relativePath); if (!C1File.Exists(path)) { throw new FileNotFoundException("File not found. Ensure path is relative (that it does not start with '/').", path); } using (var streamReader = new C1StreamReader(path)) { using (var reader = XmlReader.Create(streamReader)) { return XElement.Load(reader); } } } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "RelativePath", typeof(string), true, new NoValueValueProvider(), textboxWidget); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Xml/LoadUrlFunction.cs ================================================ using System; using System.Collections.Generic; using System.Web; using System.Web.Caching; using System.Xml.Linq; using Composite.Core.Instrumentation; using Composite.Core.Xml; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Xml { internal sealed class LoadUrlFunction : StandardFunctionBase { public LoadUrlFunction(EntityTokenFactory entityTokenFactory) : base("LoadUrl", "Composite.Xml", typeof(XElement), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { string url = parameters.GetParameter<string>("Url"); bool cachingEnabled = false; int cachePeriod; if (parameters.TryGetParameter("CacheTime", out cachePeriod)) { cachingEnabled = cachePeriod > 0; } string cacheKey = null; if (cachingEnabled) { cacheKey = typeof(LoadUrlFunction).FullName + "|" + url; var cachedValue = HttpRuntime.Cache.Get(cacheKey) as XElement; if (cachedValue != null) { return cachedValue; } } using (TimerProfilerFacade.CreateTimerProfiler(url)) { XElement value = XElementUtils.Load(url); if (cachingEnabled) { HttpRuntime.Cache.Add(cacheKey, value, null, DateTime.Now.AddSeconds(cachePeriod), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); } return value; } } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "Url", typeof(string), true, new NoValueValueProvider(),textboxWidget); yield return new StandardFunctionParameterProfile( "CacheTime", typeof(int), false, new ConstantValueProvider(0), textboxWidget); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Xml/LoadXhtmlFileFunction.cs ================================================ using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Linq; using Composite.Core.IO; using Composite.Core.Xml; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Xml { internal sealed class LoadXhtmlFileFunction : StandardFunctionBase { public LoadXhtmlFileFunction(EntityTokenFactory entityTokenFactory) : base("LoadXhtmlFile", "Composite.Xml", typeof(XhtmlDocument), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { string relativePath = parameters.GetParameter<string>("RelativePath"); string path = Path.Combine(PathUtil.Resolve("~"), relativePath); if (!C1File.Exists(path)) { throw new FileNotFoundException("File not found. Ensure path is relative (that it does not start with '/').", path); } using (var streamReader = new C1StreamReader(path)) { using (var reader = XmlReader.Create(streamReader)) { return new XhtmlDocument(XDocument.Load(reader)); } } } protected override IEnumerable<StandardFunctionParameterProfile> StandardFunctionParameterProfiles { get { WidgetFunctionProvider textboxWidget = StandardWidgetFunctions.TextBoxWidget; yield return new StandardFunctionParameterProfile( "RelativePath", typeof(string), true, new NoValueValueProvider(), textboxWidget); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Xslt/Extensions/DateFormattingXsltExtensionsFunction.cs ================================================ using System; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.Xml; using System.Xml; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Xslt.Extensions { internal sealed class DateFormattingXsltExtensionsFunction : StandardFunctionBase { public DateFormattingXsltExtensionsFunction(EntityTokenFactory entityTokenFactory) : base("DateFormatting", "Composite.Xslt.Extensions", typeof(IXsltExtensionDefinition), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { return new XsltExtensionDefinition<DateFormattingXsltExtensions> { EntensionObject = new DateFormattingXsltExtensions(), ExtensionNamespace = "#dateExtensions" }; } internal class DateFormattingXsltExtensions { public string Now() { return XmlConvert.ToString(DateTime.Now, XmlDateTimeSerializationMode.Local); } public string LongDateFormat(string xmlFormattedDate) { DateTime date = XmlConvert.ToDateTime(xmlFormattedDate, XmlDateTimeSerializationMode.Local); return date.ToLongDateString(); } public string LongTimeFormat(string xmlFormattedDate) { DateTime date = XmlConvert.ToDateTime(xmlFormattedDate, XmlDateTimeSerializationMode.Local); return date.ToLongTimeString(); } public string ShortDateFormat(string xmlFormattedDate) { DateTime date = XmlConvert.ToDateTime(xmlFormattedDate, XmlDateTimeSerializationMode.Local); return date.ToShortDateString(); } public string ShortTimeFormat(string xmlFormattedDate) { DateTime date = XmlConvert.ToDateTime(xmlFormattedDate, XmlDateTimeSerializationMode.Local); return date.ToShortTimeString(); } public int Day(string xmlFormattedDate) { DateTime date = XmlConvert.ToDateTime(xmlFormattedDate, XmlDateTimeSerializationMode.Local); return date.Day; } public int Month(string xmlFormattedDate) { DateTime date = XmlConvert.ToDateTime(xmlFormattedDate, XmlDateTimeSerializationMode.Local); return date.Month; } public int Year(string xmlFormattedDate) { DateTime date = XmlConvert.ToDateTime(xmlFormattedDate, XmlDateTimeSerializationMode.Local); return date.Year; } public string LongMonthName(int monthNumber) { if (monthNumber < 1 || monthNumber > 12) throw new ArgumentOutOfRangeException("monthNumber"); DateTime date = new DateTime(1, monthNumber, 1); return date.ToString("MMMM"); } public string ShortMonthName(int monthNumber) { if (monthNumber < 1 || monthNumber > 12) throw new ArgumentOutOfRangeException("monthNumber"); DateTime date = new DateTime(1, monthNumber, 1); return date.ToString("MMM"); } public string Format(string xmlFormattedDate, string DateFormat) { DateTime date = XmlConvert.ToDateTime(xmlFormattedDate, XmlDateTimeSerializationMode.Local); return date.ToString(DateFormat); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Xslt/Extensions/GlobalizationXsltExtensionsFunction.cs ================================================ using System; using Composite.Functions; using System.Collections.Generic; using System.Data.SqlTypes; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; using Composite.Core.Xml; using System.Xml.Linq; using System.Xml; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Xslt.Extensions { internal sealed class GlobalizationXsltExtensionsFunction : StandardFunctionBase { public GlobalizationXsltExtensionsFunction(EntityTokenFactory entityTokenFactory) : base("Globalization", "Composite.Xslt.Extensions", typeof(IXsltExtensionDefinition), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { return new XsltExtensionDefinition<GlobalizationXsltExtensions> { EntensionObject = new GlobalizationXsltExtensions(), ExtensionNamespace = "#globalizationExtensions" }; } internal class GlobalizationXsltExtensions { public string GetGlobalResourceString(string resourceClassKey, string resourceKey) { return System.Web.HttpContext.GetGlobalResourceObject(resourceClassKey, resourceKey).ToString(); } public string LongMonthName(int monthNumber) { if (monthNumber < 1 || monthNumber > 12) throw new ArgumentOutOfRangeException("monthNumber"); DateTime date = new DateTime(1, monthNumber, 1); return date.ToString("MMMM"); } public string ShortMonthName(int monthNumber) { if (monthNumber < 1 || monthNumber > 12) throw new ArgumentOutOfRangeException("monthNumber"); DateTime date = new DateTime(1, monthNumber, 1); return date.ToString("MMM"); } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/StandardFunctionProvider/Xslt/Extensions/MarkupParserXsltExtensionsFunction.cs ================================================ using System.IO; using System.Xml.XPath; using Composite.Core.Xml; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Foundation; namespace Composite.Plugins.Functions.FunctionProviders.StandardFunctionProvider.Xslt.Extensions { internal sealed class MarkupParserXsltExtensionsFunction : StandardFunctionBase { public MarkupParserXsltExtensionsFunction(EntityTokenFactory entityTokenFactory) : base("MarkupParser", "Composite.Xslt.Extensions", typeof(IXsltExtensionDefinition), entityTokenFactory) { } public override object Execute(ParameterList parameters, FunctionContextContainer context) { return new XsltExtensionDefinition<MarkupParserXsltExtensions> { EntensionObject = new MarkupParserXsltExtensions(), ExtensionNamespace = "#MarkupParserExtensions" }; } internal class MarkupParserXsltExtensions { public XPathNavigator ParseWellformedDocumentMarkup(string wellformedMarkupString) { using (StringReader sr = new StringReader(wellformedMarkupString)) { XPathDocument doc = new XPathDocument(sr); return doc.CreateNavigator(); } } public XPathNavigator ParseXhtmlBodyFragment(string xhtmlBodyFragmentString) { using (StringReader sr = new StringReader(string.Format("<html xmlns='{0}'><head /><body>{1}</body></html>", Namespaces.Xhtml, xhtmlBodyFragmentString))) { XPathDocument doc = new XPathDocument(sr); return doc.CreateNavigator(); } } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/UserControlFunctionProvider/UserControlBasedFunction.cs ================================================ using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using Composite.AspNet; using Composite.Core.IO; using Composite.Plugins.Functions.FunctionProviders.FileBasedFunctionProvider; namespace Composite.Plugins.Functions.FunctionProviders.UserControlFunctionProvider { internal class UserControlBasedFunction : FileBasedFunction<UserControlBasedFunction> { public UserControlBasedFunction( string @namespace, string name, string description, IDictionary<string, FunctionParameter> parameters, Type returnType, string virtualPath, FileBasedFunctionProvider<UserControlBasedFunction> provider) : base(@namespace, name, description, parameters, returnType, virtualPath, provider) { } public UserControlBasedFunction( string @namespace, string name, string description, string virtualPath, FileBasedFunctionProvider<UserControlBasedFunction> provider) : base(@namespace, name, description, typeof(UserControl), virtualPath, provider) { } protected override void InitializeParameters() { UserControl userControl = UserControlFunctionProvider.CompileFile(VirtualPath); Verify.IsNotNull(userControl, "Failed to get UserControl from '{0}'", VirtualPath); Type baseControlType = userControl is UserControlFunction ? typeof(UserControlFunction) : typeof(UserControl); Parameters = FunctionBasedFunctionProviderHelper.GetParameters(userControl, baseControlType, PathUtil.Resolve(VirtualPath)); } public override object Execute(Composite.Functions.ParameterList parameters, Composite.Functions.FunctionContextContainer context) { var httpContext = HttpContext.Current; Verify.IsNotNull(httpContext, "HttpContext.Current is null"); Page currentPage = httpContext.Handler as Page; Verify.IsNotNull(currentPage, "The Current HttpContext Handler must be a " + typeof (Page).FullName); var userControl = currentPage.LoadControl(VirtualPath); foreach (var param in parameters.AllParameterNames) { var value = parameters.GetParameter(param); Parameters[param].SetValue(userControl, value); } var userControlFunction = userControl as UserControlFunction; if (userControlFunction != null) { userControlFunction.FunctionContextContainer = context; } return userControl; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/UserControlFunctionProvider/UserControlFunctionProvider.cs ================================================ using System; using System.Web.UI; using Composite.AspNet; using Composite.Core.WebClient; using Composite.Functions; using Composite.Plugins.Functions.FunctionProviders.FileBasedFunctionProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Functions.FunctionProviders.UserControlFunctionProvider { [ConfigurationElementType(typeof(UserControlFunctionProviderData))] internal class UserControlFunctionProvider : FileBasedFunctionProvider.FileBasedFunctionProvider<UserControlBasedFunction> { public UserControlFunctionProvider(string name, string folder) : base(name, folder) { } protected override string FileExtension { get { return "ascx"; } } protected override string DefaultFunctionNamespace { get { return "UserControls"; } } protected override bool HandleChange(string path) { return path.EndsWith(".ascx") || path.EndsWith(".ascx.cs"); } public static UserControl CompileFile(string virtualPath) { var page = new Page(); using(BuildManagerHelper.DisableUrlMetadataCachingScope()) { return page.LoadControl(virtualPath) as UserControl; } } protected override IFunction InstantiateFunction(string virtualPath, string @namespace, string name) { UserControl userControl = CompileFile(virtualPath); if(!(userControl is UserControl)) { return null; } Type baseControlType = userControl is UserControlFunction ? typeof(UserControlFunction) : typeof(UserControl); string description = userControl is UserControlFunction ? (userControl as UserControlFunction).FunctionDescription : ""; var parameters = FunctionBasedFunctionProviderHelper.GetParameters(userControl, baseControlType, virtualPath); return new UserControlBasedFunction(@namespace, name, description, parameters, typeof(UserControl), virtualPath, this); } protected override IFunction InstantiateFunctionFromCache(string virtualPath, string @namespace, string name, Type returnType, string cachedDescription, bool preventCaching) { return new UserControlBasedFunction(@namespace, name, cachedDescription, virtualPath, this); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/UserControlFunctionProvider/UserControlFunctionProviderAssembler.cs ================================================ using Composite.Functions.Plugins.FunctionProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Functions.FunctionProviders.UserControlFunctionProvider { internal class UserControlFunctionProviderAssembler : IAssembler<IFunctionProvider, FunctionProviderData> { IFunctionProvider IAssembler<IFunctionProvider, FunctionProviderData>.Assemble(IBuilderContext context, FunctionProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { var data = objectConfiguration as UserControlFunctionProviderData; Verify.ArgumentCondition(data != null, "objectConfiguration", "Expected configuration to be of type " + typeof(UserControlFunctionProviderData).Name); return new UserControlFunctionProvider(data.Name, data.Directory); } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/UserControlFunctionProvider/UserControlFunctionProviderData.cs ================================================ using System.Configuration; using Composite.Functions.Plugins.FunctionProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.Functions.FunctionProviders.UserControlFunctionProvider { [Assembler(typeof(UserControlFunctionProviderAssembler))] internal class UserControlFunctionProviderData : FunctionProviderData { [ConfigurationProperty("directory", IsRequired = false, DefaultValue = "~/App_Data/UserControls")] public string Directory { get { return (string)base["directory"]; } set { base["directory"] = value; } } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/VisualFunctionProvider/RenderingHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Xml.Linq; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.Types; using Composite.Functions; using Composite.Core.WebClient.Renderings.Page; using Composite.Core.Types; using Composite.Core.WebClient.Renderings.Data; using Composite.Core.Xml; using System.Web; namespace Composite.Plugins.Functions.FunctionProviders.VisualFunctionProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class RenderingHelper { /// <exclude /> public static XhtmlDocument RenderCompleteDataList(IVisualFunction function, XhtmlDocument xhtmlDocument, DataTypeDescriptor typeDescriptor, FunctionContextContainer functionContextContainer) { Type typeofClassWithGenericStaticMethod = typeof(RenderingHelper); // Grabbing the specific static method MethodInfo methodInfo = typeofClassWithGenericStaticMethod.GetMethod("RenderCompleteDataListImpl", System.Reflection.BindingFlags.Static | BindingFlags.NonPublic); // Binding the method info to generic arguments Type[] genericArguments = new Type[] { typeDescriptor.GetInterfaceType() }; MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(genericArguments); // Simply invoking the method and passing parameters // The null parameter is the object to call the method from. Since the method is // static, pass null. return (XhtmlDocument)genericMethodInfo.Invoke(null, new object[] { function, xhtmlDocument, typeDescriptor, functionContextContainer }); } private static XhtmlDocument RenderCompleteDataListImpl<T>(IVisualFunction function, XhtmlDocument xhtmlDocument, DataTypeDescriptor typeDescriptor, FunctionContextContainer functionContextContainer) where T : class, IData { Expression<Func<T, bool>> filter = f => true; return RenderDataList<T>(function, xhtmlDocument, typeDescriptor, functionContextContainer, filter); } /// <exclude /> public static XhtmlDocument RenderDataList<T>(IVisualFunction function, XhtmlDocument xhtmlDocument, DataTypeDescriptor typeDescriptor, FunctionContextContainer functionContextContainer, Expression<Func<T, bool>> filter) where T : class, IData { if (function == null) throw new ArgumentNullException("function"); if (xhtmlDocument == null) throw new ArgumentNullException("xhtmlDocument"); if (typeDescriptor == null) throw new ArgumentNullException("typeDescriptor"); if (functionContextContainer == null) throw new ArgumentNullException("functionContextContainer"); Type dataType = typeDescriptor.GetInterfaceType(); if (dataType == null) { throw new InvalidOperationException(string.Format("'{0}' is not a known type manager type.", typeDescriptor.TypeManagerTypeName)); } List<T> allData = DataFacade.GetData<T>(filter).ToList(); List<T> itemsToList; if (function.OrderbyFieldName == "(random)") { int itemsInList = allData.Count(); int itemsToFetch = Math.Min(itemsInList, function.MaximumItemsToList); itemsToList = new List<T>(); while (itemsToFetch > 0) { int itemToGet = (Math.Abs(Guid.NewGuid().GetHashCode()) % itemsInList); // (new Random()).Next(0, itemsInList); itemsToList.Add(allData[itemToGet]); allData.RemoveAt(itemToGet); itemsToFetch--; itemsInList--; } } else { IComparer<T> comparer = GenericComparer<T>.Build(typeDescriptor.GetInterfaceType(), function.OrderbyFieldName, function.OrderbyAscending); allData.Sort(comparer); itemsToList = allData.Take(function.MaximumItemsToList).ToList(); } return RenderDataListImpl<T>(xhtmlDocument, typeDescriptor, itemsToList, functionContextContainer); } private static XhtmlDocument RenderDataListImpl<T>(XhtmlDocument templateDocument, DataTypeDescriptor typeDescriptor, List<T> dataList, FunctionContextContainer functionContextContainer) where T : class, IData { XhtmlDocument outputDocument = new XhtmlDocument(); if (dataList.Count > 0) { Type interfaceType = typeDescriptor.GetInterfaceType(); XElement templateBody = new XElement(templateDocument.Body); Dictionary<string, PropertyInfo> propertyInfoLookup = interfaceType.GetPropertiesRecursively(p => typeof(IData).IsAssignableFrom(p.DeclaringType)).ToList().ToDictionary(p => p.Name); List<string> fieldsWithReferenceRendering = new List<string>(); foreach (PropertyInfo dataPropertyInfo in propertyInfoLookup.Values) { Type referencedType = null; if (dataPropertyInfo.TryGetReferenceType(out referencedType)) { bool canRender = DataXhtmlRenderingServices.CanRender(referencedType, XhtmlRenderingType.Embedable); if (canRender) { fieldsWithReferenceRendering.Add(dataPropertyInfo.Name); } } } // any optimization would do wonders foreach (IData data in dataList) { XElement currentRowElementsContainer = new XElement(templateBody); List<DynamicTypeMarkupServices.FieldReferenceDefinition> references = DynamicTypeMarkupServices.GetFieldReferenceDefinitions(currentRowElementsContainer, typeDescriptor.TypeManagerTypeName).ToList(); // perf waste - if some props are not used; Dictionary<string, object> objectValues = propertyInfoLookup.ToDictionary(f => f.Key, f => f.Value.GetValue(data, new object[] { })); foreach (DynamicTypeMarkupServices.FieldReferenceDefinition reference in references) { object value = null; if (fieldsWithReferenceRendering.Contains(reference.FieldName)) { // reference field with rendering... Type referencedType = null; if (propertyInfoLookup[reference.FieldName].TryGetReferenceType(out referencedType)) { if (objectValues[reference.FieldName] != null) { IDataReference dataReference = DataReferenceFacade.BuildDataReference(referencedType, objectValues[reference.FieldName]); try { value = DataXhtmlRenderingServices.Render(dataReference, XhtmlRenderingType.Embedable).Root; } catch (Exception) { value = objectValues[reference.FieldName]; } } } } else { if (objectValues.ContainsKey(reference.FieldName)) // prevents unknown props from creating exceptions { value = objectValues[reference.FieldName]; } } if (value!=null) { if (value.GetType() == typeof(DateTime)) { DateTime dateTimeValue = (DateTime)value; if (dateTimeValue.TimeOfDay.TotalSeconds > 0) { value = string.Format("{0} {1}", dateTimeValue.ToShortDateString(), dateTimeValue.ToShortDateString()); } else { value = dateTimeValue.ToShortDateString(); } } if (value.GetType() == typeof(string)) { string stringValue = (string)value; if (stringValue.StartsWith("<html") && stringValue.Contains(Namespaces.Xhtml.NamespaceName)) { try { value = XElement.Parse(stringValue); } catch { } } else if (stringValue.Contains('\n')) { string valueEncodedWithBr = HttpUtility.HtmlEncode(stringValue).Replace("\n", "<br/>"); value = XElement.Parse(string.Format("<body xmlns='{0}'>{1}</body>", Namespaces.Xhtml, valueEncodedWithBr)).Nodes(); } } } reference.FieldReferenceElement.ReplaceWith(value); } FunctionContextContainer fcc = new FunctionContextContainer(functionContextContainer, objectValues); PageRenderer.ExecuteEmbeddedFunctions(currentRowElementsContainer, fcc); outputDocument.Body.Add(currentRowElementsContainer.Elements()); } } return outputDocument; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/VisualFunctionProvider/VisualFunctionProvider.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.Types; using Composite.Functions; using Composite.Functions.Plugins.FunctionProvider; using Composite.Core.Logging; using Composite.C1Console.Security; using Composite.Core.Types; using Composite.Core.Xml; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.Functions.FunctionProviders.VisualFunctionProvider { [ConfigurationElementType(typeof(VisualFunctionProviderData))] internal sealed class VisualFunctionProvider : IDynamicTypeFunctionProvider { private FunctionNotifier _functionNotifier; public VisualFunctionProvider() { DataEventSystemFacade.SubscribeToStoreChanged<IVisualFunction>(OnDataChanged, false); } public FunctionNotifier FunctionNotifier { set { _functionNotifier = value; } } public IEnumerable<IFunction> Functions { get { yield break; } } public IEnumerable<IFunction> DynamicTypeDependentFunctions { get { List<IVisualFunction> functions = DataFacade.GetData<IVisualFunction>().ToList(); var functionInfos = (from function in functions select new { DataType = TypeManager.TryGetType( function.TypeManagerName ), Function = function }).ToList(); foreach( var missingTypeFunctionInfo in functionInfos.Where( f=>f.DataType==null)) { LoggingService.LogError(this.GetType().Name, string.Format("The function '{0}' in namespace '{1}' is dependant on an unknown type '{2}'. Function not loaded.", missingTypeFunctionInfo.Function.Namespace, missingTypeFunctionInfo.Function.Name, missingTypeFunctionInfo.Function.TypeManagerName)); } return from fi in functionInfos where fi.DataType != null select (IFunction)Activator.CreateInstance(typeof(VisualFunction<>).MakeGenericType(fi.DataType), new object[] { fi.Function }); } } private void OnDataChanged(object sender, StoreEventArgs storeEventArgs) { _functionNotifier.FunctionsUpdated(); } private sealed class VisualFunction<T> : IFunction where T : class, IData { private IVisualFunction _visualFunction; private XhtmlDocument _templateDocument = null; private DataTypeDescriptor _typeDescriptor = null; private object _lock = new object(); public VisualFunction(IVisualFunction visualFunction) { _visualFunction = visualFunction; } public object Execute(ParameterList parameters, FunctionContextContainer context) { Initialize(); int maximumItemsToList = parameters.GetParameter<int>("MaximumItemsToList"); string orderbyFieldName = parameters.GetParameter<string>("OrderbyFieldName"); bool orderbyAscending = parameters.GetParameter<bool>("OrderbyAscending"); Expression<Func<T, bool>> filter; if (parameters.TryGetParameter<Expression<Func<T, bool>>>("Filter", out filter) == false) { filter = f => true; } var runtimeFunction = new RuntimeVisualFunction(_visualFunction, maximumItemsToList, orderbyFieldName, orderbyAscending); return RenderingHelper.RenderDataList<T>(runtimeFunction, _templateDocument, _typeDescriptor, context, filter); } private void Initialize() { if (_templateDocument == null) { lock (_lock) { if (_templateDocument == null) { Type interfaceType = TypeManager.GetType(_visualFunction.TypeManagerName); _typeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(interfaceType); if (_typeDescriptor == null) throw new InvalidOperationException(string.Format("DataTypeDescriptor not found for type '{0}'", interfaceType)); _templateDocument = XhtmlDocument.Parse(_visualFunction.XhtmlTemplate); } } } } public string Name { get { return _visualFunction.Name; } } public string Namespace { get { return _visualFunction.Namespace; } } public string Description { get { return _visualFunction.Description; } } public Type ReturnType { get { return typeof(XhtmlDocument); } } public IEnumerable<ParameterProfile> ParameterProfiles { get { Initialize(); //if (_typeDescriptor.DataAssociations.Where(f => f.AssociatedInterfaceType == typeof(IPage) && f.AssociationType == DataAssociationType.Aggregation).Any()) //{ Expression<Func<T, bool>> defaultFilter = f => true; yield return new ParameterProfile( "Filter", typeof(Expression<Func<T, bool>>), false, new ConstantValueProvider(defaultFilter), null, "List Filter", new HelpDefinition("The selection filter applied to the data to be shown. The default is no filtering.")); //} WidgetFunctionProvider fieldsDropDown = StandardWidgetFunctions.DropDownList( this.GetType(), "OrderByFieldNames", _visualFunction.TypeManagerName, false, true, true); yield return new ParameterProfile("MaximumItemsToList", typeof(int), false, new ConstantValueProvider(_visualFunction.MaximumItemsToList), StandardWidgetFunctions.IntegerTextBoxWidget, "Item list length", new HelpDefinition("The maximum number of items to show. Default value is " + _visualFunction.MaximumItemsToList.ToString())); yield return new ParameterProfile("OrderbyFieldName", typeof(string), false, new ConstantValueProvider(_visualFunction.OrderbyFieldName), fieldsDropDown, "Item sorting", new HelpDefinition("The field to use when sorting items. Use '(random)' to show random items. Default value is " + _visualFunction.OrderbyFieldName)); yield return new ParameterProfile("OrderbyAscending", typeof(bool), false, new ConstantValueProvider(_visualFunction.OrderbyAscending), StandardWidgetFunctions.CheckBoxWidget, "Sort ascending", new HelpDefinition("When checked items are sorted in ascending order (alphabetically, chronological). This field is ignored when '(random)' sorting is active. Default value is " + _visualFunction.OrderbyAscending.ToString())); } } public static IEnumerable<string> OrderByFieldNames(string typeManagerName) { yield return "(random)"; Type interfaceType = TypeManager.GetType(typeManagerName); foreach (DataFieldDescriptor dataField in DynamicTypeManager.GetDataTypeDescriptor(interfaceType).Fields.OrderBy(f => f.Position)) { yield return dataField.Name; } } public EntityToken EntityToken { get { return _visualFunction.GetDataEntityToken(); } } private class RuntimeVisualFunction : IVisualFunction { private IVisualFunction _function; private int _maximumItemsToList; private string _orderbyFieldName; private bool _orderbyAscending; public RuntimeVisualFunction(IVisualFunction function, int maximumItemsToList, string orderbyFieldName, bool orderbyAscending) { _function = function; _maximumItemsToList = maximumItemsToList; _orderbyFieldName = orderbyFieldName; _orderbyAscending = orderbyAscending; } public Guid Id { get { return _function.Id; } set { throw new NotImplementedException(); } } public string Name { get { return _function.Name; } set { throw new NotImplementedException(); } } public string Namespace { get { return _function.Namespace; } set { throw new NotImplementedException(); } } public string XhtmlTemplate { get { return _function.XhtmlTemplate; } set { throw new NotImplementedException(); } } public int MaximumItemsToList { get { return _maximumItemsToList; } set { throw new NotImplementedException(); } } public string OrderbyFieldName { get { return _orderbyFieldName; } set { throw new NotImplementedException(); } } public bool OrderbyAscending { get { return _orderbyAscending; } set { throw new NotImplementedException(); } } public DataSourceId DataSourceId { get { throw new NotImplementedException(); } } public string TypeManagerName { get { return _function.TypeManagerName; } set { throw new NotImplementedException(); } } public string Description { get { return _function.Description; } set { throw new NotImplementedException(); } } } } } [Assembler(typeof(NonConfigurableFunctionProviderAssembler))] internal sealed class VisualFunctionProviderData : FunctionProviderData { } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/XsltBasedFunctionProvider/RenderHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.Core.Extensions; using Composite.Functions; using Composite.Functions.ManagedParameters; using Composite.Core.Types; using Composite.Data; using Composite.Core.Logging; using Composite.Core.Xml; using Composite.Data.Types; using System.Reflection; using System.Diagnostics; using System.Collections; namespace Composite.Plugins.Functions.FunctionProviders.XsltBasedFunctionProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class TransformationInputs { /// <exclude /> public XContainer InputDocument { get; set; } /// <exclude /> public List<IXsltExtensionDefinition> ExtensionDefinitions { get; set; } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class RenderHelper { /// <exclude /> public static readonly XNamespace XsltInput10 = "http://www.composite.net/ns/transformation/input/1.0"; /// <exclude /> public static TransformationInputs BuildInputDocument(IEnumerable<NamedFunctionCall> FunctionCalls, List<ManagedParameterDefinition> parameterDefinitions, bool addDetailedComments) { Dictionary<string, object> inputParameters = BuildTestParameterInput(parameterDefinitions); return BuildInputDocument(FunctionCalls.ToList(), inputParameters, addDetailedComments); } /// <exclude /> public static TransformationInputs BuildInputDocument(IEnumerable<NamedFunctionCall> FunctionCalls, ParameterList parameterList, bool addDetailedComments) { Dictionary<string, object> inputParameters = new Dictionary<string, object>(); List<string> parameterNames = parameterList.AllParameterNames.ToList(); object[] paramaterValues = new object[parameterNames.Count]; for(int i=0; i<parameterNames.Count; i++) { paramaterValues[i] = parameterList.GetParameter(parameterNames[i]); }; for (int i = 0; i < parameterNames.Count; i++) { inputParameters.Add(parameterNames[i], paramaterValues[i]); } return BuildInputDocument(FunctionCalls.ToList(), inputParameters, addDetailedComments); } private static XElement CreateParameterNode(string parameterName, object value) { if (value is XDocument) value = ((XDocument)value).Root; return new XElement(XsltInput10 + "param", new XAttribute("name", parameterName), value); } private static XElement CreateFunctionCallResultNode(string functionCallName, object result) { if (result is XDocument) result = ((XDocument)result).Root; return new XElement(XsltInput10 + "result", // GetTypeAttribute(result), new XAttribute("name", functionCallName), result); } private static TransformationInputs BuildInputDocument(List<NamedFunctionCall> namedFunctions, Dictionary<string, object> inputParameters, bool addDetailedComments) { var evaluatedParameters = new List<KeyValuePair<string, XElement>>(); var xslExtensions = new List<KeyValuePair<string, IXsltExtensionDefinition>>(); foreach(KeyValuePair<string, object> entry in inputParameters) { object value = entry.Value; if(value is IXsltExtensionDefinition) { xslExtensions.Add(new KeyValuePair<string, IXsltExtensionDefinition>(entry.Key, value as IXsltExtensionDefinition)); } else { evaluatedParameters.Add(new KeyValuePair<string, XElement>(entry.Key, CreateParameterNode(entry.Key, value))); } } return BuildInputDocument2(namedFunctions, inputParameters, evaluatedParameters, xslExtensions, addDetailedComments); } private static TransformationInputs BuildInputDocument2(List<NamedFunctionCall> namedFunctions, Dictionary<string, object> inputParameters, List<KeyValuePair<string, XElement>> evaluatedParameterList, List<KeyValuePair<string, IXsltExtensionDefinition>> xslExtensions, bool addDetailedComments) { var transformationInputs = new TransformationInputs(); // NOTE: Attribute attributes from "xsi" namespaces aren't used // XElement inputRoot = XElement.Parse(string.Format(@"<in:inputs xmlns:in=""{0}"" xmlns:xsi=""{1}"" xmlns:xsd=""{2}"" />", XsltInput10, Namespaces.Xsi, Namespaces.Xsd)); XElement inputRoot = XElement.Parse(@"<in:inputs xmlns:in=""{0}"" />".FormatWith(XsltInput10)); transformationInputs.InputDocument = inputRoot; // Adding XSL extensions if(xslExtensions.Count > 0) { foreach (KeyValuePair<string, IXsltExtensionDefinition> xslExtension in xslExtensions) { IXsltExtensionDefinition extensionDefinition = xslExtension.Value; transformationInputs.ExtensionDefinitions = transformationInputs.ExtensionDefinitions ?? new List<IXsltExtensionDefinition>(); transformationInputs.ExtensionDefinitions.Add(extensionDefinition); if (addDetailedComments) { inputRoot.Add(new XComment(string.Format(" Input Parameter '{0}' has been registered as an Xslt Entension Object. Methods on '{1}' can be called using the namespace '{2}' and format 'prefix:MethodName( arguments )'. ", xslExtension.Key, extensionDefinition.EntensionObjectAsObject.GetType().FullName, extensionDefinition.ExtensionNamespace))); } } } // Adding input parameters if (evaluatedParameterList.Count > 0) { foreach (KeyValuePair<string, XElement> parameter in evaluatedParameterList) { if (addDetailedComments) { inputRoot.Add(new XComment(string.Format(" Input Parameter, XPath /in:inputs/in:param[@name='{0}'] ", parameter.Key))); } inputRoot.Add(parameter.Value); } } if (namedFunctions.Count > 0) { var functionCallResults = new object[namedFunctions.Count]; var functionCallExecutionTimes = new long[namedFunctions.Count]; for(int i=0; i<namedFunctions.Count; i++) { FunctionContextContainer functionContextContainer = new FunctionContextContainer(inputParameters); var namedFunctionCall = namedFunctions[i]; object result = null; Stopwatch executionStopwatch = Stopwatch.StartNew(); try { result = GetFunctionCallResult(functionContextContainer, namedFunctionCall, addDetailedComments); executionStopwatch.Stop(); } catch (Exception ex) { throw new InvalidOperationException(string.Format("Failed to execute function with local name '{0}'", namedFunctionCall.Name), ex); } functionCallResults[i] = result; functionCallExecutionTimes[i] = executionStopwatch.ElapsedMilliseconds; }; for (int i=0; i<namedFunctions.Count; i++) { object result = functionCallResults[i]; if (result is IXsltExtensionDefinition) { IXsltExtensionDefinition extensionDefinition = (IXsltExtensionDefinition)result; transformationInputs.ExtensionDefinitions = transformationInputs.ExtensionDefinitions ?? new List<IXsltExtensionDefinition>(); transformationInputs.ExtensionDefinitions.Add(extensionDefinition); if (addDetailedComments) { string name = namedFunctions[i].Name; inputRoot.Add(new XComment(string.Format(" Function call result '{0}' has been registered as an Xslt Entension Object. ", name, extensionDefinition.ExtensionNamespace))); inputRoot.Add(new XComment(string.Format(" Extension methods can be called using the namespace '{1}'. ", name, extensionDefinition.ExtensionNamespace))); inputRoot.Add(new XComment(" The following methods exist: ")); foreach (MethodInfo mi in extensionDefinition.EntensionObjectAsObject.GetType().GetMethods().Where(m => m.DeclaringType != typeof(object))) { string paramsInfo = string.Join(", ", mi.GetParameters().Select(p => string.Format("{0} {1}", p.ParameterType.Name, p.Name)).ToArray()); string returnTypeName = (mi.ReturnType != null ? mi.ReturnType.Name : "void"); inputRoot.Add(new XComment(string.Format(" {0} ns:{1}({2}) ", returnTypeName, mi.Name, paramsInfo))); } } } else { Verify.That(result is XElement, "Function call result had to be selialized as XElement"); if (addDetailedComments) { string xpathAppend = FindElementXPathAppend(result); inputRoot.Add(new XComment(string.Format(" Function Call Result ({0} ms), XPath /in:inputs/in:result[@name='{1}']{2} ", functionCallExecutionTimes[i], namedFunctions[i].Name, xpathAppend))); } inputRoot.Add(result as XElement); } } } return transformationInputs; } private static string FindElementXPathAppend(object result) { string xpathAppend = ""; XElement firstResultElement = ((XElement)result).Elements().FirstOrDefault(); if (firstResultElement !=null) { XElement resultElementCopy = new XElement(firstResultElement); resultElementCopy.Elements().Remove(); string serializedNode = resultElementCopy.ToString(); char[] nameEndChars = new char[] { ' ', '/', '>' }; xpathAppend = "/" + serializedNode.Substring(1, serializedNode.IndexOfAny(nameEndChars)); } return xpathAppend; } private static object GetFunctionCallResult(FunctionContextContainer functionContextContainer, NamedFunctionCall namedFunctionCall, bool addDetailedComments) { object result = namedFunctionCall.FunctionCall.GetValue(functionContextContainer); if (!(result is IXsltExtensionDefinition)) { if (addDetailedComments) { if (result is IEnumerable<XElement>) result = ((IEnumerable<XElement>)result).ToList(); // timers dont like lazy stuff, so evaluate now if (result is IEnumerable<XNode>) result = ((IEnumerable<XNode>)result).ToList(); // timers dont like lazy stuff, so evaluate now } result = CreateFunctionCallResultNode(namedFunctionCall.Name, result); } return result; } //private static XAttribute GetTypeAttribute(object data) //{ // if (data == null) return null; // Type dataType = data.GetType(); // if (dataType == typeof(string)) return new XAttribute(Namespaces.Xsi + "type", "xsd:string"); // if (dataType == typeof(XElement)) return new XAttribute(Namespaces.Xsi + "type", "xsd:any"); // if (dataType == typeof(int)) return new XAttribute(Namespaces.Xsi + "type", "xsd:integer"); // if (dataType == typeof(Int32)) return new XAttribute(Namespaces.Xsi + "type", "xsd:int"); // if (dataType == typeof(long)) return new XAttribute(Namespaces.Xsi + "type", "xsd:integer"); // if (dataType == typeof(bool)) return new XAttribute(Namespaces.Xsi + "type", "xsd:boolean"); // if (dataType == typeof(DateTime)) return new XAttribute(Namespaces.Xsi + "type", "xsd:dateTime"); // if (dataType == typeof(TimeSpan)) return new XAttribute(Namespaces.Xsi + "type", "xsd:duration"); // if (dataType == typeof(Uri)) return new XAttribute(Namespaces.Xsi + "type", "xsd:anyURI"); // return null; //} internal static IEnumerable<NamedFunctionCall> GetValidatedFunctionCalls(Guid xsltFunctionId) { List<string> errors; IEnumerable<NamedFunctionCall> result = GetValidFunctionCalls(xsltFunctionId, out errors); if (errors != null && errors.Any()) { throw new InvalidOperationException(errors.First()); } return result; } /// <exclude /> public static IEnumerable<NamedFunctionCall> GetValidFunctionCalls(Guid xsltFunctionId, out List<string> errors) { errors = null; List<NamedFunctionCall> result = new List<NamedFunctionCall>(); foreach (INamedFunctionCall namedFunctionCallData in DataFacade.GetData<INamedFunctionCall>(f => f.XsltFunctionId == xsltFunctionId)) { XElement functionElement = XElement.Parse(namedFunctionCallData.SerializedFunction); FunctionRuntimeTreeNode function = null; try { function = (FunctionRuntimeTreeNode)FunctionTreeBuilder.Build(functionElement); } catch (Exception ex) { string errDescriptionForLog = string.Format("XSLT Function call markup for failed to parse ('{0}').\nThe markup was \n{1}", ex.Message, functionElement); string errDescriptionForUser = string.Format("XSLT Function call markup for failed to parse ('{0}').\nPlease see server log for more details.", ex.Message); LoggingService.LogError("Function parse error", errDescriptionForLog); if (errors == null) errors = new List<string>(); errors.Add(errDescriptionForUser); } if (function != null) { result.Add( new NamedFunctionCall(namedFunctionCallData.Name, function)); } } return result; } private static Dictionary<string, object> BuildTestParameterInput(IEnumerable<ManagedParameterDefinition> parameters) { Dictionary<string, object> inputValues = new Dictionary<string, object>(); foreach (ManagedParameterDefinition parameterDefinition in parameters) { object value = null; if (string.IsNullOrEmpty(parameterDefinition.TestValueFunctionMarkup) == false) { FunctionRuntimeTreeNode functionNode = (FunctionRuntimeTreeNode)FunctionTreeBuilder.Build(XElement.Parse(parameterDefinition.TestValueFunctionMarkup)); value = functionNode.GetValue(); } else { if (string.IsNullOrEmpty(parameterDefinition.DefaultValueFunctionMarkup) == false) { FunctionRuntimeTreeNode functionNode = (FunctionRuntimeTreeNode)FunctionTreeBuilder.Build(XElement.Parse(parameterDefinition.DefaultValueFunctionMarkup)); value = functionNode.GetValue(); } } if (value != null) { if (parameterDefinition.Type.IsAssignableFrom(value.GetType()) == false) { value = ValueTypeConverter.Convert(value, parameterDefinition.Type); } inputValues.Add(parameterDefinition.Name, value); } } return inputValues; } } } ================================================ FILE: Composite/Plugins/Functions/FunctionProviders/XsltBasedFunctionProvider/XsltBasedFunctionProvider.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Xml; using System.Xml.Linq; using System.Xml.Xsl; using Composite.C1Console.Security; using Composite.Core.Collections.Generic; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Localization; using Composite.Core.Logging; using Composite.Core.Xml; using Composite.Data; using Composite.Data.Streams; using Composite.Data.Types; using Composite.Functions; using Composite.Functions.ManagedParameters; using Composite.Functions.Plugins.FunctionProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Composite.Core; using Composite.Core.Configuration; namespace Composite.Plugins.Functions.FunctionProviders.XsltBasedFunctionProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum OutputXmlSubType { /// <exclude /> XHTML = 0, /// <exclude /> XML = 1 } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ConfigurationElementType(typeof(XsltBasedFunctionProviderData))] public sealed class XsltBasedFunctionProvider : IDynamicTypeFunctionProvider { private FunctionNotifier _functionNotifier; /// <exclude /> public XsltBasedFunctionProvider() { DataEventSystemFacade.SubscribeToStoreChanged<IXsltFunction>(OnDataChanged, false); } /// <exclude /> public FunctionNotifier FunctionNotifier { set { _functionNotifier = value; } } /// <exclude /> public IEnumerable<IFunction> DynamicTypeDependentFunctions { get { return (from f in DataFacade.GetData<IXsltFunction>().ToList() select new XsltXmlFunction(f) as IFunction).ToList(); } } /// <exclude /> public IEnumerable<IFunction> Functions => Enumerable.Empty<IFunction>(); private void OnDataChanged(object sender, StoreEventArgs storeEventArgs) { if (!SystemSetupFacade.SetupIsRunning) { _functionNotifier.FunctionsUpdated(); } } /// <exclude /> public static void ResolveImportIncludePaths(XContainer doc) { IEnumerable<XElement> imports = doc.Descendants().Where( f => f.Name == Namespaces.Xsl + "import" || f.Name == Namespaces.Xsl + "include"); foreach (XElement import in imports) { XAttribute hrefAttribute = import.Attribute("href"); if (hrefAttribute != null && hrefAttribute.Value.StartsWith("~/")) { hrefAttribute.Value = PathUtil.Resolve(hrefAttribute.Value); } } } private sealed class XsltXmlFunction : IFunction { private readonly IXsltFunction _xsltFunction; // go through XsltFunction instead of this private IEnumerable<ParameterProfile> _parameterProfiles; private volatile IEnumerable<NamedFunctionCall> _functionCalls; private readonly object _lock = new object(); private bool _subscribedToFileChanges; private readonly Hashtable<CultureInfo, XslCompiledTransform> _xslTransformations = new Hashtable<CultureInfo, XslCompiledTransform>(); public XsltXmlFunction(IXsltFunction xsltFunction) { _xsltFunction = xsltFunction; } public object Execute(ParameterList parameters, FunctionContextContainer context) { Guid xsltFunctionId = this._xsltFunction.Id; if (_functionCalls == null) { lock (_lock) { if (_functionCalls == null) { _functionCalls = RenderHelper.GetValidatedFunctionCalls(xsltFunctionId); } } } TransformationInputs transformationInput = RenderHelper.BuildInputDocument(_functionCalls, parameters, false); XDocument newTree = new XDocument(); using (XmlWriter writer = new LimitedDepthXmlWriter(newTree.CreateWriter())) { var transformArgs = new XsltArgumentList(); XslExtensionsManager.Register(transformArgs); if (transformationInput.ExtensionDefinitions != null) { foreach (IXsltExtensionDefinition extensionDef in transformationInput.ExtensionDefinitions) { transformArgs.AddExtensionObject(extensionDef.ExtensionNamespace.ToString(), extensionDef.EntensionObjectAsObject); } } var xslTransformer = GetXslCompiledTransform(); xslTransformer.Transform(transformationInput.InputDocument.CreateReader(), transformArgs, writer); } if (this._xsltFunction.OutputXmlSubType == nameof(OutputXmlSubType.XHTML)) { return new XhtmlDocument(newTree); } return newTree.Root; } private XslCompiledTransform GetXslCompiledTransform() { var currentCultureInfo = LocalizationScopeManager.CurrentLocalizationScope; XslCompiledTransform xslCompiledTransform; if (_xslTransformations.TryGetValue(currentCultureInfo, out xslCompiledTransform)) { return xslCompiledTransform; } lock (_lock) { if (!_xslTransformations.TryGetValue(currentCultureInfo, out xslCompiledTransform)) { xslCompiledTransform = BuildCompiledTransform(); _xslTransformations.Add(currentCultureInfo, xslCompiledTransform); } } return xslCompiledTransform; } private XslCompiledTransform BuildCompiledTransform() { using (DebugLoggingScope.CompletionTime(this.GetType(), $"Loading and compiling {_xsltFunction.XslFilePath}")) { string folderPath = Path.GetDirectoryName(_xsltFunction.XslFilePath); string fileName = Path.GetFileName(_xsltFunction.XslFilePath); IXsltFile xsltFileHandle; try { var xsltFileHandles = (from file in DataFacade.GetData<IXsltFile>() where String.Equals(file.FolderPath, folderPath, StringComparison.OrdinalIgnoreCase) && String.Equals(file.FileName, fileName, StringComparison.OrdinalIgnoreCase) select file).ToList(); Verify.That(xsltFileHandles.Count == 1, "XSLT file path {0} found {1} times. Only one instance was expected.", _xsltFunction.XslFilePath, xsltFileHandles.Count); xsltFileHandle = xsltFileHandles[0]; } catch (Exception ex) { Log.LogError("XsltBasedFunctionProvider", ex); throw; } if (!_subscribedToFileChanges) { xsltFileHandle.SubscribeOnChanged(ClearCachedData); _subscribedToFileChanges = true; } var xslCompiledTransform = new XslCompiledTransform(); XDocument doc; using (Stream xsltSourceStream = xsltFileHandle.GetReadStream()) { using (XmlReader xmlReader = XmlReader.Create(xsltSourceStream)) { doc = XDocument.Load(xmlReader); } } ResolveImportIncludePaths(doc); LocalizationParser.Parse(doc); xslCompiledTransform.Load(doc.CreateReader(), XsltSettings.TrustedXslt, new XmlUrlResolver()); return xslCompiledTransform; } } private void ClearCachedData(string filePath, FileChangeType changeType) { lock(_lock) { _xslTransformations.Clear(); } } public string Name => _xsltFunction.Name; public string Namespace => _xsltFunction.Namespace; public string Description => _xsltFunction.Description; public Type ReturnType { get { switch (this._xsltFunction.OutputXmlSubType) { case "XHTML": return typeof(XhtmlDocument); default: return typeof(XElement); } } } public IEnumerable<ParameterProfile> ParameterProfiles { get { if (_parameterProfiles == null) { lock (_lock) { if (_parameterProfiles == null) { _parameterProfiles = ManagedParameterManager.GetParameterProfiles(_xsltFunction.Id); } } } return _parameterProfiles; } } public EntityToken EntityToken => _xsltFunction.GetDataEntityToken(); } } [Assembler(typeof(NonConfigurableFunctionProviderAssembler))] internal sealed class XsltBasedFunctionProviderData : FunctionProviderData { } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/Bool/BoolSelectorWidgetFuntion.cs ================================================ using System; using System.Xml.Linq; using System.Collections.Generic; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; using Composite.C1Console.Forms.CoreUiControls; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Bool { internal sealed class BoolSelectorWidgetFuntion : CompositeWidgetFunctionBase { private const string _functionName = "BoolSelector"; public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".Bool." + _functionName; public const string TrueLabelParameterName = "TrueLabel"; public const string FalseLabelParameterName = "FalseLabel"; public BoolSelectorWidgetFuntion(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(bool), entityTokenFactory) { SetParameterProfiles( true, "True", "False"); } public BoolSelectorWidgetFuntion(EntityTokenFactory entityTokenFactory, string trueLabel, string falseLabel) : base(CompositeName, typeof(bool), entityTokenFactory) { SetParameterProfiles(false, trueLabel, falseLabel); } private void SetParameterProfiles(bool require, string trueLabel, string falseLabel) { ParameterProfile trueLabelPP = new ParameterProfile(BoolSelectorWidgetFuntion.TrueLabelParameterName, typeof(string), require, new ConstantValueProvider(trueLabel), StandardWidgetFunctions.TextBoxWidget, null, "True label", new HelpDefinition("Label to show when value is true")); ParameterProfile falseLabelPP = new ParameterProfile(BoolSelectorWidgetFuntion.FalseLabelParameterName, typeof(string), require, new ConstantValueProvider(falseLabel), StandardWidgetFunctions.TextBoxWidget, null, "False label", new HelpDefinition("Label to show when value is false")); base.AddParameterProfile(trueLabelPP); base.AddParameterProfile(falseLabelPP); } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { XElement boolSelectorMarkup = base.BuildBasicWidgetMarkup("BoolSelector", "IsTrue", label, help, bindingSourceName); boolSelectorMarkup.Add(new XAttribute("TrueLabel", parameters.GetParameter<string>(BoolSelectorWidgetFuntion.TrueLabelParameterName))); boolSelectorMarkup.Add(new XAttribute("FalseLabel", parameters.GetParameter<string>(BoolSelectorWidgetFuntion.FalseLabelParameterName))); return boolSelectorMarkup; } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/Bool/CheckBoxWidgetFuntion.cs ================================================ using System; using System.Xml.Linq; using System.Collections.Generic; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; using Composite.C1Console.Forms.CoreUiControls; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Bool { internal sealed class CheckBoxWidgetFuntion : CompositeWidgetFunctionBase { private const string _functionName = "CheckBox"; public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".Bool." + _functionName; public CheckBoxWidgetFuntion(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(bool), entityTokenFactory) { ParameterProfile pp = new ParameterProfile("ItemLabel", typeof(string), false, new ConstantValueProvider(""), StandardWidgetFunctions.TextBoxWidget, null, "Sub label", new HelpDefinition("Text to whow beside the checkbox")); base.AddParameterProfile(pp); } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { XElement checkBoxMarkup = base.BuildBasicWidgetMarkup("CheckBox", "Checked", label, help, bindingSourceName); string itemLabel = parameters.GetParameter<string>("ItemLabel"); if (string.IsNullOrEmpty(itemLabel) == false) { checkBoxMarkup.Add(new XAttribute("ItemLabel", itemLabel)); } return checkBoxMarkup; } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/DataReference/DataReferenceSelectorWidgetFunction.cs ================================================ using System.Collections; using System.Xml.Linq; using Composite.Core.Types; using Composite.Data; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.DataReference { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DataReferenceSelectorWidgetFunction<T> : CompositeWidgetFunctionBase where T : class, IData { private const string _compositeNameBase = CompositeWidgetFunctionBase.CommonNamespace + ".DataReference."; /// <exclude /> public DataReferenceSelectorWidgetFunction(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(DataReference<T>), entityTokenFactory) { } internal static string CompositeName { get { return _compositeNameBase + typeof(T).FullName.Replace(".", "") + ".Selector"; } } /// <exclude /> public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition helpDefinition, string bindingSourceName) { return StandardWidgetFunctions.BuildStaticCallPopulatedSelectorFormsMarkup( parameters, label, helpDefinition, bindingSourceName, this.GetType(), "GetOptions", TypeManager.SerializeType(typeof(T)), "Key", "Label", false, true, true, false); } /// <summary> /// To be called through reflection /// </summary> /// <exclude /> public static IEnumerable GetOptions(string typeManagerName) { return GetOptionsCommon.GetOptions(typeManagerName); } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/DataReference/GetOptionsCommon.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Collections; using Composite.Data.Caching; using Composite.Data.DynamicTypes; using Composite.Core.Extensions; using Composite.Core.Types; using Composite.Core.WebClient.Renderings.Page; using Composite.Data; using System.Reflection; using TypeInfo = Composite.Core.Types.Pair<System.Type, Composite.Data.DynamicTypes.DataTypeDescriptor>; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.DataReference { internal static class GetOptionsCommon { private static readonly Cache<string, TypeInfo> _typeLookup = new Cache<string, TypeInfo>("GetOptionsCommon. Type info lookup", 150); internal static IEnumerable GetOptions(string typeManagerName) { Type t = GetTypeInfo(typeManagerName).First; switch (t.FullName) { case "Composite.Data.Types.IPage": #pragma warning disable 612 foreach (KeyValuePair<System.Guid, string> pageItem in PageStructureInfo.PageListInDocumentOrder()) #pragma warning restore 612 { yield return new { Key = pageItem.Key, Label = pageItem.Value }; } break; default: foreach (KeyValuePair pageItem in GetOptionsForDefault(t, typeManagerName)) { yield return new { Key = pageItem.Key, Label = pageItem.Value }; } break; } } private static IEnumerable<KeyValuePair> GetOptionsForDefault(Type t, string typeManagerName) { DataTypeDescriptor dtd = GetTypeInfo(typeManagerName).Second; Verify.That(dtd.KeyPropertyNames.Count == 1, "Unable to deliver data for selector widget. The selected type '{0}' should have exactly one key property.".FormatWith(typeManagerName)); string keyFieldName = dtd.KeyPropertyNames[0]; var allData = DataFacade.GetData(t) .ToDataList() .Select(data => new { Data = data, Label = data.GetLabel(true) }) .OrderBy(data => data.Label); PropertyInfo keyPi = t.GetPropertiesRecursively(f => f.Name == keyFieldName).FirstOrDefault(); Verify.That(keyPi != null, "The type '{0}' has invalid meta data. The specified key property '{1}' not found.", typeManagerName, keyFieldName); return from data in allData select new KeyValuePair { Key = (keyPi.GetValue(data.Data, new object[] { }) ?? "").ToString(), Value = data.Label }; } private static TypeInfo GetTypeInfo(string typeManagerName) { TypeInfo cachedValue = _typeLookup.Get(typeManagerName); if(cachedValue != null) { return cachedValue; } Type type = TypeManager.GetType(typeManagerName); DataTypeDescriptor typeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(type); var result = new TypeInfo(type, typeDescriptor); _typeLookup.Add(typeManagerName, result); return result; } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/DataReference/HomePageSelectorWidgetFunction.cs ================================================ using System.Collections; using System.Xml.Linq; using Composite.Core.WebClient.Renderings.Page; using Composite.Data; using Composite.Data.Types; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.DataReference { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class HomePageSelectorWidgetFunction : CompositeWidgetFunctionBase { /// <exclude /> public HomePageSelectorWidgetFunction(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(DataReference<IPage>), entityTokenFactory) { } private const string CompositeName = CommonNamespace + ".DataReference" + ".HomePageSelector"; /// <exclude /> public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition helpDefinition, string bindingSourceName) { return StandardWidgetFunctions.BuildStaticCallPopulatedSelectorFormsMarkup( parameters: parameters, label: label, helpDefinition: helpDefinition, bindingSourceName: bindingSourceName, optionsGeneratingStaticType: typeof(HomePageSelectorWidgetFunction), optionsGeneratingStaticMethodName: nameof(GetHomePages), optionsGeneratingStaticMethodParameterValue: null, optionsObjectKeyPropertyName: "Key", optionsObjectLabelPropertyName: "Label", multiSelect: false, compactMode: true, required: true, bindToString: false); } /// <summary> /// To be called through reflection /// </summary> /// <exclude /> public static IEnumerable GetHomePages() { foreach (var element in PageStructureInfo.GetSiteMap()) { yield return new { Key = PageStructureInfo.GetIdForPageElement(element), Label = PageStructureInfo.GetLabelForPageElement("", element) }; } } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/DataReference/NullableDataReferenceSelectorWidgetFunction.cs ================================================ using System.Collections; using System.Xml.Linq; using Composite.Core.Types; using Composite.Data; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.DataReference { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class NullableDataReferenceSelectorWidgetFunction<T> : CompositeWidgetFunctionBase where T : class, IData { private const string _compositeNameBase = CompositeWidgetFunctionBase.CommonNamespace + ".DataReference."; /// <exclude /> public NullableDataReferenceSelectorWidgetFunction(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(NullableDataReference<T>), entityTokenFactory) { } internal static string CompositeName { get { return _compositeNameBase + typeof(T).FullName.Replace(".", "") + ".OptionalSelector"; } } /// <exclude /> public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition helpDefinition, string bindingSourceName) { return StandardWidgetFunctions.BuildStaticCallPopulatedSelectorFormsMarkup( parameters, label, helpDefinition, bindingSourceName, this.GetType(), "GetOptions", TypeManager.SerializeType(typeof(T)), "Key", "Label", false, true, false, false); } /// <summary> /// To be called through reflection /// </summary> /// <exclude /> public static IEnumerable GetOptions(string typeManagerName) { return GetOptionsCommon.GetOptions(typeManagerName); } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/DataReference/NullablePageReferenceSelectorWidgetFunction.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Elements; using Composite.Data; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; using Composite.Data.Types; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.DataReference { internal sealed class NullablePageReferenceSelectorWidgetFunction : PageReferenceSelectorWidgetFunctionBase { public const string CompositeName = CompositeNameBase + ".OptionalPageSelector"; public NullablePageReferenceSelectorWidgetFunction(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(NullableDataReference<IPage>), entityTokenFactory) { } protected override bool IsNullable() { return true; } }; } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/DataReference/PageReferenceSelectorWidgetFunction.cs ================================================ using Composite.Data; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; using Composite.Data.Types; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.DataReference { internal sealed class PageReferenceSelectorWidgetFunction : PageReferenceSelectorWidgetFunctionBase { public const string CompositeName = CompositeNameBase + ".PageSelector"; public PageReferenceSelectorWidgetFunction(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(DataReference<IPage>), entityTokenFactory) { } protected override bool IsNullable() { return false; } }; } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/DataReference/PageReferenceSelectorWidgetFunctionBase.cs ================================================ using Composite.Core.Types; using Composite.Core.Xml; using Composite.Data.Types; using Composite.Functions; using Composite.Plugins.Elements.ElementProviders.PageElementProvider; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; using System; using System.Xml.Linq; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.DataReference { internal abstract class PageReferenceSelectorWidgetFunctionBase : CompositeWidgetFunctionBase { protected const string CompositeNameBase = CommonNamespace + ".DataReference"; private const string HomePageIdParameterName = "HomePageId"; protected PageReferenceSelectorWidgetFunctionBase(string compositeName, Type returnType, EntityTokenFactory entityTokenFactory) : base(compositeName, returnType, entityTokenFactory) { base.AddParameterProfile( new ParameterProfile(HomePageIdParameterName, typeof(Guid?), false, new ConstantValueProvider(null), new WidgetFunctionProvider(new HomePageSelectorWidgetFunction(entityTokenFactory)), null, "Filter by Home Page", new HelpDefinition("Use this field to filter by root website. If not set all websites are shown. You can use GetPageId function to get current page"))); } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition helpDefinition, string bindingSourceName) { var selector = BuildBasicWidgetMarkup("DataReferenceTreeSelector", "Selected", label, helpDefinition, bindingSourceName); selector.Add( new XAttribute("Handle", "Composite.Management.PageIdSelectorDialog"), new XAttribute("DataType", TypeManager.SerializeType(typeof(IPage))), new XAttribute("NullValueAllowed", IsNullable()) ); var searchToken = GetSearchToken(parameters, selector); if (searchToken != null) selector.Add(searchToken); return selector; } private XElement GetSearchToken(ParameterList parameters, XElement selector) { var parameter = GetParameterElement(parameters); if (parameter == null) return null; var f = Namespaces.BindingFormsStdFuncLib10; var element = new XElement(selector.Name.Namespace + "DataReferenceTreeSelector.SearchToken", new XElement(f + "StaticMethodCall", new XAttribute("Type", TypeManager.SerializeType(typeof(PageReferenceSelectorWidgetFunctionBase))), new XAttribute("Method", nameof(GetPageSearchToken)), new XElement(f + "StaticMethodCall.Parameters", parameter))); return element; } private object GetParameterElement(ParameterList parameters) { if (!parameters.TryGetParameterRuntimeTreeNode(HomePageIdParameterName, out var runtimeTreeNode)) { return null; } if (runtimeTreeNode is FunctionParameterRuntimeTreeNode functionParamNode) { return functionParamNode.GetHostedFunction().Serialize(); } if (runtimeTreeNode is ConstantParameterRuntimeTreeNode constParamNode) { return constParamNode.GetValue(); } return null; } public static string GetPageSearchToken(Guid? homePageId) { var token = new PageSearchToken { HomePageId = homePageId, }; return token.Serialize(); } protected abstract bool IsNullable(); }; } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/Date/DateSelectorWidgetFunction.cs ================================================ using System; using System.Xml.Linq; using System.Collections.Generic; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Date { internal sealed class DateSelectorWidgetFunction : CompositeWidgetFunctionBase { private const string _functionName = "DateSelector"; public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".Date." + _functionName; public DateSelectorWidgetFunction(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(DateTime), entityTokenFactory) { ParameterProfile pp = new ParameterProfile("ReadOnly", typeof(bool), false, new ConstantValueProvider(false), StandardWidgetFunctions.CheckBoxWidget, null, "Read only", new HelpDefinition("When selected users can not change the date.")); base.AddParameterProfile(pp); } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { XElement dateSelectorElement = base.BuildBasicWidgetMarkup("DateSelector", "Date", label, help, bindingSourceName); if (parameters.GetParameter<bool>("ReadOnly")) { dateSelectorElement.Add(new XAttribute("ReadOnly", true)); } return dateSelectorElement; } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/Date/DateTimeSelectorWidgetFunction.cs ================================================ using System; using System.Xml.Linq; using System.Collections.Generic; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Date { internal sealed class DateTimeSelectorWidgetFunction : CompositeWidgetFunctionBase { private const string _functionName = "DateTimeSelector"; public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".Date." + _functionName; public DateTimeSelectorWidgetFunction(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(DateTime), entityTokenFactory) { ParameterProfile pp = new ParameterProfile("ReadOnly", typeof(bool), false, new ConstantValueProvider(false), StandardWidgetFunctions.CheckBoxWidget, null, "Read only", new HelpDefinition("When selected users can not change the date.")); base.AddParameterProfile(pp); } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { XElement dateSelectorElement = base.BuildBasicWidgetMarkup("DateTimeSelector", "Date", label, help, bindingSourceName); if (parameters.GetParameter<bool>("ReadOnly")) { dateSelectorElement.Add(new XAttribute("ReadOnly", true)); } return dateSelectorElement; } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/Decimal/DecimalTextBoxWidgetFuntion.cs ================================================ using System; using System.Xml.Linq; using System.Collections.Generic; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; using Composite.C1Console.Forms.CoreUiControls; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Decimal { internal sealed class DecimalTextBoxWidgetFuntion : CompositeWidgetFunctionBase { private const string _functionName = "TextBox"; public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".Decimal." + _functionName; public DecimalTextBoxWidgetFuntion(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(decimal), entityTokenFactory) { } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { XElement textBoxMarkup = base.BuildBasicWidgetMarkup("TextBox", "Text", label, help, bindingSourceName); textBoxMarkup.Add(new XAttribute("Type", TextBoxType.Decimal)); return textBoxMarkup; } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/Foundation/CompositeWidgetFunctionBase.cs ================================================ using System; using System.Collections.Generic; using System.Xml.Linq; using Composite.C1Console.Security; using Composite.Core.Xml; using Composite.Functions; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public abstract class CompositeWidgetFunctionBase : IWidgetFunction { /// <exclude /> protected const string CommonNamespace = "Composite.Widgets"; /// <exclude /> protected const string InternalCommonNamespace = "Composite.Widgets.Internal"; // not exposed by provider private EntityTokenFactory _entityTokenFactory; /// <exclude /> protected CompositeWidgetFunctionBase(string compositeName, Type returnType, EntityTokenFactory entityTokenFactory) { if (string.IsNullOrEmpty(compositeName)) throw new ArgumentNullException("compositeName"); this.Namespace = compositeName.Substring(0,compositeName.LastIndexOf('.')); this.Name = compositeName.Substring(compositeName.LastIndexOf('.')+1); this.ReturnType = returnType; this.ParameterProfiles = new List<ParameterProfile>(); _entityTokenFactory = entityTokenFactory; } /// <exclude /> protected void AddParameterProfile(ParameterProfile pp) { ((List<ParameterProfile>)this.ParameterProfiles).Add(pp); } /// <exclude /> public virtual string Name { get; private set; } /// <exclude /> public string Namespace{ get; private set; } /// <exclude /> public virtual string Description { get { return ""; } } /// <exclude /> public Type ReturnType { get; private set; } /// <exclude /> public IEnumerable<ParameterProfile> ParameterProfiles { get; private set; } /// <exclude /> public abstract XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName); /// <exclude /> protected XElement BuildBasicWidgetMarkup(string uiControlName, string bindingPropertyName, string label, HelpDefinition help, string bindingSourceName) { return StandardWidgetFunctions.BuildBasicFormsMarkup(Namespaces.BindingFormsStdUiControls10, uiControlName, bindingPropertyName, label, help, bindingSourceName); } /// <exclude /> public EntityToken EntityToken { get { return _entityTokenFactory.CreateEntityToken(this); } } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/Foundation/EntityTokenFactory.cs ================================================ using Composite.C1Console.Security; using Composite.Functions; using Composite.Core.Extensions; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class EntityTokenFactory { private readonly string _providerName; /// <exclude /> public EntityTokenFactory(string providerName) { _providerName = providerName; } internal EntityToken CreateEntityToken(IMetaFunction function) { string id = StringExtensionMethods.CreateNamespace(function.Namespace, function.Name, '.'); return new StandardWidgetFunctionProviderEntityToken(_providerName, id ); } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/Foundation/FormFunctionMarkupBuilder.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Text; using System.Xml.Linq; using System.Reflection; using Composite.Core.Xml; using Composite.Core.Types; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation { internal static class FormFunctionMarkupBuilder { public static XElement StaticMethodCall(MethodInfo methodInfo, object parameter) { XNamespace f = Namespaces.BindingFormsStdFuncLib10; try { string parameterSerialized = ValueTypeConverter.Convert<string>(parameter); return new XElement(f + "StaticMethodCall", new XAttribute("Type", TypeManager.SerializeType(methodInfo.DeclaringType)), new XAttribute("Method", methodInfo.Name), new XAttribute("Parameters", parameterSerialized ?? "")); } catch (Exception ex) { throw new InvalidOperationException(string.Format("Failed to generate markup for static method call to '{0}' ('{1}') with parameter of type {2}", methodInfo.Name, methodInfo.DeclaringType.AssemblyQualifiedName, parameter.GetType()), ex); } } internal static object StaticMethodCall(MethodInfo methodInfo) { XNamespace f = Namespaces.BindingFormsStdFuncLib10; return new XElement(f + "StaticMethodCall", new XAttribute("Type", TypeManager.SerializeType(methodInfo.DeclaringType)), new XAttribute("Method", methodInfo.Name)); } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/Guid/GuidTextBoxWidgetFuntion.cs ================================================ using System; using System.Xml.Linq; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; using Composite.C1Console.Forms.CoreUiControls; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.GuidWidgetFunctions { internal sealed class GuidTextBoxWidgetFuntion : CompositeWidgetFunctionBase { private const string _functionName = "TextBox"; public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".Guid." + _functionName; public GuidTextBoxWidgetFuntion(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(Guid), entityTokenFactory) { } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { XElement textBoxMarkup = base.BuildBasicWidgetMarkup("TextBox", "Text", label, help, bindingSourceName); textBoxMarkup.Add(new XAttribute("Type", TextBoxType.Guid)); return textBoxMarkup; } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/ImageSelectorWidgetFunction.cs ================================================ using System; using System.Linq; using System.Xml.Linq; using System.Collections.Generic; using Composite.Data.DynamicTypes; using Composite.Functions; using Composite.Core.IO; using Composite.Core.Logging; using Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; using Composite.Data; using Composite.Core.Extensions; using Composite.Data.Types; using Composite.Core.Types; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider { internal sealed class ImageSelectorWidgetFunction : CompositeWidgetFunctionBase { private static readonly string LogTitle = "ImageSelectorWidgetFunction"; private const string _functionName = "ImageSelector"; public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + "." + _functionName; public const string RequiredParameterName = "Required"; public const string MediaFileFolderReferenceParameterName = "MediaFileFolderReference"; public ImageSelectorWidgetFunction(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(NullableDataReference<IImageFile>), entityTokenFactory) { var mediaFolderSelectorWidget = new WidgetFunctionProvider(MediaFileFolderSelectorWidget.CompositeName); base.AddParameterProfile( new ParameterProfile(MediaFileFolderReferenceParameterName, typeof(DataReference<IMediaFileFolder>), false, new ConstantValueProvider(new DataReference<IMediaFileFolder>()), mediaFolderSelectorWidget, new Dictionary<string, object>(), "Image folder", new HelpDefinition("Select a media folder to choose images from. Default is 'all media'.")) ); var requiredWidget = StandardWidgetFunctions.GetBoolSelectorWidget("Yes, require selection", "No, optional"); base.AddParameterProfile( new ParameterProfile(RequiredParameterName, typeof(bool), false, new ConstantValueProvider(true), requiredWidget, new Dictionary<string, object>(), "Selection required", new HelpDefinition("Specify if selecting an image should be required.")) ); } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { var searchToken = new MediaFileSearchToken(); searchToken.MimeTypes = new string[] { MimeTypeInfo.Gif, MimeTypeInfo.Jpeg, MimeTypeInfo.Png, MimeTypeInfo.Bmp, MimeTypeInfo.Svg }; var folderReference = parameters.GetParameter<DataReference<IMediaFileFolder>>(MediaFileFolderReferenceParameterName); bool selectionRequired = parameters.GetParameter<bool>(RequiredParameterName); if (folderReference != null && folderReference.IsSet) { IMediaFileFolder folder; try { folder = folderReference.Data; if(folder != null) { searchToken.Folder = folder.Path; } } catch (Exception) { string reference = folderReference.Serialize() ?? string.Empty; LoggingService.LogError(LogTitle, "Failed to get media folder by referece: '{0}'".FormatWith(reference)); } } XElement selector = base.BuildBasicWidgetMarkup("DataReferenceTreeSelector", "Selected", label, help, bindingSourceName); selector.Add( new XAttribute("Handle", "Composite.Management.ImageSelectorDialog"), new XAttribute("SearchToken", searchToken.Serialize()), new XAttribute("DataType", TypeManager.SerializeType(typeof(IImageFile))), new XAttribute("NullValueAllowed", (!selectionRequired)) ); return selector; } public static Type GetImageType() { return typeof (IImageFile); } /// <summary> /// Provides data for the drop down list. Left here only for backwards compatibility /// </summary> /// <param name="folderReference"></param> /// <returns></returns> [Obsolete("Was used only in old image widget's markup.", true)] public static IEnumerable<DataReferenceLabelPair<IImageFile>> GenerateSelectorOptions(DataReference<IMediaFileFolder> folderReference) { IMediaFileFolder folder = null; if (folderReference.IsSet) { try { folder = folderReference.Data; } catch (Exception) { string reference = folderReference.Serialize() ?? string.Empty; LoggingService.LogError(LogTitle, "Failed to get media folder by referece: '{0}'".FormatWith(reference)); } } if (folder != null) { int pathLength = folder.Path.Length; return from mediaFile in DataFacade.GetData<IImageFile>() where mediaFile.StoreId == folder.StoreId && mediaFile.FolderPath.StartsWith(folder.Path) orderby mediaFile.StoreId, mediaFile.FolderPath, mediaFile.FileName select new DataReferenceLabelPair<IImageFile>(mediaFile, mediaFile.FolderPath.Substring(pathLength) + "/" + mediaFile.FileName); } // Returning all of the images return from mediaFile in DataFacade.GetData<IImageFile>() orderby mediaFile.StoreId, mediaFile.FolderPath, mediaFile.FileName select new DataReferenceLabelPair<IImageFile>(mediaFile, mediaFile.StoreId + ":" + mediaFile.FolderPath + "/" + mediaFile.FileName); } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/Integer/IntegerTextBoxWidgetFuntion.cs ================================================ using System; using System.Xml.Linq; using System.Collections.Generic; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; using Composite.C1Console.Forms.CoreUiControls; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Integer { internal sealed class IntegerTextBoxWidgetFuntion : CompositeWidgetFunctionBase { private const string _functionName = "TextBox"; public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".Integer." + _functionName; public IntegerTextBoxWidgetFuntion(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(int), entityTokenFactory) { } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { XElement textBoxMarkup = base.BuildBasicWidgetMarkup("TextBox", "Text", label, help, bindingSourceName); textBoxMarkup.Add(new XAttribute("Type", TextBoxType.Integer)); return textBoxMarkup; } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/MediaFileSelectorWidgetFunction.cs ================================================ using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Xml.Linq; using System.Collections.Generic; using Composite.Core.Collections.Generic; using Composite.Core.Extensions; using Composite.Functions; using Composite.Core.Logging; using Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; using Composite.Data; using Composite.Data.Types; using Composite.Core.Types; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider { internal sealed class MediaFileSelectorWidgetFunction : CompositeWidgetFunctionBase { private static readonly string LogTitle = "MediaFileSelectorWidgetFunction"; private const string _functionName = "MediaFileSelector"; public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + "." + _functionName; public const string RequiredParameterName = "Required"; private static readonly Expression IgnoreCaseConstantExpression = Expression.Constant(StringComparison.OrdinalIgnoreCase, typeof(StringComparison)); private static readonly MethodInfo EndsWithMethodInfo = typeof(string).GetMethod("EndsWith", new[] { typeof(string), typeof(StringComparison) }); private static Hashtable<string, Expression<Func<IMediaFile, bool>>> _expressionCache = new Hashtable<string, Expression<Func<IMediaFile, bool>>>(); public MediaFileSelectorWidgetFunction(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(NullableDataReference<IMediaFile>), entityTokenFactory) { var widget = new WidgetFunctionProvider(MediaFileFolderSelectorWidget.CompositeName); base.AddParameterProfile( new ParameterProfile("MediaFileFolderReference", typeof(DataReference<IMediaFileFolder>), false, new ConstantValueProvider(new DataReference<IMediaFileFolder>()), widget, new Dictionary<string, object>(), "Media Folder", new HelpDefinition("Select a media folder to choose files from. Default is all media files."))); base.AddParameterProfile( new ParameterProfile("FileExtensionFilter", typeof(string), false, new ConstantValueProvider(""), StandardWidgetFunctions.TextBoxWidget, null, "File Extension Filter", new HelpDefinition("Limit the list to files which have the specified extension. Default is no filter."))); base.AddParameterProfile( new ParameterProfile("IncludeSubfolders", typeof(bool), false, new ConstantValueProvider(true), StandardWidgetFunctions.GetBoolSelectorWidget("Include files from subfolders", "Only show files from the specified Media folder"), null, "Include Subfolders", new HelpDefinition("When false files from subfolders will no be included."))); var requiredWidget = StandardWidgetFunctions.GetBoolSelectorWidget("Yes, require selection", "No, optional"); base.AddParameterProfile( new ParameterProfile(RequiredParameterName, typeof(bool), false, new ConstantValueProvider(true), requiredWidget, new Dictionary<string, object>(), "Selection required", new HelpDefinition("Specify if selecting a media file should be required.")) ); } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { // TODO: config widget for optional values bool selectionRequired = parameters.GetParameter<bool>(RequiredParameterName); var searchToken = new MediaFileSearchToken(); string extensionStr = parameters.GetParameter<string>("FileExtensionFilter"); if(!extensionStr.IsNullOrEmpty()) { searchToken.Extensions = extensionStr.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } searchToken.Folder = GetFolderPath(parameters.GetParameter<DataReference<IMediaFileFolder>>("MediaFileFolderReference")); searchToken.HideSubfolders = !parameters.GetParameter<bool>("IncludeSubfolders"); XElement selector = base.BuildBasicWidgetMarkup("DataReferenceTreeSelector", "Selected", label, help, bindingSourceName); selector.Add( new XAttribute("Handle", "Composite.Management.EmbeddableMediaSelectorDialog"), new XAttribute("SearchToken", searchToken.Serialize()), new XAttribute("DataType", TypeManager.SerializeType(typeof(IMediaFile))), new XAttribute("NullValueAllowed", (!selectionRequired)) ); return selector; } private static string GetFolderPath(DataReference<IMediaFileFolder> folderReference) { if (folderReference != null && folderReference.IsSet) { IMediaFileFolder folder; try { folder = folderReference.Data; if (folder != null) { return folder.Path; } } catch (Exception) { string reference = folderReference.Serialize() ?? string.Empty; LoggingService.LogError(LogTitle, "Failed to get media folder by referece: '{0}'".FormatWith(reference)); } } return null; } public static Type GetMediaType() { return typeof(IMediaFile); } /// <summary> /// Provides data for the drop down list. Left here only for backwards compatibility /// </summary> /// <param name="key"></param> /// <returns></returns> [Obsolete("Was used only in old media file widget's markup.")] public static IEnumerable<DataReferenceLabelPair<IMediaFile>> GenerateSelectorOptions(string key) { string folderString = key.Split('?')[0]; string extensionFilter = key.Split('?')[1]; bool includeSubfolders = bool.Parse(key.Split('?')[2]); IQueryable<IMediaFile> queryable = DataFacade.GetData<IMediaFile>(); bool filterByFolder = !folderString.IsNullOrEmpty(); IMediaFileFolder folder = null; if (filterByFolder) { var folderReference = new DataReference<IMediaFileFolder>(folderString); folder = folderReference.Data; string storeId = folder.StoreId; queryable = queryable.Where(mediaFile => mediaFile.StoreId == storeId); string folderPath = folder.Path; if (!includeSubfolders) { queryable = queryable.Where(mediaFile => mediaFile.FolderPath == folderPath); } else { string descFolderPrefix = folderPath + "/"; queryable = queryable.Where(mediaFile => mediaFile.FolderPath == folderPath || mediaFile.FolderPath.StartsWith(descFolderPrefix)); } } if (!extensionFilter.IsNullOrEmpty()) { Expression<Func<IMediaFile, bool>> filter = GetExtensionFilter(extensionFilter); if (filter != null) { queryable = queryable.Where(filter); } } // orderby mediaFile.StoreId, mediaFile.FolderPath, mediaFile.FileName queryable = queryable.OrderBy(file => file.StoreId).ThenBy(file => file.FolderPath).ThenBy(file => file.FileName); if (filterByFolder) { int pathLength = folder.Path.Length; return from mediaFile in queryable select new DataReferenceLabelPair<IMediaFile>(mediaFile, mediaFile.FolderPath.Substring(pathLength) + "/" + mediaFile.FileName); } return from mediaFile in queryable select new DataReferenceLabelPair<IMediaFile>(mediaFile, mediaFile.StoreId + ":" + mediaFile.FolderPath + "/" + mediaFile.FileName); } [Obsolete()] private static Expression<Func<IMediaFile, bool>> GetExtensionFilter(string allowedFileExtensions) { allowedFileExtensions = allowedFileExtensions.ToLowerInvariant(); Expression<Func<IMediaFile, bool>> cachedValue = _expressionCache[allowedFileExtensions]; if (cachedValue != null) return cachedValue; lock (_expressionCache) { cachedValue = _expressionCache[allowedFileExtensions]; if (cachedValue != null) return cachedValue; string[] extensions = allowedFileExtensions.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (extensions.Length == 0) { return null; } // "file" var fileParameter = Expression.Parameter(typeof(IMediaFile), "file"); Expression body = null; foreach (string extension in extensions) { string suffix = extension.StartsWith(".") ? extension : "." + extension; // "file.FileName" Expression fileName = Expression.Property(fileParameter, typeof(IFile), "FileName"); // Building "file.FileName.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)" MethodCallExpression predicate = Expression.Call(fileName, EndsWithMethodInfo, Expression.Constant(suffix), IgnoreCaseConstantExpression); if (body == null) { // file => file.FileName.EndsWith(extension, StringComparison.OrdinalIgnoreCase); body = predicate; } else { // body = (.....) || file.FileName.EndsWith(extension, StringComparison.OrdinalIgnoreCase; body = Expression.OrElse(body, predicate); } } var result = Expression.Lambda<Func<IMediaFile, bool>>(body, fileParameter); _expressionCache.Add(allowedFileExtensions, result); return result; } } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/MediaFolderSelectorWidget.cs ================================================ using System; using System.Linq; using System.Xml.Linq; using System.Collections.Generic; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; using Composite.Data; using System.Reflection; using Composite.Core.Types; using Composite.Data.Types; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider { internal sealed class MediaFileFolderSelectorWidget : CompositeWidgetFunctionBase { private const string _functionName = "MediaFileFolderSelector"; public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + "." + _functionName; public MediaFileFolderSelectorWidget(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(DataReference<IMediaFileFolder>), entityTokenFactory) { } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { XElement widgetMarkup = base.BuildBasicWidgetMarkup("DataReferenceSelector", "Selected", label, help, bindingSourceName); widgetMarkup.Add(new XElement("DataReferenceSelector.DataType", typeof(IMediaFileFolder).AssemblyQualifiedName)); return widgetMarkup; } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/SelectorWidgetFunction.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.Core.Xml; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider { internal sealed class SelectorWidgetFunction : CompositeWidgetFunctionBase { private const string _functionName = "Selector"; public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + "." + _functionName; private const string Parameter_Options = "Options"; private const string Parameter_KeyFieldName = "KeyFieldName"; private const string Parameter_LabelFieldName = "LabelFieldName"; private const string Parameter_Required = "Required"; public static IEnumerable GetOptions(string optionsDescriptorSerialized) { // DDZ: This method seem not to be used any more XElement optionsDescriptor = XElement.Parse(optionsDescriptorSerialized); string keyFieldName = optionsDescriptor.Attribute("KeyFieldName").Value; string labelFieldName = optionsDescriptor.Attribute("LabelFieldName").Value; XElement treeNodeElement = optionsDescriptor.Element("TreeNode").Elements().First(); BaseRuntimeTreeNode runtimeTreeNode = FunctionFacade.BuildTree(treeNodeElement); IEnumerable optionsSource = runtimeTreeNode.GetValue<IEnumerable>(); if (optionsSource is IEnumerable<XElement>) { IEnumerable<XElement> optionElements = (IEnumerable<XElement>)optionsSource; foreach (XElement optionElement in optionElements) { yield return new { Key = optionElement.Attribute(keyFieldName).Value, Label = optionElement.Attribute(labelFieldName).Value }; } } else if (optionsSource is IDictionary) { IDictionary optionsDictionary = (IDictionary)optionsSource; foreach (var optionKey in optionsDictionary.Keys) { yield return new { Key = optionKey, Label = optionsDictionary[optionKey] }; } } else if (string.IsNullOrEmpty(keyFieldName) == false || string.IsNullOrEmpty(labelFieldName)) { foreach (object optionObject in optionsSource) { if (optionObject != null) { Type objectType = optionObject.GetType(); string key = (string.IsNullOrEmpty(keyFieldName) ? optionObject.ToString() : objectType.GetProperty(keyFieldName).GetValue(optionObject, null).ToString()); string label = (string.IsNullOrEmpty(labelFieldName) ? optionObject.ToString() : objectType.GetProperty(labelFieldName).GetValue(optionObject, null).ToString()); yield return new { Key = key, Label = label }; } } } else { foreach (var option in optionsSource) { yield return new { Key = option, Label = option }; } } } public SelectorWidgetFunction(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(object), entityTokenFactory) { SetParameterProfiles(); } private void SetParameterProfiles() { base.AddParameterProfile( new ParameterProfile(Parameter_Options, typeof(IEnumerable), true, new NoValueValueProvider(), null, null, "Options", new HelpDefinition("A list of elements to use as options. Expected types are IEnumerable (simple lists) and Dictionary."))); base.AddParameterProfile( new ParameterProfile(Parameter_KeyFieldName, typeof(string), false, new ConstantValueProvider(null), StandardWidgetFunctions.TextBoxWidget, null, "Source key field name", new HelpDefinition("If your option source returns a list of objects or XElements, use this field to specify the name of the field (property) to use for key values. Leave this empty to use the source option value as a string."))); base.AddParameterProfile( new ParameterProfile(Parameter_LabelFieldName, typeof(string), false, new ConstantValueProvider(null), StandardWidgetFunctions.TextBoxWidget, null, "Source label field name", new HelpDefinition("If your option source returns a list of objects or XElements, use this field to specify the name of the field (property) to use for labels. Leave this empty to use the source option value as a string."))); base.AddParameterProfile( new ParameterProfile("Required", typeof(bool), false, new ConstantValueProvider(true), StandardWidgetFunctions.GetBoolSelectorWidget("Yes, selection is required", "No, a 'none' selection is allowed.") , null, "Selection required", new HelpDefinition("When true the user is forced to make a selection. This feature is not available when 'multiple selection' is enabled."))); } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition helpDefinition, string bindingSourceName) { BaseRuntimeTreeNode runtimeTreeNode; if (!parameters.TryGetParameterRuntimeTreeNode(Parameter_Options, out runtimeTreeNode)) { throw new InvalidOperationException("Could not get BaseRuntimeTreeNode for parameter 'Options'."); } const string selectorName = "KeySelector"; IEnumerable options = runtimeTreeNode.GetValue<IEnumerable>(); IDictionary dictionaryOptions = options as IDictionary; XElement treeNodeElement = runtimeTreeNode.Serialize().Elements().First(); XElement functionMarkup = treeNodeElement; XElement selector = StandardWidgetFunctions.BuildBasicFormsMarkup( Namespaces.BindingFormsStdUiControls10, selectorName, "Selected", label, helpDefinition, bindingSourceName); if (dictionaryOptions != null) { selector.Add(new XAttribute("OptionsKeyField", "Key")); selector.Add(new XAttribute("OptionsLabelField", "Value")); } else { string keyFieldName = parameters.GetParameter<string>(Parameter_KeyFieldName); if (keyFieldName != null) { selector.Add(new XAttribute("OptionsKeyField", keyFieldName)); } string labelFieldName = parameters.GetParameter<string>(Parameter_LabelFieldName); if (labelFieldName != null) { selector.Add(new XAttribute("OptionsLabelField", labelFieldName)); } } bool required = parameters.GetParameter<bool>(Parameter_Required); selector.Add(new XAttribute("Required", required)); selector.Add(new XElement(selector.Name.Namespace + (selectorName + ".Options"), functionMarkup)); return selector; } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/StandardWidgetFunctionProvider.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Data; using Composite.Functions; using Composite.Functions.Plugins.WidgetFunctionProvider; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Bool; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.DataReference; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.DataType; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Date; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Decimal; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.GuidWidgetFunctions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Integer; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.String; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Utils; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider { [ConfigurationElementType(typeof(StandardWidgetFunctionProviderData))] internal sealed class StandardWidgetFunctionProvider : IDynamicTypeWidgetFunctionProvider { private EntityTokenFactory _entityTokenFactory; private WidgetFunctionNotifier _widgetFunctionNotifier; private List<IWidgetFunction> _widgetStaticTypeFunctions = null; private List<IWidgetFunction> _widgetDynamicTypeFunctions = null; public StandardWidgetFunctionProvider(string providerName) { _entityTokenFactory = new EntityTokenFactory(providerName); } public WidgetFunctionNotifier WidgetFunctionNotifier { set { _widgetFunctionNotifier = value; } } public IEnumerable<IWidgetFunction> Functions { get { if (_widgetStaticTypeFunctions == null) { InitializeStaticTypeFunctions(); } foreach (IWidgetFunction widgetFunction in _widgetStaticTypeFunctions) { yield return widgetFunction; } } } public IEnumerable<IWidgetFunction> DynamicTypeDependentFunctions { get { if (_widgetDynamicTypeFunctions == null) { InitializeDynamicTypeFunctions(); } foreach (IWidgetFunction widgetFunction in _widgetDynamicTypeFunctions) { yield return widgetFunction; } } } private void InitializeStaticTypeFunctions() { _widgetStaticTypeFunctions = new List<IWidgetFunction>(); _widgetStaticTypeFunctions.Add(new FormMarkupWidgetFuntion(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new TextBoxWidgetFuntion(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new TextAreaWidgetFuntion(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new String.SelectorWidgetFunction(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new String.HierarchicalSelectorWidgetFunction(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new TreeSelectorWidgetFunction(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new DataIdMultiSelectorWidgetFunction(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new String.VisualXhtmlEditorFuntion(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new String.UrlComboBoxWidgetFunction(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new XhtmlDocument.VisualXhtmlEditorFuntion(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new DateSelectorWidgetFunction(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new DateTimeSelectorWidgetFunction(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new MediaFileFolderSelectorWidget(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new MediaFileSelectorWidgetFunction(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new SelectorWidgetFunction(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new ImageSelectorWidgetFunction(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new IntegerTextBoxWidgetFuntion(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new DecimalTextBoxWidgetFuntion(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new GuidTextBoxWidgetFuntion(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new CheckBoxWidgetFuntion(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new BoolSelectorWidgetFuntion(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new DataTypeSelectorWidgetFunction(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new PageReferenceSelectorWidgetFunction(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new NullablePageReferenceSelectorWidgetFunction(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new FontIconSelectorWidgetFuntion(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new SvgIconSelectorWidgetFuntion(_entityTokenFactory)); _widgetStaticTypeFunctions.Add(new ConsoleIconSelectorWidgetFuntion(_entityTokenFactory)); } private void InitializeDynamicTypeFunctions() { _widgetDynamicTypeFunctions = new List<IWidgetFunction>(); List<Type> dataInterfaces = DataFacade.GetAllKnownInterfaces(UserType.Developer); // Is there a better way to add these interfaces? They should be added if the properties (keys) is // visible to the user when making a custom form. dataInterfaces.Add(typeof(Composite.Data.Types.IPageFolderDefinition)); dataInterfaces.Add(typeof(Composite.Data.Types.IPageMetaDataDefinition)); object[] args = new object[] { _entityTokenFactory }; _widgetDynamicTypeFunctions.AddRange( from t in dataInterfaces select (IWidgetFunction)Activator.CreateInstance(typeof(DataReferenceSelectorWidgetFunction<>).MakeGenericType(t), args)); _widgetDynamicTypeFunctions.AddRange( from t in dataInterfaces select (IWidgetFunction)Activator.CreateInstance(typeof(NullableDataReferenceSelectorWidgetFunction<>).MakeGenericType(t), args)); } } [Assembler(typeof(StandardWidgetFunctionProviderrAssembler))] internal sealed class StandardWidgetFunctionProviderData : WidgetFunctionProviderData { } internal sealed class StandardWidgetFunctionProviderrAssembler : IAssembler<IWidgetFunctionProvider, WidgetFunctionProviderData> { public IWidgetFunctionProvider Assemble(IBuilderContext context, WidgetFunctionProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new StandardWidgetFunctionProvider(objectConfiguration.Name); } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/StandardWidgetFunctionProviderEntityToken.cs ================================================ using Composite.C1Console.Security; using Composite.C1Console.Security.SecurityAncestorProviders; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider { [SecurityAncestorProvider(typeof(NoAncestorSecurityAncestorProvider))] internal sealed class StandardWidgetFunctionProviderEntityToken : EntityToken { private string _id; private string _source; public StandardWidgetFunctionProviderEntityToken(string source, string id) { _source = source; _id = id; } public override string Type { get { return ""; } } public override string Source { get { return _source; } } public override string Id { get { return _id; } } public override string Serialize() { return DoSerialize(); } public static EntityToken Deserialize(string serializedEntityToken) { string type, source, id; DoDeserialize(serializedEntityToken, out type, out source, out id); return new StandardWidgetFunctionProviderEntityToken(source, id); } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/String/DataIdMultiSelectorWidgetFunction.cs ================================================ using System; using System.Collections; using System.Linq; using System.Xml.Linq; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.DataReference; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; using Composite.Core.Types; using Composite.Core.Xml; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.String { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class DataIdMultiSelectorWidgetFunction : CompositeWidgetFunctionBase { private const string _functionName = "DataIdMultiSelector"; internal const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".String." + _functionName; /// <summary> /// Is called through reflection /// </summary> /// <exclude /> public static IEnumerable GetOptions(string typeManagerName) { return GetOptionsCommon.GetOptions(typeManagerName); } /// <exclude /> public DataIdMultiSelectorWidgetFunction(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(string), entityTokenFactory) { SetParameterProfiles(); } private void SetParameterProfiles() { ParameterProfile dataTypePP = new ParameterProfile("OptionsType", typeof(Type), true, new NoValueValueProvider(), StandardWidgetFunctions.DataTypeSelectorWidget, null, "Data type to select from", new HelpDefinition("The list of options the user can choose from will be selected from this type.")); base.AddParameterProfile(dataTypePP); ParameterProfile compactModePP = new ParameterProfile("CompactMode", typeof(bool), false, new ConstantValueProvider(false), StandardWidgetFunctions.GetBoolSelectorWidget("Compact", "Verbose"), null, "Compact UI", new HelpDefinition("When true, a more compact representation of long option lists is used. Default is false (verbose).")); base.AddParameterProfile(compactModePP); } /// <exclude /> public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition helpDefinition, string bindingSourceName) { Type optionsType = parameters.GetParameter<Type>("OptionsType"); bool compactMode = parameters.GetParameter<bool>("CompactMode"); return BuildStaticCallPopulatedSelectorFormsMarkup( parameters, label, helpDefinition, bindingSourceName, this.GetType(), "GetOptions", TypeManager.SerializeType(optionsType), "Key", "Label", false, compactMode); } private static XElement BuildStaticCallPopulatedSelectorFormsMarkup(ParameterList parameters, string label, HelpDefinition helpDefinition, string bindingSourceName, Type optionsGeneratingStaticType, string optionsGeneratingStaticMethodName, object optionsGeneratingStaticMethodParameterValue, string optionsObjectKeyPropertyName, string optionsObjectLabelPropertyName, bool required, bool compactMode) { string tagName = "MultiKeySelector"; XElement selector = StandardWidgetFunctions.BuildBasicFormsMarkup(Namespaces.BindingFormsStdUiControls10, tagName, "SelectedAsString", label, helpDefinition, bindingSourceName); XNamespace f = Namespaces.BindingFormsStdFuncLib10; selector.Add( new XAttribute("OptionsKeyField", optionsObjectKeyPropertyName), new XAttribute("OptionsLabelField", optionsObjectLabelPropertyName), new XAttribute("Required", required), new XAttribute("CompactMode", compactMode), new XElement(selector.Name.Namespace + (tagName + ".Options"), new XElement(f + "StaticMethodCall", new XAttribute("Type", TypeManager.SerializeType(optionsGeneratingStaticType)), new XAttribute("Method", optionsGeneratingStaticMethodName)))); if (optionsGeneratingStaticMethodParameterValue != null) selector.Descendants(f + "StaticMethodCall").First().Add( new XAttribute("Parameters", optionsGeneratingStaticMethodParameterValue)); return selector; } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/String/FontIconSelectorWidgetFuntion.cs ================================================ using System; using System.Xml.Linq; using System.Collections.Generic; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; using Composite.Core.Xml; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.String { internal sealed class FontIconSelectorWidgetFuntion : CompositeWidgetFunctionBase { private const string _functionName = "FontIconSelector"; /// <exclude /> public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".String." + _functionName; /// <exclude /> public const string ClassNameOptionsParameterName = "ClassNameOptions"; public const string StylesheetPathParameterName = "StylesheetPath"; public const string ClassNamePrefixParameterName = "ClassNamePrefix"; public FontIconSelectorWidgetFuntion(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(string), entityTokenFactory) { base.AddParameterProfile( new ParameterProfile(FontIconSelectorWidgetFuntion.ClassNameOptionsParameterName, typeof(object), true, new ConstantValueProvider(null), StandardWidgetFunctions.TextAreaWidget, null, "Class Name Options", new HelpDefinition("A list of class names the user should be able to choose from. Pass in a (comma seperated) string, a IEnumerable<string> or a Dictionary<string,string>."))); base.AddParameterProfile( new ParameterProfile(FontIconSelectorWidgetFuntion.StylesheetPathParameterName, typeof(string), true, new ConstantValueProvider(null), StandardWidgetFunctions.TextBoxWidget, null, "Stylesheet Path", new HelpDefinition("Path to style sheet containing class name definitions and web font include. Example: ~/Frontend/styles/glyphicons.less"))); base.AddParameterProfile( new ParameterProfile(FontIconSelectorWidgetFuntion.ClassNamePrefixParameterName, typeof(string), false, new ConstantValueProvider(""), StandardWidgetFunctions.TextBoxWidget, null, "Class Name Prefix", new HelpDefinition("String to always prepend to the class name options for font icons to be shown in drop down. Bootstrap Example: 'glyphicon glyphicon-'"))); } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { string stylesheetPath = parameters.GetParameter<string>(FontIconSelectorWidgetFuntion.StylesheetPathParameterName); string classNamePrefix = parameters.GetParameter<string>(FontIconSelectorWidgetFuntion.ClassNamePrefixParameterName); XElement formElement = base.BuildBasicWidgetMarkup("FontIconSelector", "SelectedClassName", label, help, bindingSourceName); formElement.Add(new XElement(Namespaces.BindingFormsStdUiControls10+"FontIconSelector.ClassNameOptions", GetClassNameOptionsValueNodes(parameters))); formElement.Add(new XAttribute("StylesheetPath", stylesheetPath)); formElement.Add(new XAttribute("ClassNamePrefix", classNamePrefix)); return formElement; } private IEnumerable<XNode> GetClassNameOptionsValueNodes(ParameterList parameters) { BaseRuntimeTreeNode classNameOptionsRuntimeTreeNode = null; if (parameters.TryGetParameterRuntimeTreeNode(FontIconSelectorWidgetFuntion.ClassNameOptionsParameterName, out classNameOptionsRuntimeTreeNode)) { object value = parameters.GetParameter(FontIconSelectorWidgetFuntion.ClassNameOptionsParameterName); if (value is string) { yield return new XText((string)value); } else { foreach (var node in classNameOptionsRuntimeTreeNode.Serialize().Nodes()) { yield return node; } } } } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/String/HierarchicalSelectorWidgetFunction.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; using Composite.C1Console.Forms.CoreUiControls; using Composite.Core.Xml; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.String { internal sealed class HierarchicalSelectorWidgetFunction : CompositeWidgetFunctionBase { private const string _functionName = "HierarchicalSelector"; public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".String." + _functionName; public HierarchicalSelectorWidgetFunction(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(string), entityTokenFactory) { SetParameterProfiles(); } private void SetParameterProfiles() { base.AddParameterProfile( new ParameterProfile("TreeNodes", typeof(IEnumerable<SelectionTreeNode>), true, new NoValueValueProvider(), null, null, "Tree Nodes", new HelpDefinition("The structure to use for building hierarchy for selection. Call a function that return IEnumerable<SelectionTreeNode>."))); base.AddParameterProfile( new ParameterProfile("Required", typeof(bool), false, new ConstantValueProvider(true), StandardWidgetFunctions.GetBoolSelectorWidget("Yes, selection is required", "No, a 'none' selection is allowed.") , null, "Selection required", new HelpDefinition("When true the user is forced to make a selection. This feature is not available when 'multiple selection' is enabled."))); base.AddParameterProfile( new ParameterProfile("AutoSelectChildren", typeof(bool), false, new ConstantValueProvider(false), StandardWidgetFunctions.GetBoolSelectorWidget("Yes, auto select child elements.", "No, only one selection on click."), null, "Auto select children", new HelpDefinition("When true a selection will automatically select all descendant elements in the hierarchy."))); base.AddParameterProfile( new ParameterProfile("AutoSelectParents", typeof(bool), false, new ConstantValueProvider(false), StandardWidgetFunctions.GetBoolSelectorWidget("Yes, auto select parents.", "No, only one selection on click."), null, "Auto select parents", new HelpDefinition("When true a selection will automatically select all ancestor elements in the hierarchy."))); } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition helpDefinition, string bindingSourceName) { BaseRuntimeTreeNode optionsRuntimeTreeNode = null; if (parameters.TryGetParameterRuntimeTreeNode("TreeNodes", out optionsRuntimeTreeNode)) { bool required = parameters.GetParameter<bool>("Required"); bool autoSelectChildren = parameters.GetParameter<bool>("AutoSelectChildren"); bool autoSelectParents = parameters.GetParameter<bool>("AutoSelectParents"); XElement formElement = base.BuildBasicWidgetMarkup("HierarchicalSelector", "SelectedKeys", label, helpDefinition, bindingSourceName); formElement.Add(new XElement(Namespaces.BindingFormsStdUiControls10 + "HierarchicalSelector.TreeNodes", optionsRuntimeTreeNode.Serialize())); formElement.Add(new XAttribute("AutoSelectChildren", autoSelectChildren)); formElement.Add(new XAttribute("AutoSelectParents", autoSelectParents)); return formElement; } else { throw new InvalidOperationException("Could not get BaseRuntimeTreeNode for parameter 'TreeNodes'."); } } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/String/SelectorWidgetFunction.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.String { internal sealed class SelectorWidgetFunction : CompositeWidgetFunctionBase { private const string _functionName = "Selector"; public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".String." + _functionName; public static IEnumerable GetOptions(string optionsDescriptorSerialized) { XElement optionsDescriptor = XElement.Parse(optionsDescriptorSerialized); string keyFieldName = optionsDescriptor.Attribute("KeyFieldName").Value; string labelFieldName = optionsDescriptor.Attribute("LabelFieldName").Value; XElement treeNodeElement = optionsDescriptor.Element("TreeNode").Elements().First(); BaseRuntimeTreeNode runtimeTreeNode = FunctionFacade.BuildTree(treeNodeElement); IEnumerable optionsSource = runtimeTreeNode.GetValue<IEnumerable>(); if (optionsSource is IEnumerable<XElement>) { IEnumerable<XElement> optionElements = (IEnumerable<XElement>)optionsSource; foreach (XElement optionElement in optionElements) { yield return new { Key = optionElement.Attribute(keyFieldName).Value, Label = optionElement.Attribute(labelFieldName).Value }; } } else if (optionsSource is IDictionary) { IDictionary optionsDictionary = (IDictionary)optionsSource; foreach (var optionKey in optionsDictionary.Keys) { yield return new { Key = optionKey, Label = optionsDictionary[optionKey] }; } } else if (string.IsNullOrEmpty(keyFieldName) == false || string.IsNullOrEmpty(labelFieldName)) { foreach (object optionObject in optionsSource) { if (optionObject != null) { Type objectType = optionObject.GetType(); string key = (string.IsNullOrEmpty(keyFieldName) ? optionObject.ToString() : objectType.GetProperty(keyFieldName).GetValue(optionObject, null).ToString()); string label = (string.IsNullOrEmpty(labelFieldName) ? optionObject.ToString() : objectType.GetProperty(labelFieldName).GetValue(optionObject, null).ToString()); yield return new { Key = key, Label = label }; } } } else { foreach (var option in optionsSource) { yield return new { Key = option, Label = option }; } } } private const string _compositeNameBase = CompositeWidgetFunctionBase.CommonNamespace + ".DataReference."; public SelectorWidgetFunction(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(string), entityTokenFactory) { SetParameterProfiles(); } private void SetParameterProfiles() { base.AddParameterProfile( new ParameterProfile("Options", typeof(IEnumerable), true, new NoValueValueProvider(), null, null, "Options", new HelpDefinition("A list of elements to use as options. Expected types are IEnumerable (simple lists) and Dictionary."))); base.AddParameterProfile( new ParameterProfile("KeyFieldName", typeof(string), false, new ConstantValueProvider(null), StandardWidgetFunctions.TextBoxWidget, null, "Source key field name", new HelpDefinition("If your option source returns a list of objects or XElements, use this field to specify the name of the field (property) to use for key values. Leave this empty to use the source option value as a string."))); base.AddParameterProfile( new ParameterProfile("LabelFieldName", typeof(string), false, new ConstantValueProvider(null), StandardWidgetFunctions.TextBoxWidget, null, "Source label field name", new HelpDefinition("If your option source returns a list of objects or XElements, use this field to specify the name of the field (property) to use for labels. Leave this empty to use the source option value as a string."))); base.AddParameterProfile( new ParameterProfile("Required", typeof(bool), false, new ConstantValueProvider(true), StandardWidgetFunctions.GetBoolSelectorWidget("Yes, selection is required", "No, a 'none' selection is allowed.") , null, "Selection required", new HelpDefinition("When true the user is forced to make a selection. This feature is not available when 'multiple selection' is enabled."))); base.AddParameterProfile( new ParameterProfile("Multiple", typeof(bool), false, new ConstantValueProvider(false), StandardWidgetFunctions.GetBoolSelectorWidget("Yes, allow multiple selections.", "No, allow only one selection."), null, "Multiple selection", new HelpDefinition("When true the user can select zero, one or more values. The selected values will be joined in a comma seperated string like 'A,B,C'."))); base.AddParameterProfile( new ParameterProfile("Compact", typeof(bool), false, new ConstantValueProvider(false), StandardWidgetFunctions.GetBoolSelectorWidget("Yes, use compact/popup UI.", "No, show all options."), null, "Compact mode", new HelpDefinition("When true the UI element will be compact."))); } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition helpDefinition, string bindingSourceName) { BaseRuntimeTreeNode runtimeTreeNode = null; if (parameters.TryGetParameterRuntimeTreeNode("Options", out runtimeTreeNode)) { string keyFieldName = parameters.GetParameter<string>("KeyFieldName"); string labelFieldName = parameters.GetParameter<string>("LabelFieldName"); bool multiple = parameters.GetParameter<bool>("Multiple"); bool required = parameters.GetParameter<bool>("Required"); bool compact = parameters.GetParameter<bool>("Compact"); XElement optionsDescriptor = new XElement("SelectorOptionsSource", new XAttribute("KeyFieldName", parameters.GetParameter<string>("KeyFieldName") ?? ""), new XAttribute("LabelFieldName", parameters.GetParameter<string>("LabelFieldName") ?? ""), new XElement("TreeNode", runtimeTreeNode.Serialize())); return StandardWidgetFunctions.BuildStaticCallPopulatedSelectorFormsMarkup( parameters, label, helpDefinition, bindingSourceName, this.GetType(), "GetOptions", optionsDescriptor.ToString(), "Key", "Label", multiple, compact, required, true); } else { throw new InvalidOperationException("Could not get BaseRuntimeTreeNode for parameter 'Options'."); } } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/String/TextAreaWidgetFunction.cs ================================================ using System; using System.Xml.Linq; using System.Collections.Generic; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.String { internal sealed class TextAreaWidgetFuntion : CompositeWidgetFunctionBase { private const string _functionName = "TextArea"; /// <exclude /> public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".String." + _functionName; /// <exclude /> public const string SpellCheckParameterName = "SpellCheck"; public TextAreaWidgetFuntion(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(string), entityTokenFactory) { ParameterProfile spellCheckPP = new ParameterProfile(TextAreaWidgetFuntion.SpellCheckParameterName, typeof(bool), false, new ConstantValueProvider(true), StandardWidgetFunctions.GetBoolSelectorWidget("Allow spell checking","Do not allow spell checking"), null, "Spell check", new HelpDefinition("By default text will be spell checked (when available). You should explicitly disable spell checking on fields that contain e-mails, code values etc. not suitable for spell checking. ")); base.AddParameterProfile(spellCheckPP); } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { bool spellCheck = parameters.GetParameter<bool>(TextAreaWidgetFuntion.SpellCheckParameterName); XElement formElement = base.BuildBasicWidgetMarkup("TextArea", "Text", label, help, bindingSourceName); formElement.Add(new XAttribute("SpellCheck", spellCheck)); return formElement; } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/String/TextBoxWidgetFuntion.cs ================================================ using System; using System.Xml.Linq; using System.Collections.Generic; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.String { internal sealed class TextBoxWidgetFuntion : CompositeWidgetFunctionBase { private const string _functionName = "TextBox"; /// <exclude /> public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".String." + _functionName; /// <exclude /> public const string SpellCheckParameterName = "SpellCheck"; public TextBoxWidgetFuntion(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(string), entityTokenFactory) { ParameterProfile spellCheckPP = new ParameterProfile(TextBoxWidgetFuntion.SpellCheckParameterName, typeof(bool), false, new ConstantValueProvider(true), StandardWidgetFunctions.GetBoolSelectorWidget("Allow spell checking", "Do not allow spell checking"), null, "Spell check", new HelpDefinition("By default text will be spell checked (when available). You should explicitly disable spell checking on fields that contain e-mails, code values etc. not suitable for spell checking. ")); base.AddParameterProfile(spellCheckPP); } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { bool spellCheck = parameters.GetParameter<bool>(TextBoxWidgetFuntion.SpellCheckParameterName); XElement formElement = base.BuildBasicWidgetMarkup("TextBox", "Text", label, help, bindingSourceName); formElement.Add(new XAttribute("SpellCheck", spellCheck)); return formElement; } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/String/TreeSelectorWidgetFunction.cs ================================================ using System.Xml.Linq; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; using Composite.C1Console.Forms.CoreUiControls; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.String { internal sealed class TreeSelectorWidgetFunction : CompositeWidgetFunctionBase { private const string FunctionName = "TreeSelector"; public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".String." + FunctionName; public TreeSelectorWidgetFunction(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(string), entityTokenFactory) { SetParameterProfiles(); } private void SetParameterProfiles() { base.AddParameterProfile( new ParameterProfile(nameof(TreeSelectorUiControl.ElementProvider), typeof(string), true, new ConstantValueProvider(string.Empty), StandardWidgetFunctions.TextBoxWidget, null, "Element Provider", new HelpDefinition("The name of a tree element provider (as defined in Composite.config)"))); base.AddParameterProfile( new ParameterProfile(nameof(TreeSelectorUiControl.SelectableElementReturnValue), typeof(string), true, new ConstantValueProvider("EntityToken"), StandardWidgetFunctions.TextBoxWidget, null, "Element field to return", new HelpDefinition("The name of the element field whose value to return for selection. Typical values here can be DataId (for data trees), Uri (for linkable elements), or EntityToken (for any element). Element providers may provide more fields."))); base.AddParameterProfile( new ParameterProfile(nameof(TreeSelectorUiControl.SelectableElementPropertyName), typeof(string), false, new ConstantValueProvider(string.Empty), StandardWidgetFunctions.TextBoxWidget, null, "Selection filter, Property Name", new HelpDefinition("An element must have this field to be selectable."))); base.AddParameterProfile( new ParameterProfile(nameof(TreeSelectorUiControl.SelectableElementPropertyValue), typeof(string), false, new ConstantValueProvider(string.Empty), StandardWidgetFunctions.TextBoxWidget, null, "Selection filter, Property Value", new HelpDefinition("The value of the property optionally used (if provided) to further identify a selectable tree element by. Seperate multiple values with spaces."))); base.AddParameterProfile( new ParameterProfile(nameof(TreeSelectorUiControl.SerializedSearchToken), typeof(string), false, new ConstantValueProvider(string.Empty), StandardWidgetFunctions.TextBoxWidget, null, "Search Token", new HelpDefinition("A search token, serialized, to filter which tree elements is shown. To filter what is selectable, use the 'Selection filter' properties."))); base.AddParameterProfile( new ParameterProfile(nameof(TreeSelectorUiControl.Required), typeof(bool), false, new ConstantValueProvider(true), StandardWidgetFunctions.GetBoolSelectorWidget("Yes, selection is required", "No, a 'none' selection is allowed."), null, "Required", new HelpDefinition("An option that indicates whether the user is required to make a selection"))); } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition helpDefinition, string bindingSourceName) { XElement formElement = base.BuildBasicWidgetMarkup("TreeSelector", nameof(TreeSelectorUiControl.SelectedKey), label, helpDefinition, bindingSourceName); foreach (var propertyName in new [] { nameof(TreeSelectorUiControl.ElementProvider), nameof(TreeSelectorUiControl.SelectableElementReturnValue), nameof(TreeSelectorUiControl.SelectableElementPropertyName), nameof(TreeSelectorUiControl.SelectableElementPropertyValue), nameof(TreeSelectorUiControl.SerializedSearchToken), nameof(TreeSelectorUiControl.Required) }) { string propertyValue = parameters.GetParameter<string>(propertyName); formElement.Add(new XAttribute(propertyName, propertyValue)); } return formElement; } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/String/UrlComboBoxWidgetFunction.cs ================================================ using System; using System.Xml.Linq; using System.Collections.Generic; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.String { internal sealed class UrlComboBoxWidgetFunction : CompositeWidgetFunctionBase { private const string _functionName = "UrlComboBox"; /// <exclude /> public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".String." + _functionName; public UrlComboBoxWidgetFunction(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(string), entityTokenFactory) { } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { XElement formElement = base.BuildBasicWidgetMarkup("UrlComboBox", "Text", label, help, bindingSourceName); return formElement; } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/String/VisualXhtmlEditorWidgetFuntion.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.Core.Extensions; using Composite.Core.PageTemplates; using Composite.Core.Types; using Composite.Data.Types; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.String { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public sealed class VisualXhtmlEditorFuntion : CompositeWidgetFunctionBase { private const string _functionName = "VisualXhtmlEditor"; /// <exclude /> public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".String." +_functionName; /// <exclude /> public const string ClassConfigurationNameParameterName = "ClassConfigurationName"; /// <exclude /> public const string ContainerClassesParameterName = "ContainerClasses"; /// <exclude /> public const string PreviewPageIdParameterName = "PreviewPageId"; /// <exclude /> public const string PreviewTemplateIdParameterName = "PreviewTemplateId"; /// <exclude /> public const string PreviewPlaceholderParameterName = "PreviewPlaceholder"; /// <exclude /> private const string DefaultConfiguration = "common"; /// <exclude /> public VisualXhtmlEditorFuntion(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(string), entityTokenFactory) { BuildParameterProfiles(); } /// <exclude /> public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { XElement element = base.BuildBasicWidgetMarkup("InlineXhtmlEditor", "Xhtml", label, help, bindingSourceName); element.Add(new XAttribute("ClassConfigurationName", parameters.GetParameter<string>(ClassConfigurationNameParameterName))); var pageId = parameters.GetParameter<Guid>(PreviewPageIdParameterName); var templateId = parameters.GetParameter<Guid>(PreviewTemplateIdParameterName); string placeholderName = parameters.GetParameter<string>(PreviewPlaceholderParameterName); string containerClasses = parameters.GetParameter<string>(ContainerClassesParameterName); if (pageId != Guid.Empty) { element.Add(new XAttribute("PreviewPageId", pageId)); } if (templateId != Guid.Empty) { element.Add(new XAttribute("PreviewTemplateId", templateId)); } if (!string.IsNullOrEmpty(placeholderName)) { element.Add(new XAttribute("PreviewPlaceholder", placeholderName)); } if (!string.IsNullOrWhiteSpace(containerClasses)) { element.Add(new XAttribute("ContainerClasses", containerClasses)); } return element; } private void BuildParameterProfiles() { // TODO: localize base.AddParameterProfile(new ParameterProfile(ClassConfigurationNameParameterName, typeof(string), false, new ConstantValueProvider(DefaultConfiguration), StandardWidgetFunctions.TextBoxWidget, null, "Class configuration name", new HelpDefinition("The visual editor can be configured to offer the editor a special set of class names for formatting xhtml elements. The default value is '" + DefaultConfiguration + "'") )); base.AddParameterProfile(new ParameterProfile(ContainerClassesParameterName, typeof(string), false, new ConstantValueProvider(""), StandardWidgetFunctions.TextBoxWidget, null, "Container Classes", new HelpDefinition("Class names to attach to the editor (for styling) and to use for filtering components. Seperate multiple names with space or comma.") )); BuildInlineXhtmlEditorParameters().ForEach(AddParameterProfile); } internal static IEnumerable<ParameterProfile> BuildInlineXhtmlEditorParameters() { // TODO: localize var templateSelectorWidget = StandardWidgetFunctions.DropDownList( typeof(VisualXhtmlEditorFuntion), StaticReflection.GetMethodInfo(() => PageTemplates()).Name, "Key", "Value", false, false); yield return new ParameterProfile(PreviewTemplateIdParameterName, typeof(Guid), false, new ConstantValueProvider(Guid.Empty), templateSelectorWidget, null, "Page template for preview", new HelpDefinition("Page template to be used while generating preview images for the C1 functions calls.")); yield return new ParameterProfile(PreviewPlaceholderParameterName, typeof(string), false, new ConstantValueProvider(null), StandardWidgetFunctions.TextBoxWidget, null, "Page placeholder for preview", new HelpDefinition("Page placeholder to be used while generating preview images for the C1 functions calls. If not specified, the default placeholder for the selected template will be used.") ); yield return new ParameterProfile(PreviewPageIdParameterName, typeof(Guid), false, new ConstantValueProvider(Guid.Empty), StandardWidgetFunctions.GetDataReferenceWidget<IPage>(), null, "Page for preview", new HelpDefinition("Page template to be used while generating preview images. Certain fuctions may require page information for previewing.")); } private static IEnumerable<KeyValuePair<Guid, string>> PageTemplates() { return PageTemplateFacade.GetPageTemplates() .OrderBy(p => p.Title) .Select(p => new KeyValuePair<Guid, string>(p.Id, p.Title)); } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/Type/DataTypeSelectorWidgetFunction.cs ================================================ using System; using System.Collections; using System.Xml.Linq; using Composite.Data; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; using Composite.Core.Xml; using Composite.Core.Types; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.DataType { internal sealed class DataTypeSelectorWidgetFunction : CompositeWidgetFunctionBase { public static IEnumerable GetOptions() { return DataFacade.GetAllKnownInterfaces(UserType.Developer); //.Where(f=>f.Namespace.StartsWith(typeof(Composite.Data.Types.IPage).Namespace)==false).ToList(); } private const string _functionName = "DataTypeSelector"; public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".Type." + _functionName; public DataTypeSelectorWidgetFunction(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(Type), entityTokenFactory) { } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition helpDefinition, string bindingSourceName) { string tagName = "TypeSelector"; XElement selector = StandardWidgetFunctions.BuildBasicFormsMarkup(Namespaces.BindingFormsStdUiControls10, tagName, "SelectedType", label, helpDefinition, bindingSourceName); XNamespace f = Namespaces.BindingFormsStdFuncLib10; selector.Add( new XElement(selector.Name.Namespace + (tagName + ".TypeOptions"), new XElement(f + "StaticMethodCall", new XAttribute("Type", TypeManager.SerializeType(this.GetType())), new XAttribute("Method", "GetOptions")))); return selector; } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/Utils/ConsoleIconSelectorWidgetFuntion.cs ================================================ using System.Xml.Linq; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Utils { internal sealed class ConsoleIconSelectorWidgetFuntion : CompositeWidgetFunctionBase { private const string _functionName = "ConsoleIconSelector"; /// <exclude /> public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".Utils." + _functionName; public ConsoleIconSelectorWidgetFuntion(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(string), entityTokenFactory) { } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { XElement formElement = base.BuildBasicWidgetMarkup("ConsoleIconSelector", "Selected", label, help, bindingSourceName); return formElement; } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/Utils/FormMarkupWidgetFuntion.cs ================================================ using System; using System.Linq; using System.Xml.Linq; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Utils { internal sealed class FormMarkupWidgetFuntion : CompositeWidgetFunctionBase { private const string _functionName = "FormMarkup"; /// <exclude /> public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".Utils." + _functionName; /// <exclude /> /// /// <exclude /> public const string MarkupParameterName = "Markup"; public FormMarkupWidgetFuntion(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(string), entityTokenFactory) { var markupParameterProfile = new ParameterProfile(MarkupParameterName, typeof(string), true, new ConstantValueProvider( @"<TextBox Label=""$label"" Help=""$help"" SpellCheck=""true""> <TextBox.Text> <cms:bind source=""$binding"" /> </TextBox.Text> </TextBox>"), StandardWidgetFunctions.TextAreaWidget, null, "Markup", new HelpDefinition("Markup will be inserted into result form markup. Macroses are: '$binding', '$label' and '$help'")); base.AddParameterProfile(markupParameterProfile); } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { string markup = parameters.GetParameter<string>(MarkupParameterName) ?? ""; if (string.IsNullOrWhiteSpace(markup)) { return null; } markup = @"<cms:formdefinition xmlns:cms=""http://www.composite.net/ns/management/bindingforms/1.0"" xmlns=""http://www.composite.net/ns/management/bindingforms/std.ui.controls.lib/1.0"">" + markup + "</cms:formdefinition>"; XElement xml = XElement.Parse(markup); foreach (var attribute in xml.Descendants().SelectMany(node => node.Attributes())) { attribute.Value = attribute.Value .Replace("$label", label) .Replace("$binding", bindingSourceName) .Replace("$help", help != null ? help.HelpText : ""); } return xml.Elements().FirstOrDefault(); } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/Utils/SvgIconSelectorWidgetFuntion.cs ================================================ using System.Xml.Linq; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Utils { internal sealed class SvgIconSelectorWidgetFuntion : CompositeWidgetFunctionBase { private const string _functionName = "SvgIconSelector"; /// <exclude /> public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".Utils." + _functionName; /// <exclude /> public const string SvgSpritePathParameterName = "SvgSpritePath"; public SvgIconSelectorWidgetFuntion(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(string), entityTokenFactory) { base.AddParameterProfile( new ParameterProfile(SvgIconSelectorWidgetFuntion.SvgSpritePathParameterName, typeof(string), true, new ConstantValueProvider(null), StandardWidgetFunctions.TextBoxWidget, null, "Svg Sprite Path", new HelpDefinition("Path to the SVG sprite. Example: ~/Composite/images/sprite.svg"))); } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { string spritePath = parameters.GetParameter<string>(SvgIconSelectorWidgetFuntion.SvgSpritePathParameterName); XElement formElement = base.BuildBasicWidgetMarkup("SvgIconSelector", "Selected", label, help, bindingSourceName); formElement.Add(new XAttribute("SvgSpritePath", spritePath)); return formElement; } } } ================================================ FILE: Composite/Plugins/Functions/WidgetFunctionProviders/StandardWidgetFunctionProvider/XhtmlDocument/VisualXhtmlEditorWidgetFuntion.cs ================================================ using System; using System.Xml.Linq; using System.Collections.Generic; using Composite.Core.Extensions; using Composite.Functions; using Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.Foundation; using Composite.Core.Types; using Composite.Core.Xml; using StringSelector = Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.String.VisualXhtmlEditorFuntion; namespace Composite.Plugins.Functions.WidgetFunctionProviders.StandardWidgetFunctionProvider.XhtmlDocument { internal sealed class VisualXhtmlEditorFuntion : CompositeWidgetFunctionBase { public static IEnumerable<Type> GetOptions(object typeManagerTypeName) { yield return TypeManager.GetType((string)typeManagerTypeName); } private const string _functionName = "VisualXhtmlEditor"; public const string CompositeName = CompositeWidgetFunctionBase.CommonNamespace + ".XhtmlDocument." + _functionName; public const string ClassConfigurationNameParameterName = "ClassConfigurationName"; public const string ContainerClassesParameterName = "ContainerClasses"; public const string EmbedableFieldTypeParameterName = "EmbedableFieldsType"; public VisualXhtmlEditorFuntion(EntityTokenFactory entityTokenFactory) : base(CompositeName, typeof(Composite.Core.Xml.XhtmlDocument), entityTokenFactory) { SetParameterProfiles("common"); } public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition help, string bindingSourceName) { XElement element = base.BuildBasicWidgetMarkup("InlineXhtmlEditor", "Xhtml", label, help, bindingSourceName); element.Add(new XAttribute("ClassConfigurationName", parameters.GetParameter<string>(VisualXhtmlEditorFuntion.ClassConfigurationNameParameterName))); var pageId = parameters.GetParameter<Guid>(StringSelector.PreviewPageIdParameterName); var templateId = parameters.GetParameter<Guid>(StringSelector.PreviewTemplateIdParameterName); string placeholderName = parameters.GetParameter<string>(StringSelector.PreviewPlaceholderParameterName); string containerClasses = parameters.GetParameter<string>(ContainerClassesParameterName); if (pageId != Guid.Empty) { element.Add(new XAttribute("PreviewPageId", pageId)); } if (templateId != Guid.Empty) { element.Add(new XAttribute("PreviewTemplateId", templateId)); } if (!string.IsNullOrEmpty(placeholderName)) { element.Add(new XAttribute("PreviewPlaceholder", placeholderName)); } if (!string.IsNullOrWhiteSpace(containerClasses)) { element.Add(new XAttribute("ContainerClasses", containerClasses)); } Type embedableFieldType = parameters.GetParameter<Type>(VisualXhtmlEditorFuntion.EmbedableFieldTypeParameterName); if (embedableFieldType!=null) { XNamespace f = Namespaces.BindingFormsStdFuncLib10; element.Add( new XElement(element.Name.Namespace + "InlineXhtmlEditor.EmbedableFieldsTypes", new XElement(f + "StaticMethodCall", new XAttribute("Type", TypeManager.SerializeType(this.GetType())), new XAttribute("Parameters", TypeManager.SerializeType(embedableFieldType)), new XAttribute("Method", "GetOptions")))); } return element; } private void SetParameterProfiles(string classConfigurationName) { base.AddParameterProfile(new ParameterProfile(VisualXhtmlEditorFuntion.ContainerClassesParameterName, typeof(string), false, new ConstantValueProvider(""), StandardWidgetFunctions.TextBoxWidget, null, "Container Classes", new HelpDefinition("Class names to attach to the editor (for styling) and to use for filtering components. Seperate multiple names with space or comma.") )); ParameterProfile classConfigNamePP = new ParameterProfile(VisualXhtmlEditorFuntion.ClassConfigurationNameParameterName, typeof(string), false, new ConstantValueProvider(classConfigurationName), StandardWidgetFunctions.TextBoxWidget, null, "Class configuration name", new HelpDefinition("The visual editor can be configured to offer the editor a special set of class names for formatting xhtml elements. The default value is '" + classConfigurationName + "'")); base.AddParameterProfile(classConfigNamePP); ParameterProfile typeNamePP = new ParameterProfile(VisualXhtmlEditorFuntion.EmbedableFieldTypeParameterName, typeof(Type), false, new ConstantValueProvider(null), StandardWidgetFunctions.DataTypeSelectorWidget, null, "Embedable fields, Data type", new HelpDefinition("If a data type is selected, fields from this type can be inserted into the xhtml.")); base.AddParameterProfile(typeNamePP); StringSelector.BuildInlineXhtmlEditorParameters().ForEach(AddParameterProfile); } } } ================================================ FILE: Composite/Plugins/Functions/XslExtensionsProviders/CaptchaXslExtension.cs ================================================ using System; using Composite.Core.WebClient.Captcha; using Composite.Plugins.Functions.XslExtensionsProviders.ConfigBasedXslExtensionsProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Functions.XslExtensionsProviders { [ConfigurationElementType(typeof(ConfigBasedXslExtensionInfo))] internal class CaptchaXslExtension { public string GetEncryptedValue(string oldValue) { if(EncryptedValueIsValid(oldValue)) { return oldValue; } return CreateEncryptedValue(); } public string CreateEncryptedValue() { return Captcha.CreateEncryptedValue(); } public string GetImageUrl(string encryptedCaptchaValue) { return Captcha.GetImageUrl(encryptedCaptchaValue); } public bool IsValid(string value, string encryptedValue) { return Captcha.IsValid(value, encryptedValue); } public bool EncryptedValueIsValid(string encryptedValue) { return Captcha.IsValid(encryptedValue); } public void RegisterUsage(string encryptedValue) { Captcha.RegisterUsage(encryptedValue); } public bool IsAlreadyUsed(string encryptedValue) { return Captcha.IsAlreadyUsed(encryptedValue); } public static bool Decrypt(string encryptedValue, out DateTime timestamp, out string value) { return Captcha.Decrypt(encryptedValue, out timestamp, out value); } } } ================================================ FILE: Composite/Plugins/Functions/XslExtensionsProviders/ConfigBasedXslExtensionsProvider/ConfigBasedXslExtensionsProvider.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Reflection; using Composite.Functions.Plugins.XslExtensionsProvider; using Composite.Core.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Functions.XslExtensionsProviders.ConfigBasedXslExtensionsProvider { [ConfigurationElementType(typeof(ConfigBasedXslExtensionsProviderData))] internal class ConfigBasedXslExtensionsProvider : IXslExtensionsProvider { private object _syncRoot = new object(); private List<KeyValuePair<string, ConstructorInfo>> _constructors; private ConfigBasedXslExtensionsProviderData _providerData; internal ConfigBasedXslExtensionsProvider(ConfigBasedXslExtensionsProviderData providerData) { _providerData = providerData; } public List<Pair<string, object>> CreateExtensions() { var result = new List<Pair<string, object>>(); if(_constructors == null) { lock(_syncRoot) { if(_constructors == null) { var constructors = new List<KeyValuePair<string, ConstructorInfo>>(); if (_providerData == null) { return result; } foreach (var configLine in _providerData.XslExtensions) { PropertyInformation propertyInformation = configLine.ElementInformation.Properties["type"]; if (propertyInformation == null) continue; Type type = propertyInformation.Value as Type; if (type == null) continue; ConstructorInfo constructor = type.GetConstructors()[0]; constructors.Add(new KeyValuePair<string, ConstructorInfo>(configLine.Name, constructor)); } // TODO: uncomment _constructors = constructors; } } } foreach(var pair in _constructors) { object instance = pair.Value.Invoke(new object[0]); result.Add(new Pair<string, object>(pair.Key, instance)); } return result; } } } ================================================ FILE: Composite/Plugins/Functions/XslExtensionsProviders/ConfigBasedXslExtensionsProvider/ConfigBasedXslExtensionsProviderData.cs ================================================ using System.Configuration; using Composite.Core.Configuration; using Composite.Functions.Plugins.XslExtensionsProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.Functions.XslExtensionsProviders.ConfigBasedXslExtensionsProvider { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Assembler(typeof(ConfigBasedXslExtensionsProviderAssembler))] internal sealed class ConfigBasedXslExtensionsProviderData: XslExtensionsProviderData { public const string SectionName = "Composite.XslExtensions"; private const string _xslExtensionsProperty = "xslExtensions"; [ConfigurationProperty(_xslExtensionsProperty)] public NameTypeManagerTypeConfigurationElementCollection<ConfigBasedXslExtensionInfo> XslExtensions { get { return (NameTypeManagerTypeConfigurationElementCollection<ConfigBasedXslExtensionInfo>)base[_xslExtensionsProperty]; } } } internal sealed class ConfigBasedXslExtensionsProviderAssembler : IAssembler<IXslExtensionsProvider, XslExtensionsProviderData> { public IXslExtensionsProvider Assemble(Microsoft.Practices.ObjectBuilder.IBuilderContext context, XslExtensionsProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { ConfigBasedXslExtensionsProviderData myConfiguration = (ConfigBasedXslExtensionsProviderData)objectConfiguration; return new ConfigBasedXslExtensionsProvider(myConfiguration); } } /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ConfigBasedXslExtensionInfo : NameTypeManagerTypeConfigurationElement { } } ================================================ FILE: Composite/Plugins/Functions/XslExtensionsProviders/StandardExtension.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Web; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using Composite.Functions; using Composite.Core.Logging; using Composite.Plugins.Functions.XslExtensionsProviders.ConfigBasedXslExtensionsProvider; using Composite.Core.Extensions; using Composite.Core.Xml; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Functions.XslExtensionsProviders { [ConfigurationElementType(typeof(ConfigBasedXslExtensionInfo))] internal class StandardExtension { public static readonly string XmlNamespace = "http://c1.composite.net/StandardFunctions"; private static readonly string EmailAddressRegex = @"^([a-zA-Z0-9_\-\+\.]+)@((\[[0-9]{1,3}" + @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"; private static readonly Regex _emailValidationRegex = new Regex(EmailAddressRegex); public object CacheFunctionCall(XPathNodeIterator nodeIterator, string cacheKey, int expirationInSeconds) { Verify.ArgumentNotNullOrEmpty(cacheKey, "cacheKey"); var cache = HttpRuntime.Cache; object value = cache[cacheKey]; if (value == null) { value = CallFunction(nodeIterator); cache.Add(cacheKey, value, null, DateTime.Now.AddSeconds(expirationInSeconds), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null); } return value; } public object CallFunction(XPathNodeIterator nodeIterator) { Verify.ArgumentNotNull(nodeIterator, "nodeIterator"); if (!nodeIterator.MoveNext()) { return string.Empty; } XPathNavigator navigator = nodeIterator.Current; XElement functionNode = GetXElement(navigator); if (functionNode == null) { LoggingService.LogWarning("StandardXslExtendion", "Failed to get a function definition."); return string.Empty; } BaseRuntimeTreeNode runtimeTreeNode = FunctionTreeBuilder.Build(functionNode); object result = runtimeTreeNode.GetValue(new FunctionContextContainer()); if (result is XElement) { return (result as XElement).CreateNavigator(); } if (result is IEnumerable<XElement>) { return new FunctionResultNodeIterator(result as IEnumerable<XElement>); } if(result is XhtmlDocument) { return (result as XhtmlDocument).Root.CreateNavigator(); } return result; } /// <summary> /// Checks whether an email address is valid. /// </summary> /// <param name="email">The email address.</param> /// <returns></returns> public bool IsEmailValid(string email) { if (email.IsNullOrEmpty()) { return false; } return _emailValidationRegex.IsMatch(email.Trim()); } /// <summary> /// Checks whether an email list is valid. /// </summary> /// <param name="emailList">The email list.</param> /// <returns></returns> public bool IsEmailListValid(string emailList) { var emails = emailList.Split(new[] {',', ';'}); return !emails.Any(email => !IsEmailValid(email.Trim())); } /// <summary> /// Gets an http form post value. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> public string GetFormData(string key) { var httpContext = HttpContext.Current; if (httpContext == null || httpContext.Request == null || httpContext.Request.Form == null) { return string.Empty; } return httpContext.Request.Form[key] ?? string.Empty; } /// <summary> /// Gets a query string parameter value. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> public string GetQueryStringValue(string key) { var httpContext = HttpContext.Current; if (httpContext == null || httpContext.Request == null || httpContext.Request.QueryString == null) { return string.Empty; } return httpContext.Request.QueryString[key] ?? string.Empty; } /// <summary> /// Gets a cookie's value. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> public string GetCookieValue(string key) { var httpContext = HttpContext.Current; if (httpContext == null || httpContext.Request == null || httpContext.Request.Cookies == null) { return string.Empty; } var cookie = httpContext.Request.Cookies[key]; return cookie != null ? cookie.Value : string.Empty; } protected static XElement GetXElement(XPathNavigator navigator) { XDocument xDoc = new XDocument(); using (XmlWriter xmlWriter = xDoc.CreateWriter()) navigator.WriteSubtree(xmlWriter); return xDoc.Root; } protected static XElement GetXElement(XmlNode node) { XDocument xDoc = new XDocument(); using (XmlWriter xmlWriter = xDoc.CreateWriter()) node.WriteTo(xmlWriter); return xDoc.Root; } protected static XmlNode GetXmlNode(XElement element) { using (XmlReader xmlReader = element.CreateReader()) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlReader); return xmlDoc; } } #region Nested classes internal class FunctionResultNodeIterator: XPathNodeIterator { private readonly IEnumerable<XElement> _innerEnumerable; private readonly IEnumerator<XElement> _iterator; private int _position; public FunctionResultNodeIterator(IEnumerable<XElement> innerEnumerable) { _innerEnumerable = innerEnumerable; _iterator = innerEnumerable.GetEnumerator(); } public override XPathNodeIterator Clone() { return new FunctionResultNodeIterator(_innerEnumerable); } public override XPathNavigator Current { get { return GetXmlNode(_iterator.Current).CreateNavigator(); } } public override int CurrentPosition { get { return _position; } } public override bool MoveNext() { bool result = _iterator.MoveNext(); if(result) { _position++; } return result; } } #endregion } } ================================================ FILE: Composite/Plugins/GlobalSettings/GlobalSettingsProviders/ConfigBasedGlobalSettingsProvider.cs ================================================ using Composite.Core.Configuration; using Composite.Core.Configuration.Plugins.GlobalSettingsProvider; using Composite.Core.Extensions; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; namespace Composite.Plugins.GlobalSettings.GlobalSettingsProviders { [ConfigurationElementType(typeof(ConfigBasedGlobalSettingsProviderData))] internal sealed class ConfigBasedGlobalSettingsProvider : IGlobalSettingsProvider { private readonly ConfigBasedGlobalSettingsProviderData _configurationData; private readonly ICachingSettings _cachingSettings; private readonly List<string> _nonProbeableAssemblyNames; public ConfigBasedGlobalSettingsProvider(ConfigBasedGlobalSettingsProviderData configurationData) { _configurationData = configurationData; _cachingSettings = new ConfigCachingSettings(configurationData.Caching); string cleannonProbeString = _configurationData.NonProbeableAssemblyNames.Replace(" ", ""); _nonProbeableAssemblyNames = new List<string>(cleannonProbeString.Split(',')); } public string AppCodeDirectory => _configurationData.AppCodeDirectory; public string ApplicationName => _configurationData.ApplicationName; public string ApplicationShortName => _configurationData.ApplicationShortName; public string BrandedVersionAssemblySource => _configurationData.BrandedVersionAssemblySource; public string DefaultCultureName => _configurationData.DefaultCultureName; public string ConfigurationDirectory => _configurationData.ConfigurationDirectory; public string GeneratedAssembliesDirectory => _configurationData.GeneratedAssembliesDirectory; public string SerializedWorkflowsDirectory => _configurationData.SerializedWorkflowsDirectory; public string SerializedConsoleMessagesDirectory => _configurationData.SerializedConsoleMessagesDirectory; public string BinDirectory => _configurationData.BinDirectory; public string TempDirectory => _configurationData.TempDirectory; public string CacheDirectory => _configurationData.CacheDirectory; public string PackageDirectory => _configurationData.PackageDirectory; public string AutoPackageInstallDirectory => _configurationData.AutoPackageInstallDirectory; public string TreeDefinitionsDirectory => _configurationData.TreeDefinitionsDirectory; public string PageTemplateFeaturesDirectory => _configurationData.PageTemplateFeaturesDirectory; public string DataMetaDataDirectory => _configurationData.DataMetaDataDirectory; public string InlineCSharpFunctionDirectory => _configurationData.InlineCSharpFunctionDirectory; public string PackageLicenseDirectory => _configurationData.PackageLicenseDirectory; public IEnumerable<string> NonProbableAssemblyNames => _nonProbeableAssemblyNames; public int ConsoleMessageQueueItemSecondToLive => _configurationData.ConsoleMessageQueueItemSecondToLive; public bool EnableDataTypesAutoUpdate => _configurationData.EnableDataTypesAutoUpdate; public bool BroadcastConsoleElementChanges => _configurationData.BroadcastConsoleElementChanges; public string AutoCreatedAdministratorUserName => _configurationData.AutoCreatedAdministratorUserName; public bool OnlyTranslateWhenApproved => _configurationData.OnlyTranslateWhenApproved; public bool AllowChildPagesTranslationWithoutParent => _configurationData.AllowChildPagesTranslationWithoutParent; public string WorkflowTimeout => _configurationData.WorkflowTimeout; public string ConsoleTimeout => _configurationData.ConsoleTimeout; public ICachingSettings Caching => _cachingSettings; public int ImageQuality => _configurationData.ImageQuality; public bool PrettifyPublicMarkup => _configurationData.PrettifyPublicMarkup; public bool PrettifyRenderFunctionExceptions => _configurationData.PrettifyRenderFunctionExceptions; public bool FunctionPreviewEnabled => _configurationData.FunctionPreviewEnabled; public TimeZoneInfo TimeZone => TimeZoneInfo.FindSystemTimeZoneById( _configurationData.TimeZone.IsNullOrEmpty() ? TimeZoneInfo.Local.Id : _configurationData.TimeZone); public bool InheritGlobalReadPermissionOnHiddenPerspectives => _configurationData.InheritGlobalReadPermissionOnHiddenPerspectives; public bool OmitAspNetWebFormsSupport => _configurationData.OmitAspNetWebFormsSupport; public bool ProtectResizedImagesWithHash => _configurationData.ProtectResizedImagesWithHash; } internal class ConfigCachingSettings: ICachingSettings { private readonly CachingConfigurationElement _data; public ConfigCachingSettings(CachingConfigurationElement data) { _data = data; } public bool Enabled => _data.Enabled; public IEnumerable<ICacheSettings> Caches { get { return _data.Cast<CacheSettingsElement>() .Select(element => new ConfigCacheSettings(element)); } } } internal class ConfigCacheSettings: ICacheSettings { public ConfigCacheSettings(CacheSettingsElement data) { Name = data.Name; Enabled = data.Enabled; Size = data.Size; } public string Name { get; } public bool Enabled { get; } public int Size { get; } } internal sealed class ConfigBasedGlobalSettingsProviderAssembler : IAssembler<IGlobalSettingsProvider, GlobalSettingsProviderData> { public IGlobalSettingsProvider Assemble(IBuilderContext context, GlobalSettingsProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { return new ConfigBasedGlobalSettingsProvider((ConfigBasedGlobalSettingsProviderData)objectConfiguration); } } [Assembler(typeof(ConfigBasedGlobalSettingsProviderAssembler))] internal sealed class ConfigBasedGlobalSettingsProviderData : GlobalSettingsProviderData { private const string _applicationNamePropertyName = "applicationName"; [ConfigurationProperty(_applicationNamePropertyName, IsRequired = true, DefaultValue = "C1 CMS")] public string ApplicationName { get { return (string)base[_applicationNamePropertyName]; } set { base[_applicationNamePropertyName] = value; } } private const string _applicationShortNamePropertyName = "applicationShortName"; [ConfigurationProperty(_applicationShortNamePropertyName, IsRequired = true, DefaultValue = "CMS")] public string ApplicationShortName { get { return (string)base[_applicationShortNamePropertyName]; } set { base[_applicationShortNamePropertyName] = value; } } private const string _brandedVersionAssemblySourcePropertyName = "brandedVersionAssemblySource"; [ConfigurationProperty(_brandedVersionAssemblySourcePropertyName, IsRequired = false, DefaultValue = "Composite")] public string BrandedVersionAssemblySource { get { return (string)base[_brandedVersionAssemblySourcePropertyName]; } set { base[_brandedVersionAssemblySourcePropertyName] = value; } } private const string _defaultCultureNamePropertyName = "defaultCultureName"; [ConfigurationProperty(_defaultCultureNamePropertyName, DefaultValue = "en-US")] public string DefaultCultureName { get { return (string)base[_defaultCultureNamePropertyName]; } set { base[_defaultCultureNamePropertyName] = value; } } private const string _configurationDirectoryPropertyName = "customConfigurationDirectory"; [ConfigurationProperty(_configurationDirectoryPropertyName, DefaultValue = "~")] public string ConfigurationDirectory { get { return (string)base[_configurationDirectoryPropertyName]; } set { base[_configurationDirectoryPropertyName] = value; } } private const string _generatedAssembliesDirectoryPropertyName = "generatedAssembliesDirectory"; [ConfigurationProperty(_generatedAssembliesDirectoryPropertyName, DefaultValue = "~")] public string GeneratedAssembliesDirectory { get { return (string)base[_generatedAssembliesDirectoryPropertyName]; } set { base[_generatedAssembliesDirectoryPropertyName] = value; } } private const string _serializedWorkflowsDirectoryPropertyName = "serializedWorkflowsDirectory"; [ConfigurationProperty(_serializedWorkflowsDirectoryPropertyName, DefaultValue = "~")] public string SerializedWorkflowsDirectory { get { return (string)base[_serializedWorkflowsDirectoryPropertyName]; } set { base[_serializedWorkflowsDirectoryPropertyName] = value; } } private const string _serializedConsoleMessagesDirectoryPropertyName = "serializedConsoleMessagesDirectory"; [ConfigurationProperty(_serializedConsoleMessagesDirectoryPropertyName, DefaultValue = "~")] public string SerializedConsoleMessagesDirectory { get { return (string)base[_serializedConsoleMessagesDirectoryPropertyName]; } set { base[_serializedConsoleMessagesDirectoryPropertyName] = value; } } private const string _appCodeDirectoryPropertyName = "appCodeDirectory"; [ConfigurationProperty(_appCodeDirectoryPropertyName, DefaultValue = "App_Code")] public string AppCodeDirectory { get { return (string)base[_appCodeDirectoryPropertyName]; } set { base[_appCodeDirectoryPropertyName] = value; } } private const string _binDirectoryPropertyName = "binDirectory"; [ConfigurationProperty(_binDirectoryPropertyName, DefaultValue = "~")] public string BinDirectory { get { return (string)base[_binDirectoryPropertyName]; } set { base[_binDirectoryPropertyName] = value; } } private const string _tempDirectoryPropertyName = "tempDirectory"; [ConfigurationProperty(_tempDirectoryPropertyName, DefaultValue = "~")] public string TempDirectory { get { return (string)base[_tempDirectoryPropertyName]; } set { base[_tempDirectoryPropertyName] = value; } } private const string _cacheDirectoryPropertyName = "cacheDirectory"; [ConfigurationProperty(_cacheDirectoryPropertyName, DefaultValue = "~/App_Data/Composite/Cache")] public string CacheDirectory { get { return (string)base[_cacheDirectoryPropertyName]; } set { base[_cacheDirectoryPropertyName] = value; } } private const string _packageDirectoryPropertyName = "packageDirectory"; [ConfigurationProperty(_packageDirectoryPropertyName, DefaultValue = "~")] public string PackageDirectory { get { return (string)base[_packageDirectoryPropertyName]; } set { base[_packageDirectoryPropertyName] = value; } } private const string _autoPackageInstallDirectoryPropertyName = "autoPackageInstallDirectory"; [ConfigurationProperty(_autoPackageInstallDirectoryPropertyName, DefaultValue = "~")] public string AutoPackageInstallDirectory { get { return (string)base[_autoPackageInstallDirectoryPropertyName]; } set { base[_autoPackageInstallDirectoryPropertyName] = value; } } private const string _treeDefinitionsDirectoryPropertyName = "treeDefinitionsDirectory"; [ConfigurationProperty(_treeDefinitionsDirectoryPropertyName, DefaultValue = "~")] public string TreeDefinitionsDirectory { get { return (string)base[_treeDefinitionsDirectoryPropertyName]; } set { base[_treeDefinitionsDirectoryPropertyName] = value; } } private const string _pageTemplateFeaturesDirectoryPropertyName = "pageTemplateFeaturesDirectory"; [ConfigurationProperty(_pageTemplateFeaturesDirectoryPropertyName, DefaultValue = "~")] public string PageTemplateFeaturesDirectory { get { return (string)base[_pageTemplateFeaturesDirectoryPropertyName]; } set { base[_pageTemplateFeaturesDirectoryPropertyName] = value; } } private const string _dataMetaDataDirectoryPropertyName = "dataMetaDataDirectory"; [ConfigurationProperty(_dataMetaDataDirectoryPropertyName, DefaultValue = "~")] public string DataMetaDataDirectory { get { return (string)base[_dataMetaDataDirectoryPropertyName]; } set { base[_dataMetaDataDirectoryPropertyName] = value; } } private const string _inlineCSharpFunctionDirectoryPropertyName = "inlineCSharpFunctionDirectory"; [ConfigurationProperty(_inlineCSharpFunctionDirectoryPropertyName, DefaultValue = "~")] public string InlineCSharpFunctionDirectory { get { return (string)base[_inlineCSharpFunctionDirectoryPropertyName]; } set { base[_inlineCSharpFunctionDirectoryPropertyName] = value; } } private const string _packageLicenseDirectoryPropertyName = "packageLicenseDirectory"; [ConfigurationProperty(_packageLicenseDirectoryPropertyName, DefaultValue = "~")] public string PackageLicenseDirectory { get { return (string)base[_packageLicenseDirectoryPropertyName]; } set { base[_packageLicenseDirectoryPropertyName] = value; } } private const int A_DAY_IN_MINUTES = 24*60; private const int A_WEEK_IN_MINUTES = 7*24*60; private const string _resourceCacheDirectory = "resourceCacheDirectory"; [Obsolete] [ConfigurationProperty(_resourceCacheDirectory, IsRequired = false)] public string ResourceCacheDirectory { get { return (string)base[_resourceCacheDirectory]; } set { base[_resourceCacheDirectory] = value; } } private const string _clientCacheMinutesProperty = "clientCacheMinutes"; public static readonly int DefaultClientCacheMinutes = A_WEEK_IN_MINUTES; [Obsolete] [ConfigurationProperty(_clientCacheMinutesProperty, IsRequired = false, DefaultValue = A_WEEK_IN_MINUTES)] public int ClientCacheMinutes { get { return (int)base[_clientCacheMinutesProperty]; } set { base[_clientCacheMinutesProperty] = value; } } private const string _serverCacheMinutesProperty = "serverCacheMinutes"; public static readonly int DefaultServerCacheMinutes = A_DAY_IN_MINUTES; [Obsolete] [ConfigurationProperty(_serverCacheMinutesProperty, IsRequired = false, DefaultValue = A_DAY_IN_MINUTES)] public int ServerCacheMinutes { get { return (int)base[_serverCacheMinutesProperty]; } set { base[_serverCacheMinutesProperty] = value; } } private const string _nonProbeableAssemblyNames = "nonProbeableAssemblyNames"; [ConfigurationProperty(_nonProbeableAssemblyNames, IsRequired = false, DefaultValue = "")] public string NonProbeableAssemblyNames { get { return (string)base[_nonProbeableAssemblyNames]; } set { base[_nonProbeableAssemblyNames] = value; } } private const string _onlyTranslateWhenApproved = "onlyTranslateWhenApproved"; [ConfigurationProperty(_onlyTranslateWhenApproved, IsRequired = false, DefaultValue = false)] public bool OnlyTranslateWhenApproved { get { return (bool)base[_onlyTranslateWhenApproved]; } set { base[_onlyTranslateWhenApproved] = value; } } private const string _allowChildPagesTranslationWithoutParent = "allowChildPagesTranslationWithoutParent"; [ConfigurationProperty(_allowChildPagesTranslationWithoutParent, IsRequired = false, DefaultValue = false)] public bool AllowChildPagesTranslationWithoutParent { get { return (bool)base[_allowChildPagesTranslationWithoutParent]; } set { base[_allowChildPagesTranslationWithoutParent] = value; } } private const string _applicationCultureNames = "applicationCultureNames"; [ConfigurationProperty(_applicationCultureNames, IsRequired = false, DefaultValue = "da-DK,en-US")] [Obsolete("Preserved for compatibility with old language packages (versions older than C1 4.0)")] public string ApplicationCultureNames { get { return (string)base[_applicationCultureNames]; } set { base[_applicationCultureNames] = value; } } private const string _consoleMessageQueueItemSecondToLiveProperty = "consoleMessageQueueItemSecondToLive"; public static readonly int DefaultConsoleMessageQueueItemSecondToLive = 600; [ConfigurationProperty(_consoleMessageQueueItemSecondToLiveProperty, IsRequired = false, DefaultValue = 600)] public int ConsoleMessageQueueItemSecondToLive { get { return (int)base[_consoleMessageQueueItemSecondToLiveProperty]; } set { base[_consoleMessageQueueItemSecondToLiveProperty] = value; } } private const string _enableDataTypesAutoUdpatePropertyName = "enableDataTypesAutoUpdate"; [ConfigurationProperty(_enableDataTypesAutoUdpatePropertyName, DefaultValue = true)] public bool EnableDataTypesAutoUpdate { get { return (bool)base[_enableDataTypesAutoUdpatePropertyName]; } set { base[_enableDataTypesAutoUdpatePropertyName] = value; } } private const string _broadcastConsoleElementChangesPropertyName = "broadcastConsoleElementChanges"; [ConfigurationProperty(_broadcastConsoleElementChangesPropertyName, DefaultValue = true)] public bool BroadcastConsoleElementChanges { get { return (bool)base[_broadcastConsoleElementChangesPropertyName]; } set { base[_broadcastConsoleElementChangesPropertyName] = value; } } private const string _autoCreatedAdministratorUserNamePropertyName = "autoCreatedAdministratorUserName"; [ConfigurationProperty(_autoCreatedAdministratorUserNamePropertyName, DefaultValue = "")] public string AutoCreatedAdministratorUserName { get { return (string)base[_autoCreatedAdministratorUserNamePropertyName]; } set { base[_autoCreatedAdministratorUserNamePropertyName] = value; } } private const string _workflowTimeoutPropertyName = "workflowTimeout"; [ConfigurationProperty(_workflowTimeoutPropertyName, DefaultValue = "7.00:00:00")] public string WorkflowTimeout { get { return (string)base[_workflowTimeoutPropertyName]; } set { base[_workflowTimeoutPropertyName] = value; } } private const string _consoleTimeoutPropertyName = "consoleTimeout"; [ConfigurationProperty(_consoleTimeoutPropertyName, DefaultValue = "00:05:00")] public string ConsoleTimeout { get { return (string)base[_consoleTimeoutPropertyName]; } set { base[_consoleTimeoutPropertyName] = value; } } private const string _cachingElementName = "Caching"; [ConfigurationProperty(_cachingElementName)] public CachingConfigurationElement Caching { get { return (CachingConfigurationElement)base[_cachingElementName]; } set { base[_cachingElementName] = value; } } private const string _imageQualityPropertyName = "imageQuality"; [ConfigurationProperty(_imageQualityPropertyName, DefaultValue = 80)] public int ImageQuality { get { return (int)base[_imageQualityPropertyName]; } set { base[_imageQualityPropertyName] = value; } } private const string _prettifyPublicMarkupPropertyName = "prettifyPublicMarkup"; [ConfigurationProperty(_prettifyPublicMarkupPropertyName, DefaultValue = true)] public bool PrettifyPublicMarkup { get { return (bool)base[_prettifyPublicMarkupPropertyName]; } set { base[_prettifyPublicMarkupPropertyName] = value; } } private const string _prettifyRenderFunctionExceptionsPropertyName = "prettifyRenderFunctionExceptions"; [ConfigurationProperty(_prettifyRenderFunctionExceptionsPropertyName, DefaultValue = true)] public bool PrettifyRenderFunctionExceptions { get { return (bool)base[_prettifyRenderFunctionExceptionsPropertyName]; } set { base[_prettifyRenderFunctionExceptionsPropertyName] = value; } } private const string _functionPreviewEnabledPropertyName = "functionPreviewEnabled"; [ConfigurationProperty(_functionPreviewEnabledPropertyName, DefaultValue = true)] public bool FunctionPreviewEnabled { get { return (bool)base[_functionPreviewEnabledPropertyName]; } set { base[_functionPreviewEnabledPropertyName] = value; } } private const string TimeZonePropertyName = "timezone"; [ConfigurationProperty(TimeZonePropertyName, DefaultValue = null)] public string TimeZone { get { return (string)base[TimeZonePropertyName]; } set { base[TimeZonePropertyName] = value; } } private const string InheritGlobalReadPermissionOnHiddenPerspectivesPropertyName = "inheritGlobalReadPermissionOnHiddenPerspectives"; [ConfigurationProperty(InheritGlobalReadPermissionOnHiddenPerspectivesPropertyName, DefaultValue = false)] public bool InheritGlobalReadPermissionOnHiddenPerspectives { get { return (bool)base[InheritGlobalReadPermissionOnHiddenPerspectivesPropertyName]; } set { base[InheritGlobalReadPermissionOnHiddenPerspectivesPropertyName] = value; } } private const string _omitAspNetWebFormsSupportPropertyName = "omitAspNetWebFormsSupport"; [ConfigurationProperty(_omitAspNetWebFormsSupportPropertyName, DefaultValue = false)] public bool OmitAspNetWebFormsSupport { get { return (bool)base[_omitAspNetWebFormsSupportPropertyName]; } set { base[_omitAspNetWebFormsSupportPropertyName] = value; } } private const string _protectResizedImagesWithHash = "protectResizedImagesWithHash"; [ConfigurationProperty(_protectResizedImagesWithHash, DefaultValue = false)] public bool ProtectResizedImagesWithHash { get => (bool)base[_protectResizedImagesWithHash]; set => base[_protectResizedImagesWithHash] = value; } } internal sealed class CachingConfigurationElement : ConfigurationElementCollection { private const string _enabledPropertyName = "enabled"; [ConfigurationProperty(_enabledPropertyName, DefaultValue = "true")] public bool Enabled { get { return (bool)base[_enabledPropertyName]; } set { base[_enabledPropertyName] = value; } } protected override ConfigurationElement CreateNewElement() { return new CacheSettingsElement(); } protected override object GetElementKey(ConfigurationElement element) { var cacheSettings = (CacheSettingsElement)element; return cacheSettings.Name; } } internal sealed class CacheSettingsElement: ConfigurationElement { private const string _namePropertyName = "name"; [ConfigurationProperty(_namePropertyName)] public string Name { get { return (string)base[_namePropertyName]; } set { base[_namePropertyName] = value; } } private const string _sizePropertyName = "size"; [ConfigurationProperty(_sizePropertyName, DefaultValue = "1000")] public int Size { get { return (int)base[_sizePropertyName]; } set { base[_sizePropertyName] = value; } } private const string _enabledPropertyName = "enabled"; [ConfigurationProperty(_enabledPropertyName, DefaultValue = "true")] public bool Enabled { get { return (bool)base[_enabledPropertyName]; } set { base[_enabledPropertyName] = value; } } } } ================================================ FILE: Composite/Plugins/IO/IOProviders/LocalIOProvider/LocalC1Configuration.cs ================================================ using System.Configuration; using Composite.Core.IO.Plugins.IOProvider; namespace Composite.Plugins.IO.IOProviders.LocalIOProvider { internal class LocalC1Configuration : IC1Configuration { private Configuration _configuration; [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "IO implementation")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationManagerClass:DoNotUseConfigurationManagerClass", Justification = "IO implementation")] public LocalC1Configuration(string path) { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = path; _configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "IO implementation")] public string FilePath { get { return _configuration.FilePath; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "IO implementation")] public bool HasFile { get { return _configuration.HasFile; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "IO implementation")] public AppSettingsSection AppSettings { get { return _configuration.AppSettings; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "IO implementation")] public ConnectionStringsSection ConnectionStrings { get { return _configuration.ConnectionStrings; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "IO implementation")] public ConfigurationSectionCollection Sections { get { return _configuration.Sections; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "IO implementation")] public ConfigurationSectionGroup RootSectionGroup { get { return _configuration.RootSectionGroup; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "IO implementation")] public ConfigurationSectionGroupCollection SectionGroups { get { return _configuration.SectionGroups; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "IO implementation")] public ConfigurationSection GetSection(string sectionName) { return _configuration.GetSection(sectionName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "IO implementation")] public ConfigurationSectionGroup GetSectionGroup(string sectionGroupName) { return _configuration.GetSectionGroup(sectionGroupName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "IO implementation")] public void Save() { _configuration.Save(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "IO implementation")] public void Save(ConfigurationSaveMode saveMode) { _configuration.Save(saveMode); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "IO implementation")] public void Save(ConfigurationSaveMode saveMode, bool forceSaveAll) { _configuration.Save(saveMode, forceSaveAll); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "IO implementation")] public void SaveAs(string filename) { _configuration.SaveAs(filename); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "IO implementation")] public void SaveAs(string filename, ConfigurationSaveMode saveMode) { _configuration.SaveAs(filename, saveMode); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseConfigurationClass:DoNotUseConfigurationClass", Justification = "IO implementation")] public void SaveAs(string filename, ConfigurationSaveMode saveMode, bool forceSaveAll) { _configuration.SaveAs(filename, saveMode, forceSaveAll); } } } ================================================ FILE: Composite/Plugins/IO/IOProviders/LocalIOProvider/LocalC1Directory.cs ================================================ using System; using System.IO; using Composite.Core.IO; using Composite.Core.IO.Plugins.IOProvider; namespace Composite.Plugins.IO.IOProviders.LocalIOProvider { internal class LocalC1Directory : IC1Directory { [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1DirectoryInfo CreateDirectory(string path) { return new C1DirectoryInfo(Directory.CreateDirectory(path).FullName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] public void Delete(string path) { Directory.Delete(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] public void Delete(string path, bool recursive) { Directory.Delete(path, recursive); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] public void Move(string sourceDirName, string destDirName) { Directory.Move(sourceDirName, destDirName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] public bool Exists(string path) { return Directory.Exists(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] public string GetCurrentDirectory() { return Directory.GetCurrentDirectory(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] public void SetCurrentDirectory(string path) { Directory.SetCurrentDirectory(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1DirectoryInfo GetParent(string path) { return new C1DirectoryInfo(Directory.GetParent(path).FullName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] public string GetDirectoryRoot(string path) { return Directory.GetDirectoryRoot(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] public string[] GetDirectories(string path) { return Directory.GetDirectories(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] public string[] GetDirectories(string path, string searchPattern) { return Directory.GetDirectories(path, searchPattern); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] public string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) { return Directory.GetDirectories(path, searchPattern, searchOption); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] public string[] GetFiles(string path) { return Directory.GetFiles(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] public string[] GetFiles(string path, string searchPattern) { return Directory.GetFiles(path, searchPattern); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] public string[] GetFiles(string path, string searchPattern, SearchOption searchOption) { return Directory.Exists(path) ? Directory.GetFiles(path, searchPattern, searchOption) : new string[] { }; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] public DateTime GetCreationTime(string path) { return Directory.GetCreationTime(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] public DateTime GetCreationTimeUtc(string path) { return Directory.GetCreationTimeUtc(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] public void SetCreationTime(string path, DateTime creationTime) { Directory.SetCreationTime(path, creationTime); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] public void SetCreationTimeUtc(string path, DateTime creationTimeUtc) { Directory.SetCreationTimeUtc(path, creationTimeUtc); } } } ================================================ FILE: Composite/Plugins/IO/IOProviders/LocalIOProvider/LocalC1DirectoryInfo.cs ================================================ using System; using System.IO; using System.Linq; using System.Runtime.Serialization; using Composite.Core.IO; using Composite.Core.IO.Plugins.IOProvider; namespace Composite.Plugins.IO.IOProviders.LocalIOProvider { internal class LocalC1DirectoryInfo : IC1DirectoryInfo { private DirectoryInfo _directoryInfo; [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseDirectoryInfoClass:DotNotUseDirectoryInfoClass")] public LocalC1DirectoryInfo(string path) { _directoryInfo = new DirectoryInfo(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public string Name { get { return _directoryInfo.Name; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public string FullName { get { return _directoryInfo.FullName; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public string Extension { get { return _directoryInfo.Extension; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public bool Exists { get { return _directoryInfo.Exists; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseDirectoryInfoClass:DotNotUseDirectoryInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1DirectoryInfo Root { get { return new C1DirectoryInfo(_directoryInfo.Root.FullName); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseDirectoryInfoClass:DotNotUseDirectoryInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1DirectoryInfo Parent { get { return new C1DirectoryInfo(_directoryInfo.Parent.FullName); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public FileAttributes Attributes { get { return _directoryInfo.Attributes; } set { _directoryInfo.Attributes = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseDirectoryInfoClass:DotNotUseDirectoryInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1DirectoryInfo[] GetDirectories() { return _directoryInfo.GetDirectories().Select(f => new C1DirectoryInfo(f.FullName)).ToArray(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseDirectoryInfoClass:DotNotUseDirectoryInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1DirectoryInfo[] GetDirectories(string searchPattern) { return _directoryInfo.GetDirectories(searchPattern).Select(f => new C1DirectoryInfo(f.FullName)).ToArray(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseDirectoryInfoClass:DotNotUseDirectoryInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1DirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption) { return _directoryInfo.GetDirectories(searchPattern, searchOption).Select(f => new C1DirectoryInfo(f.FullName)).ToArray(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseDirectoryInfoClass:DotNotUseDirectoryInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1FileInfo[] GetFiles() { return _directoryInfo.GetFiles().Select(f => new C1FileInfo(f.FullName)).ToArray(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseDirectoryInfoClass:DotNotUseDirectoryInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1FileInfo[] GetFiles(string searchPattern) { return _directoryInfo.GetFiles(searchPattern).Select(f => new C1FileInfo(f.FullName)).ToArray(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseDirectoryInfoClass:DotNotUseDirectoryInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1FileInfo[] GetFiles(string searchPattern, SearchOption searchOption) { return _directoryInfo.GetFiles(searchPattern, searchOption).Select(f => new C1FileInfo(f.FullName)).ToArray(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseDirectoryInfoClass:DotNotUseDirectoryInfoClass")] public void Create() { _directoryInfo.Create(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseDirectoryInfoClass:DotNotUseDirectoryInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1DirectoryInfo CreateSubdirectory(string path) { return new C1DirectoryInfo(_directoryInfo.CreateSubdirectory(path).FullName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseDirectoryInfoClass:DotNotUseDirectoryInfoClass")] public void MoveTo(string destDirName) { _directoryInfo.MoveTo(destDirName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public void Delete() { _directoryInfo.Delete(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseDirectoryInfoClass:DotNotUseDirectoryInfoClass")] public void Delete(bool recursive) { _directoryInfo.Delete(recursive); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public DateTime CreationTime { get { return _directoryInfo.CreationTime; } set { _directoryInfo.CreationTime = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public DateTime CreationTimeUtc { get { return _directoryInfo.CreationTimeUtc; } set { _directoryInfo.CreationTimeUtc = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public DateTime LastAccessTime { get { return _directoryInfo.LastAccessTime; } set { _directoryInfo.LastAccessTime = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public DateTime LastAccessTimeUtc { get { return _directoryInfo.LastAccessTimeUtc; } set { _directoryInfo.LastAccessTimeUtc = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public DateTime LastWriteTime { get { return _directoryInfo.LastWriteTime; } set { _directoryInfo.LastWriteTime = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public DateTime LastWriteTimeUtc { get { return _directoryInfo.LastWriteTimeUtc; } set { _directoryInfo.LastWriteTimeUtc = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public void GetObjectData(SerializationInfo info, StreamingContext context) { _directoryInfo.GetObjectData(info, context); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public void Refresh() { _directoryInfo.Refresh(); } } } ================================================ FILE: Composite/Plugins/IO/IOProviders/LocalIOProvider/LocalC1File.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Text; using Composite.Core.IO; using Composite.Core.IO.Plugins.IOProvider; namespace Composite.Plugins.IO.IOProviders.LocalIOProvider { internal class LocalC1File : IC1File { [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public bool Exists(string path) { return File.Exists(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void Touch(string path) { File.SetLastWriteTime(path, DateTime.Now); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void Copy(string sourceFileName, string destFileName) { File.Copy(sourceFileName, destFileName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void Copy(string sourceFileName, string destFileName, bool overwrite) { File.Copy(sourceFileName, destFileName, overwrite); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void Move(string sourceFileName, string destFileName) { File.Move(sourceFileName, destFileName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { File.Replace(sourceFileName, destinationFileName, destinationBackupFileName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { File.Replace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void Delete(string path) { File.Delete(path); } public C1FileStream Create(string path) { return new C1FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.Read); } public C1FileStream Create(string path, int bufferSize) { return new C1FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, bufferSize); } public C1FileStream Create(string path, int bufferSize, FileOptions options) { return new C1FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, bufferSize, options); } public C1StreamWriter CreateText(string path) { return new C1StreamWriter(path, false); } public C1StreamWriter AppendText(string path) { return new C1StreamWriter(path, true); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void AppendAllText(string path, string contents) { File.AppendAllText(path, contents); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void AppendAllText(string path, string contents, Encoding encoding) { File.AppendAllText(path, contents, encoding); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void AppendAllLines(string path, IEnumerable<string> contents) { File.AppendAllLines(path, contents); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void AppendAllLines(string path, IEnumerable<string> contents, Encoding encoding) { File.AppendAllLines(path, contents, encoding); } public C1FileStream Open(string path, FileMode mode) { return new C1FileStream(path, mode); } public C1FileStream Open(string path, FileMode mode, FileAccess access) { return new C1FileStream(path, mode, access); } public C1FileStream Open(string path, FileMode mode, FileAccess access, FileShare share) { return new C1FileStream(path, mode, access, share); } public C1FileStream OpenRead(string path) { return new C1FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); } public C1StreamReader OpenText(string path) { return new C1StreamReader(path); } public C1FileStream OpenWrite(string path) { return new C1FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public byte[] ReadAllBytes(string path) { return File.ReadAllBytes(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public string[] ReadAllLines(string path) { return File.ReadAllLines(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public string[] ReadAllLines(string path, Encoding encoding) { return File.ReadAllLines(path, encoding); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public string ReadAllText(string path) { return File.ReadAllText(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public string ReadAllText(string path, Encoding encoding) { return File.ReadAllText(path, encoding); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public IEnumerable<string> ReadLines(string path) { return File.ReadLines(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public IEnumerable<string> ReadLines(string path, Encoding encoding) { return File.ReadLines(path, encoding); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void WriteAllBytes(string path, byte[] bytes) { File.WriteAllBytes(path, bytes); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void WriteAllLines(string path, IEnumerable<string> contents) { File.WriteAllLines(path, contents); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void WriteAllLines(string path, IEnumerable<string> contents, Encoding encoding) { File.WriteAllLines(path, contents, encoding); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void WriteAllLines(string path, string[] contents) { File.WriteAllLines(path, contents); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void WriteAllLines(string path, string[] contents, Encoding encoding) { File.WriteAllLines(path, contents, encoding); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void WriteAllText(string path, string contents) { File.WriteAllText(path, contents); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void WriteAllText(string path, string contents, Encoding encoding) { File.WriteAllText(path, contents, encoding); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public FileAttributes GetAttributes(string path) { return File.GetAttributes(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void SetAttributes(string path, FileAttributes fileAttributes) { File.SetAttributes(path, fileAttributes); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public DateTime GetCreationTime(string path) { return File.GetCreationTime(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public DateTime GetCreationTimeUtc(string path) { return File.GetCreationTimeUtc(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void SetCreationTime(string path, DateTime creationTime) { File.SetCreationTime(path, creationTime); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void SetCreationTimeUtc(string path, DateTime creationTimeUtc) { File.SetCreationTimeUtc(path, creationTimeUtc); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public DateTime GetLastAccessTime(string path) { return File.GetLastAccessTime(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public DateTime GetLastAccessTimeUtc(string path) { return File.GetLastAccessTimeUtc(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void SetLastAccessTime(string path, DateTime lastAccessTime) { File.SetLastAccessTime(path, lastAccessTime); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) { File.SetLastAccessTimeUtc(path, lastAccessTimeUtc); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public DateTime GetLastWriteTime(string path) { return File.GetLastWriteTime(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public DateTime GetLastWriteTimeUtc(string path) { return File.GetLastWriteTimeUtc(path); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void SetLastWriteTime(string path, DateTime lastWriteTime) { File.SetLastWriteTime(path, lastWriteTime); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] public void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) { File.SetLastWriteTimeUtc(path, lastWriteTimeUtc); } } } ================================================ FILE: Composite/Plugins/IO/IOProviders/LocalIOProvider/LocalC1FileInfo.cs ================================================ using System; using System.IO; using System.Runtime.Serialization; using System.Text; using Composite.Core.IO; using Composite.Core.IO.Plugins.IOProvider; namespace Composite.Plugins.IO.IOProviders.LocalIOProvider { internal class LocalC1FileInfo : IC1FileInfo { private FileInfo _fileInfo; [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] public LocalC1FileInfo(string fileName) { _fileInfo = new FileInfo(fileName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] public string DirectoryName { get { return _fileInfo.DirectoryName; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] public C1DirectoryInfo Directory { get { return new C1DirectoryInfo(_fileInfo.DirectoryName); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public string Name { get { return _fileInfo.Name; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public string FullName { get { return _fileInfo.FullName; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public bool Exists { get { return _fileInfo.Exists; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public string Extension { get { return _fileInfo.Extension; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] public bool IsReadOnly { get { return _fileInfo.IsReadOnly; } set { _fileInfo.IsReadOnly = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] public long Length { get { return _fileInfo.Length; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public FileAttributes Attributes { get { return _fileInfo.Attributes; } set { _fileInfo.Attributes = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1FileStream Create() { return new C1FileStream(_fileInfo.FullName, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 0x1000, FileOptions.None); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1StreamWriter CreateText() { return new C1StreamWriter(_fileInfo.FullName, false); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1StreamWriter AppendText() { return new C1StreamWriter(_fileInfo.FullName, true); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1FileStream Open(FileMode mode) { return Open(mode, FileAccess.ReadWrite, FileShare.Read); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1FileStream Open(FileMode mode, FileAccess access) { return Open(mode, access, FileShare.Read); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1FileStream Open(FileMode mode, FileAccess access, FileShare share) { return new C1FileStream(_fileInfo.FullName, mode, access, share); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1FileStream OpenRead() { return new C1FileStream(_fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.Read); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1StreamReader OpenText() { return new C1StreamReader(_fileInfo.FullName, Encoding.UTF8, true, 0x400); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1FileStream OpenWrite() { return new C1FileStream(_fileInfo.FullName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1FileInfo CopyTo(string destFileName) { return new C1FileInfo(_fileInfo.CopyTo(destFileName).FullName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1FileInfo CopyTo(string destFileName, bool overwrite) { return new C1FileInfo(_fileInfo.CopyTo(destFileName, overwrite).FullName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public void MoveTo(string destFileName) { _fileInfo.MoveTo(destFileName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1FileInfo Replace(string destinationFileName, string destinationBackupFileName) { return new C1FileInfo(_fileInfo.Replace(destinationFileName, destinationBackupFileName).FullName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileInfoClass:DotNotUseFileInfoClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public C1FileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { return new C1FileInfo(_fileInfo.Replace(destinationFileName, destinationBackupFileName, ignoreMetadataErrors).FullName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public void Delete() { _fileInfo.Delete(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public void Refresh() { _fileInfo.Refresh(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public void GetObjectData(SerializationInfo info, StreamingContext context) { _fileInfo.GetObjectData(info, context); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public DateTime CreationTime { get { return _fileInfo.CreationTime; } set { _fileInfo.CreationTime = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public DateTime CreationTimeUtc { get { return _fileInfo.CreationTimeUtc; } set { _fileInfo.CreationTimeUtc = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public DateTime LastAccessTime { get { return _fileInfo.LastAccessTime; } set { _fileInfo.LastAccessTime = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public DateTime LastAccessTimeUtc { get { return _fileInfo.LastAccessTimeUtc; } set { _fileInfo.LastAccessTimeUtc = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public DateTime LastWriteTime { get { return _fileInfo.LastWriteTime; } set { _fileInfo.LastWriteTime = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseFileSystemInfoClass:DotNotUseFileSystemInfoClass")] public DateTime LastWriteTimeUtc { get { return _fileInfo.LastWriteTimeUtc; } set { _fileInfo.LastWriteTimeUtc = value; } } } } ================================================ FILE: Composite/Plugins/IO/IOProviders/LocalIOProvider/LocalC1FileStream.cs ================================================ using System; using System.IO; using Composite.Core.IO.Plugins.IOProvider; namespace Composite.Plugins.IO.IOProviders.LocalIOProvider { internal class LocalC1FileStream : IC1FileStream { private FileStream _fileStream; [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] public LocalC1FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { _fileStream = new System.IO.FileStream(path, mode, access, share, bufferSize, options); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] public string Name => _fileStream.Name; [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] public long Length => _fileStream.Length; [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] public void SetLength(long value) { _fileStream.SetLength(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] public long Position { get => _fileStream.Position; set => _fileStream.Position = value; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] public int Read(byte[] array, int offset, int count) { return _fileStream.Read(array, offset, count); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] public int ReadByte() { return _fileStream.ReadByte(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] public void Write(byte[] array, int offset, int count) { _fileStream.Write(array, offset, count); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] public void WriteByte(byte value) { _fileStream.WriteByte(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] public long Seek(long offset, SeekOrigin origin) { return _fileStream.Seek(offset, origin); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] public bool CanRead => _fileStream.CanRead; [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] public bool CanSeek => _fileStream.CanSeek; [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] public bool CanWrite => _fileStream.CanWrite; [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] public void Flush() { _fileStream.Flush(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] public void Flush(bool flushToDisk) { _fileStream.Flush(flushToDisk); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] public void Close() { _fileStream.Close(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass")] public void Dispose() { _fileStream?.Dispose(); _fileStream = null; #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// <exclude /> ~LocalC1FileStream() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } ================================================ FILE: Composite/Plugins/IO/IOProviders/LocalIOProvider/LocalC1FileSystemWatcher.cs ================================================ using System.IO; using Composite.Core.IO; using Composite.Core.IO.Plugins.IOProvider; using System; using System.Threading.Tasks; using System.Threading; namespace Composite.Plugins.IO.IOProviders.LocalIOProvider { // TODO: has to implement IDisposable as it may contain unmanaged resources internal class LocalC1FileSystemWatcher : IC1FileSystemWatcher { private const string LogTitle = "LocalC1FileSystemWatcher"; private readonly FileSystemWatcher _fileSystemWatcher; [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileSystemWatcherClass:DoNotUseFileSystemWatcherClass")] public LocalC1FileSystemWatcher(string path, string filter) { if (filter == null) { _fileSystemWatcher = new FileSystemWatcher(path) { InternalBufferSize = 8192 }; } else { _fileSystemWatcher = new FileSystemWatcher(path, filter); } _fileSystemWatcher.Error += _fileSystemWatcher_Error; } void _fileSystemWatcher_Error(object sender, ErrorEventArgs e) { Composite.Core.Log.LogWarning(LogTitle, e.GetException()); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileSystemWatcherClass:DoNotUseFileSystemWatcherClass")] public bool EnableRaisingEvents { get { return _fileSystemWatcher.EnableRaisingEvents; } set { // Systems with flaky disk IO this can block thread for a very long time Task.Factory.StartNew(() => { Thread.Sleep(1000); DoEnableRaisingEvents(value); }); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileSystemWatcherClass:DoNotUseFileSystemWatcherClass")] private void DoEnableRaisingEvents(bool raiseEvents) { try { _fileSystemWatcher.EnableRaisingEvents = raiseEvents; } catch (Exception ex) { Composite.Core.Log.LogWarning(LogTitle, ex); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileSystemWatcherClass:DoNotUseFileSystemWatcherClass")] public string Path { get { return _fileSystemWatcher.Path; } set { _fileSystemWatcher.Path = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileSystemWatcherClass:DoNotUseFileSystemWatcherClass")] public string Filter { get { return _fileSystemWatcher.Filter; } set { _fileSystemWatcher.Filter = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileSystemWatcherClass:DoNotUseFileSystemWatcherClass")] public bool IncludeSubdirectories { get { return _fileSystemWatcher.IncludeSubdirectories; } set { _fileSystemWatcher.IncludeSubdirectories = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileSystemWatcherClass:DoNotUseFileSystemWatcherClass")] public int InternalBufferSize { get { return _fileSystemWatcher.InternalBufferSize; } set { _fileSystemWatcher.InternalBufferSize = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileSystemWatcherClass:DoNotUseFileSystemWatcherClass")] public event FileSystemEventHandler Created { add { _fileSystemWatcher.Created += value; } remove { _fileSystemWatcher.Created -= value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileSystemWatcherClass:DoNotUseFileSystemWatcherClass")] public event FileSystemEventHandler Changed { add { _fileSystemWatcher.Changed += value; } remove { _fileSystemWatcher.Changed -= value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileSystemWatcherClass:DoNotUseFileSystemWatcherClass")] public event RenamedEventHandler Renamed { add { _fileSystemWatcher.Renamed += value; } remove { _fileSystemWatcher.Renamed -= value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileSystemWatcherClass:DoNotUseFileSystemWatcherClass")] public event FileSystemEventHandler Deleted { add { _fileSystemWatcher.Deleted += value; } remove { _fileSystemWatcher.Deleted -= value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileSystemWatcherClass:DoNotUseFileSystemWatcherClass")] public event ErrorEventHandler Error { add { _fileSystemWatcher.Error += value; } remove { _fileSystemWatcher.Error -= value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileSystemWatcherClass:DoNotUseFileSystemWatcherClass")] public NotifyFilters NotifyFilter { get { return _fileSystemWatcher.NotifyFilter; } set { _fileSystemWatcher.NotifyFilter = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileSystemWatcherClass:DoNotUseFileSystemWatcherClass")] public void BeginInit() { _fileSystemWatcher.BeginInit(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileSystemWatcherClass:DoNotUseFileSystemWatcherClass")] public void EndInit() { _fileSystemWatcher.EndInit(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileSystemWatcherClass:DoNotUseFileSystemWatcherClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseWaitForChangedResultClass:DoNotUseWaitForChangedResultClass")] public C1WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) { WaitForChangedResult result = _fileSystemWatcher.WaitForChanged(changeType); return new C1WaitForChangedResult { Name = result.Name, OldName = result.OldName, ChangeType = result.ChangeType, TimedOut = result.TimedOut }; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileSystemWatcherClass:DoNotUseFileSystemWatcherClass")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseWaitForChangedResultClass:DoNotUseWaitForChangedResultClass")] public C1WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout) { WaitForChangedResult result = _fileSystemWatcher.WaitForChanged(changeType, timeout); return new C1WaitForChangedResult { Name = result.Name, OldName = result.OldName, ChangeType = result.ChangeType, TimedOut = result.TimedOut }; } } } ================================================ FILE: Composite/Plugins/IO/IOProviders/LocalIOProvider/LocalC1StreamReader.cs ================================================ using System.IO; using System.Text; using Composite.Core.IO.Plugins.IOProvider; namespace Composite.Plugins.IO.IOProviders.LocalIOProvider { internal class LocalC1StreamReader : IC1StreamReader { private StreamReader _streamReader; [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamReaderClass:DotNotUseStreamReaderClass")] public LocalC1StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { _streamReader = new StreamReader(path, encoding, detectEncodingFromByteOrderMarks, bufferSize); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamReaderClass:DotNotUseStreamReaderClass")] public LocalC1StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { _streamReader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamReaderClass:DotNotUseStreamReaderClass")] public int Read() { return _streamReader.Read(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamReaderClass:DotNotUseStreamReaderClass")] public int Read(char[] buffer, int index, int count) { return _streamReader.Read(buffer, index, count); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamReaderClass:DotNotUseStreamReaderClass")] public string ReadLine() { return _streamReader.ReadLine(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamReaderClass:DotNotUseStreamReaderClass")] public string ReadToEnd() { return _streamReader.ReadToEnd(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamReaderClass:DotNotUseStreamReaderClass")] public int ReadBlock(char[] buffer, int index, int count) { return _streamReader.ReadBlock(buffer, index, count); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamReaderClass:DotNotUseStreamReaderClass")] public int Peek() { return _streamReader.Peek(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamReaderClass:DotNotUseStreamReaderClass")] public bool EndOfStream { get { return _streamReader.EndOfStream; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamReaderClass:DotNotUseStreamReaderClass")] public void Close() { _streamReader.Close(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamReaderClass:DotNotUseStreamReaderClass")] public Stream BaseStream { get { return _streamReader.BaseStream; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamReaderClass:DotNotUseStreamReaderClass")] public Encoding CurrentEncoding { get { return _streamReader.CurrentEncoding; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamReaderClass:DotNotUseStreamReaderClass")] public void Dispose() { _streamReader.Dispose(); #if LeakCheck System.GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = System.Environment.StackTrace; /// <exclude /> ~LocalC1StreamReader() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } ================================================ FILE: Composite/Plugins/IO/IOProviders/LocalIOProvider/LocalC1StreamWriter.cs ================================================ using System; using System.IO; using System.Text; using Composite.Core.IO.Plugins.IOProvider; namespace Composite.Plugins.IO.IOProviders.LocalIOProvider { internal class LocalC1StreamWriter : IC1StreamWriter { private StreamWriter _streamWriter; [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public LocalC1StreamWriter(string path, bool append, Encoding encoding, int bufferSize) { _streamWriter = new StreamWriter(path, append, encoding, bufferSize); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public LocalC1StreamWriter(Stream stream, Encoding encoding, int bufferSize) { _streamWriter = new StreamWriter(stream, encoding, bufferSize); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Write(string value) { _streamWriter.Write(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Write(string format, object arg0) { _streamWriter.Write(format, arg0); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Write(string format, object arg0, object arg1) { _streamWriter.Write(format, arg0, arg1); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Write(string format, object arg0, object arg1, object arg2) { _streamWriter.Write(format, arg0, arg1, arg2); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Write(string format, params object[] arg) { _streamWriter.Write(format, arg); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Write(char value) { _streamWriter.Write(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Write(char[] buffer) { _streamWriter.Write(buffer); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Write(char[] buffer, int index, int count) { _streamWriter.Write(buffer, index, count); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Write(bool value) { _streamWriter.Write(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Write(int value) { _streamWriter.Write(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Write(uint value) { _streamWriter.Write(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Write(long value) { _streamWriter.Write(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Write(ulong value) { _streamWriter.Write(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Write(float value) { _streamWriter.Write(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Write(double value) { _streamWriter.Write(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Write(decimal value) { _streamWriter.Write(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Write(object value) { _streamWriter.Write(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void WriteLine() { _streamWriter.WriteLine(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void WriteLine(string value) { _streamWriter.WriteLine(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void WriteLine(string format, object arg0) { _streamWriter.WriteLine(format, arg0); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void WriteLine(string format, object arg0, object arg1) { _streamWriter.WriteLine(format, arg0, arg1); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void WriteLine(string format, object arg0, object arg1, object arg2) { _streamWriter.WriteLine(format, arg0, arg1, arg2); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void WriteLine(string format, params object[] arg) { _streamWriter.WriteLine(format, arg); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void WriteLine(char value) { _streamWriter.WriteLine(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void WriteLine(char[] buffer) { _streamWriter.WriteLine(buffer); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void WriteLine(char[] buffer, int index, int count) { _streamWriter.WriteLine(buffer, index, count); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void WriteLine(bool value) { _streamWriter.WriteLine(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void WriteLine(int value) { _streamWriter.WriteLine(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void WriteLine(uint value) { _streamWriter.WriteLine(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void WriteLine(long value) { _streamWriter.WriteLine(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void WriteLine(ulong value) { _streamWriter.WriteLine(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void WriteLine(float value) { _streamWriter.WriteLine(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void WriteLine(double value) { _streamWriter.WriteLine(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void WriteLine(decimal value) { _streamWriter.WriteLine(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void WriteLine(object value) { _streamWriter.WriteLine(value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public string NewLine { get { return _streamWriter.NewLine; } set { _streamWriter.NewLine = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public IFormatProvider FormatProvider { get { return _streamWriter.FormatProvider; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public bool AutoFlush { get { return _streamWriter.AutoFlush; } set { _streamWriter.AutoFlush = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Flush() { _streamWriter.Flush(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Close() { _streamWriter.Close(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public Stream BaseStream { get { return _streamWriter.BaseStream; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public Encoding Encoding { get { return _streamWriter.Encoding; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamWriterClass:DotNotUseStreamWriterClass")] public void Dispose() { _streamWriter.Dispose(); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// <exclude /> ~LocalC1StreamWriter() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } ================================================ FILE: Composite/Plugins/IO/IOProviders/LocalIOProvider/LocalIOProvider.cs ================================================ using System.IO; using System.Text; using Composite.Core.IO.Plugins.IOProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.IO.IOProviders.LocalIOProvider { [ConfigurationElementType(typeof(NonConfigurableIOProvider))] internal class LocalIOProvider : IIOProvider { public IC1Directory C1Directory { get { return new LocalC1Directory(); } } public IC1File C1File { get { return new LocalC1File(); } } public IC1FileInfo CreateFileInfo(string fileName) { return new LocalC1FileInfo(fileName); } public IC1DirectoryInfo CreateDirectoryInfo(string path) { return new LocalC1DirectoryInfo(path); } public IC1FileStream CreateFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { return new LocalC1FileStream(path, mode, access, share, bufferSize, options); } public IC1FileSystemWatcher CreateFileSystemWatcher(string path, string filter) { return new LocalC1FileSystemWatcher(path, filter); } public IC1StreamReader CreateStreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { return new LocalC1StreamReader(path, encoding, detectEncodingFromByteOrderMarks, bufferSize); } public IC1StreamReader CreateStreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { return new LocalC1StreamReader(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize); } public IC1StreamWriter CreateStreamWriter(string path, bool append, Encoding encoding, int bufferSize) { return new LocalC1StreamWriter(path, append, encoding, bufferSize); } public IC1StreamWriter CreateStreamWriter(Stream stream, Encoding encoding, int bufferSize) { return new LocalC1StreamWriter(stream, encoding, bufferSize); } public IC1Configuration CreateConfiguration(string path) { return new LocalC1Configuration(path); } } } ================================================ FILE: Composite/Plugins/Instrumentation/PerformanceCounterProviders/NoPerformanceCounterProvider/NoPerformanceCounterProvider.cs ================================================ using Composite.Core.Instrumentation; using Composite.Core.Instrumentation.Plugin; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Instrumentation.PerformanceCounterProviders.NoPerformanceCounterProvider { [ConfigurationElementType(typeof(NonConfigurablePerformanceCounterProvider))] internal sealed class NoPerformanceCounterProvider : IPerformanceCounterProvider { NoPerformanceCounterProviderPerformanceToken _noPerformanceCounterProviderPerformanceToken = new NoPerformanceCounterProviderPerformanceToken(); public void SystemStartupIncrement() { } public IPerformanceCounterToken BeginElementCreation() { return _noPerformanceCounterProviderPerformanceToken; } public void EndElementCreation(IPerformanceCounterToken performanceToken, int resultElementCount, int totalElementCount) { } public IPerformanceCounterToken BeginAspNetControlCompile() { return _noPerformanceCounterProviderPerformanceToken; } public void EndAspNetControlCompile(IPerformanceCounterToken performanceToken, int controlsCompiledCount) { } public IPerformanceCounterToken BeginPageHookCreation() { return _noPerformanceCounterProviderPerformanceToken; } public void EndPageHookCreation(IPerformanceCounterToken performanceToken, int pageCount) { } public void EntityTokenParentCacheHitIncrement() { } public void EntityTokenParentCacheMissIncrement() { } private sealed class NoPerformanceCounterProviderPerformanceToken : IPerformanceCounterToken { public void Dispose() { } } } } ================================================ FILE: Composite/Plugins/Instrumentation/PerformanceCounterProviders/WindowsPerformanceCounterProvider/PerformanceCounterInstaller.cs ================================================ using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Manageability; namespace Composite.Plugins.Instrumentation.PerformanceCounterProviders.WindowsPerformanceCounterProvider { /// <summary> /// Use Installutil.exe to install performance counters /// </summary> [RunInstallerAttribute(true)] internal sealed class PerformanceCounterInstaller : Installer { public override void Install(IDictionary stateSaver) { base.Install(stateSaver); if (PerformanceCounterCategory.Exists(PerformanceNames.CategoryName)) throw new InvalidOperationException("Already installed"); CounterCreationDataCollection collection = new CounterCreationDataCollection(); collection.Add(new CounterCreationData(PerformanceNames.SystemStartupCountName, PerformanceNames.SystemStartupCountDescription, PerformanceCounterType.NumberOfItems32)); collection.Add(new CounterCreationData(PerformanceNames.ElementResultCreationAverageTimeName, PerformanceNames.ElementResultCreationAverageTimeDescription, PerformanceCounterType.AverageTimer32)); collection.Add(new CounterCreationData(PerformanceNames.ElementResultCreationAverageTimeBaseName, PerformanceNames.ElementResultCreationAverageTimeBaseDescription, PerformanceCounterType.AverageBase)); collection.Add(new CounterCreationData(PerformanceNames.ElementTotalCreationAverageTimeName, PerformanceNames.ElementTotalCreationAverageTimeDescription, PerformanceCounterType.AverageTimer32)); collection.Add(new CounterCreationData(PerformanceNames.ElementTotalCreationAverageTimeBaseName, PerformanceNames.ElementTotalCreationAverageTimeBaseDescription, PerformanceCounterType.AverageBase)); collection.Add(new CounterCreationData(PerformanceNames.AspNetControlCompileAverageTimeName, PerformanceNames.AspNetControlCompileAverageTimeDescription, PerformanceCounterType.AverageTimer32)); collection.Add(new CounterCreationData(PerformanceNames.AspNetControlCompileAverageTimeBaseName, PerformanceNames.AspNetControlCompileAverageTimeBaseDescription, PerformanceCounterType.AverageBase)); collection.Add(new CounterCreationData(PerformanceNames.PageHookCreationAverageTimeName, PerformanceNames.PageHookCreationAverageTimeDescription, PerformanceCounterType.AverageCount64)); collection.Add(new CounterCreationData(PerformanceNames.PageHookCreationAverageTimeBaseName, PerformanceNames.PageHookCreationAverageTimeBaseDescription, PerformanceCounterType.AverageBase)); collection.Add(new CounterCreationData(PerformanceNames.EntityTokenParentCacheHitCountName, PerformanceNames.EntityTokenParentCacheHitCountDescription, PerformanceCounterType.NumberOfItems32)); collection.Add(new CounterCreationData(PerformanceNames.EntityTokenParentCacheMissCountName, PerformanceNames.EntityTokenParentCacheMissCountDescription, PerformanceCounterType.NumberOfItems32)); PerformanceCounterCategory.Create(PerformanceNames.CategoryName, PerformanceNames.CategoryDescription, PerformanceCounterCategoryType.MultiInstance, collection); } public override void Uninstall(IDictionary savedState) { base.Uninstall(savedState); if (PerformanceCounterCategory.Exists(PerformanceNames.CategoryName)) { PerformanceCounterCategory.Delete(PerformanceNames.CategoryName); } } } } ================================================ FILE: Composite/Plugins/Instrumentation/PerformanceCounterProviders/WindowsPerformanceCounterProvider/PerformanceNames.cs ================================================  namespace Composite.Plugins.Instrumentation.PerformanceCounterProviders.WindowsPerformanceCounterProvider { internal static class PerformanceNames { public static string CategoryName { get { return "C1 CMS"; } } public static string CategoryDescription { get { return "C1 CMS"; } } public static string SystemStartupCountName { get { return "SystemStartupCount"; } } public static string SystemStartupCountDescription { get { return "SystemStartupCount"; } } public static string ElementResultCreationAverageTimeName { get { return "ElementResultCreationAverageTime"; } } public static string ElementResultCreationAverageTimeDescription { get { return "ElementResultCreationAverageTime"; } } public static string ElementResultCreationAverageTimeBaseName { get { return "ElementResultCreationAverageTimeBase"; } } public static string ElementResultCreationAverageTimeBaseDescription { get { return "ElementResultCreationAverageTimeBase"; } } public static string ElementTotalCreationAverageTimeName { get { return "ElementTotalCreationAverageTime"; } } public static string ElementTotalCreationAverageTimeDescription { get { return "ElementTotalCreationAverageTime"; } } public static string ElementTotalCreationAverageTimeBaseName { get { return "ElementTotalCreationAverageTimeBase"; } } public static string ElementTotalCreationAverageTimeBaseDescription { get { return "ElementTotalCreationAverageTimeBase"; } } public static string AspNetControlCompileAverageTimeName { get { return "AspNetControlCompileAverageTime"; } } public static string AspNetControlCompileAverageTimeDescription { get { return "AspNetControlCompileAverageTime"; } } public static string AspNetControlCompileAverageTimeBaseName { get { return "AspNetControlCompileAverageAverageTimeBase"; } } public static string AspNetControlCompileAverageTimeBaseDescription { get { return "AspNetControlCompileAverageAverageTimeBase"; } } public static string PageHookCreationAverageTimeName { get { return "PageHookCreationAverageTime"; } } public static string PageHookCreationAverageTimeDescription { get { return "PageHookCreationAverageTime"; } } public static string PageHookCreationAverageTimeBaseName { get { return "PageHookCreationAverageAverageTimeBase"; } } public static string PageHookCreationAverageTimeBaseDescription { get { return "PageHookCreationAverageAverageTimeBase"; } } public static string EntityTokenParentCacheHitCountName { get { return "EntityTokenParentCacheHitCount"; } } public static string EntityTokenParentCacheHitCountDescription { get { return "EntityTokenParentCacheHitCount"; } } public static string EntityTokenParentCacheMissCountName { get { return "EntityTokenParentCacheMissCount"; } } public static string EntityTokenParentCacheMissCountDescription { get { return "EntityTokenParentCacheMissCount"; } } } } ================================================ FILE: Composite/Plugins/Instrumentation/PerformanceCounterProviders/WindowsPerformanceCounterProvider/WindowsPerformanceCounterProvider.cs ================================================ using System; using System.Diagnostics; using Composite.Core.Instrumentation; using Composite.Core.Instrumentation.Plugin; using Composite.Core.Logging; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Instrumentation.PerformanceCounterProviders.WindowsPerformanceCounterProvider { [ConfigurationElementType(typeof(NonConfigurablePerformanceCounterProvider))] internal sealed class WindowsPerformanceCounterProvider : IPerformanceCounterProvider { private PerformanceCounter _systemStartupCount = null; private PerformanceCounter _elementResultCreationAverageTime = null; private PerformanceCounter _elementResultCreationAverageTimeBase = null; private PerformanceCounter _elementTotalCreationAverageTime = null; private PerformanceCounter _elementTotalCreationAverageTimeBase = null; private PerformanceCounter _aspNetControlCompileAverageTime = null; private PerformanceCounter _aspNetControlCompileAverageTimeBase = null; private PerformanceCounter _pageHookCreationAverageTime = null; private PerformanceCounter _pageHookCreationAverageTimeBase = null; private PerformanceCounter _entityTokenParentCacheHitCount = null; private PerformanceCounter _entityTokenParentCacheMissCount = null; public WindowsPerformanceCounterProvider() { _systemStartupCount = TryCreateCounter(PerformanceNames.SystemStartupCountName); _elementResultCreationAverageTime = TryCreateCounter(PerformanceNames.ElementResultCreationAverageTimeName); _elementResultCreationAverageTimeBase = TryCreateCounter(PerformanceNames.ElementResultCreationAverageTimeBaseName); _elementTotalCreationAverageTime = TryCreateCounter(PerformanceNames.ElementTotalCreationAverageTimeName); _elementTotalCreationAverageTimeBase = TryCreateCounter(PerformanceNames.ElementTotalCreationAverageTimeBaseName); _aspNetControlCompileAverageTime = TryCreateCounter(PerformanceNames.AspNetControlCompileAverageTimeName); _aspNetControlCompileAverageTimeBase = TryCreateCounter(PerformanceNames.AspNetControlCompileAverageTimeBaseName); _pageHookCreationAverageTime = TryCreateCounter(PerformanceNames.PageHookCreationAverageTimeName); _pageHookCreationAverageTimeBase = TryCreateCounter(PerformanceNames.PageHookCreationAverageTimeBaseName); _entityTokenParentCacheHitCount = TryCreateCounter(PerformanceNames.EntityTokenParentCacheHitCountName); _entityTokenParentCacheMissCount = TryCreateCounter(PerformanceNames.EntityTokenParentCacheMissCountName); } public void SystemStartupIncrement() { if (_systemStartupCount != null) { _systemStartupCount.Increment(); } } public IPerformanceCounterToken BeginElementCreation() { WindowsPerformanceCounterProviderToken windowsPerformanceCounterProviderToken = new WindowsPerformanceCounterProviderToken(); windowsPerformanceCounterProviderToken.Start(); return windowsPerformanceCounterProviderToken; } public void EndElementCreation(IPerformanceCounterToken performanceToken, int resultElementCount, int totalElementCount) { WindowsPerformanceCounterProviderToken windowsPerformanceCounterProviderToken = (WindowsPerformanceCounterProviderToken)performanceToken; windowsPerformanceCounterProviderToken.Stop(); if ((_elementResultCreationAverageTime != null) && (_elementResultCreationAverageTime != null) && (_elementResultCreationAverageTimeBase != null) && (_elementTotalCreationAverageTimeBase != null)) { _elementResultCreationAverageTime.IncrementBy(windowsPerformanceCounterProviderToken.StopTicks - windowsPerformanceCounterProviderToken.StartTicks); _elementTotalCreationAverageTime.IncrementBy(windowsPerformanceCounterProviderToken.StopTicks - windowsPerformanceCounterProviderToken.StartTicks); _elementResultCreationAverageTimeBase.IncrementBy(resultElementCount); _elementTotalCreationAverageTimeBase.IncrementBy(totalElementCount); } } public IPerformanceCounterToken BeginAspNetControlCompile() { WindowsPerformanceCounterProviderToken windowsPerformanceCounterProviderToken = new WindowsPerformanceCounterProviderToken(); windowsPerformanceCounterProviderToken.Start(); return windowsPerformanceCounterProviderToken; } public void EndAspNetControlCompile(IPerformanceCounterToken performanceToken, int controlsCompiledCount) { WindowsPerformanceCounterProviderToken windowsPerformanceCounterProviderToken = (WindowsPerformanceCounterProviderToken)performanceToken; windowsPerformanceCounterProviderToken.Stop(); if ((_aspNetControlCompileAverageTime != null) && (_aspNetControlCompileAverageTimeBase != null)) { _aspNetControlCompileAverageTime.IncrementBy(windowsPerformanceCounterProviderToken.StopTicks - windowsPerformanceCounterProviderToken.StartTicks); _aspNetControlCompileAverageTimeBase.IncrementBy(controlsCompiledCount); } } public IPerformanceCounterToken BeginPageHookCreation() { WindowsPerformanceCounterProviderToken windowsPerformanceCounterProviderToken = new WindowsPerformanceCounterProviderToken(); windowsPerformanceCounterProviderToken.Start(); return windowsPerformanceCounterProviderToken; } public void EndPageHookCreation(IPerformanceCounterToken performanceToken, int pageCount) { WindowsPerformanceCounterProviderToken windowsPerformanceCounterProviderToken = (WindowsPerformanceCounterProviderToken)performanceToken; windowsPerformanceCounterProviderToken.Stop(); if ((_pageHookCreationAverageTime != null) && (_pageHookCreationAverageTimeBase != null)) { _pageHookCreationAverageTime.IncrementBy(windowsPerformanceCounterProviderToken.StopTicks - windowsPerformanceCounterProviderToken.StartTicks); _pageHookCreationAverageTimeBase.IncrementBy(pageCount); } } public void EntityTokenParentCacheHitIncrement() { if (_entityTokenParentCacheHitCount != null) { _entityTokenParentCacheHitCount.Increment(); } } public void EntityTokenParentCacheMissIncrement() { if (_entityTokenParentCacheMissCount != null) { _entityTokenParentCacheMissCount.Increment(); } } private PerformanceCounter TryCreateCounter(string counterName) { PerformanceCounter performanceCounter = null; try { performanceCounter = new PerformanceCounter(PerformanceNames.CategoryName, counterName, GetInstanceName(), false); } catch(Exception ex) { LoggingService.LogWarning("WindowsPerformanceCounterProvider", ex); } return performanceCounter; } private static string GetInstanceName() { return RuntimeInformation.UniqueInstanceName; } private sealed class WindowsPerformanceCounterProviderToken : IPerformanceCounterToken { internal delegate void OnComplete(); public long StartTicks { get; set; } public long StopTicks { get; set; } public void Start() { this.StartTicks = DateTime.Now.Ticks; } public void Stop() { this.StopTicks = DateTime.Now.Ticks; } public void Dispose() { } } } } ================================================ FILE: Composite/Plugins/Logging/LogTraceListeners/FileLogTraceListener/CircullarList.cs ================================================ using System; using System.Linq; namespace Composite.Plugins.Logging.LogTraceListeners.FileLogTraceListener { class CircularList<T> where T: class { private readonly T[] _data; private readonly int _size; private int _position; public CircularList(int size) { _data = new T[size]; _size = size; } public int Count => (_position > _size) ? _size : _position; public void Add(T element) { _data[_position % _size] = element; _position++; } public T First() { return _position == 0 ? null : _data[Offset(_position - 1)]; } public T[] ToArray() { if (_position <= _size) { return _data.Take(_position).ToArray(); } var insertPosition = Offset(_position); var result = new T[_size]; Array.Copy(_data, insertPosition, result, 0, _size - insertPosition); Array.Copy(_data, 0, result, _size - insertPosition, insertPosition); return result; } private int Offset(int position) => position % _size; } } ================================================ FILE: Composite/Plugins/Logging/LogTraceListeners/FileLogTraceListener/CurrentFileReader.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using Composite.Core.Logging; namespace Composite.Plugins.Logging.LogTraceListeners.FileLogTraceListener { /// <summary> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] internal class CurrentFileReader : LogFileReader { private readonly FileLogger _fileLogger; public CurrentFileReader(FileLogger fileLogger) { _fileLogger = fileLogger; lock (_fileLogger.SyncRoot) { var fileConnection = _fileLogger.FileConnection; if (fileConnection != null) { Date = fileConnection.CreationDate; } } } public override bool Open() { // do nothing return true; } public override void Close() { // do nothing } public override int EntriesCount { get { DateTime readUntil; int count; string filePath; lock (_fileLogger.SyncRoot) { var fileConn = _fileLogger.FileConnection; var firstEntry = fileConn.NewEntries.First(); readUntil = firstEntry?.TimeStamp ?? DateTime.MaxValue; count = fileConn.NewEntries.Count; filePath = fileConn.FilePath; } using (var fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { foreach (var logEntry in LogReaderHelper.ParseLogLines(fs)) { if (logEntry.TimeStamp >= readUntil) { break; } count++; } } return count; } } public override IEnumerable<LogEntry> GetLogEntries(DateTime timeFrom, DateTime timeTo) { Verify.That(timeFrom <= timeTo, "An incorrect time interval given."); string filePath; LogEntry[] newEntries; lock (_fileLogger.SyncRoot) { var fileConn = _fileLogger.FileConnection; newEntries = fileConn.NewEntries.ToArray(); filePath = fileConn.FilePath; } DateTime readUntil = newEntries.FirstOrDefault()?.TimeStamp.AddMilliseconds(-1) ?? DateTime.Now; if (timeFrom <= readUntil) { using (var fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var parserEnumerable = LogReaderHelper.ParseLogLines(fs); foreach (var logEntry in parserEnumerable) { if(logEntry.TimeStamp < timeFrom) continue; if (logEntry.TimeStamp > timeTo || logEntry.TimeStamp > readUntil) break; yield return logEntry; } } } foreach (var logEntry in newEntries) { if (logEntry.TimeStamp < timeFrom) continue; if (logEntry.TimeStamp > timeTo) break; yield return logEntry; } } public override bool Delete() { return false; } } } ================================================ FILE: Composite/Plugins/Logging/LogTraceListeners/FileLogTraceListener/FileLogTraceListener.cs ================================================ using System; using System.Text; using System.Xml; using Composite.Core.Logging; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration; using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners; namespace Composite.Plugins.Logging.LogTraceListeners.FileLogTraceListener { [ConfigurationElementType(typeof(CustomTraceListenerData))] internal class FileLogTraceListener: CustomTraceListener { private static readonly TimeSpan TimeZoneAdjustment = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now); public FileLogTraceListener() { // That one should not be used } public FileLogTraceListener(string initializeData) { Verify.ArgumentNotNullOrEmpty(initializeData, nameof(initializeData)); string[] parts = initializeData.Split(new[] {','}); Verify.ArgumentCondition(parts.Length == 2, "initializeData", "Wrong configuration parameters"); if(LoggerInstance == null) { string logFolderPath = parts[0]; bool flushAfterEveryLine; if (!bool.TryParse(parts[1], out flushAfterEveryLine)) { throw new ArgumentException(initializeData, nameof(initializeData)); } // Setting public property, so it can be used by a webservice LoggerInstance = new FileLogger(logFolderPath, flushAfterEveryLine); } } public override void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, object data) { var logEntry = (Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry)data; var fileLogEntry = new LogEntry { TimeStamp = logEntry.TimeStamp.Add(TimeZoneAdjustment), ApplicationDomainId = AppDomain.CurrentDomain.Id, ThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId, Message = SanitizeForLog(logEntry.Message), Severity = logEntry.Severity.ToString(), }; string title = logEntry.Title; title = title.Substring(title.IndexOf(')') + 2); // Removing ({AppDomainId} - {ThreadId}}) prefix. // Extracting display options from title if (title.StartsWith("RGB(")) { fileLogEntry.DisplayOptions = title.Substring(0, title.IndexOf(')') + 1); title = title.Substring(fileLogEntry.DisplayOptions.Length); } fileLogEntry.Title = SanitizeForLog(title); LoggerInstance.WriteEntry(fileLogEntry); } public override void Write(string message) { // Do nothing here... } public override void WriteLine(string message) { // Do nothing here... } public static FileLogger LoggerInstance { get; private set; } private static string SanitizeForLog(string input) { if (string.IsNullOrEmpty(input)) { return input; } var builder = new StringBuilder(input.Length); foreach (char ch in input) { builder.Append(XmlConvert.IsXmlChar(ch) ? ch : ' '); } return builder.ToString(); } } } ================================================ FILE: Composite/Plugins/Logging/LogTraceListeners/FileLogTraceListener/FileLogger.cs ================================================ //#define UseLockFiles using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web.Hosting; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Logging; namespace Composite.Plugins.Logging.LogTraceListeners.FileLogTraceListener { /// <summary> /// File logger /// </summary> internal class FileLogger : IDisposable { private const int MaxLogFiles = 10; private bool _initializationFailed; #if UseLockFiles private static readonly TimeSpan LockFileUpdateFrequency = TimeSpan.FromSeconds(20); private static readonly TimeSpan OldLockFilesPreservationTime = TimeSpan.FromSeconds(60); private DateTime _lockFileUpdatedLast = DateTime.MinValue; #endif private static readonly TimeSpan FileStreamFlushInterval = TimeSpan.FromSeconds(5); private static readonly TimeSpan FileStreamCloseOnIdleInterval = TimeSpan.FromSeconds(10); private readonly string _logDirectoryPath; private readonly bool _flushImmediately; public static event ThreadStart OnReset; private static Task _flushOnIdleTask; internal LogFileInfo FileConnection; readonly object _syncRoot = new object(); public object SyncRoot => _syncRoot; public FileLogger(string logDirectoryPath, bool flushImmediately) { Verify.ArgumentNotNull(logDirectoryPath, "logDirectoryPath"); _logDirectoryPath = Path.Combine(PathUtil.BaseDirectory, logDirectoryPath); if (!C1Directory.Exists(_logDirectoryPath)) { C1Directory.CreateDirectory(_logDirectoryPath); } _flushImmediately = flushImmediately; _flushOnIdleTask = Task.Factory.StartNew(FlushOnIdle); #if UseLockFiles TouchLockFile(); #endif } private void FlushOnIdle() { Predicate<LogFileInfo> fileShouldBeClosed = logFile => logFile.LastUsageTime != null && DateTime.Now - logFile.LastUsageTime.Value > FileStreamCloseOnIdleInterval; Predicate<LogFileInfo> fileStreamShouldBeFlushed = logFile => { var lastFlushTime = logFile.LastFlushTime ?? logFile.StartupTime; return logFile.LastUsageTime != null && logFile.LastUsageTime.Value > lastFlushTime && DateTime.Now - lastFlushTime > FileStreamFlushInterval; }; while (!HostingEnvironment.ApplicationHost.ShutdownInitiated()) { Thread.Sleep(500); var conn = this.FileConnection; if (conn != null && (fileShouldBeClosed(conn) || fileStreamShouldBeFlushed(conn))) { lock (SyncRoot) { conn = this.FileConnection; if (conn != null) { if (fileShouldBeClosed(conn)) { CloseLogFile(true); } else if (fileStreamShouldBeFlushed(conn)) { Flush(true); } } } } } } public DateTime StartupTime { get { lock (_syncRoot) { return FileConnection?.StartupTime ?? DateTime.Now; } } } public void WriteEntry(LogEntry entry) { if (_initializationFailed) return; string logLine = entry.ToString(); byte[] bytes = Encoding.UTF8.GetBytes(logLine + "\n"); lock (_syncRoot) { // Checking whether we should change the file after midnight int dayNumber = entry.TimeStamp.Day; var now = DateTime.Now; if (FileConnection != null && dayNumber != FileConnection.CreationDate.Day && dayNumber == now.Day) { CloseLogFile(true); } EnsureInitialize(); if (_initializationFailed) return; FileConnection.NewEntries.Add(entry); // Writing the file in the "catch" block in order to prevent chance of corrupting the file by experiencing ThreadAbortException. Exception thrownException = null; try { } finally { try { FileConnection.FileStream.Write(bytes, 0, bytes.Length); FileConnection.LastUsageTime = now; if (_flushImmediately) { Flush(false); } } catch (Exception exception) { thrownException = exception; } } // ThreadAbortException should have a higher priority, and therefore we're doing rethrow in a separate block if (thrownException != null) throw thrownException; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass", Justification = "This is what we want, touch is used later on")] public LogFileReader[] GetLogFiles() { #if UseLockFiles if (MoreThanOneAppDomainRunning()) return Array.Empty<LogFileReader>(); #endif string[] filePathes = Directory.GetFiles(_logDirectoryPath); string currentlyOpenedFileName = null; var result = new List<LogFileReader>(); lock (_syncRoot) { if (FileConnection != null) { currentlyOpenedFileName = FileConnection.FileName; result.Add(new CurrentFileReader(this)); FileConnection.LastUsageTime = DateTime.Now; } } foreach (string filePath in filePathes) { string fileName = Path.GetFileName(filePath); // Skipping file to which we're currently using if (currentlyOpenedFileName != null && string.Compare(fileName, currentlyOpenedFileName, StringComparison.OrdinalIgnoreCase) == 0) { continue; } // File names have format yyyymmdd[_number].txt if (fileName.Length < 12) { continue; } DateTime date; if (!DateTime.TryParseExact(fileName.Substring(0, 8), "yyyyMMdd", CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out date)) { continue; } result.Add(new PlainFileReader(filePath, date)); } // Sorting by date result.Sort((a, b) => a.Date.CompareTo(b.Date)); return result.ToArray(); } internal void Flush(bool silent) { lock (_syncRoot) { if (FileConnection != null) { try { FileConnection.FileStream.Flush(); } catch (Exception) when (silent) { } FileConnection.LastFlushTime = DateTime.Now; } } } [DebuggerStepThrough] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass", Justification = "This is what we want, touch is used later on")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass", Justification = "This is what we want, touch is used later on")] private static FileStream TryOpenFile(string filePath, out Exception e) { e = null; try { return File.Open(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read); } catch (Exception ex) { e = ex; return null; } } [DebuggerStepThrough] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass", Justification = "This is what we want, touch is used later on")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass", Justification = "This is what we want, touch is used later on")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DotNotUseStreamReaderClass:DotNotUseStreamReaderClass", Justification = "This is what we want, touch is used later on")] private static bool TryReadAndOpen(string filePath, out string[] content, out FileStream stream, out Exception exception) { content = null; stream = null; exception = null; try { stream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read); // Not disposing StreamReader so the stream is not closed afterwards var reader = new StreamReader(stream, Encoding.UTF8, true); var lines = new List<string>(); string line; while ((line = reader.ReadLine()) != null) { lines.Add(line); } content = lines.ToArray(); } catch (Exception e) { exception = e; return false; } return true; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass", Justification = "This is what we want, touch is used later on")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass", Justification = "This is what we want, touch is used later on")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileStreamClass:DoNotUseFileStreamClass", Justification = "This is what we want, touch is used later on")] private void EnsureInitialize() { #if UseLockFiles TouchLockFile(); RemoveOldLockFiles(); #endif if (FileConnection != null) return; lock (_syncRoot) { if (FileConnection != null) return; DateTime creationDate = DateTime.Now; string fileNamePrefix = creationDate.ToString("yyyyMMdd"); for (int i = 0; i < MaxLogFiles; i++) { var fileName = fileNamePrefix + (i > 0 ? "_" + i : string.Empty) + ".txt"; string filePath = Path.Combine(_logDirectoryPath, fileName); FileStream stream; Exception ex; if (!File.Exists(filePath)) { stream = TryOpenFile(filePath, out ex); if (stream == null) { // Ignoring this exception if the file has already created if (File.Exists(filePath)) continue; throw new Exception($"Failed to create file '{filePath}'", ex); } FileConnection = new LogFileInfo { CreationDate = creationDate.Date, StartupTime = creationDate, FileName = fileName, FilePath = filePath, FileStream = stream }; WriteUTF8EncodingHeader(stream); return; } string[] alreadyWritten; if (!TryReadAndOpen(filePath, out alreadyWritten, out stream, out ex)) { // Trying another file name, since the file may be in use by another process continue; } FileConnection = new LogFileInfo { CreationDate = creationDate.Date, StartupTime = creationDate, FileName = fileName, FilePath = filePath, FileStream = stream }; return; } _initializationFailed = true; } } #if UseLockFiles [SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] [SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] private void RemoveOldLockFiles() { foreach (string filePath in Directory.GetFiles(_logDirectoryPath, "*.lock")) { string appDomainIdString = Path.GetFileNameWithoutExtension(filePath); int appDomainId; if (!int.TryParse(appDomainIdString, out appDomainId)) continue; if (appDomainId != AppDomain.CurrentDomain.Id) { DateTime lastWrite = File.GetLastWriteTime(filePath); TimeSpan fileAge = DateTime.Now - lastWrite; if (fileAge > OldLockFilesPreservationTime) { try { File.Delete(filePath); } catch (Exception) { // Ignore } } } } } [SuppressMessage("Composite.IO", "Composite.DoNotUseDirectoryClass:DoNotUseDirectoryClass")] private bool MoreThanOneAppDomainRunning() { return Directory.GetFiles(_logDirectoryPath, "*.lock").Length > 1; } #endif private void CloseLogFile(bool raiseOnResetEvent) { if (FileConnection != null) { FileConnection.Dispose(); FileConnection = null; } if (raiseOnResetEvent) { OnReset?.Invoke(); } } private static void WriteUTF8EncodingHeader(Stream stream) { byte[] preamble = Encoding.UTF8.GetPreamble(); stream.Write(preamble, 0, preamble.Length); } #if UseLockFiles [SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] private void TouchLockFile() { if (_lockFileUpdatedLast + LockFileUpdateFrequency >= DateTime.Now) { return; } // Create .lock file try { File.WriteAllText(LockFileName, ""); _lockFileUpdatedLast = DateTime.Now; } catch (Exception) { // Ignore } } #endif #if UseLockFiles private string LockFileName => Path.Combine(_logDirectoryPath, AppDomain.CurrentDomain.Id + ".lock"); #endif bool _disposed; [SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass")] protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { CloseLogFile(false); } _disposed = true; } #if UseLockFiles // Delete the file in any case try { File.Delete(LockFileName); } catch (Exception) { // Ignore } #endif } public void Dispose() { Dispose(true); #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// <exclude /> ~FileLogger() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); Dispose(false); } #endif } } ================================================ FILE: Composite/Plugins/Logging/LogTraceListeners/FileLogTraceListener/LogFileInfo.cs ================================================ using System; using System.IO; using Composite.Core.Logging; namespace Composite.Plugins.Logging.LogTraceListeners.FileLogTraceListener { internal class LogFileInfo : IDisposable { public string FileName; public string FilePath; public FileStream FileStream; public CircularList<LogEntry> NewEntries = new CircularList<LogEntry>(100); public DateTime CreationDate; public DateTime? LastUsageTime; public DateTime? LastFlushTime; public DateTime StartupTime; private bool _disposed; public void Dispose() { if (!_disposed) { FileStream.Dispose(); _disposed = true; } #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// <exclude /> ~LogFileInfo() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } ================================================ FILE: Composite/Plugins/Logging/LogTraceListeners/FileLogTraceListener/LogFileReader.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using Composite.Core.Logging; namespace Composite.Plugins.Logging.LogTraceListeners.FileLogTraceListener { /// <summary> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] internal abstract class LogFileReader { public DateTime Date { get; protected set; } public abstract int EntriesCount { get; } public abstract bool Open(); public abstract void Close(); public abstract bool Delete(); public abstract IEnumerable<LogEntry> GetLogEntries(DateTime timeFrom, DateTime timeFromTo); } } ================================================ FILE: Composite/Plugins/Logging/LogTraceListeners/FileLogTraceListener/LogReaderHelper.cs ================================================ using System.Collections.Generic; using System.IO; using System.Text; using Composite.Core.Logging; namespace Composite.Plugins.Logging.LogTraceListeners.FileLogTraceListener { internal static class LogReaderHelper { public static IEnumerable<string> GetLinesEnumerable(FileStream fileStream) { using (var reader = new StreamReader(fileStream, Encoding.UTF8)) { while (reader.Peek() >= 0) { yield return reader.ReadLine(); } } } public static IEnumerable<LogEntry> ParseLogLines(FileStream fileStream) { var linesEnumerable = GetLinesEnumerable(fileStream); return ParseLogLines(linesEnumerable); } public static IEnumerable<LogEntry> ParseLogLines(IEnumerable<string> lines) { var multilineMessage = new StringBuilder(); LogEntry currentEntry = null; foreach (string line in lines) { LogEntry nextEntry = LogEntry.Parse(line); if (nextEntry != null) { if (currentEntry != null) { if (multilineMessage.Length > 0) { currentEntry.Message = multilineMessage.ToString(); multilineMessage.Clear(); } yield return currentEntry; } currentEntry = nextEntry; } else { if (currentEntry != null) { if (multilineMessage.Length == 0) { multilineMessage.Append(currentEntry.Message); } multilineMessage.AppendLine(line); } } } if (currentEntry != null) { if (multilineMessage.Length > 0) { currentEntry.Message = multilineMessage.ToString(); multilineMessage.Clear(); } yield return currentEntry; } } } } ================================================ FILE: Composite/Plugins/Logging/LogTraceListeners/FileLogTraceListener/PlainFileReader.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using Composite.Core.Logging; namespace Composite.Plugins.Logging.LogTraceListeners.FileLogTraceListener { /// <summary> /// </summary> /// <exclude /> [EditorBrowsable(EditorBrowsableState.Never)] internal class PlainFileReader : LogFileReader { private FileStream _file; private readonly string _filePath; private int? _entriesCount; public PlainFileReader(string filePath, DateTime date) { _filePath = filePath; Date = date; } [DebuggerStepThrough] [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass", Justification = "This is what we want, touch is used later on")] public override bool Open() { try { _file = File.OpenRead(_filePath); } catch (Exception) { return false; } return true; } public override void Close() { if (_file == null) return; _file.Close(); _file.Dispose(); _file = null; } public override IEnumerable<LogEntry> GetLogEntries(DateTime timeFrom, DateTime timeFromTo) { var logLines = LogReaderHelper.GetLinesEnumerable(_file); return LogReaderHelper.ParseLogLines(logLines); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass", Justification = "This is what we want, touch is used later on")] public override int EntriesCount { get { if (_entriesCount == null) { try { Open(); _entriesCount = GetLogEntries(DateTime.MinValue, DateTime.MaxValue).Count(); } finally { Close(); } } return (int)_entriesCount; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass", Justification = "This is what we want, touch is used later on")] public override bool Delete() { try { File.Delete(_filePath); return true; } catch { return false; } } } } ================================================ FILE: Composite/Plugins/Logging/LogTraceListeners/ManagementConsoleLogTracer/ManagementConsoleLogTracer.cs ================================================ using System; using System.Text.RegularExpressions; using Composite.C1Console.Events; using Composite.Core.Logging; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration; using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners; namespace Composite.Plugins.Logging.LogTraceListeners.ManagementConsoleLogTracer { [ConfigurationElementType(typeof(CustomTraceListenerData))] internal sealed class ManagementConsoleLogTracer : CustomTraceListener { private LogLevel _logLevel; public ManagementConsoleLogTracer() { _logLevel = LogLevel.Info; } public ManagementConsoleLogTracer(string logLevel) { switch (logLevel) { case "Fine": _logLevel = LogLevel.Fine; break; case "Info": _logLevel = LogLevel.Info; break; case "Fatal": _logLevel = LogLevel.Fatal; break; case "Warning": _logLevel = LogLevel.Warning; break; case "Debug": _logLevel = LogLevel.Debug; break; case "Error": _logLevel = LogLevel.Error; break; default: throw new ArgumentException( "Unhandled log level: " + logLevel); } } public override void Write(string message) { Regex regex = new Regex(@"RGB\((?<r>[0-9]+), (?<g>[0-9]+), (?<b>[0-9]+)\)"); Match matchMessage = regex.Match(message); if (matchMessage.Success) { message = message.Replace(matchMessage.Groups[0].Value, ""); } LogEntryMessageQueueItem messageItem = new LogEntryMessageQueueItem { Level = _logLevel, Message = message, Sender = this.GetType() }; ConsoleMessageQueueFacade.Enqueue(messageItem, null); } public override void WriteLine(string message) { this.Write(message); } } } ================================================ FILE: Composite/Plugins/Logging/LogTraceListeners/SystemDiagnosticsTrace/SystemDiagnosticsTraceBridge.cs ================================================ using System; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration; using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners; namespace Composite.Plugins.Logging.LogTraceListeners.SystemDiagnosticsTrace { [ConfigurationElementType(typeof(CustomTraceListenerData))] internal sealed class SystemDiagnosticsTraceBridge : CustomTraceListener { public SystemDiagnosticsTraceBridge() { } public SystemDiagnosticsTraceBridge(string initializeData) { } public override void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, object data) { var logEntry = (Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry)data; string title = logEntry.Title; title = title.Substring(title.IndexOf(')') + 2); // Removing ({AppDomainId} - {ThreadId}}) prefix. if (title.StartsWith("RGB(")) { string displayOptions = title.Substring(0, title.IndexOf(')') + 1); title = title.Substring(displayOptions.Length); } string message = String.Format("[{0}] {1}", title, logEntry.Message); switch (logEntry.Severity) { case System.Diagnostics.TraceEventType.Critical: case System.Diagnostics.TraceEventType.Error: System.Diagnostics.Trace.TraceError(message); break; case System.Diagnostics.TraceEventType.Warning: System.Diagnostics.Trace.TraceWarning(message); break; case System.Diagnostics.TraceEventType.Information: System.Diagnostics.Trace.TraceInformation(message); break; default: System.Diagnostics.Trace.WriteLine(message); break; } System.Diagnostics.Trace.Flush(); } public override void Write(string message) { System.Diagnostics.Trace.Write(message); } public override void WriteLine(string message) { System.Diagnostics.Trace.WriteLine(message); } } } ================================================ FILE: Composite/Plugins/PageTemplates/Common/CachedTemplateInformation.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Core.IO; namespace Composite.Plugins.PageTemplates.Common { internal class CachedTemplateInformation { private CachedTemplateInformation() {} public CachedTemplateInformation(Core.PageTemplates.PageTemplateDescriptor parsedTemplate) { TemplateId = parsedTemplate.Id; Title = parsedTemplate.Title; } public Guid TemplateId { get; set; } public string Title { get; set; } public static void SerializeToFile(CachedTemplateInformation pageTemplate, string filePath) { var lines = new List<string>(); if (pageTemplate != null) { lines.Add(pageTemplate.TemplateId.ToString()); lines.Add(pageTemplate.Title); } C1File.WriteAllLines(filePath, lines); } public static CachedTemplateInformation DeserializeFromFile(string filePath) { var lines = C1File.ReadAllLines(filePath); if (lines == null || lines.Length == 0) { return null; } Guid templateId = Guid.Parse(lines[0]); string title = string.Join(Environment.NewLine, lines.Skip(1)); return new CachedTemplateInformation { TemplateId = templateId, Title = title }; } } } ================================================ FILE: Composite/Plugins/PageTemplates/Common/TemplateParsingHelper.cs ================================================ using System; using System.Text; using Composite.Core.Extensions; using Composite.Core.IO; namespace Composite.Plugins.PageTemplates.Common { internal static class TemplateParsingHelper { public static bool TryExtractTemplateIdFromCSharpCode(string filePath, out Guid templateId, string idTokenBegin, string idTokenEnd) { templateId = Guid.Empty; if (!C1File.Exists(filePath)) return false; var allText = C1File.ReadAllText(filePath, Encoding.UTF8); allText = RemoveWhiteSpaces(allText); string beginning = RemoveWhiteSpaces(idTokenBegin); string ending = RemoveWhiteSpaces(idTokenEnd); int firstIndex = allText.IndexOf(beginning, StringComparison.Ordinal); if (firstIndex < 0) return false; int lastIndex = allText.LastIndexOf(beginning, StringComparison.Ordinal); if (lastIndex != firstIndex) return false; int endOffset = allText.IndexOf(ending, firstIndex, StringComparison.Ordinal); if (endOffset < 0) return false; int guidOffset = firstIndex + beginning.Length; string guidStr = allText.Substring(guidOffset, endOffset - guidOffset); return Guid.TryParse(guidStr, out templateId); } private static string RemoveWhiteSpaces(string str) { var whiteSpaces = new[] { ' ', '\t', '\r', '\n' }; whiteSpaces.ForEach(ch => str = str.Replace(new string(ch, 1), "")); return str; } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/CompilationHelper.cs ================================================ using System; using System.Reflection; using System.Web; using System.Web.Compilation; using System.Web.UI; using System.Web.Util; using Composite.Core.WebClient; namespace Composite.Plugins.PageTemplates.MasterPages { internal static class CompilationHelper { public static MasterPage CompileMasterPage(string virtualPath) { // Calling: object virtualPathObj = new System.Web.VirtualPath(virtualPath); Assembly asmSystemWeb = typeof(HttpContext).Assembly; Type tVirtualType = asmSystemWeb.GetType("System.Web.VirtualPath"); var virtualTypeConstructor = tVirtualType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(string) }, null); object virtualPathObj = virtualTypeConstructor.Invoke(new object[] { virtualPath }); // Calling: return System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(null, virtualPathObj, false, false, false) IWebObjectFactory factory; using(BuildManagerHelper.DisableUrlMetadataCachingScope()) { factory = typeof(BuildManager) .GetMethod("GetVPathBuildResultWithNoAssert", BindingFlags.NonPublic | BindingFlags.Static, null, CallingConventions.Any, new Type[] { typeof(HttpContext), tVirtualType, typeof(bool), typeof(bool), typeof(bool) }, null) .Invoke(null, new object[] { null, virtualPathObj, false, false, false }) as IWebObjectFactory; } Verify.IsNotNull(factory, "Failed to compile master page file"); return factory.CreateInstance() as MasterPage; } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/Controls/Functions/Function.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Xml.Linq; using Composite.Core.Extensions; using Composite.Core.Types; using Composite.Core.WebClient.Renderings.Page; using Composite.Core.Xml; using Composite.Functions; namespace Composite.Plugins.PageTemplates.MasterPages.Controls.Functions { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [PersistChildren(false)] [ParseChildren(true, "Parameters")] public class Function : Control { private static readonly string LogTitle = "Controls.Function"; /// <exclude /> public string Name { get; set; } private ParamCollection _parameters; /// <exclude /> [PersistenceMode(PersistenceMode.InnerDefaultProperty)] [DefaultValue(default(string))] [MergableProperty(false)] public ParamCollection Parameters { get { if (_parameters == null) { _parameters = new ParamCollection(); } return _parameters; } } /// <exclude /> protected override void OnInit(EventArgs e) { Type returnType; object result; string functionName = Name; var functionContextContainer = PageRenderer.GetPageRenderFunctionContextContainer(); try { result = GetValue(functionContextContainer, out returnType); } catch (Exception ex) { XElement errorBoxHtml; if (!functionContextContainer.ProcessException(functionName, ex, LogTitle, out errorBoxHtml)) { throw; } result = errorBoxHtml; returnType = typeof(XElement); } if (result != null) { if (returnType == typeof(XElement) || returnType == typeof(XhtmlDocument)) { var element = ValueTypeConverter.Convert<XElement>(result); var markup = new Markup(element, functionContextContainer); Controls.Add(markup); } else if (typeof(Control).IsAssignableFrom(returnType)) { var control = (Control) result; Controls.Add(control); } else if (result is IEnumerable<XNode>) { var nodes = result as IEnumerable<XNode>; foreach (XNode node in nodes) { if (node == null) continue; if (node is XElement) { var markup = new Markup(node as XElement, functionContextContainer); Controls.Add(markup); } else { Controls.Add(new LiteralControl(node.ToString())); } } } else if (result is XAttribute) { var parentControl = this.Parent as HtmlGenericControl; if(parentControl != null) { var attr = (XAttribute) result; parentControl.Attributes.Add(attr.Name.ToString(), attr.Value); } else { const string comment = @"<!-- Failed to add attribute, parent control should be of type HtmlGenericControl, check that runat=""server"" attribute is added -->"; Controls.Add(new LiteralControl(comment)); } } else { var str = result.ToString(); Controls.Add(new LiteralControl(str)); } } base.OnInit(e); } private object GetValue(FunctionContextContainer functionContextContainer, out Type returnType) { string functionName = Name; IFunction function; if (!FunctionFacade.TryGetFunction(out function, functionName)) { throw new InvalidOperationException("Invalid function name '{0}'".FormatWith(functionName)); } returnType = function.ReturnType; IDictionary<string, object> parameters = parseParameters(functionContextContainer); VerifyParameterMatch(function, parameters); return ExecuteFunction(function, parameters, functionContextContainer); } /// <summary> /// Executes the function. Note that all the XhtmlParameters will have all the nested >f:function /< lazily evaluated /// </summary> private static object ExecuteFunction(IFunction function, IDictionary<string, object> parameters, FunctionContextContainer functionContextContainer ) { List<BaseParameterRuntimeTreeNode> parameterNodes = new List<BaseParameterRuntimeTreeNode>(); if (parameters != null) { foreach (KeyValuePair<string, object> kvp in parameters) { var value = kvp.Value; if (value is XhtmlDocument) { parameterNodes.Add(new LazyParameterRuntimeTreeNode(kvp.Key, () => ExecuteNestedFunctions(value as XhtmlDocument, functionContextContainer))); } else { parameterNodes.Add(new ConstantObjectParameterRuntimeTreeNode(kvp.Key, kvp.Value)); } } } var treeNode = new FunctionRuntimeTreeNode(function, parameterNodes); return treeNode.GetValue(functionContextContainer); } private static XhtmlDocument ExecuteNestedFunctions(XhtmlDocument document, FunctionContextContainer functionContextContainer) { PageRenderer.ExecuteEmbeddedFunctions(document.Root, functionContextContainer); return document; } private static void VerifyParameterMatch(IFunction function, IDictionary<string, object> parameters) { var initializationInfo = function as IFunctionInitializationInfo; if(initializationInfo != null && !initializationInfo.FunctionInitializedCorrectly) return; foreach(string parameterName in parameters.Keys) { Verify.That(function.ParameterProfiles.Any(p => p.Name == parameterName), "Function '{0}.{1}' does not have parameter '{2}' defined", function.Namespace, function.Name, parameterName); } } private IDictionary<string, object> parseParameters(FunctionContextContainer functionContextContainer) { var result = new Dictionary<string, object>(); foreach (Param param in Parameters) { param.DataBind(); object value; if (param.Controls.Count == 1 && param.Controls[0] is Function) { var nestedFunction = param.Controls[0] as Function; Type returnType; value = nestedFunction.GetValue(functionContextContainer, out returnType); } else { value = param.Value; } result.Add(param.Name, value); } return result; } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/Controls/Functions/LazyParameterRuntimeTreeNode.cs ================================================ using System; using System.Collections.Generic; using Composite.Functions; namespace Composite.Plugins.PageTemplates.MasterPages.Controls.Functions { internal class LazyParameterRuntimeTreeNode : BaseParameterRuntimeTreeNode { private readonly Func<object> _getValueFunction; private object _result; private bool _evaluated; public LazyParameterRuntimeTreeNode(string parameterName, Func<object> getValueFunction) : base(parameterName) { _getValueFunction = getValueFunction; } public override object GetValue(FunctionContextContainer contextContainer) { if (!_evaluated) { _result = _getValueFunction(); _evaluated = true; } return _result; } public override IEnumerable<string> GetAllSubFunctionNames() { throw new NotSupportedException(); } public override bool ContainsNestedFunctions { get { return false; } } public override System.Xml.Linq.XElement Serialize() { throw new NotSupportedException(); } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/Controls/Functions/Markup.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Xml.Linq; using Composite.AspNet; using Composite.Core.Localization; using Composite.Core.WebClient.Renderings.Page; using Composite.Core.Xml; using Composite.Functions; using Composite.Plugins.PageTemplates.MasterPages.Controls.Rendering; namespace Composite.Plugins.PageTemplates.MasterPages.Controls.Functions { /// <exclude /> [ParseChildren(false)] public class Markup : Control { private readonly FunctionContextContainer _functionContextContainer; /// <exclude /> protected XElement InnerContent { get; set; } /// <exclude /> public Markup() { } /// <exclude /> public Markup(XElement content, FunctionContextContainer functionContextContainer) { if(content.Name.LocalName == "html") { InnerContent = content; } else { var document = new XhtmlDocument(); document.Body.Add(content); InnerContent = document.Root; } _functionContextContainer = functionContextContainer; } /// <exclude /> protected override void OnInit(EventArgs e) { EnsureChildControls(); base.OnInit(e); } /// <exclude /> protected override void CreateChildControls() { if (InnerContent == null) { ProcessInternalControls(); } if (InnerContent != null) { var functionContextContainer = _functionContextContainer; if (functionContextContainer == null && this.NamingContainer is UserControlFunction) { var containerFunction = this.NamingContainer as UserControlFunction; functionContextContainer = containerFunction.FunctionContextContainer; } if (functionContextContainer == null) { functionContextContainer = PageRenderer.GetPageRenderFunctionContextContainer(); } var controlMapper = (IXElementToControlMapper) functionContextContainer.XEmbedableMapper; PageRenderer.ExecuteEmbeddedFunctions(InnerContent, functionContextContainer); var xhmlDocument = new XhtmlDocument(InnerContent); PageRenderer.NormalizeXhtmlDocument(xhmlDocument); PageRenderer.ResolveRelativePaths(xhmlDocument); if (PageRenderer.CurrentPage != null) { PageRenderer.ResolvePageFields(xhmlDocument, PageRenderer.CurrentPage); } NormalizeAspNetForms(xhmlDocument); AddNodesAsControls(xhmlDocument.Body.Nodes(), this, controlMapper); if (Page.Header != null) { MergeHeadSection(xhmlDocument, Page.Header, controlMapper); } } base.CreateChildControls(); } private void MergeHeadSection(XhtmlDocument xhtmlDocument, HtmlHead headControl, IXElementToControlMapper controlMapper) { xhtmlDocument.MergeToHeadControl(headControl, controlMapper); // handling custom master page head control locally - removing it if a generic meta description tag was in the document if (headControl.Controls.OfType<HtmlMeta>().Any(f=>f.Name=="description")) { var existingDescriptionMetaTag = headControl.Controls.OfType<DescriptionMetaTag>().FirstOrDefault(); if (existingDescriptionMetaTag != null) { headControl.Controls.Remove(existingDescriptionMetaTag); } } } private void NormalizeAspNetForms(XhtmlDocument xhtmlDocument) { // If current control is inside <form id="" runat="server"> tag all <asp:forms> tags will be removed from placeholder bool isInsideAspNetForm = false; var ansestor = this.Parent; while (ansestor != null) { if (ansestor is HtmlForm) { isInsideAspNetForm = true; break; } ansestor = ansestor.Parent; } if (!isInsideAspNetForm) { return; } List<XElement> aspNetFormElements = xhtmlDocument.Descendants(Namespaces.AspNetControls + "form").Reverse().ToList(); foreach (XElement aspNetFormElement in aspNetFormElements) { aspNetFormElement.ReplaceWith(aspNetFormElement.Nodes()); } } private void ProcessInternalControls() { string str = null; if (Controls.Count > 0) { var content = Controls[0] as LiteralControl; if (content != null) { str = content.Text; } } if (!String.IsNullOrEmpty(str)) { Controls.Clear(); InnerContent = new XElement(Namespaces.Xhtml + "html", new XAttribute(XNamespace.Xmlns + "f", Namespaces.Function10), new XAttribute(XNamespace.Xmlns + "lang", LocalizationXmlConstants.XmlNamespace), new XElement(Namespaces.Xhtml + "head"), new XElement(Namespaces.Xhtml + "body", XElement.Parse(str))); } } private static void AddNodesAsControls(IEnumerable<XNode> nodes, Control parent, IXElementToControlMapper mapper) { foreach (var node in nodes) { var c = node.AsAspNetControl(mapper); parent.Controls.Add(c); } } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/Controls/Functions/Param.cs ================================================ using System.ComponentModel; using System.Web.UI; namespace Composite.Plugins.PageTemplates.MasterPages.Controls.Functions { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ControlBuilder(typeof(ParamControlBuilder))] public class Param : Control, IParserAccessor { private object _value; /// <exclude /> [TypeConverter(typeof(StringToObjectConverter))] public object Value { get { return _value; } set { if (value is ParamObjectConverter) { _value = ((ParamObjectConverter)value).Value; } else { _value = value; } } } /// <exclude /> public string Name { get; set; } /// <exclude /> public Param() { } /// <exclude /> public Param(string name, object value) { Name = name; Value = value; } /// <exclude /> protected override void AddParsedSubObject(object obj) { if (!HasControls() && (obj is LiteralControl)) { this.Value = ((LiteralControl)obj).Text; return; } base.AddParsedSubObject(obj); } /// <exclude /> protected override void DataBindChildren() { base.DataBindChildren(); if (Value == null) { if (Controls.Count > 0) { var child = Controls[0]; if (child is DataBoundLiteralControl) { Value = ((DataBoundLiteralControl)child).Text; } } } } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/Controls/Functions/ParamCollection.cs ================================================ using System; using System.Collections; namespace Composite.Plugins.PageTemplates.MasterPages.Controls.Functions { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ParamCollection : IList, ICollection, IEnumerable { private readonly ArrayList _innerList = new ArrayList(); /// <exclude /> public void Add(Param value) { _innerList.Add(value); } /// <exclude /> public void Clear() { _innerList.Clear(); } /// <exclude /> public bool Contains(Param value) { return _innerList.Contains(value); } /// <exclude /> public int IndexOf(Param value) { return _innerList.IndexOf(value); } /// <exclude /> public void Insert(int index, Param value) { _innerList.Insert(index, value); } /// <exclude /> public bool IsFixedSize { get { return false; } } /// <exclude /> public bool IsReadOnly { get { return false; } } /// <exclude /> public void Remove(Param value) { _innerList.Remove(value); } /// <exclude /> public void RemoveAt(int index) { _innerList.RemoveAt(index); } /// <exclude /> public Param this[int index] { get { return (Param)_innerList[index]; } set { _innerList[index] = value; } } /// <exclude /> public void CopyTo(Array array, int index) { _innerList.CopyTo(array, index); } /// <exclude /> public int Count { get { return _innerList.Count; } } /// <exclude /> public bool IsSynchronized { get { return _innerList.IsSynchronized; } } /// <exclude /> public object SyncRoot { get { return this; } } /// <exclude /> public IEnumerator GetEnumerator() { return _innerList.GetEnumerator(); } int IList.Add(object value) { var param = (Param)value; return _innerList.Add(param); } bool IList.Contains(object value) { return this.Contains((Param)value); } int IList.IndexOf(object value) { return this.IndexOf((Param)value); } void IList.Insert(int index, object value) { this.Insert(index, (Param)value); } void IList.Remove(object value) { this.Remove((Param)value); } object IList.this[int index] { get { return this._innerList[index]; } set { this._innerList[index] = (Param)value; } } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/Controls/Functions/ParamObjectConverter.cs ================================================ namespace Composite.Plugins.PageTemplates.MasterPages.Controls.Functions { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ParamObjectConverter { /// <exclude /> public object Value { get; set; } /// <exclude /> public ParamObjectConverter() { } /// <exclude /> public ParamObjectConverter(string oValue) : this() { this.Value = oValue; } /// <exclude /> public override string ToString() { return Value == null ? string.Empty : Value.ToString(); } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/Controls/Functions/ParamTagControlBuilder.cs ================================================ using System.Web.UI; namespace Composite.Plugins.PageTemplates.MasterPages.Controls.Functions { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class ParamControlBuilder : ControlBuilder { /// <exclude /> public override bool AllowWhitespaceLiterals() { return false; } /// <exclude /> public override bool HtmlDecodeLiterals() { return true; } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/Controls/Functions/StringToObjectConverter.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Globalization; namespace Composite.Plugins.PageTemplates.MasterPages.Controls.Functions { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class StringToObjectConverter : TypeConverter { /// <exclude /> public override bool IsValid(ITypeDescriptorContext context, object value) { return true; } /// <exclude /> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } /// <exclude /> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(object)) { return true; } if (destinationType == typeof(InstanceDescriptor)) { return true; } return base.CanConvertTo(context, destinationType); } /// <exclude /> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { return value.ToString(); } /// <exclude /> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(object)) { return (object)value; } if (destinationType == typeof(InstanceDescriptor)) { return new InstanceDescriptor(typeof(ParamObjectConverter).GetConstructor(new Type[] { value.GetType() }), new object[] { value }); } return base.ConvertTo(context, culture, value, destinationType); } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/Controls/Rendering/Description.cs ================================================ using System.Web.UI; using Composite.Core.WebClient.Renderings.Page; namespace Composite.Plugins.PageTemplates.MasterPages.Controls.Rendering { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Description : Control { /// <exclude /> protected override void Render(HtmlTextWriter writer) { string description = Page.Header.Description; if (string.IsNullOrWhiteSpace(description)) { description = PageRenderer.CurrentPage.Description; } if (string.IsNullOrWhiteSpace(description)) return; writer.WriteEncodedText(description); } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/Controls/Rendering/DescriptionMetaTag.cs ================================================ using System.Web.UI; using Composite.Core.WebClient.Renderings.Page; namespace Composite.Plugins.PageTemplates.MasterPages.Controls.Rendering { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class DescriptionMetaTag : Control { /// <exclude /> protected override void Render(HtmlTextWriter writer) { string description = Page.Header.Description; if (string.IsNullOrWhiteSpace(description)) { description = PageRenderer.CurrentPage.Description; } if(string.IsNullOrWhiteSpace(description)) return; writer.AddAttribute("name", "description"); writer.AddAttribute("content", description, true); writer.RenderBeginTag("meta"); writer.RenderEndTag(); } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/Controls/Rendering/PageTemplateFeature.cs ================================================ using System.Web.UI; using Composite.Core.WebClient.Renderings.Page; using Composite.Core.WebClient.Renderings.Template; using Composite.Core.Xml; using Composite.Functions; using Composite.Plugins.PageTemplates.MasterPages.Controls.Functions; namespace Composite.Plugins.PageTemplates.MasterPages.Controls.Rendering { /// <summary> /// /// </summary> public class PageTemplateFeature : Control { /// <summary> /// Name of Page Template Feature to include /// </summary> public string Name { get; set; } /// <exclude /> protected override void OnInit(System.EventArgs e) { XhtmlDocument feature = PageTemplateFeatureFacade.GetPageTemplateFeature(this.Name); FunctionContextContainer functionContextContainer = PageRenderer.GetPageRenderFunctionContextContainer(); var markup = new Markup(feature.Root, functionContextContainer); Controls.Add(markup); base.OnInit(e); } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/Controls/Rendering/Render.cs ================================================ using System; using System.Linq; using System.Xml.Linq; using Composite.Core.Localization; using Composite.Core.Xml; using Composite.Plugins.PageTemplates.MasterPages.Controls.Functions; namespace Composite.Plugins.PageTemplates.MasterPages.Controls.Rendering { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Render : Markup { private string _placeholderId; /// <exclude /> public string PlaceholderID { get { return _placeholderId; } set { _placeholderId = value; } } /// <exclude /> public bool HasBody { get { EnsureChildControls(); if (Markup == null) { return false; } var body = new XhtmlDocument(Markup).Body; return body != null && body.Nodes().Any(); } } /// <exclude /> public XhtmlDocument Markup { get { return InnerContent == null ? null : new XhtmlDocument(base.InnerContent); } set { InnerContent = value != null ? value.Root : null; } } /// <exclude /> protected override void CreateChildControls() { DataBind(); if (InnerContent == null) { var renderingInfo = MasterPagePageRenderer.GetRenderingInfo(this.Page); string placeholderId = PlaceholderID ?? ID; if (placeholderId != null) { var content = renderingInfo.Contents.SingleOrDefault(c => c.PlaceHolderId == placeholderId); if (content == null) { InnerContent = new XElement(Namespaces.Xhtml + "html", new XAttribute(XNamespace.Xmlns + "f", Namespaces.Function10), new XAttribute(XNamespace.Xmlns + "lang", LocalizationXmlConstants.XmlNamespace), new XElement(Namespaces.Xhtml + "head"), new XElement(Namespaces.Xhtml + "body")); } else { if (content.Content.StartsWith("<html")) { try { InnerContent = XhtmlDocument.Parse(content.Content).Root; } catch (ArgumentException) { } } else { InnerContent = new XElement(Namespaces.Xhtml + "html", new XAttribute(XNamespace.Xmlns + "f", Namespaces.Function10), new XElement(Namespaces.Xhtml + "head"), new XElement(Namespaces.Xhtml + "body", XElement.Parse(content.Content))); } } } } base.CreateChildControls(); } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/Controls/Rendering/Title.cs ================================================ using System.Web.UI; using Composite.Core.WebClient.Renderings.Page; namespace Composite.Plugins.PageTemplates.MasterPages.Controls.Rendering { /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Title : Control { /// <exclude /> protected override void Render(HtmlTextWriter writer) { string pageTitle = string.IsNullOrWhiteSpace(Page.Title) ? PageRenderer.CurrentPage.Title : Page.Title; writer.WriteEncodedText(pageTitle); this.Page.Title = pageTitle; } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/MasterPageBase.cs ================================================ using System; using System.Web.UI; using Composite.Core.PageTemplates; using Composite.Data; using Composite.Plugins.PageTemplates.MasterPages.Controls.Rendering; namespace Composite.Plugins.PageTemplates.MasterPages { /// <summary> /// Base class for ASP.NET MasterPage classes in C1 CMS. Inheriting from this bring common features like easy data and sitemap access. /// This class is intended for use in shared MasterPages, to create a MasterPage based page template for C1 CMS use <see cref="Composite.Plugins.PageTemplates.MasterPages.MasterPagePageTemplate"/>. /// </summary> public abstract class MasterPageBase : MasterPage { private DataConnection _dataConnection; /// <summary> /// Gets or sets the data connection. /// </summary> /// <value> /// The data connection. /// </value> public DataConnection Data { get { if (_dataConnection == null) { _dataConnection = new DataConnection(); } return _dataConnection; } } /// <summary> /// Gets the sitemap navigator. /// </summary> public SitemapNavigator SitemapNavigator { get { return Data.SitemapNavigator; } } /// <summary> /// Gets a Page Template Feature based on name. /// </summary> /// <param name="featureName">Name of the Page Template Feature to return.</param> /// <returns>The Page Template Feature as an ASP.NET Control</returns> public Control GetPageTemplateFeature(string featureName) { var feature = new PageTemplateFeature(); feature.Name = featureName; return feature; } /// <exclude /> public override void Dispose() { if (_dataConnection != null) { _dataConnection.Dispose(); _dataConnection = null; } base.Dispose(); } #if LeakCheck private string stack = Environment.StackTrace; /// <exclude /> ~MasterPageBase() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/MasterPagePageRenderer.cs ================================================ using System; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml.Linq; using System.Linq; using Composite.C1Console.Security; using Composite.Core.Collections.Generic; using Composite.Core.Extensions; using Composite.Core.PageTemplates; using Composite.Core.WebClient.Renderings.Page; using Composite.Core.Xml; using Composite.Data.Types; namespace Composite.Plugins.PageTemplates.MasterPages { internal class MasterPagePageRenderer: IPageRenderer { private static readonly string PageRenderingJob_Key = "MasterPages.PageRenderingJob"; private readonly Hashtable<Guid, MasterPageRenderingInfo> _renderingInfo; private readonly Hashtable<Guid, Exception> _loadingExceptions; public MasterPagePageRenderer( Hashtable<Guid, MasterPageRenderingInfo> renderingInfo, Hashtable<Guid, Exception> loadingExceptions) { Verify.ArgumentNotNull(renderingInfo, "renderingInfo"); _renderingInfo = renderingInfo; _loadingExceptions = loadingExceptions; } public void AttachToPage(Page aspnetPage, PageContentToRender contentToRender) { Verify.ArgumentNotNull(aspnetPage, "aspnetPage"); Verify.ArgumentNotNull(contentToRender, "contentToRender"); aspnetPage.Items.Add(PageRenderingJob_Key, contentToRender); Guid templateId = contentToRender.Page.TemplateId; var rendering = _renderingInfo[templateId]; if(rendering == null) { Exception loadingException = _loadingExceptions[templateId]; if(loadingException != null) { throw loadingException; } Verify.ThrowInvalidOperationException("Failed to get master page by template ID '{0}'. Check for compilation errors".FormatWith(templateId)); } aspnetPage.MasterPageFile = rendering.VirtualPath; aspnetPage.PreRender += (e, args) => PageOnPreRender(aspnetPage, contentToRender.Page); var master = aspnetPage.Master as MasterPagePageTemplate; TemplateDefinitionHelper.BindPlaceholders(master, contentToRender, rendering.PlaceholderProperties, null); } private void PageOnPreRender(Page aspnetPage, IPage page) { bool emitMenuTitleMetaTag = !page.MenuTitle.IsNullOrEmpty(); bool emitUrlTitleMetaTag = !page.UrlTitle.IsNullOrEmpty(); if ((emitMenuTitleMetaTag || emitUrlTitleMetaTag) && UserValidationFacade.IsLoggedIn()) { var xhtmlDocument = new XhtmlDocument(); PageRenderer.AppendC1MetaTags(page, xhtmlDocument); if (aspnetPage.Header != null) { string xml = string.Join(string.Empty, xhtmlDocument.Head.Nodes().Select(node => node.ToString())); aspnetPage.Header.Controls.Add(new Literal {Text = xml}); } } } public static PageContentToRender GetRenderingInfo(Page page) { return page.Items[PageRenderingJob_Key] as PageContentToRender; } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/MasterPagePageTemplate.cs ================================================ using System; using Composite.Core.PageTemplates; namespace Composite.Plugins.PageTemplates.MasterPages { /// <summary> /// Base master page /// </summary> public abstract class MasterPagePageTemplate : MasterPageBase, IPageTemplate { /// <summary> /// Gets the template id. /// </summary> public abstract Guid TemplateId { get; } /// <summary> /// Gets the template title. /// </summary> public virtual string TemplateTitle { get { return null; } } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/MasterPagePageTemplateDescriptor.cs ================================================ using System; using System.Collections.Generic; using System.Web.UI; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Core.PageTemplates; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Plugins_MasterPagePageTemplate; namespace Composite.Plugins.PageTemplates.MasterPages { internal class MasterPagePageTemplateDescriptor : PageTemplateDescriptor { private static readonly PermissionType[] _editWebsiteFilePermissionTypes = new[] { PermissionType.Edit }; private static readonly ResourceHandle EditTemplateIcon = new ResourceHandle(BuildInIconProviderName.ProviderName, "page-template-edit"); public static ResourceHandle DeleteTemplateIcon { get { return PageTemplateElementProvider.GetIconHandle("page-template-delete"); } } private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); private readonly string _filePath; private readonly string _codeBehindFilePath; public MasterPagePageTemplateDescriptor(string filePath, string codeBehindFilePath) { Verify.ArgumentNotNull(filePath, "filePath"); _filePath = filePath; _codeBehindFilePath = codeBehindFilePath; } public string FilePath { get { return _filePath; } } public string CodeBehindFilePath { get { return _codeBehindFilePath; } } public string[] GetFiles() { var result = new List<string>(); result.Add(FilePath); if(CodeBehindFilePath != null) { result.Add(CodeBehindFilePath); } return result.ToArray(); } public override IEnumerable<C1Console.Elements.ElementAction> GetActions() { var result = new List<ElementAction>(); Type workflowType = WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider.EditMasterPageWorkflow"); result.Add(new ElementAction(new ActionHandle(new WorkflowActionToken( workflowType, _editWebsiteFilePermissionTypes))) { VisualData = new ActionVisualizedData { Label = Texts.EditMasterPageAction_Label, ToolTip = Texts.EditMasterPageAction_ToolTip, Icon = EditTemplateIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); workflowType = WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider.DeletePageTemplateWorkflow"); result.Add(new ElementAction(new ActionHandle(new WorkflowActionToken(workflowType, new[] { PermissionType.Delete }))) { VisualData = new ActionVisualizedData { Label = Texts.DeleteMasterPageAction_Label, ToolTip = Texts.DeleteMasterPageAction_ToolTip, Icon = DeleteTemplateIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); return result; } } internal class LazyInitializedMasterPagePageTemplateDescriptor: MasterPagePageTemplateDescriptor { private readonly MasterPagePageTemplateProvider _provider; private bool _initialized; public LazyInitializedMasterPagePageTemplateDescriptor(string filePath, string codeBehindFilePath, Guid templateId, string templateTitle, MasterPagePageTemplateProvider provider) :base(filePath, codeBehindFilePath) { Id = templateId; Title = templateTitle; _provider = provider; } private void EnsureInitialize() { if (!_initialized) { lock (this) { if (!_initialized) { Initialize(); _initialized = true; } } } } private void Initialize() { MasterPage masterPage; MasterPagePageTemplateDescriptor parsedPageTemplateDescriptor; MasterPageRenderingInfo renderingInfo; Exception loadingException; if (!_provider.LoadMasterPage( FilePath, out masterPage, out parsedPageTemplateDescriptor, out renderingInfo, out loadingException)) { this.LoadingException = loadingException; return; } Verify.IsNotNull(masterPage, "Failed to compile master page file '{0}'", FilePath); Verify.That(masterPage is MasterPagePageTemplate, "Incorrect base class. '{0}'", FilePath); this.DefaultPlaceholderId = parsedPageTemplateDescriptor.DefaultPlaceholderId; this.PlaceholderDescriptions = parsedPageTemplateDescriptor.PlaceholderDescriptions; } public override IEnumerable<PlaceholderDescriptor> PlaceholderDescriptions { get { EnsureInitialize(); return base.PlaceholderDescriptions; } set { base.PlaceholderDescriptions = value; } } public override string DefaultPlaceholderId { get { EnsureInitialize(); return base.DefaultPlaceholderId; } set { base.DefaultPlaceholderId = value; } } public override Exception LoadingException { get { EnsureInitialize(); return base.LoadingException; } set { base.LoadingException = value; } } public override bool IsValid { get { EnsureInitialize(); return base.IsValid; } } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/MasterPagePageTemplateProvider.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Web.Hosting; using System.Web.UI; using Composite.C1Console.Elements; using Composite.Core; using Composite.Core.Caching; using Composite.Core.Collections.Generic; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.PageTemplates; using Composite.Core.PageTemplates.Foundation; using Composite.Core.WebClient; using Composite.Core.WebClient.Services.WysiwygEditor; using Composite.Plugins.PageTemplates.Common; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.PageTemplates.MasterPages { [ConfigurationElementType(typeof(MasterPagePageTemplateProviderData))] internal class MasterPagePageTemplateProvider : IPageTemplateProvider, ISharedCodePageTemplateProvider { private static readonly string LogTitle = typeof (MasterPagePageTemplateProvider).FullName; private static readonly FileRelatedDataCache<CachedTemplateInformation> _templateCache = new FileRelatedDataCache<CachedTemplateInformation>("Templates", "masterPage", CachedTemplateInformation.SerializeToFile, CachedTemplateInformation.DeserializeFromFile); internal static readonly string TempFilePrefix = "_temp_"; private static readonly string MasterPageFileMask = "*.master"; private static readonly string FileWatcherMask = "*.master*"; private static readonly string FileWatcher_Regex = @"\.cs|\.master"; private readonly string _providerName; private readonly string _templatesDirectoryVirtualPath; private readonly string _templatesDirectory; private volatile State _state; private readonly object _initializationLock = new object(); private readonly C1FileSystemWatcher _watcher; public string AddNewTemplateLabel { get; private set; } public Type AddNewTemplateWorkflow { get; private set; } public MasterPagePageTemplateProvider(string name, string templatesDirectoryVirtualPath, string addNewTemplateLabel, Type addNewTemplateWorkflow) { _providerName = name; _templatesDirectoryVirtualPath = templatesDirectoryVirtualPath; _templatesDirectory = PathUtil.Resolve(_templatesDirectoryVirtualPath); AddNewTemplateLabel = addNewTemplateLabel; AddNewTemplateWorkflow = addNewTemplateWorkflow; Verify.That(C1Directory.Exists(_templatesDirectory), "Folder '{0}' does not exist", _templatesDirectory); string folderToWatch = _templatesDirectory; try { if (ReparsePointUtils.DirectoryIsReparsePoint(folderToWatch)) { folderToWatch = ReparsePointUtils.GetDirectoryReparsePointTarget(folderToWatch); } _watcher = new C1FileSystemWatcher(folderToWatch, FileWatcherMask) { IncludeSubdirectories = true }; _watcher.Created += Watcher_OnChanged; _watcher.Deleted += Watcher_OnChanged; _watcher.Changed += Watcher_OnChanged; _watcher.Renamed += Watcher_OnChanged; _watcher.EnableRaisingEvents = true; } catch (Exception ex) { Log.LogWarning(LogTitle, "Failed to create a file system watcher for directory '{0}'. Provider: {1}", folderToWatch, name); Log.LogWarning(LogTitle, ex); } } public IEnumerable<PageTemplateDescriptor> GetPageTemplates() { return GetInitializedState().Templates; } public IPageRenderer BuildPageRenderer(Guid templateId) { var state = GetInitializedState(); return new MasterPagePageRenderer(state.RenderingInfo, state.LoadingExceptions); } public IEnumerable<ElementAction> GetRootActions() { return new ElementAction[0]; } public IEnumerable<SharedFile> GetSharedFiles() { var state = GetInitializedState(); return state.SharedSourceFiles; } private State GetInitializedState() { var state = _state; if(state != null) { return state; } lock (_initializationLock) { state = _state; if (state == null) { _state = state = Initialize(); } } return state; } private State Initialize() { var files = new C1DirectoryInfo(_templatesDirectory) .GetFiles(MasterPageFileMask, SearchOption.AllDirectories) .Where(f => !f.Name.StartsWith(TempFilePrefix, StringComparison.Ordinal)); var templates = new List<PageTemplateDescriptor>(); var templateRenderingData = new Hashtable<Guid, MasterPageRenderingInfo>(); var loadingExceptions = new Hashtable<Guid, Exception>(); var sharedSourceFiles = new List<SharedFile>(); // Loading and compiling layout controls foreach (var fileInfo in files) { string filePath = fileInfo.FullName; string virtualPath = ConvertToVirtualPath(filePath); string codeBehindFilePath = GetCodebehindFilePath(filePath); string[] cacheRelatedFiles = { filePath, codeBehindFilePath }; CachedTemplateInformation cachedTemplateInformation; if (_templateCache.Get(virtualPath, cacheRelatedFiles, out cachedTemplateInformation)) { if (cachedTemplateInformation == null) { sharedSourceFiles.Add(new SharedMasterPage(virtualPath)); continue; } Guid templateId = cachedTemplateInformation.TemplateId; templates.Add(new LazyInitializedMasterPagePageTemplateDescriptor( filePath, codeBehindFilePath, templateId, cachedTemplateInformation.Title, this)); Verify.That(!templateRenderingData.ContainsKey(templateId), "Multiple master page templates defined with the same ID '{0}'", templateId); templateRenderingData.Add(templateId, new LazyInitializedMasterPageRenderingInfo(filePath, virtualPath, this)); continue; } MasterPage masterPage; MasterPagePageTemplateDescriptor parsedPageTemplateDescriptor; MasterPageRenderingInfo renderingInfo; Exception loadingException; if (!LoadMasterPage(filePath, out masterPage, out parsedPageTemplateDescriptor, out renderingInfo, out loadingException)) { var brokenTemplate = GetIncorrectlyLoadedPageTemplate(filePath, loadingException); loadingExceptions.Add(brokenTemplate.Id, brokenTemplate.LoadingException); templates.Add(brokenTemplate); continue; } if (masterPage == null) { continue; } if (!(masterPage is MasterPagePageTemplate)) { sharedSourceFiles.Add(new SharedMasterPage(virtualPath)); if (!HostingEnvironment.ApplicationHost.ShutdownInitiated()) { _templateCache.Add(virtualPath, cacheRelatedFiles, null); } continue; } templates.Add(parsedPageTemplateDescriptor); Verify.That(!templateRenderingData.ContainsKey(parsedPageTemplateDescriptor.Id), "Multiple master page templates defined with the same ID '{0}'", parsedPageTemplateDescriptor.Id); templateRenderingData.Add(parsedPageTemplateDescriptor.Id, renderingInfo); _templateCache.Add(virtualPath, cacheRelatedFiles, new CachedTemplateInformation(parsedPageTemplateDescriptor)); } return new State { Templates = templates, RenderingInfo = templateRenderingData, LoadingExceptions = loadingExceptions, SharedSourceFiles = sharedSourceFiles }; } /// <summary> /// Compiles masters page and builds a <see cref="PageTemplateDescriptor" />. /// Returns <value>True</value> if there's no compilation errors /// </summary> /// <param name="filePath">The file path.</param> /// <param name="masterPage">The master page.</param> /// <param name="pageTemplateDescriptor">The page template descriptor.</param> /// <param name="renderingInfo">The rendering info.</param> /// <param name="loadingException">The loading exception.</param> /// <returns></returns> internal bool LoadMasterPage( string filePath, out MasterPage masterPage, out MasterPagePageTemplateDescriptor pageTemplateDescriptor, out MasterPageRenderingInfo renderingInfo, out Exception loadingException) { string virtualPath = ConvertToVirtualPath(filePath); try { masterPage = CompilationHelper.CompileMasterPage(virtualPath); } catch (Exception ex) { Log.LogError(LogTitle, "Failed to compile master page file '{0}'", virtualPath); Log.LogError(LogTitle, ex); loadingException = ex is TargetInvocationException ? ex.InnerException : ex; masterPage = null; pageTemplateDescriptor = null; renderingInfo = null; return false; } if (!(masterPage is MasterPagePageTemplate)) { pageTemplateDescriptor = null; renderingInfo = null; loadingException = null; return true; } try { ParseTemplate(virtualPath, filePath, masterPage as MasterPagePageTemplate, out pageTemplateDescriptor, out renderingInfo); } catch (Exception ex) { Log.LogError(LogTitle, "Failed to load master page template file '{0}'", virtualPath); Log.LogError(LogTitle, ex); loadingException = ex; pageTemplateDescriptor = null; renderingInfo = null; return false; } loadingException = null; return true; } private static Guid GetMD5Hash(string text) { using (MD5 md5 = MD5.Create()) { byte[] hash = md5.ComputeHash(Encoding.Unicode.GetBytes(text)); return new Guid(hash); } } private PageTemplateDescriptor GetIncorrectlyLoadedPageTemplate(string filePath, Exception loadingException) { string codeBehindFile = GetCodebehindFilePath(filePath); Guid templateId; string idTokenBegin = "Guid TemplateId { get { return new Guid(\""; string idTokenEnd = "\"); } }"; if(!TemplateParsingHelper.TryExtractTemplateIdFromCSharpCode(codeBehindFile, out templateId, idTokenBegin, idTokenEnd)) { templateId = GetMD5Hash(filePath.ToLowerInvariant()); } return new MasterPagePageTemplateDescriptor(filePath, codeBehindFile) { Id = templateId, Title = Path.GetFileName(filePath), LoadingException = loadingException }; } internal static string GetCodebehindFilePath(string masterFilePath) { string csFile = masterFilePath + ".cs"; return C1File.Exists(csFile) ? csFile : null; } internal static void ParseTemplate(string virtualPath, string filePath, MasterPagePageTemplate masterPage, out MasterPagePageTemplateDescriptor pageTemplateDescriptor, out MasterPageRenderingInfo renderingInfo) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath); string csFile = GetCodebehindFilePath(filePath); IDictionary<string, PropertyInfo> placeholderProperties; Func<MasterPagePageTemplateDescriptor> constructor = () => new MasterPagePageTemplateDescriptor(filePath, csFile); pageTemplateDescriptor = TemplateDefinitionHelper.BuildPageTemplateDescriptor(masterPage, constructor, out placeholderProperties); if (pageTemplateDescriptor.Title == null) { pageTemplateDescriptor.Title = fileNameWithoutExtension; } renderingInfo = new MasterPageRenderingInfo(virtualPath, placeholderProperties); } public string ConvertToVirtualPath(string filePath) { return UrlUtils.Combine(_templatesDirectoryVirtualPath, filePath.Substring(_templatesDirectory.Length).Replace('\\', '/')); } private void Watcher_OnChanged(object sender, FileSystemEventArgs e) { // Ignoring changes to files, not related to master pages, and temporary files if (e.Name.StartsWith(TempFilePrefix) || !Regex.IsMatch(e.Name, FileWatcher_Regex, RegexOptions.IgnoreCase)) { return; } PageTemplateProviderRegistry.FlushTemplates(); PageTemplatePreview.ClearCache(); } public void FlushTemplates() { _state = null; } public string TemplateDirectoryPath { get { return _templatesDirectory; } } /// <summary> /// Immutable state - loaded page templates /// </summary> private class State { public List<PageTemplateDescriptor> Templates; public Hashtable<Guid, MasterPageRenderingInfo> RenderingInfo; public Hashtable<Guid, Exception> LoadingExceptions; public List<SharedFile> SharedSourceFiles; } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/MasterPagePageTemplateProviderData.cs ================================================ using System; using System.Configuration; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.PageTemplates; using Composite.Core.PageTemplates.Plugins; using Composite.Core.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.PageTemplates.MasterPages { [Assembler(typeof(MasterPagePageTemplateProviderAssembler))] internal class MasterPagePageTemplateProviderData : PageTemplateProviderData { [ConfigurationProperty("directory", IsRequired = false, DefaultValue = "~/App_Data/Razor/PageTemplates")] public string Directory { get { return (string)base["directory"]; } set { base["directory"] = value; } } [ConfigurationProperty("addNewTemplateLabel", IsRequired = false, DefaultValue = null)] public string AddNewTemplateLabel { get { return (string)base["addNewTemplateLabel"]; } set { base["addNewTemplateLabel"] = value; } } [ConfigurationProperty("addNewTemplateWorkflow", IsRequired = false, DefaultValue = null)] public string AddNewTemplateWorkflow { get { return (string)base["addNewTemplateWorkflow"]; } set { base["addNewTemplateWorkflow"] = value; } } } internal class MasterPagePageTemplateProviderAssembler : IAssembler<IPageTemplateProvider, PageTemplateProviderData> { public IPageTemplateProvider Assemble(Microsoft.Practices.ObjectBuilder.IBuilderContext context, PageTemplateProviderData objectConfiguration, Microsoft.Practices.EnterpriseLibrary.Common.Configuration.IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { var data = objectConfiguration as MasterPagePageTemplateProviderData; if (data == null) { throw new ArgumentException("Expected configuration to be of type " + typeof(MasterPagePageTemplateProviderAssembler).Name, "objectConfiguration"); } Type addNewTemplateWorkflow = null; if (!string.IsNullOrEmpty(data.AddNewTemplateWorkflow)) { try { addNewTemplateWorkflow = TypeManager.GetType(data.AddNewTemplateWorkflow); } catch (Exception ex) { Log.LogError(this.GetType().FullName, ex); } } string folderPath = PathUtil.Resolve(data.Directory); if (!C1Directory.Exists(folderPath)) { throw new ConfigurationErrorsException("Folder '{0}' does not exists".FormatWith(folderPath), objectConfiguration.ElementInformation.Source, objectConfiguration.ElementInformation.LineNumber); } return new MasterPagePageTemplateProvider(data.Name, data.Directory, data.AddNewTemplateLabel, addNewTemplateWorkflow); } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/MasterPageRenderingInfo.cs ================================================ using System; using System.Collections.Generic; using System.Reflection; using System.Web.UI; namespace Composite.Plugins.PageTemplates.MasterPages { internal class MasterPageRenderingInfo { public MasterPageRenderingInfo(string virtualPath, IDictionary<string, PropertyInfo> placeholderProperties) { VirtualPath = virtualPath; PlaceholderProperties = placeholderProperties; } public string VirtualPath { get; private set; } public virtual IDictionary<string, PropertyInfo> PlaceholderProperties { get; private set; } } internal class LazyInitializedMasterPageRenderingInfo : MasterPageRenderingInfo { private IDictionary<string, PropertyInfo> _placeholderProperties; private readonly MasterPagePageTemplateProvider _provider; private readonly string _filePath; public LazyInitializedMasterPageRenderingInfo(string filePath, string virtualPath, MasterPagePageTemplateProvider provider) : base(virtualPath, null) { _filePath = filePath; _provider = provider; } public override IDictionary<string, PropertyInfo> PlaceholderProperties { get { if (_placeholderProperties == null) { lock (this) { if (_placeholderProperties == null) { _placeholderProperties = InitializePlaceholderProperties(); } } } return _placeholderProperties; } } private IDictionary<string, PropertyInfo> InitializePlaceholderProperties() { MasterPage masterPage; MasterPagePageTemplateDescriptor parsedPageTemplateDescriptor; MasterPageRenderingInfo renderingInfo; Exception loadingException; if (!_provider.LoadMasterPage( _filePath, out masterPage, out parsedPageTemplateDescriptor, out renderingInfo, out loadingException)) { throw loadingException; } Verify.IsNotNull(masterPage, "Failed to compile master page file '{0}'", _filePath); Verify.That(masterPage is MasterPagePageTemplate, "Incorrect base class. '{0}'", _filePath); return renderingInfo.PlaceholderProperties; } } } ================================================ FILE: Composite/Plugins/PageTemplates/MasterPages/SharedMasterPage.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Core.PageTemplates; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; namespace Composite.Plugins.PageTemplates.MasterPages { internal class SharedMasterPage: SharedFile { private static readonly PermissionType[] _editWebsiteFilePermissionTypes = new[] { PermissionType.Edit }; private static readonly ResourceHandle EditTemplateIcon = new ResourceHandle(BuildInIconProviderName.ProviderName, "page-template-edit"); private static readonly ActionGroup PrimaryFileActionGroup = new ActionGroup("File", ActionGroupPriority.PrimaryMedium); public SharedMasterPage(string virtualFilePath) : base(virtualFilePath) { this.DefaultEditAction = false; } public override IEnumerable<C1Console.Elements.ElementAction> GetActions() { return new[] { new ElementAction(new ActionHandle(new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider.EditMasterPageWorkflow"), _editWebsiteFilePermissionTypes))) { VisualData = new ActionVisualizedData { Label = GetText("EditMasterPageAction.Label"), ToolTip = GetText("EditMasterPageAction.ToolTip"), Icon = EditTemplateIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFileActionGroup } } }}; } private static string GetText(string stringId) { return StringResourceSystemFacade.GetString("Composite.Plugins.MasterPagePageTemplate", stringId); } } } ================================================ FILE: Composite/Plugins/PageTemplates/Razor/RazorPageRenderer.cs ================================================ using System; using System.IO; using System.Text; using System.Web; using System.Web.UI; using System.Web.WebPages; using System.Xml.Linq; using Composite.AspNet.Razor; using Composite.Core.Collections.Generic; using Composite.Core.Instrumentation; using Composite.Core.PageTemplates; using Composite.Core.WebClient.Renderings.Page; using Composite.Functions; namespace Composite.Plugins.PageTemplates.Razor { internal class RazorPageRenderer : IPageRenderer, ISlimPageRenderer { private readonly Hashtable<Guid, TemplateRenderingInfo> _renderingInfo; private readonly Hashtable<Guid, Exception> _loadingExceptions; public RazorPageRenderer( Hashtable<Guid, TemplateRenderingInfo> renderingInfo, Hashtable<Guid, Exception> loadingExceptions) { _renderingInfo = renderingInfo; _loadingExceptions = loadingExceptions; } private Page _aspnetPage; private PageContentToRender _job; public void AttachToPage(Page renderTarget, PageContentToRender contentToRender) { _aspnetPage = renderTarget; _job = contentToRender; _aspnetPage.Init += RendererPage; } public XDocument Render(PageContentToRender contentToRender, FunctionContextContainer functionContextContainer) { Guid templateId = contentToRender.Page.TemplateId; var renderingInfo = _renderingInfo[templateId]; if (renderingInfo == null) { Exception loadingException = _loadingExceptions[templateId]; if (loadingException != null) { throw loadingException; } Verify.ThrowInvalidOperationException($"Missing template '{templateId}'"); } string output; RazorPageTemplate webPage = null; try { webPage = WebPageBase.CreateInstanceFromVirtualPath(renderingInfo.ControlVirtualPath) as RazorPageTemplate; Verify.IsNotNull(webPage, "Razor compilation failed or base type does not inherit '{0}'", typeof(RazorPageTemplate).FullName); webPage.Configure(); using (Profiler.Measure("Evaluating placeholders")) { TemplateDefinitionHelper.BindPlaceholders(webPage, contentToRender, renderingInfo.PlaceholderProperties, functionContextContainer); } // Executing razor code var httpContext = new HttpContextWrapper(HttpContext.Current); var startPage = StartPage.GetStartPage(webPage, "_PageStart", new[] { "cshtml" }); var pageContext = new WebPageContext(httpContext, webPage, startPage); pageContext.PageData.Add(RazorHelper.PageContext_FunctionContextContainer, functionContextContainer); var sb = new StringBuilder(); using (var writer = new StringWriter(sb)) { using (Profiler.Measure("Executing Razor page template")) { webPage.ExecutePageHierarchy(pageContext, writer); } } output = sb.ToString(); } finally { webPage?.Dispose(); } return XDocument.Parse(output); } private void RendererPage(object sender, EventArgs e) { var functionContextContainer = PageRenderer.GetPageRenderFunctionContextContainer(); var resultDocument = Render(_job, functionContextContainer); var controlMapper = (IXElementToControlMapper)functionContextContainer.XEmbedableMapper; Control control; using (Profiler.Measure("Rendering the page")) { control = PageRenderer.Render(resultDocument, functionContextContainer, controlMapper, _job.Page); } using (Profiler.Measure("ASP.NET controls: PagePreInit")) { _aspnetPage.Controls.Add(control); } } } } ================================================ FILE: Composite/Plugins/PageTemplates/Razor/RazorPageTemplateDescriptor.cs ================================================ using System; using System.Collections.Generic; using System.Reflection; using System.Web.WebPages; using Composite.AspNet.Razor; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Core.PageTemplates; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; using Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider; using SR = Composite.Core.ResourceSystem.StringResourceSystemFacade; namespace Composite.Plugins.PageTemplates.Razor { internal class RazorPageTemplateDescriptor: PageTemplateDescriptor { private static readonly PermissionType[] _editWebsiteFilePermissionTypes = new [] { PermissionType.Edit }; private static readonly ResourceHandle EditTemplateIcon = new ResourceHandle(BuildInIconProviderName.ProviderName, "page-template-edit"); public static ResourceHandle DeleteTemplateIcon { get { return PageTemplateElementProvider.GetIconHandle("page-template-delete"); } } private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); private readonly string _virtualPath; public RazorPageTemplateDescriptor(string virtualPath) { _virtualPath = virtualPath; } public string VirtualPath { get { return _virtualPath; } } public override IEnumerable<ElementAction> GetActions() { var result = new List<ElementAction>(); Type workflowType = WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider.EditRazorPageTemplateWorkflow"); result.Add(new ElementAction(new ActionHandle(new WorkflowActionToken( workflowType, _editWebsiteFilePermissionTypes))) { VisualData = new ActionVisualizedData { Label = GetText("EditRazorTemplateAction.Label"), ToolTip = GetText( "EditRazorTemplateAction.ToolTip"), Icon = EditTemplateIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); workflowType = WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider.DeletePageTemplateWorkflow"); result.Add(new ElementAction(new ActionHandle(new WorkflowActionToken(workflowType, new[] { PermissionType.Delete }))) { VisualData = new ActionVisualizedData { Label = GetText("DeleteRazorPageTemplateAction.Label"), ToolTip = GetText("DeleteRazorPageTemplateAction.ToolTip"), Icon = DeleteTemplateIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); return result; } private static string GetText(string stringId) { return StringResourceSystemFacade.GetString("Composite.Plugins.RazorPageTemplate", stringId); } } internal class LazyInitializedRazorPageTemplateDescriptor : RazorPageTemplateDescriptor { private readonly RazorPageTemplateProvider _provider; private bool _initialized; public LazyInitializedRazorPageTemplateDescriptor( string virtualPath, Guid templateId, string templateTitle, RazorPageTemplateProvider provider) : base(virtualPath) { Id = templateId; Title = templateTitle; _provider = provider; } private void EnsureInitialize() { if (!_initialized) { lock (this) { if (!_initialized) { Initialize(); _initialized = true; } } } } private void Initialize() { WebPageBase webPage; PageTemplateDescriptor parsedTemplate; IDictionary<string, PropertyInfo> placeholderProperties; Exception loadingException; if (!_provider.LoadRazorTemplate(VirtualPath, out webPage, out parsedTemplate, out placeholderProperties, out loadingException)) { LoadingException = loadingException; _initialized = true; throw loadingException; } Verify.IsNotNull(webPage, "Failed to compile razor page template '{0}'", VirtualPath); Verify.That(webPage is RazorPageTemplate, "Incorrect base class. '{0}'", VirtualPath); this.DefaultPlaceholderId = parsedTemplate.DefaultPlaceholderId; this.PlaceholderDescriptions = parsedTemplate.PlaceholderDescriptions; } public override IEnumerable<PlaceholderDescriptor> PlaceholderDescriptions { get { EnsureInitialize(); return base.PlaceholderDescriptions; } set { base.PlaceholderDescriptions = value; } } public override string DefaultPlaceholderId { get { EnsureInitialize(); return base.DefaultPlaceholderId; } set { base.DefaultPlaceholderId = value; } } public override Exception LoadingException { get { EnsureInitialize(); return base.LoadingException; } set { base.LoadingException = value; } } public override bool IsValid { get { EnsureInitialize(); return base.IsValid; } } } } ================================================ FILE: Composite/Plugins/PageTemplates/Razor/RazorPageTemplateProvider.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Web.Hosting; using System.Web.WebPages; using Composite.C1Console.Elements; using Composite.Core; using Composite.Core.Caching; using Composite.Core.Collections.Generic; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.PageTemplates; using Composite.Core.PageTemplates.Foundation; using Composite.Core.WebClient; using Composite.Core.WebClient.Services.WysiwygEditor; using Composite.Plugins.PageTemplates.Common; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Composite.AspNet.Razor; namespace Composite.Plugins.PageTemplates.Razor { [ConfigurationElementType(typeof(RazorPageTemplateProviderData))] internal class RazorPageTemplateProvider : IPageTemplateProvider, ISharedCodePageTemplateProvider { private static readonly string LayoutFileMask = "*.cshtml"; private static readonly string LogTitle = typeof (RazorPageTemplateProvider).Name; internal static readonly string TempFilePrefix = "_temp_"; private static readonly FileRelatedDataCache<CachedTemplateInformation> _templateCache = new FileRelatedDataCache<CachedTemplateInformation>("Templates", "razorTemplate", CachedTemplateInformation.SerializeToFile, CachedTemplateInformation.DeserializeFromFile); private readonly string _providerName; private readonly string _templatesDirectory; private readonly string _templatesDirectoryVirtualPath; private readonly object _initializationLock = new object(); private readonly C1FileSystemWatcher _watcher; private volatile State _state; private class State { public List<PageTemplateDescriptor> Templates; public List<SharedFile> SharedFiles; public Hashtable<Guid, TemplateRenderingInfo> RenderingInfo; public Hashtable<Guid, Exception> LoadingExceptions; } public string AddNewTemplateLabel { get; private set; } public Type AddNewTemplateWorkflow { get; private set; } public RazorPageTemplateProvider(string providerName, string templatesDirectoryVirtualPath, string addNewTemplateLabel, Type addNewTemplateWorkflow) { _providerName = providerName; _templatesDirectoryVirtualPath = templatesDirectoryVirtualPath; _templatesDirectory = PathUtil.Resolve(templatesDirectoryVirtualPath); AddNewTemplateLabel = addNewTemplateLabel; AddNewTemplateWorkflow = addNewTemplateWorkflow; string folderToWatch = _templatesDirectory; try { if (ReparsePointUtils.DirectoryIsReparsePoint(folderToWatch)) { folderToWatch = ReparsePointUtils.GetDirectoryReparsePointTarget(folderToWatch); } _watcher = new C1FileSystemWatcher(folderToWatch, LayoutFileMask) { IncludeSubdirectories = true }; _watcher.Created += Watcher_OnChanged; _watcher.Deleted += Watcher_OnChanged; _watcher.Changed += Watcher_OnChanged; _watcher.Renamed += Watcher_OnChanged; _watcher.EnableRaisingEvents = true; } catch (Exception ex) { Log.LogWarning(LogTitle, "Failed to create a file system watcher for directory '{0}'. Provider: {1}", folderToWatch, providerName); Log.LogWarning(LogTitle, ex); } } public IPageRenderer BuildPageRenderer(Guid templateId) { var state = GetInitializedState(); return new RazorPageRenderer(state.RenderingInfo, state.LoadingExceptions); } public IEnumerable<PageTemplateDescriptor> GetPageTemplates() { return GetInitializedState().Templates; } private State GetInitializedState() { var state = _state; if (state != null) return state; lock (_initializationLock) { state = _state; if (state == null) { _state = state = Initialize(); } } return state; } private State Initialize() { var files = new C1DirectoryInfo(_templatesDirectory) .GetFiles(LayoutFileMask, SearchOption.AllDirectories) .Where(f => !f.Name.StartsWith(TempFilePrefix, StringComparison.Ordinal)); var templates = new List<PageTemplateDescriptor>(); var templateRenderingData = new Hashtable<Guid, TemplateRenderingInfo>(); var loadingExceptions = new Hashtable<Guid, Exception>(); var sharedFiles = new List<SharedFile>(); // Loading and compiling layout controls foreach (var fileInfo in files) { string filePath = fileInfo.FullName; string virtualPath = ConvertToVirtualPath(filePath); CachedTemplateInformation cachedTemplateInformation; if (_templateCache.Get(virtualPath, filePath, out cachedTemplateInformation)) { if (cachedTemplateInformation == null) { sharedFiles.Add(new SharedRazorFile(virtualPath)); continue; } Guid templateId = cachedTemplateInformation.TemplateId; templates.Add(new LazyInitializedRazorPageTemplateDescriptor( virtualPath, templateId, cachedTemplateInformation.Title, this)); Verify.That(!templateRenderingData.ContainsKey(templateId), "Multiple master page templates defined with the same ID '{0}'", templateId); templateRenderingData.Add(templateId, new LazyInitializedTemplateRenderingInfo(virtualPath, this)); continue; } WebPageBase webPage; PageTemplateDescriptor parsedTemplate; IDictionary<string, PropertyInfo> placeholderProperties; Exception loadingException; if (!LoadRazorTemplate(virtualPath, out webPage, out parsedTemplate, out placeholderProperties, out loadingException)) { var brokenTemplate = GetIncorrectlyLoadedPageTemplate(virtualPath, loadingException); loadingExceptions.Add(brokenTemplate.Id, brokenTemplate.LoadingException); templates.Add(brokenTemplate); continue; } if (!(webPage is RazorPageTemplate)) { sharedFiles.Add(new SharedRazorFile(virtualPath)); if (!HostingEnvironment.ApplicationHost.ShutdownInitiated()) { _templateCache.Add(virtualPath, filePath, null); } continue; } templates.Add(parsedTemplate); templateRenderingData.Add(parsedTemplate.Id, new TemplateRenderingInfo(virtualPath, placeholderProperties)); _templateCache.Add(virtualPath, filePath, new CachedTemplateInformation(parsedTemplate)); } return new State { Templates = templates, RenderingInfo = templateRenderingData, SharedFiles = sharedFiles, LoadingExceptions = loadingExceptions }; } internal bool LoadRazorTemplate( string virtualPath, out WebPageBase webPage, out PageTemplateDescriptor parsedTemplate, out IDictionary<string, PropertyInfo> placeholderProperties, out Exception loadingException) { try { webPage = WebPageBase.CreateInstanceFromVirtualPath(virtualPath); } catch(Exception ex) { Log.LogError(LogTitle, "Failed to compile razor file '{0}'", virtualPath); Log.LogError(LogTitle, ex); loadingException = ex is TargetInvocationException ? ex.InnerException : ex; webPage = null; parsedTemplate = null; placeholderProperties = null; return false; } if (!(webPage is RazorPageTemplate)) { parsedTemplate = null; placeholderProperties = null; loadingException = null; return true; } RazorPageTemplate razorPageTemplate = webPage as RazorPageTemplate; razorPageTemplate.Configure(); try { ParseTemplate(virtualPath, razorPageTemplate, out parsedTemplate, out placeholderProperties); } catch (Exception ex) { Log.LogError(LogTitle, "Failed to load razor page template '{0}'", virtualPath); Log.LogError(LogTitle, ex); loadingException = ex; parsedTemplate = null; placeholderProperties = null; return false; } finally { razorPageTemplate.Dispose(); } loadingException = null; return true; } private PageTemplateDescriptor GetIncorrectlyLoadedPageTemplate(string virtualPath, Exception loadingException) { Guid templateId; string idTokenBegin = "TemplateId = new Guid(\""; string idTokenEnd = "\");"; if (!TemplateParsingHelper.TryExtractTemplateIdFromCSharpCode(PathUtil.Resolve(virtualPath), out templateId, idTokenBegin, idTokenEnd)) { templateId = GetMD5Hash(virtualPath.ToLowerInvariant()); } return new RazorPageTemplateDescriptor(virtualPath) { Id = templateId, Title = Path.GetFileName(virtualPath), LoadingException = loadingException }; } private static Guid GetMD5Hash(string text) { using (MD5 md5 = MD5.Create()) { byte[] hash = md5.ComputeHash(Encoding.Unicode.GetBytes(text)); return new Guid(hash); } } public string ConvertToVirtualPath(string filePath) { return UrlUtils.Combine(_templatesDirectoryVirtualPath, filePath.Substring(_templatesDirectory.Length).Replace('\\', '/')); } private void ParseTemplate(string virtualPath, AspNet.Razor.RazorPageTemplate webPage, out PageTemplateDescriptor templateDescriptor, out IDictionary<string, PropertyInfo> placeholderProperties) { Func<PageTemplateDescriptor> constructor = () => new RazorPageTemplateDescriptor(virtualPath); templateDescriptor = TemplateDefinitionHelper.BuildPageTemplateDescriptor(webPage, constructor, out placeholderProperties); } private void Watcher_OnChanged(object sender, FileSystemEventArgs e) { // Ignoring system and temporary files if (e.Name.StartsWith(TempFilePrefix)) { return; } PageTemplateProviderRegistry.FlushTemplates(); PageTemplatePreview.ClearCache(); } public IEnumerable<ElementAction> GetRootActions() { return new ElementAction[0]; } public IEnumerable<SharedFile> GetSharedFiles() { var state = GetInitializedState(); return state.SharedFiles; } public string TemplateDirectoryPath { get { return _templatesDirectory; } } public void FlushTemplates() { lock(_initializationLock) { _state = null; } } } } ================================================ FILE: Composite/Plugins/PageTemplates/Razor/RazorPageTemplateProviderAssembler.cs ================================================ using System; using System.Configuration; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.PageTemplates; using Composite.Core.PageTemplates.Plugins; using Composite.Core.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.PageTemplates.Razor { internal class RazorPageTemplateProviderAssembler : IAssembler<IPageTemplateProvider, PageTemplateProviderData> { public IPageTemplateProvider Assemble(Microsoft.Practices.ObjectBuilder.IBuilderContext context, PageTemplateProviderData objectConfiguration, Microsoft.Practices.EnterpriseLibrary.Common.Configuration.IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { var data = objectConfiguration as RazorPageTemplateProviderData; if (data == null) { throw new ArgumentException("Expected configuration to be of type " + typeof(RazorPageTemplateProviderData).Name, "objectConfiguration"); } Type addNewTemplateWorkflow = null; if (!string.IsNullOrEmpty(data.AddNewTemplateWorkflow)) { try { addNewTemplateWorkflow = TypeManager.GetType(data.AddNewTemplateWorkflow); } catch (Exception ex) { Log.LogError(this.GetType().FullName, ex); } } string folderPath = PathUtil.Resolve(data.Directory); if (!C1Directory.Exists(folderPath)) { throw new ConfigurationErrorsException("Folder '{0}' does not exists".FormatWith(folderPath), objectConfiguration.ElementInformation.Source, objectConfiguration.ElementInformation.LineNumber); } return new RazorPageTemplateProvider(data.Name, data.Directory, data.AddNewTemplateLabel, addNewTemplateWorkflow); } } } ================================================ FILE: Composite/Plugins/PageTemplates/Razor/RazorPageTemplateProviderData.cs ================================================ using System; using System.Configuration; using Composite.Core.PageTemplates.Plugins; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.PageTemplates.Razor { [Assembler(typeof(RazorPageTemplateProviderAssembler))] internal class RazorPageTemplateProviderData : PageTemplateProviderData { [ConfigurationProperty("directory", IsRequired = false, DefaultValue = "~/App_Data/Razor/PageTemplates")] public string Directory { get { return (string)base["directory"]; } set { base["directory"] = value; } } [ConfigurationProperty("addNewTemplateLabel", IsRequired = false, DefaultValue = null)] public string AddNewTemplateLabel { get { return (string)base["addNewTemplateLabel"]; } set { base["addNewTemplateLabel"] = value; } } [ConfigurationProperty("addNewTemplateWorkflow", IsRequired = false, DefaultValue = null)] public string AddNewTemplateWorkflow { get { return (string)base["addNewTemplateWorkflow"]; } set { base["addNewTemplateWorkflow"] = value; } } } } ================================================ FILE: Composite/Plugins/PageTemplates/Razor/SharedRazorFile.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Core.PageTemplates; using Composite.Core.ResourceSystem; using Composite.Core.ResourceSystem.Icons; namespace Composite.Plugins.PageTemplates.Razor { internal class SharedRazorFile: SharedFile { private static readonly PermissionType[] _editWebsiteFilePermissionTypes = new[] { PermissionType.Edit }; private static readonly ResourceHandle EditTemplateIcon = new ResourceHandle(BuildInIconProviderName.ProviderName, "page-template-edit"); private static readonly ActionGroup PrimaryFileActionGroup = new ActionGroup("File", ActionGroupPriority.PrimaryMedium); public SharedRazorFile(string filePath): base(filePath) { this.DefaultEditAction = false; } public override IEnumerable<C1Console.Elements.ElementAction> GetActions() { return new[] { new ElementAction(new ActionHandle(new WorkflowActionToken( WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider.EditRazorPageTemplateWorkflow"), _editWebsiteFilePermissionTypes))) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("Composite.Plugins.RazorPageTemplate", "EditRazorFileAction.Label"), ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.RazorPageTemplate", "EditRazorFileAction.ToolTip"), Icon = EditTemplateIcon, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryFileActionGroup } } }}; } } } ================================================ FILE: Composite/Plugins/PageTemplates/Razor/TemplateRenderingInfo.cs ================================================ using System; using System.Collections.Generic; using System.Reflection; using System.Web.WebPages; using Composite.AspNet.Razor; using Composite.Core.PageTemplates; namespace Composite.Plugins.PageTemplates.Razor { internal class TemplateRenderingInfo { public TemplateRenderingInfo(string controlVirtualPath, IDictionary<string, PropertyInfo> placeholders) { ControlVirtualPath = controlVirtualPath; PlaceholderProperties = placeholders; } public string ControlVirtualPath { get; set; } public virtual IDictionary<string, PropertyInfo> PlaceholderProperties { get; private set; } } internal class LazyInitializedTemplateRenderingInfo : TemplateRenderingInfo { private IDictionary<string, PropertyInfo> _placeholderProperties; private readonly RazorPageTemplateProvider _provider; public LazyInitializedTemplateRenderingInfo(string controlVirtualPath, RazorPageTemplateProvider provider) :base(controlVirtualPath, null) { _provider = provider; } public override IDictionary<string, PropertyInfo> PlaceholderProperties { get { if (_placeholderProperties == null) { lock (this) { if (_placeholderProperties == null) { _placeholderProperties = InitializePlaceholderProperties(); } } } return _placeholderProperties; } } private IDictionary<string, PropertyInfo> InitializePlaceholderProperties() { WebPageBase webPage; PageTemplateDescriptor parsedTemplate; IDictionary<string, PropertyInfo> placeholderProperties; Exception loadingException; if (!_provider.LoadRazorTemplate(ControlVirtualPath, out webPage, out parsedTemplate, out placeholderProperties, out loadingException)) { throw loadingException; } Verify.IsNotNull(webPage, "Failed to compile razor page template '{0}'", ControlVirtualPath); Verify.That(webPage is RazorPageTemplate, "Incorrect base class. '{0}'", ControlVirtualPath); return placeholderProperties; } } } ================================================ FILE: Composite/Plugins/PageTemplates/XmlPageTemplates/XmlPageRenderer.cs ================================================ using System; using System.Web.UI; using System.Xml.Linq; using Composite.Core.PageTemplates; using Composite.Core.Instrumentation; using Composite.Core.WebClient.Renderings.Page; using Composite.Core.WebClient.Renderings.Template; using Composite.Functions; namespace Composite.Plugins.PageTemplates.XmlPageTemplates { internal class XmlPageRenderer: IPageRenderer, ISlimPageRenderer { private Page _aspnetPage; private PageContentToRender _job; public void AttachToPage(Page renderTarget, PageContentToRender contentToRender) { _aspnetPage = renderTarget; _job = contentToRender; _aspnetPage.Init += RendererPage; } public XDocument Render(PageContentToRender contentToRender, FunctionContextContainer functionContextContainer) { var document = TemplateInfo.GetTemplateDocument(contentToRender.Page.TemplateId); PageRenderer.ResolvePlaceholders(document, contentToRender.Contents); return document; } private void RendererPage(object sender, EventArgs e) { if (_aspnetPage.Master != null) { // Backward compatibility with CompositeC1Contrib.Renderes.MasterPages package return; } Control renderedPage; using (Profiler.Measure("Page build up")) { renderedPage = PageRenderer.Render(_job.Page, _job.Contents); } using (Profiler.Measure("ASP.NET controls: PagePreInit")) { _aspnetPage.Controls.Add(renderedPage); } } } } ================================================ FILE: Composite/Plugins/PageTemplates/XmlPageTemplates/XmlPageTemplateDescriptor.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Core.PageTemplates; using Composite.Core.ResourceSystem; using Composite.Data; using Composite.Data.Types; using Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider; using SR = Composite.Core.ResourceSystem.StringResourceSystemFacade; namespace Composite.Plugins.PageTemplates.XmlPageTemplates { internal class XmlPageTemplateDescriptor: PageTemplateDescriptor { public static ResourceHandle DeleteTemplate { get { return PageTemplateElementProvider.GetIconHandle("page-template-delete"); } } private static readonly ActionGroup PrimaryActionGroup = new ActionGroup(ActionGroupPriority.PrimaryHigh); private readonly IXmlPageTemplate _xmlPageTemplate; public XmlPageTemplateDescriptor(IXmlPageTemplate pageTemplate) { _xmlPageTemplate = pageTemplate; } public override C1Console.Security.EntityToken GetEntityToken() { return _xmlPageTemplate.GetDataEntityToken(); } public override IEnumerable<ElementAction> GetActions() { var result = new List<ElementAction>(); Type type = WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider.EditXmlPageTemplateWorkflow"); result.Add(new ElementAction(new ActionHandle(new WorkflowActionToken(type, new[] { PermissionType.Edit }))) { VisualData = new ActionVisualizedData { Label = SR.GetString("Composite.Plugins.PageTemplateElementProvider", "PageTemplateElementProvider.EditXmlTemplate"), ToolTip = SR.GetString("Composite.Plugins.PageTemplateElementProvider", "PageTemplateElementProvider.EditXmlTemplateToolTip"), Icon = PageTemplateElementProvider.EditTemplate, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Edit, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); type = WorkflowFacade.GetWorkflowType( "Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider.DeletePageTemplateWorkflow"); result.Add(new ElementAction(new ActionHandle(new WorkflowActionToken(type, new[] { PermissionType.Delete }))) { VisualData = new ActionVisualizedData { Label = SR.GetString("Composite.Plugins.PageTemplateElementProvider", "PageTemplateElementProvider.DeleteTemplate"), ToolTip = SR.GetString("Composite.Plugins.PageTemplateElementProvider", "PageTemplateElementProvider.DeleteTemplateToolTip"), Icon = DeleteTemplate, Disabled = false, ActionLocation = new ActionLocation { ActionType = ActionType.Delete, IsInFolder = false, IsInToolbar = true, ActionGroup = PrimaryActionGroup } } }); return result; } } } ================================================ FILE: Composite/Plugins/PageTemplates/XmlPageTemplates/XmlPageTemplateProvider.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Elements; using Composite.Core.PageTemplates; using Composite.Core.WebClient.Renderings.Template; using Composite.Data; using Composite.Data.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using SR = Composite.Core.ResourceSystem.StringResourceSystemFacade; namespace Composite.Plugins.PageTemplates.XmlPageTemplates { [ConfigurationElementType(typeof(XmlPageTemplateProviderData))] internal class XmlPageTemplateProvider : IPageTemplateProvider { public string AddNewTemplateLabel { get; private set; } public Type AddNewTemplateWorkflow { get; private set; } public XmlPageTemplateProvider(string providerName, string addNewTemplateLabel, Type addNewTemplateWorkflow) { AddNewTemplateLabel = addNewTemplateLabel; AddNewTemplateWorkflow = addNewTemplateWorkflow; } public IEnumerable<PageTemplateDescriptor> GetPageTemplates() { using (var conn = new DataConnection(PublicationScope.Published)) { var result = new List<PageTemplateDescriptor>(); foreach (var xmlPageTemplate in conn.Get<IXmlPageTemplate>()) { string defaultPlaceholderId; PlaceholderDescriptor[] placeholders; ParseLayoutFile(xmlPageTemplate, out placeholders, out defaultPlaceholderId); PageTemplateDescriptor descriptor = new XmlPageTemplateDescriptor(xmlPageTemplate) { Id = xmlPageTemplate.Id, Title = xmlPageTemplate.Title, DefaultPlaceholderId = defaultPlaceholderId, PlaceholderDescriptions = placeholders }; result.Add(descriptor); } return result; } } private static void ParseLayoutFile(IXmlPageTemplate pageTemplate, out PlaceholderDescriptor[] placeholders, out string defaultPlaceholder) { var placeholdersInfo = TemplateInfo.GetRenderingPlaceHolders(pageTemplate.Id); defaultPlaceholder = placeholdersInfo.DefaultPlaceholderId; placeholders = placeholdersInfo .Placeholders .Select(pair => new PlaceholderDescriptor { Id = pair.Key, Title = pair.Value }) .ToArray(); } public IPageRenderer BuildPageRenderer(Guid templateId) { return new XmlPageRenderer(); } public IEnumerable<ElementAction> GetRootActions() { return new ElementAction[0]; } public void FlushTemplates() { // Provider holds no state - no need to reinitialize anything } } } ================================================ FILE: Composite/Plugins/PageTemplates/XmlPageTemplates/XmlPageTemplateProviderData.cs ================================================ using System; using System.Configuration; using Composite.Core; using Composite.Core.PageTemplates; using Composite.Core.PageTemplates.Plugins; using Composite.Core.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.PageTemplates.XmlPageTemplates { [Assembler(typeof(XmlPageTemplateProviderAssembler))] internal class XmlPageTemplateProviderData : PageTemplateProviderData { [ConfigurationProperty("addNewTemplateLabel", IsRequired = false, DefaultValue = null)] public string AddNewTemplateLabel { get { return (string)base["addNewTemplateLabel"]; } set { base["addNewTemplateLabel"] = value; } } [ConfigurationProperty("addNewTemplateWorkflow", IsRequired = false, DefaultValue = null)] public string AddNewTemplateWorkflow { get { return (string)base["addNewTemplateWorkflow"]; } set { base["addNewTemplateWorkflow"] = value; } } } internal class XmlPageTemplateProviderAssembler : IAssembler<IPageTemplateProvider, PageTemplateProviderData> { public IPageTemplateProvider Assemble(Microsoft.Practices.ObjectBuilder.IBuilderContext context, PageTemplateProviderData objectConfiguration, Microsoft.Practices.EnterpriseLibrary.Common.Configuration.IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { var data = objectConfiguration as XmlPageTemplateProviderData; if (data == null) { throw new ArgumentException("Expected configuration to be of type " + typeof(XmlPageTemplateProviderData).Name, "objectConfiguration"); } Type addNewTemplateWorkflow = null; if (!string.IsNullOrEmpty(data.AddNewTemplateWorkflow)) { try { addNewTemplateWorkflow = TypeManager.GetType(data.AddNewTemplateWorkflow); } catch (Exception ex) { Log.LogError(this.GetType().FullName, ex); } } return new XmlPageTemplateProvider(data.Name, data.AddNewTemplateLabel, addNewTemplateWorkflow); } } } ================================================ FILE: Composite/Plugins/ResourceSystem/AggregationLocalizationProvider/AggregationLocalizationProvider.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.Core.ResourceSystem.Plugins.ResourceProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.ResourceSystem.AggregationLocalizationProvider { /// <summary> /// ILocalizationProvider that aggrages multiple IStringResourceProviders. To be used for backward compatibility. /// </summary> [ConfigurationElementType(typeof(AggregationLocalizationProviderData))] internal class AggregationLocalizationProvider: ILocalizationProvider { private readonly Dictionary<string, IStringResourceProvider> _providers; private CultureInfo[] _supportedCultures; public AggregationLocalizationProvider(Dictionary<string, IStringResourceProvider> providers) { _providers = providers; } public IEnumerable<string> GetSections() { return _providers.Keys; } public string GetString(string section, string stringId, CultureInfo cultureInfo) { IStringResourceProvider stringResourceProvider; if (!_providers.TryGetValue(section, out stringResourceProvider)) { return null; } return stringResourceProvider.GetStringValue(stringId, cultureInfo); } public ReadOnlyDictionary<string, string> GetAllStrings(string section, CultureInfo cultureInfo) { IStringResourceProvider stringResourceProvider; if (!_providers.TryGetValue(section, out stringResourceProvider)) { return null; } IDictionary<string, string> dictionary = stringResourceProvider.GetAllStrings(cultureInfo); return new ReadOnlyDictionary<string, string>(new Dictionary<string, string>(dictionary)); } public IEnumerable<CultureInfo> GetSupportedCultures() { if(_supportedCultures == null) { var result = new List<CultureInfo>(); foreach(var provider in _providers.Values) { result.AddRange(provider.GetSupportedCultures()); } _supportedCultures = result.Distinct().ToArray(); } return _supportedCultures; } #region Configuration [Assembler(typeof(AggregationLocalizationProviderAssembler))] internal sealed class AggregationLocalizationProviderData : ResourceProviderData { private const string _providersProperty = "Providers"; [ConfigurationProperty(_providersProperty)] public NameTypeManagerTypeConfigurationElementCollection<ResourceProviderData> Providers { get { return (NameTypeManagerTypeConfigurationElementCollection<ResourceProviderData>)base[_providersProperty]; } } } internal sealed class AggregationLocalizationProviderAssembler : IAssembler<IResourceProvider, ResourceProviderData> { public IResourceProvider Assemble(IBuilderContext context, ResourceProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { var data = (AggregationLocalizationProviderData)objectConfiguration; var stringResourceProviders = new Dictionary<string, IStringResourceProvider>(); // TODO: rewrite using proper Object builder API foreach(var configRecord in data.Providers) { var type = configRecord.Type; var configTypeAttr = type.GetCustomAttributes(typeof (ConfigurationElementTypeAttribute), true).FirstOrDefault() as ConfigurationElementTypeAttribute; Verify.IsNotNull(configTypeAttr, "Attribute not defined: " + typeof(ConfigurationElementTypeAttribute).FullName); Type configType = configTypeAttr.ConfigurationType; var assemblerAttr = configType.GetCustomAttributes(typeof(AssemblerAttribute), true).FirstOrDefault() as AssemblerAttribute; Verify.IsNotNull(configTypeAttr, "Attribute not defined: " + typeof(AssemblerAttribute).FullName); var assemblerType = assemblerAttr.AssemblerType; var assembler = assemblerType.GetConstructor(new Type[0]).Invoke(new object[0]) as IAssembler<IResourceProvider, ResourceProviderData>; IResourceProvider resourceProvider = assembler.Assemble(context, configRecord, configurationSource, reflectionCache); Verify.That(resourceProvider is IStringResourceProvider, "Provider should inherit " + typeof(IStringResourceProvider).FullName); stringResourceProviders.Add(configRecord.Name, resourceProvider as IStringResourceProvider); } return new AggregationLocalizationProvider(stringResourceProviders); } } #endregion Configuration } } ================================================ FILE: Composite/Plugins/ResourceSystem/PropertyResourceProvider/PropertyResourceProvider.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Reflection; using Composite.Core.ResourceSystem.Plugins.ResourceProvider; using Composite.Core.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.ResourceSystem.PropertyResourceProvider { [ConfigurationElementType(typeof(NonConfigurableResourceProvider))] internal sealed class PropertyResourceProvider : IStringResourceProvider { public string GetStringValue(string stringId, CultureInfo cultureInfo) { int index = stringId.LastIndexOf('.'); if (index == -1) throw new InvalidOperationException(string.Format("'{0}' is not of correct format", stringId)); string typeName = stringId.Substring(0, index); string propertyName = stringId.Substring(index + 1); Type type = TypeManager.GetType(typeName); if (type == null) throw new InvalidOperationException(string.Format("'{0}' type could not found", typeName)); PropertyInfo propertyInfo = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Static); if (propertyInfo == null) throw new InvalidOperationException(string.Format("The property '{0}' on the type '{1}' could not be found", propertyInfo)); return (string)propertyInfo.GetValue(null, null); } public IDictionary<string, string> GetAllStrings(CultureInfo cultureInfo) { return new Dictionary<string, string>(); } public IEnumerable<CultureInfo> GetSupportedCultures() { yield break; } } } ================================================ FILE: Composite/Plugins/ResourceSystem/XmlLocalizationProvider/XmlLocalizationProvider.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.IO; using System.Linq; using System.Xml.Linq; using Composite.Core; using Composite.Core.Collections.Generic; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.ResourceSystem.Plugins.ResourceProvider; using Composite.Core.Xml; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.ResourceSystem.XmlLocalizationProvider { [ConfigurationElementType(typeof(XmlLocalizationProviderData))] internal class XmlLocalizationProvider: ILocalizationProvider { private static readonly string LogTitle = typeof (XmlLocalizationProvider).Name; readonly string _directory; readonly CultureInfo _defaultCulture; private State _state; private readonly object _syncRoot = new object(); private readonly C1FileSystemWatcher _watcher; public XmlLocalizationProvider(string directoryVirtualPath, CultureInfo defaultCulture) { _defaultCulture = defaultCulture; _directory = PathUtil.Resolve(directoryVirtualPath); if(!C1Directory.Exists(_directory)) { Log.LogVerbose(LogTitle, "Directory '{0}' does not exist", directoryVirtualPath); return; } _watcher = new C1FileSystemWatcher(_directory, "*.xml"); _watcher.Created += (sender, args) => Reset(); _watcher.Changed += (sender, args) => Reset(); _watcher.Deleted += (sender, args) => Reset(); _watcher.EnableRaisingEvents = true; } public IEnumerable<string> GetSections() { var state = GetState(); return state.Sections.Keys; } public string GetString(string section, string stringId, CultureInfo cultureInfo) { var state = GetState(); if(!state.Sections.ContainsKey(section)) { return null; } var filesByCulture = state.Sections[section]; if(filesByCulture.ContainsKey(cultureInfo)) { var strings = filesByCulture[cultureInfo].GetStrings(); if(strings.ContainsKey(stringId)) { return strings[stringId]; } } // If not found - searching in default culture if(!cultureInfo.Equals(_defaultCulture) && filesByCulture.ContainsKey(_defaultCulture)) { var strings = filesByCulture[_defaultCulture].GetStrings(); if(strings.ContainsKey(stringId)) { return strings[stringId]; } } return null; } public ReadOnlyDictionary<string, string> GetAllStrings(string section, CultureInfo cultureInfo) { var state = GetState(); if (!state.Sections.ContainsKey(section)) { return null; } var filesByCulture = state.Sections[section]; if(filesByCulture.ContainsKey(cultureInfo)) { return filesByCulture[cultureInfo].GetStrings(); } // If not found - searching in default culture if(!cultureInfo.Equals(_defaultCulture) && filesByCulture.ContainsKey(_defaultCulture)) { return filesByCulture[_defaultCulture].GetStrings(); } return null; } public IEnumerable<CultureInfo> GetSupportedCultures() { var state = GetState(); var result = new List<CultureInfo>(); foreach(var section in state.Sections) { result.AddRange(section.Value.Keys); } return result.Distinct(); } public IEnumerable<System.Globalization.CultureInfo> GetSupportedCultures(string section) { var state = GetState(); if(!state.Sections.ContainsKey(section)) { return new CultureInfo[0]; } return state.Sections[section].Keys; } private State Initialize() { var sections = new Dictionary<string, Dictionary<CultureInfo, LocalizationFile>>(); if (C1Directory.Exists(_directory)) { foreach (string xmlFile in C1Directory.GetFiles(_directory, "*.xml", SearchOption.AllDirectories)) { // File names have format <section name>.<culture name>.xml string fileName = Path.GetFileName(xmlFile); fileName = fileName.Substring(0, fileName.Length - 4); // removing ".xml"; if (!fileName.Contains(".")) continue; string cultureName = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1); CultureInfo cultureInfo; try { cultureInfo = CultureInfo.GetCultureInfo(cultureName); } catch (CultureNotFoundException) { Log.LogInformation(LogTitle, "Skipping file '{0}' as '{1}' is not a valid culture name", Path.GetFileName(xmlFile), cultureName); continue; } string sectionName = fileName.Substring(0, fileName.Length - cultureName.Length - 1); if (!sections.ContainsKey(sectionName)) { sections.Add(sectionName, new Dictionary<CultureInfo, LocalizationFile>()); } var localizationFile = new LocalizationFile(xmlFile); sections[sectionName].Add(cultureInfo, localizationFile); } } return new State { Sections = sections }; } private void Reset() { lock(_syncRoot) { _state = null; } } private State GetState() { var state = _state; if(state == null) { lock (_syncRoot) { state = _state; if(state == null) { _state = state = Initialize(); } } } return state; } private static ReadOnlyDictionary<string, string> LoadStrings(string fileName) { XElement strings = XElementUtils.Load(fileName); var stringDictionary = new Dictionary<string, string>(); foreach (XElement stringElement in strings.Elements()) { XAttribute keyAttribute = stringElement.Attribute("key"); XAttribute valueAttribute = stringElement.Attribute("value"); if (keyAttribute != null && valueAttribute != null) { if (stringDictionary.ContainsKey(keyAttribute.Value)) { throw new InvalidOperationException("Duplicate string resource key '{0}' in XML file '{1}'" .FormatWith(keyAttribute.Value, Path.GetFileName(fileName))); } stringDictionary.Add(keyAttribute.Value, valueAttribute.Value); } else { Log.LogError(LogTitle, "Invalid entry '{0}' in file '{1}'" .FormatWith(stringElement.ToString(SaveOptions.DisableFormatting), Path.GetFileName(fileName))); } } return new ReadOnlyDictionary<string, string>(stringDictionary); } private class State { public IDictionary<string, Dictionary<CultureInfo, LocalizationFile>> Sections; } private class LocalizationFile { private readonly string _filePath; private volatile ReadOnlyDictionary<string, string> _strings; public LocalizationFile(string filePath) { _filePath = filePath; } public ReadOnlyDictionary<string, string> GetStrings() { if(_strings == null) { lock(this) { if(_strings == null) { _strings = LoadStrings(_filePath); } } } return _strings; } } #region Configuration [Assembler(typeof(XmlLocalizationProviderAssembler))] internal sealed class XmlLocalizationProviderData : ResourceProviderData { private const string _defaultCultureNameProperty = "defaultCultureName"; [ConfigurationProperty(_defaultCultureNameProperty, IsRequired = true)] public string DefaultCultureName { get { return (string)base[_defaultCultureNameProperty]; } set { base[_defaultCultureNameProperty] = value; } } private const string _directoryProperty = "directory"; [ConfigurationProperty(_directoryProperty)] public string Directory { get { return (string)base[_directoryProperty]; } } } internal sealed class XmlLocalizationProviderAssembler : IAssembler<IResourceProvider, ResourceProviderData> { public IResourceProvider Assemble(IBuilderContext context, ResourceProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { var data = (XmlLocalizationProviderData)objectConfiguration; var defaultCulture = CultureInfo.GetCultureInfo(data.DefaultCultureName); string directoryVirtualPath = data.Directory; return new XmlLocalizationProvider(directoryVirtualPath, defaultCulture); } } #endregion Configuration } } ================================================ FILE: Composite/Plugins/ResourceSystem/XmlStringResourceProvider/XmlStringResourceProvider.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.IO; using System.Linq; using System.Xml.Linq; using Composite.Core.Collections.Generic; using Composite.Core.IO; using Composite.Core.Logging; using Composite.Core.ResourceSystem.Plugins.ResourceProvider; using Composite.Core.Xml; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.ResourceSystem.XmlStringResourceProvider { [ConfigurationElementType(typeof(XmlStringResourceProviderData))] internal sealed class XmlStringResourceProvider : IStringResourceProvider { private ResourceLocker<Resources> _resourceLocker = new ResourceLocker<Resources>(new Resources(), Resources.Initialize, false); private string _providerName; public XmlStringResourceProvider(string defaultCultureName, Dictionary<CultureInfo, string> cultureToFileLookup, Dictionary<CultureInfo, bool> watchForFileChanges, string providerName) { using (_resourceLocker.Locker) { _providerName = providerName; _resourceLocker.Resources.DefaultCulture = new CultureInfo(defaultCultureName); _resourceLocker.Resources.CultureToFileLookup = cultureToFileLookup; foreach (CultureInfo watchedCulture in watchForFileChanges.Where(f => f.Value).Select(f => f.Key)) { string unresolvedFileName; if (_resourceLocker.Resources.CultureToFileLookup.TryGetValue(watchedCulture, out unresolvedFileName)) { string resolvedFileName = PathUtil.Resolve(unresolvedFileName); DateTime lastWrite = C1File.GetLastWriteTime(resolvedFileName); _resourceLocker.Resources.CultureFileLastUpdated.Add(watchedCulture, lastWrite); } } } } public string GetStringValue(string stringId, CultureInfo cultureInfo) { Dictionary<string, string> stringDictionary; try { stringDictionary = GetStringsForCulture(cultureInfo); } catch (FileNotFoundException ex) { return string.Format("*** FILE '{0}' NOT FOUND ***", ex.FileName); } using (_resourceLocker.ReadLocker) { if (stringDictionary == null) { if (cultureInfo != _resourceLocker.Resources.DefaultCulture) { return GetStringValue(stringId, _resourceLocker.Resources.DefaultCulture); } else { LoggingService.LogError("XmlStringResourceProvider", "String provider misconfigured. No string file available for default culture."); return "*** STRING NOT FOUND ***"; } } else { string result; if (stringDictionary.TryGetValue(stringId, out result) == false) { if (cultureInfo != _resourceLocker.Resources.DefaultCulture) { return GetStringValue(stringId, _resourceLocker.Resources.DefaultCulture); } else { LoggingService.LogError("XmlStringResourceProvider", string.Format("String not found: '{0}' for provider '{1}'", stringId, _providerName)); return "*** STRING NOT FOUND ***"; } } else { return result; } } } } public IDictionary<string, string> GetAllStrings(CultureInfo cultureInfo) { IDictionary<string, string> currentCultureStrings = GetStringsForCulture(cultureInfo); using (_resourceLocker.ReadLocker) { if (currentCultureStrings == null) return GetStringsForCulture(_resourceLocker.Resources.DefaultCulture); if (cultureInfo == _resourceLocker.Resources.DefaultCulture) return currentCultureStrings; IDictionary<string, string> defaultCultureStrings = GetStringsForCulture(_resourceLocker.Resources.DefaultCulture); if (defaultCultureStrings.Count == currentCultureStrings.Count) return currentCultureStrings; return currentCultureStrings.Union(defaultCultureStrings.Where(f => currentCultureStrings.ContainsKey(f.Key) == false)).ToDictionary(f => f.Key, f => f.Value); } } public IEnumerable<CultureInfo> GetSupportedCultures() { using (_resourceLocker.Locker) { foreach (CultureInfo cultureInfo in _resourceLocker.Resources.CultureToFileLookup.Keys.Distinct()) { yield return cultureInfo; } } } /// <summary> /// Returns strings for the specified culture or null if no strings exists. /// </summary> private Dictionary<string, string> GetStringsForCulture(CultureInfo cultureInfo) { Dictionary<string, string> stringDictionary; using (_resourceLocker.Locker) { if (_resourceLocker.Resources.CultureFileLastUpdated.ContainsKey(cultureInfo)) { string unresolvedFileName = _resourceLocker.Resources.CultureToFileLookup[cultureInfo]; string resolvedFileName = PathUtil.Resolve(unresolvedFileName); DateTime lastWrite = C1File.GetLastWriteTime(resolvedFileName); double secondsSinceLastWrite = (DateTime.Now - lastWrite).TotalSeconds; if (secondsSinceLastWrite < 300 || lastWrite > _resourceLocker.Resources.CultureFileLastUpdated[cultureInfo]) { _resourceLocker.Resources.CultureToTranslation.Remove(cultureInfo); _resourceLocker.Resources.CultureFileLastUpdated[cultureInfo] = lastWrite; } } if (_resourceLocker.Resources.CultureToTranslation.TryGetValue(cultureInfo, out stringDictionary) == false) { string unresolvedFileName; if (_resourceLocker.Resources.CultureToFileLookup.TryGetValue(cultureInfo, out unresolvedFileName) == false) { return null; } string resolvedFileName = PathUtil.Resolve(unresolvedFileName); XElement strings = XElementUtils.Load(resolvedFileName); stringDictionary = new Dictionary<string, string>(); foreach (XElement stringElement in strings.Elements()) { XAttribute keyAttribute = stringElement.Attribute("key"); XAttribute valueAttribute = stringElement.Attribute("value"); if (keyAttribute != null && valueAttribute != null) { if (stringDictionary.ContainsKey(keyAttribute.Value)) { throw new InvalidOperationException(string.Format("Duplicate string resource key '{0}' in XML file '{1}'", keyAttribute.Value, unresolvedFileName)); } stringDictionary.Add(keyAttribute.Value, valueAttribute.Value); } else { LoggingService.LogError("XmlStringResourceProvider", string.Format("Invalid entry '{0}' in file '{1}'", stringElement.ToString(SaveOptions.DisableFormatting), unresolvedFileName)); } } _resourceLocker.Resources.CultureToTranslation.Add(cultureInfo, stringDictionary); } } return stringDictionary; } private sealed class Resources { public CultureInfo DefaultCulture { get; set; } public Dictionary<CultureInfo, string> CultureToFileLookup { get; set; } public Dictionary<CultureInfo, Dictionary<string, string>> CultureToTranslation { get; set; } public Dictionary<CultureInfo, DateTime> CultureFileLastUpdated { get; set; } public static void Initialize(Resources resources) { resources.CultureToTranslation = new Dictionary<CultureInfo, Dictionary<string, string>>(); resources.CultureFileLastUpdated = new Dictionary<CultureInfo, DateTime>(); } } } [Assembler(typeof(XmlStringResourceProviderAssembler))] internal sealed class XmlStringResourceProviderData : ResourceProviderData { private const string _defaultCultureNameProperty = "defaultCultureName"; [ConfigurationProperty(_defaultCultureNameProperty, IsRequired = true)] public string DefaultCultureName { get { return (string)base[_defaultCultureNameProperty]; } set { base[_defaultCultureNameProperty] = value; } } private const string _culturesProperty = "Cultures"; [ConfigurationProperty(_culturesProperty)] public CultureElementCollection Cultures { get { return (CultureElementCollection)base[_culturesProperty]; } } } internal sealed class CulturenameConfigurationElement : ConfigurationElement { private const string _cultureNameProperty = "cultureName"; [ConfigurationProperty(_cultureNameProperty, IsKey = true)] public string CultureName { get { return (string)base[_cultureNameProperty]; } set { base[_cultureNameProperty] = value; } } private const string _xmlFileProperty = "xmlFile"; [ConfigurationProperty(_xmlFileProperty)] public string XmlFile { get { return (string)base[_xmlFileProperty]; } set { base[_xmlFileProperty] = value; } } private const string _monitorFileChanges = "monitorFileChanges"; [ConfigurationProperty(_monitorFileChanges)] public bool MonitorFileChanges { get { return (bool)base[_monitorFileChanges]; } set { base[_monitorFileChanges] = value; } } } internal sealed class CultureElementCollection : ConfigurationElementCollection { public void Add(CulturenameConfigurationElement element) { BaseAdd(element); } protected override ConfigurationElement CreateNewElement() { return new CulturenameConfigurationElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((CulturenameConfigurationElement)element).CultureName; } } internal sealed class XmlStringResourceProviderAssembler : IAssembler<IResourceProvider, ResourceProviderData> { public IResourceProvider Assemble(IBuilderContext context, ResourceProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { XmlStringResourceProviderData data = (XmlStringResourceProviderData)objectConfiguration; IEnumerable<CulturenameConfigurationElement> cultureElements = data.Cultures.Cast<CulturenameConfigurationElement>(); Dictionary<CultureInfo, string> cultureFiles = cultureElements.ToDictionary(k => new CultureInfo(k.CultureName), f => f.XmlFile); Dictionary<CultureInfo, bool> cultureFileWatches = cultureElements.ToDictionary(k => new CultureInfo(k.CultureName), f => f.MonitorFileChanges); XmlStringResourceProvider provider = new XmlStringResourceProvider(data.DefaultCultureName, cultureFiles, cultureFileWatches, data.Name); return provider; } } } ================================================ FILE: Composite/Plugins/Routing/Hostnames/FormFunctions.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Composite.Data; using Composite.Data.Types; namespace Composite.Plugins.Routing.Hostnames { internal class FormFunctions { public static IEnumerable<Tuple<object, object, string>> GetRootPages() { var result = new List<Tuple<object, object, string>>(); CultureInfo[] cultures = DataLocalizationFacade.ActiveLocalizationCultures.ToArray(); foreach(var culture in cultures) { using(new DataScope(PublicationScope.Unpublished, culture)) { foreach(Guid rootPageId in PageManager.GetChildrenIDs(Guid.Empty)) { IPage page = PageManager.GetPageById(rootPageId); if(page == null) continue; string label = page.Title; if(cultures.Length > 1) { label += ", " + culture.NativeName; } result.Add(new Tuple<object, object, string>(page.Id, culture.Name, label)); } } } return result; } } } ================================================ FILE: Composite/Plugins/Routing/InternalUrlConverters/DataInternalUrlConverter.cs ================================================ using System; using System.Collections.Generic; using System.Reflection; using Composite.Core; using Composite.Core.Routing; using Composite.Core.Types; using Composite.Data; namespace Composite.Plugins.Routing.InternalUrlConverters { class DataInternalUrlConverter: IInternalUrlConverter { private readonly Type _type; private readonly Type _keyType; private readonly ConstructorInfo _dataReferenceConstructor; public DataInternalUrlConverter(string shortTypeName, Type type) { AcceptedUrlPrefixes = new[] { shortTypeName + "(" }; _type = type; _keyType = _type.GetSingleKeyProperty().PropertyType; _dataReferenceConstructor = typeof(DataReference<>).MakeGenericType(_type).GetConstructor(new[] { typeof(object) }); } public IEnumerable<string> AcceptedUrlPrefixes { get; } public string ToPublicUrl(string internalDataUrl, UrlSpace urlSpace) { object keyValue = ExtractKeyValue(internalDataUrl); if(keyValue == null) return null; var data = DataFacade.TryGetDataByUniqueKey(_type, keyValue); if(data == null) return null; var pageUrlData = DataUrls.TryGetPageUrlData(data.ToDataReference()); if (internalDataUrl.IndexOf("?", StringComparison.Ordinal) > 0) { var parameters = new UrlBuilder(internalDataUrl).GetQueryParameters(); if (parameters.HasKeys()) { if (pageUrlData.QueryParameters == null) { pageUrlData.QueryParameters = parameters; } else { pageUrlData.QueryParameters.Add(parameters); } } } return pageUrlData != null ? PageUrls.BuildUrl(pageUrlData, UrlKind.Public, urlSpace) : null; } private object ExtractKeyValue(string internalDataUrl) { int openBracketIndex = internalDataUrl.IndexOf("(", StringComparison.Ordinal); if (openBracketIndex < 0) { return null; } int closingBracketOffset = internalDataUrl.IndexOf(")", openBracketIndex + 1, StringComparison.Ordinal); if (closingBracketOffset < 0) { return null; } string dataIdStr = internalDataUrl.Substring(openBracketIndex + 1, closingBracketOffset - openBracketIndex - 1); object keyValue = ValueTypeConverter.Convert(dataIdStr, _keyType); if (keyValue == null || (keyValue is Guid && (Guid)keyValue == Guid.Empty)) { return null; } return keyValue; } public IDataReference ToDataReference(string internalDataUrl) { object keyValue = ExtractKeyValue(internalDataUrl); if (keyValue == null) return null; return (IDataReference)_dataReferenceConstructor.Invoke(new [] { keyValue }); } } } ================================================ FILE: Composite/Plugins/Routing/InternalUrlConverters/MediaInternalUrlConverter.cs ================================================ using System; using System.Collections.Generic; using System.Collections.Specialized; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.Routing; using Composite.Data; namespace Composite.Plugins.Routing.InternalUrlConverters { internal class MediaInternalUrlConverter: IInternalUrlConverter { internal static readonly string DefaultMediaStore = "MediaArchive"; private static readonly string LogTitle = typeof (MediaInternalUrlConverter).Name; private readonly string[] _acceptedUrlPrefixes = {"media("}; public IEnumerable<string> AcceptedUrlPrefixes { get { return _acceptedUrlPrefixes; } } public string ToPublicUrl(string internalMediaUrl, UrlSpace urlSpace) { int openBracketIndex = internalMediaUrl.IndexOf("(", StringComparison.Ordinal); if (openBracketIndex < 0) { return null; } int closingBracketOffset = internalMediaUrl.IndexOf(")", openBracketIndex + 1, StringComparison.Ordinal); if (closingBracketOffset < 0) { return null; } Guid mediaId; string mediaStore; string mediaIdStr = internalMediaUrl.Substring(openBracketIndex + 1, closingBracketOffset - openBracketIndex - 1); int semicolonOffset = mediaIdStr.IndexOf(":", StringComparison.Ordinal); if (semicolonOffset > 0) { mediaStore = mediaIdStr.Substring(0, semicolonOffset); mediaIdStr = mediaIdStr.Substring(semicolonOffset + 1); } else { mediaStore = DefaultMediaStore; } if (!Guid.TryParse(mediaIdStr, out mediaId)) { return null; } UrlBuilder parsedOldUrl; try { parsedOldUrl = new UrlBuilder(internalMediaUrl); } catch { Log.LogWarning(LogTitle, "Failed to parse url '{0}'".FormatWith(internalMediaUrl)); return null; } NameValueCollection queryParams = parsedOldUrl.GetQueryParameters(); return MediaUrls.BuildUrl( new MediaUrlData { MediaId = mediaId, MediaStore = mediaStore, QueryParameters = queryParams }, UrlKind.Public); } public IDataReference ToDataReference(string internalUrl) { return null; } } } ================================================ FILE: Composite/Plugins/Routing/InternalUrlConverters/PageInternalUrlConverter.cs ================================================ using System.Collections.Generic; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.Routing; using Composite.Data; namespace Composite.Plugins.Routing.InternalUrlConverters { /// <summary> /// Url provider for "internal" page links, f.e. "~/page({Guid})" /// </summary> public class PageInternalUrlConverter: IInternalUrlConverter { private static readonly string LogTitle = nameof(PageInternalUrlConverter); private readonly string[] _acceptedUrlPrefixes = { "page(", "Renderers/Page.aspx" }; /// <inheritdoc /> public IEnumerable<string> AcceptedUrlPrefixes => _acceptedUrlPrefixes; /// <inheritdoc /> public string ToPublicUrl(string internalPageUrl, UrlSpace urlSpace) { PageUrlData pageUrlData; string anchor; try { anchor = new UrlBuilder(internalPageUrl).Anchor; pageUrlData = PageUrls.UrlProvider.ParseInternalUrl(internalPageUrl); } catch { Log.LogWarning(LogTitle, "Failed to parse url '{0}'", internalPageUrl); return null; } if (pageUrlData == null) { return null; } // While viewing pages in "unpublished" scope, all the links should also be in the same scope if (DataScopeManager.CurrentDataScope == DataScopeIdentifier.Administrated) { pageUrlData.PublicationScope = PublicationScope.Unpublished; } string publicPageUrl = PageUrls.BuildUrl(pageUrlData, UrlKind.Public, urlSpace); if (publicPageUrl == null) { // We have this situation if page does not exist return null; } if (!anchor.IsNullOrEmpty()) { publicPageUrl += "#" + anchor; } return publicPageUrl; } /// <inheritdoc /> public IDataReference ToDataReference(string internalUrl) { return null; } } } ================================================ FILE: Composite/Plugins/Routing/InternalUrlProviders/DataInternalUrlProvider.cs ================================================ using System; using System.Linq; using Composite.Core.Extensions; using Composite.Core.Routing; using Composite.Core.Types; using Composite.Data; namespace Composite.Plugins.Routing.InternalUrlProviders { class DataInternalUrlProvider : IInternalUrlProvider { private readonly string _shortTypeName; private readonly Type _type; //private readonly Type _keyType; public DataInternalUrlProvider(string shortTypeName, Type type) { _type = type; //_keyType = type.GetKeyProperties().Single().PropertyType; _shortTypeName = shortTypeName; } public string BuildInternalUrl(IDataReference reference) { Verify.That(reference.ReferencedType == _type, "Incorrect type of referenced data"); string serializedKey = ValueTypeConverter.Convert<string>(reference.KeyValue); if (string.IsNullOrEmpty(serializedKey)) { return null; } return "~/{0}({1})".FormatWith(_shortTypeName, serializedKey); } } } ================================================ FILE: Composite/Plugins/Routing/MediaUrlProviders/DefaultMediaUrlProvider.cs ================================================ using System; using System.IO; using System.Text; using System.Web; using Composite.Core; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.Routing; using Composite.Core.WebClient; using Composite.Core.WebClient.Media; using Composite.Data.Types; namespace Composite.Plugins.Routing.MediaUrlProviders { /// <exclude /> public class DefaultMediaUrlProvider: IResizableImageUrlProvider { internal static readonly string DefaultMediaStore = "MediaArchive"; private static readonly string ForbiddenUrlCharacters = @"<>*%&\?#"""; private readonly string _storeId; /// <exclude /> public DefaultMediaUrlProvider(string storeId) { _storeId = storeId; } /// <exclude /> public bool IsSupportedStoreId(string storeId) { return storeId == _storeId; } /// <exclude /> public string GetPublicMediaUrl(string storeId, Guid mediaId) { return GetResizedImageUrl(storeId, mediaId, null); } /// <exclude /> public string GetResizedImageUrl(string storeId, Guid mediaId, ResizingOptions resizingOptions) { IMediaFile file = MediaUrlHelper.GetFileById(storeId, mediaId); if (file == null) { return null; } string pathToFile = UrlUtils.Combine(file.FolderPath, file.FileName); pathToFile = RemoveForbiddenCharactersAndNormalize(pathToFile); // IIS6 doesn't have wildcard mapping by default, so removing image extension if running in "classic" app pool if (!HttpRuntime.UsingIntegratedPipeline) { int dotOffset = pathToFile.IndexOf(".", StringComparison.Ordinal); if (dotOffset >= 0) { pathToFile = pathToFile.Substring(0, dotOffset); } } string mediaStore = string.Empty; if (!storeId.Equals(DefaultMediaStore, StringComparison.InvariantCultureIgnoreCase)) { mediaStore = storeId + "/"; } var url = new UrlBuilder(UrlUtils.PublicRootPath + "/media/" + mediaStore + /* UrlUtils.CompressGuid(*/ mediaId /*)*/) { PathInfo = file.LastWriteTime != null ? "/" + GetDateTimeHash(file.LastWriteTime.Value.ToUniversalTime()) : string.Empty }; if (pathToFile.Length > 0) { url.PathInfo += pathToFile; } if (resizingOptions != null && !resizingOptions.IsEmpty) { var urlWithResizing = url + "?" + resizingOptions; if (!GlobalSettingsFacade.ProtectResizedImagesWithHash) { return urlWithResizing; } return $"{urlWithResizing}&sh={resizingOptions.GetSecureHash(mediaId)}"; } return url.ToString(); } private static string GetDateTimeHash(DateTime dateTime) { int hash = dateTime.GetHashCode(); return Convert.ToBase64String(BitConverter.GetBytes(hash)).Substring(0, 6).Replace('+', '-').Replace('/', '_'); } private static string RemoveForbiddenCharactersAndNormalize(string path) { // Replacing dots with underscores, so IIS will not intercept requests in some scenarios string legalFilePath = RemoveFilePathIllegalCharacters(path); string extension = Path.GetExtension(legalFilePath); if (!MimeTypeInfo.IsIisServeable(extension)) { path = path.Replace('.', '_'); } path = path.Replace('+', ' '); foreach (var ch in ForbiddenUrlCharacters) { path = path.Replace(ch, '#'); } path = path.Replace("#", string.Empty); // Removing consecutive white spaces while (path.Contains(" ")) { path = path.Replace(" ", " "); } string[] parts = path.Split('/'); var result = new StringBuilder(); for (int i = 0; i < parts.Length; i++) { string trimmedPart = parts[i].Trim(); if (trimmedPart.Length > 0) { result.Append("/").Append(trimmedPart); } } // Encoding white spaces result.Replace(" ", "%20"); return result.ToString(); } private static string RemoveFilePathIllegalCharacters(string path) { path = path.Replace('\"', ' ').Replace('<', ' ').Replace('>', ' ').Replace('|', ' '); for (int i = 0; i < 31; i++) { path = path.Replace((char)i, ' '); } return path; } } } ================================================ FILE: Composite/Plugins/Routing/Pages/DefaultPageUrlProvider.cs ================================================ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Collections.Specialized; using System.Text; using System.Web; using Composite.Core; using Composite.Core.Collections.Generic; using Composite.Core.Extensions; using Composite.Core.Routing; using Composite.Core.Routing.Plugins.PageUrlsProviders; using Composite.Core.Routing.Plugins.PageUrlsProviders.Runtime; using Composite.Core.WebClient; using Composite.Data; using Composite.Data.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Routing.Pages { /// <summary> /// Default implementation of <see cref="IPageUrlProvider"/>. /// </summary> [ConfigurationElementType(typeof(NonConfigurablePageUrlProvider))] public class DefaultPageUrlProvider: IPageUrlProvider { /// <summary> /// Url fragment than indicates that the hostname should be ignored when resolving root page. /// Used for internally by C1 console. /// </summary> public static readonly string UrlMarker_RelativeUrl = "/c1mode(relative)"; /// <summary> /// URL fragment that indicates that "unpublished" version of the page should be shown. /// </summary> public static readonly string UrlMarker_Unpublished = "/c1mode(unpublished)"; private static readonly string InternalUrlPrefix = "~/page("; private static readonly string InternalUrlPrefixResolved = UrlUtils.PublicRootPath + "/page("; private static readonly Hashtable<Tuple<DataScopeIdentifier, string>, Hashtable<string, Guid>> _friendlyUrls = new Hashtable<Tuple<DataScopeIdentifier, string>, Hashtable<string, Guid>>(); /// <summary> /// A URL suffix, to be inserted in every page URL, f.e. ".aspx" /// </summary> public static string UrlSuffix { get; private set;} static DefaultPageUrlProvider() { DataEvents<IPage>.OnAfterAdd += (a, b) => UpdateFriendlyUrl((IPage) b.Data); DataEvents<IPage>.OnAfterUpdate += (a, b) => UpdateFriendlyUrl((IPage) b.Data); DataEvents<IPage>.OnStoreChanged += (sender, args) => { if (!args.DataEventsFired) { lock (_friendlyUrls) _friendlyUrls.Clear(); } }; DataEvents<IHostnameBinding>.OnAfterAdd += (a, b) => _hostnameBindings = null; DataEvents<IHostnameBinding>.OnAfterUpdate += (a, b) => _hostnameBindings = null; DataEvents<IHostnameBinding>.OnDeleted += (a, b) => _hostnameBindings = null; DataEvents<IUrlConfiguration>.OnStoreChanged += (a, b) => LoadUrlSuffix(); } /// <summary> /// Creates a new instance of <see cref="DefaultPageUrlProvider" /> /// </summary> public DefaultPageUrlProvider() { LoadUrlSuffix(); } private static void LoadUrlSuffix() { UrlSuffix = DataFacade.GetData<IUrlConfiguration>() .Select(c => c.PageUrlSuffix).FirstOrDefault() ?? string.Empty; } /// <inheritdoc /> [Obsolete] public IPageUrlBuilder CreateUrlBuilder(PublicationScope publicationScope, CultureInfo localizationScope, UrlSpace urlSpace) { return new PageUrlBuilder(publicationScope, localizationScope, urlSpace); } private static IReadOnlyCollection<IHostnameBinding> _hostnameBindings; private static readonly object _hostnameBindingsSyncRoot = new object(); private static IReadOnlyCollection<IHostnameBinding> GetHostnameBindings() { var result = _hostnameBindings; if (result == null) { lock (_hostnameBindingsSyncRoot) { result = _hostnameBindings; if (result == null) { _hostnameBindings = result = new ReadOnlyCollection<IHostnameBinding>( DataFacade.GetData<IHostnameBinding>().ToList()); } } } return result; } /// <inheritdoc /> public bool IsInternalUrl(string relativeUrl) { string decodedRelativeUrl = HttpUtility.UrlDecode(relativeUrl); return IsPageRendererRequest(new UrlBuilder(relativeUrl).FilePath) || decodedRelativeUrl.StartsWith(InternalUrlPrefix, true) || decodedRelativeUrl.StartsWith(InternalUrlPrefixResolved, true); } internal static bool IsPageRendererRequest(string filePath) { return filePath.EndsWith("Renderers/Page.aspx", true); } /// <inheritdoc /> public PageUrlData ParseInternalUrl(string relativeUrl) { return ParseInternalUrl(relativeUrl, out _); } private PageUrlData ParseInternalUrl(string relativeUrl, out UrlKind urlKind) { var urlBuilder = new UrlBuilder(relativeUrl); if (IsPageRendererRequest(urlBuilder.FilePath)) { urlKind = UrlKind.Renderer; return ParseRendererUrl(urlBuilder); } urlKind = UrlKind.Undefined; string decodedPath = HttpUtility.UrlDecode(urlBuilder.FullPath); string prefix = InternalUrlPrefix; if (!decodedPath.StartsWith(prefix, true)) { prefix = InternalUrlPrefixResolved; if (!decodedPath.StartsWith(prefix, true)) { return null; } } int closingBracketOffset = decodedPath.IndexOf(')'); if (closingBracketOffset < 0) { return null; } Guid pageId; if (!Guid.TryParse(decodedPath.Substring(prefix.Length, closingBracketOffset - prefix.Length), out pageId)) { return null; } string pathInfo = decodedPath.Substring(closingBracketOffset + 1); if (pathInfo.Length > 0 && pathInfo[0] != '/') { return null; } bool isUnpublished = pathInfo.Contains(UrlMarker_Unpublished); if (isUnpublished) { pathInfo = pathInfo.Replace(UrlMarker_Unpublished, string.Empty); } NameValueCollection queryString = urlBuilder.GetQueryParameters(); string cultureInfoStr = queryString["cultureInfo"]; CultureInfo cultureInfo; if (!cultureInfoStr.IsNullOrEmpty()) { cultureInfo = new CultureInfo(cultureInfoStr); } else { cultureInfo = LocalizationScopeManager.CurrentLocalizationScope; if (cultureInfo.Equals(CultureInfo.InvariantCulture)) { cultureInfo = DataLocalizationFacade.DefaultLocalizationCulture; } } queryString.Remove("cultureInfo"); urlKind = UrlKind.Internal; return new PageUrlData(pageId, isUnpublished ? PublicationScope.Unpublished : PublicationScope.Published, cultureInfo) { PathInfo = pathInfo, QueryParameters = queryString }; } private static PageUrlData ParseRendererUrl(UrlBuilder urlBuilder) { NameValueCollection queryString = urlBuilder.GetQueryParameters(); Verify.That(!string.IsNullOrEmpty(queryString["pageId"]), "Invalid query string. The 'pageId' parameter of the GUID type is expected."); string dataScopeName = queryString["dataScope"]; PublicationScope publicationScope = PublicationScope.Published; if (dataScopeName != null && string.Compare(dataScopeName, DataScopeIdentifier.AdministratedName, StringComparison.OrdinalIgnoreCase) == 0) { publicationScope = PublicationScope.Unpublished; } string cultureInfoStr = queryString["cultureInfo"]; if (cultureInfoStr.IsNullOrEmpty()) { cultureInfoStr = queryString["CultureInfo"]; } CultureInfo cultureInfo; if (!cultureInfoStr.IsNullOrEmpty()) { cultureInfo = new CultureInfo(cultureInfoStr); } else { cultureInfo = LocalizationScopeManager.CurrentLocalizationScope; if (cultureInfo.Equals(CultureInfo.InvariantCulture)) { cultureInfo = DataLocalizationFacade.DefaultLocalizationCulture; } } Guid pageId = new Guid(queryString["pageId"]); var queryParameters = new NameValueCollection(); var queryKeys = new[] { "pageId", "dataScope", "cultureInfo", "CultureInfo" }; var notUsedKeys = queryString.AllKeys.Where(key => !queryKeys.Contains(key, StringComparer.OrdinalIgnoreCase)); foreach (string key in notUsedKeys) { queryParameters.Add(key, queryString[key]); } string pathInfo = urlBuilder.PathInfo != null ? HttpUtility.UrlDecode(urlBuilder.PathInfo) : null; return new PageUrlData(pageId, publicationScope, cultureInfo) { PathInfo = pathInfo, QueryParameters = queryParameters, }; } /// <inheritdoc /> public PageUrlData ParseUrl(string absoluteUrl, out UrlKind urlKind) { Verify.ArgumentNotNullOrEmpty(absoluteUrl, "absoluteUrl"); // Converting links // "http://localhost" to "http://localhost/" // "http://localhost?..." to "http://localhost/?..." if((absoluteUrl.Count(c => c == '/') == 2) && absoluteUrl.Contains("//")) { int questionMarkIndex = absoluteUrl.IndexOf('?'); if(questionMarkIndex > 0) { absoluteUrl = absoluteUrl.Insert(questionMarkIndex, "/"); } else { absoluteUrl += "/"; } } Uri uri = new Uri(absoluteUrl); string hostname = uri.DnsSafeHost; if(!IsKnownHostname(hostname)) { urlKind = UrlKind.Undefined; return null; } string serverUrl = new UrlBuilder(absoluteUrl).ServerUrl; string relativeUrl = absoluteUrl.Substring(serverUrl.Length - 1); var urlSpace = new UrlSpace(hostname, relativeUrl); return ParseUrl(relativeUrl, urlSpace, out urlKind); } private bool IsKnownHostname(string hostname) { var context = HttpContext.Current; if(context != null && context.Request.Url.DnsSafeHost == hostname) { return true; } return GetHostnameBindings().Any(b => b.Hostname == hostname); } /// <inheritdoc /> public PageUrlData ParseUrl(string relativeUrl, UrlSpace urlSpace, out UrlKind urlKind) { if (IsInternalUrl(relativeUrl)) { return ParseInternalUrl(relativeUrl, out urlKind); } var urlBuilder = new UrlBuilder(relativeUrl); // Structure of a public url: // http[s]://<hostname>[/<ApplicationVirtualPath>]{/<languageCode>}[/<Path to a page>][/c1mode(unpublished)][/c1mode(relative)][<UrlSuffix>][/<PathInfo>] string filePathAndPathInfo = HttpUtility.UrlDecode(urlBuilder.FullPath); filePathAndPathInfo = RemoveForceRelativeUrlMarker(filePathAndPathInfo, urlSpace); filePathAndPathInfo = ParseAndRemovePublicationScopeMarker(filePathAndPathInfo, out PublicationScope publicationScope); CultureInfo locale; string pathWithoutLanguageCode; IHostnameBinding hostnameBinding = urlSpace.ForceRelativeUrls ? null : GetHostnameBindings().FirstOrDefault(b => b.Hostname == urlSpace.Hostname); if (hostnameBinding != null && filePathAndPathInfo == "/") { pathWithoutLanguageCode = "/"; locale = CultureInfo.GetCultureInfo(hostnameBinding.Culture); } else { locale = GetCultureInfo(filePathAndPathInfo, hostnameBinding, out pathWithoutLanguageCode); if (locale == null) { urlKind = UrlKind.Undefined; return null; } } using (new DataScope(publicationScope, locale)) { bool isObsolete = false; string pathToResolve = pathWithoutLanguageCode; // Supporting obsolete "*.aspx" urls if (!string.Equals(UrlSuffix, ".aspx", StringComparison.OrdinalIgnoreCase) && (pathToResolve.Contains(".aspx/") || pathToResolve.EndsWith(".aspx"))) { pathToResolve = pathToResolve.Replace(".aspx", UrlSuffix); isObsolete = true; } PageUrlData data = ParsePagePath(pathToResolve, publicationScope, locale, hostnameBinding); if (data != null) { urlKind = !isObsolete ? UrlKind.Public : UrlKind.Redirect; data.QueryParameters = urlBuilder.GetQueryParameters(); return data; } Guid friendlyUrlPageId = ParseFriendlyUrlPath(pathWithoutLanguageCode); if (friendlyUrlPageId != Guid.Empty) { urlKind = UrlKind.Friendly; return new PageUrlData(friendlyUrlPageId, publicationScope, locale) {QueryParameters = urlBuilder.GetQueryParameters()}; } } urlKind = UrlKind.Undefined; return null; } private Guid ParseFriendlyUrlPath(string pathWithoutLanguageCode) { if (pathWithoutLanguageCode.Length <= 1) { return Guid.Empty; } var map = GetFriendlyUrlsMap(); string friendlyUrl1 = pathWithoutLanguageCode.ToLowerInvariant(); string friendlyUrl2 = "~" + friendlyUrl1; string friendlyUrl3 = friendlyUrl1.Substring(1); Guid pageId; if (map.TryGetValue(friendlyUrl1, out pageId) || map.TryGetValue(friendlyUrl2, out pageId) || map.TryGetValue(friendlyUrl3, out pageId)) { return pageId; } return Guid.Empty; } private static Hashtable<string, Guid> GetFriendlyUrlsMap() { var scopeKey = new Tuple<DataScopeIdentifier, string>(DataScopeManager.CurrentDataScope, LocalizationScopeManager.CurrentLocalizationScope.Name); return _friendlyUrls.GetOrAddSync(scopeKey, a => { var result = new Hashtable<string, Guid>(); foreach (var pair in DataFacade.GetData<IPage>().Where(p => !(p.FriendlyUrl == null || p.FriendlyUrl == string.Empty)) .Select(p => new {p.Id, p.FriendlyUrl})) { result[pair.FriendlyUrl.ToLowerInvariant()] = pair.Id; } return result; }); } private static void UpdateFriendlyUrl(IPage page) { if (string.IsNullOrEmpty(page.FriendlyUrl)) { return; } var scopeKey = new Tuple<DataScopeIdentifier, string>(page.DataSourceId.DataScopeIdentifier, page.DataSourceId.LocaleScope.Name); Hashtable<string, Guid> friendlyUrlsMap; if(!_friendlyUrls.TryGetValue(scopeKey, out friendlyUrlsMap)) { return; } lock (friendlyUrlsMap) { friendlyUrlsMap[page.FriendlyUrl.ToLowerInvariant()] = page.Id; } } private PageUrlData ParsePagePath(string pagePath, PublicationScope publicationScope, CultureInfo locale, IHostnameBinding hostnameBinding) { // Parsing what's left: // [/Path to a page][UrlSuffix]{/PathInfo} string pathInfo = null; bool canBePublicUrl = true; bool pathInfoExtracted = false; if (!string.IsNullOrEmpty(UrlSuffix)) { string urlSuffixPlusSlash = UrlSuffix + "/"; int suffixOffset = pagePath.IndexOf(urlSuffixPlusSlash, StringComparison.OrdinalIgnoreCase); if (suffixOffset > 0) { pathInfo = pagePath.Substring(suffixOffset + UrlSuffix.Length); pagePath = pagePath.Substring(0, suffixOffset); pathInfoExtracted = true; } else if (pagePath.EndsWith(UrlSuffix, StringComparison.OrdinalIgnoreCase)) { pagePath = pagePath.Substring(0, pagePath.Length - UrlSuffix.Length); pathInfoExtracted = true; } else { canBePublicUrl = pagePath == "/"; // Only root page may not have a UrlSuffix } } if (canBePublicUrl) { IPage page = TryGetPageByUrlTitlePath(pagePath, pathInfoExtracted, hostnameBinding, ref pathInfo); if (page != null) { return new PageUrlData(page.Id, publicationScope, page.DataSourceId.LocaleScope) { VersionId = page.VersionId, PathInfo = pathInfo }; } } return null; } private IPage TryGetPageByUrlTitlePath(string pagePath, bool pathInfoExtracted, IHostnameBinding hostnameBinding, ref string pathInfo) { string[] pageUrlTitles = pagePath.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries); if (pageUrlTitles.Length == 0) { if (hostnameBinding != null) { IPage rootPage = PageManager.GetPageById(hostnameBinding.HomePageId, true); if (rootPage != null && (!hostnameBinding.IncludeHomePageInUrl || string.IsNullOrEmpty(rootPage.UrlTitle))) { return rootPage; } return null; } } IEnumerable<IPage> rootPages = GetChildPages(Guid.Empty); if (pageUrlTitles.Length == 0) { return rootPages.FirstOrDefault(p => string.IsNullOrEmpty(p.UrlTitle)); } string firstUrlTitle = pageUrlTitles[0]; IPage firstPage = null; if (hostnameBinding != null) { IPage rootPage = PageManager.GetPageById(hostnameBinding.HomePageId, true); bool rootPageIsOmitted = rootPage != null && (!hostnameBinding.IncludeHomePageInUrl || string.IsNullOrEmpty(rootPage.UrlTitle)); if (rootPageIsOmitted) { firstPage = FindMatchingPage(rootPage.Id, firstUrlTitle); } } if (firstPage == null) { IPage defaultRootPage = rootPages.FirstOrDefault(p => string.IsNullOrEmpty(p.UrlTitle)); if (defaultRootPage != null) { firstPage = FindMatchingPage(defaultRootPage.Id, firstUrlTitle); } if (firstPage == null) { // Searching the first pageId among root pages firstPage = FindMatchingPage(Guid.Empty, firstUrlTitle); } if (firstPage == null) return null; } IPage currentPage = firstPage; if (pageUrlTitles.Length == 1) return currentPage; for (int i = 1; i < pageUrlTitles.Length; i++) { IPage nextPage = FindMatchingPage(currentPage.Id, pageUrlTitles[i]); if (nextPage == null) { if (pathInfoExtracted) return null; pathInfo = "/" + string.Join("/", pageUrlTitles.Skip(i)); return currentPage; } currentPage = nextPage; } return currentPage; } /// <xmlignore /> protected virtual IPage FindMatchingPage(Guid parentId, string urlTitle) { foreach (var page in GetChildPages(parentId)) { if(string.Equals(page.UrlTitle, urlTitle, StringComparison.OrdinalIgnoreCase)) { return page; } } return null; } /// <xmlignore /> protected virtual IEnumerable<IPage> GetChildPages(Guid parentId) { var children = PageManager.GetChildrenIDs(parentId); for (int i=0; i<children.Count; i++) { var page = PageManager.GetPageById(children[i], true); if (page != null) { yield return page; } } } private static string RemoveForceRelativeUrlMarker(string filePath, UrlSpace urlSpace) { if (urlSpace.ForceRelativeUrls && filePath.Contains(UrlMarker_RelativeUrl)) { filePath = filePath.Replace(UrlMarker_RelativeUrl, string.Empty); } if (filePath == string.Empty) { filePath = "/"; } return filePath; } private static string ParseAndRemovePublicationScopeMarker(string filePath, out PublicationScope publicationScope) { publicationScope = PublicationScope.Published; if (filePath.Contains(UrlMarker_Unpublished)) { publicationScope = PublicationScope.Unpublished; filePath = filePath.Replace(UrlMarker_Unpublished, string.Empty); if (filePath == string.Empty) { filePath = "/"; } } return filePath; } internal static CultureInfo GetCultureInfo(string requestPath, IHostnameBinding hostnameBinding, out string pathWithoutLanguageAndAppRoot) { int startIndex = requestPath.IndexOf('/', UrlUtils.PublicRootPath.Length) + 1; if (startIndex > 0 && requestPath.Length > startIndex) { int endIndex = requestPath.IndexOf('/', startIndex + 1) - 1; if(endIndex < 0) { endIndex = requestPath.Length - 1; } if (endIndex > startIndex) { string urlMappingName = requestPath.Substring(startIndex, endIndex - startIndex + 1); if (DataLocalizationFacade.UrlMappingNames.Any(um => String.Equals(um, urlMappingName, StringComparison.OrdinalIgnoreCase))) { CultureInfo cultureInfo = DataLocalizationFacade.GetCultureInfoByUrlMappingName(urlMappingName); bool exists = DataLocalizationFacade.ActiveLocalizationNames.Contains(cultureInfo.Name); if (exists) { pathWithoutLanguageAndAppRoot = requestPath.Substring(endIndex + 1); return cultureInfo; } // Culture is inactive pathWithoutLanguageAndAppRoot = null; return null; } } } pathWithoutLanguageAndAppRoot = requestPath.Substring(UrlUtils.PublicRootPath.Length); if (hostnameBinding != null && !hostnameBinding.IncludeCultureInUrl) { return new CultureInfo(hostnameBinding.Culture); } return DataLocalizationFacade.DefaultUrlMappingCulture; } /// <inheritdoc /> public virtual string BuildUrl(PageUrlData pageUrlData, UrlKind urlKind, UrlSpace urlSpace) { Verify.ArgumentCondition(urlKind != UrlKind.Undefined, "urlKind", "Url kind is undefined"); /*var page = pageUrlData.Data; Verify.ArgumentCondition(page != null, "urlData", "Failed to get page from UrlData<IPage>");*/ if (urlKind == UrlKind.Public) { return BuildPublicUrl(pageUrlData, urlSpace); } if (urlKind == UrlKind.Renderer) { return BuildRenderUrl(pageUrlData); } if (urlKind == UrlKind.Internal) { return BuildInternalUrl(pageUrlData); } throw new NotImplementedException("Only 'Public' and 'Internal' url types are supported."); } protected string BuildPublicUrl(PageUrlData pageUrlData, UrlSpace urlSpace) { var cultureInfo = pageUrlData.LocalizationScope; var publicationScope = pageUrlData.PublicationScope; var pageUrlPath = new StringBuilder(); using (new DataScope(publicationScope, cultureInfo)) { if (!BuildPageUrlPath(pageUrlData.PageId, pageUrlData.VersionId, cultureInfo, urlSpace, pageUrlPath)) { return null; } } if (publicationScope == PublicationScope.Unpublished) { AppendUrlPart(pageUrlPath, UrlMarker_Unpublished); } if (urlSpace.ForceRelativeUrls) { AppendUrlPart(pageUrlPath, UrlMarker_RelativeUrl); } if (!string.IsNullOrEmpty(UrlSuffix) && pageUrlPath[pageUrlPath.Length - 1] != '/') { pageUrlPath.Append(UrlSuffix); } if (!string.IsNullOrEmpty(pageUrlData.PathInfo)) { AppendPathInfo(pageUrlPath, pageUrlData.PathInfo); } string url = pageUrlPath.ToString(); if (pageUrlData.QueryParameters != null) { var urlWithQuery = new UrlBuilder(url); urlWithQuery.AddQueryParameters(pageUrlData.QueryParameters); return urlWithQuery; } return url; } protected virtual bool BuildPageUrlPath(Guid pageId, Guid? versionId, CultureInfo culture, UrlSpace urlSpace, StringBuilder result) { IPage page; if (versionId != null) { page = PageManager.GetPageById(pageId, versionId.Value, true); } else { page = PageManager.GetPageById(pageId, true); } if (page == null) { return false; } Guid parentPageId = PageManager.GetParentId(pageId); if (parentPageId == Guid.Empty) { return BuildRootPageUrl(page, culture, urlSpace, result); } if (!BuildPageUrlPath(parentPageId, null, culture, urlSpace, result)) { return false; } Verify.That(result.Length >= 1, "Parent page urls is empty"); AppendSlash(result); result.Append(page.UrlTitle); return true; } protected bool BuildRootPageUrl(IPage rootPage, CultureInfo cultureInfo, UrlSpace urlSpace, StringBuilder result) { var bindings = GetHostnameBindings(); bool knownHostname = urlSpace.Hostname != null && bindings.Any(b => b.Hostname == urlSpace.Hostname); IHostnameBinding hostnameBinding = null; // Searching for a hostname binding matching either the root page, or current hostname/UrlSpace if (!urlSpace.ForceRelativeUrls && knownHostname) { Guid pageId = rootPage.Id; string host = urlSpace.Hostname; string cultureName = cultureInfo.Name; hostnameBinding = bindings.FirstOrDefault(b => b.HomePageId == pageId && b.Hostname == host && b.Culture == cultureName) ?? bindings.FirstOrDefault(b => b.HomePageId == pageId && b.Culture == cultureName) ?? bindings.FirstOrDefault(b => b.HomePageId == pageId && b.Hostname == host) ?? bindings.FirstOrDefault(b => b.HomePageId == pageId); if (hostnameBinding != null) { if (hostnameBinding.Hostname != urlSpace.Hostname) { result.AppendFormat("http{0}://", hostnameBinding.EnforceHttps ? "s" : "") .Append(hostnameBinding.Hostname); } } else { hostnameBinding = bindings.FirstOrDefault(b => b.Hostname == urlSpace.Hostname); } } result.Append(UrlUtils.PublicRootPath); string cultureUrlMapping = DataLocalizationFacade.GetUrlMappingName(cultureInfo); if (cultureUrlMapping != string.Empty && (hostnameBinding == null || hostnameBinding.IncludeCultureInUrl || hostnameBinding.Culture != cultureInfo.Name)) { result.Append("/").Append(cultureUrlMapping); } AppendSlash(result); if (rootPage.UrlTitle != string.Empty && (hostnameBinding == null || hostnameBinding.IncludeHomePageInUrl || hostnameBinding.HomePageId != rootPage.Id)) { result.Append(rootPage.UrlTitle); } return true; } protected static StringBuilder AppendSlash(StringBuilder sb) { if (sb.Length == 0 || sb[sb.Length - 1] != '/') { sb.Append('/'); } return sb; } private static StringBuilder AppendUrlPart(StringBuilder sb, string urlPart) { bool endsWithSlash = sb.Length != 0 && sb[sb.Length - 1] == '/'; bool startsWithSlash = urlPart.StartsWith("/", StringComparison.Ordinal); if (endsWithSlash != startsWithSlash) { return sb.Append(urlPart); } if (endsWithSlash) { return sb.Append(urlPart, 1, urlPart.Length - 1); } return sb.Append('/').Append(urlPart); } private static StringBuilder AppendPathInfo(StringBuilder sb, string pathInfo) { if (string.IsNullOrEmpty(pathInfo)) { return sb; } Verify.That(pathInfo[0] == '/', "pathInfo has to start with '/' character"); bool endsWithSlash = sb.Length != 0 && sb[sb.Length - 1] == '/'; if (!endsWithSlash) { sb.Append('/'); } var parts = pathInfo.Split('/'); bool isFirst = true; foreach (var pathInfoPart in parts.Skip(1)) { if (!isFirst) { sb.Append('/'); } sb.Append(UrlBuilder.DefaultHttpEncoder.UrlPathEncode(pathInfoPart)); isFirst = false; } return sb; } protected virtual string BuildRenderUrl(PageUrlData pageUrlData) { var cultureInfo = pageUrlData.LocalizationScope; string legacyScopeName = GetLegacyPublicationScopeIdentifier(pageUrlData.PublicationScope); string basePath = UrlUtils.ResolvePublicUrl("Renderers/Page.aspx"); var result = new UrlBuilder(basePath); result["pageId"] = pageUrlData.PageId.ToString(); result["cultureInfo"] = cultureInfo.ToString(); result["dataScope"] = legacyScopeName; result.PathInfo = pageUrlData.PathInfo; if (pageUrlData.QueryParameters != null) { result.AddQueryParameters(pageUrlData.QueryParameters); } return result; } private static string BuildInternalUrl(PageUrlData pageUrlData) { var cultureInfo = pageUrlData.LocalizationScope; var publicationScope = pageUrlData.PublicationScope; var result = new UrlBuilder("~/page(" + pageUrlData.PageId + ")"); string pathInfo = string.Empty; if (publicationScope == PublicationScope.Unpublished) { pathInfo = UrlMarker_Unpublished; } if (!pageUrlData.PathInfo.IsNullOrEmpty()) { pathInfo += pageUrlData.PathInfo; } result.PathInfo = pathInfo; result["cultureInfo"] = cultureInfo.ToString(); if (pageUrlData.QueryParameters != null) { result.AddQueryParameters(pageUrlData.QueryParameters); } return result; } private static string GetLegacyPublicationScopeIdentifier(PublicationScope publicationScope) { return publicationScope == PublicationScope.Published ? "public" : "administrated"; } } } ================================================ FILE: Composite/Plugins/Routing/Pages/PageUrlBuilder.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Composite.Core; using Composite.Core.Collections.Generic; using Composite.Core.Extensions; using Composite.Core.Routing; using Composite.Core.Routing.Plugins.PageUrlsProviders; using Composite.Core.WebClient; using Composite.Data; using Composite.Data.Types; namespace Composite.Plugins.Routing.Pages { [Obsolete] internal class PageUrlBuilder: IPageUrlBuilder { private static readonly string LogTitle = typeof (PageUrlBuilder).FullName; private readonly Hashtable<Guid, string> _folderPaths = new Hashtable<Guid, string>(); private readonly Hashtable<Guid, string> _redirectFolderPaths = new Hashtable<Guid, string>(); public Hashtable<string, Guid> UrlToIdLookup = new Hashtable<string, Guid>(); public Hashtable<string, Guid> UrlToIdLookupLowerCased = new Hashtable<string, Guid>(); public Hashtable<string, Guid> RedirectUrlToIdLookupLowerCased = new Hashtable<string, Guid>(); public Hashtable<string, Guid> FriendlyUrlToIdLookup = new Hashtable<string, Guid>(); public Hashtable<Guid, string> IdToUrlLookup = new Hashtable<Guid, string>(); private readonly UrlSpace _urlSpace; private readonly bool _forceRelativeUrls; // public Hashtable<Guid, IHostnameBinding> HostnameBindings = new Hashtable<Guid, IHostnameBinding>(); private readonly List<IHostnameBinding> _hostnameBindings = new List<IHostnameBinding>(); private readonly IHostnameBinding _hostnameBinding; private readonly PublicationScope _publicationScope; private readonly CultureInfo _localizationScope; private readonly string _friendlyUrlPrefix; private readonly string _friendlyUrlPrefixWithLanguageCode; private static readonly HashSet<string> _knownNotUniqueUrls = new HashSet<string>(); public string UrlSuffix { get; private set;} public PageUrlBuilder(PublicationScope publicationScope, CultureInfo localizationScope, UrlSpace urlSpace) { _publicationScope = publicationScope; _localizationScope = localizationScope; var localeMappedName = DataLocalizationFacade.GetUrlMappingName(localizationScope) ?? string.Empty; _forceRelativeUrls = urlSpace != null && urlSpace.ForceRelativeUrls; if (!_forceRelativeUrls && urlSpace != null && urlSpace.Hostname != null) { List<IHostnameBinding> hostnameBindings = DataFacade.GetData<IHostnameBinding>().ToList(); _hostnameBinding = hostnameBindings.FirstOrDefault(b => b.Hostname == urlSpace.Hostname); bool knownHostname = _hostnameBinding != null; if(knownHostname) { _hostnameBindings = hostnameBindings; _urlSpace = urlSpace; } } if(_hostnameBinding != null && !_hostnameBinding.IncludeCultureInUrl && _hostnameBinding.Culture == localizationScope.Name) { _friendlyUrlPrefix = UrlUtils.PublicRootPath; if (!localeMappedName.IsNullOrEmpty()) { _friendlyUrlPrefixWithLanguageCode = UrlUtils.PublicRootPath + "/" + localeMappedName; } } else { _friendlyUrlPrefix = UrlUtils.PublicRootPath + (localeMappedName.IsNullOrEmpty() ? string.Empty : "/" + localeMappedName); } UrlSuffix = DataFacade.GetData<IUrlConfiguration>().Select(c => c.PageUrlSuffix).FirstOrDefault() ?? string.Empty; } public PageUrlSet BuildUrlSet(IPage page, Guid parentPageId) { Verify.ArgumentNotNull(page, "page"); Verify.ArgumentCondition(page.DataSourceId.PublicationScope == _publicationScope, "page", "Page belongs to a wrong publication scope"); Verify.ArgumentCondition(page.DataSourceId.LocaleScope.Name == _localizationScope.Name, "page", "Page belongs to a wrong localization scope"); DataScopeIdentifier dataScopeIdentifier = page.DataSourceId.DataScopeIdentifier; CultureInfo cultureInfo = page.DataSourceId.LocaleScope; string parentPath; IHostnameBinding appliedHostnameBinding = null; // Checking if it is a root-level page if (parentPageId == Guid.Empty) { parentPath = GetRootPageBaseUrl(page.Id, cultureInfo, out appliedHostnameBinding); } else { Verify.That(_folderPaths.ContainsKey(parentPageId), "Method BuildUrlInternal() should be called for parent page before running for childildren, so 'urlBuildingCache' parameter will contains parent pages data."); parentPath = _folderPaths[parentPageId]; } // Building folderPath & lookup url string lookupUrl, folderPath; if (page.UrlTitle == string.Empty || (appliedHostnameBinding != null && !appliedHostnameBinding.IncludeHomePageInUrl && appliedHostnameBinding.HomePageId == page.Id)) { // Extensionless root url lookupUrl = folderPath = (parentPath == "" ? "/" : parentPath); } else { string parentPathWithSlash = parentPath + (parentPath.EndsWith("/") ? "" : "/"); string urlTitle = page.UrlTitle; #if URLDEBUG urlTitle = UrlFormattersPluginFacade.FormatUrl(urlTitle, true); #endif folderPath = parentPathWithSlash + urlTitle; lookupUrl = folderPath + UrlSuffix; } _folderPaths.Add(page.Id, folderPath); string lookupUrlLowerCased = lookupUrl.ToLowerInvariant(); if (UrlToIdLookupLowerCased.ContainsKey(lookupUrlLowerCased)) { if (!_knownNotUniqueUrls.Contains(lookupUrlLowerCased)) { lock (_knownNotUniqueUrls) { _knownNotUniqueUrls.Add(lookupUrlLowerCased); } Log.LogError(LogTitle, "Multiple pages share the same path '{0}'. Page ID: '{1}'. Duplicates are ignored.".FormatWith(lookupUrlLowerCased, page.Id)); } return null; } UrlToIdLookupLowerCased.Add(lookupUrlLowerCased, page.Id); UrlToIdLookup.Add(lookupUrl, page.Id); IdToUrlLookup.Add(page.Id, lookupUrl); // Building redirect folder path & url string redirectParentPath = (parentPageId == Guid.Empty) ? GetRedirectBaseUrl(cultureInfo) : _redirectFolderPaths[parentPageId]; if (redirectParentPath != null) { string redirectLookupUrl; string redirectFolderPath; if (!page.UrlTitle.IsNullOrEmpty()) { string parentPathWithTrailingSlash = redirectParentPath + (redirectParentPath.EndsWith("/") ? "" : "/"); redirectFolderPath = parentPathWithTrailingSlash + page.UrlTitle; redirectLookupUrl = redirectFolderPath + UrlSuffix; } else { redirectLookupUrl = redirectFolderPath = redirectParentPath; } if (redirectLookupUrl != lookupUrl || UrlSuffix == string.Empty) { _redirectFolderPaths.Add(page.Id, redirectFolderPath); string redirectLookupUrlLowerCased = redirectLookupUrl.ToLowerInvariant(); if (redirectLookupUrlLowerCased != lookupUrlLowerCased) { if (!RedirectUrlToIdLookupLowerCased.ContainsKey(redirectLookupUrlLowerCased)) { RedirectUrlToIdLookupLowerCased.Add(redirectLookupUrlLowerCased, page.Id); } } if(UrlSuffix == string.Empty) { string aspxExtensionRedirectUrl = redirectLookupUrlLowerCased + ".aspx"; if (!RedirectUrlToIdLookupLowerCased.ContainsKey(aspxExtensionRedirectUrl)) { RedirectUrlToIdLookupLowerCased.Add(aspxExtensionRedirectUrl, page.Id); } } } } string url = lookupUrl; if(_forceRelativeUrls) { url = UrlUtils.Combine(url, DefaultPageUrlProvider.UrlMarker_RelativeUrl); } if (dataScopeIdentifier.Name == DataScopeIdentifier.AdministratedName) { url = UrlUtils.Combine(url, DefaultPageUrlProvider.UrlMarker_Unpublished); } var pageUrls = new PageUrlSet { PublicUrl = url }; if(!string.IsNullOrEmpty(page.FriendlyUrl)) { string friendlyUrl = _friendlyUrlPrefix + MakeRelativeUrl(page.FriendlyUrl); string lowerCasedFriendlyUrl = friendlyUrl.ToLowerInvariant(); if(!FriendlyUrlToIdLookup.ContainsKey(lowerCasedFriendlyUrl)) { pageUrls.FriendlyUrl = friendlyUrl; FriendlyUrlToIdLookup.Add(lowerCasedFriendlyUrl, page.Id); } if(_friendlyUrlPrefixWithLanguageCode != null) { string alternativeFriendlyUrl = (_friendlyUrlPrefixWithLanguageCode + MakeRelativeUrl(page.FriendlyUrl)).ToLowerInvariant(); if(!FriendlyUrlToIdLookup.ContainsKey(alternativeFriendlyUrl)) { FriendlyUrlToIdLookup.Add(alternativeFriendlyUrl, page.Id); } } } return pageUrls; } private static string GetRedirectBaseUrl(CultureInfo cultureInfo) { string cultureUrlMapping = DataLocalizationFacade.GetUrlMappingName(cultureInfo); if (cultureUrlMapping != "") { return UrlUtils.PublicRootPath + "/" + cultureUrlMapping; } return UrlUtils.PublicRootPath; } private string GetRootPageBaseUrl(Guid pageId, CultureInfo cultureInfo, out IHostnameBinding appliedHostnameBinding) { // TODO: merge with DefaultPageUrlProvider logic string cultureUrlMapping = DataLocalizationFacade.GetUrlMappingName(cultureInfo); if (!_forceRelativeUrls && _hostnameBindings.Any()) { IHostnameBinding match = _hostnameBindings.FirstOrDefault(b => b.HomePageId == pageId && b.Culture == cultureInfo.Name); if(match == null) { match = _hostnameBindings.FirstOrDefault(b => b.HomePageId == pageId); } if(match != null) { string result = string.Empty; if (match.Hostname != _urlSpace.Hostname) { result = "http://" + match.Hostname; } result += UrlUtils.PublicRootPath; if (match.IncludeCultureInUrl || match.Culture != cultureInfo.Name) { if (cultureUrlMapping != string.Empty) { result += "/" + cultureUrlMapping; } } appliedHostnameBinding = match; return result; } } appliedHostnameBinding = _hostnameBinding; if (cultureUrlMapping != "" && (appliedHostnameBinding == null || appliedHostnameBinding.IncludeCultureInUrl || appliedHostnameBinding.Culture != cultureInfo.Name)) { return UrlUtils.PublicRootPath + "/" + cultureUrlMapping; } return UrlUtils.PublicRootPath; } private static string MakeRelativeUrl(string url) { return url.StartsWith("/") ? url : "/" + url; } } } ================================================ FILE: Composite/Plugins/Routing/UrlFormatters/StringReplaceUrlFormatter.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Web.Hosting; using System.Xml.Linq; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Routing.Plugins.UrlFormatters; using Composite.Core.Routing.Plugins.UrlFormatters.Runtime; using Composite.Core.Types; using Composite.Core.Xml; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Routing.UrlFormatters { [ConfigurationElementType(typeof(StringReplaceUrlFormatterData))] internal class StringReplaceUrlFormatter : IUrlFormatter { readonly List<Pair<string, string>> _replacementRules = new List<Pair<string, string>>(); public StringReplaceUrlFormatter(List<Pair<string, string>> replacementRules) { _replacementRules = replacementRules; } public string FormatUrl(string url) { foreach(var pair in _replacementRules) { if(pair.First.Length == 1 && pair.Second.Length == 1) { url = url.Replace(pair.First[0], pair.Second[0]); } else { url = url.Replace(pair.First, pair.Second); } } return url; } } [Assembler(typeof(StringReplaceUrlFormatterAssembler))] internal sealed class StringReplaceUrlFormatterData : UrlFormatterData { private const string RulesFilePropertyName = "rulesFile"; /// <exclude /> [ConfigurationProperty(RulesFilePropertyName, IsRequired = false)] public string RulesFile { get { return (string)this[RulesFilePropertyName]; } set { this[RulesFilePropertyName] = value; } } private const string ReplaceProperty = "ReplacementRules"; [ConfigurationProperty(ReplaceProperty)] public ReplacementElementCollection Replace { get { return (ReplacementElementCollection)base[ReplaceProperty]; } } } internal sealed class ReplacementElementCollection : ConfigurationElementCollection { public void Add(ReplacementRuleConfigurationElement element) { BaseAdd(element); } protected override ConfigurationElement CreateNewElement() { return new ReplacementRuleConfigurationElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((ReplacementRuleConfigurationElement)element).OldValue; } } internal sealed class StringReplaceUrlFormatterAssembler : IAssembler<IUrlFormatter, UrlFormatterData> { public IUrlFormatter Assemble(IBuilderContext context, UrlFormatterData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { var data = (StringReplaceUrlFormatterData)objectConfiguration; string rulesFile = data.RulesFile; if (!rulesFile.IsNullOrEmpty()) { string fullPath = HostingEnvironment.MapPath(rulesFile); Verify.That(C1File.Exists(fullPath), "Cannot find file '{0}'", rulesFile); try { XDocument xDoc = XDocumentUtils.Load(fullPath); return new StringReplaceUrlFormatter( xDoc.Root.Elements() .Select(e => new Pair<string, string>(GetAttributeNotNull(e, "oldValue"), GetAttributeNotNull(e, "newValue"))).ToList()); } catch (Exception e) { throw new ConfigurationErrorsException("Failed to process file '{0}'".FormatWith(rulesFile), e); } } var replacements = data.Replace.Cast<ReplacementRuleConfigurationElement>(); return new StringReplaceUrlFormatter(replacements.Select(r => new Pair<string, string>(r.OldValue, r.NewValue)).ToList()); } private static string GetAttributeNotNull(XElement xelement, string attributeName) { var attr = xelement.Attribute(attributeName); Verify.IsNotNull(attr, "Missing '{0}' attribute", attributeName); return attr.Value; } } internal sealed class ReplacementRuleConfigurationElement : ConfigurationElement { private const string _oldValueAttributeName = "oldValue"; [ConfigurationProperty(_oldValueAttributeName)] public string OldValue { get { return (string)base[_oldValueAttributeName]; } set { base[_oldValueAttributeName] = value; } } private const string _newValueAttributeName = "newValue"; [ConfigurationProperty(_newValueAttributeName)] public string NewValue { get { return (string)base[_newValueAttributeName]; } set { base[_newValueAttributeName] = value; } } } } ================================================ FILE: Composite/Plugins/Routing/UrlFormatters/ToLowerCaseUrlFormatter.cs ================================================ using Composite.Core.Routing.Plugins.UrlFormatters; using Composite.Core.Routing.Plugins.UrlFormatters.Runtime; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Routing.UrlFormatters { [ConfigurationElementType(typeof(NonConfigurableUrlFormatter))] internal class ToLowerCaseUrlFormatter: IUrlFormatter { public string FormatUrl(string url) { return url.ToLowerInvariant(); } } } ================================================ FILE: Composite/Plugins/Search/Endpoint/ConsoleSearchPageStructure.cs ================================================ using Composite.Plugins.Components.ComponentsEndpoint; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Search; namespace Composite.Plugins.Search.Endpoint { /// <exclude /> public class ConsoleSearchPageStructure { /// <exclude /> public string Name => "search"; /// <exclude /> public string Type => "search"; /// <exclude /> public string SearchProvider => "searchProvider"; /// <exclude /> public string UrlColumn => "label"; /// <exclude /> public ProviderResponse[] Providers => new ProviderResponse[] {new ConsoleSearchProviderResponse()}; /// <exclude /> public string Placeholder => Texts.SearchPage_SearchHerePlaceholder; /// <exclude /> public string NoResultsFound => Texts.SearchPage_NoResultFound_Template; /// <exclude /> public string SingleResultFound => Texts.SearchPage_SingleResultFound_Template; /// <exclude /> public string MultipleResultsFound => Texts.SearchPage_MultipleResultsFound_Template; } /// <exclude /> public class ConsoleSearchProviderResponse: ProviderResponse { /// <exclude /> public override string Name => "searchProvider"; /// <exclude /> public override string Uri => ConsoleSearchRpcService.WampProcedureName; } } ================================================ FILE: Composite/Plugins/Search/Endpoint/ConsoleSearchQuery.cs ================================================ namespace Composite.Plugins.Search.Endpoint { /// <exclude /> public class ConsoleSearchQuerySelection { /// <exclude /> public string FieldName { get; set; } /// <exclude /> public string[] Values { get; set; } } /// <exclude /> public class ConsoleSearchQuery { /// <exclude /> public string CultureName { get; set; } /// <exclude /> public string Text { get; set; } /// <exclude /> public string SortBy { get; set; } /// <exclude /> public bool SortInReverseOrder { get; set; } /// <exclude /> public ConsoleSearchQuerySelection[] Selections { get; set; } } } ================================================ FILE: Composite/Plugins/Search/Endpoint/ConsoleSearchResult.cs ================================================ using System.Collections.Generic; namespace Composite.Plugins.Search.Endpoint { /// <exclude /> public class ConsoleSearchResult { /// <exclude /> public string QueryText { get; set; } /// <exclude /> public ConsoleSearchResultColumn[] Columns { get; set; } /// <exclude /> public ConsoleSearchResultRow[] Rows { get; set; } /// <exclude /> public int TotalHits { get; set; } /// <exclude /> public ConsoleSearchResultFacetField[] FacetFields { get; set; } } /// <exclude /> public class ConsoleSearchResultColumn { /// <exclude /> public string FieldName { get; set; } /// <exclude /> public string Label { get; set; } /// <exclude /> public bool Sortable { get; set; } } /// <exclude /> public class ConsoleSearchResultRow { /// <exclude /> public string Label { get; set; } /// <exclude /> public string Url { get; set; } /// <exclude /> public Dictionary<string, string> Values { get; set; } } /// <exclude /> public class ConsoleSearchResultFacetField { /// <exclude /> public string FieldName { get; set; } /// <exclude /> public string Label { get; set; } /// <exclude /> public ConsoleSearchResultFacetValue[] Facets { get; set; } } /// <exclude /> public class ConsoleSearchResultFacetValue { /// <exclude /> public string Value { get; set; } /// <exclude /> public string Label { get; set; } /// <exclude /> public int HitCount { get; set; } } } ================================================ FILE: Composite/Plugins/Search/Endpoint/ConsoleSearchRpcService.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Composite.Search; using Composite.Search.Crawling; using Composite.C1Console.Users; using Composite.Core; using Composite.Core.Application; using Composite.Core.Linq; using Composite.Core.ResourceSystem; using Composite.Core.Threading; using Composite.Core.WebClient; using Composite.Core.WebClient.Services.WampRouter; using Composite.Data; using Microsoft.Extensions.DependencyInjection; using WampSharp.V2.Rpc; namespace Composite.Plugins.Search.Endpoint { [ApplicationStartup] class SearchApplicationStartup { public static void OnInitialized(IServiceProvider serviceProvider) { WampRouterFacade.RegisterCallee(new ConsoleSearchRpcService( serviceProvider.GetService<ISearchProvider>(), serviceProvider.GetServices<ISearchDocumentSourceProvider>())); } } /// <exclude /> public class ConsoleSearchRpcService : IRpcService { internal const string WampProcedureName = "search.query"; private readonly ISearchProvider _searchProvider; private readonly IEnumerable<ISearchDocumentSourceProvider> _docSourceProviders; /// <exclude /> public ConsoleSearchRpcService( ISearchProvider searchProvider, IEnumerable<ISearchDocumentSourceProvider> docSourceProviders) { _searchProvider = searchProvider; _docSourceProviders = docSourceProviders; } /// <exclude /> [WampProcedure(WampProcedureName)] public async Task<ConsoleSearchResult> QueryAsync(ConsoleSearchQuery query) { if (_searchProvider == null || query == null) return null; using (ThreadDataManager.EnsureInitialize()) { Thread.CurrentThread.CurrentCulture = UserSettings.CultureInfo; Thread.CurrentThread.CurrentUICulture = UserSettings.C1ConsoleUiLanguage; var documentSources = _docSourceProviders.SelectMany(dsp => dsp.GetDocumentSources()).ToList(); var allFields = documentSources.SelectMany(ds => ds.CustomFields).ToList(); var facetFields = RemoveDuplicateKeys( allFields .Where(f => f.FacetedSearchEnabled && f.Label != null), f => f.Name).ToList(); if (string.IsNullOrEmpty(query.Text)) { return new ConsoleSearchResult { QueryText = string.Empty, FacetFields = EmptyFacetsFromSelections(query, facetFields), TotalHits = 0 }; } var selections = new List<SearchQuerySelection>(); if (query.Selections != null) { foreach (var selection in query.Selections) { string fieldName = ExtractFieldName(selection.FieldName); var field = allFields.Where(f => f.Facet != null) .FirstOrDefault(f => f.Name == fieldName); Verify.IsNotNull(field, $"Failed to find a facet field by name '{fieldName}'"); selections.Add(new SearchQuerySelection { FieldName = fieldName, Values = selection.Values, Operation = field.Facet.FacetType == FacetType.SingleValue ? SearchQuerySelectionOperation.Or : SearchQuerySelectionOperation.And }); } } var sortOptions = new List<SearchQuerySortOption>(); if (!string.IsNullOrEmpty(query.SortBy)) { string sortByFieldName = ExtractFieldName(query.SortBy); var sortTermsAs = allFields .Where(f => f.Name == sortByFieldName && f.Preview != null && f.Preview.Sortable) .Select(f => f.Preview.SortTermsAs) .FirstOrDefault(); sortOptions.Add(new SearchQuerySortOption(sortByFieldName, query.SortInReverseOrder, sortTermsAs)); } var culture = !string.IsNullOrEmpty(query.CultureName) ? new CultureInfo(query.CultureName) : UserSettings.ActiveLocaleCultureInfo; var searchQuery = new SearchQuery(query.Text, culture) { Facets = facetFields.Select(f => new KeyValuePair<string, DocumentFieldFacet>(f.Name, f.Facet)).ToList(), Selection = selections, SortOptions = sortOptions }; searchQuery.FilterByUser(UserSettings.Username); searchQuery.AddFieldFacet(DocumentFieldNames.Source); var result = await _searchProvider.SearchAsync(searchQuery); var items = result?.Items?.Evaluate() ?? Array.Empty<SearchResultItem>(); if (!items.Any()) { return new ConsoleSearchResult { QueryText = query.Text, FacetFields = EmptyFacetsFromSelections(query, facetFields), TotalHits = 0 }; } var documents = items.Select(m => m.Document); HashSet<string> dataSourceNames; Facet[] dsFacets; if (result.Facets != null && result.Facets.TryGetValue(DocumentFieldNames.Source, out dsFacets)) { dataSourceNames = new HashSet<string>(dsFacets.Select(v => v.Value)); } else { Log.LogWarning(nameof(ConsoleSearchRpcService), "The search provider did not return the list of document sources"); dataSourceNames = new HashSet<string>(documents.Select(d => d.Source).Distinct()); } var dataSources = documentSources.Where(d => dataSourceNames.Contains(d.Name)).ToList(); var previewFields = RemoveDuplicateKeys( dataSources .SelectMany(ds => ds.CustomFields) .Where(f => f.FieldValuePreserved), f => f.Name).ToList(); using (new DataConnection(culture)) { return new ConsoleSearchResult { QueryText = query.Text, Columns = previewFields.Select(pf => new ConsoleSearchResultColumn { FieldName = MakeFieldNameJsFriendly(pf.Name), Label = StringResourceSystemFacade.ParseString(pf.Label), Sortable = pf.Preview.Sortable }).ToArray(), Rows = documents.Select(doc => new ConsoleSearchResultRow { Label = doc.Label, Url = GetFocusUrl(doc.SerializedEntityToken), Values = GetPreviewValues(doc, previewFields) }).ToArray(), FacetFields = GetFacets(result, facetFields), TotalHits = result.TotalHits }; } } } private ConsoleSearchResultFacetField[] EmptyFacetsFromSelections( ConsoleSearchQuery query, List<DocumentField> facetFields) { if (query.Selections == null) return null; return (from selection in query.Selections where selection.Values.Length > 0 let facetField = facetFields.Where(ff => ff.Name == selection.FieldName) .FirstOrException($"Facet field '{selection.FieldName}' not found") select new ConsoleSearchResultFacetField { FieldName = MakeFieldNameJsFriendly(selection.FieldName), Label = StringResourceSystemFacade.ParseString(facetField.Label), Facets = selection.Values.Select(value => new ConsoleSearchResultFacetValue { Label = (facetField.Facet.PreviewFunction ?? (v => v))(value), Value = value, HitCount = 0 }).ToArray() }).ToArray(); } private ConsoleSearchResultFacetField[] GetFacets(SearchResult queryResult, ICollection<DocumentField> facetFields) { if (queryResult.Facets == null) { return null; } var result = new List<ConsoleSearchResultFacetField>(); foreach (var field in facetFields.Where(f => queryResult.Facets.ContainsKey(f.Name))) { if(field.Label == null) continue; Facet[] values = queryResult.Facets[field.Name]; if (values.Length == 0) continue; result.Add(new ConsoleSearchResultFacetField { FieldName = MakeFieldNameJsFriendly(field.Name), Label = StringResourceSystemFacade.ParseString(field.Label), Facets = values.Select(v => new ConsoleSearchResultFacetValue { Value = v.Value, HitCount = v.HitCount, Label = (field.Facet.PreviewFunction ?? (value => value))(v.Value) }).ToArray() }); } return result.ToArray(); } private Dictionary<string, string> GetPreviewValues( SearchDocument searchDocument, IEnumerable<DocumentField> fields) { var result = new Dictionary<string, string>(); foreach (var field in fields) { object value; if (!searchDocument.FieldValues.TryGetValue(field.Name, out value)) continue; var stringValue = (field.Preview.PreviewFunction ?? (v => v?.ToString()))(value); result[MakeFieldNameJsFriendly(field.Name)] = stringValue; } return result; } private static string MakeFieldNameJsFriendly(string fieldName) { return char.IsUpper(fieldName[0]) ? "_" + fieldName : fieldName; } private static string ExtractFieldName(string jsFriendlyFieldName) { return jsFriendlyFieldName.StartsWith("_") ? jsFriendlyFieldName.Substring(1) : jsFriendlyFieldName; } private string GetFocusUrl(string serializedEntityToken) { return UrlUtils.AdminRootPath + "/top.aspx#FocusElement;" + serializedEntityToken; } private IEnumerable<T> RemoveDuplicateKeys<T>(IEnumerable<T> sequence, Func<T, string> getKeyFunc) { var keys = new HashSet<string>(); foreach (var el in sequence) { string key = getKeyFunc(el); if (keys.Contains(key)) continue; keys.Add(key); yield return el; } } } } ================================================ FILE: Composite/Plugins/Security/HookRegistrators/ElementHookRegistrator/ElementHookRegistrator.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Elements; using Composite.C1Console.Security; using Composite.C1Console.Security.Plugins.HookRegistrator; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.Security.HookRegistrators.ElementHookRegistrator { [ConfigurationElementType(typeof(ElementHookRegistratorData))] internal sealed class ElementHookRegistrator : IHookRegistrator { public IEnumerable<EntityTokenHook> GetHooks() { return ElementHookRegistratorFacade.GetHooks(); } } [Assembler(typeof(NonConfigurableHookRegistratorAssembler))] internal sealed class ElementHookRegistratorData : HookRegistratorData { } } ================================================ FILE: Composite/Plugins/Security/LoginProviderPlugins/ConfigBasedFormLoginProvider/ConfigBasedFormLoginProvider.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using Composite.C1Console.Security; using Composite.C1Console.Security.Plugins.LoginProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.Security.LoginProviderPlugins.ConfigBasedFormLoginProvider { [ConfigurationElementType(typeof(ConfigBasedFormLoginProviderData))] internal sealed class ConfigBasedFormLoginProvider : IFormLoginProvider { private NamedElementCollection<ValidLoginConfigurationElement> _validLogins; internal ConfigBasedFormLoginProvider(NamedElementCollection<ValidLoginConfigurationElement> validLogins) { _validLogins = validLogins; } public IEnumerable<string> AllUsernames { get { return _validLogins.Select(f => f.Name); } } public bool CanSetUserPassword { get { return false; } } LoginResult IFormLoginProvider.Validate(string username, string password) { if (_validLogins.Contains(username)) { ValidLoginConfigurationElement usernameMatch = _validLogins.Get(username); return usernameMatch.Password == password ? LoginResult.Success : LoginResult.IncorrectPassword; } return LoginResult.UserDoesNotExist; } public void SetUserPassword(string username, string password) { throw new NotImplementedException(); } public bool CanAddNewUser { get { return false; } } public void AddNewUser(string userName, string password, string group, string email) { throw new NotImplementedException(); } public bool UsersExists { get { return _validLogins.Any(); } } } [Assembler(typeof(ConfigBasedFormLoginProviderAssembler))] internal sealed class ConfigBasedFormLoginProviderData : LoginProviderData { private const string _validLoginsProperty = "ValidLogins"; [ConfigurationProperty(_validLoginsProperty, IsRequired = true)] public NamedElementCollection<ValidLoginConfigurationElement> ValidLogins { get { return (NamedElementCollection<ValidLoginConfigurationElement>)base[_validLoginsProperty]; } } } internal sealed class ConfigBasedFormLoginProviderAssembler : IAssembler<ILoginProvider, LoginProviderData> { public ILoginProvider Assemble(Microsoft.Practices.ObjectBuilder.IBuilderContext context, LoginProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { ConfigBasedFormLoginProviderData myConfiguration = (ConfigBasedFormLoginProviderData)objectConfiguration; return new ConfigBasedFormLoginProvider(myConfiguration.ValidLogins); } } internal sealed class ValidLoginConfigurationElement : NamedConfigurationElement { private const string _passwordProperty = "password"; [ConfigurationProperty(_passwordProperty, IsRequired = true)] public string Password { get { return (string)base[_passwordProperty]; } set { base[_passwordProperty] = value; } } } } ================================================ FILE: Composite/Plugins/Security/LoginProviderPlugins/DataBasedFormLoginProvider/DataBasedFormLoginProvider.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; using Composite.C1Console.Security; using Composite.C1Console.Security.Cryptography; using Composite.C1Console.Security.Plugins.LoginProvider.Runtime; using Composite.Core; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Security.Plugins.LoginProvider; using Composite.Data.Transactions; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.Security.LoginProviderPlugins.DataBasedFormLoginProvider { [ConfigurationElementType(typeof(DataBasedFormLoginProviderData))] internal sealed class DataBasedFormLoginProvider : IFormLoginProvider { private static readonly string LogTitle = typeof (DataBasedFormLoginProvider).Name; static readonly TimeSpan MinimalTimeBetweenLoginAttempts = TimeSpan.FromMilliseconds(500); static readonly TimeSpan HalfAnHour = TimeSpan.FromMinutes(30); private const int BruteForcePrevention_MaximumLoginAttempts = 30; private readonly int _maxLoginAttemptsBeforeLockout; static DataBasedFormLoginProvider() { if (!DataFacade.GetData<IUserFormLogin>().Any()) { UpgradeUserData(); } } public DataBasedFormLoginProvider() { var settings = ConfigurationServices.ConfigurationSource.GetSection(LoginProviderSettings.SectionName) as LoginProviderSettings; Verify.IsNotNull(settings, "Failed to load section '{0}'", LoginProviderSettings.SectionName); _maxLoginAttemptsBeforeLockout = settings.MaxLoginAttempts; } private class FailedLoginInfo { public DateTime LastLoginAttempt; public int LoginAttemptCount; } static readonly ConcurrentDictionary<string, FailedLoginInfo> _loginHistory = new ConcurrentDictionary<string, FailedLoginInfo>(); public IEnumerable<string> AllUsernames { get { return (from u in DataFacade.GetData<IUser>() select u.Username).ToList(); } } public bool CanSetUserPassword { get { return true; } } public bool CanAddNewUser { get { return true; } } public LoginResult Validate(string username, string password) { username = username.ToLower(CultureInfo.InvariantCulture); FailedLoginInfo failedLoginInfo; _loginHistory.TryGetValue(username, out failedLoginInfo); if(!BruteForcePreventionCheck(username, failedLoginInfo)) { return LoginResult.PolicyViolated; } IUser user = (from u in DataFacade.GetData<IUser>() where string.Compare(u.Username, username, StringComparison.InvariantCultureIgnoreCase) == 0 select u).FirstOrDefault(); if(user == null) { return LoginResult.UserDoesNotExist; } var userFormLogin = DataFacade.GetData<IUserFormLogin>().FirstOrDefault(u => u.UserId == user.Id); if (userFormLogin == null) { if (!user.EncryptedPassword.IsNullOrEmpty()) { throw new InvalidOperationException("User form login data is missing or present in obsolete format."); } throw new InvalidOperationException("User form login data is missing."); } bool passwordIsCorrect = UserFormLoginManager.ValidatePassword(userFormLogin, password); if (passwordIsCorrect) { if (userFormLogin.IsLocked) { if (userFormLogin.LockoutReason == (int)UserLockoutReason.LockedByAdministrator) { return LoginResult.UserLockedByAdministrator; } return LoginResult.UserLockedAfterMaxLoginAttempts; } int passwordExpirationDays = PasswordPolicyFacade.PasswordExpirationTimeInDays; if (passwordExpirationDays > 0 && DateTime.Now > userFormLogin.LastPasswordChangeDate + TimeSpan.FromDays(passwordExpirationDays)) { return LoginResult.PasswordUpdateRequired; } } UpdateLoginHistory(username, passwordIsCorrect, failedLoginInfo); if (!passwordIsCorrect && failedLoginInfo != null && failedLoginInfo.LoginAttemptCount >= _maxLoginAttemptsBeforeLockout) { LockUser(userFormLogin); } return passwordIsCorrect ? LoginResult.Success : LoginResult.IncorrectPassword; } private void LockUser(IUserFormLogin userFormLogin) { userFormLogin.IsLocked = true; userFormLogin.LockoutReason = (int) UserLockoutReason.TooManyFailedLoginAttempts; DataFacade.Update(userFormLogin); } private static void UpdateLoginHistory(string username, bool loginIsValid, FailedLoginInfo failedLoginInfo) { if(loginIsValid) { _loginHistory.TryRemove(username, out failedLoginInfo); return; } if(failedLoginInfo != null) { failedLoginInfo.LastLoginAttempt = DateTime.Now; lock(failedLoginInfo) { failedLoginInfo.LoginAttemptCount++; } return; } _loginHistory[username] = new FailedLoginInfo {LastLoginAttempt = DateTime.Now, LoginAttemptCount = 1}; } static bool BruteForcePreventionCheck(string username, FailedLoginInfo failedLoginInfo) { if (failedLoginInfo == null) { return true; } var now = DateTime.Now; /* If a user tries to login quicker that 500ms from previous attempt - it is failed automatically */ lock (failedLoginInfo) { if (now - failedLoginInfo.LastLoginAttempt < MinimalTimeBetweenLoginAttempts) { return false; } if (failedLoginInfo.LoginAttemptCount > BruteForcePrevention_MaximumLoginAttempts) { if (now - failedLoginInfo.LastLoginAttempt < HalfAnHour) { // User is "locked" for 30 minutes after 30 failed logins in a row return false; } // After half an hour - cleaning up the history FailedLoginInfo temp; _loginHistory.TryRemove(username, out temp); } } return true; } public void SetUserPassword(string username, string password) { using (var transactionScope = TransactionsFacade.CreateNewScope()) { IUser user = DataFacade.GetData<IUser>().FirstOrDefault(u => u.Username == username); Verify.IsNotNull(user, "The userFormLogin '{0}' does not exists", username); var userFormLogin = user.GetUserFormLogin(); UserFormLoginManager.SetPassword(userFormLogin, password); transactionScope.Complete(); } } public void AddNewUser(string userName, string password, string folder, string email) { var user = DataFacade.BuildNew<IUser>(); user.Id = Guid.NewGuid(); user.Username = userName.Trim().ToLowerInvariant(); user.Email = email; user = DataFacade.AddNew(user); UserFormLoginManager.CreateUserFormLogin(user.Id, password, folder); Log.LogVerbose(LogTitle, "Added new userFormLogin '{0}'", userName); } public bool UsersExists { get { return DataFacade.GetData<IUser>().Any(); } } static void UpgradeUserData() { // TODO: to be removed after upgrades will be performed from versions newer that C1 4.3 + ConvertOldPasswordFormat(); MoveDataFromIUserToIUserFormLogin(); } static void ConvertOldPasswordFormat() { int processed = 0; var toBeUpdated = new List<IUser>(); foreach (var user in DataFacade.GetData<IUser>()) { if (string.IsNullOrEmpty(user.EncryptedPassword) || !string.IsNullOrEmpty(user.PasswordHashSalt)) { continue; } string password = Cryptographer.Decrypt(user.EncryptedPassword); var salt = UserFormLoginManager.GenerateHashSalt(); user.PasswordHashSalt = Convert.ToBase64String(salt); user.EncryptedPassword = UserFormLoginManager.GeneratePasswordHash(password, salt); toBeUpdated.Add(user); processed++; } if (toBeUpdated.Any()) { DataFacade.Update(toBeUpdated); } if (processed > 0) { Log.LogInformation(LogTitle, "User passwords converted to a new format: " + processed); } } private static void MoveDataFromIUserToIUserFormLogin() { using (var conn = new DataConnection()) { var users = conn.Get<IUser>().ToList(); var existingUserLogins = new HashSet<Guid>(conn.Get<IUserFormLogin>().Select(l => l.UserId)); foreach (var user in users.Where(u => !existingUserLogins.Contains(u.Id))) { if (string.IsNullOrEmpty(user.PasswordHashSalt) && !string.IsNullOrEmpty(user.EncryptedPassword)) { throw new InvalidOperationException("User password stored in old format"); } var userFormLogin = DataConnection.New<IUserFormLogin>(); userFormLogin.UserId = user.Id; userFormLogin.Folder = user.Group; userFormLogin.IsLocked = user.IsLocked; userFormLogin.LockoutReason = user.LockoutReason; userFormLogin.PasswordHash = user.EncryptedPassword; userFormLogin.PasswordHashSalt = user.PasswordHashSalt; conn.Add(userFormLogin); // Clear out old data user.IsLocked = false; user.LockoutReason = 0; user.Group = null; user.EncryptedPassword = null; user.PasswordHashSalt = null; conn.Update(user); } } } } [Assembler(typeof(NonConfigurableLoginProviderAssembler))] internal sealed class DataBasedFormLoginProviderData : LoginProviderData { } } ================================================ FILE: Composite/Plugins/Security/LoginProviderPlugins/DataBasedFormLoginProvider/UserFormLoginManager.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using Composite.C1Console.Security; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Data; using Composite.Data.Types; namespace Composite.Plugins.Security.LoginProviderPlugins.DataBasedFormLoginProvider { /// <summary> /// User password update/validation. /// </summary> public static class UserFormLoginManager { /// <summary> /// Creates user's form login data. /// </summary> /// <param name="userId">The user id.</param> /// <param name="password">Password</param> /// <param name="userFolder">The name of the folder in which the user will be shown in c1 console.</param> public static void CreateUserFormLogin(Guid userId, string password, string userFolder) { var userFormLogin = DataFacade.BuildNew<IUserFormLogin>(); userFormLogin.UserId = userId; userFormLogin.Folder = userFolder; SetPasswordFieldsInt(userFormLogin, password); DataFacade.AddNew(userFormLogin); } /// <summary> /// Sets a password for a user, preserving password history. /// </summary> /// <param name="userFormLogin">The user form login data.</param> /// <param name="password">The new password.</param> public static void SetPassword(IUserFormLogin userFormLogin, string password) { Verify.ArgumentNotNullOrEmpty(password, "password"); SavePasswordHistory(userFormLogin); SetPasswordFieldsInt(userFormLogin, password); userFormLogin.LastPasswordChangeDate = DateTime.Now; DataFacade.Update(userFormLogin); } private static void SavePasswordHistory(IUserFormLogin userFormLogin) { if (string.IsNullOrEmpty(userFormLogin.PasswordHash) || PasswordPolicyFacade.PasswordHistoryLength <= 0) { return; } var passwordHistoryRecord = DataFacade.BuildNew<IUserPasswordHistory>(); passwordHistoryRecord.Id = Guid.NewGuid(); passwordHistoryRecord.UserId = userFormLogin.UserId; passwordHistoryRecord.SetDate = userFormLogin.LastPasswordChangeDate; passwordHistoryRecord.PasswordSalt = userFormLogin.PasswordHashSalt; passwordHistoryRecord.PasswordHash = userFormLogin.PasswordHash; DataFacade.AddNew(passwordHistoryRecord); // Cleaning up old history records Guid userId = userFormLogin.UserId; var passwordDataToBeRemoved = DataFacade.GetData<IUserPasswordHistory>() .Where(uph => uph.UserId == userId) .OrderByDescending(uph => uph.SetDate).Skip(PasswordPolicyFacade.PasswordHistoryLength).ToList(); if (passwordDataToBeRemoved.Any()) { DataFacade.Delete((IEnumerable<IData>) passwordDataToBeRemoved); } } private static void SetPasswordFieldsInt(IUserFormLogin user, string password) { var salt = GenerateHashSalt(); user.PasswordHashSalt = Convert.ToBase64String(salt); user.PasswordHash = GeneratePasswordHash(password, salt); } /// <summary> /// Validates user's password. /// </summary> /// <param name="user"></param> /// <param name="password"></param> /// <returns></returns> public static bool ValidatePassword(IUserFormLogin user, string password) { if (user.PasswordHash.IsNullOrEmpty()) { return false; } if (user.PasswordHashSalt.IsNullOrEmpty()) { return false; } byte[] salt = Convert.FromBase64String(user.PasswordHashSalt); return user.PasswordHash == GeneratePasswordHash(password, salt); } /// <summary> /// Checks whether the password appears in the user's password history. /// </summary> /// <param name="user">The user.</param> /// <param name="password">The password.</param> /// <returns></returns> public static bool PasswordFoundInHistory(IUser user, string password) { Guid userId = user.Id; var allOldPasswords = DataFacade.GetData<IUserPasswordHistory>().Where(uph => uph.UserId == userId).Evaluate(); foreach (var pwdHistory in allOldPasswords) { byte[] salt = Convert.FromBase64String(pwdHistory.PasswordSalt); if (pwdHistory.PasswordHash == GeneratePasswordHash(password, salt)) { return true; } } return false; } /// <summary> /// Generates password hash. /// </summary> /// <param name="password">The password.</param> /// <param name="salt">The salt.</param> /// <returns></returns> public static string GeneratePasswordHash(string password, byte[] salt) { using (HashAlgorithm algorithm = new SHA256Managed()) { var plainText = Encoding.UTF8.GetBytes(password); byte[] plainTextWithSaltBytes = new byte[plainText.Length + salt.Length]; plainText.CopyTo(plainTextWithSaltBytes, 0); salt.CopyTo(plainTextWithSaltBytes, plainText.Length); return Convert.ToBase64String(algorithm.ComputeHash(plainTextWithSaltBytes)); } } /// <summary> /// Generates hash salt. /// </summary> public static byte[] GenerateHashSalt() { using (var csprng = new RNGCryptoServiceProvider()) { var salt = new byte[24]; csprng.GetBytes(salt); return salt; } } /// <exclude /> public static IUserFormLogin GetUserFormLogin(this IUser user) { Guid userId = user.Id; return DataFacade.GetData<IUserFormLogin>().Where(ufl => ufl.UserId == userId) .FirstOrException("Missing user form login data for user id '{0}'", userId); } } } ================================================ FILE: Composite/Plugins/Security/LoginProviderPlugins/ValidateAllWindowsLoginProvider/ValidateAllWindowsLoginProvider.cs ================================================ using System.Collections.Generic; using System.Management; using Composite.C1Console.Security.Plugins.LoginProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.Security.LoginProviderPlugins.ValidateAllWindowsLoginProvider { [Assembler(typeof(NonConfigurableLoginProviderAssembler))] internal sealed class ValidateAllWindowsLoginProviderData : LoginProviderData { } [ConfigurationElementType(typeof(ValidateAllWindowsLoginProviderData))] internal class ValidateAllWindowsLoginProvider : IWindowsLoginProvider { private List<string> _usernames = null; public IEnumerable<string> AllUsernames { get { if (_usernames == null) { SelectQuery selectQuery = new SelectQuery("Win32_UserAccount"); ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(selectQuery); foreach (ManagementObject managementObject in managementObjectSearcher.Get()) { _usernames.Add(managementObject["Name"].ToString()); } } return _usernames; } } public bool CanSetUserPassword { get { return false; } } public bool CanAddNewUser { get { return false; } } bool IWindowsLoginProvider.Validate(string username, string domainName) { return true; } public bool UsersExists { get { return true; } } } } ================================================ FILE: Composite/Plugins/Security/LoginSessionStores/HttpContextBasedLoginSessionStore/HttpContextBasedLoginSessionStore.cs ================================================ using System; using System.Diagnostics; using System.Globalization; using System.Net; using System.Security.Cryptography; using System.Web; using System.Web.Security; using Composite.C1Console.Security.Plugins.LoginSessionStore; using Composite.Core.Caching; using Composite.Core.Extensions; using Composite.Core.Threading; using Composite.Core.WebClient; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.Security.LoginSessionStores.HttpContextBasedLoginSessionStore { [ConfigurationElementType(typeof(HttpContextBasedSessionDataProviderData))] internal sealed class HttpContextBasedLoginSessionStore : ILoginSessionStore { private static readonly TimeSpan TempTicketMaxAge = TimeSpan.FromDays(5); private static readonly TimeSpan TempTicketMinAge = TimeSpan.FromDays(4); // auto renew tickets younger than this private static readonly string ContextKey = typeof(HttpContextBasedLoginSessionStore).FullName + "StoredUsername"; internal const string AuthCookieName = ".CMSAUTH"; public bool CanPersistAcrossSessions { get { return true; } } public void StoreUsername(string userName, bool persistAcrossSessions) { StoreUsernameImpl(userName, persistAcrossSessions); } private static void StoreUsernameImpl(string userName, bool persistAcrossSessions) { Verify.ArgumentNotNullOrEmpty(userName, "userName"); userName = userName.ToLower(CultureInfo.InvariantCulture); TimeSpan timeToLive = (persistAcrossSessions ? TimeSpan.FromDays(365) : TempTicketMaxAge); var ticket = new FormsAuthenticationTicket(userName, persistAcrossSessions, (int)timeToLive.TotalMinutes); string encryptedTicket = FormsAuthentication.Encrypt(ticket); var cookie = CookieHandler.SetCookieInternal(AuthCookieName, encryptedTicket); cookie.HttpOnly = true; var context = HttpContext.Current; if (context != null) { if (context.Request.IsSecureConnection) { cookie.Secure = true; } else if (cookie.Secure) { throw new InvalidOperationException( "A login attempt over a not secure connection, when system.web/httpCookies/@requireSSL is set to 'true'. " + "Either secure connection should be required for console login, or SSL should not be required for cookies."); } } if (persistAcrossSessions) { cookie.Expires = DateTime.Now + timeToLive; } } public string StoredUsername { [DebuggerStepThrough] get { HttpContext context = HttpContext.Current; if (context == null || !context.RequestIsAvaliable()) { return null; } ThreadDataManagerData threadDataManagerData = ThreadDataManager.GetCurrentNotNull(); object value; if (threadDataManagerData.TryGetParentValue(ContextKey, out value) == false) { try { value = GetUsernameFromCookie(); if (!string.IsNullOrEmpty(value as string)) { threadDataManagerData.SetValue(ContextKey, value); } } catch (Exception) { return null; } } return value as string; } } [DebuggerStepThrough] private static string GetUsernameFromCookie() { try { string cookieValue = CookieHandler.Get(AuthCookieName); if (!string.IsNullOrEmpty(cookieValue)) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookieValue); if (!ticket.Expired && (ticket.Expiration - DateTime.Now) < TempTicketMinAge) { StoreUsernameImpl(ticket.Name, false); } return ticket.Name; } } catch (CryptographicException) { } return null; } public void FlushUsername() { CookieHandler.Set(AuthCookieName, "", DateTime.Now.AddYears(-10)); string key = typeof(HttpContextBasedLoginSessionStore) + "StoredUsername"; if (RequestLifetimeCache.HasKey(key)) { RequestLifetimeCache.Remove(key); } } public IPAddress UserIpAddress { get { string ipString = HttpContext.Current.Request.UserHostAddress; return ipString != null ? IPAddress.Parse(ipString) : null; } } } [Assembler(typeof(NonConfigurableSessionDataProviderAssembler))] internal sealed class HttpContextBasedSessionDataProviderData : LoginSessionStoreData { } } ================================================ FILE: Composite/Plugins/Security/LoginSessionStores/WampContextBasedLoginSessionStore/WampContextBasedBasedLoginSessionStore.cs ================================================ using System.Net; using Composite.C1Console.Security.Plugins.LoginSessionStore; using Composite.Core.Application; using Microsoft.Extensions.DependencyInjection; using WampSharp.V2; namespace Composite.Plugins.Security.LoginSessionStores.WampContextBasedLoginSessionStore { [ApplicationStartup] internal class WampContextBasedLoginSessionStoreRegistrator { public void ConfigureServices(IServiceCollection serviceCollection) { serviceCollection.AddSingleton(typeof(INoneConfigurationBasedLoginSessionStore), typeof(WampContextBasedBasedLoginSessionStore)); } } internal class WampContextBasedBasedLoginSessionStore : INoneConfigurationBasedLoginSessionStore { public bool CanPersistAcrossSessions => false; public void StoreUsername(string username, bool persistAcrossSessions) { } public string StoredUsername { get { if (WampInvocationContext.Current != null) { return WampInvocationContext.Current.InvocationDetails.CallerAuthenticationId; } return null; } } public void FlushUsername() { } public IPAddress UserIpAddress => null; } } ================================================ FILE: Composite/Plugins/Security/PasswordRules/DifferentCharacterGroups/DifferentCharacterGroupsPasswordRule.cs ================================================ using Composite.C1Console.Security.Plugins.PasswordPolicy; using Composite.Core.ResourceSystem; using Composite.Data.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Security.PasswordRules.DifferentCharacterGroups { [ConfigurationElementType(typeof(NonConfigurablePasswordRule))] internal class DifferentCharacterGroupsPasswordRule : IPasswordRule { public bool ValidatePassword(IUser user, string password) { bool lowerCaseLetters = false, upperCaseLetters = false, digits = false, otherCharacters = false; foreach (var ch in password) { if (char.IsLower(ch)) { lowerCaseLetters = true; continue; } if (char.IsUpper(ch)) { upperCaseLetters = true; continue; } if (char.IsDigit(ch)) { digits = true; continue; } otherCharacters = true; } int points = 0; if (lowerCaseLetters) points++; if (upperCaseLetters) points++; if (digits) points++; if (otherCharacters) points++; return points >= 3; } public string GetRuleDescription() { return LocalizationFiles.Composite_C1Console_Users.PasswordRules_DifferentCharacterGroups; } } } ================================================ FILE: Composite/Plugins/Security/PasswordRules/DoNotUseUserName/DoNotUseUserNamePasswordRule.cs ================================================ using System; using Composite.C1Console.Security.Plugins.PasswordPolicy; using Composite.Core.ResourceSystem; using Composite.Data.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Security.PasswordRules.DoNotUseUserName { [ConfigurationElementType(typeof(NonConfigurablePasswordRule))] internal class DoNotUseUserNamePasswordRule : IPasswordRule { public bool ValidatePassword(IUser user, string password) { return password.IndexOf(user.Username, StringComparison.InvariantCultureIgnoreCase) == -1; } public string GetRuleDescription() { return LocalizationFiles.Composite_C1Console_Users.PasswordRules_DoNotUseUserName; } } } ================================================ FILE: Composite/Plugins/Security/PasswordRules/EnforcePasswordHistory/EnforcePasswordHistoryPasswordRule.cs ================================================ using Composite.C1Console.Security; using Composite.C1Console.Security.Plugins.PasswordPolicy; using Composite.Core.ResourceSystem; using Composite.Data.Types; using Composite.Plugins.Security.LoginProviderPlugins.DataBasedFormLoginProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Security.PasswordRules.EnforcePasswordHistory { [ConfigurationElementType(typeof(NonConfigurablePasswordRule))] internal class EnforcePasswordHistoryPasswordRule : IPasswordRule { public bool ValidatePassword(IUser user, string password) { if (PasswordPolicyFacade.PasswordHistoryLength <= 0) return true; return !UserFormLoginManager.PasswordFoundInHistory(user, password); } public string GetRuleDescription() { return LocalizationFiles.Composite_C1Console_Users.PasswordRules_EnforcePasswordHistory(PasswordPolicyFacade.PasswordHistoryLength + 1); } } } ================================================ FILE: Composite/Plugins/Security/PasswordRules/MinimumLength/MinimumLengthPasswordRule.cs ================================================ using System.Configuration; using Composite.C1Console.Security.Plugins.PasswordPolicy; using Composite.Core.ResourceSystem; using Composite.Data.Types; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Security.PasswordRules.MinimumLength { [ConfigurationElementType(typeof(MinimumLengthPasswordRuleData))] internal class MinimumLengthPasswordRule : IPasswordRule { public MinimumLengthPasswordRule(int minLength) { Verify.That(minLength > 0, "The minimum length of a password should be at least 1 character."); _minLength = minLength; } private readonly int _minLength; public bool ValidatePassword(IUser user, string password) { return password.Length >= _minLength; } public string GetRuleDescription() { return LocalizationFiles.Composite_C1Console_Users.PasswordRules_MinimumLength(_minLength); } } [Assembler(typeof(MinimumLengthPasswordRuleAssembler))] internal class MinimumLengthPasswordRuleData : PasswordRuleData { [ConfigurationProperty("minLength", IsRequired = true)] public int MinLength { get { return (int)base["minLength"]; } set { base["minLength"] = value; } } } internal class MinimumLengthPasswordRuleAssembler : IAssembler<IPasswordRule, PasswordRuleData> { IPasswordRule IAssembler<IPasswordRule, PasswordRuleData>.Assemble(IBuilderContext context, PasswordRuleData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { var data = (MinimumLengthPasswordRuleData) objectConfiguration; return new MinimumLengthPasswordRule(data.MinLength); } } } ================================================ FILE: Composite/Plugins/Security/UserGroupPermissionDefinitionProvider/DataBasedUserGroupPermissionDefinitionProvider/DataBasedUserGroupPermissionDefinitionProvider.cs ================================================ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Transactions; using Composite.Data; using Composite.Data.Caching; using Composite.Data.Types; using Composite.C1Console.Security; using Composite.C1Console.Security.Plugins.UserGroupPermissionDefinitionProvider; using Composite.Data.Transactions; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace Composite.Plugins.Security.UserGroupPermissionDefinitionProvider.DataBasedUserGroupPermissionDefinitionProvider { [ConfigurationElementType(typeof(NonConfigurableUserGroupPermissionDefinitionProvider))] class DataBasedUserGroupPermissionDefinitionProvider : IUserGroupPermissionDefinitionProvider { private static readonly int PermissionCacheSize = 50; private static readonly Cache<Guid, ReadOnlyCollection<UserGroupPermissionDefinition>> _permissionCache = new Cache<Guid, ReadOnlyCollection<UserGroupPermissionDefinition>>("DataBasedUserGroupPermissionDefinitionProvider", PermissionCacheSize); static DataBasedUserGroupPermissionDefinitionProvider() { DataEventSystemFacade.SubscribeToDataAfterUpdate<IUserGroupPermissionDefinition>(OnUserGroupPermissionChanged, true); DataEventSystemFacade.SubscribeToDataAfterAdd<IUserGroupPermissionDefinition>(OnUserGroupPermissionChanged, true); DataEventSystemFacade.SubscribeToDataDeleted<IUserGroupPermissionDefinition>(OnUserGroupPermissionChanged, true); DataEventSystemFacade.SubscribeToStoreChanged<IUserGroupPermissionDefinition>(OnUserGroupPermissionStoreChanged, true); } public IEnumerable<UserGroupPermissionDefinition> AllUserGroupPermissionDefinitions { get { return (from urd in DataFacade.GetData<IUserGroupPermissionDefinition>() select (UserGroupPermissionDefinition)new DataUserGroupPermissionDefinition(urd)).ToList(); } } public bool CanAlterDefinitions { get { return true; } } public IEnumerable<UserGroupPermissionDefinition> GetPermissionsByUserGroup(Guid userGroupId) { ReadOnlyCollection<UserGroupPermissionDefinition> cachedUserGroupPermissionDefinitions = _permissionCache.Get(userGroupId); if (cachedUserGroupPermissionDefinitions != null) { return cachedUserGroupPermissionDefinitions; } List<UserGroupPermissionDefinition> userGroupPermissionDefinitions = (from urd in DataFacade.GetData<IUserGroupPermissionDefinition>() where urd.UserGroupId == userGroupId select (UserGroupPermissionDefinition)new DataUserGroupPermissionDefinition(urd)).ToList(); _permissionCache.Add(userGroupId, new ReadOnlyCollection<UserGroupPermissionDefinition>(userGroupPermissionDefinitions)); return userGroupPermissionDefinitions; } private EntityToken DeserializeSilent(string serializedEntityToken) { try { return EntityTokenSerializer.Deserialize(serializedEntityToken); } catch (Exception) { // Silent return null; } } public void SetUserGroupPermissionDefinition(UserGroupPermissionDefinition userGroupPermissionDefinition) { Guid userGroupId = userGroupPermissionDefinition.UserGroupId; string serializedEntityToken = userGroupPermissionDefinition.SerializedEntityToken; using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { IEnumerable<IUserGroupPermissionDefinition> existingPermissionDefinitions = DataFacade.GetData<IUserGroupPermissionDefinition>() .Where(d => d.UserGroupId == userGroupId) .ToList() .Where(d => userGroupPermissionDefinition.EntityToken.EqualsWithVersionIgnore(DeserializeSilent(d.SerializedEntityToken))) .ToList(); DataFacade.Delete(existingPermissionDefinitions); IUserGroupPermissionDefinition definition = DataFacade.BuildNew<IUserGroupPermissionDefinition>(); definition.Id = Guid.NewGuid(); definition.UserGroupId = userGroupId; definition.SerializedEntityToken = serializedEntityToken; DataFacade.AddNew(definition); foreach (PermissionType permissionType in userGroupPermissionDefinition.PermissionTypes) { IUserGroupPermissionDefinitionPermissionType permission = DataFacade.BuildNew<IUserGroupPermissionDefinitionPermissionType>(); permission.Id = Guid.NewGuid(); permission.PermissionTypeName = permissionType.ToString(); permission.UserGroupPermissionDefinitionId = definition.Id; DataFacade.AddNew(permission); } transactionScope.Complete(); } } public void RemoveUserGroupPermissionDefinition(Guid userGroupId, string serializedEntityToken) { var entityToken = EntityTokenSerializer.Deserialize(serializedEntityToken); using (var transactionScope = TransactionsFacade.CreateNewScope()) { IList<IUserGroupPermissionDefinition> toDelete; if (entityToken.IsValid()) { toDelete = DataFacade.GetData<IUserGroupPermissionDefinition>() .Where(ugpd => ugpd.UserGroupId == userGroupId) .ToList() .Where(d => entityToken.EqualsWithVersionIgnore(DeserializeSilent(d.SerializedEntityToken))) .ToList(); } else { toDelete = DataFacade.GetData<IUserGroupPermissionDefinition>() .Where(ugpd => ugpd.UserGroupId == userGroupId && ugpd.SerializedEntityToken == serializedEntityToken).ToList(); } if (toDelete.Any()) { DataFacade.Delete<IUserGroupPermissionDefinition>(toDelete); } transactionScope.Complete(); } } private static void OnUserGroupPermissionStoreChanged(object sender, StoreEventArgs storeEventArgs) { if (!storeEventArgs.DataEventsFired) { _permissionCache.Clear(); } } private static void OnUserGroupPermissionChanged(object sender, DataEventArgs args) { var userGroupPermissionDefinition = args.Data as IUserGroupPermissionDefinition; if (userGroupPermissionDefinition == null) { return; } _permissionCache.Remove(userGroupPermissionDefinition.UserGroupId); } internal sealed class DataUserGroupPermissionDefinition : UserGroupPermissionDefinition { private IUserGroupPermissionDefinition _userGroupPermissionDefinition; private List<PermissionType> _permissionTypes; public DataUserGroupPermissionDefinition(IUserGroupPermissionDefinition userGroupPermissionDefinition) { _userGroupPermissionDefinition = userGroupPermissionDefinition; Guid permissionDefinitionId = userGroupPermissionDefinition.Id; List<string> permissionTypeNames = (from pt in DataFacade.GetData<IUserGroupPermissionDefinitionPermissionType>() where pt.UserGroupPermissionDefinitionId == permissionDefinitionId select pt.PermissionTypeName).ToList(); _permissionTypes = permissionTypeNames.FromListOfStrings().ToList(); } public override Guid UserGroupId { get { return _userGroupPermissionDefinition.UserGroupId; } } public override IEnumerable<PermissionType> PermissionTypes { get { foreach (PermissionType permissionType in _permissionTypes) { yield return permissionType; } } } public override string SerializedEntityToken { get { return _userGroupPermissionDefinition.SerializedEntityToken; } } } } } ================================================ FILE: Composite/Plugins/Security/UserPermissionDefinitionProvider/ConfigBasedUserPermissionDefinitionProvider/ConfigBasedUserPermissionDefinitionProvider.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using Composite.C1Console.Security; using Composite.C1Console.Security.Plugins.UserPermissionDefinitionProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder; namespace Composite.Plugins.Security.UserPermissionDefinitionProvider.ConfigBasedUserPermissionDefinitionProvider { [ConfigurationElementType(typeof(ConfigBasedUserPermissionDefinitionProviderData))] internal sealed class ConfigBasedUserPermissionDefinitionProvider : IUserPermissionDefinitionProvider { List<UserPermissionDefinition> _userPermissionDefinitions = new List<UserPermissionDefinition>(); public ConfigBasedUserPermissionDefinitionProvider(ConfigBasedUserPermissionDefinitionProviderData configBasedUserPermissionDefinitionProviderData) { foreach (UserPermissionDefinitionConfigurationElement element in configBasedUserPermissionDefinitionProviderData.UserPermissionDefinitions) { _userPermissionDefinitions.Add(new ConfigUserPermissionDefinition(element)); } } public IEnumerable<UserPermissionDefinition> AllUserPermissionDefinitions { get { foreach (UserPermissionDefinition userPermissionDefinition in _userPermissionDefinitions) { yield return userPermissionDefinition; } } } public bool CanAlterDefinitions { get { return false; } } public void SetUserPermissionDefinition(UserPermissionDefinition userPermissionDefinition) { throw new NotImplementedException(); } public void RemoveUserPermissionDefinition(UserToken userToken, string serializedEntityToken) { throw new NotImplementedException(); } internal sealed class ConfigUserPermissionDefinition : UserPermissionDefinition { UserPermissionDefinitionConfigurationElement _element; public ConfigUserPermissionDefinition(UserPermissionDefinitionConfigurationElement element) { _element = element; } public override string Username { get { return _element.Username; } } public override IEnumerable<PermissionType> PermissionTypes { get { throw new NotImplementedException(); //return _element.PermissionName; } } public override string SerializedEntityToken { get { return _element.SerializedEntityToken; } } } #region IUserPermissionDefinitionProvider Members public IEnumerable<UserPermissionDefinition> GetPermissionsByUser(string userName) { return from urd in AllUserPermissionDefinitions where urd.Username == userName select urd; } #endregion } [Assembler(typeof(ConfigBasedUserPermissionDefinitionProviderAssembler))] internal sealed class ConfigBasedUserPermissionDefinitionProviderData : UserPermissionDefinitionProviderData { private const string _userPermissionDefinitionsProperty = "UserPermissionDefinitions"; [ConfigurationProperty(_userPermissionDefinitionsProperty, IsRequired = true)] public UserPermissionDefinitionConfigurationElementCollection UserPermissionDefinitions { get { return (UserPermissionDefinitionConfigurationElementCollection)base[_userPermissionDefinitionsProperty]; } } } internal sealed class UserPermissionDefinitionConfigurationElement : ConfigurationElement { private const string _usernameProperty = "username"; [ConfigurationProperty(_usernameProperty, IsRequired = true)] public string Username { get { return (string)base[_usernameProperty]; } set { base[_usernameProperty] = value; } } private const string _permissionTypeNameProperty = "permissionTypeName"; [ConfigurationProperty(_permissionTypeNameProperty, IsRequired = true)] public string PermissionTypeName { get { return (string)base[_permissionTypeNameProperty]; } set { base[_permissionTypeNameProperty] = value; } } private const string _serializedEntityTokenProperty = "serializedEntityToken"; [ConfigurationProperty(_serializedEntityTokenProperty, IsRequired = true)] public string SerializedEntityToken { get { return (string)base[_serializedEntityTokenProperty]; } set { base[_serializedEntityTokenProperty] = value; } } public string CompositionName { get { return string.Format("{0}{1}{2}", this.Username, this.PermissionTypeName, this.SerializedEntityToken); } } } internal sealed class UserPermissionDefinitionConfigurationElementCollection : ConfigurationElementCollection { public void Add(UserPermissionDefinitionConfigurationElement element) { base.BaseAdd(element); } protected override ConfigurationElement CreateNewElement() { return new UserPermissionDefinitionConfigurationElement(); } protected override object GetElementKey(ConfigurationElement element) { UserPermissionDefinitionConfigurationElement castedElement = (UserPermissionDefinitionConfigurationElement)element; return castedElement.CompositionName; } } internal sealed class ConfigBasedUserPermissionDefinitionProviderAssembler : IAssembler<IUserPermissionDefinitionProvider, UserPermissionDefinitionProviderData> { public IUserPermissionDefinitionProvider Assemble(IBuilderContext context, UserPermissionDefinitionProviderData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { ConfigBasedUserPermissionDefinitionProviderData data = (ConfigBasedUserPermissionDefinitionProviderData)objectConfiguration; return new ConfigBasedUserPermissionDefinitionProvider(data); } } } ================================================ FILE: Composite/Plugins/Security/UserPermissionDefinitionProvider/DataBaseUserPermissionDefinitionProvider/DataBaseUserPermissionDefinitionProvider.cs ================================================ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Transactions; using Composite.Core.Linq; using Composite.Data; using Composite.Data.Caching; using Composite.Data.Types; using Composite.C1Console.Security; using Composite.C1Console.Security.Plugins.UserPermissionDefinitionProvider; using Composite.Data.Transactions; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.Security.UserPermissionDefinitionProvider.DataBaseUserPermissionDefinitionProvider { [ConfigurationElementType(typeof(DataBaseUserPermissionDefinitionProviderData))] internal sealed class DataBaseUserPermissionDefinitionProvider : IUserPermissionDefinitionProvider { private static readonly int PermissionCacheSize = 1000; private static readonly Cache<string, ReadOnlyCollection<UserPermissionDefinition>> _permissionCache = new Cache<string, ReadOnlyCollection<UserPermissionDefinition>>("Security permissions", PermissionCacheSize); static DataBaseUserPermissionDefinitionProvider() { SubscribeToEvents(); } private static void SubscribeToEvents() { DataEventSystemFacade.SubscribeToDataAfterUpdate<IUserPermissionDefinition>(OnUserPermissionChanged, true); DataEventSystemFacade.SubscribeToDataAfterAdd<IUserPermissionDefinition>(OnUserPermissionChanged, true); DataEventSystemFacade.SubscribeToDataDeleted<IUserPermissionDefinition>(OnUserPermissionChanged, true); DataEventSystemFacade.SubscribeToStoreChanged<IUserPermissionDefinition>(OnUserPermissionStoreChanged, true); } public IEnumerable<UserPermissionDefinition> AllUserPermissionDefinitions { get { // DDZ: To be refactored - has O(N(IUserPermissionDefinition) * N(IUserPermissionDefinitionType)) compexity, which isn't acceplable // for 100+ users. return (from urd in DataFacade.GetData<IUserPermissionDefinition>() select (UserPermissionDefinition)new DataUserPermissionDefinition(urd)).ToList(); } } public bool CanAlterDefinitions { get { return true; } } private EntityToken DeserializeSilent(string serializedEntityToken) { try { return EntityTokenSerializer.Deserialize(serializedEntityToken); } catch (Exception) { // Silent return null; } } public void SetUserPermissionDefinition(UserPermissionDefinition userPermissionDefinition) { string username = userPermissionDefinition.Username; string serializedEntityToken = userPermissionDefinition.SerializedEntityToken; using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { IEnumerable<IUserPermissionDefinition> existingUserPermissionDefinitions = DataFacade.GetData<IUserPermissionDefinition>() .Where(d => d.Username == username) .ToList() .Where(d => userPermissionDefinition.EntityToken.EqualsWithVersionIgnore(DeserializeSilent(d.SerializedEntityToken))) .ToList(); DataFacade.Delete(existingUserPermissionDefinitions); IUserPermissionDefinition definition = DataFacade.BuildNew<IUserPermissionDefinition>(); definition.Id = Guid.NewGuid(); definition.Username = userPermissionDefinition.Username; definition.SerializedEntityToken = serializedEntityToken; DataFacade.AddNew(definition); foreach (PermissionType permissionType in userPermissionDefinition.PermissionTypes) { IUserPermissionDefinitionPermissionType permission = DataFacade.BuildNew<IUserPermissionDefinitionPermissionType>(); permission.Id = Guid.NewGuid(); permission.PermissionTypeName = permissionType.ToString(); permission.UserPermissionDefinitionId = definition.Id; DataFacade.AddNew(permission); } transactionScope.Complete(); } } public void RemoveUserPermissionDefinition(UserToken userToken, string serializedEntityToken) { string username = userToken.Username; var entityToken = EntityTokenSerializer.Deserialize(serializedEntityToken); using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { IList<IUserPermissionDefinition> toDelete; if (entityToken.IsValid()) { toDelete = DataFacade.GetData<IUserPermissionDefinition>() .Where(upd => upd.Username == username) .ToList() .Where(d => entityToken.EqualsWithVersionIgnore(DeserializeSilent(d.SerializedEntityToken))) .ToList(); } else { toDelete = DataFacade.GetData<IUserPermissionDefinition>() .Where(upd => upd.Username == username && upd.SerializedEntityToken == serializedEntityToken) .ToList(); } if (toDelete.Count > 0) { DataFacade.Delete<IUserPermissionDefinition>(toDelete); } transactionScope.Complete(); } } public IEnumerable<UserPermissionDefinition> GetPermissionsByUser(string userName) { var cachedValue = _permissionCache.Get(userName); if(cachedValue != null) { return cachedValue; } var allPermissionTypes = DataFacade.GetData<IUserPermissionDefinitionPermissionType>() .GroupBy(p => p.UserPermissionDefinitionId).ToDictionary(g => g.Key, g => g.ToList()); var permissions = (from urd in DataFacade.GetData<IUserPermissionDefinition>().Evaluate() where urd.Username == userName && allPermissionTypes.ContainsKey(urd.Id) select (UserPermissionDefinition) new DataUserPermissionDefinition(urd, allPermissionTypes[urd.Id])).ToList(); _permissionCache.Add(userName, new ReadOnlyCollection<UserPermissionDefinition>(permissions)); return permissions; } internal sealed class DataUserPermissionDefinition : UserPermissionDefinition { private readonly IUserPermissionDefinition _userPermissionDefinition; private readonly List<PermissionType> _permissionTypes; public DataUserPermissionDefinition(IUserPermissionDefinition userPermissionDefinition) { _userPermissionDefinition = userPermissionDefinition; Guid permissionDefinitionId = userPermissionDefinition.Id; List<string> permissionTypeNames = (from pt in DataFacade.GetData<IUserPermissionDefinitionPermissionType>() where pt.UserPermissionDefinitionId == permissionDefinitionId select pt.PermissionTypeName).ToList(); _permissionTypes = permissionTypeNames.FromListOfStrings().ToList(); } public DataUserPermissionDefinition(IUserPermissionDefinition userPermissionDefinition, IEnumerable<IUserPermissionDefinitionPermissionType> permissionTypes) { _userPermissionDefinition = userPermissionDefinition; var permissionTypeNames = permissionTypes.Select(pt => pt.PermissionTypeName); _permissionTypes = permissionTypeNames.FromListOfStrings().ToList(); } public override string Username { get { return _userPermissionDefinition.Username; } } public override IEnumerable<PermissionType> PermissionTypes { get { return _permissionTypes; } } public override string SerializedEntityToken { get { return _userPermissionDefinition.SerializedEntityToken; } } } private static void OnUserPermissionStoreChanged(object sender, StoreEventArgs storeEventArgs) { if (!storeEventArgs.DataEventsFired) { _permissionCache.Clear(); } } private static void OnUserPermissionChanged(object sender, DataEventArgs args) { var permission = args.Data as IUserPermissionDefinition; if (permission == null) { return; } _permissionCache.Remove(permission.Username); } } [Assembler(typeof(NonConfigurableUserPermissionDefinitionProviderAssembler))] internal sealed class DataBaseUserPermissionDefinitionProviderData : UserPermissionDefinitionProviderData { } } ================================================ FILE: Composite/Plugins/Types/TypeManagerTypeHandler/AspNetBuildManagerTypeManagerTypeHandler/AspNetBuildManagerTypeManagerTypeHandler.cs ================================================ using System; using System.Linq; using System.Reflection; using System.Web.Compilation; using Composite.Core.Types.Plugins.TypeManagerTypeHandler; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using System.Web.Hosting; namespace Composite.Plugins.Types.TypeManagerTypeHandler.AspNetBuildManagerTypeManagerTypeHandler { [ConfigurationElementType(typeof(AspNetBuildManagerTypeManagerTypeHandlerData))] internal sealed class AspNetBuildManagerTypeManagerTypeHandler : ITypeManagerTypeHandler { private const string _typeNamePrefix = "AspNetType:"; public Type GetType(string fullName) { if (!HostingEnvironment.IsHosted) return null; string name = fullName; if (name.StartsWith(_typeNamePrefix)) { name = name.Remove(0, _typeNamePrefix.Length); } if(name.Contains(":")) { return null; } return BuildManager.GetType(name, false, true); } public string SerializeType(Type type) { if (!HostingEnvironment.IsHosted) return null; if (BuildManager.CodeAssemblies != null) { foreach (object obj in BuildManager.CodeAssemblies) { Assembly assembly = obj as Assembly; if (assembly != null) { if (assembly.GetTypes().Contains(type)) { return string.Format("{0}{1}", _typeNamePrefix, type.FullName); } } } } return null; } public bool HasTypeWithName(string typeFullname) { if (!HostingEnvironment.IsHosted) return false; return BuildManager.GetType(typeFullname, false, true) != null; } } [Assembler(typeof(NonConfigurableTypeManagerTypeHandlerAssembler))] internal sealed class AspNetBuildManagerTypeManagerTypeHandlerData : TypeManagerTypeHandlerData { } } ================================================ FILE: Composite/Plugins/Types/TypeManagerTypeHandler/DynamicBuildManagerTypeManagerTypeHandler/DynamicBuildManagerTypeManagerTypeHandler.cs ================================================ using System; using System.Collections.Generic; using System.Web.Hosting; using Composite.Core.Types; using Composite.Core.Types.Plugins.TypeManagerTypeHandler; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.Types.TypeManagerTypeHandler.DynamicBuildManagerTypeManagerTypeHandler { [ConfigurationElementType(typeof(DynamicBuildManagerTypeManagerTypeHandlerData))] internal sealed class DynamicBuildManagerTypeManagerTypeHandler : ITypeManagerTypeHandler { private static readonly string _prefix = "DynamicType:"; private static readonly object _lock = new object(); private static readonly Dictionary<Type, string> _serializedCache = new Dictionary<Type, string>(); public Type GetType(string fullName) { Type compiledType = CodeGenerationManager.GetCompiledType(fullName); if (compiledType != null) return compiledType; string name = fullName; bool hasObsoletePrefix = name.StartsWith(_prefix); if (hasObsoletePrefix) { name = name.Substring(_prefix.Length); } if (!name.Contains(",") && (hasObsoletePrefix || !HostingEnvironment.IsHosted)) { return Type.GetType(name + ", Composite.Generated"); } return null; } public string SerializeType(Type type) { lock (_lock) { string result; if (!_serializedCache.TryGetValue(type, out result)) { result = SerializeTypeImpl(type); _serializedCache.Add(type, result); } return result; } } public bool HasTypeWithName(string typeFullname) { return GetType(typeFullname) != null; } private static string SerializeTypeImpl(Type type) { string assemblyLocation = type.Assembly.Location; string assemblyCodeBase = type.Assembly.CodeBase; string tempAssemblyFolderPath = CodeGenerationManager.TempAssemblyFolderPath; string tempAssemblyFolderUri = new Uri(tempAssemblyFolderPath).AbsoluteUri; if (assemblyLocation.StartsWith(tempAssemblyFolderPath, StringComparison.InvariantCultureIgnoreCase) || assemblyCodeBase.StartsWith(tempAssemblyFolderUri, StringComparison.InvariantCultureIgnoreCase) || assemblyLocation.IndexOf(CodeGenerationManager.CompositeGeneratedFileName, StringComparison.InvariantCultureIgnoreCase) >= 0) { return type.FullName; } return null; } } [Assembler(typeof(NonConfigurableTypeManagerTypeHandlerAssembler))] internal sealed class DynamicBuildManagerTypeManagerTypeHandlerData : TypeManagerTypeHandlerData { } } ================================================ FILE: Composite/Plugins/Types/TypeManagerTypeHandler/SystemTypeManagerTypeHandler/SystemTypeManagerTypeHandler.cs ================================================ using System; using Composite.Core.Types; using Composite.Core.Types.Plugins.TypeManagerTypeHandler; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.Types.TypeManagerTypeHandler.SystemTypeManagerTypeHandler { [ConfigurationElementType(typeof(SystemTypeManagerTypeHandlerData))] internal sealed class SystemTypeManagerTypeHandler : ITypeManagerTypeHandler { public Type GetType(string fullName) { if(fullName.Contains(":")) { return null; } try { return Type.GetType(fullName); } catch (Exception) { // Suppress all exceptions return null; } } public string SerializeType(Type type) { if (type.FullName.StartsWith("System") == false) { return type.GetVersionNeutralName(); } else { return type.AssemblyQualifiedName; } } public bool HasTypeWithName(string typeFullname) { return GetType(typeFullname) != null; } } [Assembler(typeof(NonConfigurableTypeManagerTypeHandlerAssembler))] internal sealed class SystemTypeManagerTypeHandlerData : TypeManagerTypeHandlerData { } } ================================================ FILE: Composite/Plugins/Validation/ClientValidationRuleTranslators/StandardClientValidationRuleTranslator/StandardClientValidationRuleTranslator.cs ================================================ using System; using System.Collections.Generic; using Composite.Data.Validation.ClientValidationRules; using Composite.Data.Validation.Plugins.ClientValidationRuleTranslator; using Composite.Data.Validation.Validators; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.Validation.ClientValidationRuleTranslators.StandardClientValidationRuleTranslator { [ConfigurationElementType(typeof(StandardClientValidationRuleTranslatorData))] internal sealed class StandardClientValidationRuleTranslator : IClientValidationRuleTranslator { private readonly List<Type> _supportedTypes = new List<Type> { typeof(RegexValidatorAttribute), #pragma warning disable 0612 typeof(StringLengthValidatorAttribute), #pragma warning restore 0612 typeof(Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidatorAttribute) }; public IEnumerable<Type> GetSupportedAttributeTypes() { return _supportedTypes; } public ClientValidationRule Translate(Attribute attribute) { Type type = attribute.GetType(); if (type == typeof(RegexValidatorAttribute)) { return new RegexClientValidationRule((attribute as RegexValidatorAttribute).Pattern); } #pragma warning disable 0612 else if (type == typeof(StringLengthValidatorAttribute)) { return new StringLengthClientValidationRule((attribute as StringLengthValidatorAttribute).LowerBound, (attribute as StringLengthValidatorAttribute).UpperBound); } #pragma warning restore 0612 else if (type == typeof(StringSizeValidatorAttribute)) { return new StringLengthClientValidationRule((attribute as StringSizeValidatorAttribute).LowerBound, (attribute as StringSizeValidatorAttribute).UpperBound); } else if (type == typeof(Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidatorAttribute)) { return new NotNullClientValidationRule(); } else { throw new InvalidOperationException(string.Format("The attribute type '{0}' is not supported", attribute.GetType())); } } } [Assembler(typeof(NonConfigurableClientValidationRuleTranslatorAssembler))] internal sealed class StandardClientValidationRuleTranslatorData : ClientValidationRuleTranslatorData { } } ================================================ FILE: Composite/Plugins/Workflow/WorkflowRuntimeProviders/StandardWorkflowRuntimeProvider/StandardWorkflowRuntimeProvider.cs ================================================ using System.Workflow.Runtime; using Composite.C1Console.Workflow.Plugins.WorkflowRuntimeProvider; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; namespace Composite.Plugins.Workflow.WorkflowRuntimeProviders.StandardWorkflowRuntimeProvider { [ConfigurationElementType(typeof(StandardWorkflowRuntimeProviderData))] internal sealed class StandardWorkflowRuntimeProvider : IWorkflowRuntimeProvider { public WorkflowRuntime GetWorkflowRuntime() { return new WorkflowRuntime(); } } [Assembler(typeof(NonConfigurableWorkflowRuntimeProviderAssembler))] internal sealed class StandardWorkflowRuntimeProviderData : WorkflowRuntimeProviderData { } } ================================================ FILE: Composite/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. See also Composite SharedAssemblyInfo.cs [assembly: AssemblyDescription("C1 CMS Core classes")] [assembly: AssemblyConfiguration("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c190c8d0-449f-42db-972d-0fc30f8c301d")] [assembly: InternalsVisibleTo("UpgradePackage")] [assembly: InternalsVisibleTo("Composite.Workflows")] ================================================ FILE: Composite/Properties/SharedAssemblyInfo.cs ================================================ using System.Reflection; // General Information about the assemblies Composite and Composite.Workflows #if !InternalBuild [assembly: AssemblyTitle("C1 CMS 6.13")] #else [assembly: AssemblyTitle("C1 CMS 6.13 (Internal Build)")] #endif [assembly: AssemblyCompany("Orckestra Technologies Inc.")] [assembly: AssemblyProduct("C1 CMS")] [assembly: AssemblyCopyright("Copyright © Orckestra Technologies Inc. 2022")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("6.13.*")] ================================================ FILE: Composite/RuntimeInformation.cs ================================================ using System; using System.Linq; using Composite.Core.IO; using System.Reflection; using Composite.Core; using Composite.Core.Configuration; namespace Composite { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class RuntimeInformation { private static bool? _isUnitTest; private static string _uniqueInstanceName; private static string _uniqueInstanceNameSafe; private static readonly Lazy<Version> _brandedAssemblyName = new Lazy<Version>(GetBrandedProductVersion); /// <exclude /> public static bool IsDebugBuild { get { #if DEBUG return true; #else return false; #endif } } /// <exclude /> public static bool AppDomainLockingDisabled => IsUnittest; /// <exclude /> public static bool IsUnittest { get { if (!_isUnitTest.HasValue) { _isUnitTest = IsUnittestEnvironment(); } return _isUnitTest.Value; } } private static bool IsUnittestEnvironment() { var domain = AppDomain.CurrentDomain; string applicationName = domain.SetupInformation.ApplicationName; return domain.FriendlyName.StartsWith("NUnit ") || applicationName == null || applicationName == "vstesthost.exe"; } internal static bool TestAutomationEnabled => true; /// <exclude /> public static Version ProductVersion { get { return typeof(RuntimeInformation).Assembly.GetName().Version; } } /// <summary> /// A version number to be shown in UI. /// </summary> public static Version BrandedProductVersion { get { return _brandedAssemblyName.Value ?? ProductVersion; } } private static Version GetBrandedProductVersion() { try { string assemblyName = GlobalSettingsFacade.BrandedVersionAssemblySource; if (assemblyName == null) { return null; } var asm = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == assemblyName); if (asm == null) { Log.LogWarning(nameof(RuntimeInformation), $"Failed to find branded product version source assembly by name '{assemblyName}'"); return null; } return asm.GetName().Version; } catch (Exception ex) { Log.LogError(nameof(RuntimeInformation), ex); return null; } } /// <exclude /> public static string ProductTitle { get { Assembly asm = typeof(RuntimeInformation).Assembly; string assemblyTitle = ((AssemblyTitleAttribute)asm.GetCustomAttributes(typeof(AssemblyTitleAttribute), false)[0]).Title; return assemblyTitle; } } /// <exclude /> public static string UniqueInstanceName { get { if (_uniqueInstanceName == null) { string baseString = PathUtil.BaseDirectory.ToLowerInvariant(); _uniqueInstanceName = $"C1@{PathUtil.CleanFileName(baseString)}"; } return _uniqueInstanceName; } } /// <exclude /> public static string UniqueInstanceNameSafe { get { if (_uniqueInstanceNameSafe == null) { string baseString = PathUtil.BaseDirectory.ToLowerInvariant().Replace(@"\", "-").Replace("/", "-"); _uniqueInstanceNameSafe = $"C1@{PathUtil.CleanFileName(baseString)}"; } return _uniqueInstanceNameSafe; } } } } ================================================ FILE: Composite/Search/Crawling/DataFieldProcessors/DateTimeDataFieldProcessor.cs ================================================ using System; using System.Globalization; using System.Reflection; namespace Composite.Search.Crawling.DataFieldProcessors { /// <summary> /// The default field processor for <see cref="DateTime"/> fields. /// </summary> public class DateTimeDataFieldProcessor: DefaultDataFieldProcessor { /// <exclude /> public override object GetIndexValue(object fieldValue) { return ((DateTime?) fieldValue)?.ToString("s"); } /// <exclude /> protected override DocumentFieldPreview.ValuePreviewDelegate GetPreviewFunction(PropertyInfo propertyInfo) { return value => { if (value == null) return null; if (DateTime.TryParseExact((string)value, "s", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)) { return date.ToString("yyyy MMM d"); } return (string)value; }; } /// <exclude /> public override string[] GetFacetValues(object value) { var str = ((DateTime?) value)?.ToString("yyyy MM"); return str != null ? new [] {str} : null; } /// <exclude /> protected override DocumentFieldFacet.FacetValuePreviewDelegate GetFacetValuePreviewFunction(PropertyInfo propertyInfo) { return value => { if (value == null) return null; var parts = value.Split(' '); int month = int.Parse(parts[1]); var monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month); return $"{parts[0]} {monthName}"; }; } } } ================================================ FILE: Composite/Search/Crawling/DataFieldProcessors/FileNameDataFieldProcessor.cs ================================================ using System; using System.Collections.Generic; namespace Composite.Search.Crawling.DataFieldProcessors { internal class FileNameDataFieldProcessor: DefaultDataFieldProcessor { public override IEnumerable<string> GetTextParts(object value) { string fileName = (string) value; yield return fileName; int extensionSeparator = fileName.LastIndexOf(".", StringComparison.Ordinal); if (extensionSeparator > 0) { yield return fileName.Substring(0, extensionSeparator); } if (extensionSeparator + 1 < fileName.Length) { yield return fileName.Substring(extensionSeparator + 1); } } } } ================================================ FILE: Composite/Search/Crawling/DataFieldProcessors/MediaTagsDataFieldProcessor.cs ================================================ using Composite.Core.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Composite.Search.Crawling.DataFieldProcessors { class MediaTagsDataFieldProcessor : DefaultDataFieldProcessor { public override string[] GetFacetValues(object value) { var str = (string)value; var strList = str.Split(',').Select(s => s.Trim()).Where(s => !s.IsNullOrEmpty()).ToArray(); return strList; } public override DocumentFieldFacet GetDocumentFieldFacet(PropertyInfo propertyInfo) { var result = base.GetDocumentFieldFacet(propertyInfo); result.FacetType = FacetType.MultipleValues; return result; } } } ================================================ FILE: Composite/Search/Crawling/DataFieldProcessors/MimeTypeDataFieldProcessor.cs ================================================ using System.Reflection; using Composite.Core.IO; namespace Composite.Search.Crawling.DataFieldProcessors { internal class MimeTypeDataFieldProcessor : DefaultDataFieldProcessor { protected override DocumentFieldPreview.ValuePreviewDelegate GetPreviewFunction(PropertyInfo propertyInfo) { return value => GetLocalizedLabel((string)value); } protected override DocumentFieldFacet.FacetValuePreviewDelegate GetFacetValuePreviewFunction(PropertyInfo propertyInfo) { return GetLocalizedLabel; } private string GetLocalizedLabel(string mimeType) => MimeTypeInfo.TryGetLocalizedName(mimeType) ?? mimeType; } } ================================================ FILE: Composite/Search/Crawling/DataFieldProcessors/PublicationStatusDataFieldProcessor.cs ================================================ using System.Reflection; using Composite.Core.ResourceSystem; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Search.Untranslated; namespace Composite.Search.Crawling.DataFieldProcessors { internal class PublicationStatusDataFieldProcessor: DefaultDataFieldProcessor { public override string GetFieldLabel(PropertyInfo propertyInfo) => Texts.FieldNames_PublicationStatus; protected override DocumentFieldPreview.ValuePreviewDelegate GetPreviewFunction(PropertyInfo propertyInfo) { return value => GetLocalizedPublicationStatus((string) value); } protected override DocumentFieldFacet.FacetValuePreviewDelegate GetFacetValuePreviewFunction(PropertyInfo propertyInfo) { return GetLocalizedPublicationStatus; } private static string GetLocalizedPublicationStatus(string status) { switch (status) { case GenericPublishProcessController.Published: return LocalizationFiles.Composite_Management.PublishingStatus_published; case GenericPublishProcessController.Draft: return LocalizationFiles.Composite_Management.PublishingStatus_draft; case GenericPublishProcessController.AwaitingApproval: return LocalizationFiles.Composite_Management.PublishingStatus_awaitingApproval; case GenericPublishProcessController.AwaitingPublication: return LocalizationFiles.Composite_Management.PublishingStatus_awaitingPublication; } return status; } } } ================================================ FILE: Composite/Search/Crawling/DataTypeSearchReflectionHelper.cs ================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.Core; using Composite.Core.Types; using Composite.Data; using Composite.Data.ProcessControlled; using Composite.Data.Types; using Composite.Search.Crawling.DataFieldProcessors; using SearchableFieldInfo = System.Collections.Generic.KeyValuePair<System.Reflection.PropertyInfo, Composite.Data.SearchableFieldAttribute>; namespace Composite.Search.Crawling { /// <summary> /// A helper class for extracting search related information frome the data types. /// </summary> public static class DataTypeSearchReflectionHelper { private static readonly ConcurrentDictionary<Type, IEnumerable<SearchableFieldInfo>> DocumentFieldsCache = new ConcurrentDictionary<Type, IEnumerable<SearchableFieldInfo>>(); private static readonly ConcurrentDictionary<PropertyInfo, IDataFieldProcessor> DataFieldProcessors = new ConcurrentDictionary<PropertyInfo, IDataFieldProcessor>(); internal static IEnumerable<SearchableFieldInfo> GetSearchableFields(Type interfaceType) { if (!typeof(IData).IsAssignableFrom(interfaceType)) return Enumerable.Empty<SearchableFieldInfo>(); return DocumentFieldsCache.GetOrAdd(interfaceType, type => { var properties = type.GetAllProperties(); var result = new List<SearchableFieldInfo>(); foreach (var property in properties) { var searchableAttr = property.GetCustomAttributesRecursively<SearchableFieldAttribute>().FirstOrDefault(); if (searchableAttr == null) continue; result.Add(new SearchableFieldInfo(property, searchableAttr)); } return result; }); } internal static IDataFieldProcessor GetDataFieldProcessor(PropertyInfo propertyInfo) { return DataFieldProcessors.GetOrAdd(propertyInfo, pi => { var processor = ServiceLocator.GetServices<IDataFieldProcessorProvider>() .Select(p => p.GetDataFieldProcessor(pi)) .FirstOrDefault(pr => pr != null); if (processor != null) return processor; var propertyType = pi.PropertyType; if (propertyType == typeof (DateTime) || propertyType == typeof (DateTime?)) { return new DateTimeDataFieldProcessor(); } if (propertyInfo.DeclaringType == typeof(IPublishControlled) && propertyInfo.Name == nameof(IPublishControlled.PublicationStatus)) { return new PublicationStatusDataFieldProcessor(); } if (propertyInfo.DeclaringType == typeof(IFile) && propertyInfo.Name == nameof(IFile.FileName)) { return new FileNameDataFieldProcessor(); } if (propertyInfo.DeclaringType == typeof(IMediaFile) && propertyInfo.Name == nameof(IMediaFile.MimeType)) { return new MimeTypeDataFieldProcessor(); } if (propertyInfo.DeclaringType == typeof(IMediaFile) && propertyInfo.Name == nameof(IMediaFile.Tags)) { return new MediaTagsDataFieldProcessor(); } return new DefaultDataFieldProcessor(); }); } /// <summary> /// Gets an enumeration of the search document fields from a data type. /// </summary> /// <param name="interfaceType"></param> /// <param name="includeDefaultFields"></param> /// <returns></returns> public static IEnumerable<DocumentField> GetDocumentFields(Type interfaceType, bool includeDefaultFields = true) { var fields = includeDefaultFields ? SearchDocumentBuilder.GetDefaultDocumentFields() : Enumerable.Empty<DocumentField>(); fields = fields.Concat( from info in GetSearchableFields(interfaceType) let prop = info.Key let attr = info.Value where attr.Previewable || attr.Faceted let processor = GetDataFieldProcessor(prop) select new DocumentField( processor.GetDocumentFieldName(prop), attr.Faceted ? processor.GetDocumentFieldFacet(prop) : null, attr.Previewable ? processor.GetDocumentFieldPreview(prop) : null) { Label = processor.GetFieldLabel(prop) }); if (includeDefaultFields) { fields = fields.Concat( ServiceLocator.GetServices<IDocumentFieldProvider>() .SelectMany(fp => fp.GetCustomFields(interfaceType))); } return fields; } } } ================================================ FILE: Composite/Search/Crawling/DefaultDataFieldProcessor.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.Types; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Search.Untranslated; namespace Composite.Search.Crawling { /// <summary> /// The default data field processor. /// </summary> public class DefaultDataFieldProcessor: IDataFieldProcessor { /// <exclude /> public virtual IEnumerable<string> GetTextParts(object value) { if (value is string str) { yield return str; } } /// <exclude /> public virtual object GetIndexValue(object fieldValue) { return fieldValue == null ? null : ValueTypeConverter.Convert<string>(fieldValue); } /// <exclude /> public virtual string[] GetFacetValues(object value) { if (value == null) return null; string stringValue = value.ToString(); return string.IsNullOrEmpty(stringValue) ? null : new[] { stringValue }; } /// <exclude /> public virtual string GetDocumentFieldName(PropertyInfo pi) { if (pi.Name == nameof(IPage.Description) && pi.PropertyType == typeof(string)) { return DocumentFieldNames.Description; } if ((pi.Name == nameof(IChangeHistory.ChangeDate) || pi.Name == nameof(IMediaFile.CreationTime)) && (pi.PropertyType == typeof(DateTime) || pi.PropertyType == typeof(DateTime?))) { return DocumentFieldNames.LastUpdated; } return $"{pi.ReflectedType.Name}.{pi.Name}"; } /// <exclude /> public virtual DocumentFieldFacet GetDocumentFieldFacet(PropertyInfo propertyInfo) { return new DocumentFieldFacet { Limit = 100, MinHitCount = 1, PreviewFunction = GetFacetValuePreviewFunction(propertyInfo) }; } /// <exclude /> public virtual DocumentFieldPreview GetDocumentFieldPreview(PropertyInfo propertyInfo) { return new DocumentFieldPreview { Sortable = IsFieldSortable(propertyInfo), SortTermsAs = GetFieldSortingMethod(propertyInfo.PropertyType), PreviewFunction = GetPreviewFunction(propertyInfo), FieldOrder = 100 }; } private SortTermsAs GetFieldSortingMethod(Type propertyType) { if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof (Nullable<>)) { propertyType = propertyType.GetGenericArguments()[0]; } if (propertyType == typeof (byte)) { return SortTermsAs.Int; } if (propertyType == typeof(short)) { return SortTermsAs.Int; } if (propertyType == typeof(int)) { return SortTermsAs.Int; } if (propertyType == typeof(long)) { return SortTermsAs.Long; } if (propertyType == typeof(float)) { return SortTermsAs.Float; } if (propertyType == typeof(decimal)) { return SortTermsAs.Double; } return SortTermsAs.String; } /// <exclude /> public virtual string GetFieldLabel(PropertyInfo propertyInfo) { var fieldName = GetDocumentFieldName(propertyInfo); if (fieldName == DocumentFieldNames.Description) { return Texts.FieldNames_Description; } if (fieldName == DocumentFieldNames.LastUpdated) return Texts.FieldNames_LastUpdated; if (propertyInfo.Name == nameof(IChangeHistory.ChangedBy)) return Texts.FieldNames_UpdatedBy; if (propertyInfo.Name == nameof(IMediaFile.MimeType)) return Texts.FieldNames_MimeType; if (propertyInfo.Name == nameof(IPage.PageTypeId)) return Texts.FieldNames_PageTypeId; var frpAttribute = propertyInfo.GetCustomAttribute<FormRenderingProfileAttribute>(); if (!string.IsNullOrEmpty(frpAttribute?.Label)) { return frpAttribute.Label; } Guid immutableTypeId; DataTypeDescriptor dataTypeDescriptor; if (propertyInfo.DeclaringType.TryGetImmutableTypeId(out immutableTypeId) && DynamicTypeManager.TryGetDataTypeDescriptor(immutableTypeId, out dataTypeDescriptor)) { var fieldDescriptor = dataTypeDescriptor?.Fields.FirstOrDefault(f => f.Name == propertyInfo.Name); var label = fieldDescriptor?.FormRenderingProfile?.Label; if (label != null) { return label; } } return propertyInfo.Name; } /// <exclude /> protected virtual DocumentFieldPreview.ValuePreviewDelegate GetPreviewFunction(PropertyInfo propertyInfo) { return value => value?.ToString(); } /// <exclude /> protected virtual DocumentFieldFacet.FacetValuePreviewDelegate GetFacetValuePreviewFunction(PropertyInfo propertyInfo) { var foreignKey = propertyInfo.GetCustomAttributes<ForeignKeyAttribute>().FirstOrDefault(); if (foreignKey != null) { var targetType = foreignKey.InterfaceType; if (targetType != null && DynamicTypeManager.TryGetDataTypeDescriptor(targetType, out DataTypeDescriptor typeDescriptor) && !string.IsNullOrEmpty(typeDescriptor.LabelFieldName)) { return key => { if (key == null) return string.Empty; var data = DataFacade.TryGetDataByUniqueKey(targetType, key); return data?.GetLabel() ?? key.ToString(); }; } } return obj => obj; } private static bool IsFieldSortable(PropertyInfo propertyInfo) { var attr = propertyInfo.GetCustomAttribute<StoreFieldTypeAttribute>(true); Verify.IsNotNull(attr, $"Failed to find and attribute of type '{nameof(StoreFieldTypeAttribute)}'"); var storeFieldType = attr.StoreFieldType; if (storeFieldType.IsString) { return storeFieldType.MaximumLength <= 64; } return storeFieldType.IsDateTime || storeFieldType.IsNumeric || storeFieldType.IsBoolean; } } } ================================================ FILE: Composite/Search/Crawling/DocumentFieldNames.cs ================================================ using System; namespace Composite.Search.Crawling { /// <exclude/> [Obsolete("Use DocumentFieldNames instead", true)] public static class DefaultDocumentFieldNames { /// <exclude/> public static readonly string Label = DocumentFieldNames.Label; /// <exclude/> public static readonly string Source = DocumentFieldNames.Source; /// <exclude/> public static readonly string Description = DocumentFieldNames.Description; /// <exclude/> public static readonly string DataType = DocumentFieldNames.DataType; /// <exclude/> public static readonly string ConsoleAccess = DocumentFieldNames.ConsoleAccess; /// <exclude/> public static readonly string Ancestors = DocumentFieldNames.Ancestors; /// <exclude/> public static readonly string HasUrl = DocumentFieldNames.HasUrl; /// <exclude/> public static readonly string LastUpdated = DocumentFieldNames.LastUpdated; } /// <summary> /// Contains default document field names /// </summary> public static class DocumentFieldNames { /// <summary> /// The name of the label field. /// </summary> public static readonly string Label = "label"; /// <summary> /// The name of the source field. /// The source field contains a name of the document source that created the search document. /// It is used both for updating documents for a given source as well as filtering search result columns. /// </summary> public static readonly string Source = "src"; /// <summary> /// The name of the description field. /// </summary> public static readonly string Description = "desc"; /// <summary> /// The name of the data type field. /// </summary> public static readonly string DataType = "datatype"; /// <summary> /// The name of the facet field that contains the list of users and user groups that have access to the current document. /// </summary> public static readonly string ConsoleAccess = "access"; /// <summary> /// The name of the facet field that contains the hashes of all ancestor's and current entity tokens. /// </summary> public static readonly string Ancestors = "ancestors"; /// <summary> /// The name of the boolean facet field that indicates whether the document has a url. /// </summary> public static readonly string HasUrl = "hasUrl"; /// <summary> /// The name of the creation time field. /// </summary> public static readonly string LastUpdated = "lastupdated"; /// <summary> /// Gets the field name for the given data type property /// </summary> /// <param name="dataType">The data type.</param> /// <param name="propertyName">The property name.</param> /// <returns></returns> public static string GetFieldName(Type dataType, string propertyName) { Verify.ArgumentNotNull(dataType, nameof(dataType)); Verify.ArgumentNotNull(propertyName, nameof(propertyName)); var propertyInfo = dataType.GetProperty(propertyName); Verify.IsNotNull(propertyInfo, "Type '{0}' does not have a prorety '{1}'", dataType.FullName, propertyName); var processor = DataTypeSearchReflectionHelper.GetDataFieldProcessor(propertyInfo); return processor.GetDocumentFieldName(propertyInfo); } } } ================================================ FILE: Composite/Search/Crawling/EntityTokenSecurityHelper.cs ================================================ using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Composite.C1Console.Security; using Composite.C1Console.Security.Foundation.PluginFacades; using Composite.Core.Threading; using Composite.Data; using Composite.Data.Types; namespace Composite.Search.Crawling { internal static class EntityTokenSecurityHelper { static EntityTokenSecurityHelper() { DataEvents<IUserPermissionDefinition>.OnStoreChanged += (a,b) => _allUserAccessDefinitions = null; DataEvents<IUserPermissionDefinitionPermissionType>.OnStoreChanged += (a, b) => _allUserAccessDefinitions = null; DataEvents<IUserGroupPermissionDefinition>.OnStoreChanged += (a, b) => _allUserGroupAccessDefinitions = null; DataEvents<IUserGroupPermissionDefinitionPermissionType>.OnStoreChanged += (a, b) => _allUserGroupAccessDefinitions = null; } class UserAccess { public string UserName; public bool HasAccess; } class GroupAccess { public Guid UserGroupId; public bool HasAccess; } private static Dictionary<EntityToken, List<UserAccess>> _allUserAccessDefinitions; private static Dictionary<EntityToken, List<GroupAccess>> _allUserGroupAccessDefinitions; public static void GetUsersAndGroupsWithReadAccess(EntityToken entityToken, out IEnumerable<EntityToken> ancestors, out IEnumerable<string> users, out IEnumerable<Guid> userGroups) { var userSet = new HashSet<string>(); var userGroupSet = new HashSet<Guid>(); var ancestorsSet = new HashSet<EntityToken>(); using (ThreadDataManager.EnsureInitialize()) using (new DataScope(DataScopeIdentifier.Administrated)) { CollectUsersAndGroupsRec(entityToken, GetUserAccessDefinitions(), GetUserGroupAccessDefinitions(), ImmutableHashSet<string>.Empty, ImmutableHashSet<Guid>.Empty, userSet, userGroupSet, ancestorsSet, 20); } ancestors = ancestorsSet; users = userSet; userGroups = userGroupSet; } private static void CollectUsersAndGroupsRec( EntityToken entityToken, Dictionary<EntityToken, List<UserAccess>> userAccessDefinitions, Dictionary<EntityToken, List<GroupAccess>> groupAccessDefinitions, ImmutableHashSet<string> usersWithoutAccess, ImmutableHashSet<Guid> groupsWithoutAccess, HashSet<string> usersWithAccess, HashSet<Guid> groupsWithAccess, HashSet<EntityToken> alreadyVisited, int depth) { if(depth < 1) return; List<UserAccess> users; if (userAccessDefinitions.TryGetValue(entityToken, out users)) { foreach (var user in users) { if (!user.HasAccess) { usersWithoutAccess = usersWithoutAccess.Add(user.UserName); } else if(!usersWithoutAccess.Contains(user.UserName)) { usersWithAccess.Add(user.UserName); } } } List<GroupAccess> userGroups; if (groupAccessDefinitions.TryGetValue(entityToken, out userGroups)) { foreach (var userGroup in userGroups) { if (!userGroup.HasAccess) { groupsWithoutAccess = groupsWithoutAccess.Add(userGroup.UserGroupId); } else if (!groupsWithoutAccess.Contains(userGroup.UserGroupId)) { groupsWithAccess.Add(userGroup.UserGroupId); } } } alreadyVisited.Add(entityToken); var parents = ParentsFacade.GetAllParents(entityToken); foreach (var parent in parents) { if(alreadyVisited.Contains(parent)) continue; CollectUsersAndGroupsRec(parent, userAccessDefinitions, groupAccessDefinitions, usersWithoutAccess, groupsWithoutAccess, usersWithAccess, groupsWithAccess, alreadyVisited, depth - 1); } } private static Dictionary<EntityToken, List<UserAccess>> GetUserAccessDefinitions() { var result = _allUserAccessDefinitions; if (result != null) { return result; } result = UserPermissionDefinitionProviderPluginFacade.AllUserPermissionDefinitions .Select(pd => new { pd.EntityToken, pd.Username, HasAccess = pd.PermissionTypes.Contains(PermissionType.Read) }) .Where(a => a.EntityToken != null && a.EntityToken.IsValid()) .GroupBy(a => a.EntityToken) .ToDictionary(group => group.Key, group => group.Select(a => new UserAccess {UserName = a.Username, HasAccess = a.HasAccess }) .ToList()); _allUserAccessDefinitions = result; return result; } private static Dictionary<EntityToken, List<GroupAccess>> GetUserGroupAccessDefinitions() { var result = _allUserGroupAccessDefinitions; if (result != null) { return result; } result = UserGroupPermissionDefinitionProviderPluginFacade.AllUserGroupPermissionDefinitions .Select(pd => new { pd.EntityToken, pd.UserGroupId, HasAccess = pd.PermissionTypes.Contains(PermissionType.Read) }) .Where(a => a.EntityToken != null && a.EntityToken.IsValid()) .GroupBy(a => a.EntityToken) .ToDictionary(group => group.Key, group => group.Select(a => new GroupAccess { UserGroupId = a.UserGroupId, HasAccess = a.HasAccess }) .ToList()); _allUserGroupAccessDefinitions = result; return result; } } } ================================================ FILE: Composite/Search/Crawling/IDataFieldProcessor.cs ================================================ using System.Collections.Generic; using System.Reflection; namespace Composite.Search.Crawling { /// <summary> /// Extracts indexable information for a data type field. /// </summary> public interface IDataFieldProcessor { /// <summary> /// Gets the text parts for the full text search. /// </summary> /// <param name="fieldValue"></param> /// <returns></returns> IEnumerable<string> GetTextParts(object fieldValue); /// <summary> /// Get the field value to be preserved in the index. /// </summary> /// <param name="fieldValue"></param> /// <returns></returns> object GetIndexValue(object fieldValue); /// <summary> /// Gets the facet values from the given field. /// </summary> /// <param name="fieldValue"></param> /// <returns></returns> string[] GetFacetValues(object fieldValue); /// <summary> /// Gets the document field name for the specified data type property. /// </summary> /// <param name="propertyInfo"></param> /// <returns></returns> string GetDocumentFieldName(PropertyInfo propertyInfo); /// <summary> /// Gets the facet information for the given property. /// </summary> /// <param name="propertyInfo"></param> /// <returns></returns> DocumentFieldFacet GetDocumentFieldFacet(PropertyInfo propertyInfo); /// <summary> /// Gets the field preview information for the given property. /// </summary> /// <param name="propertyInfo"></param> /// <returns></returns> DocumentFieldPreview GetDocumentFieldPreview(PropertyInfo propertyInfo); /// <summary> /// Gets the field label in a given locale. /// </summary> /// <param name="propertyInfo"></param> /// <returns></returns> string GetFieldLabel(PropertyInfo propertyInfo); } } ================================================ FILE: Composite/Search/Crawling/IDataFieldProcessorProvider.cs ================================================ using System.Reflection; namespace Composite.Search.Crawling { /// <summary> /// Allows augmenting crawling data types for search related information. /// </summary> public interface IDataFieldProcessorProvider { /// <summary> /// Provides <see cref="IDataFieldProcessor" /> for a given property info /// </summary> IDataFieldProcessor GetDataFieldProcessor(PropertyInfo dataTypeProperty); } } ================================================ FILE: Composite/Search/Crawling/IDocumentFieldProvider.cs ================================================ using System; using System.Collections.Generic; namespace Composite.Search.Crawling { /// <summary> /// Allows adding custom document fields to existing document sources. /// </summary> public interface IDocumentFieldProvider { /// <summary> /// Returns custom fields that should be added to the datatype's search document. /// </summary> /// <param name="dataType">The data type.</param> /// <returns></returns> IEnumerable<DocumentField> GetCustomFields(Type dataType); } } ================================================ FILE: Composite/Search/Crawling/ISearchDocumentBuilderExtension.cs ================================================ using Composite.Data; namespace Composite.Search.Crawling { /// <summary> /// Allows extending the default SearchDocumentBuilder class, /// making it possible to index additional new text fragments/field values. /// </summary> public interface ISearchDocumentBuilderExtension { /// <summary> /// Populates the search document builder with the new data. /// </summary> /// <param name="searchDocumentBuilder"></param> /// <param name="data"></param> void Populate(SearchDocumentBuilder searchDocumentBuilder, IData data); } } ================================================ FILE: Composite/Search/Crawling/SearchDocumentBuilder.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading; using Composite.C1Console.Security; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.WebClient; using Composite.Data; using Composite.Data.Types; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Search; namespace Composite.Search.Crawling { /// <summary> /// A helper class to create search documents based of IData instances /// </summary> public class SearchDocumentBuilder { private readonly List<string> _textParts = new List<string>(); private readonly List<KeyValuePair<string, object>> _fieldValues = new List<KeyValuePair<string, object>>(); private readonly List<KeyValuePair<string, string[]>> _facetFieldValues = new List<KeyValuePair<string, string[]>>(); private readonly IEnumerable<ISearchDocumentBuilderExtension> _extensions; private IPage _currentPage; /// <summary> /// Creates a new instance of <see cref="SearchDocumentBuilder"/>. /// </summary> [Obsolete("Use an overload taking extensions as a parameter.")] public SearchDocumentBuilder(): this(null) { } /// <summary> /// Creates a new instance of <see cref="SearchDocumentBuilder"/>. /// </summary> public SearchDocumentBuilder(IEnumerable<ISearchDocumentBuilderExtension> extensions) { _extensions = extensions; } /// <summary> /// Collected text parts. /// </summary> public ICollection<string> TextParts => _textParts; /// <summary> /// Collected field values to be available in search results. /// </summary> public ICollection<KeyValuePair<string, object>> FieldPreviewValues => _fieldValues; /// <summary> /// Collected facet field values /// </summary> public ICollection<KeyValuePair<string, string[]>> FacetFieldValues => _facetFieldValues; /// <summary> /// The document url. Setting a not empty value makes the document searchable from the frontend. /// </summary> public string Url { get; set; } /// <summary> /// A factor by which a search document should be boosted index time. /// </summary> public float Boost { get; set; } = 1; /// <summary> /// Sets the interface type, name of which will be used for populating the "Data Type" column in the search results. /// </summary> /// <param name="interfaceType">The interface type.</param> public void SetDataType(Type interfaceType) { string value; if (typeof (IData).IsAssignableFrom(interfaceType)) { Guid dataTypeId = interfaceType.GetImmutableTypeId(); value = dataTypeId.ToString(); } else { value = interfaceType.FullName; } SetDataType(value); } /// Sets the data type name, which will be used for populating the "Data Type" column in the search results. public void SetDataType(string dataTypeName) { _fieldValues.Add(new KeyValuePair<string, object>(DocumentFieldNames.DataType, dataTypeName)); _facetFieldValues.Add(new KeyValuePair<string, string[]>(DocumentFieldNames.DataType, new[] { dataTypeName })); } /// <summary> /// Extracts searchable information from a given data object /// (including text parts, field values for search results preview and faceted search). /// </summary> /// <param name="data">The data item to collect searchable information from.</param> /// <param name="skipInheritedInterfaces">When <value>true</value>, the inherited properties will not be processed.</param> public void CrawlData(IData data, bool skipInheritedInterfaces = false) { var interfaceType = data.DataSourceId.InterfaceType; var fields = DataTypeSearchReflectionHelper.GetSearchableFields(interfaceType); if (data is IPage page) { _currentPage = page; } foreach (var field in fields) { var propertyInfo = field.Key; if (skipInheritedInterfaces && propertyInfo.DeclaringType != interfaceType) { continue; } var fieldProcessor = DataTypeSearchReflectionHelper.GetDataFieldProcessor(propertyInfo); object value = propertyInfo.GetValue(data); if(value == null) continue; var attr = field.Value; // Text indexing if (attr.IndexText) { var textParts = fieldProcessor.GetTextParts(value); if (textParts != null) { _textParts.AddRange(textParts.SelectMany(ProcessXhtml)); } } // Field previewing if (attr.Previewable) { var indexValue = fieldProcessor.GetIndexValue(value); if (indexValue != null) { _fieldValues.Add(new KeyValuePair<string, object>( fieldProcessor.GetDocumentFieldName(propertyInfo), indexValue)); } } // Faceted fields if (attr.Faceted) { string[] facetValues = fieldProcessor.GetFacetValues(value); if (facetValues != null && facetValues.Length > 0) { _facetFieldValues.Add(new KeyValuePair<string, string[]>( fieldProcessor.GetDocumentFieldName(propertyInfo), facetValues)); } } } _extensions?.ForEach(e => { try { e.Populate(this, data); } catch (Exception ex) when (!(ex is ThreadAbortException)) { Log.LogError(nameof(SearchDocumentBuilder), ex); } }); } /// <exclude /> [Obsolete("Use an overload that does not take a Url parameter and use the Url property instead.")] public SearchDocument BuildDocument( string source, string documentId, string label, string versionName, EntityToken entityToken, string url) { Url = Url ?? url; return BuildDocument(source, documentId, label, versionName, entityToken); } /// <summary> /// Builds an instance of <see cref="SearchDocument"/> based on collected information. /// </summary> /// <param name="source">The document source name</param> /// <param name="documentId">The document id</param> /// <param name="label">The label of the item in the tree</param> /// <param name="versionName">The version name of the item</param> /// <param name="entityToken">The entity token.</param> /// <returns></returns> public SearchDocument BuildDocument( string source, string documentId, string label, string versionName, EntityToken entityToken) { Verify.ArgumentNotNullOrEmpty(source, nameof(source)); Verify.ArgumentNotNullOrEmpty(documentId, nameof(documentId)); Verify.ArgumentNotNullOrEmpty(label, nameof(label)); _fieldValues.Add(new KeyValuePair<string, object>(DocumentFieldNames.Label, label)); if (!string.IsNullOrWhiteSpace(Url)) { _facetFieldValues.Add(new KeyValuePair<string, string[]>(DocumentFieldNames.HasUrl, new[] { "1" })); } AddAccessField(entityToken); return new SearchDocument(source, documentId, label, entityToken) { ElementBundleName = versionName, FullText = _textParts, Url = Url, Boost = Boost, FieldValues = _fieldValues .ExcludeDuplicateKeys(pair => pair.Key) .ToDictionary(pair => pair.Key, pair => pair.Value), FacetFieldValues = _facetFieldValues .ExcludeDuplicateKeys(pair => pair.Key) .ToDictionary(pair => pair.Key, pair => pair.Value) }; } private void AddAccessField(EntityToken entityToken) { IEnumerable<EntityToken> ancestors; IEnumerable<string> users; IEnumerable<Guid> groups; EntityTokenSecurityHelper.GetUsersAndGroupsWithReadAccess(entityToken, out ancestors, out users, out groups); var tokens = users.Concat(groups.Select(g => g.ToString())).ToArray(); if (tokens.Any()) { _facetFieldValues.Add(new KeyValuePair<string, string[]>( DocumentFieldNames.ConsoleAccess, tokens)); } if (ancestors.Any()) { var ancestorTokens = ancestors.Select(GetEntityTokenHash).ToArray(); _facetFieldValues.Add(new KeyValuePair<string, string[]>( DocumentFieldNames.Ancestors, ancestorTokens)); } } internal static string GetEntityTokenHash(EntityToken entityToken) { var token = new StringBuilder(); if (entityToken is DataEntityToken dataEntityToken && typeof(IVersioned).IsAssignableFrom(dataEntityToken.InterfaceType)) { var dataSourceId = dataEntityToken.DataSourceId; // Serialize without versionId token.Append(dataEntityToken.Id); token.Append(':'); token.Append(dataSourceId.LocaleScope); token.Append(":"); token.Append(dataSourceId.DataScopeIdentifier); } else { token.Append(EntityTokenSerializer.Serialize(entityToken)); } var md5Hash = HashingHelper.ComputeMD5Hash(token.ToString(), Encoding.UTF8); return UrlUtils.CompressGuid(md5Hash); } /// <summary> /// Gets the list of default document fields /// </summary> /// <returns></returns> public static IEnumerable<DocumentField> GetDefaultDocumentFields() { return new[] { new DocumentField( DocumentFieldNames.Label, null, new DocumentFieldPreview { PreviewFunction = value => value?.ToString(), Sortable = true, FieldOrder = 1 }) { Label = Texts.Untranslated.FieldNames_Label }, new DocumentField( DocumentFieldNames.Source, new DocumentFieldFacet { PreviewFunction = value => value, FacetType = FacetType.SingleValue, MinHitCount = 1 }, null) { Label = null }, new DocumentField( DocumentFieldNames.DataType, new DocumentFieldFacet { PreviewFunction = GetDataTypeLabel, MinHitCount = 1 }, new DocumentFieldPreview { PreviewFunction = GetDataTypeLabel, Sortable = false, FieldOrder = 2 }) { Label = Texts.Untranslated.FieldNames_DataType }, new DocumentField( DocumentFieldNames.HasUrl, new DocumentFieldFacet { PreviewFunction = value => value, MinHitCount = 1 }, null) { Label = null }, new DocumentField( DocumentFieldNames.ConsoleAccess, new DocumentFieldFacet { FacetType = FacetType.MultipleValues, MinHitCount = 1 }, null) { Label = null }, new DocumentField( DocumentFieldNames.Ancestors, new DocumentFieldFacet { FacetType = FacetType.MultipleValues, MinHitCount = 1 }, null) { Label = null } }; } private IEnumerable<string> ProcessXhtml(string textFragment) { if (textFragment.StartsWith("<html")) { var crawler = new XhtmlCrawlingHelper { CrawlFunctionParameters = _currentPage?.DataSourceId.PublicationScope == PublicationScope.Unpublished }; crawler.SetPageContext(_currentPage); crawler.CrawlXhtml(textFragment); foreach (var fragment in crawler.TextParts) { yield return fragment; } } else { yield return textFragment; } } private static string GetDataTypeLabel(object datatype) { var str = (string)datatype; Guid dataTypeId; if (Guid.TryParse(str, out dataTypeId)) { if (dataTypeId == new Guid("C046F704-D3E4-4b3d-8CB9-77564FB0B9E7")) { return Texts.DataType_Page; } if (dataTypeId == new Guid("A8716C78-1499-4155-875B-2545006385B2")) { return Texts.DataType_MediaFile; } var descriptor = DataMetaDataFacade.GetDataTypeDescriptor(dataTypeId); if (descriptor != null) { return descriptor.Title ?? descriptor.Name; } } return str; } } } ================================================ FILE: Composite/Search/Crawling/XhtmlCrawlingHelper.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Xml.Linq; using Composite.Core; using Composite.Core.Routing; using Composite.Core.Routing.Pages; using Composite.Core.WebClient.Renderings.Page; using Composite.Core.Xml; using Composite.Data.Types; using Composite.Functions; namespace Composite.Search.Crawling { internal class XhtmlCrawlingHelper { private const int FunctionExecutionTimeout = 5000; private readonly IList<string> _textParts = new List<string>(); public IEnumerable<string> TextParts => _textParts; private IPage _page; private readonly StringBuilder _currentFragment = new StringBuilder(); public void SetPageContext(IPage page) { _page = page; } public bool CrawlFunctionParameters { get; set; } /// <summary> /// Crawls xhtml content and extracts text parts /// </summary> /// <param name="xhtml"></param> public bool CrawlXhtml(string xhtml) { try { var doc = XhtmlDocument.Parse(xhtml); CrawlXhtml(doc); CompleteTextFragment(); return true; } catch (Exception ex) { Log.LogError(nameof(XhtmlCrawlingHelper), ex); _currentFragment.Clear(); return false; } } private void CrawlXhtml(XhtmlDocument document) => ProcessNode(document.Body); private void AppendToCurrentTextFragment(string text) { _currentFragment.Append(text); } private void CompleteTextFragment() { if (_currentFragment.Length == 0) return; var str = _currentFragment.ToString(); if (!string.IsNullOrWhiteSpace(str)) { _textParts.Add(str); } _currentFragment.Clear(); } private void ProcessNode(XNode node) { if (node is XText textNode) { AppendToCurrentTextFragment(textNode.Value); return; } if (node is XElement element) { ProcessElement(element); } } private void ProcessElement(XElement element) { if (element.Name.Namespace == Namespaces.Function10 && element.Name.LocalName == "function") { ProcessFunctionCall(element); return; } if (element.Name.LocalName == "script" || element.Name.LocalName == "noscript" || element.Name.LocalName == "style") { return; } if (element.Name.LocalName == "a") { // TODO: process "href" attribute for page/data references } bool isInlineElement = XhtmlPrettifier.InlineElements.Contains( new XhtmlPrettifier.NamespaceName { Name = element.Name.LocalName, Namespace = "" }); bool isFragmentContinuation = element.Name.LocalName != "br" && (element.Name.LocalName == "body" || isInlineElement); if (!isFragmentContinuation) { CompleteTextFragment(); } foreach (var childNode in element.Nodes()) { ProcessNode(childNode); } if (!isFragmentContinuation) { CompleteTextFragment(); } } private void ProcessFunctionCall(XElement functionNode) { var functionName = functionNode.GetAttributeValue("name"); if(functionName == null) return; IFunction function; try { if (!FunctionFacade.TryGetFunction(out function, functionName)) { return; } } catch { return; } if (CrawlFunctionParameters) { foreach (var paramElement in functionNode.Elements()) { var parameterName = paramElement.GetAttributeValue("name"); if (parameterName == null) continue; var profile = function.ParameterProfiles.FirstOrDefault(p => p.Name == parameterName); if (profile != null) { if (profile.Type == typeof(XhtmlDocument) || profile.Type == typeof(Lazy<XhtmlDocument>)) { ProcessElement(paramElement); } // TODO: handle the other parameter types } } } var returnType = function.ReturnType; if (returnType == typeof(XhtmlDocument) || function.ReturnType == typeof(string)) { var functionResult = TryExecuteFunction(functionNode, FunctionExecutionTimeout); if (functionResult is XhtmlDocument document) { CrawlXhtml(document); } if (functionResult is string str) { if (str.TrimStart().StartsWith("<html")) { CrawlXhtml(str); } else { AppendToCurrentTextFragment(str); } } } } private object TryExecuteFunction(XElement functionNode, int timeoutMs) { object result = null; var cts = new CancellationTokenSource(); var executeTask = Task.Run(() => result = TryExecuteFunction(functionNode), cts.Token); executeTask.Wait(timeoutMs); if(executeTask.Status == TaskStatus.Running) { cts.Cancel(); }; return result; } private object TryExecuteFunction(XElement functionNode) { try { var tree = FunctionFacade.BuildTree(functionNode); using (new FakeHttpContext()) { if (_page != null) { PageRenderer.CurrentPage = _page; C1PageRoute.PageUrlData = new PageUrlData(_page); } PageRenderer.RenderingReason = RenderingReason.BuildSearchIndex; return tree.GetValue(new FunctionContextContainer { SuppressXhtmlExceptions = false }); } } catch (Exception) { return null; } } private class FakeHttpContext : IDisposable { private readonly HttpContext _originalContext; public FakeHttpContext() { _originalContext = HttpContext.Current; HttpContext.Current = new HttpContext( new HttpRequest("", "http://contoso.com", ""), new HttpResponse(new StringWriter()) ); } public void Dispose() { HttpContext.Current = _originalContext; #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// <exclude /> ~FakeHttpContext() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } } ================================================ FILE: Composite/Search/DocumentField.cs ================================================ namespace Composite.Search { /// <summary> /// Contains information about the facet. /// </summary> public class DocumentFieldFacet { /// <exclude /> public delegate string FacetValuePreviewDelegate(string value); /// <summary> /// Gets or sets the maximum number of choices to return. The default value is 0 which means - all. /// </summary> public int Limit { get; set; } /// <summary> /// Gets or sets the minimum about of hits a choice should have to be listed in the result. /// </summary> public int MinHitCount { get; set; } /// <summary> /// Gets or sets the facet type. /// </summary> public FacetType FacetType { get; set; } /// <summary> /// Gets or sets the facet type. /// </summary> public FacetSorting FacetSorting { get; set; } /// <summary> /// A function to get a label for a given facet value. /// </summary> public FacetValuePreviewDelegate PreviewFunction { get; set; } /// <summary> /// When <value>true</value>, information about not selected facet values should be returned when querying the facet. /// </summary> public bool ExpandSelection { get; set; } = true; //public int FieldOrder { get; set; } } /// <summary> /// Defines a type of a facet field. /// </summary> public enum FacetType { /// <summary> /// A signle facet value per data field value. /// </summary> SingleValue = 0, /// <summary> /// Allows multiple facet values per data field value. /// </summary> MultipleValues = 1 } /// <summary> /// Defines a type of a facet field. /// </summary> public enum FacetSorting { /// <summary> /// A the facets with the most hits will be shown first. /// </summary> HitCount = 0, /// <summary> /// The facets will be shown in lexicographical ascending order. /// </summary> Ascending = 1 } /// <summary> /// Defines a sorting methods for the search results /// </summary> public enum SortTermsAs { /// <summary> /// The values will be sorted alphabetically /// </summary> String = 0, /// <summary> /// The values will be sorted as integer values /// </summary> Int = 1, /// <summary> /// The values will be sorted as long values /// </summary> Long = 2, /// <summary> /// The values will be sorted as float values /// </summary> Float = 3, /// <summary> /// The values will be sorted as double values /// </summary> Double = 4 } /// <summary> /// Constains information how a data field is preserved and shown in search results. /// </summary> public sealed class DocumentFieldPreview { /// <exclude /> public delegate string ValuePreviewDelegate(object value); /// <summary> /// A function reference to preview the field value. /// </summary> public ValuePreviewDelegate PreviewFunction { get; set; } /// <summary> /// Indicates whether sorting for the given field should be enabled. /// </summary> public bool Sortable { get; set; } /// <summary> /// Defines a sorting method for the given values. /// </summary> public SortTermsAs SortTermsAs { get; set; } /// <summary> /// Indicates the order in which the field appears /// </summary> public int FieldOrder { get; set; } } /// <summary> /// Defines a custom field in a search document. /// </summary> public sealed class DocumentField { /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="facetInformation"></param> /// <param name="previewInformation"></param> public DocumentField( string name, DocumentFieldFacet facetInformation, DocumentFieldPreview previewInformation) { Name = name; Facet = facetInformation; Preview = previewInformation; Label = name; } /// <summary> /// The name of the field /// </summary> public string Name { get; } /// <summary> /// A function to get the field label in the given culture. ${,} /// </summary> public string Label { get; set; } /// <summary> /// Indicates whether faceted search is enabled for this field. /// </summary> public bool FacetedSearchEnabled => Facet != null; /// <summary> /// Indicates whether field value is preserved in the index to be shown in search results. /// </summary> public bool FieldValuePreserved => Preview != null; /// <summary> /// Faceted search information. /// </summary> public DocumentFieldFacet Facet { get; set; } /// <summary> /// Field preview information. /// </summary> public DocumentFieldPreview Preview { get; set; } } } ================================================ FILE: Composite/Search/DocumentSources/BuiltInTypesDocumentSourceProvider.cs ================================================ using System.Collections.Generic; namespace Composite.Search.DocumentSources { internal class BuiltInTypesDocumentSourceProvider: ISearchDocumentSourceProvider { private readonly ISearchDocumentSource[] _documentSources; public BuiltInTypesDocumentSourceProvider( CmsPageDocumentSource cmsPageDocumentSource, MediaLibraryDocumentSource mediaLibraryDocumentSource) { _documentSources = new ISearchDocumentSource[] { cmsPageDocumentSource, mediaLibraryDocumentSource }; } public IEnumerable<ISearchDocumentSource> GetDocumentSources() => _documentSources; } } ================================================ FILE: Composite/Search/DocumentSources/CmsPageDocumentSource.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Composite.C1Console.Security; using Composite.Search.Crawling; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.Routing; using Composite.Core.Routing.Foundation.PluginFacades; using Composite.Core.WebClient; using Composite.Data; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.Types; namespace Composite.Search.DocumentSources { public class CmsPageDocumentSource : ISearchDocumentSource { const string LogTitle = nameof(CmsPageDocumentSource); protected List<IDocumentSourceListener> _listeners = new List<IDocumentSourceListener>(); private readonly DataChangesIndexNotifier _changesIndexNotifier; protected Lazy<IReadOnlyCollection<DocumentField>> _customFields; protected IEnumerable<ISearchDocumentBuilderExtension> _docBuilderExtensions; protected CmsPageDocumentSource() { } public CmsPageDocumentSource(IEnumerable<ISearchDocumentBuilderExtension> extensions) { _customFields = new Lazy<IReadOnlyCollection<DocumentField>>(() => { var pageDocFields = DataTypeSearchReflectionHelper.GetDocumentFields(typeof (IPage)); var metaDataFields = PageMetaDataFacade.GetAllMetaDataTypes() .SelectMany(dataType => DataTypeSearchReflectionHelper.GetDocumentFields(dataType, false)); return pageDocFields .Concat(metaDataFields) .ExcludeDuplicateKeys(f => f.Name) .ToList(); }); _docBuilderExtensions = extensions; _changesIndexNotifier = new DataChangesIndexNotifier( _listeners, typeof(IPage), (data, culture) => { var page = (IPage) data; var entityToken = GetAdministratedEntityToken(page); return entityToken != null ? FromPage(page, entityToken, null) : null; }, data => GetDocumentId((IPage) data), PageShouldBeIndexed); _changesIndexNotifier.Start(); } public virtual string Name => typeof (IPage).FullName; public virtual void Subscribe(IDocumentSourceListener sourceListener) { _listeners.Add(sourceListener); } public virtual IEnumerable<DocumentWithContinuationToken> GetSearchDocuments(CultureInfo culture, string continuationToken = null) { ICollection<IPage> unpublishedPages; IDictionary<Guid, Guid> parentPageIDs; var (lastPageId, lastPagesPublicationScope) = ParseContinuationToken(continuationToken); using (var conn = new DataConnection(PublicationScope.Unpublished, culture)) { unpublishedPages = conn.Get<IPage>().Evaluate(); parentPageIDs = conn.Get<IPageStructure>().ToDictionary(ps => ps.Id, ps => ps.ParentId); } unpublishedPages = unpublishedPages .Where(p => p.Id.CompareTo(lastPageId) >= 0) .OrderBy(p => p.Id) .ToList(); var publishedPages = new Dictionary<Tuple<Guid, Guid>, IPage>(); HashSet<Guid> publishedPageIds; using (var conn = new DataConnection(PublicationScope.Published, culture)) { publishedPages = conn.Get<IPage>().ToDictionary(page => new Tuple<Guid, Guid>(page.Id, page.VersionId)); publishedPageIds = new HashSet<Guid>(publishedPages.Select(p => p.Key.Item1)); } var unpublishedMetaData = GetAllMetaData(PublicationScope.Unpublished, culture); var publishedMetaData = GetAllMetaData(PublicationScope.Published, culture); foreach (var unpublishedPage in unpublishedPages) { Guid pageId = unpublishedPage.Id; var entityToken = unpublishedPage.GetDataEntityToken(); if (pageId.CompareTo(lastPageId) > 0 && publishedPages.TryGetValue(new Tuple<Guid, Guid>(pageId, unpublishedPage.VersionId), out IPage publishedPage) && AllAncestorPagesArePublished(pageId, publishedPageIds, parentPageIDs)) { yield return new DocumentWithContinuationToken { Document = FromPage(publishedPage, entityToken, publishedMetaData), ContinuationToken = GetContinuationToken(publishedPage) }; if (unpublishedPage.PublicationStatus == GenericPublishProcessController.Published) { // If page is in "published" state, indexing only one version of it continue; } } if (pageId.CompareTo(lastPageId) > 0 || lastPagesPublicationScope == PublicationScope.Published) { yield return new DocumentWithContinuationToken { Document = FromPage(unpublishedPage, entityToken, unpublishedMetaData), ContinuationToken = GetContinuationToken(unpublishedPage) }; } } } private (Guid lastPage, PublicationScope publicationScope) ParseContinuationToken(string continuationToken) { if (continuationToken == null) { return (Guid.Empty, PublicationScope.Unpublished); } var values = continuationToken.Split(':'); return (Guid.Parse(values[0]), (PublicationScope) Enum.Parse(typeof(PublicationScope), values[1])); } private string GetContinuationToken(IPage page) => $"{page.Id}:{page.DataSourceId.PublicationScope}"; public IReadOnlyCollection<DocumentField> CustomFields => _customFields.Value; protected virtual SearchDocument FromPage(IPage page, EntityToken entityToken, Dictionary<Tuple<Guid, Guid>, List<IData>> allMetaData) { string label = page.MenuTitle; if (string.IsNullOrWhiteSpace(label)) { label = page.Title; } bool isPublished = page.DataSourceId.PublicationScope == PublicationScope.Published; string documentId = GetDocumentId(page); var docBuilder = new SearchDocumentBuilder(_docBuilderExtensions); docBuilder.SetDataType(typeof(IPage)); docBuilder.CrawlData(page); using (new DataConnection(page.DataSourceId.PublicationScope, page.DataSourceId.LocaleScope)) { if (isPublished) { docBuilder.Url = PageUrls.BuildUrl(page, UrlKind.Internal); } var placeholders = PageManager.GetPlaceholderContent(page.Id, page.VersionId); placeholders.ForEach(pl => docBuilder.CrawlData(pl, true)); List<IData> metaData; if (allMetaData != null) { allMetaData.TryGetValue(new Tuple<Guid, Guid>(page.Id, page.VersionId), out metaData); } else { metaData = GetMetaData(page.Id, page.VersionId, page.DataSourceId.PublicationScope, page.DataSourceId.LocaleScope); } try { metaData?.ForEach(pageMetaData => docBuilder.CrawlData(pageMetaData)); } catch (Exception ex) { Log.LogWarning(LogTitle, ex); } } if (!string.IsNullOrEmpty(page.UrlTitle) && !UrlFormattersPluginFacade.FormatUrl(page.Title, true).Equals(page.UrlTitle, StringComparison.OrdinalIgnoreCase) && !UrlFormattersPluginFacade.FormatUrl(page.Title, false).Equals(page.UrlTitle, StringComparison.OrdinalIgnoreCase)) { docBuilder.TextParts.Add(page.UrlTitle); } return docBuilder.BuildDocument(Name, documentId, label, null, entityToken); } private EntityToken GetAdministratedEntityToken(IPage page) { if (page.DataSourceId.PublicationScope == PublicationScope.Published) { return page.GetDataEntityToken(); } using (new DataScope(PublicationScope.Unpublished, page.DataSourceId.LocaleScope)) { var unpublishedPage = PageManager.GetPageById(page.Id, page.VersionId, true); return unpublishedPage?.GetDataEntityToken(); } } protected virtual string GetDocumentId(IPage page) { bool isUnpublished = page.DataSourceId.PublicationScope == PublicationScope.Unpublished; string versionId = ""; if (page.VersionId != Guid.Empty) { versionId = UrlUtils.CompressGuid(page.VersionId); } return $"{UrlUtils.CompressGuid(page.Id)}{versionId}" + (isUnpublished ? "u" : ""); } private Dictionary<Tuple<Guid, Guid>, List<IData>> GetAllMetaData(PublicationScope publicationScope, CultureInfo culture) { var result = new Dictionary<Tuple<Guid, Guid>, List<IData>>(); using (var conn = new DataConnection(publicationScope, culture)) { conn.DisableServices(); foreach (var metaDataType in PageMetaDataFacade.GetAllMetaDataTypes() .Where(type => typeof(IPageMetaData).IsAssignableFrom(type))) { foreach (var dataItem in DataFacade.GetData(metaDataType).OfType<IPageMetaData>()) { var key = new Tuple<Guid, Guid>(dataItem.PageId, dataItem.VersionId); var list = result.GetOrAdd(key, () => new List<IData>()); list.Add(dataItem); } } } return result; } private List<IData> GetMetaData(Guid pageId, Guid versionId, PublicationScope publicationScope, CultureInfo culture) { var result = new List<IData>(); using (var conn = new DataConnection(publicationScope, culture)) { conn.DisableServices(); foreach (var metaDataType in PageMetaDataFacade.GetAllMetaDataTypes() .Where(type => typeof(IPageMetaData).IsAssignableFrom(type))) { result.AddRange(DataFacade.GetData(metaDataType).OfType<IPageMetaData>() .Where(md => md.PageId == pageId && md.VersionId == versionId)); } } return result; } private bool AllAncestorPagesArePublished(Guid pageId, HashSet<Guid> publishedPageIds, IDictionary<Guid, Guid> parentPageIDs) { int depth = 100; while (depth > 0) { if (!parentPageIDs.TryGetValue(pageId, out Guid parentPageID)) { // The the page is unreachable from the tree, no need to index it return false; } if (parentPageID == Guid.Empty) { return true; } if (!publishedPageIds.Contains(parentPageID)) { return false; } pageId = parentPageID; depth--; } Log.LogError(nameof(CmsPageDocumentSource), $"There's a loop in page hierarchy. Page ID: '{pageId}'"); return false; } private bool AllAncestorPagesArePublished(Guid pageId, CultureInfo locale) { using (var dc = new DataConnection(PublicationScope.Published, locale)) { dc.DisableServices(); int depth = 100; while (depth > 0) { var parentPageId = PageManager.GetParentId(pageId); if (parentPageId == Guid.Empty) return true; var parentPage = PageManager.GetPageById(parentPageId, true); if (parentPage == null) { return false; } pageId = parentPageId; depth--; } } Log.LogError(nameof(CmsPageDocumentSource), $"There's a loop in page hierarchy. Page ID: '{pageId}'"); return false; } protected bool PageShouldBeIndexed(IData data) { if (!(data is IPage page)) { return true; } if (data.DataSourceId.PublicationScope == PublicationScope.Published) { return AllAncestorPagesArePublished(page.Id, page.DataSourceId.LocaleScope); } // Indexing the unpublished version fo the page only if the page is not in the "published" state, // or the published version isn't indexed return page.PublicationStatus != GenericPublishProcessController.Published || !AllAncestorPagesArePublished(page.Id, page.DataSourceId.LocaleScope); } } } ================================================ FILE: Composite/Search/DocumentSources/DataChangesIndexNotifier.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Composite.Core; using Composite.Core.Extensions; using Composite.Data; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; namespace Composite.Search.DocumentSources { internal class DataChangesIndexNotifier { const string LogTitle = nameof(DataChangesIndexNotifier); private readonly IEnumerable<IDocumentSourceListener> _listeners; private readonly Type _interfaceType; private Func<IData, CultureInfo, SearchDocument> GetDocument { get; } private Func<IData, string> GetDocumentId { get; } private Predicate<IData> DataItemShouldBeIndexed { get; } public DataChangesIndexNotifier( IEnumerable<IDocumentSourceListener> listeners, Type interfaceType, Func<IData, CultureInfo, SearchDocument> getDocumentFunc, Func<IData, string> getDocumentIdFunc, Predicate<IData> dataItemShouldBeIndexed = null) { _listeners = listeners; _interfaceType = interfaceType; GetDocument = getDocumentFunc; GetDocumentId = getDocumentIdFunc; DataItemShouldBeIndexed = dataItemShouldBeIndexed ?? (_ => !IsPublishedDataFromUnpublishedScope(_)); } public void Start() { DataEventSystemFacade.SubscribeToDataAfterAdd(_interfaceType, (sender, args) => CatchAll(() => GetActionContainer().Add(() => Data_OnAfterAdd(sender, args))), true); DataEventSystemFacade.SubscribeToDataAfterUpdate(_interfaceType, (sender, args) => CatchAll(() => GetActionContainer().Add(() => Data_OnAfterUpdate(sender, args))), true); DataEventSystemFacade.SubscribeToDataDeleted(_interfaceType, (sender, args) => CatchAll(() => GetActionContainer().Add(() => Data_OnDeleted(sender, args))), true); } private IndexUpdateActionContainer GetActionContainer() { var service = ServiceLocator.GetService<IndexUpdateActionContainer>(); return service ?? new IndexUpdateActionContainer(); } private IEnumerable<CultureInfo> GetCultures(IData data) { if (data is ILocalizedControlled) { return new[] { data.DataSourceId.LocaleScope }; } // If data is not localized, it should be indexed for every localization scope return DataLocalizationFacade.ActiveLocalizationCultures; } private bool IgnoreNotifications() => !_listeners.Any(); private void Data_OnAfterAdd(object sender, DataEventArgs dataEventArgs) { if (IgnoreNotifications()) return; try { var data = dataEventArgs.Data; if (!DataItemShouldBeIndexed(data)) { return; } foreach (var culture in GetCultures(data)) { var document = GetDocument(data, culture); if (document == null) continue; _listeners.ForEach(l => l.Create(culture, document)); } } catch (Exception ex) { Log.LogError(LogTitle, ex); } } private void Data_OnAfterUpdate(object sender, DataEventArgs dataEventArgs) { if (IgnoreNotifications()) return; try { var data = dataEventArgs.Data; bool toBeDeleted = !DataItemShouldBeIndexed(data); if (toBeDeleted) { DeleteDocuments(data); return; } foreach (var culture in GetCultures(data)) { var document = GetDocument(data, culture); if (document == null) continue; _listeners.ForEach(l => l.Update(culture, document)); } } catch (Exception ex) { Log.LogError(LogTitle, ex); } } private void Data_OnDeleted(object sender, DataEventArgs dataEventArgs) { if (IgnoreNotifications()) return; var data = dataEventArgs.Data; DeleteDocuments(data); } private void DeleteDocuments(IData data) { try { var documentId = GetDocumentId(data); foreach (var culture in GetCultures(data)) { _listeners.ForEach(l => l.Delete(culture, documentId)); } } catch (Exception ex) { Log.LogError(LogTitle, ex); } } private bool IsPublishedDataFromUnpublishedScope(IData data) { return typeof (IPublishControlled).IsAssignableFrom(_interfaceType) && data.DataSourceId.PublicationScope == PublicationScope.Unpublished && ((IPublishControlled)data).PublicationStatus == GenericPublishProcessController.Published; } private void CatchAll(Action action) { try { action(); } catch (Exception ex) { Log.LogError(nameof(DataChangesIndexNotifier), ex); } } } } ================================================ FILE: Composite/Search/DocumentSources/DataTypeDocumentSource.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Composite.C1Console.Security; using Composite.Search.Crawling; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.Routing; using Composite.Core.Types; using Composite.Core.WebClient; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; namespace Composite.Search.DocumentSources { internal class DataTypeDocumentSource : ISearchDocumentSource { const string LogTitle = nameof(DataTypeDocumentSource); private readonly List<IDocumentSourceListener> _listeners = new List<IDocumentSourceListener>(); private readonly Type _interfaceType; private readonly DataChangesIndexNotifier _changesIndexNotifier; private readonly Lazy<IReadOnlyCollection<DocumentField>> _customFields; private readonly bool _isPublishable; static DataTypeDocumentSource() { DynamicTypeManager.OnStoreCreated += OnStoreCreated; DynamicTypeManager.OnStoreDropped += OnStoreDropped; DynamicTypeManager.OnStoreUpdated += OnStoreUpdated; } public DataTypeDocumentSource(Type interfaceType) { _interfaceType = interfaceType; _isPublishable = typeof (IPublishControlled).IsAssignableFrom(_interfaceType); _customFields = new Lazy<IReadOnlyCollection<DocumentField>>(GetDocumentFields); _changesIndexNotifier = new DataChangesIndexNotifier( _listeners, _interfaceType, FromData, GetDocumentId); _changesIndexNotifier.Start(); } public string Name => _interfaceType.FullName; public void Subscribe(IDocumentSourceListener sourceListener) { _listeners.Add(sourceListener); } public IEnumerable<DocumentWithContinuationToken> GetSearchDocuments(CultureInfo culture, string continuationToken = null) { var (continueFromScope, continueFromKey) = ParseCToken(continuationToken); if (continueFromScope == PublicationScope.Published) { var documents = GetDocumentsFromScope(PublicationScope.Published, culture, continueFromKey); foreach (var doc in documents) { yield return doc; } } if (typeof (IPublishControlled).IsAssignableFrom(_interfaceType)) { var documents = GetDocumentsFromScope(PublicationScope.Unpublished, culture, continueFromScope == PublicationScope.Unpublished ? continueFromKey : null); foreach (var doc in documents) { yield return doc; } } } private IEnumerable<DocumentWithContinuationToken> GetDocumentsFromScope( PublicationScope publicationScope, CultureInfo culture, object continueFromKey) { using (new DataConnection(publicationScope, culture)) { var query = DataFacade.GetData(_interfaceType); query = FilterAndOrderByKey(query, continueFromKey); if (publicationScope == PublicationScope.Unpublished) { query = query .Cast<IPublishControlled>() .Where(data => data.PublicationStatus != GenericPublishProcessController.Published); } var dataSet = query.Cast<IData>().Evaluate(); foreach (var data in dataSet) { var document = FromData(data, culture); if (document == null) continue; yield return new DocumentWithContinuationToken { Document = document, ContinuationToken = GetContinuationToken(data, publicationScope) }; } } } private IQueryable FilterAndOrderByKey(IQueryable dataset, object continueFromKey) { var keyProperties = _interfaceType.GetKeyProperties(); if (keyProperties.Count > 1 || !keyProperties.All(property => typeof(IComparable).IsAssignableFrom(property.PropertyType))) { return dataset.Cast<IData>(); // Not supported } var keyProperty = keyProperties.Single(); dataset = dataset.OrderBy(_interfaceType, keyProperty.Name); if (continueFromKey != null) { dataset = dataset.Cast<IData>() .ToList() .Where(data => (keyProperty.GetValue(data) as IComparable).CompareTo(continueFromKey) > 0) .AsQueryable(); } return dataset; } private (PublicationScope continueFromScope, object continueFromKey) ParseCToken(string continuationToken) { if (continuationToken == null) { return (PublicationScope.Published, null); } int separator = continuationToken.IndexOf(':'); string keyStr = continuationToken.Substring(separator + 1); var keyPropertyType = _interfaceType.GetKeyProperties().Single().PropertyType; object key = ValueTypeConverter.Convert(keyStr, keyPropertyType); var scope = (PublicationScope) Enum.Parse(typeof(PublicationScope), continuationToken.Substring(0, separator)); return (scope, key); } private string GetContinuationToken(IData data, PublicationScope publicationScope) { if (_interfaceType.GetKeyProperties().Count > 1) return null; // Not supported var key = data.GetUniqueKey(); string keyStr = ValueTypeConverter.Convert<string>(key); return $"{publicationScope}:{keyStr}"; } public IReadOnlyCollection<DocumentField> CustomFields => _customFields.Value; private SearchDocument FromData(IData data, CultureInfo culture) { using (new DataScope(culture)) { string label = data.GetLabel(); if (string.IsNullOrEmpty(label)) { // Having a label is a requirement for a data item to be searchable return null; } var docBuilder = new SearchDocumentBuilder(); docBuilder.SetDataType(_interfaceType); string documentId = GetDocumentId(data); if (InternalUrls.DataTypeSupported(_interfaceType) && (!_isPublishable || data.DataSourceId.PublicationScope == PublicationScope.Published)) { docBuilder.Url = InternalUrls.TryBuildInternalUrl(data.ToDataReference()); } docBuilder.CrawlData(data); var entityToken = GetConsoleEntityToken(data); if (entityToken == null) { return null; } return docBuilder.BuildDocument(Name, documentId, label, null, entityToken); } } private EntityToken GetConsoleEntityToken(IData data) { if (!(data is IPublishControlled) || data.DataSourceId.DataScopeIdentifier == DataScopeIdentifier.Administrated) { return data.GetDataEntityToken(); } var administratedData = DataFacade.GetDataFromOtherScope(data, DataScopeIdentifier.Administrated).FirstOrDefault(); if (administratedData == null) { Log.LogWarning(LogTitle, $"The following data item exists in published scope, but doesn't exist in unpublished scope '{data.DataSourceId.Serialize()}'."); return null; } return administratedData.GetDataEntityToken(); } private string GetDocumentId(IData data) { var uniqueKey = data.GetUniqueKey(); if (uniqueKey is Guid) { uniqueKey = UrlUtils.CompressGuid((Guid)uniqueKey); } string scopeSuffix = _isPublishable && data.DataSourceId.PublicationScope == PublicationScope.Unpublished ? "u" : string.Empty; return uniqueKey + scopeSuffix; } List<DocumentField> GetDocumentFields() { return DataTypeSearchReflectionHelper.GetDocumentFields(_interfaceType).ToList(); } private static void OnStoreCreated(DataTypeDescriptor dataTypeDescriptor) { if (!dataTypeDescriptor.Searchable) return; var indexUpdater = ServiceLocator.GetService<ISearchIndexUpdater>(); if (dataTypeDescriptor.IsCodeGenerated) { indexUpdater?.StopProcessingUpdates(); } indexUpdater?.Populate(GetStoreName(dataTypeDescriptor)); } private static void OnStoreDropped(DataTypeDescriptor dataTypeDescriptor) { if (!dataTypeDescriptor.Searchable) return; var indexUpdater = ServiceLocator.GetService<ISearchIndexUpdater>(); if (dataTypeDescriptor.IsCodeGenerated) { indexUpdater?.StopProcessingUpdates(); } indexUpdater?.Remove(GetStoreName(dataTypeDescriptor)); } private static void OnStoreUpdated(UpdateDataTypeDescriptor updateDataTypeDescriptor) { OnStoreDropped(updateDataTypeDescriptor.OldDataTypeDescriptor); OnStoreCreated(updateDataTypeDescriptor.NewDataTypeDescriptor); } private static string GetStoreName(DataTypeDescriptor dtd) => dtd.GetFullInterfaceName(); } } ================================================ FILE: Composite/Search/DocumentSources/DataTypesDocumentSourceProvider.cs ================================================ using System.Collections.Generic; using System.Linq; using Composite.Data; namespace Composite.Search.DocumentSources { class DataTypesDocumentSourceProvider: ISearchDocumentSourceProvider { private List<ISearchDocumentSource> _documentSources; public IEnumerable<ISearchDocumentSource> GetDocumentSources() { if (_documentSources == null) { lock (this) { if (_documentSources == null) { _documentSources = GetDataTypeDocumentSources().ToList(); } } } return _documentSources; } private IEnumerable<ISearchDocumentSource> GetDataTypeDocumentSources() { return from dataType in DataFacade.GetAllInterfaces() where !typeof(IPageMetaData).IsAssignableFrom(dataType) let attributes = dataType.GetCustomAttributes(true) where attributes.Any(a => a is SearchableTypeAttribute) select new DataTypeDocumentSource(dataType); } } } ================================================ FILE: Composite/Search/DocumentSources/IndexUpdateActionContainer.cs ================================================ using System; using System.Collections.Generic; namespace Composite.Search.DocumentSources { internal class IndexUpdateActionContainer : IDisposable { private List<Action> _actions; public void Add(Action action) { if (_actions == null) _actions = new List<Action>(); _actions.Add(action); } public void Dispose() { if (_actions == null) return; foreach (var action in _actions) { action(); } #if LeakCheck GC.SuppressFinalize(this); #endif } #if LeakCheck private string stack = Environment.StackTrace; /// <exclude /> ~IndexUpdateActionContainer() { Composite.Core.Instrumentation.DisposableResourceTracer.RegisterFinalizerExecution(stack); } #endif } } ================================================ FILE: Composite/Search/DocumentSources/MediaLibraryDocumentSource.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Composite.Core; using Composite.Core.Linq; using Composite.Data; using Composite.Data.Types; using Composite.Search.Crawling; namespace Composite.Search.DocumentSources { internal class MediaLibraryDocumentSource : ISearchDocumentSource { private readonly List<IDocumentSourceListener> _listeners = new List<IDocumentSourceListener>(); private readonly Lazy<IReadOnlyCollection<DocumentField>> _customFields; private readonly DataChangesIndexNotifier _changesIndexNotifier; private readonly IEnumerable<ISearchDocumentBuilderExtension> _docBuilderExtensions; public MediaLibraryDocumentSource(IEnumerable<ISearchDocumentBuilderExtension> extensions) { _customFields = new Lazy<IReadOnlyCollection<DocumentField>>(() => DataTypeSearchReflectionHelper.GetDocumentFields(typeof(IMediaFile)).ToList()); _docBuilderExtensions = extensions; _changesIndexNotifier = new DataChangesIndexNotifier( _listeners, typeof(IMediaFile), (data, culture) => FromMediaFile((IMediaFile)data), data => ((IMediaFile)data).Id.ToString()); _changesIndexNotifier.Start(); } public string Name => typeof(IMediaFile).FullName; public IReadOnlyCollection<DocumentField> CustomFields => _customFields.Value; public void Subscribe(IDocumentSourceListener sourceListener) { _listeners.Add(sourceListener); } public IEnumerable<DocumentWithContinuationToken> GetSearchDocuments(CultureInfo culture, string continuationToken = null) { IEnumerable<IMediaFile> mediaFiles; Guid lastMediaFileId = continuationToken == null ? Guid.Empty : new Guid(continuationToken); using (var conn = new DataConnection()) { mediaFiles = conn.Get<IMediaFile>() .Where(m => m.Id.CompareTo(lastMediaFileId) > 0) .OrderBy(m => m.Id) .Evaluate(); } return mediaFiles.Select(m => new DocumentWithContinuationToken { Document = FromMediaFile(m), ContinuationToken = m.Id.ToString() }).Where(doc => doc.Document != null); } private SearchDocument FromMediaFile(IMediaFile mediaFile) { string label = mediaFile.Title; if (string.IsNullOrWhiteSpace(label)) { label = mediaFile.FileName; } if(string.IsNullOrEmpty(label)) { Log.LogWarning(nameof(MediaLibraryDocumentSource), $"A media file has neither FileName nor Label fields specified, Id: '{mediaFile.Id}', StoreId: '{mediaFile.StoreId}'."); return null; } var docBuilder = new SearchDocumentBuilder(_docBuilderExtensions); docBuilder.SetDataType(typeof(IMediaFile)); docBuilder.CrawlData(mediaFile); return docBuilder.BuildDocument(Name, mediaFile.Id.ToString(), label, null, mediaFile.GetDataEntityToken()); } } } ================================================ FILE: Composite/Search/IDocumentSourceListener.cs ================================================ using System.Globalization; namespace Composite.Search { /// <summary> /// Listener to the <see cref="Composite.Search.DocumentSources"/> changes. /// </summary> public interface IDocumentSourceListener { /// <summary> /// Creates a search document. /// </summary> /// <param name="cultureInfo"></param> /// <param name="document"></param> void Create(CultureInfo cultureInfo, SearchDocument document); /// <summary> /// Updates the given document in the search collection. /// </summary> /// <param name="cultureInfo">The culture.</param> /// <param name="document"></param> void Update(CultureInfo cultureInfo, SearchDocument document); /// <summary> /// Deletes a search document from collection. /// </summary> /// <param name="cultureInfo">The culture.</param> /// <param name="documentId">The id of the document to be deleted.</param> void Delete(CultureInfo cultureInfo, string documentId); /// <summary> /// Requests rebuilding all of the document for the specified source /// </summary> /// <param name="cultureInfo">The culture.</param> /// <param name="source">The document source name.</param> void Rebuild(CultureInfo cultureInfo, string source); } } ================================================ FILE: Composite/Search/ISearchDocumentSource.cs ================================================ using System.Collections.Generic; using System.Globalization; namespace Composite.Search { /// <summary> /// Represents a search document source (f.e. cms pages, media, etc.) /// </summary> public interface ISearchDocumentSource { /// <summary> /// The name of the document source. /// </summary> string Name { get; } /// <summary> /// Returns search documents along with continuation tokens, so the indexing can be /// can be continued after website restart. /// </summary> /// <param name="culture">The culture for which the documents should be build.</param> /// <param name="continuationToken">Continuation token - contains pointer to the last /// already indexed search documents, so the method will return all the following ones.</param> /// <returns></returns> IEnumerable<DocumentWithContinuationToken> GetSearchDocuments( CultureInfo culture, string continuationToken = null); /// <summary> /// Gets the custom fields. /// </summary> IReadOnlyCollection<DocumentField> CustomFields { get; } /// <summary> /// Subscribes the given search document sourceListener to the source. /// </summary> /// <param name="sourceListener"></param> void Subscribe(IDocumentSourceListener sourceListener); } /// <summary> /// Represents a tuple of a document and a continuation token /// </summary> public sealed class DocumentWithContinuationToken { /// <summary> /// The current document. /// </summary> public SearchDocument Document { get; set; } /// <summary> /// The continuation token for the document source. /// </summary> public string ContinuationToken { get; set; } } } ================================================ FILE: Composite/Search/ISearchDocumentSourceProvider.cs ================================================ using System.Collections.Generic; namespace Composite.Search { /// <summary> /// Provides an enumeration of <see cref="ISearchDocumentSource"/>. /// </summary> public interface ISearchDocumentSourceProvider { /// <summary> /// Provides an enumeration of <see cref="ISearchDocumentSource"/>. /// </summary> IEnumerable<ISearchDocumentSource> GetDocumentSources(); } } ================================================ FILE: Composite/Search/ISearchIndexUpdater.cs ================================================ using System.Globalization; namespace Composite.Search { /// <summary> /// An interface for updating a search index. /// </summary> public interface ISearchIndexUpdater { /// <summary> /// Rebuilds the index. /// </summary> void Rebuild(); /// <summary> /// Rebuilds search data for the given data source. /// </summary> /// <param name="searchDocumentSource"></param> void Populate(string searchDocumentSource); /// <summary> /// Removes search documents received from the given data source. /// </summary> /// <param name="searchDocumentSource"></param> void Remove(string searchDocumentSource); /// <summary> /// Creates a search document collection for the given culture. /// </summary> /// <param name="cultureInfo"></param> void CreateCollection(CultureInfo cultureInfo); /// <summary> /// Drops the document collection created for the given culture. /// </summary> /// <param name="cultureInfo"></param> void DropCollection(CultureInfo cultureInfo); /// <summary> /// Notifies the search updater that no updates should be processed until a website restart. /// </summary> void StopProcessingUpdates(); } } ================================================ FILE: Composite/Search/ISearchProvider.cs ================================================ using System.Threading.Tasks; namespace Composite.Search { /// <summary> /// A search provider. /// </summary> public interface ISearchProvider { /// <summary> /// Executes the given search query asynchronously. /// </summary> /// <param name="query">The search query.</param> /// <returns></returns> Task<SearchResult> SearchAsync(SearchQuery query); } } ================================================ FILE: Composite/Search/SearchDocument.cs ================================================ using System.Collections.Generic; using Composite.C1Console.Security; namespace Composite.Search { /// <summary> /// Represents a console document to be indexed and searched for. /// </summary> public sealed class SearchDocument { /// <summary> /// To be used for deserialization. /// </summary> public SearchDocument() { } /// <summary> /// Constructs a new search document. /// </summary> /// <param name="source">The data source name.</param> /// <param name="id">An id to update the document later on.</param> /// <param name="label">A text to be shown in search results.</param> /// <param name="serializedEntityToken">The serialized entity token, will be used to locate the found document in the /// console tree structure.</param> public SearchDocument(string source, string id, string label, string serializedEntityToken) { Verify.ArgumentNotNull(source, nameof(source)); Verify.ArgumentNotNull(id, nameof(id)); Verify.ArgumentNotNull(label, nameof(label)); Verify.ArgumentNotNull(serializedEntityToken, nameof(serializedEntityToken)); Source = source; Id = id; Label = label; SerializedEntityToken = serializedEntityToken; } /// <summary> /// Constructs a new search document. /// </summary> /// <param name="source">The data source name.</param> /// <param name="id">An id to update the document later on.</param> /// <param name="label">A text to be shown in search results.</param> /// <param name="entityToken">The entity token, will be used to locate the found document in the /// console tree structure.</param> public SearchDocument(string source, string id, string label, EntityToken entityToken) : this(source, id, label, "") { Verify.ArgumentNotNull(entityToken, nameof(entityToken)); SerializedEntityToken = EntityTokenSerializer.Serialize(entityToken, true); } /// <summary> /// A unique identifier for the document. /// </summary> public string Id { get; set; } /// <summary> /// Document source name. /// </summary> public string Source { get; set; } /// <summary> /// Element label, to be shown in search results as well as searched for. /// </summary> public string Label { get; set; } /// <summary> /// Element bundle name, to be shown in search results as well as searched for. /// </summary> public string ElementBundleName { get; set; } /// <summary> /// A serialized entity token of an console tree element that's related to the document /// </summary> public string SerializedEntityToken { get; set; } /// <summary> /// Url, to be shown in search results as well as searched for. /// </summary> public string Url { get; set; } /// <summary> /// Contains all the text string that should be indexed. /// </summary> public IEnumerable<string> FullText { get; set; } /// <summary> /// Field values that is preserved in the index and will appear in the search results. /// </summary> public IDictionary<string, object> FieldValues { get; set; } /// <summary> /// Field values that is preserved in the index and will be used in faceted search. /// </summary> public IDictionary<string, string[]> FacetFieldValues { get; set; } /// <summary> /// A factor by which a search document should be boosted index time. /// </summary> public float Boost { get; set; } = 1; } } ================================================ FILE: Composite/Search/SearchFacade.cs ================================================ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Composite.Search.DocumentSources; using Composite.Core; using Microsoft.Extensions.DependencyInjection; namespace Composite.Search { /// <summary> /// Console search functionality /// </summary> public static class SearchFacade { /// <summary> /// Gets the document sources /// </summary> public static IEnumerable<ISearchDocumentSource> DocumentSources => ServiceLocator.GetServices<ISearchDocumentSourceProvider>() .SelectMany(sp => sp.GetDocumentSources()); /// <summary> /// Gets or sets the search provider /// </summary> public static ISearchProvider SearchProvider => ServiceLocator.GetService<ISearchProvider>(); /// <summary> /// Indicates whether search functionality is enabled /// </summary> public static bool SearchEnabled => SearchProvider != null; /// <summary> /// Executes a search query /// </summary> /// <param name="query"></param> /// <returns></returns> public static async Task<SearchResult> SearchConsoleAsync( SearchQuery query) { if (!SearchEnabled) { return SearchResult.Empty; } return await SearchProvider.SearchAsync(query); } internal static void AddDefaultSearchDocumentSourceProviders(this IServiceCollection services) { services.AddSingleton<CmsPageDocumentSource>(); services.AddSingleton<MediaLibraryDocumentSource>(); services.Add(new ServiceDescriptor( typeof(ISearchDocumentSourceProvider), typeof(BuiltInTypesDocumentSourceProvider), ServiceLifetime.Singleton)); services.Add(new ServiceDescriptor( typeof(ISearchDocumentSourceProvider), typeof(DataTypesDocumentSourceProvider), ServiceLifetime.Singleton)); services.AddScoped<IndexUpdateActionContainer>(); } } } ================================================ FILE: Composite/Search/SearchQuery.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Composite.Search.Crawling; using Composite.C1Console.Security; using Composite.Core.Threading; using Composite.Data; using Composite.Data.Types; namespace Composite.Search { /// <summary> /// Defines how multiple selected values should be resolved (should all or them much the document or any) /// </summary> public enum SearchQuerySelectionOperation { /// <summary> /// The result documents should have at least one of the given values. /// </summary> Or = 0, /// <summary> /// The result documents should have all of the given values. /// </summary> And = 1 } /// <summary> /// Allows filtering search results by defining the needed facet values. /// </summary> public class SearchQuerySelection { /// <summary> /// The name of the field. /// </summary> public string FieldName { get; set; } /// <summary> /// The array of values that are required to appear in the search documents. /// </summary> public string[] Values { get; set; } /// <summary> /// Defines how multiple selected values should be resolved. /// </summary> public SearchQuerySelectionOperation Operation { get; set; } /// <summary> /// The array of field values, documents containing which, should not appear in the results. /// </summary> public string[] NotValues { get; set; } } /// <summary> /// Represents a sort option for the a search query. /// </summary> public class SearchQuerySortOption { /// <summary> /// Constructs a new instance of <see cref="SearchQuerySortOption"/>. /// </summary> /// <param name="fieldName"></param> /// <param name="reverseOrder"></param> /// <param name="sortTermsAs"></param> public SearchQuerySortOption(string fieldName, bool reverseOrder, SortTermsAs sortTermsAs = SortTermsAs.String) { FieldName = fieldName; ReverseOrder = reverseOrder; SortTermsAs = sortTermsAs; } /// <summary> /// A field name to sort results by /// </summary> public string FieldName { get; } /// <summary> /// Indicates whether the results should appear in an order reverse to the way it is kept in the index. /// </summary> public bool ReverseOrder { get; } /// <summary> /// Defines how the field values are interpreted during sorting of the search results. /// </summary> public SortTermsAs SortTermsAs { get; set; } } /// <summary> /// Search query hightlight settings. /// </summary> public sealed class SearchQueryHighlightSettings { /// <summary> /// When set to <value>true</value>, highlihts will be included in the search results. /// </summary> public bool Enabled { get; set; } /// <summary> /// Maximum amount of highlight fragments. /// </summary> public int FragmentsCount { get; set; } = 1; /// <summary> /// Maximum fragment size. The default is 100 characters. /// </summary> public int FragmentSize { get; set; } = 100; /// <summary> /// Maximum amount of the full text field characters to be analyzed when extracting fragments to highlight. /// The default value is 51200. /// </summary> public int MaxAnalyzedChars { get; set; } = 51200; } /// <summary> /// A search query. /// </summary> public sealed class SearchQuery { /// <summary> /// Constructs a search query. /// </summary> public SearchQuery(string query, CultureInfo cultureInfo) { Verify.ArgumentNotNullOrEmpty(query, nameof(query)); Verify.ArgumentNotNull(cultureInfo, nameof(cultureInfo)); Query = query; CultureInfo = cultureInfo; MaxDocumentsNumber = 100; } /// <summary> /// Filters search results by data types. /// </summary> /// <param name="dataTypes"></param> public void FilterByDataTypes(params Type[] dataTypes) { Verify.ArgumentNotNull(dataTypes, nameof(dataTypes)); Selection.Add(new SearchQuerySelection { FieldName = DocumentFieldNames.DataType, Operation = SearchQuerySelectionOperation.Or, Values = dataTypes.Select(type => type.GetImmutableTypeId().ToString()).ToArray() }); } /// <summary> /// Filters search results by page types. /// </summary> /// <param name="pageTypes"></param> public void FilterByPageTypes(params string[] pageTypes) { Verify.ArgumentNotNull(pageTypes, nameof(pageTypes)); Selection.Add(new SearchQuerySelection { FieldName = DocumentFieldNames.GetFieldName(typeof(IPage), nameof(IPage.PageTypeId)), Operation = SearchQuerySelectionOperation.Or, Values = pageTypes }); } /// <summary> /// Only documents that have the <see cref="SearchDocument.Url"/> property set should be returned. /// </summary> public void ShowOnlyDocumentsWithUrls() { Selection.Add(new SearchQuerySelection { FieldName = DocumentFieldNames.HasUrl, Values = new [] {"1"} }); } /// <summary> /// Filters the results, so only entity tokens that have at least one of the given entity tokens /// as an ancestor, will be returned. This enables searching for the child elements in the console /// and searching for data that belongs to a specific website on frontend. /// </summary> public void FilterByAncestors(params EntityToken[] entityTokens) { Selection.Add(new SearchQuerySelection { FieldName = DocumentFieldNames.Ancestors, Operation = SearchQuerySelectionOperation.Or, Values = entityTokens.Select(SearchDocumentBuilder.GetEntityTokenHash).ToArray() }); } /// <summary> /// Filtering search results to which the given user does not have read access permission. /// </summary> /// <param name="userName"></param> public void FilterByUser(string userName) { Verify.ArgumentNotNullOrEmpty(userName, nameof(userName)); var tokens = new List<string> {userName}; using (ThreadDataManager.EnsureInitialize()) { tokens.AddRange(UserGroupFacade.GetUserGroupIds(userName).Select(id => id.ToString())); } Selection.Add(new SearchQuerySelection { FieldName = DocumentFieldNames.ConsoleAccess, Operation = SearchQuerySelectionOperation.Or, Values = tokens.ToArray() }); } /// <summary> /// The query text /// </summary> public string Query { get; } /// <summary> /// The culture in which the search is performed /// </summary> public CultureInfo CultureInfo { get; } /// <summary> /// To be used for pagination - number for the first page from the result set to be returned. /// </summary> public int SearchResultOffset { get; set; } /// <summary> /// Maximum amount of documents returned. /// </summary> public int MaxDocumentsNumber { get; set; } /// <summary> /// Facets to be returned. /// </summary> public ICollection<KeyValuePair<string, DocumentFieldFacet>> Facets { get; set; } = new List<KeyValuePair<string, DocumentFieldFacet>>(); /// <summary> /// To be used to filter results by facet field values. /// </summary> public ICollection<SearchQuerySelection> Selection { get; set; } = new List<SearchQuerySelection>(); /// <summary> /// Sort options. /// </summary> public IEnumerable<SearchQuerySortOption> SortOptions { get; set; } /// <summary> /// Highlight settings. /// </summary> public SearchQueryHighlightSettings HighlightSettings { get; set; } = new SearchQueryHighlightSettings(); /// <summary> /// Gets or sets a flag indicating whether to set an explanation to the <see cref="SearchResultItem"/>. /// An explanation describes the score computation for document and query. /// </summary> public bool ShowExplanation { get; set; } /// <summary> /// Will indicate that the search results should return facet information for the given field. /// </summary> /// <param name="fieldName"></param> public void AddFieldFacet(string fieldName) { AddFieldFacet(fieldName, null, null); } /// <summary> /// Will indicate that the search results should return facet information for the given field. /// </summary> /// <param name="fieldName"></param> /// <param name="values">The array of values that are required to appear in the search documents.</param> /// <param name="notValues">The array of values that are required not to appear in the search documents.</param> public void AddFieldFacet(string fieldName, string[] values, string[] notValues) { Verify.ArgumentNotNullOrEmpty(fieldName, nameof(fieldName)); if (Facets.Any(f => f.Key == fieldName)) { return; } var field = SearchDocumentBuilder.GetDefaultDocumentFields() .FirstOrDefault(f => f.Name == fieldName); if (field == null) { field = SearchFacade.DocumentSources.SelectMany(f => f.CustomFields) .FirstOrDefault(f => f.Name == fieldName); Verify.IsNotNull(field, $"Failed to find a document field by name '{fieldName}'"); } Verify.IsNotNull(field.Facet, $"Faceted search is not enabled for the field '{fieldName}'"); Facets.Add(new KeyValuePair<string, DocumentFieldFacet>( fieldName, field.Facet)); if ((values != null && values.Length > 0) || (notValues != null && notValues.Length > 0)) { Selection.Add(new SearchQuerySelection { FieldName = fieldName, Values = values, NotValues = notValues, Operation = field.Facet.FacetType == FacetType.SingleValue ? SearchQuerySelectionOperation.Or : SearchQuerySelectionOperation.And }); } } } } ================================================ FILE: Composite/Search/SearchResult.cs ================================================ using System.Collections.Generic; using System.Linq; namespace Composite.Search { /// <summary> /// Information about a search facet. /// </summary> public class Facet { /// <summary> /// The field value. /// </summary> public string Value { get; set; } /// <summary> /// Amount of document found for the given value. /// </summary> public int HitCount { get; set; } } /// <summary> /// Represents a search result item, which consists of the document as well as highlighted matched terms. /// </summary> public sealed class SearchResultItem { /// <summary> /// Gets the underlying search document. /// </summary> public SearchDocument Document { get; set; } /// <summary> /// Returns the label of the documents with highlighted matched terms. /// </summary> public string LabelHtmlHighlight { get; set; } /// <summary> /// Returns text fragments of the full text field with highlighted matched terms. /// </summary> public string[] FullTextHtmlHighlights { get; set; } /// <summary> /// Gets or sets the score. /// </summary> public float Score { get; set; } /// <summary> /// Gets or sets the explanation summary. This will be set if the <see cref="P:SearchQuery.ShowExplanation" /> property is set to <value>true</value>. /// An explanation describes the score computation for document and query. /// </summary> public string ExplanationSummary { get; set; } } /// <summary> /// Search result. /// </summary> public sealed class SearchResult { /// <summary> /// Found documents. /// </summary> public IEnumerable<SearchResultItem> Items { get; set; } /// <summary> /// Total documents found. /// </summary> public int TotalHits { get; set; } /// <summary> /// Found facet values. /// </summary> public IDictionary<string, Facet[]> Facets { get; set; } /// <exclude /> public static SearchResult Empty => new SearchResult { Items = Enumerable.Empty<SearchResultItem>() }; } } ================================================ FILE: Composite/Verify.cs ================================================ using System; using System.Collections.Generic; using Composite.Core.Extensions; using JetBrains.Annotations; namespace Composite { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static class Verify { /// <summary> /// Asserts that argument value is not null /// </summary> /// <param name="value">The argument's value.</param> /// <param name="paramName">The parameter's name.</param> /// <exception cref="ArgumentNullException"></exception> [AssertionMethod] public static void ArgumentNotNull([AssertionConditionAttribute(AssertionConditionType.IS_NOT_NULL)] object value, string paramName) { if (value == null) { ThrowArgumentNullException(paramName); } } /// <summary> /// Asserts that argument value is not null or emptry /// </summary> /// <param name="value">The argument's value.</param> /// <param name="paramName">The parameter's name.</param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentException"></exception> [AssertionMethod] public static void ArgumentNotNullOrEmpty([AssertionConditionAttribute(AssertionConditionType.IS_NOT_NULL)] string value, string paramName) { if (string.IsNullOrEmpty(value)) { if (value == null) { ThrowArgumentNullException(paramName); } ThrowArgumentException("Value cannot be String.Empty", paramName); } } /// <summary> /// Checks a condition. /// </summary> /// <param name="condition">A condition to check.</param> /// <param name="paramName">Parameter name.</param> /// <param name="message">The message.</param> /// <exception cref="ArgumentException"></exception> [AssertionMethod] public static void ArgumentCondition([AssertionConditionAttribute(AssertionConditionType.IS_TRUE)] bool condition, string paramName, string message) { if (!condition) { ThrowArgumentException(message, paramName); } } /// <summary> /// If condition isn't true, throws an <see cref="InvalidOperationException"/> exception. /// </summary> /// <param name="condition"></param> /// <param name="message"></param> /// <exception cref="InvalidOperationException"></exception> [AssertionMethod] public static void IsTrue([AssertionConditionAttribute(AssertionConditionType.IS_TRUE)] bool condition, string message) { if (!condition) { ThrowInvalidOperationException(message); } } /// <summary> /// If condition is true, throws an <see cref="InvalidOperationException"/> exception. /// </summary> /// <param name="condition"></param> /// <param name="message"></param> /// <exception cref="InvalidOperationException"></exception> [AssertionMethod] public static void IsFalse([AssertionConditionAttribute(AssertionConditionType.IS_FALSE)] bool condition, string message) { if (condition) { ThrowInvalidOperationException(message); } } /// <summary> /// If condition isn't true, throws an <see cref="InvalidOperationException"/> exception. /// </summary> /// <param name="condition"></param> /// <param name="message"></param> /// <param name="formatArgs">Parameters for string.Format method.</param> /// <exception cref="InvalidOperationException"></exception> [AssertionMethod] [StringFormatMethod("message")] public static void That([AssertionConditionAttribute(AssertionConditionType.IS_TRUE)] bool condition, string message, params object[] formatArgs) { if (!condition) { ThrowInvalidOperationException(message, formatArgs); } } /// <summary> /// Checks that the value is null. /// </summary> /// <param name="value">The value.</param> /// <param name="message">The message to be an exception desctiption.</param> /// <exception cref="InvalidOperationException"></exception> [AssertionMethod] public static void IsNull([AssertionConditionAttribute(AssertionConditionType.IS_NULL)] object value, string message) { if (value != null) ThrowInvalidOperationException(message); } /// <summary> /// Checks that the value is not null. /// </summary> /// <param name="value">The value.</param> /// <param name="message">The message to be an exception desctiption.</param> /// <exception cref="InvalidOperationException"></exception> [AssertionMethod] public static void IsNotNull([AssertionConditionAttribute(AssertionConditionType.IS_NOT_NULL)] object value, [NotNull] string message) { if (value == null) ThrowInvalidOperationException(message); } /// <summary> /// Checks that the value is not null. /// </summary> /// <param name="value">The value.</param> /// <param name="message">The message to be an exception desctiption.</param> /// <param name="formattingArgs">Parameters for string.Format() method.</param> /// <exception cref="InvalidOperationException"></exception> [AssertionMethod] [StringFormatMethod("message")] public static void IsNotNull([AssertionConditionAttribute(AssertionConditionType.IS_NOT_NULL)] object value, string message, params object[] formattingArgs) { if (value == null) ThrowInvalidOperationException(message, formattingArgs); } #region Exception throwing /// <exception cref="InvalidOperationException"></exception> public static void ThrowInvalidOperationException(string message) { throw new InvalidOperationException(message); } private static void ThrowInvalidOperationException(string message, object[] formatArguments) { throw new InvalidOperationException(formatArguments.Length > 0 ? string.Format(message, formatArguments) : message); } /// <summary> /// Throws an "ThrowArgumentNullException" exception. /// </summary> /// <param name="parameterName">The parameter's name</param> /// <exception cref="ArgumentNullException"></exception> public static void ThrowArgumentNullException(string parameterName) { throw new ArgumentNullException(parameterName); } /// <summary> /// Throws an "ThrowArgumentNullException" exception. /// </summary> /// <param name="parameterName">The parameter's name</param> /// <param name="message">The message.</param> /// <exception cref="ArgumentNullException"></exception> public static void ThrowArgumentException(string message, string parameterName) { throw new ArgumentException(message, parameterName); } /// <exclude /> public static T ResultNotNull<T>(T value) where T : class { return ResultNotNull(value, "Result value should not be null"); } /// <exclude /> [StringFormatMethod("errorMessageOnNull")] public static T ResultNotNull<T>(T value, string errorMessageOnNull, params object[] formattingArgs) where T : class { if (value == null) ThrowInvalidOperationException(errorMessageOnNull.FormatWith(formattingArgs)); return value; } /// <exclude /> [AssertionMethod] public static string StringNotIsNullOrWhiteSpace([AssertionConditionAttribute(AssertionConditionType.IS_NOT_NULL)] string value) { return StringNotIsNullOrWhiteSpace(value, "Result string should not be null or empty"); } /// <exclude /> [AssertionMethod] [StringFormatMethod("errorMessageOnNull")] public static string StringNotIsNullOrWhiteSpace([AssertionConditionAttribute(AssertionConditionType.IS_NOT_NULL)] string value, string errorMessageOnNull, params object[] formattingArgs) { if (String.IsNullOrWhiteSpace(value)) ThrowInvalidOperationException(errorMessageOnNull.FormatWith(formattingArgs)); return value; } #endregion Exception throwing } } #region JetBrains Annotations namespace JetBrains.Annotations { /// <summary> /// Indicates that marked element should be localized or not. /// </summary> [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] internal sealed class LocalizationRequiredAttribute : Attribute { /// <summary> /// Initializes a new instance of the <see cref="LocalizationRequiredAttribute"/> class. /// </summary> /// <param name="required"><c>true</c> if a element should be localized; otherwise, <c>false</c>.</param> public LocalizationRequiredAttribute(bool required) { Required = required; } /// <summary> /// Gets a value indicating whether a element should be localized. /// <value><c>true</c> if a element should be localized; otherwise, <c>false</c>.</value> /// </summary> public bool Required { get; set; } /// <summary> /// Returns whether the value of the given object is equal to the current <see cref="LocalizationRequiredAttribute"/>. /// </summary> /// <param name="obj">The object to test the value equality of. </param> /// <returns> /// <c>true</c> if the value of the given object is equal to that of the current; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { var attribute = obj as LocalizationRequiredAttribute; return attribute != null && attribute.Required == Required; } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A hash code for the current <see cref="LocalizationRequiredAttribute"/>.</returns> public override int GetHashCode() { return base.GetHashCode(); } } /// <summary> /// Indicates that marked method builds string by format pattern and (optional) arguments. /// Parameter, which contains format string, should be given in constructor. /// The format string should be in <see cref="string.Format(IFormatProvider,string,object[])"/> -like form /// </summary> [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] internal sealed class StringFormatMethodAttribute : Attribute { private readonly string myFormatParameterName; /// <summary> /// Initializes new instance of StringFormatMethodAttribute /// </summary> /// <param name="formatParameterName">Specifies which parameter of an annotated method should be treated as format-string</param> public StringFormatMethodAttribute(string formatParameterName) { myFormatParameterName = formatParameterName; } /// <summary> /// Gets format parameter name /// </summary> public string FormatParameterName { get { return myFormatParameterName; } } } /// <summary> /// Indicates that the function argument should be string literal and match one of the parameters of the caller function. /// For example, <see cref="ArgumentNullException"/> has such parameter. /// </summary> [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] internal sealed class InvokerParameterNameAttribute : Attribute { } /// <summary> /// Indicates that the marked method is assertion method, i.e. it halts control flow if one of the conditions is satisfied. /// To set the condition, mark one of the parameters with <see cref="AssertionConditionAttribute"/> attribute /// </summary> /// <seealso cref="AssertionConditionAttribute"/> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] internal sealed class AssertionMethodAttribute : Attribute { } /// <summary> /// Indicates the condition parameter of the assertion method. /// The method itself should be marked by <see cref="AssertionMethodAttribute"/> attribute. /// The mandatory argument of the attribute is the assertion type. /// </summary> /// <seealso cref="AssertionConditionType"/> [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] internal sealed class AssertionConditionAttribute : Attribute { private readonly AssertionConditionType myConditionType; /// <summary> /// Initializes new instance of AssertionConditionAttribute /// </summary> /// <param name="conditionType">Specifies condition type</param> public AssertionConditionAttribute(AssertionConditionType conditionType) { myConditionType = conditionType; } /// <summary> /// Gets condition type /// </summary> public AssertionConditionType ConditionType { get { return myConditionType; } } } /// <summary> /// Specifies assertion type. If the assertion method argument satisifes the condition, then the execution continues. /// Otherwise, execution is assumed to be halted /// </summary> internal enum AssertionConditionType { /// <summary> /// Indicates that the marked parameter should be evaluated to true /// </summary> IS_TRUE = 0, /// <summary> /// Indicates that the marked parameter should be evaluated to false /// </summary> IS_FALSE = 1, /// <summary> /// Indicates that the marked parameter should be evaluated to null value /// </summary> IS_NULL = 2, /// <summary> /// Indicates that the marked parameter should be evaluated to not null value /// </summary> IS_NOT_NULL = 3, } /// <summary> /// Indicates that the marked method unconditionally terminates control flow execution. /// For example, it could unconditionally throw exception /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] internal sealed class TerminatesProgramAttribute : Attribute { } /// <summary> /// Indicates that the value of marked element could be <c>null</c> sometimes, so the check for <c>null</c> is necessary before its usage /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] internal sealed class CanBeNullAttribute : Attribute { } /// <summary> /// Indicates that the value of marked element could never be <c>null</c> /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] internal sealed class NotNullAttribute : Attribute { } /// <summary> /// Indicates that the value of marked type (or its derivatives) cannot be compared using '==' or '!=' operators. /// There is only exception to compare with <c>null</c>, it is permitted /// </summary> [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = true)] internal sealed class CannotApplyEqualityOperatorAttribute : Attribute { } /// <summary> /// When applied to target attribute, specifies a requirement for any type which is marked with /// target attribute to implement or inherit specific type or types /// </summary> /// <example> /// <code> /// [BaseTypeRequired(typeof(IComponent)] // Specify requirement /// public class ComponentAttribute : Attribute /// {} /// /// [Component] // ComponentAttribute requires implementing IComponent interface /// public class MyComponent : IComponent /// {} /// </code> /// </example> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] [BaseTypeRequired(typeof(Attribute))] internal sealed class BaseTypeRequiredAttribute : Attribute { private readonly Type[] myBaseTypes; /// <summary> /// Initializes new instance of BaseTypeRequiredAttribute /// </summary> /// <param name="baseType">Specifies which types are required</param> public BaseTypeRequiredAttribute(Type baseType) { myBaseTypes = new[] { baseType }; } /// <summary> /// Gets enumerations of specified base types /// </summary> public IEnumerable<Type> BaseTypes { get { return myBaseTypes; } } } /// <summary> /// Indicates that the marked symbol is used implicitly (e.g. via reflection, in external library), /// so this symbol will not be marked as unused (as well as by other usage inspections) /// </summary> [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] internal sealed class UsedImplicitlyAttribute : Attribute { [UsedImplicitly] public UsedImplicitlyAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } [UsedImplicitly] public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } [UsedImplicitly] public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } [UsedImplicitly] public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } [UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; } /// <summary> /// Gets value indicating what is meant to be used /// </summary> [UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; } } /// <summary> /// Should be used on attributes and causes ReSharper to not mark symbols marked with such attributes as unused (as well as by other usage inspections) /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] internal sealed class MeansImplicitUseAttribute : Attribute { [UsedImplicitly] public MeansImplicitUseAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } [UsedImplicitly] public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } [UsedImplicitly] public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } [UsedImplicitly] public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } [UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; } /// <summary> /// Gets value indicating what is meant to be used /// </summary> [UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; } } [Flags] internal enum ImplicitUseKindFlags { Default = Access | Assign | InstantiatedWithFixedConstructorSignature, /// <summary> /// Only entity marked with attribute considered used /// </summary> Access = 1, /// <summary> /// Indicates implicit assignment to a member /// </summary> Assign = 2, /// <summary> /// Indicates implicit instantiation of a type with fixed constructor signature. /// That means any unused constructor parameters won't be reported as such. /// </summary> InstantiatedWithFixedConstructorSignature = 4, /// <summary> /// Indicates implicit instantiation of a type /// </summary> InstantiatedNoFixedConstructorSignature = 8, } /// <summary> /// Specify what is considered used implicitly when marked with <see cref="MeansImplicitUseAttribute"/> or <see cref="UsedImplicitlyAttribute"/> /// </summary> [Flags] internal enum ImplicitUseTargetFlags { Default = Itself, Itself = 1, /// <summary> /// Members of entity marked with attribute are considered used /// </summary> Members = 2, /// <summary> /// Entity marked with attribute and all its members considered used /// </summary> WithMembers = Itself | Members } /// <summary> /// This attribute is intended to mark publicly available API which should not be removed and so is treated as used. /// </summary> [MeansImplicitUse] internal sealed class PublicAPIAttribute : Attribute { public PublicAPIAttribute() { } // ReSharper disable UnusedParameter.Local public PublicAPIAttribute(string comment) // ReSharper restore UnusedParameter.Local { } } /// <summary> /// Tells code analysis engine if the parameter is completely handled when the invoked method is on stack. /// If the parameter is delegate, indicates that delegate is executed while the method is executed. /// If the parameter is enumerable, indicates that it is enumerated while the method is executed. /// </summary> [AttributeUsage(AttributeTargets.Parameter, Inherited = true)] internal sealed class InstantHandleAttribute : Attribute { } /// <summary> /// Indicates that method doesn't contain observable side effects. /// The same as <see cref="System.Diagnostics.Contracts.PureAttribute"/> /// </summary> [AttributeUsage(AttributeTargets.Method, Inherited = true)] internal sealed class PureAttribute : Attribute { } } namespace JetBrains.Annotations { [System.AttributeUsage(System.AttributeTargets.Parameter)] internal class PathReferenceAttribute : System.Attribute { public PathReferenceAttribute() { } public PathReferenceAttribute([PathReference] string basePath) { BasePath = basePath; } public string BasePath { get; private set; } } } namespace JetBrains.Annotations { [System.AttributeUsage(System.AttributeTargets.Parameter)] internal sealed class AspMvcModelTypeAttribute : System.Attribute { } } namespace JetBrains.Annotations { [System.AttributeUsage(System.AttributeTargets.Parameter | System.AttributeTargets.Method)] internal sealed class AspMvcControllerAttribute : System.Attribute { public string AnonymousProperty { get; private set; } public AspMvcControllerAttribute() { } public AspMvcControllerAttribute(string anonymousProperty) { AnonymousProperty = anonymousProperty; } } } namespace JetBrains.Annotations { [System.AttributeUsage(System.AttributeTargets.Parameter)] internal sealed class AspMvcMasterAttribute : System.Attribute { } } namespace JetBrains.Annotations { [System.AttributeUsage(System.AttributeTargets.Parameter | System.AttributeTargets.Method)] internal sealed class AspMvcViewAttribute : PathReferenceAttribute { } } namespace JetBrains.Annotations { [System.AttributeUsage(System.AttributeTargets.Parameter)] internal sealed class AspMvcAreaAttribute : PathReferenceAttribute { public string AnonymousProperty { get; private set; } public AspMvcAreaAttribute() { } public AspMvcAreaAttribute(string anonymousProperty) { AnonymousProperty = anonymousProperty; } } } namespace JetBrains.Annotations { [System.AttributeUsage(System.AttributeTargets.Parameter | System.AttributeTargets.Method)] internal sealed class AspMvcActionAttribute : System.Attribute { public string AnonymousProperty { get; private set; } public AspMvcActionAttribute() { } public AspMvcActionAttribute(string anonymousProperty) { AnonymousProperty = anonymousProperty; } } } namespace JetBrains.Annotations { [System.AttributeUsage(System.AttributeTargets.Parameter)] internal sealed class AspMvcTemplateAttribute : System.Attribute { } } #endregion JetBrains Annotations ================================================ FILE: Composite/packages.config ================================================ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="Castle.Core" version="4.2.1" targetFramework="net471" /> <package id="Microsoft.AspNet.Razor" version="3.2.3" targetFramework="net45" /> <package id="Microsoft.AspNet.WebPages" version="3.2.3" targetFramework="net45" /> <package id="Microsoft.Extensions.DependencyInjection" version="1.1.0" targetFramework="net461" /> <package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="1.1.0" targetFramework="net461" /> <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" /> <package id="Newtonsoft.Json" version="6.0.5" targetFramework="net461" /> <package id="System.Collections.Immutable" version="1.3.1" targetFramework="net461" /> <package id="System.Reactive" version="3.0.0" targetFramework="net461" /> <package id="System.Reactive.Core" version="3.0.0" targetFramework="net461" /> <package id="System.Reactive.Interfaces" version="3.0.0" targetFramework="net461" /> <package id="System.Reactive.Linq" version="3.0.0" targetFramework="net461" /> <package id="System.Reactive.PlatformServices" version="3.0.0" targetFramework="net461" /> <package id="System.Reactive.Windows.Threading" version="3.0.0" targetFramework="net461" /> <package id="System.Threading.Tasks.Dataflow" version="4.7.0" targetFramework="net471" /> <package id="System.ValueTuple" version="4.4.0" targetFramework="net471" /> <package id="WampSharp" version="18.3.1" targetFramework="net471" /> <package id="WampSharp.AspNet.WebSockets.Server" version="18.3.1" targetFramework="net471" /> <package id="WampSharp.NewtonsoftJson" version="18.3.1" targetFramework="net471" /> <package id="WampSharp.WebSockets" version="18.3.1" targetFramework="net471" /> </packages> ================================================ FILE: Composite.Workflows/C1Console/Actions/Workflows/EntityTokenLockedWorkflow.cs ================================================ using System; using Composite.C1Console.Security; using Composite.C1Console.Workflow; namespace Composite.C1Console.Actions.Workflows { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EntityTokenLockedWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EntityTokenLockedWorkflow() { InitializeComponent(); } private void initializeCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { EntityTokenLockedEntityToken entityToken = (EntityTokenLockedEntityToken)this.EntityToken; this.Bindings.Add("LockedByUsername", entityToken.LockedByUsername); this.Bindings.Add("IsSameUser", entityToken.LockedByUsername == UserValidationFacade.GetUsername()); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { EntityTokenLockedEntityToken entityToken = (EntityTokenLockedEntityToken)this.EntityToken; ActionLockingFacade.RemoveLock(entityToken.LockedEntityToken); this.CloseCurrentView(); this.ExecuteAction(entityToken.LockedEntityToken, entityToken.LockedActionToken); } } } ================================================ FILE: Composite.Workflows/C1Console/Actions/Workflows/EntityTokenLockedWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Actions.Workflows { partial class EntityTokenLockedWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.dataDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // dataDialogFormActivity1 // this.dataDialogFormActivity1.ContainerLabel = null; this.dataDialogFormActivity1.FormDefinitionFileName = "\\Administrative\\EntityTokenLockedStep1.xml"; this.dataDialogFormActivity1.Name = "dataDialogFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // initializeCodeActivity_Initialize // this.initializeCodeActivity_Initialize.Name = "initializeCodeActivity_Initialize"; this.initializeCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_Initialize_ExecuteCode); // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity5); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity3); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity4); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.dataDialogFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_Initialize); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // EntityTokenLockedWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "EntityTokenLockedWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private CodeActivity initializeCodeActivity_Initialize; private StateInitializationActivity step1StateInitializationActivity; private StateActivity step1StateActivity; private Composite.C1Console.Workflow.Activities.DataDialogFormActivity dataDialogFormActivity1; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private CodeActivity finalizeCodeActivity_Finalize; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity2; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateActivity finalizeStateActivity; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Actions/Workflows/EntityTokenLockedWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="EntityTokenLockedWorkflow" Location="30; 30" Size="1176; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="EntityTokenLockedWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="EntityTokenLockedWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="413" Y="179" /> <ns0:Point X="413" Y="435" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="511" Y="500" /> <ns0:Point X="713" Y="500" /> <ns0:Point X="713" Y="617" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="515" Y="524" /> <ns0:Point X="1058" Y="524" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="812" Y="658" /> <ns0:Point X="1058" Y="658" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity_Initialize" Location="108; 231" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="108; 291" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="step1StateActivity" Location="308; 435" Size="211; 102" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="316; 466"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="dataDialogFormActivity1" Location="326; 528" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Finish" Location="316; 490"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="326; 552" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="326; 612" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="316; 514"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="326; 576" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="326; 636" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="611; 617" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="finalizeStateInitializationActivity" Location="619; 648"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity_Finalize" Location="629; 710" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="629; 770" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="629; 830" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Actions/Workflows/FlowInformationScavengerWorkflow.cs ================================================ using System; using System.Web.Hosting; using Composite.Core.Extensions; using System.Workflow.Activities; using Composite.Core.Configuration; namespace Composite.C1Console.Actions.Workflows { public sealed partial class FlowInformationScavengerWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public FlowInformationScavengerWorkflow() { InitializeComponent(); } private void OnInitializeTimeout(object sender, EventArgs e) { (sender as DelayActivity).TimeoutDuration = GlobalSettingsFacade.WorkflowTimeout; } private void scavengeCodeActivity_ExecuteCode(object sender, EventArgs e) { if(HostingEnvironment.ApplicationHost.ShutdownInitiated()) { return; } try { FlowControllerFacade.Scavenge(); } catch { // Ignore exceptions } } } } ================================================ FILE: Composite.Workflows/C1Console/Actions/Workflows/FlowInformationScavengerWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Actions.Workflows { partial class FlowInformationScavengerWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.delayActivity1 = new System.Workflow.Activities.DelayActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.scavengeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.waitEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.waitStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.scavengeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.waitStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.scavengeStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "scavengeStateActivity"; // // delayActivity1 // this.delayActivity1.Name = "delayActivity1"; this.delayActivity1.TimeoutDuration = System.TimeSpan.Parse("00:00:00"); this.delayActivity1.InitializeTimeoutDuration += new System.EventHandler(this.OnInitializeTimeout); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "waitStateActivity"; // // scavengeCodeActivity // this.scavengeCodeActivity.Name = "scavengeCodeActivity"; this.scavengeCodeActivity.ExecuteCode += new System.EventHandler(this.scavengeCodeActivity_ExecuteCode); // // waitEventDrivenActivity // this.waitEventDrivenActivity.Activities.Add(this.delayActivity1); this.waitEventDrivenActivity.Activities.Add(this.setStateActivity1); this.waitEventDrivenActivity.Name = "waitEventDrivenActivity"; // // waitStateInitializationActivity // this.waitStateInitializationActivity.Name = "waitStateInitializationActivity"; // // scavengeStateInitializationActivity // this.scavengeStateInitializationActivity.Activities.Add(this.scavengeCodeActivity); this.scavengeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.scavengeStateInitializationActivity.Name = "scavengeStateInitializationActivity"; // // waitStateActivity // this.waitStateActivity.Activities.Add(this.waitStateInitializationActivity); this.waitStateActivity.Activities.Add(this.waitEventDrivenActivity); this.waitStateActivity.Name = "waitStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // scavengeStateActivity // this.scavengeStateActivity.Activities.Add(this.scavengeStateInitializationActivity); this.scavengeStateActivity.Name = "scavengeStateActivity"; // // FlowInformationScavengerWorkflow // this.Activities.Add(this.scavengeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.waitStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "scavengeStateActivity"; this.Name = "FlowInformationScavengerWorkflow"; this.CanModifyActivities = false; } #endregion private StateInitializationActivity scavengeStateInitializationActivity; private DelayActivity delayActivity1; private EventDrivenActivity waitEventDrivenActivity; private StateInitializationActivity waitStateInitializationActivity; private StateActivity waitStateActivity; private StateActivity finalStateActivity; private SetStateActivity setStateActivity1; private CodeActivity scavengeCodeActivity; private SetStateActivity setStateActivity2; private StateActivity scavengeStateActivity; } } ================================================ FILE: Composite.Workflows/C1Console/Actions/Workflows/FlowInformationScavengerWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="FlowInformationScavengerWorkflow" Location="30; 30" Size="1182; 996" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="waitStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="scavengeStateActivity" SourceConnectionEdge="Right" TargetActivity="waitStateActivity" SourceActivity="scavengeStateActivity" EventHandlerName="scavengeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="678" Y="419" /> <ns0:Point X="694" Y="419" /> <ns0:Point X="694" Y="132" /> <ns0:Point X="318" Y="132" /> <ns0:Point X="318" Y="140" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="scavengeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="waitStateActivity" SourceConnectionEdge="Right" TargetActivity="scavengeStateActivity" SourceActivity="waitStateActivity" EventHandlerName="waitEventDrivenActivity"> <StateDesignerConnector.Segments> <ns0:Point X="384" Y="205" /> <ns0:Point X="573" Y="205" /> <ns0:Point X="573" Y="378" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="scavengeStateActivity" Location="465; 378" Size="217; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="scavengeStateInitializationActivity" Location="473; 409"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="scavengeCodeActivity" Location="483; 471" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="483; 531" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="waitStateActivity" Location="223; 140" Size="191; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 109" Name="waitStateInitializationActivity" Location="538; 135" /> <EventDrivenDesigner Size="150; 182" Name="waitEventDrivenActivity" Location="546; 148"> <EventDrivenDesigner.Designers> <DelayDesigner Size="130; 41" Name="delayActivity1" Location="556; 210" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="556; 270" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Actions/Workflows/SecurityViolationWorkflow.cs ================================================ using System; using System.Linq; namespace Composite.C1Console.Actions.Workflows { public sealed partial class SecurityViolationWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public SecurityViolationWorkflow() { InitializeComponent(); } } } ================================================ FILE: Composite.Workflows/C1Console/Actions/Workflows/SecurityViolationWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Actions.Workflows { partial class SecurityViolationWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.dataDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // dataDialogFormActivity1 // this.dataDialogFormActivity1.ContainerLabel = null; this.dataDialogFormActivity1.FormDefinitionFileName = "\\Administrative\\SecurityViolationStep1.xml"; this.dataDialogFormActivity1.Name = "dataDialogFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity3); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.dataDialogFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // SecurityViolationWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "SecurityViolationWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private StateActivity step1StateActivity; private StateInitializationActivity finalizeStateInitializationActivity; private StateInitializationActivity step1StateInitializationActivity; private StateActivity finalizeStateActivity; private Composite.C1Console.Workflow.Activities.DataDialogFormActivity dataDialogFormActivity1; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private EventDrivenActivity step1EventDrivenActivity_Finish; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Actions/Workflows/SecurityViolationWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="SecurityViolationWorkflow" Location="30; 30" Size="1176; 974" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="SecurityViolationWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="SecurityViolationWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="437" Y="179" /> <ns0:Point X="437" Y="363" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="537" Y="428" /> <ns0:Point X="717" Y="428" /> <ns0:Point X="717" Y="518" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="816" Y="559" /> <ns0:Point X="1058" Y="559" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="108; 231" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="step1StateActivity" Location="334; 363" Size="207; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="342; 394"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="dataDialogFormActivity1" Location="352; 456" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Finish" Location="342; 418"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="352; 480" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="352; 540" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="615; 518" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="finalizeStateInitializationActivity" Location="623; 549"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="633; 611" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/AddAssociatedDataWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Scheduling; using Composite.C1Console.Security; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.C1Console.Workflow.Activities; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { /// <summary> /// This is used when adding data to a page folder /// </summary> [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddAssociatedDataWorkflow : FormsWorkflow { [NonSerialized] private bool _doPublish; private static class BindingNames { public const string PageId = nameof(PageId); } public AddAssociatedDataWorkflow() { InitializeComponent(); } private void IsDataTypeDescriptorNullTest(object sender, ConditionalEventArgs e) { e.Result = !BindingExist("DataTypeDescriptor"); } private void initialCodeActivity_ExecuteCode(object sender, EventArgs e) { var entityToken = EntityToken as AssociatedDataElementProviderHelperEntityToken; if (!string.IsNullOrEmpty(entityToken?.Payload)) { var type = TypeManager.GetType(entityToken.Payload); var id = type.GetImmutableTypeId(); var dataTypeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(id); UpdateBinding("DataTypeDescriptor", dataTypeDescriptor); UpdateBinding(BindingNames.PageId, new Guid(entityToken.Id)); if (!PermissionsFacade.GetPermissionsForCurrentUser(EntityToken).Contains(PermissionType.Publish) || !typeof(IPublishControlled).IsAssignableFrom(type)) { var formData = WorkflowFacade.GetFormData(InstanceId, true); if (formData.ExcludedEvents == null) formData.ExcludedEvents = new List<string>(); formData.ExcludedEvents.Add("SaveAndPublish"); } } } private void selectTypeCodeActivity_ExecuteCode(object sender, EventArgs e) { var types = PageFolderFacade.GetAllFolderTypes().ToList(); Bindings.Add("Types", types); Bindings.Add("SelectedType", types[0]); } private void selectTypeCodeActivity_Next_ExecuteCode(object sender, EventArgs e) { var type = GetBinding<Type>("SelectedType"); var dataEntityToken = (DataEntityToken)EntityToken; var parentInterfaceType = dataEntityToken.Data.DataSourceId.InterfaceType; var id = parentInterfaceType.GetKeyProperties()[0].GetValue(dataEntityToken.Data, null); var idString = ValueTypeConverter.Convert<string>(id); var entityToken = new AssociatedDataElementProviderHelperEntityToken( TypeManager.SerializeType(parentInterfaceType), EntityToken.Source, idString, TypeManager.SerializeType(type) ); ExecuteWorklow(entityToken, typeof(AddAssociatedDataWorkflow)); var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(type.GetImmutableTypeId()); UpdateBinding("DataTypeDescriptor", dataTypeDescriptor); } private void enterDataCodeActivity_ExecuteCode(object sender, EventArgs e) { var dataTypeDescriptor = GetBinding<DataTypeDescriptor>("DataTypeDescriptor"); var type = TypeManager.GetType(dataTypeDescriptor.TypeManagerTypeName); Guid pageId = GetBinding<Guid>(BindingNames.PageId); var helper = new DataTypeDescriptorFormsHelper(dataTypeDescriptor, true, EntityToken) { LayoutIconHandle = "associated-data-add" }; var generatedTypesHelper = new GeneratedTypesHelper(dataTypeDescriptor); helper.AddReadOnlyFields(generatedTypesHelper.NotEditableDataFieldDescriptorNames); IData newData; if (!BindingExist("NewData")) { newData = DataFacade.BuildNew(type); PageFolderFacade.AssignFolderDataSpecificValues(newData, pageId); var publishControlled = newData as IPublishControlled; if (publishControlled != null) { publishControlled.PublicationStatus = GenericPublishProcessController.Draft; } var localizedData = newData as ILocalizedControlled; if (localizedData != null) { var cultureInfo = UserSettings.ActiveLocaleCultureInfo ?? DataLocalizationFacade.DefaultLocalizationCulture; localizedData.SourceCultureName = cultureInfo.Name; } Bindings.Add("NewData", newData); helper.UpdateWithNewBindings(Bindings); helper.ObjectToBindings(newData, Bindings); } else { newData = GetBinding<IData>("NewData"); } DeliverFormData( type.Name, StandardUiContainerTypes.Document, helper.GetForm(), Bindings, helper.GetBindingsValidationRules(newData) ); } private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { var dataTypeDescriptor = GetBinding<DataTypeDescriptor>("DataTypeDescriptor"); var newData = GetBinding<IData>("NewData"); var helper = new DataTypeDescriptorFormsHelper(dataTypeDescriptor, true, newData.GetDataEntityToken()); var generatedTypesHelper = new GeneratedTypesHelper(dataTypeDescriptor); helper.AddReadOnlyFields(generatedTypesHelper.NotEditableDataFieldDescriptorNames); var isValid = ValidateBindings(); if (!BindAndValidate(helper, newData)) { isValid = false; } var justAdded = false; if (isValid) { var published = false; if (!BindingExist("DataAdded")) { var dataScopeIdentifier = DataScopeIdentifier.Public; if (dataTypeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled))) { dataScopeIdentifier = DataScopeIdentifier.Administrated; } using (new DataScope(dataScopeIdentifier)) { newData = DataFacade.AddNew(newData); justAdded = true; } PublishControlledHelper.PublishIfNeeded(newData, _doPublish, Bindings, ShowMessage); AcquireLock(newData.GetDataEntityToken()); UpdateBinding("NewData", newData); Bindings.Add("DataAdded", true); } else { var publishedControlled = newData as IPublishControlled; if (publishedControlled != null) { var refreshedData = (IPublishControlled)DataFacade.GetDataFromDataSourceId(newData.DataSourceId); if (refreshedData != null && refreshedData.PublicationStatus == GenericPublishProcessController.Published) { refreshedData.PublicationStatus = GenericPublishProcessController.Draft; DataFacade.Update(refreshedData); } } DataFacade.Update(newData); published = PublishControlledHelper.PublishIfNeeded(newData, _doPublish, Bindings, ShowMessage); EntityTokenCacheFacade.ClearCache(newData.GetDataEntityToken()); } if (!published) { var specificTreeRefresher = CreateParentTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(EntityToken); } if (justAdded) { SetSaveStatus(true, newData); } else { SetSaveStatus(true); } } else { SetSaveStatus(false); } } private void enablePublishCodeActivity_ExecuteCode(object sender, EventArgs e) { _doPublish = true; } } } ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/AddAssociatedDataWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { partial class AddAssociatedDataWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.selectTypeCodeActivity_Next = new System.Workflow.Activities.CodeActivity(); this.nextHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.selectTypeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.enablePublishCodeActivity = new System.Workflow.Activities.CodeActivity(); this.saveAndPublishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveAndPublishHandleExternalEventActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.enterDataCodeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElseActivity2 = new System.Workflow.Activities.IfElseActivity(); this.initialCodeActivity = new System.Workflow.Activities.CodeActivity(); this.selectTypeEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.selectTypeEventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.selectTypeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.enterDataEventDrivenActivity_SaveAndPublish = new System.Workflow.Activities.EventDrivenActivity(); this.enterDataEventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.enterDataStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.selectTypeStateActivity = new System.Workflow.Activities.StateActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.enterDataStateActivity = new System.Workflow.Activities.StateActivity(); this.initialStateActivity = new System.Workflow.Activities.StateActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "enterDataStateActivity"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "selectTypeStateActivity"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity2); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.setStateActivity7); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsDataTypeDescriptorNullTest); this.ifElseBranchActivity3.Condition = codecondition1; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // selectTypeCodeActivity_Next // this.selectTypeCodeActivity_Next.Name = "selectTypeCodeActivity_Next"; this.selectTypeCodeActivity_Next.ExecuteCode += new System.EventHandler(this.selectTypeCodeActivity_Next_ExecuteCode); // // nextHandleExternalEventActivity1 // this.nextHandleExternalEventActivity1.EventName = "Next"; this.nextHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity1.Name = "nextHandleExternalEventActivity1"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = null; this.wizzardFormActivity1.FormDefinitionFileName = "/Administrative/AddAssociatedDataWorkflowTypeSelection.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // selectTypeCodeActivity // this.selectTypeCodeActivity.Name = "selectTypeCodeActivity"; this.selectTypeCodeActivity.ExecuteCode += new System.EventHandler(this.selectTypeCodeActivity_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "enterDataStateActivity"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "saveStateActivity"; // // enablePublishCodeActivity // this.enablePublishCodeActivity.Name = "enablePublishCodeActivity"; this.enablePublishCodeActivity.ExecuteCode += new System.EventHandler(this.enablePublishCodeActivity_ExecuteCode); // // saveAndPublishHandleExternalEventActivity1 // this.saveAndPublishHandleExternalEventActivity1.EventName = "SaveAndPublish"; this.saveAndPublishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveAndPublishHandleExternalEventActivity1.Name = "saveAndPublishHandleExternalEventActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "saveStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // enterDataCodeActivity // this.enterDataCodeActivity.Name = "enterDataCodeActivity"; this.enterDataCodeActivity.ExecuteCode += new System.EventHandler(this.enterDataCodeActivity_ExecuteCode); // // ifElseActivity2 // this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity4); this.ifElseActivity2.Name = "ifElseActivity2"; // // initialCodeActivity // this.initialCodeActivity.Name = "initialCodeActivity"; this.initialCodeActivity.ExecuteCode += new System.EventHandler(this.initialCodeActivity_ExecuteCode); // // selectTypeEventDrivenActivity_Cancel // this.selectTypeEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.selectTypeEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity8); this.selectTypeEventDrivenActivity_Cancel.Name = "selectTypeEventDrivenActivity_Cancel"; // // selectTypeEventDrivenActivity_Next // this.selectTypeEventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity1); this.selectTypeEventDrivenActivity_Next.Activities.Add(this.selectTypeCodeActivity_Next); this.selectTypeEventDrivenActivity_Next.Activities.Add(this.closeCurrentViewActivity1); this.selectTypeEventDrivenActivity_Next.Activities.Add(this.setStateActivity6); this.selectTypeEventDrivenActivity_Next.Name = "selectTypeEventDrivenActivity_Next"; // // selectTypeStateInitializationActivity // this.selectTypeStateInitializationActivity.Activities.Add(this.selectTypeCodeActivity); this.selectTypeStateInitializationActivity.Activities.Add(this.wizzardFormActivity1); this.selectTypeStateInitializationActivity.Name = "selectTypeStateInitializationActivity"; // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.finalizeCodeActivity); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity5); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // enterDataEventDrivenActivity_SaveAndPublish // this.enterDataEventDrivenActivity_SaveAndPublish.Activities.Add(this.saveAndPublishHandleExternalEventActivity1); this.enterDataEventDrivenActivity_SaveAndPublish.Activities.Add(this.enablePublishCodeActivity); this.enterDataEventDrivenActivity_SaveAndPublish.Activities.Add(this.setStateActivity3); this.enterDataEventDrivenActivity_SaveAndPublish.Name = "enterDataEventDrivenActivity_SaveAndPublish"; // // enterDataEventDrivenActivity_Save // this.enterDataEventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.enterDataEventDrivenActivity_Save.Activities.Add(this.setStateActivity4); this.enterDataEventDrivenActivity_Save.Name = "enterDataEventDrivenActivity_Save"; // // enterDataStateInitializationActivity // this.enterDataStateInitializationActivity.Activities.Add(this.enterDataCodeActivity); this.enterDataStateInitializationActivity.Name = "enterDataStateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.initialCodeActivity); this.initialStateInitializationActivity.Activities.Add(this.ifElseActivity2); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // selectTypeStateActivity // this.selectTypeStateActivity.Activities.Add(this.selectTypeStateInitializationActivity); this.selectTypeStateActivity.Activities.Add(this.selectTypeEventDrivenActivity_Next); this.selectTypeStateActivity.Activities.Add(this.selectTypeEventDrivenActivity_Cancel); this.selectTypeStateActivity.Name = "selectTypeStateActivity"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.saveStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // enterDataStateActivity // this.enterDataStateActivity.Activities.Add(this.enterDataStateInitializationActivity); this.enterDataStateActivity.Activities.Add(this.enterDataEventDrivenActivity_Save); this.enterDataStateActivity.Activities.Add(this.enterDataEventDrivenActivity_SaveAndPublish); this.enterDataStateActivity.Name = "enterDataStateActivity"; // // initialStateActivity // this.initialStateActivity.Activities.Add(this.initialStateInitializationActivity); this.initialStateActivity.Name = "initialStateActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity1); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // AddAssociatedDataWorkflow // this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelEventDrivenActivity); this.Activities.Add(this.initialStateActivity); this.Activities.Add(this.enterDataStateActivity); this.Activities.Add(this.saveStateActivity); this.Activities.Add(this.selectTypeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialStateActivity"; this.Name = "AddAssociatedDataWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity8; private Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity selectTypeEventDrivenActivity_Cancel; private CodeActivity selectTypeCodeActivity_Next; private SetStateActivity setStateActivity7; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElseActivity2; private Workflow.Activities.WizardFormActivity wizzardFormActivity1; private CodeActivity selectTypeCodeActivity; private SetStateActivity setStateActivity6; private Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity1; private EventDrivenActivity selectTypeEventDrivenActivity_Next; private StateInitializationActivity selectTypeStateInitializationActivity; private StateActivity selectTypeStateActivity; private SetStateActivity setStateActivity5; private EventDrivenActivity enterDataEventDrivenActivity_Save; private CodeActivity finalizeCodeActivity; private SetStateActivity setStateActivity1; private Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity cancelEventDrivenActivity; private CodeActivity enterDataCodeActivity; private SetStateActivity setStateActivity2; private StateInitializationActivity saveStateInitializationActivity; private StateInitializationActivity enterDataStateInitializationActivity; private StateInitializationActivity initialStateInitializationActivity; private StateActivity saveStateActivity; private StateActivity enterDataStateActivity; private StateActivity initialStateActivity; private CodeActivity initialCodeActivity; private SetStateActivity setStateActivity4; private Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity3; private CodeActivity enablePublishCodeActivity; private Workflow.Activities.SaveAndPublishHandleExternalEventActivity saveAndPublishHandleExternalEventActivity1; private EventDrivenActivity enterDataEventDrivenActivity_SaveAndPublish; private StateActivity finalStateActivity; } } ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/AddAssociatedDataWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1199; 932" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="AddAssociatedDataWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="827; 665" Name="finalStateActivity" /> <EventDrivenDesigner Name="cancelEventDrivenActivity" Size="150; 209" Location="38; 63"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 44" Location="48; 128" /> <SetStateDesigner Name="setStateActivity1" Size="130; 62" Location="48; 191" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="212; 80" AutoSizeMargin="16; 24" Location="65; 141" Name="initialStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initialStateInitializationActivity" Size="381; 396" Location="73; 174"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initialCodeActivity" Size="130; 44" Location="198; 239" /> <IfElseDesigner Name="ifElseActivity2" Size="361; 249" Location="83; 302"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity3" Size="150; 146" Location="102; 376"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity7" Size="130; 62" Location="112; 441" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity4" Size="150; 146" Location="275; 376"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity2" Size="130; 62" Location="285; 441" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="299; 110" AutoSizeMargin="16; 24" AutoSize="False" Location="206; 296" Name="enterDataStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="enterDataStateInitializationActivity" Size="150; 128" Location="546; 141"> <StateInitializationDesigner.Designers> <CodeDesigner Name="enterDataCodeActivity" Size="130; 44" Location="556; 206" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="enterDataEventDrivenActivity_Save" Size="150; 209" Location="546; 167"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130; 44" Location="556; 232" /> <SetStateDesigner Name="setStateActivity4" Size="130; 62" Location="556; 295" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="enterDataEventDrivenActivity_SaveAndPublish" Size="150; 272" Location="554; 154"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveAndPublishHandleExternalEventActivity1" Size="130; 44" Location="564; 219" /> <CodeDesigner Name="enablePublishCodeActivity" Size="130; 44" Location="564; 282" /> <SetStateDesigner Name="setStateActivity3" Size="130; 62" Location="564; 345" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="206; 80" AutoSizeMargin="16; 24" Location="607; 306" Name="saveStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="saveStateInitializationActivity" Size="150; 209" Location="615; 339"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity" Size="130; 44" Location="625; 404" /> <SetStateDesigner Name="setStateActivity5" Size="130; 62" Location="625; 467" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="252; 118" AutoSizeMargin="16; 24" Location="58; 499" Name="selectTypeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="selectTypeStateInitializationActivity" Size="150; 191" Location="66; 532"> <StateInitializationDesigner.Designers> <CodeDesigner Name="selectTypeCodeActivity" Size="130; 44" Location="76; 597" /> <ActivityDesigner Name="wizzardFormActivity1" Size="130; 44" Location="76; 660" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="selectTypeEventDrivenActivity_Next" Size="150; 335" Location="66; 558"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="nextHandleExternalEventActivity1" Size="130; 44" Location="76; 623" /> <CodeDesigner Name="selectTypeCodeActivity_Next" Size="130; 44" Location="76; 686" /> <ActivityDesigner Name="closeCurrentViewActivity1" Size="130; 44" Location="76; 749" /> <SetStateDesigner Name="setStateActivity6" Size="130; 62" Location="76; 812" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="selectTypeEventDrivenActivity_Cancel" Size="150; 209" Location="66; 584"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 44" Location="76; 649" /> <SetStateDesigner Name="setStateActivity8" Size="130; 62" Location="76; 712" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="AddAssociatedDataWorkflow" TargetConnectionIndex="0" SourceStateName="AddAssociatedDataWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="cancelEventDrivenActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="214" Y="74" /> <ns0:Point X="907" Y="74" /> <ns0:Point X="907" Y="665" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="selectTypeStateActivity" SetStateName="setStateActivity7" SourceActivity="initialStateActivity" TargetConnectionIndex="0" SourceStateName="initialStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initialStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="selectTypeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="273" Y="185" /> <ns0:Point X="512" Y="185" /> <ns0:Point X="512" Y="487" /> <ns0:Point X="184" Y="487" /> <ns0:Point X="184" Y="499" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="enterDataStateActivity" SetStateName="setStateActivity2" SourceActivity="initialStateActivity" TargetConnectionIndex="0" SourceStateName="initialStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initialStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="enterDataStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="273" Y="185" /> <ns0:Point X="355" Y="185" /> <ns0:Point X="355" Y="296" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" SetStateName="setStateActivity4" SourceActivity="enterDataStateActivity" TargetConnectionIndex="0" SourceStateName="enterDataStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="enterDataEventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="440" Y="366" /> <ns0:Point X="517" Y="366" /> <ns0:Point X="517" Y="298" /> <ns0:Point X="710" Y="298" /> <ns0:Point X="710" Y="306" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="enterDataStateActivity" SetStateName="setStateActivity5" SourceActivity="saveStateActivity" TargetConnectionIndex="0" SourceStateName="saveStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="saveStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="enterDataStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="809" Y="350" /> <ns0:Point X="819" Y="350" /> <ns0:Point X="819" Y="288" /> <ns0:Point X="355" Y="288" /> <ns0:Point X="355" Y="296" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity6" SourceActivity="selectTypeStateActivity" TargetConnectionIndex="0" SourceStateName="selectTypeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="selectTypeEventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="569" /> <ns0:Point X="907" Y="569" /> <ns0:Point X="907" Y="665" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity8" SourceActivity="selectTypeStateActivity" TargetConnectionIndex="0" SourceStateName="selectTypeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="selectTypeEventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="306" Y="595" /> <ns0:Point X="907" Y="595" /> <ns0:Point X="907" Y="665" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" SetStateName="setStateActivity3" SourceActivity="enterDataStateActivity" TargetConnectionIndex="0" SourceStateName="enterDataStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="enterDataEventDrivenActivity_SaveAndPublish" SourceConnectionIndex="2" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="501" Y="392" /> <ns0:Point X="517" Y="392" /> <ns0:Point X="517" Y="298" /> <ns0:Point X="710" Y="298" /> <ns0:Point X="710" Y="306" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/AddDataFolderExWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Events; using Composite.Core; using Composite.Data; using Composite.Core.Types; using Composite.C1Console.Workflow; using Composite.C1Console.Actions; using Composite.Data.GeneratedTypes; using Composite.Data.DynamicTypes; using Composite.C1Console.Users; using Composite.Data.Validation.ClientValidationRules; using Composite.Data.Types; using Composite.Plugins.Elements.ElementProviders.PageElementProvider; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] [Obsolete("To be removed")] public sealed partial class AddDataFolderExWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { private string TypesBindingName { get { return "Types"; } } private string SelectedTypeBindingName { get { return "SelectedType"; } } private string NewTypeNameBindingName { get { return "NewTypeName"; } } private string NewTypeNamespaceBindingName { get { return "NewTypeNamespace"; } } private string NewTypeTitleBindingName { get { return "NewTypeTitle"; } } private string DataFieldDescriptorsBindingName { get { return "DataFieldDescriptors"; } } private string LabelFieldNameBindingName { get { return "LabelFieldName"; } } private string HasRecycleBinBindingName { get { return "HasRecycleBin"; } } private string HasPublishingBindingName { get { return "HasPublishing"; } } private string HasLocalizationBindingName { get { return "HasLocalization"; } } private static readonly object _lock = new object(); public AddDataFolderExWorkflow() { InitializeComponent(); } private void ShouldCreateNewType(object sender, ConditionalEventArgs e) { e.Result = this.ExtraPayload == "CreateNew"; } private void UnunsedTypesExist(object sender, ConditionalEventArgs e) { Type associatedType = TypeManager.GetType(this.Payload); IEnumerable<Type> associationTypes = PageFolderFacade.GetAllFolderTypes(); IEnumerable<Type> usedAssociationTypes = PageFolderFacade.GetDefinedFolderTypes(this.GetDataItemFromEntityToken<IPage>()); e.Result = associationTypes.Except(usedAssociationTypes).Any(); } private void UseExistingType(object sender, ConditionalEventArgs e) { Type type = this.GetBinding<Type>(this.SelectedTypeBindingName); e.Result = type != typeof(AddDataFolderExWorkflow); } private void IsTypeCreated(object sender, ConditionalEventArgs e) { e.Result = this.BindingExist(this.SelectedTypeBindingName); } private void selectTypeCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { Type associatedType = TypeManager.GetType(this.Payload); IEnumerable<Type> associationTypes = PageFolderFacade.GetAllFolderTypes(); IEnumerable<Type> usedAccociationTypes = PageFolderFacade.GetDefinedFolderTypes(this.GetDataItemFromEntityToken<IPage>()); var types = new Dictionary<Type, string>(); foreach (var kvp in associationTypes.Except(usedAccociationTypes).ToDictionary(f => f, f => f.GetTypeTitle())) { types.Add(kvp.Key, kvp.Value); } this.Bindings.Add(this.TypesBindingName, types); this.Bindings.Add(this.SelectedTypeBindingName, types.Keys.First()); } private void selectTypeCodeActivity_StartCreateNewTypeWorkflow_ExecuteCode(object sender, EventArgs e) { this.CloseCurrentView(); this.ExecuteAction(this.EntityToken, new WorkflowActionToken(typeof(AddDataFolderExWorkflow), this.ActionToken.PermissionTypes) { Payload = this.Payload, ExtraPayload = "CreateNew", DoIgnoreEntityTokenLocking = this.ActionToken.IgnoreEntityTokenLocking }); } private void createNewTypeCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { if (!this.BindingExist(this.NewTypeNameBindingName)) { this.Bindings.Add(this.NewTypeNameBindingName, ""); this.Bindings.Add(this.NewTypeNamespaceBindingName, UserSettings.LastSpecifiedNamespace); this.Bindings.Add(this.NewTypeTitleBindingName, ""); this.Bindings.Add(this.DataFieldDescriptorsBindingName, new List<DataFieldDescriptor>()); this.Bindings.Add(this.LabelFieldNameBindingName, ""); this.Bindings.Add(this.HasRecycleBinBindingName, false); this.Bindings.Add(this.HasPublishingBindingName, false); this.Bindings.Add(this.HasLocalizationBindingName, false); this.BindingsValidationRules.Add(this.NewTypeNameBindingName, new List<ClientValidationRule> { new NotNullClientValidationRule() }); this.BindingsValidationRules.Add(this.NewTypeNamespaceBindingName, new List<ClientValidationRule> { new NotNullClientValidationRule() }); this.BindingsValidationRules.Add(this.NewTypeTitleBindingName, new List<ClientValidationRule> { new NotNullClientValidationRule() }); } //if (RuntimeInformation.IsDebugBuild) //{ // DynamicTempTypeCreator dynamicTempTypeCreator = new DynamicTempTypeCreator("IAggTest"); // this.UpdateBinding(this.NewTypeNameBindingName, dynamicTempTypeCreator.TypeName); // this.UpdateBinding(this.NewTypeTitleBindingName, dynamicTempTypeCreator.TypeTitle); // this.UpdateBinding(this.DataFieldDescriptorsBindingName, dynamicTempTypeCreator.DataFieldDescriptors); //} } private void saceNewTypeCodeActivity_Save_ExecuteCode(object sender, EventArgs e) { bool saveResult = false; try { string typeName = this.GetBinding<string>(this.NewTypeNameBindingName); string typeNamespace = this.GetBinding<string>(this.NewTypeNamespaceBindingName); string typeTitle = this.GetBinding<string>(this.NewTypeTitleBindingName); bool hasRecycleBin = this.GetBinding<bool>(this.HasRecycleBinBindingName); bool hasPublishing = this.GetBinding<bool>(this.HasPublishingBindingName); bool hasLocalization = this.GetBinding<bool>(this.HasLocalizationBindingName); string labelFieldName = this.GetBinding<string>(this.LabelFieldNameBindingName); var dataFieldDescriptors = this.GetBinding<List<DataFieldDescriptor>>(this.DataFieldDescriptorsBindingName); var helper = new GeneratedTypesHelper(); helper = new GeneratedTypesHelper(); string errorMessage; if (!helper.ValidateNewTypeName(typeName, out errorMessage)) { this.ShowFieldMessage("NewTypeName", errorMessage); SetSaveStatus(false); return; } if (!helper.ValidateNewTypeNamespace(typeNamespace, out errorMessage)) { this.ShowFieldMessage("NewTypeNamespace", errorMessage); SetSaveStatus(false); return; } if (!helper.ValidateNewTypeFullName(typeName, typeNamespace, out errorMessage)) { this.ShowFieldMessage("NewTypeName", errorMessage); SetSaveStatus(false); return; } if (!helper.ValidateNewFieldDescriptors(dataFieldDescriptors, null, out errorMessage)) { this.ShowMessage( DialogType.Warning, "${Composite.Management, AssociatedDataElementProviderHelper.AddDataFolderExCreateNewType.ErrorTitle}", errorMessage ); SetSaveStatus(false); return; } if (helper.IsEditProcessControlledAllowed) { helper.SetPublishControlled(hasPublishing); helper.SetLocalizedControlled(hasLocalization); } helper.SetNewTypeFullName(typeName, typeNamespace); helper.SetNewTypeTitle(typeTitle); // TODO: fix and check where the workflow is actually used helper.SetNewFieldDescriptors(dataFieldDescriptors, null, labelFieldName); Type targetType = TypeManager.GetType(this.Payload); helper.SetForeignKeyReference(targetType, Composite.Data.DataAssociationType.Aggregation); helper.CreateType(false); this.UpdateBinding(this.SelectedTypeBindingName, helper.InterfaceType); UserSettings.LastSpecifiedNamespace = typeNamespace; saveResult = true; } catch (Exception ex) { Log.LogCritical("AddNewAggregationTypeWorkflow", ex); this.ShowMessage(DialogType.Error, ex.Message, ex.Message); } SetSaveStatus(saveResult); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { var dataEntityToken = (DataEntityToken)this.EntityToken; Type type = this.GetBinding<Type>(SelectedTypeBindingName); IPage page = (IPage)dataEntityToken.Data; Guid dataTypeId = type.GetImmutableTypeId(); lock (_lock) { if (page.GetFolderDefinitionId(dataTypeId) == Guid.Empty) { page.AddFolderDefinition(dataTypeId); } } SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(this.EntityToken); var folderEntityToken = new AssociatedDataElementProviderHelperEntityToken( TypeManager.SerializeType(typeof (IPage)), PageElementProvider.DefaultConfigurationName, page.Id.ToString(), TypeManager.SerializeType(type)); SelectElement(folderEntityToken); } private void noTypesToAddCodeActivity_ShowMessage_ExecuteCode(object sender, EventArgs e) { Type associatedType = TypeManager.GetType(this.Payload); var associationTypes = PageFolderFacade.GetAllFolderTypes(); if (!associationTypes.Any()) { this.ShowMessage( DialogType.Message, "${Composite.Management, AssociatedDataElementProviderHelper.AddDataFolderExWorkflow.NoTypesTitle}", "${Composite.Management, AssociatedDataElementProviderHelper.AddDataFolderExWorkflow.NoTypesMessage}" ); } else { this.ShowMessage( DialogType.Message, "${Composite.Management, AssociatedDataElementProviderHelper.AddDataFolderExWorkflow.NoUnusedTypesTitle}", "${Composite.Management, AssociatedDataElementProviderHelper.AddDataFolderExWorkflow.NoUnusedTypesMessage}" ); } } } } ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/AddDataFolderExWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { partial class AddDataFolderExWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition3 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition4 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity12 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity8 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity7 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity2 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity3 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.selectTypeCodeActivity_StartCreateNewTypeWorkflow = new System.Workflow.Activities.CodeActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.if_UnusedTypesExist = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity6 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity5 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity11 = new System.Workflow.Activities.SetStateActivity(); this.noTypesToAddCodeActivity_ShowMessage = new System.Workflow.Activities.CodeActivity(); this.ifElseActivity2 = new System.Workflow.Activities.IfElseActivity(); this.saceNewTypeCodeActivity_Save = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.createNewTypeCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.dataDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.selectTypeCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.if_CreateNewType = new System.Workflow.Activities.IfElseActivity(); this.noTypesToAddStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.saveNewTypeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.createNewTypeEventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.createNewTypeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.selectTypeEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.selectTypeEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.selectTypeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.noTypesToAddStateActivity = new System.Workflow.Activities.StateActivity(); this.saveNewTypeStateActivity = new System.Workflow.Activities.StateActivity(); this.createNewTypeStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.selectTypeToAddStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity12 // this.setStateActivity12.Name = "setStateActivity12"; this.setStateActivity12.TargetStateName = "noTypesToAddStateActivity"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "selectTypeToAddStateActivity"; // // ifElseBranchActivity8 // this.ifElseBranchActivity8.Activities.Add(this.setStateActivity12); this.ifElseBranchActivity8.Name = "ifElseBranchActivity8"; // // ifElseBranchActivity7 // this.ifElseBranchActivity7.Activities.Add(this.setStateActivity3); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.UnunsedTypesExist); this.ifElseBranchActivity7.Condition = codecondition1; this.ifElseBranchActivity7.Name = "ifElseBranchActivity7"; // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "createNewTypeStateActivity"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalizeStateActivity"; // // closeCurrentViewActivity2 // this.closeCurrentViewActivity2.Name = "closeCurrentViewActivity2"; // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity3 // this.closeCurrentViewActivity3.Name = "closeCurrentViewActivity3"; // // selectTypeCodeActivity_StartCreateNewTypeWorkflow // this.selectTypeCodeActivity_StartCreateNewTypeWorkflow.Name = "selectTypeCodeActivity_StartCreateNewTypeWorkflow"; this.selectTypeCodeActivity_StartCreateNewTypeWorkflow.ExecuteCode += new System.EventHandler(this.selectTypeCodeActivity_StartCreateNewTypeWorkflow_ExecuteCode); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalizeStateActivity"; // // if_UnusedTypesExist // this.if_UnusedTypesExist.Activities.Add(this.ifElseBranchActivity7); this.if_UnusedTypesExist.Activities.Add(this.ifElseBranchActivity8); this.if_UnusedTypesExist.Name = "if_UnusedTypesExist"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "createNewTypeStateActivity"; // // ifElseBranchActivity6 // this.ifElseBranchActivity6.Activities.Add(this.setStateActivity10); this.ifElseBranchActivity6.Name = "ifElseBranchActivity6"; // // ifElseBranchActivity5 // this.ifElseBranchActivity5.Activities.Add(this.closeCurrentViewActivity2); this.ifElseBranchActivity5.Activities.Add(this.setStateActivity5); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsTypeCreated); this.ifElseBranchActivity5.Condition = codecondition2; this.ifElseBranchActivity5.Name = "ifElseBranchActivity5"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.selectTypeCodeActivity_StartCreateNewTypeWorkflow); this.ifElseBranchActivity2.Activities.Add(this.closeCurrentViewActivity3); this.ifElseBranchActivity2.Activities.Add(this.setStateActivity9); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity6); codecondition3.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.UseExistingType); this.ifElseBranchActivity1.Condition = codecondition3; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.if_UnusedTypesExist); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.setStateActivity8); codecondition4.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ShouldCreateNewType); this.ifElseBranchActivity3.Condition = codecondition4; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // setStateActivity11 // this.setStateActivity11.Name = "setStateActivity11"; this.setStateActivity11.TargetStateName = "finalStateActivity"; // // noTypesToAddCodeActivity_ShowMessage // this.noTypesToAddCodeActivity_ShowMessage.Name = "noTypesToAddCodeActivity_ShowMessage"; this.noTypesToAddCodeActivity_ShowMessage.ExecuteCode += new System.EventHandler(this.noTypesToAddCodeActivity_ShowMessage_ExecuteCode); // // ifElseActivity2 // this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity5); this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity6); this.ifElseActivity2.Name = "ifElseActivity2"; // // saceNewTypeCodeActivity_Save // this.saceNewTypeCodeActivity_Save.Name = "saceNewTypeCodeActivity_Save"; this.saceNewTypeCodeActivity_Save.ExecuteCode += new System.EventHandler(this.saceNewTypeCodeActivity_Save_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "saveNewTypeStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.CustomToolbarDefinitionFileName = null; this.documentFormActivity1.FormDefinitionFileName = "\\Administrative\\AddDataFolderCreateNewType.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // createNewTypeCodeActivity_Initialize // this.createNewTypeCodeActivity_Initialize.Name = "createNewTypeCodeActivity_Initialize"; this.createNewTypeCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.createNewTypeCodeActivity_Initialize_ExecuteCode); // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // dataDialogFormActivity1 // this.dataDialogFormActivity1.ContainerLabel = null; this.dataDialogFormActivity1.FormDefinitionFileName = "\\Administrative\\AddDataFolderExSelectType.xml"; this.dataDialogFormActivity1.Name = "dataDialogFormActivity1"; // // selectTypeCodeActivity_Initialize // this.selectTypeCodeActivity_Initialize.Name = "selectTypeCodeActivity_Initialize"; this.selectTypeCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.selectTypeCodeActivity_Initialize_ExecuteCode); // // if_CreateNewType // this.if_CreateNewType.Activities.Add(this.ifElseBranchActivity3); this.if_CreateNewType.Activities.Add(this.ifElseBranchActivity4); this.if_CreateNewType.Name = "if_CreateNewType"; // // noTypesToAddStateInitializationActivity // this.noTypesToAddStateInitializationActivity.Activities.Add(this.noTypesToAddCodeActivity_ShowMessage); this.noTypesToAddStateInitializationActivity.Activities.Add(this.setStateActivity11); this.noTypesToAddStateInitializationActivity.Name = "noTypesToAddStateInitializationActivity"; // // saveNewTypeStateInitializationActivity // this.saveNewTypeStateInitializationActivity.Activities.Add(this.saceNewTypeCodeActivity_Save); this.saveNewTypeStateInitializationActivity.Activities.Add(this.ifElseActivity2); this.saveNewTypeStateInitializationActivity.Name = "saveNewTypeStateInitializationActivity"; // // createNewTypeEventDrivenActivity_Save // this.createNewTypeEventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.createNewTypeEventDrivenActivity_Save.Activities.Add(this.setStateActivity4); this.createNewTypeEventDrivenActivity_Save.Name = "createNewTypeEventDrivenActivity_Save"; // // createNewTypeStateInitializationActivity // this.createNewTypeStateInitializationActivity.Activities.Add(this.createNewTypeCodeActivity_Initialize); this.createNewTypeStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.createNewTypeStateInitializationActivity.Name = "createNewTypeStateInitializationActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity7); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // selectTypeEventDrivenActivity_Cancel // this.selectTypeEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.selectTypeEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity2); this.selectTypeEventDrivenActivity_Cancel.Name = "selectTypeEventDrivenActivity_Cancel"; // // selectTypeEventDrivenActivity_Finish // this.selectTypeEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.selectTypeEventDrivenActivity_Finish.Activities.Add(this.ifElseActivity1); this.selectTypeEventDrivenActivity_Finish.Name = "selectTypeEventDrivenActivity_Finish"; // // selectTypeStateInitializationActivity // this.selectTypeStateInitializationActivity.Activities.Add(this.selectTypeCodeActivity_Initialize); this.selectTypeStateInitializationActivity.Activities.Add(this.dataDialogFormActivity1); this.selectTypeStateInitializationActivity.Name = "selectTypeStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.if_CreateNewType); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // noTypesToAddStateActivity // this.noTypesToAddStateActivity.Activities.Add(this.noTypesToAddStateInitializationActivity); this.noTypesToAddStateActivity.Name = "noTypesToAddStateActivity"; // // saveNewTypeStateActivity // this.saveNewTypeStateActivity.Activities.Add(this.saveNewTypeStateInitializationActivity); this.saveNewTypeStateActivity.Name = "saveNewTypeStateActivity"; // // createNewTypeStateActivity // this.createNewTypeStateActivity.Activities.Add(this.createNewTypeStateInitializationActivity); this.createNewTypeStateActivity.Activities.Add(this.createNewTypeEventDrivenActivity_Save); this.createNewTypeStateActivity.Name = "createNewTypeStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // selectTypeToAddStateActivity // this.selectTypeToAddStateActivity.Activities.Add(this.selectTypeStateInitializationActivity); this.selectTypeToAddStateActivity.Activities.Add(this.selectTypeEventDrivenActivity_Finish); this.selectTypeToAddStateActivity.Activities.Add(this.selectTypeEventDrivenActivity_Cancel); this.selectTypeToAddStateActivity.Name = "selectTypeToAddStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // AddDataFolderExWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.selectTypeToAddStateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.createNewTypeStateActivity); this.Activities.Add(this.saveNewTypeStateActivity); this.Activities.Add(this.noTypesToAddStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddDataFolderExWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity selectTypeToAddStateActivity; private SetStateActivity setStateActivity2; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity3; private EventDrivenActivity selectTypeEventDrivenActivity_Cancel; private EventDrivenActivity selectTypeEventDrivenActivity_Finish; private StateInitializationActivity selectTypeStateInitializationActivity; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.WizardFormActivity dataDialogFormActivity1; private CodeActivity selectTypeCodeActivity_Initialize; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private CodeActivity finalizeCodeActivity_Finalize; private StateInitializationActivity finalizeStateInitializationActivity; private StateActivity finalizeStateActivity; private SetStateActivity setStateActivity7; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity6; private Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private EventDrivenActivity createNewTypeEventDrivenActivity_Save; private StateInitializationActivity createNewTypeStateInitializationActivity; private StateActivity saveNewTypeStateActivity; private StateActivity createNewTypeStateActivity; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity4; private IfElseActivity ifElseActivity1; private StateInitializationActivity saveNewTypeStateInitializationActivity; private Composite.C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private CodeActivity saceNewTypeCodeActivity_Save; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity2; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity if_CreateNewType; private SetStateActivity setStateActivity8; private CodeActivity selectTypeCodeActivity_StartCreateNewTypeWorkflow; private SetStateActivity setStateActivity9; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity3; private CodeActivity createNewTypeCodeActivity_Initialize; private IfElseBranchActivity ifElseBranchActivity6; private IfElseBranchActivity ifElseBranchActivity5; private IfElseActivity ifElseActivity2; private SetStateActivity setStateActivity10; private SetStateActivity setStateActivity12; private IfElseBranchActivity ifElseBranchActivity8; private IfElseBranchActivity ifElseBranchActivity7; private IfElseActivity if_UnusedTypesExist; private SetStateActivity setStateActivity11; private CodeActivity noTypesToAddCodeActivity_ShowMessage; private StateInitializationActivity noTypesToAddStateInitializationActivity; private StateActivity noTypesToAddStateActivity; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/AddDataFolderExWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="AddDataFolderExWorkflow" Location="30; 30" Size="1146; 937" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="AddDataFolderExWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="AddDataFolderExWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="857" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="createNewTypeStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity8" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="createNewTypeStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="238" /> <ns0:Point X="305" Y="238" /> <ns0:Point X="305" Y="462" /> <ns0:Point X="217" Y="462" /> <ns0:Point X="217" Y="474" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="selectTypeToAddStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="selectTypeToAddStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="238" /> <ns0:Point X="312" Y="238" /> <ns0:Point X="312" Y="331" /> <ns0:Point X="582" Y="331" /> <ns0:Point X="582" Y="343" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="selectTypeToAddStateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="selectTypeToAddStateActivity" EventHandlerName="selectTypeEventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="693" Y="408" /> <ns0:Point X="781" Y="408" /> <ns0:Point X="781" Y="627" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity9" SourceStateName="selectTypeToAddStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="selectTypeToAddStateActivity" EventHandlerName="selectTypeEventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="693" Y="408" /> <ns0:Point X="1058" Y="408" /> <ns0:Point X="1058" Y="857" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="selectTypeToAddStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="selectTypeToAddStateActivity" EventHandlerName="selectTypeEventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="697" Y="432" /> <ns0:Point X="1058" Y="432" /> <ns0:Point X="1058" Y="857" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="880" Y="668" /> <ns0:Point X="1058" Y="668" /> <ns0:Point X="1058" Y="857" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="saveNewTypeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="createNewTypeStateActivity" SourceConnectionEdge="Right" TargetActivity="saveNewTypeStateActivity" SourceActivity="createNewTypeStateActivity" EventHandlerName="createNewTypeEventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="339" Y="539" /> <ns0:Point X="403" Y="539" /> <ns0:Point X="403" Y="637" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="saveNewTypeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="saveNewTypeStateActivity" EventHandlerName="saveNewTypeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="519" Y="678" /> <ns0:Point X="535" Y="678" /> <ns0:Point X="535" Y="619" /> <ns0:Point X="781" Y="619" /> <ns0:Point X="781" Y="627" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="createNewTypeStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity10" SourceStateName="saveNewTypeStateActivity" SourceConnectionEdge="Right" TargetActivity="createNewTypeStateActivity" SourceActivity="saveNewTypeStateActivity" EventHandlerName="saveNewTypeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="519" Y="678" /> <ns0:Point X="529" Y="678" /> <ns0:Point X="529" Y="466" /> <ns0:Point X="217" Y="466" /> <ns0:Point X="217" Y="474" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity11" SourceStateName="noTypesToAddStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="noTypesToAddStateActivity" EventHandlerName="noTypesToAddStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="738" Y="248" /> <ns0:Point X="1058" Y="248" /> <ns0:Point X="1058" Y="857" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="noTypesToAddStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity12" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="noTypesToAddStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="238" /> <ns0:Point X="312" Y="238" /> <ns0:Point X="312" Y="199" /> <ns0:Point X="619" Y="199" /> <ns0:Point X="619" Y="207" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 197" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="612; 496" Name="initializeStateInitializationActivity" Location="98; 228"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="592; 415" Name="if_CreateNewType" Location="108; 290"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 315" Name="ifElseBranchActivity3" Location="127; 361"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity8" Location="137; 520" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="381; 315" Name="ifElseBranchActivity4" Location="300; 361"> <IfElseBranchDesigner.Designers> <IfElseDesigner Size="361; 234" Name="if_UnusedTypesExist" Location="310; 423"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 134" Name="ifElseBranchActivity7" Location="329; 494"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="339; 562" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 134" Name="ifElseBranchActivity8" Location="502; 494"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 53" Name="setStateActivity12" Location="512; 556" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 857" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="selectTypeToAddStateActivity" Location="464; 343" Size="237; 102" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="selectTypeStateInitializationActivity" Location="472; 374"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="selectTypeCodeActivity_Initialize" Location="482; 436" /> <ActivityDesigner Size="130; 41" Name="dataDialogFormActivity1" Location="482; 496" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="381; 483" Name="selectTypeEventDrivenActivity_Finish" Location="472; 398"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="597; 460" /> <IfElseDesigner Size="361; 342" Name="ifElseActivity1" Location="482; 520"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 242" Name="ifElseBranchActivity1" Location="501; 591"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="511; 713" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 242" Name="ifElseBranchActivity2" Location="674; 591"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="selectTypeCodeActivity_StartCreateNewTypeWorkflow" Location="684; 653" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity3" Location="684; 713" /> <SetStateDesigner Size="130; 41" Name="setStateActivity9" Location="684; 773" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="selectTypeEventDrivenActivity_Cancel" Location="472; 422"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="482; 484" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="482; 544" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="679; 627" Size="205; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="finalizeStateInitializationActivity" Location="687; 658"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="697; 720" /> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity_Finalize" Location="697; 780" /> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="697; 840" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="createNewTypeStateActivity" Location="91; 474" Size="252; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="createNewTypeStateInitializationActivity" Location="99; 505"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="createNewTypeCodeActivity_Initialize" Location="109; 567" /> <ActivityDesigner Size="130; 41" Name="documentFormActivity1" Location="109; 627" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="createNewTypeEventDrivenActivity_Save" Location="99; 529"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="saveHandleExternalEventActivity1" Location="109; 591" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="109; 651" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="saveNewTypeStateActivity" Location="283; 637" Size="240; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 423" Name="saveNewTypeStateInitializationActivity" Location="291; 668"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="saceNewTypeCodeActivity_Save" Location="416; 730" /> <IfElseDesigner Size="361; 282" Name="ifElseActivity2" Location="301; 790"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity5" Location="320; 861"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity2" Location="330; 923" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="330; 983" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity6" Location="493; 861"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 53" Name="setStateActivity10" Location="503; 947" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="noTypesToAddStateActivity" Location="497; 207" Size="245; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 194" Name="noTypesToAddStateInitializationActivity" Location="304; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="noTypesToAddCodeActivity_ShowMessage" Location="314; 210" /> <SetStateDesigner Size="130; 53" Name="setStateActivity11" Location="314; 270" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/AddMetaDataWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Transactions; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Workflow; using Composite.Core.ResourceSystem; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; using Composite.Data.Transactions; using Composite.Data.Types; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddMetaDataWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { private static string TypesBindingName { get { return "Types"; } } private static string SelectedTypeBindingName { get { return "SelectedType"; } } private static string FieldGroupNameBindingName { get { return "FieldGroupName"; } } private static string FieldGroupLabelBindingName { get { return "FieldGroupLabel"; } } private static string ContainersBindingName { get { return "Containers"; } } private static string SelectedContainerBindingName { get { return "SelectedContainer"; } } private static string StartDisplayOptionsBindingName { get { return "StartDisplayOptions"; } } private static string SelectedStartDisplayBindingName { get { return "SelectedStartDisplay"; } } private static string InheritDisplayOptionsBindingName { get { return "InheritDisplayOptions"; } } private static string SelectedInheritDisplayBindingName { get { return "SelectedInheritDisplay"; } } private static string DataAssociationVisabilityDescriptionBindingName { get { return "DataAssociationVisabilityRule"; } } public AddMetaDataWorkflow() { InitializeComponent(); } private IEnumerable<Type> GetAddebleTypes() { IEnumerable<Type> accociationTypes = PageMetaDataFacade.GetAllMetaDataTypes(); return accociationTypes; } private IPage GetCurrentPage() { if ((this.EntityToken is DataEntityToken)) { return this.GetDataItemFromEntityToken<IPage>(); } else { return null; } } private Guid GetCurrentPageId() { IPage page = GetCurrentPage(); if (page != null) { return page.Id; } else { return Guid.Empty; } } private bool IsAnyPagesAffected() { PageMetaDataDescription dataAssociationVisabilityRule = this.GetBinding<PageMetaDataDescription>(DataAssociationVisabilityDescriptionBindingName); IPage page = GetCurrentPage(); return page.GetMetaDataAffectedPages(dataAssociationVisabilityRule.StartLevel, dataAssociationVisabilityRule.Levels).Any(); } private void DoesTypesToAddExists(object sender, ConditionalEventArgs e) { e.Result = GetAddebleTypes().FirstOrDefault() != null; } private void DidFieldNameValidate(object sender, ConditionalEventArgs e) { PageMetaDataDescription dataAssociationVisabilityRule = this.GetBinding<PageMetaDataDescription>(DataAssociationVisabilityDescriptionBindingName); e.Result = dataAssociationVisabilityRule != null; } private void DoesTargetDataExists(object sender, ConditionalEventArgs e) { e.Result = IsAnyPagesAffected(); } private void selectTypeCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { if (this.BindingExist(TypesBindingName) == false) { Dictionary<Type, string> types = GetAddebleTypes().OrderBy(f => f.GetTypeTitle()).ToDictionary(f => f, f => f.GetTypeTitle()); this.UpdateBinding(TypesBindingName, types); this.UpdateBinding(SelectedTypeBindingName, types.Keys.First()); } } private void noTypesToAddCodeActivity_ShowMessage_ExecuteCode(object sender, EventArgs e) { this.ShowMessage( DialogType.Message, "${Composite.Management, AssociatedDataElementProviderHelper.AddMetaDataWorkflow.NoTypesTitle}", "${Composite.Management, AssociatedDataElementProviderHelper.AddMetaDataWorkflow.NoTypesMessage}" ); } private void createFieldGroupCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { Type type = this.GetBinding<Type>(SelectedTypeBindingName); string metaDataDefinitionName = type.GetTypeTitle(); int counter = 1; while (PageMetaDataFacade.IsDefinitionAllowed(GetCurrentPageId(), metaDataDefinitionName, metaDataDefinitionName, type.GetImmutableTypeId()) == false) { metaDataDefinitionName = string.Format("{0} {1}", type.GetTypeTitle(), counter++); } this.UpdateBinding(FieldGroupNameBindingName, metaDataDefinitionName); this.UpdateBinding(FieldGroupLabelBindingName, metaDataDefinitionName); if (this.BindingExist(ContainersBindingName) == false) { List<KeyValuePair<Guid, string>> containers = PageMetaDataFacade.GetAllMetaDataContainers(); this.UpdateBinding(ContainersBindingName, containers); this.UpdateBinding(SelectedContainerBindingName, containers.First().Key); Dictionary<int, string> startDisplayOptions = new Dictionary<int, string>(); if (GetCurrentPage() != null) { startDisplayOptions.Add(0, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.StartDisplayOption0")); } startDisplayOptions.Add(1, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.StartDisplayOption1")); startDisplayOptions.Add(2, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.StartDisplayOption2")); startDisplayOptions.Add(3, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.StartDisplayOption3")); startDisplayOptions.Add(4, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.StartDisplayOption4")); startDisplayOptions.Add(5, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.StartDisplayOption5")); this.UpdateBinding(StartDisplayOptionsBindingName, startDisplayOptions); this.UpdateBinding(SelectedStartDisplayBindingName, startDisplayOptions.Keys.First()); Dictionary<int, string> inheritDisplayOptions = new Dictionary<int, string>(); inheritDisplayOptions.Add(0, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.InheritDisplayOption0")); inheritDisplayOptions.Add(1, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.InheritDisplayOption1")); inheritDisplayOptions.Add(2, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.InheritDisplayOption2")); inheritDisplayOptions.Add(3, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.InheritDisplayOption3")); inheritDisplayOptions.Add(10000, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.InheritDisplayOption4")); this.UpdateBinding(InheritDisplayOptionsBindingName, inheritDisplayOptions); this.UpdateBinding(SelectedInheritDisplayBindingName, inheritDisplayOptions.Keys.Last()); } } private void createFieldGroupCodeActivity_CreateVisabilatiyRule_ExecuteCode(object sender, EventArgs e) { string metaDataDefinitionName = this.GetBinding<string>(FieldGroupNameBindingName); string metaDataDefinitionLabel = this.GetBinding<string>(FieldGroupLabelBindingName); Type type = this.GetBinding<Type>(SelectedTypeBindingName); if (PageMetaDataFacade.IsDefinitionAllowed(GetCurrentPageId(), metaDataDefinitionName, metaDataDefinitionLabel, type.GetImmutableTypeId())) { int startLevel = this.GetBinding<int>(SelectedStartDisplayBindingName); int levels = this.GetBinding<int>(SelectedInheritDisplayBindingName); PageMetaDataDescription dataAssociationVisabilityRule = PageMetaDataDescription.Branch(startLevel, levels); this.UpdateBinding(DataAssociationVisabilityDescriptionBindingName, dataAssociationVisabilityRule); } else { this.UpdateBinding(DataAssociationVisabilityDescriptionBindingName, null); this.ShowFieldMessage(FieldGroupNameBindingName, "${Composite.Management, AssociatedDataElementProviderHelper.AddMetaDataWorkflow.FieldGroupNameNotValid}"); } } private void enterDefaultValuesCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { Type type = this.GetBinding<Type>(SelectedTypeBindingName); DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(type.GetImmutableTypeId()); DataTypeDescriptorFormsHelper helper = new DataTypeDescriptorFormsHelper(dataTypeDescriptor); helper.LayoutIconHandle = "associated-data-add"; GeneratedTypesHelper generatedTypesHelper = new GeneratedTypesHelper(dataTypeDescriptor); helper.AddReadOnlyFields(generatedTypesHelper.NotEditableDataFieldDescriptorNames); IData newData = DataFacade.BuildNew(type); helper.UpdateWithNewBindings(this.Bindings); helper.ObjectToBindings(newData, this.Bindings); this.DeliverFormData( type.Name, StandardUiContainerTypes.Wizard, helper.GetForm(), this.Bindings, helper.GetBindingsValidationRules(newData) ); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { Type selectedMetaDataType = this.GetBinding<Type>(SelectedTypeBindingName); DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(selectedMetaDataType.GetImmutableTypeId()); PageMetaDataDescription dataAssociationVisabilityRule = this.GetBinding<PageMetaDataDescription>(DataAssociationVisabilityDescriptionBindingName); Guid metaDataContainerId = this.GetBinding<Guid>(SelectedContainerBindingName); string metaDataDefinitionName = this.GetBinding<string>(FieldGroupNameBindingName); string metaDataDefinitionLabel = this.GetBinding<string>(FieldGroupLabelBindingName); IData newDataTemplate = null; if (IsAnyPagesAffected()) { DataTypeDescriptorFormsHelper helper = new DataTypeDescriptorFormsHelper(dataTypeDescriptor); GeneratedTypesHelper generatedTypesHelper = new GeneratedTypesHelper(dataTypeDescriptor); helper.AddReadOnlyFields(generatedTypesHelper.NotEditableDataFieldDescriptorNames); newDataTemplate = DataFacade.BuildNew(selectedMetaDataType); helper.BindingsToObject(this.Bindings, newDataTemplate); } using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { IPage page = GetCurrentPage(); page.AddMetaDataDefinition(metaDataDefinitionName, metaDataDefinitionLabel, selectedMetaDataType.GetImmutableTypeId(), metaDataContainerId, dataAssociationVisabilityRule.StartLevel, dataAssociationVisabilityRule.Levels); if (newDataTemplate != null) { page.AddNewMetaDataToExistingPages(metaDataDefinitionName, newDataTemplate); } transactionScope.Complete(); } ParentTreeRefresher parentTreeRefresher = this.CreateParentTreeRefresher(); parentTreeRefresher.PostRefreshMesseges(this.EntityToken); } private void MetaDataValid(object sender, ConditionalEventArgs e) { bool valid = ValidateBindings(); Type selectedMetaDataType = this.GetBinding<Type>(SelectedTypeBindingName); DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(selectedMetaDataType.GetImmutableTypeId()); DataTypeDescriptorFormsHelper helper = new DataTypeDescriptorFormsHelper(dataTypeDescriptor); GeneratedTypesHelper generatedTypesHelper = new GeneratedTypesHelper(dataTypeDescriptor); helper.AddReadOnlyFields(generatedTypesHelper.NotEditableDataFieldDescriptorNames); IData newDataTemplate = DataFacade.BuildNew(selectedMetaDataType); if(!BindAndValidate(helper, newDataTemplate)) { valid = false; } if (valid) { var fieldsWithInvalidForeginKey = new List<string>(); DataReferenceFacade.TryValidateForeignKeyIntegrity(newDataTemplate, fieldsWithInvalidForeginKey); if (fieldsWithInvalidForeginKey.Count > 0) { foreach (string fieldName in fieldsWithInvalidForeginKey) { if (!generatedTypesHelper.NotEditableDataFieldDescriptorNames.Contains(fieldName)) { this.ShowFieldMessage(fieldName, "Invalid reference"); valid = false; } } } } e.Result = valid; } } } ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/AddMetaDataWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { partial class AddMetaDataWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition3 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition4 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity21 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity14 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity15 = new System.Workflow.Activities.SetStateActivity(); this.if_DoesPagesExists = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity10 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity9 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity6 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity5 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity18 = new System.Workflow.Activities.SetStateActivity(); this.previousHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.PreviousHandleExternalEventActivity(); this.setStateActivity12 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity4 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity13 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizardFormActivity4 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity17 = new System.Workflow.Activities.SetStateActivity(); this.previousHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.PreviousHandleExternalEventActivity(); this.setStateActivity11 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity3 = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.enterDefaultValuesCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity16 = new System.Workflow.Activities.SetStateActivity(); this.previousHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.PreviousHandleExternalEventActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity5 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.if_DidFieldNameValidate = new System.Workflow.Activities.IfElseActivity(); this.createFieldGroupCodeActivity_CreateVisabilatiyRule = new System.Workflow.Activities.CodeActivity(); this.nextHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.wizardFormActivity1 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.createFieldGroupCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity20 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity2 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.codeActivity1 = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.noTypesToAddCodeActivity_ShowMessage = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.nextHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.wizardFormActivity2 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.selectTypeCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.noTargetDataEventDrivenActivity_Previous = new System.Workflow.Activities.EventDrivenActivity(); this.noTargetDataEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.noTargetDataEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.noTargetDataStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.enterDefaultValuesEventDrivenActivity_Previous = new System.Workflow.Activities.EventDrivenActivity(); this.enterDefaultValuesEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.enterDefaultValuesEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.enterDefaultValuesSateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.createFieldGroupEventDrivenActivity_Previous = new System.Workflow.Activities.EventDrivenActivity(); this.createFieldGroupEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.createFieldGroupEventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.createFieldGroupStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.noTypesToAddStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.selectTypeEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.selectTypeEventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.selectTypeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.noTargetDataWarningStateActivity = new System.Workflow.Activities.StateActivity(); this.enterDefaultValuesStateActivity = new System.Workflow.Activities.StateActivity(); this.createFieldGroupStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.noTypesToAddStateActivity = new System.Workflow.Activities.StateActivity(); this.selectTypeToAddStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "noTargetDataWarningStateActivity"; // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "enterDefaultValuesStateActivity"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity10); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.setStateActivity9); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DoesTargetDataExists); this.ifElseBranchActivity3.Condition = codecondition1; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // setStateActivity21 // this.setStateActivity21.Name = "setStateActivity21"; this.setStateActivity21.TargetStateName = "enterDefaultValuesStateActivity"; // // setStateActivity14 // this.setStateActivity14.Name = "setStateActivity14"; this.setStateActivity14.TargetStateName = "finalizeStateActivity"; // // setStateActivity15 // this.setStateActivity15.Name = "setStateActivity15"; this.setStateActivity15.TargetStateName = "createFieldGroupStateActivity"; // // if_DoesPagesExists // this.if_DoesPagesExists.Activities.Add(this.ifElseBranchActivity3); this.if_DoesPagesExists.Activities.Add(this.ifElseBranchActivity4); this.if_DoesPagesExists.Name = "if_DoesPagesExists"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "noTypesToAddStateActivity"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "selectTypeToAddStateActivity"; // // ifElseBranchActivity10 // this.ifElseBranchActivity10.Activities.Add(this.setStateActivity21); this.ifElseBranchActivity10.Name = "ifElseBranchActivity10"; // // ifElseBranchActivity9 // this.ifElseBranchActivity9.Activities.Add(this.setStateActivity14); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.MetaDataValid); this.ifElseBranchActivity9.Condition = codecondition2; this.ifElseBranchActivity9.Name = "ifElseBranchActivity9"; // // ifElseBranchActivity6 // this.ifElseBranchActivity6.Activities.Add(this.setStateActivity15); this.ifElseBranchActivity6.Name = "ifElseBranchActivity6"; // // ifElseBranchActivity5 // this.ifElseBranchActivity5.Activities.Add(this.if_DoesPagesExists); codecondition3.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DidFieldNameValidate); this.ifElseBranchActivity5.Condition = codecondition3; this.ifElseBranchActivity5.Name = "ifElseBranchActivity5"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity5); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity3); codecondition4.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DoesTypesToAddExists); this.ifElseBranchActivity1.Condition = codecondition4; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity18 // this.setStateActivity18.Name = "setStateActivity18"; this.setStateActivity18.TargetStateName = "createFieldGroupStateActivity"; // // previousHandleExternalEventActivity3 // this.previousHandleExternalEventActivity3.EventName = "Previous"; this.previousHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.previousHandleExternalEventActivity3.Name = "previousHandleExternalEventActivity3"; // // setStateActivity12 // this.setStateActivity12.Name = "setStateActivity12"; this.setStateActivity12.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity4 // this.cancelHandleExternalEventActivity4.EventName = "Cancel"; this.cancelHandleExternalEventActivity4.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity4.Name = "cancelHandleExternalEventActivity4"; // // setStateActivity13 // this.setStateActivity13.Name = "setStateActivity13"; this.setStateActivity13.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // wizardFormActivity4 // this.wizardFormActivity4.ContainerLabel = null; this.wizardFormActivity4.FormDefinitionFileName = "\\Administrative\\AddMetaDataNoTargetDataWarning.xml"; this.wizardFormActivity4.Name = "wizardFormActivity4"; // // setStateActivity17 // this.setStateActivity17.Name = "setStateActivity17"; this.setStateActivity17.TargetStateName = "createFieldGroupStateActivity"; // // previousHandleExternalEventActivity2 // this.previousHandleExternalEventActivity2.EventName = "Previous"; this.previousHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.previousHandleExternalEventActivity2.Name = "previousHandleExternalEventActivity2"; // // setStateActivity11 // this.setStateActivity11.Name = "setStateActivity11"; this.setStateActivity11.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // ifElseActivity3 // this.ifElseActivity3.Activities.Add(this.ifElseBranchActivity9); this.ifElseActivity3.Activities.Add(this.ifElseBranchActivity10); this.ifElseActivity3.Name = "ifElseActivity3"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // enterDefaultValuesCodeActivity_Initialize // this.enterDefaultValuesCodeActivity_Initialize.Name = "enterDefaultValuesCodeActivity_Initialize"; this.enterDefaultValuesCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.enterDefaultValuesCodeActivity_Initialize_ExecuteCode); // // setStateActivity16 // this.setStateActivity16.Name = "setStateActivity16"; this.setStateActivity16.TargetStateName = "selectTypeToAddStateActivity"; // // previousHandleExternalEventActivity1 // this.previousHandleExternalEventActivity1.EventName = "Previous"; this.previousHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.previousHandleExternalEventActivity1.Name = "previousHandleExternalEventActivity1"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity5 // this.cancelHandleExternalEventActivity5.EventName = "Cancel"; this.cancelHandleExternalEventActivity5.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity5.Name = "cancelHandleExternalEventActivity5"; // // if_DidFieldNameValidate // this.if_DidFieldNameValidate.Activities.Add(this.ifElseBranchActivity5); this.if_DidFieldNameValidate.Activities.Add(this.ifElseBranchActivity6); this.if_DidFieldNameValidate.Name = "if_DidFieldNameValidate"; // // createFieldGroupCodeActivity_CreateVisabilatiyRule // this.createFieldGroupCodeActivity_CreateVisabilatiyRule.Name = "createFieldGroupCodeActivity_CreateVisabilatiyRule"; this.createFieldGroupCodeActivity_CreateVisabilatiyRule.ExecuteCode += new System.EventHandler(this.createFieldGroupCodeActivity_CreateVisabilatiyRule_ExecuteCode); // // nextHandleExternalEventActivity2 // this.nextHandleExternalEventActivity2.EventName = "Next"; this.nextHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity2.Name = "nextHandleExternalEventActivity2"; // // wizardFormActivity1 // this.wizardFormActivity1.ContainerLabel = null; this.wizardFormActivity1.FormDefinitionFileName = "\\Administrative\\AddMetaDataCreateFieldGroup.xml"; this.wizardFormActivity1.Name = "wizardFormActivity1"; // // createFieldGroupCodeActivity_Initialize // this.createFieldGroupCodeActivity_Initialize.Name = "createFieldGroupCodeActivity_Initialize"; this.createFieldGroupCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.createFieldGroupCodeActivity_Initialize_ExecuteCode); // // setStateActivity20 // this.setStateActivity20.Name = "setStateActivity20"; this.setStateActivity20.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity2 // this.closeCurrentViewActivity2.Name = "closeCurrentViewActivity2"; // // codeActivity1 // this.codeActivity1.Name = "codeActivity1"; this.codeActivity1.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // noTypesToAddCodeActivity_ShowMessage // this.noTypesToAddCodeActivity_ShowMessage.Name = "noTypesToAddCodeActivity_ShowMessage"; this.noTypesToAddCodeActivity_ShowMessage.ExecuteCode += new System.EventHandler(this.noTypesToAddCodeActivity_ShowMessage_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "createFieldGroupStateActivity"; // // nextHandleExternalEventActivity1 // this.nextHandleExternalEventActivity1.EventName = "Next"; this.nextHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity1.Name = "nextHandleExternalEventActivity1"; // // wizardFormActivity2 // this.wizardFormActivity2.ContainerLabel = null; this.wizardFormActivity2.FormDefinitionFileName = "\\Administrative\\AddMetaDataSelectType.xml"; this.wizardFormActivity2.Name = "wizardFormActivity2"; // // selectTypeCodeActivity_Initialize // this.selectTypeCodeActivity_Initialize.Name = "selectTypeCodeActivity_Initialize"; this.selectTypeCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.selectTypeCodeActivity_Initialize_ExecuteCode); // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // noTargetDataEventDrivenActivity_Previous // this.noTargetDataEventDrivenActivity_Previous.Activities.Add(this.previousHandleExternalEventActivity3); this.noTargetDataEventDrivenActivity_Previous.Activities.Add(this.setStateActivity18); this.noTargetDataEventDrivenActivity_Previous.Name = "noTargetDataEventDrivenActivity_Previous"; // // noTargetDataEventDrivenActivity_Cancel // this.noTargetDataEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity4); this.noTargetDataEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity12); this.noTargetDataEventDrivenActivity_Cancel.Name = "noTargetDataEventDrivenActivity_Cancel"; // // noTargetDataEventDrivenActivity_Finish // this.noTargetDataEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.noTargetDataEventDrivenActivity_Finish.Activities.Add(this.setStateActivity13); this.noTargetDataEventDrivenActivity_Finish.Name = "noTargetDataEventDrivenActivity_Finish"; // // noTargetDataStateInitializationActivity // this.noTargetDataStateInitializationActivity.Activities.Add(this.wizardFormActivity4); this.noTargetDataStateInitializationActivity.Name = "noTargetDataStateInitializationActivity"; // // enterDefaultValuesEventDrivenActivity_Previous // this.enterDefaultValuesEventDrivenActivity_Previous.Activities.Add(this.previousHandleExternalEventActivity2); this.enterDefaultValuesEventDrivenActivity_Previous.Activities.Add(this.setStateActivity17); this.enterDefaultValuesEventDrivenActivity_Previous.Name = "enterDefaultValuesEventDrivenActivity_Previous"; // // enterDefaultValuesEventDrivenActivity_Cancel // this.enterDefaultValuesEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.enterDefaultValuesEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity11); this.enterDefaultValuesEventDrivenActivity_Cancel.Name = "enterDefaultValuesEventDrivenActivity_Cancel"; // // enterDefaultValuesEventDrivenActivity_Finish // this.enterDefaultValuesEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.enterDefaultValuesEventDrivenActivity_Finish.Activities.Add(this.ifElseActivity3); this.enterDefaultValuesEventDrivenActivity_Finish.Name = "enterDefaultValuesEventDrivenActivity_Finish"; // // enterDefaultValuesSateInitializationActivity // this.enterDefaultValuesSateInitializationActivity.Activities.Add(this.enterDefaultValuesCodeActivity_Initialize); this.enterDefaultValuesSateInitializationActivity.Name = "enterDefaultValuesSateInitializationActivity"; // // createFieldGroupEventDrivenActivity_Previous // this.createFieldGroupEventDrivenActivity_Previous.Activities.Add(this.previousHandleExternalEventActivity1); this.createFieldGroupEventDrivenActivity_Previous.Activities.Add(this.setStateActivity16); this.createFieldGroupEventDrivenActivity_Previous.Name = "createFieldGroupEventDrivenActivity_Previous"; // // createFieldGroupEventDrivenActivity_Cancel // this.createFieldGroupEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity5); this.createFieldGroupEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity8); this.createFieldGroupEventDrivenActivity_Cancel.Name = "createFieldGroupEventDrivenActivity_Cancel"; // // createFieldGroupEventDrivenActivity_Next // this.createFieldGroupEventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity2); this.createFieldGroupEventDrivenActivity_Next.Activities.Add(this.createFieldGroupCodeActivity_CreateVisabilatiyRule); this.createFieldGroupEventDrivenActivity_Next.Activities.Add(this.if_DidFieldNameValidate); this.createFieldGroupEventDrivenActivity_Next.Name = "createFieldGroupEventDrivenActivity_Next"; // // createFieldGroupStateInitializationActivity // this.createFieldGroupStateInitializationActivity.Activities.Add(this.createFieldGroupCodeActivity_Initialize); this.createFieldGroupStateInitializationActivity.Activities.Add(this.wizardFormActivity1); this.createFieldGroupStateInitializationActivity.Name = "createFieldGroupStateInitializationActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.codeActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity2); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity20); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // noTypesToAddStateInitializationActivity // this.noTypesToAddStateInitializationActivity.Activities.Add(this.noTypesToAddCodeActivity_ShowMessage); this.noTypesToAddStateInitializationActivity.Activities.Add(this.setStateActivity4); this.noTypesToAddStateInitializationActivity.Name = "noTypesToAddStateInitializationActivity"; // // selectTypeEventDrivenActivity_Cancel // this.selectTypeEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.selectTypeEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity2); this.selectTypeEventDrivenActivity_Cancel.Name = "selectTypeEventDrivenActivity_Cancel"; // // selectTypeEventDrivenActivity_Next // this.selectTypeEventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity1); this.selectTypeEventDrivenActivity_Next.Activities.Add(this.setStateActivity6); this.selectTypeEventDrivenActivity_Next.Name = "selectTypeEventDrivenActivity_Next"; // // selectTypeStateInitializationActivity // this.selectTypeStateInitializationActivity.Activities.Add(this.selectTypeCodeActivity_Initialize); this.selectTypeStateInitializationActivity.Activities.Add(this.wizardFormActivity2); this.selectTypeStateInitializationActivity.Name = "selectTypeStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.ifElseActivity1); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // noTargetDataWarningStateActivity // this.noTargetDataWarningStateActivity.Activities.Add(this.noTargetDataStateInitializationActivity); this.noTargetDataWarningStateActivity.Activities.Add(this.noTargetDataEventDrivenActivity_Finish); this.noTargetDataWarningStateActivity.Activities.Add(this.noTargetDataEventDrivenActivity_Cancel); this.noTargetDataWarningStateActivity.Activities.Add(this.noTargetDataEventDrivenActivity_Previous); this.noTargetDataWarningStateActivity.Name = "noTargetDataWarningStateActivity"; // // enterDefaultValuesStateActivity // this.enterDefaultValuesStateActivity.Activities.Add(this.enterDefaultValuesSateInitializationActivity); this.enterDefaultValuesStateActivity.Activities.Add(this.enterDefaultValuesEventDrivenActivity_Finish); this.enterDefaultValuesStateActivity.Activities.Add(this.enterDefaultValuesEventDrivenActivity_Cancel); this.enterDefaultValuesStateActivity.Activities.Add(this.enterDefaultValuesEventDrivenActivity_Previous); this.enterDefaultValuesStateActivity.Name = "enterDefaultValuesStateActivity"; // // createFieldGroupStateActivity // this.createFieldGroupStateActivity.Activities.Add(this.createFieldGroupStateInitializationActivity); this.createFieldGroupStateActivity.Activities.Add(this.createFieldGroupEventDrivenActivity_Next); this.createFieldGroupStateActivity.Activities.Add(this.createFieldGroupEventDrivenActivity_Cancel); this.createFieldGroupStateActivity.Activities.Add(this.createFieldGroupEventDrivenActivity_Previous); this.createFieldGroupStateActivity.Name = "createFieldGroupStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // noTypesToAddStateActivity // this.noTypesToAddStateActivity.Activities.Add(this.noTypesToAddStateInitializationActivity); this.noTypesToAddStateActivity.Name = "noTypesToAddStateActivity"; // // selectTypeToAddStateActivity // this.selectTypeToAddStateActivity.Activities.Add(this.selectTypeStateInitializationActivity); this.selectTypeToAddStateActivity.Activities.Add(this.selectTypeEventDrivenActivity_Next); this.selectTypeToAddStateActivity.Activities.Add(this.selectTypeEventDrivenActivity_Cancel); this.selectTypeToAddStateActivity.Name = "selectTypeToAddStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // AddMetaDataWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.selectTypeToAddStateActivity); this.Activities.Add(this.noTypesToAddStateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.createFieldGroupStateActivity); this.Activities.Add(this.enterDefaultValuesStateActivity); this.Activities.Add(this.noTargetDataWarningStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddMetaDataWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity selectTypeToAddStateActivity; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity3; private EventDrivenActivity selectTypeEventDrivenActivity_Cancel; private EventDrivenActivity selectTypeEventDrivenActivity_Next; private StateInitializationActivity selectTypeStateInitializationActivity; private CodeActivity selectTypeCodeActivity_Initialize; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity4; private CodeActivity noTypesToAddCodeActivity_ShowMessage; private StateInitializationActivity noTypesToAddStateInitializationActivity; private StateActivity noTypesToAddStateActivity; private StateInitializationActivity finalizeStateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity createFieldGroupStateActivity; private C1Console.Workflow.Activities.WizardFormActivity wizardFormActivity1; private SetStateActivity setStateActivity6; private StateInitializationActivity createFieldGroupStateInitializationActivity; private C1Console.Workflow.Activities.WizardFormActivity wizardFormActivity2; private C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity1; private EventDrivenActivity createFieldGroupEventDrivenActivity_Cancel; private EventDrivenActivity createFieldGroupEventDrivenActivity_Next; private SetStateActivity setStateActivity8; private StateActivity noTargetDataWarningStateActivity; private StateActivity enterDefaultValuesStateActivity; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity if_DoesPagesExists; private C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity2; private SetStateActivity setStateActivity10; private SetStateActivity setStateActivity9; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private EventDrivenActivity noTargetDataEventDrivenActivity_Cancel; private EventDrivenActivity noTargetDataEventDrivenActivity_Finish; private StateInitializationActivity noTargetDataStateInitializationActivity; private EventDrivenActivity enterDefaultValuesEventDrivenActivity_Cancel; private EventDrivenActivity enterDefaultValuesEventDrivenActivity_Finish; private StateInitializationActivity enterDefaultValuesSateInitializationActivity; private SetStateActivity setStateActivity12; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity4; private SetStateActivity setStateActivity13; private SetStateActivity setStateActivity11; private C1Console.Workflow.Activities.WizardFormActivity wizardFormActivity4; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity5; private CodeActivity createFieldGroupCodeActivity_Initialize; private CodeActivity createFieldGroupCodeActivity_CreateVisabilatiyRule; private CodeActivity enterDefaultValuesCodeActivity_Initialize; private IfElseBranchActivity ifElseBranchActivity6; private IfElseBranchActivity ifElseBranchActivity5; private IfElseActivity if_DidFieldNameValidate; private SetStateActivity setStateActivity15; private EventDrivenActivity createFieldGroupEventDrivenActivity_Previous; private SetStateActivity setStateActivity18; private C1Console.Workflow.Activities.PreviousHandleExternalEventActivity previousHandleExternalEventActivity3; private SetStateActivity setStateActivity17; private C1Console.Workflow.Activities.PreviousHandleExternalEventActivity previousHandleExternalEventActivity2; private SetStateActivity setStateActivity16; private C1Console.Workflow.Activities.PreviousHandleExternalEventActivity previousHandleExternalEventActivity1; private EventDrivenActivity noTargetDataEventDrivenActivity_Previous; private EventDrivenActivity enterDefaultValuesEventDrivenActivity_Previous; private SetStateActivity setStateActivity20; private SetStateActivity setStateActivity21; private SetStateActivity setStateActivity14; private IfElseBranchActivity ifElseBranchActivity10; private IfElseBranchActivity ifElseBranchActivity9; private IfElseActivity ifElseActivity3; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity2; private CodeActivity codeActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/AddMetaDataWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1232; 986" AutoSizeMargin="16; 24" Location="30; 30" Name="AddMetaDataWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="381; 303" Location="98; 169"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="ifElseActivity1" Size="361; 222" Location="108; 231"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 122" Location="127; 302"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="137; 364" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 122" Location="300; 302"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="310; 364" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="237; 102" AutoSizeMargin="16; 24" Location="180; 261" Name="selectTypeToAddStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="selectTypeStateInitializationActivity" Size="150; 182" Location="188; 292"> <StateInitializationDesigner.Designers> <CodeDesigner Name="selectTypeCodeActivity_Initialize" Size="130; 41" Location="198; 354" /> <ActivityDesigner Name="wizardFormActivity2" Size="130; 41" Location="198; 414" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="selectTypeEventDrivenActivity_Next" Size="150; 182" Location="188; 316"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="nextHandleExternalEventActivity1" Size="130; 41" Location="198; 378" /> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="198; 438" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="selectTypeEventDrivenActivity_Cancel" Size="150; 182" Location="188; 340"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="198; 402" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="198; 462" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="245; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="637; 228" Name="noTypesToAddStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="noTypesToAddStateInitializationActivity" Size="150; 182" Location="645; 259"> <StateInitializationDesigner.Designers> <CodeDesigner Name="noTypesToAddCodeActivity_ShowMessage" Size="130; 41" Location="655; 321" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="655; 381" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" Location="345; 896" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 254" Location="353; 927"> <StateInitializationDesigner.Designers> <CodeDesigner Name="codeActivity1" Size="130; 41" Location="363; 989" /> <ActivityDesigner Name="closeCurrentViewActivity2" Size="130; 41" Location="363; 1049" /> <SetStateDesigner Name="setStateActivity20" Size="130; 53" Location="363; 1109" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="277; 126" AutoSizeMargin="16; 24" Location="169; 418" Name="createFieldGroupStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="createFieldGroupStateInitializationActivity" Size="150; 182" Location="177; 449"> <StateInitializationDesigner.Designers> <CodeDesigner Name="createFieldGroupCodeActivity_Initialize" Size="130; 41" Location="187; 511" /> <ActivityDesigner Name="wizardFormActivity1" Size="130; 41" Location="187; 571" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="createFieldGroupEventDrivenActivity_Next" Size="612; 616" Location="177; 473"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="nextHandleExternalEventActivity2" Size="130; 41" Location="418; 535" /> <CodeDesigner Name="createFieldGroupCodeActivity_CreateVisabilatiyRule" Size="130; 41" Location="418; 595" /> <IfElseDesigner Name="if_DidFieldNameValidate" Size="592; 415" Location="187; 655"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity5" Size="381; 315" Location="206; 726"> <IfElseBranchDesigner.Designers> <IfElseDesigner Name="if_DoesPagesExists" Size="361; 234" Location="216; 788"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity3" Size="150; 134" Location="235; 859"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity9" Size="130; 41" Location="245; 927" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity4" Size="150; 134" Location="408; 859"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity10" Size="130; 53" Location="418; 921" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity6" Size="150; 315" Location="610; 726"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity15" Size="130; 53" Location="620; 879" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="createFieldGroupEventDrivenActivity_Cancel" Size="150; 182" Location="177; 497"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity5" Size="130; 41" Location="187; 559" /> <SetStateDesigner Name="setStateActivity8" Size="130; 41" Location="187; 619" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="createFieldGroupEventDrivenActivity_Previous" Size="150; 194" Location="177; 521"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="previousHandleExternalEventActivity1" Size="130; 41" Location="187; 583" /> <SetStateDesigner Name="setStateActivity16" Size="130; 53" Location="187; 643" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="287; 126" AutoSizeMargin="16; 24" AutoSize="False" Location="96; 602" Name="enterDefaultValuesStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="enterDefaultValuesSateInitializationActivity" Size="150; 122" Location="104; 633"> <StateInitializationDesigner.Designers> <CodeDesigner Name="enterDefaultValuesCodeActivity_Initialize" Size="130; 41" Location="114; 695" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="enterDefaultValuesEventDrivenActivity_Finish" Size="381; 375" Location="104; 657"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="229; 719" /> <IfElseDesigner Name="ifElseActivity3" Size="361; 234" Location="114; 779"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity9" Size="150; 134" Location="133; 850"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity14" Size="130; 53" Location="143; 912" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity10" Size="150; 134" Location="306; 850"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity21" Size="130; 53" Location="316; 912" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="enterDefaultValuesEventDrivenActivity_Cancel" Size="150; 194" Location="104; 681"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity3" Size="130; 41" Location="114; 743" /> <SetStateDesigner Name="setStateActivity11" Size="130; 53" Location="114; 803" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="enterDefaultValuesEventDrivenActivity_Previous" Size="150; 194" Location="104; 705"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="previousHandleExternalEventActivity2" Size="130; 41" Location="114; 767" /> <SetStateDesigner Name="setStateActivity17" Size="130; 53" Location="114; 827" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="261; 126" AutoSizeMargin="16; 24" Location="470; 601" Name="noTargetDataWarningStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="noTargetDataStateInitializationActivity" Size="150; 122" Location="478; 632"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizardFormActivity4" Size="130; 41" Location="488; 694" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="noTargetDataEventDrivenActivity_Finish" Size="150; 194" Location="478; 656"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity2" Size="130; 41" Location="488; 718" /> <SetStateDesigner Name="setStateActivity13" Size="130; 53" Location="488; 778" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="noTargetDataEventDrivenActivity_Cancel" Size="150; 194" Location="478; 680"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity4" Size="130; 41" Location="488; 742" /> <SetStateDesigner Name="setStateActivity12" Size="130; 53" Location="488; 802" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="noTargetDataEventDrivenActivity_Previous" Size="150; 194" Location="478; 704"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="previousHandleExternalEventActivity3" Size="130; 41" Location="488; 766" /> <SetStateDesigner Name="setStateActivity18" Size="130; 53" Location="488; 826" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="AddMetaDataWorkflow" TargetConnectionIndex="0" SourceStateName="AddMetaDataWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="selectTypeToAddStateActivity" SetStateName="setStateActivity3" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="selectTypeToAddStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="306" Y="179" /> <ns0:Point X="306" Y="249" /> <ns0:Point X="298" Y="249" /> <ns0:Point X="298" Y="261" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="noTypesToAddStateActivity" SetStateName="setStateActivity5" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="noTypesToAddStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="759" Y="179" /> <ns0:Point X="759" Y="228" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="createFieldGroupStateActivity" SetStateName="setStateActivity6" SourceActivity="selectTypeToAddStateActivity" TargetConnectionIndex="0" SourceStateName="selectTypeToAddStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="selectTypeEventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="createFieldGroupStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="403" Y="326" /> <ns0:Point X="427" Y="326" /> <ns0:Point X="427" Y="406" /> <ns0:Point X="307" Y="406" /> <ns0:Point X="307" Y="418" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity2" SourceActivity="selectTypeToAddStateActivity" TargetConnectionIndex="0" SourceStateName="selectTypeToAddStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="selectTypeEventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="413" Y="350" /> <ns0:Point X="1058" Y="350" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity4" SourceActivity="noTypesToAddStateActivity" TargetConnectionIndex="0" SourceStateName="noTypesToAddStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="noTypesToAddStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="878" Y="269" /> <ns0:Point X="1058" Y="269" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity20" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="546" Y="937" /> <ns0:Point X="766" Y="937" /> <ns0:Point X="766" Y="798" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="createFieldGroupStateActivity" SetStateName="setStateActivity15" SourceActivity="createFieldGroupStateActivity" TargetConnectionIndex="0" SourceStateName="createFieldGroupStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="createFieldGroupEventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="createFieldGroupStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="423" Y="483" /> <ns0:Point X="451" Y="483" /> <ns0:Point X="451" Y="410" /> <ns0:Point X="307" Y="410" /> <ns0:Point X="307" Y="418" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="enterDefaultValuesStateActivity" SetStateName="setStateActivity9" SourceActivity="createFieldGroupStateActivity" TargetConnectionIndex="0" SourceStateName="createFieldGroupStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="createFieldGroupEventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="enterDefaultValuesStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="423" Y="483" /> <ns0:Point X="455" Y="483" /> <ns0:Point X="455" Y="590" /> <ns0:Point X="239" Y="590" /> <ns0:Point X="239" Y="602" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="noTargetDataWarningStateActivity" SetStateName="setStateActivity10" SourceActivity="createFieldGroupStateActivity" TargetConnectionIndex="0" SourceStateName="createFieldGroupStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="createFieldGroupEventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="noTargetDataWarningStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="423" Y="483" /> <ns0:Point X="600" Y="483" /> <ns0:Point X="600" Y="601" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity8" SourceActivity="createFieldGroupStateActivity" TargetConnectionIndex="0" SourceStateName="createFieldGroupStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="createFieldGroupEventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="433" Y="507" /> <ns0:Point X="1058" Y="507" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="selectTypeToAddStateActivity" SetStateName="setStateActivity16" SourceActivity="createFieldGroupStateActivity" TargetConnectionIndex="0" SourceStateName="createFieldGroupStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Left" EventHandlerName="createFieldGroupEventDrivenActivity_Previous" SourceConnectionIndex="3" TargetStateName="selectTypeToAddStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="173" Y="531" /> <ns0:Point X="162" Y="531" /> <ns0:Point X="162" Y="253" /> <ns0:Point X="298" Y="253" /> <ns0:Point X="298" Y="261" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity14" SourceActivity="enterDefaultValuesStateActivity" TargetConnectionIndex="0" SourceStateName="enterDefaultValuesStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="enterDefaultValuesEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="366" Y="667" /> <ns0:Point X="447" Y="667" /> <ns0:Point X="447" Y="896" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="enterDefaultValuesStateActivity" SetStateName="setStateActivity21" SourceActivity="enterDefaultValuesStateActivity" TargetConnectionIndex="0" SourceStateName="enterDefaultValuesStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="enterDefaultValuesEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="enterDefaultValuesStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="366" Y="667" /> <ns0:Point X="391" Y="667" /> <ns0:Point X="391" Y="594" /> <ns0:Point X="239" Y="594" /> <ns0:Point X="239" Y="602" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity11" SourceActivity="enterDefaultValuesStateActivity" TargetConnectionIndex="0" SourceStateName="enterDefaultValuesStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="enterDefaultValuesEventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="370" Y="691" /> <ns0:Point X="386" Y="691" /> <ns0:Point X="386" Y="786" /> <ns0:Point X="1058" Y="786" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="createFieldGroupStateActivity" SetStateName="setStateActivity17" SourceActivity="enterDefaultValuesStateActivity" TargetConnectionIndex="0" SourceStateName="enterDefaultValuesStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Left" EventHandlerName="enterDefaultValuesEventDrivenActivity_Previous" SourceConnectionIndex="3" TargetStateName="createFieldGroupStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="100" Y="715" /> <ns0:Point X="91" Y="715" /> <ns0:Point X="91" Y="410" /> <ns0:Point X="307" Y="410" /> <ns0:Point X="307" Y="418" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity13" SourceActivity="noTargetDataWarningStateActivity" TargetConnectionIndex="0" SourceStateName="noTargetDataWarningStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="noTargetDataEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="714" Y="666" /> <ns0:Point X="727" Y="666" /> <ns0:Point X="727" Y="884" /> <ns0:Point X="447" Y="884" /> <ns0:Point X="447" Y="896" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity12" SourceActivity="noTargetDataWarningStateActivity" TargetConnectionIndex="0" SourceStateName="noTargetDataWarningStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="noTargetDataEventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="718" Y="690" /> <ns0:Point X="1058" Y="690" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="createFieldGroupStateActivity" SetStateName="setStateActivity18" SourceActivity="noTargetDataWarningStateActivity" TargetConnectionIndex="0" SourceStateName="noTargetDataWarningStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Left" EventHandlerName="noTargetDataEventDrivenActivity_Previous" SourceConnectionIndex="3" TargetStateName="createFieldGroupStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="474" Y="714" /> <ns0:Point X="458" Y="714" /> <ns0:Point X="458" Y="410" /> <ns0:Point X="307" Y="410" /> <ns0:Point X="307" Y="418" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/DeleteAssociatedDataWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.Data; using Composite.Data.DynamicTypes.Foundation; using Composite.Data.ProcessControlled; using Composite.C1Console.Events; using Composite.Core.ResourceSystem; using Composite.Core.Extensions; using Composite.C1Console.Workflow; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteAssociatedDataWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeleteAssociatedDataWorkflow() { InitializeComponent(); } private void HasDataReferences(object sender, ConditionalEventArgs e) { IData data = ((DataEntityToken)this.EntityToken).Data; var brokenReferences = new List<IData>(); var references = DataReferenceFacade.GetNotOptionalReferences(data); foreach (var reference in references) { DataSourceId dataSourceId = reference.DataSourceId; if (brokenReferences.Any(brokenRef => brokenRef.DataSourceId == dataSourceId)) { continue; } brokenReferences.Add(reference); } e.Result = brokenReferences.Count > 0; if (brokenReferences.Count == 0) { return; } Bindings.Add("ReferencedData", DataReferenceFacade.GetBrokenReferencesReport(brokenReferences)); } private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { DeleteTreeRefresher deleteTreeRefresher = this.CreateDeleteTreeRefresher(this.EntityToken); IData data = ((DataEntityToken)this.EntityToken).Data; if (DataFacade.WillDeleteSucceed(data)) { ProcessControllerFacade.FullDelete(data); deleteTreeRefresher.PostRefreshMesseges(true); } else { this.ShowMessage( DialogType.Error, StringResourceSystemFacade.GetString("Composite.Management", "DeleteAssociatedDataWorkflow.CascadeDeleteErrorTitle"), StringResourceSystemFacade.GetString("Composite.Management", "DeleteAssociatedDataWorkflow.CascadeDeleteErrorMessage") ); } } } } ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/DeleteAssociatedDataWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { partial class DeleteAssociatedDataWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.confirmDialogFormActivity2 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.branchHasNoRelatedData = new System.Workflow.Activities.IfElseBranchActivity(); this.branchHasRelatedData = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseHasRelatedData = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.eventDrivenActivity_OK = new System.Workflow.Activities.EventDrivenActivity(); this.eventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_OK = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.checkRelatedDataStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.initialStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finishState = new System.Workflow.Activities.StateActivity(); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "step1StateActivity"; // // confirmDialogFormActivity2 // this.confirmDialogFormActivity2.ContainerLabel = null; this.confirmDialogFormActivity2.FormDefinitionFileName = "/Administrative/DeleteGeneratedDataStep2.xml"; this.confirmDialogFormActivity2.Name = "confirmDialogFormActivity2"; // // branchHasNoRelatedData // this.branchHasNoRelatedData.Activities.Add(this.setStateActivity6); this.branchHasNoRelatedData.Name = "branchHasNoRelatedData"; // // branchHasRelatedData // this.branchHasRelatedData.Activities.Add(this.confirmDialogFormActivity2); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.HasDataReferences); this.branchHasRelatedData.Condition = codecondition1; this.branchHasRelatedData.Name = "branchHasRelatedData"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // ifElseHasRelatedData // this.ifElseHasRelatedData.Activities.Add(this.branchHasRelatedData); this.ifElseHasRelatedData.Activities.Add(this.branchHasNoRelatedData); this.ifElseHasRelatedData.Name = "ifElseHasRelatedData"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "/Administrative/DeleteAssociatedTypeDataStep1.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finishState"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "checkRelatedDataStateActivity"; // // eventDrivenActivity_OK // this.eventDrivenActivity_OK.Activities.Add(this.finishHandleExternalEventActivity2); this.eventDrivenActivity_OK.Activities.Add(this.setStateActivity8); this.eventDrivenActivity_OK.Name = "eventDrivenActivity_OK"; // // eventDrivenActivity_Cancel // this.eventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.eventDrivenActivity_Cancel.Activities.Add(this.setStateActivity7); this.eventDrivenActivity_Cancel.Name = "eventDrivenActivity_Cancel"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.ifElseHasRelatedData); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity5); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_OK // this.step1EventDrivenActivity_OK.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_OK.Activities.Add(this.setStateActivity4); this.step1EventDrivenActivity_OK.Name = "step1EventDrivenActivity_OK"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.confirmDialogFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity3); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // checkRelatedDataStateActivity // this.checkRelatedDataStateActivity.Activities.Add(this.stateInitializationActivity1); this.checkRelatedDataStateActivity.Activities.Add(this.eventDrivenActivity_Cancel); this.checkRelatedDataStateActivity.Activities.Add(this.eventDrivenActivity_OK); this.checkRelatedDataStateActivity.Name = "checkRelatedDataStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_OK); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // initialStateActivity // this.initialStateActivity.Activities.Add(this.initialStateInitializationActivity); this.initialStateActivity.Name = "initialStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finishState // this.finishState.Name = "finishState"; // // DeleteAssociatedDataWorkflow // this.Activities.Add(this.finishState); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initialStateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.checkRelatedDataStateActivity); this.CompletedStateName = "finishState"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialStateActivity"; this.Name = "DeleteAssociatedDataWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity finishState; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private SetStateActivity setStateActivity1; private StateActivity initialStateActivity; private CodeActivity finalizeCodeActivity; private StateInitializationActivity finalizeStateInitializationActivity; private StateInitializationActivity initialStateInitializationActivity; private StateActivity finalizeStateActivity; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_OK; private StateInitializationActivity step1StateInitializationActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity6; private IfElseBranchActivity branchHasNoRelatedData; private IfElseBranchActivity branchHasRelatedData; private SetStateActivity setStateActivity7; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private IfElseActivity ifElseHasRelatedData; private EventDrivenActivity eventDrivenActivity_Cancel; private StateInitializationActivity stateInitializationActivity1; private StateActivity checkRelatedDataStateActivity; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity2; private SetStateActivity setStateActivity8; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private EventDrivenActivity eventDrivenActivity_OK; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/DeleteAssociatedDataWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="DeleteAssociatedDataWorkflow" Location="30; 30" Size="822; 643" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="DeleteAssociatedDataWorkflow" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="DeleteAssociatedDataWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="739" Y="71" /> <ns0:Point X="739" Y="131" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="checkRelatedDataStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initialStateActivity" SourceConnectionEdge="Right" TargetActivity="checkRelatedDataStateActivity" SourceActivity="initialStateActivity" EventHandlerName="initialStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="253" Y="162" /> <ns0:Point X="275" Y="162" /> <ns0:Point X="275" Y="284" /> <ns0:Point X="155" Y="284" /> <ns0:Point X="155" Y="296" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="808" Y="327" /> <ns0:Point X="824" Y="327" /> <ns0:Point X="824" Y="95" /> <ns0:Point X="739" Y="95" /> <ns0:Point X="739" Y="131" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="555" Y="480" /> <ns0:Point X="571" Y="480" /> <ns0:Point X="571" Y="123" /> <ns0:Point X="739" Y="123" /> <ns0:Point X="739" Y="131" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="checkRelatedDataStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="checkRelatedDataStateActivity" EventHandlerName="stateInitializationActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="235" Y="337" /> <ns0:Point X="453" Y="337" /> <ns0:Point X="453" Y="391" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="checkRelatedDataStateActivity" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="checkRelatedDataStateActivity" EventHandlerName="eventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="243" Y="361" /> <ns0:Point X="259" Y="361" /> <ns0:Point X="259" Y="371" /> <ns0:Point X="827" Y="371" /> <ns0:Point X="827" Y="123" /> <ns0:Point X="739" Y="123" /> <ns0:Point X="739" Y="131" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_OK"> <StateDesignerConnector.Segments> <ns0:Point X="537" Y="456" /> <ns0:Point X="571" Y="456" /> <ns0:Point X="571" Y="278" /> <ns0:Point X="709" Y="278" /> <ns0:Point X="709" Y="286" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity8" SourceStateName="checkRelatedDataStateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="checkRelatedDataStateActivity" EventHandlerName="eventDrivenActivity_OK"> <StateDesignerConnector.Segments> <ns0:Point X="225" Y="385" /> <ns0:Point X="259" Y="385" /> <ns0:Point X="259" Y="278" /> <ns0:Point X="709" Y="278" /> <ns0:Point X="709" Y="286" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="finishState" Location="659; 131" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initialStateActivity" Location="60; 121" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="initialStateInitializationActivity" Location="68; 152"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="78; 214" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="607; 286" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="finalizeStateInitializationActivity" Location="615; 317"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity" Location="625; 379" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="625; 439" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="625; 499" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="step1StateActivity" Location="348; 391" Size="211; 102" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="356; 422"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="confirmDialogFormActivity1" Location="366; 484" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_OK" Location="356; 446"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="366; 508" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="366; 568" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="356; 470"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="366; 532" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="366; 592" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="checkRelatedDataStateActivity" Location="64; 296" Size="183; 118" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 303" Name="stateInitializationActivity1" Location="250; 148"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="361; 222" Name="ifElseHasRelatedData" Location="260; 210"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="branchHasRelatedData" Location="279; 281"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="confirmDialogFormActivity2" Location="289; 343" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="branchHasNoRelatedData" Location="452; 281"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="462; 343" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_Cancel" Location="242; 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity3" Location="252; 221" /> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="252; 281" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_OK" Location="242; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity2" Location="252; 245" /> <SetStateDesigner Size="130; 41" Name="setStateActivity8" Location="252; 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/DeleteDataFolderWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.Data; using Composite.Data.Types; using Composite.Core.Types; using Composite.C1Console.Workflow; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteDataFolderWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeleteDataFolderWorkflow() { InitializeComponent(); } private IPage GetPage() { AssociatedDataElementProviderHelperEntityToken entityToken = (AssociatedDataElementProviderHelperEntityToken)this.EntityToken; return Composite.Data.PageManager.GetPageById(new Guid(entityToken.Id)); } private Type GetFolderType() { AssociatedDataElementProviderHelperEntityToken entityToken = (AssociatedDataElementProviderHelperEntityToken)this.EntityToken; return TypeManager.GetType(entityToken.Payload); } private void confirmCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { this.Bindings.Add("DeleteDatas", true); } private void HasDataReferences(object sender, ConditionalEventArgs e) { IPage page = GetPage(); Type folderType = GetFolderType(); IEnumerable<IData> dataToDelete = page.GetFolderData(folderType); var brokenReferences = new List<IData>(); foreach (var data in dataToDelete) { var references = DataReferenceFacade.GetNotOptionalReferences(data); foreach (var reference in references) { DataSourceId dataSourceId = reference.DataSourceId; if (brokenReferences.Any(brokenRef => brokenRef.DataSourceId.Equals(dataSourceId)) || dataToDelete.Any(elem => elem.DataSourceId.Equals(dataSourceId))) { continue; } brokenReferences.Add(reference); } } e.Result = brokenReferences.Count > 0; if (brokenReferences.Count == 0) { return; } Bindings.Add("ReferencedData", DataReferenceFacade.GetBrokenReferencesReport(brokenReferences)); } private void ShouldDeleteData(object sender, ConditionalEventArgs e) { e.Result = this.GetBinding<bool>("DeleteDatas"); } private void deleteCodeActivity_Delete_ExecuteCode(object sender, EventArgs e) { IPage page = GetPage(); Type folderType = GetFolderType(); page.RemoveFolderDefinition(folderType, this.GetBinding<bool>("DeleteDatas")); SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(page.GetDataEntityToken()); } } } ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/DeleteDataFolderWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { partial class DeleteDataFolderWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.confirmIfElseActivity_RelatedDataExists = new System.Workflow.Activities.IfElseActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.confirmDialogFormActivity2 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.deleteCodeActivity_Delete = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.confirmIfElseActivity_DeleteData = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.confirmCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.eventDrivenActivity_Ok = new System.Workflow.Activities.EventDrivenActivity(); this.eventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.deleteStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.confirmEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.confirmEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.confirmStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.checkRelatedDataStateActivity = new System.Workflow.Activities.StateActivity(); this.deleteStateActivity = new System.Workflow.Activities.StateActivity(); this.confirmStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "deleteStateActivity"; // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "checkRelatedDataStateActivity"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity9); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.setStateActivity10); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.HasDataReferences); this.ifElseBranchActivity3.Condition = codecondition1; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "deleteStateActivity"; // // confirmIfElseActivity_RelatedDataExists // this.confirmIfElseActivity_RelatedDataExists.Activities.Add(this.ifElseBranchActivity3); this.confirmIfElseActivity_RelatedDataExists.Activities.Add(this.ifElseBranchActivity4); this.confirmIfElseActivity_RelatedDataExists.Name = "confirmIfElseActivity_RelatedDataExists"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity4); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.confirmIfElseActivity_RelatedDataExists); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ShouldDeleteData); this.ifElseBranchActivity1.Condition = codecondition2; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "deleteStateActivity"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // confirmDialogFormActivity2 // this.confirmDialogFormActivity2.ContainerLabel = null; this.confirmDialogFormActivity2.FormDefinitionFileName = "/Administrative/DeleteDataFolderConfirmDeletingRelatedData.xml"; this.confirmDialogFormActivity2.Name = "confirmDialogFormActivity2"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // deleteCodeActivity_Delete // this.deleteCodeActivity_Delete.Name = "deleteCodeActivity_Delete"; this.deleteCodeActivity_Delete.ExecuteCode += new System.EventHandler(this.deleteCodeActivity_Delete_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // confirmIfElseActivity_DeleteData // this.confirmIfElseActivity_DeleteData.Activities.Add(this.ifElseBranchActivity1); this.confirmIfElseActivity_DeleteData.Activities.Add(this.ifElseBranchActivity2); this.confirmIfElseActivity_DeleteData.Name = "confirmIfElseActivity_DeleteData"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "\\Administrative\\DeleteDataFolderConfirm.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // confirmCodeActivity_Initialize // this.confirmCodeActivity_Initialize.Name = "confirmCodeActivity_Initialize"; this.confirmCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.confirmCodeActivity_Initialize_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "confirmStateActivity"; // // eventDrivenActivity_Ok // this.eventDrivenActivity_Ok.Activities.Add(this.finishHandleExternalEventActivity2); this.eventDrivenActivity_Ok.Activities.Add(this.setStateActivity7); this.eventDrivenActivity_Ok.Name = "eventDrivenActivity_Ok"; // // eventDrivenActivity_Cancel // this.eventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.eventDrivenActivity_Cancel.Activities.Add(this.setStateActivity8); this.eventDrivenActivity_Cancel.Name = "eventDrivenActivity_Cancel"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.confirmDialogFormActivity2); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // deleteStateInitializationActivity // this.deleteStateInitializationActivity.Activities.Add(this.deleteCodeActivity_Delete); this.deleteStateInitializationActivity.Activities.Add(this.setStateActivity5); this.deleteStateInitializationActivity.Name = "deleteStateInitializationActivity"; // // confirmEventDrivenActivity_Cancel // this.confirmEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.confirmEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity2); this.confirmEventDrivenActivity_Cancel.Name = "confirmEventDrivenActivity_Cancel"; // // confirmEventDrivenActivity_Finish // this.confirmEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.confirmEventDrivenActivity_Finish.Activities.Add(this.confirmIfElseActivity_DeleteData); this.confirmEventDrivenActivity_Finish.Name = "confirmEventDrivenActivity_Finish"; // // confirmStateInitializationActivity // this.confirmStateInitializationActivity.Activities.Add(this.confirmCodeActivity_Initialize); this.confirmStateInitializationActivity.Activities.Add(this.confirmDialogFormActivity1); this.confirmStateInitializationActivity.Name = "confirmStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity3); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // checkRelatedDataStateActivity // this.checkRelatedDataStateActivity.Activities.Add(this.stateInitializationActivity1); this.checkRelatedDataStateActivity.Activities.Add(this.eventDrivenActivity_Cancel); this.checkRelatedDataStateActivity.Activities.Add(this.eventDrivenActivity_Ok); this.checkRelatedDataStateActivity.Name = "checkRelatedDataStateActivity"; // // deleteStateActivity // this.deleteStateActivity.Activities.Add(this.deleteStateInitializationActivity); this.deleteStateActivity.Name = "deleteStateActivity"; // // confirmStateActivity // this.confirmStateActivity.Activities.Add(this.confirmStateInitializationActivity); this.confirmStateActivity.Activities.Add(this.confirmEventDrivenActivity_Finish); this.confirmStateActivity.Activities.Add(this.confirmEventDrivenActivity_Cancel); this.confirmStateActivity.Name = "confirmStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // DeleteDataFolderWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.confirmStateActivity); this.Activities.Add(this.deleteStateActivity); this.Activities.Add(this.checkRelatedDataStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "DeleteDataFolderWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private EventDrivenActivity confirmEventDrivenActivity_Cancel; private EventDrivenActivity confirmEventDrivenActivity_Finish; private StateInitializationActivity confirmStateInitializationActivity; private StateActivity confirmStateActivity; private SetStateActivity setStateActivity5; private CodeActivity deleteCodeActivity_Delete; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity3; private StateInitializationActivity deleteStateInitializationActivity; private StateActivity deleteStateActivity; private C1Console.Workflow.Activities.DataDialogFormActivity confirmDialogFormActivity1; private CodeActivity confirmCodeActivity_Initialize; private StateInitializationActivity stateInitializationActivity1; private StateActivity checkRelatedDataStateActivity; private C1Console.Workflow.Activities.DataDialogFormActivity confirmDialogFormActivity2; private SetStateActivity setStateActivity7; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private SetStateActivity setStateActivity8; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private EventDrivenActivity eventDrivenActivity_Ok; private EventDrivenActivity eventDrivenActivity_Cancel; private SetStateActivity setStateActivity9; private SetStateActivity setStateActivity10; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity confirmIfElseActivity_RelatedDataExists; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity confirmIfElseActivity_DeleteData; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/DeleteDataFolderWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1221; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="DeleteDataFolderWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="48; 131" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 122" Location="56; 162"> <StateInitializationDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="66; 224" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="786; 768" Name="finalStateActivity" /> <StateDesigner Size="221; 102" AutoSizeMargin="16; 24" AutoSize="False" Location="126; 274" Name="confirmStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="confirmStateInitializationActivity" Size="150; 182" Location="565; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Name="confirmCodeActivity_Initialize" Size="130; 41" Location="575; 210" /> <ActivityDesigner Name="confirmDialogFormActivity1" Size="130; 41" Location="575; 270" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="confirmEventDrivenActivity_Finish" Size="612; 556" Location="557; 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="798; 221" /> <IfElseDesigner Name="confirmIfElseActivity_DeleteData" Size="592; 415" Location="567; 281"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="381; 315" Location="586; 352"> <IfElseBranchDesigner.Designers> <IfElseDesigner Name="confirmIfElseActivity_RelatedDataExists" Size="361; 234" Location="596; 414"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity3" Size="150; 134" Location="615; 485"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity10" Size="130; 53" Location="625; 547" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity4" Size="150; 134" Location="788; 485"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity9" Size="130; 41" Location="798; 553" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 315" Location="990; 352"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="1000; 511" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="confirmEventDrivenActivity_Cancel" Size="150; 182" Location="557; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="567; 245" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="567; 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="201; 80" AutoSizeMargin="16; 24" Location="563; 623" Name="deleteStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="deleteStateInitializationActivity" Size="150; 182" Location="571; 654"> <StateInitializationDesigner.Designers> <CodeDesigner Name="deleteCodeActivity_Delete" Size="130; 41" Location="581; 716" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="581; 776" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="183; 118" AutoSizeMargin="16; 24" Location="646; 280" Name="checkRelatedDataStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="stateInitializationActivity1" Size="150; 122" Location="654; 311"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="confirmDialogFormActivity2" Size="130; 41" Location="664; 373" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="eventDrivenActivity_Cancel" Size="150; 182" Location="654; 335"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity3" Size="130; 41" Location="664; 397" /> <SetStateDesigner Name="setStateActivity8" Size="130; 41" Location="664; 457" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="eventDrivenActivity_Ok" Size="150; 182" Location="654; 359"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity2" Size="130; 41" Location="664; 421" /> <SetStateDesigner Name="setStateActivity7" Size="130; 41" Location="664; 481" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="DeleteDataFolderWorkflow" TargetConnectionIndex="0" SourceStateName="DeleteDataFolderWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="873" Y="71" /> <ns0:Point X="873" Y="768" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="deleteStateActivity" SetStateName="setStateActivity4" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="confirmEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="deleteStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="339" Y="339" /> <ns0:Point X="359" Y="339" /> <ns0:Point X="359" Y="611" /> <ns0:Point X="663" Y="611" /> <ns0:Point X="663" Y="623" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity2" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="confirmEventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="343" Y="363" /> <ns0:Point X="359" Y="363" /> <ns0:Point X="359" Y="756" /> <ns0:Point X="873" Y="756" /> <ns0:Point X="873" Y="768" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity5" SourceActivity="deleteStateActivity" TargetConnectionIndex="0" SourceStateName="deleteStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="deleteStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="760" Y="664" /> <ns0:Point X="873" Y="664" /> <ns0:Point X="873" Y="768" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity8" SourceActivity="checkRelatedDataStateActivity" TargetConnectionIndex="0" SourceStateName="checkRelatedDataStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_Cancel" SourceConnectionIndex="1" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="825" Y="345" /> <ns0:Point X="873" Y="345" /> <ns0:Point X="873" Y="768" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="deleteStateActivity" SetStateName="setStateActivity7" SourceActivity="checkRelatedDataStateActivity" TargetConnectionIndex="0" SourceStateName="checkRelatedDataStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_Ok" SourceConnectionIndex="2" TargetStateName="deleteStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="806" Y="369" /> <ns0:Point X="839" Y="369" /> <ns0:Point X="839" Y="611" /> <ns0:Point X="663" Y="611" /> <ns0:Point X="663" Y="623" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="deleteStateActivity" SetStateName="setStateActivity9" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="confirmEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="deleteStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="339" Y="339" /> <ns0:Point X="359" Y="339" /> <ns0:Point X="359" Y="611" /> <ns0:Point X="663" Y="611" /> <ns0:Point X="663" Y="623" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="checkRelatedDataStateActivity" SetStateName="setStateActivity10" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="confirmEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="checkRelatedDataStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="339" Y="339" /> <ns0:Point X="359" Y="339" /> <ns0:Point X="359" Y="272" /> <ns0:Point X="737" Y="272" /> <ns0:Point X="737" Y="280" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="confirmStateActivity" SetStateName="setStateActivity3" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="confirmStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="254" Y="172" /> <ns0:Point X="268" Y="172" /> <ns0:Point X="268" Y="262" /> <ns0:Point X="236" Y="262" /> <ns0:Point X="236" Y="274" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/DeleteMetaDataWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Actions; using Composite.Data; using Composite.Core.Types; using Composite.C1Console.Workflow; using Composite.Data.Types; using Composite.Core.ResourceSystem; using Composite.C1Console.Events; using System.Workflow.Activities; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteMetaDataWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeleteMetaDataWorkflow() { InitializeComponent(); } private IPage GetCurrentPage() { if ((this.EntityToken is DataEntityToken)) { return this.GetDataItemFromEntityToken<IPage>(); } else { return null; } } private void DoesDefinedMetaDataTypesExists(object sender, ConditionalEventArgs e) { IPage page = GetCurrentPage(); e.Result = page.GetDefinedMetaDataTypes().Count() > 0; } private void initializeCodeActivity_ShowMessage_ExecuteCode(object sender, EventArgs e) { this.ShowMessage( DialogType.Message, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.DeleteMetaDataWorkflow.NoDefinedTypesExists.Title"), StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.DeleteMetaDataWorkflow.NoDefinedTypesExists.Message")); } private void confirmCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { IPage page = GetCurrentPage(); Dictionary<Pair<string, Type>, string> fieldGroupNames = new Dictionary<Pair<string, Type>, string>(); foreach (Tuple<Type, string> typeName in page.GetDefinedMetaDataTypeAndNames().OrderBy(f => f.Item2)) { fieldGroupNames.Add(new Pair<string, Type>(typeName.Item2, typeName.Item1), typeName.Item2); } this.UpdateBinding("FieldGroupNames", fieldGroupNames); this.UpdateBinding("SelectedFieldGroupName", fieldGroupNames.Keys.First()); } private void deleteCodeActivity_Delete_ExecuteCode(object sender, EventArgs e) { IPage page = GetCurrentPage(); Pair<string, Type> metaDataPair = this.GetBinding<Pair<string, Type>>("SelectedFieldGroupName"); page.RemoveMetaDataDefinition(metaDataPair.First); ParentTreeRefresher parentTreeRefresher = this.CreateParentTreeRefresher(); parentTreeRefresher.PostRefreshMesseges(this.EntityToken); } } } ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/DeleteMetaDataWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { partial class DeleteMetaDataWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_ShowMessage = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.deleteCodeActivity_Delete = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.dataDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.confirmCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.deleteStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.confirmEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.confirmEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.confirmStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.deleteStateActivity = new System.Workflow.Activities.StateActivity(); this.confirmStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // initializeCodeActivity_ShowMessage // this.initializeCodeActivity_ShowMessage.Name = "initializeCodeActivity_ShowMessage"; this.initializeCodeActivity_ShowMessage.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ShowMessage_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "confirmStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.initializeCodeActivity_ShowMessage); this.ifElseBranchActivity2.Activities.Add(this.setStateActivity6); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity3); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DoesDefinedMetaDataTypesExists); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // deleteCodeActivity_Delete // this.deleteCodeActivity_Delete.Name = "deleteCodeActivity_Delete"; this.deleteCodeActivity_Delete.ExecuteCode += new System.EventHandler(this.deleteCodeActivity_Delete_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "deleteStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // dataDialogFormActivity1 // this.dataDialogFormActivity1.ContainerLabel = null; this.dataDialogFormActivity1.FormDefinitionFileName = "\\Administrative\\DeleteMetaDataConfirm.xml"; this.dataDialogFormActivity1.Name = "dataDialogFormActivity1"; // // confirmCodeActivity_Initialize // this.confirmCodeActivity_Initialize.Name = "confirmCodeActivity_Initialize"; this.confirmCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.confirmCodeActivity_Initialize_ExecuteCode); // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // deleteStateInitializationActivity // this.deleteStateInitializationActivity.Activities.Add(this.deleteCodeActivity_Delete); this.deleteStateInitializationActivity.Activities.Add(this.setStateActivity5); this.deleteStateInitializationActivity.Name = "deleteStateInitializationActivity"; // // confirmEventDrivenActivity_Cancel // this.confirmEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.confirmEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity2); this.confirmEventDrivenActivity_Cancel.Name = "confirmEventDrivenActivity_Cancel"; // // confirmEventDrivenActivity_Finish // this.confirmEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.confirmEventDrivenActivity_Finish.Activities.Add(this.setStateActivity4); this.confirmEventDrivenActivity_Finish.Name = "confirmEventDrivenActivity_Finish"; // // confirmStateInitializationActivity // this.confirmStateInitializationActivity.Activities.Add(this.confirmCodeActivity_Initialize); this.confirmStateInitializationActivity.Activities.Add(this.dataDialogFormActivity1); this.confirmStateInitializationActivity.Name = "confirmStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.ifElseActivity1); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // deleteStateActivity // this.deleteStateActivity.Activities.Add(this.deleteStateInitializationActivity); this.deleteStateActivity.Name = "deleteStateActivity"; // // confirmStateActivity // this.confirmStateActivity.Activities.Add(this.confirmStateInitializationActivity); this.confirmStateActivity.Activities.Add(this.confirmEventDrivenActivity_Finish); this.confirmStateActivity.Activities.Add(this.confirmEventDrivenActivity_Cancel); this.confirmStateActivity.Name = "confirmStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // DeleteMetaDataWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.confirmStateActivity); this.Activities.Add(this.deleteStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "DeleteMetaDataWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private EventDrivenActivity confirmEventDrivenActivity_Cancel; private EventDrivenActivity confirmEventDrivenActivity_Finish; private StateInitializationActivity confirmStateInitializationActivity; private StateActivity confirmStateActivity; private SetStateActivity setStateActivity5; private CodeActivity deleteCodeActivity_Delete; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity3; private StateInitializationActivity deleteStateInitializationActivity; private StateActivity deleteStateActivity; private CodeActivity confirmCodeActivity_Initialize; private C1Console.Workflow.Activities.DataDialogFormActivity dataDialogFormActivity1; private SetStateActivity setStateActivity6; private CodeActivity initializeCodeActivity_ShowMessage; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/DeleteMetaDataWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1190; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="DeleteMetaDataWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="381; 363" Location="434; 148"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="ifElseActivity1" Size="361; 282" Location="444; 210"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 182" Location="463; 281"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="473; 373" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 182" Location="636; 281"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_ShowMessage" Size="130; 41" Location="646; 343" /> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="646; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="221; 102" AutoSizeMargin="16; 24" Location="210; 365" Name="confirmStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="confirmStateInitializationActivity" Size="150; 182" Location="218; 396"> <StateInitializationDesigner.Designers> <CodeDesigner Name="confirmCodeActivity_Initialize" Size="130; 41" Location="228; 458" /> <ActivityDesigner Name="dataDialogFormActivity1" Size="130; 41" Location="228; 518" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="confirmEventDrivenActivity_Finish" Size="150; 182" Location="218; 420"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="228; 482" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="228; 542" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="confirmEventDrivenActivity_Cancel" Size="150; 182" Location="218; 444"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="228; 506" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="228; 566" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="201; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="643; 536" Name="deleteStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="deleteStateInitializationActivity" Size="150; 182" Location="651; 567"> <StateInitializationDesigner.Designers> <CodeDesigner Name="deleteCodeActivity_Delete" Size="130; 41" Location="661; 629" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="661; 689" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="DeleteMetaDataWorkflow" TargetConnectionIndex="0" SourceStateName="DeleteMetaDataWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="confirmStateActivity" SetStateName="setStateActivity3" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="confirmStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="320" Y="179" /> <ns0:Point X="320" Y="365" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="deleteStateActivity" SetStateName="setStateActivity4" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="confirmEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="deleteStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="423" Y="430" /> <ns0:Point X="743" Y="430" /> <ns0:Point X="743" Y="536" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity2" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="confirmEventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="427" Y="454" /> <ns0:Point X="1058" Y="454" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity5" SourceActivity="deleteStateActivity" TargetConnectionIndex="0" SourceStateName="deleteStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="deleteStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="840" Y="577" /> <ns0:Point X="1058" Y="577" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/EditAssociatedDataWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Scheduling; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.C1Console.Workflow.Activities; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditAssociatedDataWorkflow : FormsWorkflow { [NonSerialized] private bool _doPublish; [NonSerialized] private DataTypeDescriptorFormsHelper _helper; private string _typeName; public EditAssociatedDataWorkflow() { InitializeComponent(); } private DataTypeDescriptorFormsHelper GetDataTypeDescriptorFormsHelper() { if (_helper == null) { var dataEntityToken = (DataEntityToken)EntityToken; var interfaceType = dataEntityToken.Data.DataSourceId.InterfaceType; var guid = interfaceType.GetImmutableTypeId(); var typeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(guid); var generatedTypesHelper = new GeneratedTypesHelper(typeDescriptor); _helper = new DataTypeDescriptorFormsHelper(typeDescriptor, true, EntityToken); _helper.AddReadOnlyFields(generatedTypesHelper.NotEditableDataFieldDescriptorNames); _typeName = typeDescriptor.Name; } return _helper; } private void editDataCodeActivity_ExecuteCode(object sender, EventArgs e) { var helper = GetDataTypeDescriptorFormsHelper(); helper.LayoutIconHandle = "associated-data-edit"; var data = ((DataEntityToken)EntityToken).Data; var publishedControlled = data as IPublishControlled; if (!PermissionsFacade.GetPermissionsForCurrentUser(EntityToken).Contains(PermissionType.Publish) || publishedControlled == null) { var formData = WorkflowFacade.GetFormData(InstanceId, true); if (formData.ExcludedEvents == null) { formData.ExcludedEvents = new List<string>(); } formData.ExcludedEvents.Add("SaveAndPublish"); } if (publishedControlled != null) { if (publishedControlled.PublicationStatus == GenericPublishProcessController.Published) { publishedControlled.PublicationStatus = GenericPublishProcessController.Draft; } } helper.UpdateWithBindings(data, Bindings); DeliverFormData( _typeName, StandardUiContainerTypes.Document, helper.GetForm(), Bindings, helper.GetBindingsValidationRules(data) ); } private void saveDataCodeActivity_ExecuteCode(object sender, EventArgs e) { var isValid = ValidateBindings(); var updateTreeRefresher = CreateUpdateTreeRefresher(EntityToken); var helper = GetDataTypeDescriptorFormsHelper(); var data = ((DataEntityToken)EntityToken).Data; if (!BindAndValidate(helper, data)) { isValid = false; } if (isValid) { // published data stayed as published data - change to draft if status is published if (data is IPublishControlled) { var publishControlledData = (IPublishControlled)data; if (publishControlledData.PublicationStatus == GenericPublishProcessController.Published) { publishControlledData.PublicationStatus = GenericPublishProcessController.Draft; } } DataFacade.Update(data); EntityTokenCacheFacade.ClearCache(EntityToken); updateTreeRefresher.PostRefreshMessages(EntityToken); PublishControlledHelper.PublishIfNeeded(data, _doPublish, Bindings, ShowMessage); SetSaveStatus(true); } else { SetSaveStatus(false); } } private void enablePublishCodeActivity_ExecuteCode(object sender, EventArgs e) { _doPublish = true; } } } ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/EditAssociatedDataWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { partial class EditAssociatedDataWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.saveDataCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.enablePublishCodeActivity = new System.Workflow.Activities.CodeActivity(); this.saveAndPublishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveAndPublishHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.editDataCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.saveDataStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editDataEventDrivenActivity_SaveAndPublish = new System.Workflow.Activities.EventDrivenActivity(); this.editDataEventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editDataStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveDataStateActivity = new System.Workflow.Activities.StateActivity(); this.editDataStateActivity = new System.Workflow.Activities.StateActivity(); this.initialStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finishState = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editDataStateActivity"; // // saveDataCodeActivity // this.saveDataCodeActivity.Name = "saveDataCodeActivity"; this.saveDataCodeActivity.ExecuteCode += new System.EventHandler(this.saveDataCodeActivity_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "saveDataStateActivity"; // // enablePublishCodeActivity // this.enablePublishCodeActivity.Name = "enablePublishCodeActivity"; this.enablePublishCodeActivity.ExecuteCode += new System.EventHandler(this.enablePublishCodeActivity_ExecuteCode); // // saveAndPublishHandleExternalEventActivity1 // this.saveAndPublishHandleExternalEventActivity1.EventName = "SaveAndPublish"; this.saveAndPublishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveAndPublishHandleExternalEventActivity1.Name = "saveAndPublishHandleExternalEventActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "saveDataStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // editDataCodeActivity // this.editDataCodeActivity.Name = "editDataCodeActivity"; this.editDataCodeActivity.ExecuteCode += new System.EventHandler(this.editDataCodeActivity_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editDataStateActivity"; // // saveDataStateInitializationActivity // this.saveDataStateInitializationActivity.Activities.Add(this.saveDataCodeActivity); this.saveDataStateInitializationActivity.Activities.Add(this.setStateActivity4); this.saveDataStateInitializationActivity.Name = "saveDataStateInitializationActivity"; // // editDataEventDrivenActivity_SaveAndPublish // this.editDataEventDrivenActivity_SaveAndPublish.Activities.Add(this.saveAndPublishHandleExternalEventActivity1); this.editDataEventDrivenActivity_SaveAndPublish.Activities.Add(this.enablePublishCodeActivity); this.editDataEventDrivenActivity_SaveAndPublish.Activities.Add(this.setStateActivity5); this.editDataEventDrivenActivity_SaveAndPublish.Name = "editDataEventDrivenActivity_SaveAndPublish"; // // editDataEventDrivenActivity_Save // this.editDataEventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.editDataEventDrivenActivity_Save.Activities.Add(this.setStateActivity3); this.editDataEventDrivenActivity_Save.Name = "editDataEventDrivenActivity_Save"; // // editDataStateInitializationActivity // this.editDataStateInitializationActivity.Activities.Add(this.editDataCodeActivity); this.editDataStateInitializationActivity.Name = "editDataStateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveDataStateActivity // this.saveDataStateActivity.Activities.Add(this.saveDataStateInitializationActivity); this.saveDataStateActivity.Name = "saveDataStateActivity"; // // editDataStateActivity // this.editDataStateActivity.Activities.Add(this.editDataStateInitializationActivity); this.editDataStateActivity.Activities.Add(this.editDataEventDrivenActivity_Save); this.editDataStateActivity.Activities.Add(this.editDataEventDrivenActivity_SaveAndPublish); this.editDataStateActivity.Name = "editDataStateActivity"; // // initialStateActivity // this.initialStateActivity.Activities.Add(this.initialStateInitializationActivity); this.initialStateActivity.Name = "initialStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finishState // this.finishState.Name = "finishState"; // // EditAssociatedDataWorkflow // this.Activities.Add(this.finishState); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initialStateActivity); this.Activities.Add(this.editDataStateActivity); this.Activities.Add(this.saveDataStateActivity); this.CompletedStateName = "finishState"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialStateActivity"; this.Name = "EditAssociatedDataWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity5; private CodeActivity enablePublishCodeActivity; private Workflow.Activities.SaveAndPublishHandleExternalEventActivity saveAndPublishHandleExternalEventActivity1; private EventDrivenActivity editDataEventDrivenActivity_SaveAndPublish; private StateActivity finishState; private Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private SetStateActivity setStateActivity1; private StateActivity initialStateActivity; private SetStateActivity setStateActivity2; private StateInitializationActivity saveDataStateInitializationActivity; private EventDrivenActivity editDataEventDrivenActivity_Save; private StateInitializationActivity editDataStateInitializationActivity; private StateInitializationActivity initialStateInitializationActivity; private StateActivity saveDataStateActivity; private StateActivity editDataStateActivity; private Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private CodeActivity editDataCodeActivity; private CodeActivity saveDataCodeActivity; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity3; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/EditAssociatedDataWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1199; 932" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="EditAssociatedDataWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="1037; 810" Name="finishState" /> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 209" Location="38; 63"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 44" Location="48; 128" /> <SetStateDesigner Name="setStateActivity1" Size="130; 62" Location="48; 191" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="212; 80" AutoSizeMargin="16; 24" Location="83; 150" Name="initialStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initialStateInitializationActivity" Size="150; 146" Location="91; 183"> <StateInitializationDesigner.Designers> <SetStateDesigner Name="setStateActivity2" Size="130; 62" Location="101; 248" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="292; 110" AutoSizeMargin="16; 24" AutoSize="False" Location="218; 462" Name="editDataStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="editDataStateInitializationActivity" Size="150; 128" Location="546; 141"> <StateInitializationDesigner.Designers> <CodeDesigner Name="editDataCodeActivity" Size="130; 44" Location="556; 206" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="editDataEventDrivenActivity_Save" Size="150; 209" Location="546; 167"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130; 44" Location="556; 232" /> <SetStateDesigner Name="setStateActivity3" Size="130; 62" Location="556; 295" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="editDataEventDrivenActivity_SaveAndPublish" Size="150; 272" Location="554; 154"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveAndPublishHandleExternalEventActivity1" Size="130; 44" Location="564; 219" /> <CodeDesigner Name="enablePublishCodeActivity" Size="130; 44" Location="564; 282" /> <SetStateDesigner Name="setStateActivity5" Size="130; 62" Location="564; 345" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="232; 80" AutoSizeMargin="16; 24" Location="612; 468" Name="saveDataStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="saveDataStateInitializationActivity" Size="150; 209" Location="620; 501"> <StateInitializationDesigner.Designers> <CodeDesigner Name="saveDataCodeActivity" Size="130; 44" Location="630; 566" /> <SetStateDesigner Name="setStateActivity4" Size="130; 62" Location="630; 629" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finishState" SetStateName="setStateActivity1" SourceActivity="EditAssociatedDataWorkflow" TargetConnectionIndex="0" SourceStateName="EditAssociatedDataWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finishState"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="74" /> <ns0:Point X="1117" Y="74" /> <ns0:Point X="1117" Y="810" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editDataStateActivity" SetStateName="setStateActivity2" SourceActivity="initialStateActivity" TargetConnectionIndex="0" SourceStateName="initialStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initialStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editDataStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="291" Y="194" /> <ns0:Point X="364" Y="194" /> <ns0:Point X="364" Y="462" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveDataStateActivity" SetStateName="setStateActivity3" SourceActivity="editDataStateActivity" TargetConnectionIndex="0" SourceStateName="editDataStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editDataEventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="saveDataStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="444" Y="532" /> <ns0:Point X="522" Y="532" /> <ns0:Point X="522" Y="460" /> <ns0:Point X="728" Y="460" /> <ns0:Point X="728" Y="468" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editDataStateActivity" SetStateName="setStateActivity4" SourceActivity="saveDataStateActivity" TargetConnectionIndex="0" SourceStateName="saveDataStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="saveDataStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editDataStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="840" Y="512" /> <ns0:Point X="852" Y="512" /> <ns0:Point X="852" Y="454" /> <ns0:Point X="364" Y="454" /> <ns0:Point X="364" Y="462" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveDataStateActivity" SetStateName="setStateActivity5" SourceActivity="editDataStateActivity" TargetConnectionIndex="0" SourceStateName="editDataStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editDataEventDrivenActivity_SaveAndPublish" SourceConnectionIndex="2" TargetStateName="saveDataStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="506" Y="558" /> <ns0:Point X="522" Y="558" /> <ns0:Point X="522" Y="460" /> <ns0:Point X="728" Y="460" /> <ns0:Point X="728" Y="468" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/EditMetaDataWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Transactions; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; using Composite.Data.Types; using Composite.Core.ResourceSystem; using Composite.Data.Transactions; using Composite.Core.Types; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { public sealed partial class EditMetaDataWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditMetaDataWorkflow() { InitializeComponent(); } private IPage GetCurrentPage() { if ((this.EntityToken is DataEntityToken)) { return this.GetDataItemFromEntityToken<IPage>(); } else { return null; } } private Guid GetCurrentPageId() { IPage page = GetCurrentPage(); if (page != null) { return page.Id; } else { return Guid.Empty; } } private List<Guid> GetOldAffectedPageIds() { Pair<string, Type> metaDataPair = this.GetBinding<Pair<string, Type>>("SelectedMetaDataDefinition"); IPageMetaDataDefinition pageMetaDataDefinition = PageMetaDataFacade.GetMetaDataDefinition(GetCurrentPageId(), metaDataPair.First); IPage page = GetCurrentPage(); return page.GetMetaDataAffectedPages(pageMetaDataDefinition.StartLevel, pageMetaDataDefinition.Levels).Select(f => f.Id).ToList(); } private List<Guid> GetNewAffectedPageIds() { int startLevel = this.GetBinding<int>("SelectedStartDisplay"); int levels = this.GetBinding<int>("SelectedInheritDisplay"); IPage page = GetCurrentPage(); return page.GetMetaDataAffectedPages(startLevel, levels).Select(f => f.Id).ToList(); } private void DefinedDefinitionsExists(object sender, ConditionalEventArgs e) { IPage page = GetCurrentPage(); e.Result = page.GetDefinedMetaDataTypes().Count() > 0; } private void AffectedPagesExists(object sender, ConditionalEventArgs e) { List<Guid> oldPageIds = GetOldAffectedPageIds(); List<Guid> newPageIds = GetNewAffectedPageIds(); Pair<string, Type> metaDataPair = this.GetBinding<Pair<string, Type>>("SelectedMetaDataDefinition"); IEnumerable<Guid> newPageIdsToAdd = newPageIds.Except(oldPageIds); foreach (Guid id in newPageIdsToAdd) { IPage page = Composite.Data.PageManager.GetPageById(id); if (page.GetMetaData(metaDataPair.First, metaDataPair.Second) == null) { e.Result = true; return; } } e.Result = false; } private void ValidateNewDefinition(object sender, ConditionalEventArgs e) { Pair<string, Type> metaDataPair = this.GetBinding<Pair<string, Type>>("SelectedMetaDataDefinition"); IPageMetaDataDefinition pageMetaDataDefinition = PageMetaDataFacade.GetMetaDataDefinition(GetCurrentPageId(), metaDataPair.First); e.Result = true; string newLabel = this.GetBinding<string>("Label"); Guid newMetaDataContainerId = this.GetBinding<Guid>("SelectedMetaDataContainer"); Guid pageId = GetCurrentPageId(); if (pageMetaDataDefinition.Label != newLabel) { if (PageMetaDataFacade.IsDefinitionAllowed(pageId, pageMetaDataDefinition.Name, newLabel, pageMetaDataDefinition.MetaDataTypeId) == false) { e.Result = false; ShowFieldMessage("Label", StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.EditMetaDataWorkflow.MetaDataFieldNameAlreadyUsed")); } } if (pageMetaDataDefinition.MetaDataContainerId != newMetaDataContainerId) { if (PageMetaDataFacade.IsNewContainerIdAllowed(pageId, pageMetaDataDefinition.Name, newMetaDataContainerId) == false) { e.Result = false; ShowFieldMessage("SelectedMetaDataContainer", StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.EditMetaDataWorkflow.MetaDataContainerChangeNotAllowed")); } } } private void initializeCodeActivity_ShowNoDefinedDefinitionsMessage_ExecuteCode(object sender, EventArgs e) { this.ShowMessage( DialogType.Message, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.EditMetaDataWorkflow.NoMetaDataDefinitionsExists.Title"), StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.EditMetaDataWorkflow.NoMetaDataDefinitionsExists.Message") ); } private void initializeCodeActivity_UpdateBindings_ExecuteCode(object sender, EventArgs e) { IPage page = GetCurrentPage(); Dictionary<Pair<string, Type>, string> fieldGroupNames = new Dictionary<Pair<string, Type>, string>(); foreach (Tuple<Type, string> typeName in page.GetDefinedMetaDataTypeAndNames().OrderBy(f => f.Item2)) { fieldGroupNames.Add(new Pair<string, Type>(typeName.Item2, typeName.Item1), typeName.Item2); } this.Bindings.Add("MetaDataDefinitionOptions", fieldGroupNames); this.Bindings.Add("SelectedMetaDataDefinition", fieldGroupNames.Keys.First()); } private void editDefinitionCodeActivity_UpdateBindings_ExecuteCode(object sender, EventArgs e) { Pair<string, Type> metaDataPair = this.GetBinding<Pair<string, Type>>("SelectedMetaDataDefinition"); IPageMetaDataDefinition pageMetaDataDefinition = PageMetaDataFacade.GetMetaDataDefinition(GetCurrentPageId(), metaDataPair.First); this.UpdateBinding("Label", pageMetaDataDefinition.Label); List<KeyValuePair<Guid, string>> containers = PageMetaDataFacade.GetAllMetaDataContainers(); this.UpdateBinding("MetaDataContainerOptions", containers); this.UpdateBinding("SelectedMetaDataContainer", pageMetaDataDefinition.MetaDataContainerId); IPage page = GetCurrentPage(); Dictionary<int, string> startDisplayOptions = new Dictionary<int, string>(); if (page != null) { startDisplayOptions.Add(0, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.StartDisplayOption0")); } startDisplayOptions.Add(1, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.StartDisplayOption1")); startDisplayOptions.Add(2, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.StartDisplayOption2")); startDisplayOptions.Add(3, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.StartDisplayOption3")); startDisplayOptions.Add(4, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.StartDisplayOption4")); startDisplayOptions.Add(5, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.StartDisplayOption5")); this.UpdateBinding("StartDisplayOptions", startDisplayOptions); this.UpdateBinding("SelectedStartDisplay", pageMetaDataDefinition.StartLevel); int levels = pageMetaDataDefinition.Levels; if (levels > 10) levels = 10000; Dictionary<int, string> inheritDisplayOptions = new Dictionary<int, string>(); inheritDisplayOptions.Add(0, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.InheritDisplayOption0")); inheritDisplayOptions.Add(1, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.InheritDisplayOption1")); inheritDisplayOptions.Add(2, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.InheritDisplayOption2")); inheritDisplayOptions.Add(3, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.InheritDisplayOption3")); inheritDisplayOptions.Add(10000, StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataWorkflow.InheritDisplayOption4")); this.UpdateBinding("InheritDisplayOptions", inheritDisplayOptions); this.UpdateBinding("SelectedInheritDisplay", levels); } private void collectDefaultValuesCodeActivity_ShowWizzard_ExecuteCode(object sender, EventArgs e) { Pair<string, Type> metaDataPair = this.GetBinding<Pair<string, Type>>("SelectedMetaDataDefinition"); DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(metaDataPair.Second); Type metaDataType = TypeManager.GetType(dataTypeDescriptor.TypeManagerTypeName); DataTypeDescriptorFormsHelper helper = new DataTypeDescriptorFormsHelper(dataTypeDescriptor); helper.LayoutLabel = StringResourceSystemFacade.GetString("Composite.Plugins.PageTypeElementProvider", "PageType.AddPageTypeMetaDataFieldWorkflow.AddingDefaultMetaData.Title"); helper.LayoutIconHandle = "pagetype-add-metedatafield"; GeneratedTypesHelper generatedTypesHelper = new GeneratedTypesHelper(dataTypeDescriptor); helper.AddReadOnlyFields(generatedTypesHelper.NotEditableDataFieldDescriptorNames); IData newDataTemplate = DataFacade.BuildNew(metaDataType); helper.UpdateWithNewBindings(this.Bindings); helper.ObjectToBindings(newDataTemplate, this.Bindings); this.UpdateBinding("NewDataTemplate", newDataTemplate); this.DeliverFormData( metaDataType.GetTypeTitle(), StandardUiContainerTypes.Wizard, helper.GetForm(), this.Bindings, helper.GetBindingsValidationRules(newDataTemplate) ); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { List<Guid> oldPageIds = GetOldAffectedPageIds(); List<Guid> newPageIds = GetNewAffectedPageIds(); Pair<string, Type> metaDataPair = this.GetBinding<Pair<string, Type>>("SelectedMetaDataDefinition"); Guid newMetaDataContainerId = this.GetBinding<Guid>("SelectedMetaDataContainer"); string newLabel = this.GetBinding<string>("Label"); int startLevel = this.GetBinding<int>("SelectedStartDisplay"); int levels = this.GetBinding<int>("SelectedInheritDisplay"); PageMetaDataFacade.UpdateDefinition(GetCurrentPageId(), metaDataPair.First, newLabel, startLevel, levels, newMetaDataContainerId); IEnumerable<Guid> oldPageIdsToRemove = oldPageIds.Except(newPageIds); foreach (Guid id in oldPageIdsToRemove) { IPage page = Composite.Data.PageManager.GetPageById(id); bool otherDefinitionExists = page.GetAllowedMetaDataDefinitions().Where(f => f.Name == metaDataPair.First).Any(); if (otherDefinitionExists) continue; using (new DataScope(DataScopeIdentifier.Public)) { IData dataToDelete = page.GetMetaData(metaDataPair.First, metaDataPair.Second); if (dataToDelete != null) { DataFacade.Delete(dataToDelete); } } using (new DataScope(DataScopeIdentifier.Administrated)) { IData dataToDelete = page.GetMetaData(metaDataPair.First, metaDataPair.Second); if (dataToDelete != null) { DataFacade.Delete(dataToDelete); } } } IData newDataTemplate = null; if (this.BindingExist("NewDataTemplate")) { newDataTemplate = this.GetBinding<IData>("NewDataTemplate"); DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(metaDataPair.Second.GetImmutableTypeId()); DataTypeDescriptorFormsHelper helper = new DataTypeDescriptorFormsHelper(dataTypeDescriptor); helper.BindingsToObject(this.Bindings, newDataTemplate); } IEnumerable<Guid> newPageIdsToAdd = newPageIds.Except(oldPageIds); foreach (Guid id in newPageIdsToAdd) { IPage page = Composite.Data.PageManager.GetPageById(id); page.AddNewMetaDataToExistingPage(metaDataPair.First, metaDataPair.Second, newDataTemplate); } transactionScope.Complete(); } } } } ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/EditMetaDataWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper { partial class EditMetaDataWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition3 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity15 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity14 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity16 = new System.Workflow.Activities.SetStateActivity(); this.editDefinitionIfElseActivity_AffectedPagesExists = new System.Workflow.Activities.IfElseActivity(); this.initializeCodeActivity_ShowNoDefinedDefinitionsMessage = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_UpdateBindings = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity6 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity5 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity11 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity5 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity12 = new System.Workflow.Activities.SetStateActivity(); this.previousHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.PreviousHandleExternalEventActivity(); this.setStateActivity13 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizardFormActivity3 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity4 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.previousHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.PreviousHandleExternalEventActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.collectDefaultValuesCodeActivity_ShowWizzard = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.previousHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.PreviousHandleExternalEventActivity(); this.editIfElseActivity_ValidateNewBinding = new System.Workflow.Activities.IfElseActivity(); this.nextHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.wizardFormActivity2 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.editDefinitionCodeActivity_UpdateBindings = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.nextHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.wizardFormActivity1 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.initializeIfElseActivity_DefinedDefintionsExists = new System.Workflow.Activities.IfElseActivity(); this.noDefaultValuesNeededEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.noDefaultValuesNeededEventDrivenActivity_Previous = new System.Workflow.Activities.EventDrivenActivity(); this.noDefaultValuesNeededEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.noDefaultValuesNeededStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.colectDefaultValuesEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.colectDefaultValuesEventDrivenActivity_Previous = new System.Workflow.Activities.EventDrivenActivity(); this.colectDefaultValuesEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.colectDefaultValuesStateInitializationActivity3 = new System.Workflow.Activities.StateInitializationActivity(); this.editDefinitionEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.editDefinitionEventDrivenActivity_Previous = new System.Workflow.Activities.EventDrivenActivity(); this.editDefinitionEventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.editDefinitionStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.selectDefinitionEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.selectDefinitionEventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.selectDefinitionStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.noDefaultDataNeededStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.colectDefaultValuesStateActivity3 = new System.Workflow.Activities.StateActivity(); this.editDefinitionStateActivity2 = new System.Workflow.Activities.StateActivity(); this.selectDefinitionStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity15 // this.setStateActivity15.Name = "setStateActivity15"; this.setStateActivity15.TargetStateName = "noDefaultDataNeededStateActivity"; // // setStateActivity14 // this.setStateActivity14.Name = "setStateActivity14"; this.setStateActivity14.TargetStateName = "colectDefaultValuesStateActivity3"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity15); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity14); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.AffectedPagesExists); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity16 // this.setStateActivity16.Name = "setStateActivity16"; this.setStateActivity16.TargetStateName = "colectDefaultValuesStateActivity3"; // // editDefinitionIfElseActivity_AffectedPagesExists // this.editDefinitionIfElseActivity_AffectedPagesExists.Activities.Add(this.ifElseBranchActivity1); this.editDefinitionIfElseActivity_AffectedPagesExists.Activities.Add(this.ifElseBranchActivity2); this.editDefinitionIfElseActivity_AffectedPagesExists.Name = "editDefinitionIfElseActivity_AffectedPagesExists"; // // initializeCodeActivity_ShowNoDefinedDefinitionsMessage // this.initializeCodeActivity_ShowNoDefinedDefinitionsMessage.Name = "initializeCodeActivity_ShowNoDefinedDefinitionsMessage"; this.initializeCodeActivity_ShowNoDefinedDefinitionsMessage.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ShowNoDefinedDefinitionsMessage_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "selectDefinitionStateActivity"; // // initializeCodeActivity_UpdateBindings // this.initializeCodeActivity_UpdateBindings.Name = "initializeCodeActivity_UpdateBindings"; this.initializeCodeActivity_UpdateBindings.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_UpdateBindings_ExecuteCode); // // ifElseBranchActivity6 // this.ifElseBranchActivity6.Activities.Add(this.setStateActivity16); this.ifElseBranchActivity6.Name = "ifElseBranchActivity6"; // // ifElseBranchActivity5 // this.ifElseBranchActivity5.Activities.Add(this.editDefinitionIfElseActivity_AffectedPagesExists); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateNewDefinition); this.ifElseBranchActivity5.Condition = codecondition2; this.ifElseBranchActivity5.Name = "ifElseBranchActivity5"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.initializeCodeActivity_ShowNoDefinedDefinitionsMessage); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.initializeCodeActivity_UpdateBindings); this.ifElseBranchActivity3.Activities.Add(this.setStateActivity2); codecondition3.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DefinedDefinitionsExists); this.ifElseBranchActivity3.Condition = codecondition3; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // setStateActivity11 // this.setStateActivity11.Name = "setStateActivity11"; this.setStateActivity11.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity5 // this.cancelHandleExternalEventActivity5.EventName = "Cancel"; this.cancelHandleExternalEventActivity5.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity5.Name = "cancelHandleExternalEventActivity5"; // // setStateActivity12 // this.setStateActivity12.Name = "setStateActivity12"; this.setStateActivity12.TargetStateName = "editDefinitionStateActivity2"; // // previousHandleExternalEventActivity3 // this.previousHandleExternalEventActivity3.EventName = "Previous"; this.previousHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.previousHandleExternalEventActivity3.Name = "previousHandleExternalEventActivity3"; // // setStateActivity13 // this.setStateActivity13.Name = "setStateActivity13"; this.setStateActivity13.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // wizardFormActivity3 // this.wizardFormActivity3.ContainerLabel = null; this.wizardFormActivity3.FormDefinitionFileName = "/Administrative/EditMetaData_NoDefaultValuesNeeded.xml"; this.wizardFormActivity3.Name = "wizardFormActivity3"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity4 // this.cancelHandleExternalEventActivity4.EventName = "Cancel"; this.cancelHandleExternalEventActivity4.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity4.Name = "cancelHandleExternalEventActivity4"; // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "editDefinitionStateActivity2"; // // previousHandleExternalEventActivity2 // this.previousHandleExternalEventActivity2.EventName = "Previous"; this.previousHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.previousHandleExternalEventActivity2.Name = "previousHandleExternalEventActivity2"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // collectDefaultValuesCodeActivity_ShowWizzard // this.collectDefaultValuesCodeActivity_ShowWizzard.Name = "collectDefaultValuesCodeActivity_ShowWizzard"; this.collectDefaultValuesCodeActivity_ShowWizzard.ExecuteCode += new System.EventHandler(this.collectDefaultValuesCodeActivity_ShowWizzard_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "selectDefinitionStateActivity"; // // previousHandleExternalEventActivity1 // this.previousHandleExternalEventActivity1.EventName = "Previous"; this.previousHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.previousHandleExternalEventActivity1.Name = "previousHandleExternalEventActivity1"; // // editIfElseActivity_ValidateNewBinding // this.editIfElseActivity_ValidateNewBinding.Activities.Add(this.ifElseBranchActivity5); this.editIfElseActivity_ValidateNewBinding.Activities.Add(this.ifElseBranchActivity6); this.editIfElseActivity_ValidateNewBinding.Name = "editIfElseActivity_ValidateNewBinding"; // // nextHandleExternalEventActivity2 // this.nextHandleExternalEventActivity2.EventName = "Next"; this.nextHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity2.Name = "nextHandleExternalEventActivity2"; // // wizardFormActivity2 // this.wizardFormActivity2.ContainerLabel = null; this.wizardFormActivity2.FormDefinitionFileName = "/Administrative/EditMetaData_EditDefinition.xml"; this.wizardFormActivity2.Name = "wizardFormActivity2"; // // editDefinitionCodeActivity_UpdateBindings // this.editDefinitionCodeActivity_UpdateBindings.Name = "editDefinitionCodeActivity_UpdateBindings"; this.editDefinitionCodeActivity_UpdateBindings.ExecuteCode += new System.EventHandler(this.editDefinitionCodeActivity_UpdateBindings_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "editDefinitionStateActivity2"; // // nextHandleExternalEventActivity1 // this.nextHandleExternalEventActivity1.EventName = "Next"; this.nextHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity1.Name = "nextHandleExternalEventActivity1"; // // wizardFormActivity1 // this.wizardFormActivity1.ContainerLabel = null; this.wizardFormActivity1.FormDefinitionFileName = "/Administrative/EditMetaData_SelectDefinition.xml"; this.wizardFormActivity1.Name = "wizardFormActivity1"; // // initializeIfElseActivity_DefinedDefintionsExists // this.initializeIfElseActivity_DefinedDefintionsExists.Activities.Add(this.ifElseBranchActivity3); this.initializeIfElseActivity_DefinedDefintionsExists.Activities.Add(this.ifElseBranchActivity4); this.initializeIfElseActivity_DefinedDefintionsExists.Name = "initializeIfElseActivity_DefinedDefintionsExists"; // // noDefaultValuesNeededEventDrivenActivity_Cancel // this.noDefaultValuesNeededEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity5); this.noDefaultValuesNeededEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity11); this.noDefaultValuesNeededEventDrivenActivity_Cancel.Name = "noDefaultValuesNeededEventDrivenActivity_Cancel"; // // noDefaultValuesNeededEventDrivenActivity_Previous // this.noDefaultValuesNeededEventDrivenActivity_Previous.Activities.Add(this.previousHandleExternalEventActivity3); this.noDefaultValuesNeededEventDrivenActivity_Previous.Activities.Add(this.setStateActivity12); this.noDefaultValuesNeededEventDrivenActivity_Previous.Name = "noDefaultValuesNeededEventDrivenActivity_Previous"; // // noDefaultValuesNeededEventDrivenActivity_Finish // this.noDefaultValuesNeededEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.noDefaultValuesNeededEventDrivenActivity_Finish.Activities.Add(this.setStateActivity13); this.noDefaultValuesNeededEventDrivenActivity_Finish.Name = "noDefaultValuesNeededEventDrivenActivity_Finish"; // // noDefaultValuesNeededStateInitializationActivity // this.noDefaultValuesNeededStateInitializationActivity.Activities.Add(this.wizardFormActivity3); this.noDefaultValuesNeededStateInitializationActivity.Name = "noDefaultValuesNeededStateInitializationActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity7); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // colectDefaultValuesEventDrivenActivity_Cancel // this.colectDefaultValuesEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity4); this.colectDefaultValuesEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity5); this.colectDefaultValuesEventDrivenActivity_Cancel.Name = "colectDefaultValuesEventDrivenActivity_Cancel"; // // colectDefaultValuesEventDrivenActivity_Previous // this.colectDefaultValuesEventDrivenActivity_Previous.Activities.Add(this.previousHandleExternalEventActivity2); this.colectDefaultValuesEventDrivenActivity_Previous.Activities.Add(this.setStateActivity10); this.colectDefaultValuesEventDrivenActivity_Previous.Name = "colectDefaultValuesEventDrivenActivity_Previous"; // // colectDefaultValuesEventDrivenActivity_Finish // this.colectDefaultValuesEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.colectDefaultValuesEventDrivenActivity_Finish.Activities.Add(this.setStateActivity6); this.colectDefaultValuesEventDrivenActivity_Finish.Name = "colectDefaultValuesEventDrivenActivity_Finish"; // // colectDefaultValuesStateInitializationActivity3 // this.colectDefaultValuesStateInitializationActivity3.Activities.Add(this.collectDefaultValuesCodeActivity_ShowWizzard); this.colectDefaultValuesStateInitializationActivity3.Name = "colectDefaultValuesStateInitializationActivity3"; // // editDefinitionEventDrivenActivity_Cancel // this.editDefinitionEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.editDefinitionEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity3); this.editDefinitionEventDrivenActivity_Cancel.Name = "editDefinitionEventDrivenActivity_Cancel"; // // editDefinitionEventDrivenActivity_Previous // this.editDefinitionEventDrivenActivity_Previous.Activities.Add(this.previousHandleExternalEventActivity1); this.editDefinitionEventDrivenActivity_Previous.Activities.Add(this.setStateActivity8); this.editDefinitionEventDrivenActivity_Previous.Name = "editDefinitionEventDrivenActivity_Previous"; // // editDefinitionEventDrivenActivity_Next // this.editDefinitionEventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity2); this.editDefinitionEventDrivenActivity_Next.Activities.Add(this.editIfElseActivity_ValidateNewBinding); this.editDefinitionEventDrivenActivity_Next.Name = "editDefinitionEventDrivenActivity_Next"; // // editDefinitionStateInitializationActivity // this.editDefinitionStateInitializationActivity.Activities.Add(this.editDefinitionCodeActivity_UpdateBindings); this.editDefinitionStateInitializationActivity.Activities.Add(this.wizardFormActivity2); this.editDefinitionStateInitializationActivity.Name = "editDefinitionStateInitializationActivity"; // // selectDefinitionEventDrivenActivity_Cancel // this.selectDefinitionEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.selectDefinitionEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity4); this.selectDefinitionEventDrivenActivity_Cancel.Name = "selectDefinitionEventDrivenActivity_Cancel"; // // selectDefinitionEventDrivenActivity_Next // this.selectDefinitionEventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity1); this.selectDefinitionEventDrivenActivity_Next.Activities.Add(this.setStateActivity9); this.selectDefinitionEventDrivenActivity_Next.Name = "selectDefinitionEventDrivenActivity_Next"; // // selectDefinitionStateInitializationActivity // this.selectDefinitionStateInitializationActivity.Activities.Add(this.wizardFormActivity1); this.selectDefinitionStateInitializationActivity.Name = "selectDefinitionStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeIfElseActivity_DefinedDefintionsExists); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // noDefaultDataNeededStateActivity // this.noDefaultDataNeededStateActivity.Activities.Add(this.noDefaultValuesNeededStateInitializationActivity); this.noDefaultDataNeededStateActivity.Activities.Add(this.noDefaultValuesNeededEventDrivenActivity_Finish); this.noDefaultDataNeededStateActivity.Activities.Add(this.noDefaultValuesNeededEventDrivenActivity_Previous); this.noDefaultDataNeededStateActivity.Activities.Add(this.noDefaultValuesNeededEventDrivenActivity_Cancel); this.noDefaultDataNeededStateActivity.Name = "noDefaultDataNeededStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // colectDefaultValuesStateActivity3 // this.colectDefaultValuesStateActivity3.Activities.Add(this.colectDefaultValuesStateInitializationActivity3); this.colectDefaultValuesStateActivity3.Activities.Add(this.colectDefaultValuesEventDrivenActivity_Finish); this.colectDefaultValuesStateActivity3.Activities.Add(this.colectDefaultValuesEventDrivenActivity_Previous); this.colectDefaultValuesStateActivity3.Activities.Add(this.colectDefaultValuesEventDrivenActivity_Cancel); this.colectDefaultValuesStateActivity3.Name = "colectDefaultValuesStateActivity3"; // // editDefinitionStateActivity2 // this.editDefinitionStateActivity2.Activities.Add(this.editDefinitionStateInitializationActivity); this.editDefinitionStateActivity2.Activities.Add(this.editDefinitionEventDrivenActivity_Next); this.editDefinitionStateActivity2.Activities.Add(this.editDefinitionEventDrivenActivity_Previous); this.editDefinitionStateActivity2.Activities.Add(this.editDefinitionEventDrivenActivity_Cancel); this.editDefinitionStateActivity2.Name = "editDefinitionStateActivity2"; // // selectDefinitionStateActivity // this.selectDefinitionStateActivity.Activities.Add(this.selectDefinitionStateInitializationActivity); this.selectDefinitionStateActivity.Activities.Add(this.selectDefinitionEventDrivenActivity_Next); this.selectDefinitionStateActivity.Activities.Add(this.selectDefinitionEventDrivenActivity_Cancel); this.selectDefinitionStateActivity.Name = "selectDefinitionStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // EditMetaDataWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.selectDefinitionStateActivity); this.Activities.Add(this.editDefinitionStateActivity2); this.Activities.Add(this.colectDefaultValuesStateActivity3); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.noDefaultDataNeededStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "EditMetaDataWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private CodeActivity initializeCodeActivity_UpdateBindings; private SetStateActivity setStateActivity11; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity5; private SetStateActivity setStateActivity12; private C1Console.Workflow.Activities.PreviousHandleExternalEventActivity previousHandleExternalEventActivity3; private SetStateActivity setStateActivity13; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private SetStateActivity setStateActivity7; private SetStateActivity setStateActivity5; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity4; private SetStateActivity setStateActivity10; private C1Console.Workflow.Activities.PreviousHandleExternalEventActivity previousHandleExternalEventActivity2; private SetStateActivity setStateActivity6; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private SetStateActivity setStateActivity8; private C1Console.Workflow.Activities.PreviousHandleExternalEventActivity previousHandleExternalEventActivity1; private C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity2; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity9; private C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity noDefaultValuesNeededEventDrivenActivity_Cancel; private EventDrivenActivity noDefaultValuesNeededEventDrivenActivity_Previous; private EventDrivenActivity noDefaultValuesNeededEventDrivenActivity_Finish; private StateInitializationActivity noDefaultValuesNeededStateInitializationActivity; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity colectDefaultValuesEventDrivenActivity_Cancel; private EventDrivenActivity colectDefaultValuesEventDrivenActivity_Previous; private EventDrivenActivity colectDefaultValuesEventDrivenActivity_Finish; private StateInitializationActivity colectDefaultValuesStateInitializationActivity3; private EventDrivenActivity editDefinitionEventDrivenActivity_Cancel; private EventDrivenActivity editDefinitionEventDrivenActivity_Previous; private EventDrivenActivity editDefinitionEventDrivenActivity_Next; private StateInitializationActivity editDefinitionStateInitializationActivity; private EventDrivenActivity selectDefinitionEventDrivenActivity_Cancel; private EventDrivenActivity selectDefinitionEventDrivenActivity_Next; private StateInitializationActivity selectDefinitionStateInitializationActivity; private StateActivity noDefaultDataNeededStateActivity; private StateActivity finalizeStateActivity; private StateActivity colectDefaultValuesStateActivity3; private StateActivity editDefinitionStateActivity2; private StateActivity selectDefinitionStateActivity; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity editDefinitionIfElseActivity_AffectedPagesExists; private SetStateActivity setStateActivity15; private SetStateActivity setStateActivity14; private CodeActivity initializeCodeActivity_ShowNoDefinedDefinitionsMessage; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private C1Console.Workflow.Activities.WizardFormActivity wizardFormActivity1; private IfElseActivity initializeIfElseActivity_DefinedDefintionsExists; private C1Console.Workflow.Activities.WizardFormActivity wizardFormActivity3; private CodeActivity collectDefaultValuesCodeActivity_ShowWizzard; private C1Console.Workflow.Activities.WizardFormActivity wizardFormActivity2; private CodeActivity finalizeCodeActivity_Finalize; private CodeActivity editDefinitionCodeActivity_UpdateBindings; private SetStateActivity setStateActivity16; private IfElseBranchActivity ifElseBranchActivity6; private IfElseBranchActivity ifElseBranchActivity5; private IfElseActivity editIfElseActivity_ValidateNewBinding; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Elements/ElementProviderHelpers/AssociatedDataElementProviderHelper/EditMetaDataWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1190; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="EditMetaDataWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="381; 363" Location="98; 169"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="initializeIfElseActivity_DefinedDefintionsExists" Size="361; 282" Location="108; 231"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity3" Size="150; 182" Location="127; 302"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_UpdateBindings" Size="130; 41" Location="137; 364" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="137; 424" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity4" Size="150; 182" Location="300; 302"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_ShowNoDefinedDefinitionsMessage" Size="130; 41" Location="310; 394" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="260; 102" AutoSizeMargin="16; 24" Location="192; 335" Name="selectDefinitionStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="selectDefinitionStateInitializationActivity" Size="150; 122" Location="200; 366"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizardFormActivity1" Size="130; 41" Location="210; 428" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="selectDefinitionEventDrivenActivity_Next" Size="150; 182" Location="200; 390"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="nextHandleExternalEventActivity1" Size="130; 41" Location="210; 452" /> <SetStateDesigner Name="setStateActivity9" Size="130; 41" Location="210; 512" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="selectDefinitionEventDrivenActivity_Cancel" Size="150; 182" Location="200; 414"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="210; 476" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="210; 536" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="259; 126" AutoSizeMargin="16; 24" AutoSize="False" Location="576; 336" Name="editDefinitionStateActivity2"> <StateDesigner.Designers> <StateInitializationDesigner Name="editDefinitionStateInitializationActivity" Size="150; 182" Location="311; 135"> <StateInitializationDesigner.Designers> <CodeDesigner Name="editDefinitionCodeActivity_UpdateBindings" Size="130; 41" Location="321; 197" /> <ActivityDesigner Name="wizardFormActivity2" Size="130; 41" Location="321; 257" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="editDefinitionEventDrivenActivity_Next" Size="612; 556" Location="319; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="nextHandleExternalEventActivity2" Size="130; 41" Location="560; 210" /> <IfElseDesigner Name="editIfElseActivity_ValidateNewBinding" Size="592; 415" Location="329; 270"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity5" Size="381; 315" Location="348; 341"> <IfElseBranchDesigner.Designers> <IfElseDesigner Name="editDefinitionIfElseActivity_AffectedPagesExists" Size="361; 234" Location="358; 403"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 134" Location="377; 474"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity14" Size="130; 53" Location="387; 536" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 134" Location="550; 474"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity15" Size="130; 53" Location="560; 536" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity6" Size="150; 315" Location="752; 341"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity16" Size="130; 53" Location="762; 494" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="editDefinitionEventDrivenActivity_Previous" Size="150; 182" Location="311; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="previousHandleExternalEventActivity1" Size="130; 41" Location="321; 245" /> <SetStateDesigner Name="setStateActivity8" Size="130; 41" Location="321; 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="editDefinitionEventDrivenActivity_Cancel" Size="150; 182" Location="311; 207"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity3" Size="130; 41" Location="321; 269" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="321; 329" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="290; 126" AutoSizeMargin="16; 24" AutoSize="False" Location="109; 607" Name="colectDefaultValuesStateActivity3"> <StateDesigner.Designers> <StateInitializationDesigner Name="colectDefaultValuesStateInitializationActivity3" Size="150; 122" Location="117; 638"> <StateInitializationDesigner.Designers> <CodeDesigner Name="collectDefaultValuesCodeActivity_ShowWizzard" Size="130; 41" Location="127; 700" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="colectDefaultValuesEventDrivenActivity_Finish" Size="150; 182" Location="117; 662"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="127; 724" /> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="127; 784" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="colectDefaultValuesEventDrivenActivity_Previous" Size="150; 194" Location="117; 686"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="previousHandleExternalEventActivity2" Size="130; 41" Location="127; 748" /> <SetStateDesigner Name="setStateActivity10" Size="130; 53" Location="127; 808" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="colectDefaultValuesEventDrivenActivity_Cancel" Size="150; 182" Location="117; 710"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity4" Size="130; 41" Location="127; 772" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="127; 832" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 102" AutoSizeMargin="16; 24" Location="611; 816" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 182" Location="619; 847"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity_Finalize" Size="130; 41" Location="629; 909" /> <SetStateDesigner Name="setStateActivity7" Size="130; 41" Location="629; 969" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="312; 126" AutoSizeMargin="16; 24" Location="854; 533" Name="noDefaultDataNeededStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="noDefaultValuesNeededStateInitializationActivity" Size="150; 122" Location="862; 564"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizardFormActivity3" Size="130; 41" Location="872; 626" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="noDefaultValuesNeededEventDrivenActivity_Finish" Size="150; 194" Location="862; 588"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity2" Size="130; 41" Location="872; 650" /> <SetStateDesigner Name="setStateActivity13" Size="130; 53" Location="872; 710" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="noDefaultValuesNeededEventDrivenActivity_Previous" Size="150; 194" Location="862; 612"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="previousHandleExternalEventActivity3" Size="130; 41" Location="872; 674" /> <SetStateDesigner Name="setStateActivity12" Size="130; 53" Location="872; 734" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="noDefaultValuesNeededEventDrivenActivity_Cancel" Size="150; 194" Location="862; 636"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity5" Size="130; 41" Location="872; 698" /> <SetStateDesigner Name="setStateActivity11" Size="130; 53" Location="872; 758" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="EditMetaDataWorkflow" TargetConnectionIndex="0" SourceStateName="EditMetaDataWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1179" Y="71" /> <ns0:Point X="1179" Y="730" /> <ns0:Point X="1058" Y="730" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="selectDefinitionStateActivity" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="selectDefinitionStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="322" Y="179" /> <ns0:Point X="322" Y="335" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editDefinitionStateActivity2" SetStateName="setStateActivity9" SourceActivity="selectDefinitionStateActivity" TargetConnectionIndex="0" SourceStateName="selectDefinitionStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="selectDefinitionEventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="editDefinitionStateActivity2"> <StateDesignerConnector.Segments> <ns0:Point X="438" Y="400" /> <ns0:Point X="464" Y="400" /> <ns0:Point X="464" Y="328" /> <ns0:Point X="705" Y="328" /> <ns0:Point X="705" Y="336" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity4" SourceActivity="selectDefinitionStateActivity" TargetConnectionIndex="0" SourceStateName="selectDefinitionStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="selectDefinitionEventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="448" Y="424" /> <ns0:Point X="522" Y="424" /> <ns0:Point X="522" Y="786" /> <ns0:Point X="1058" Y="786" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="colectDefaultValuesStateActivity3" SetStateName="setStateActivity14" SourceActivity="editDefinitionStateActivity2" TargetConnectionIndex="0" SourceStateName="editDefinitionStateActivity2" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editDefinitionEventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="colectDefaultValuesStateActivity3"> <StateDesignerConnector.Segments> <ns0:Point X="812" Y="401" /> <ns0:Point X="846" Y="401" /> <ns0:Point X="846" Y="595" /> <ns0:Point X="254" Y="595" /> <ns0:Point X="254" Y="607" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="noDefaultDataNeededStateActivity" SetStateName="setStateActivity15" SourceActivity="editDefinitionStateActivity2" TargetConnectionIndex="0" SourceStateName="editDefinitionStateActivity2" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editDefinitionEventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="noDefaultDataNeededStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="812" Y="401" /> <ns0:Point X="1010" Y="401" /> <ns0:Point X="1010" Y="533" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="selectDefinitionStateActivity" SetStateName="setStateActivity8" SourceActivity="editDefinitionStateActivity2" TargetConnectionIndex="0" SourceStateName="editDefinitionStateActivity2" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editDefinitionEventDrivenActivity_Previous" SourceConnectionIndex="2" TargetStateName="selectDefinitionStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="831" Y="425" /> <ns0:Point X="842" Y="425" /> <ns0:Point X="842" Y="327" /> <ns0:Point X="322" Y="327" /> <ns0:Point X="322" Y="335" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity3" SourceActivity="editDefinitionStateActivity2" TargetConnectionIndex="0" SourceStateName="editDefinitionStateActivity2" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editDefinitionEventDrivenActivity_Cancel" SourceConnectionIndex="3" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="822" Y="449" /> <ns0:Point X="1180" Y="449" /> <ns0:Point X="1180" Y="711" /> <ns0:Point X="1058" Y="711" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity6" SourceActivity="colectDefaultValuesStateActivity3" TargetConnectionIndex="0" SourceStateName="colectDefaultValuesStateActivity3" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="colectDefaultValuesEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="382" Y="672" /> <ns0:Point X="713" Y="672" /> <ns0:Point X="713" Y="816" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editDefinitionStateActivity2" SetStateName="setStateActivity10" SourceActivity="colectDefaultValuesStateActivity3" TargetConnectionIndex="0" SourceStateName="colectDefaultValuesStateActivity3" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="colectDefaultValuesEventDrivenActivity_Previous" SourceConnectionIndex="2" TargetStateName="editDefinitionStateActivity2"> <StateDesignerConnector.Segments> <ns0:Point X="395" Y="696" /> <ns0:Point X="841" Y="696" /> <ns0:Point X="841" Y="328" /> <ns0:Point X="705" Y="328" /> <ns0:Point X="705" Y="336" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity5" SourceActivity="colectDefaultValuesStateActivity3" TargetConnectionIndex="0" SourceStateName="colectDefaultValuesStateActivity3" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="colectDefaultValuesEventDrivenActivity_Cancel" SourceConnectionIndex="3" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="386" Y="720" /> <ns0:Point X="1058" Y="720" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity7" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="812" Y="857" /> <ns0:Point X="828" Y="857" /> <ns0:Point X="828" Y="790" /> <ns0:Point X="1058" Y="790" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity13" SourceActivity="noDefaultDataNeededStateActivity" TargetConnectionIndex="0" SourceStateName="noDefaultDataNeededStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="noDefaultValuesNeededEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="1149" Y="598" /> <ns0:Point X="1177" Y="598" /> <ns0:Point X="1177" Y="786" /> <ns0:Point X="713" Y="786" /> <ns0:Point X="713" Y="816" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editDefinitionStateActivity2" SetStateName="setStateActivity12" SourceActivity="noDefaultDataNeededStateActivity" TargetConnectionIndex="0" SourceStateName="noDefaultDataNeededStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="noDefaultValuesNeededEventDrivenActivity_Previous" SourceConnectionIndex="2" TargetStateName="editDefinitionStateActivity2"> <StateDesignerConnector.Segments> <ns0:Point X="1162" Y="622" /> <ns0:Point X="1177" Y="622" /> <ns0:Point X="1177" Y="328" /> <ns0:Point X="705" Y="328" /> <ns0:Point X="705" Y="336" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity11" SourceActivity="noDefaultDataNeededStateActivity" TargetConnectionIndex="0" SourceStateName="noDefaultDataNeededStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="noDefaultValuesNeededEventDrivenActivity_Cancel" SourceConnectionIndex="3" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="1153" Y="646" /> <ns0:Point X="1178" Y="646" /> <ns0:Point X="1178" Y="786" /> <ns0:Point X="1058" Y="786" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Events/Workflows/UserConsoleInformationScavengerWorkflow.cs ================================================ using System; using System.Web.Hosting; using System.Workflow.Activities; using Composite.Core.Extensions; using Composite.Core.Configuration; using Composite.Core.Threading; namespace Composite.C1Console.Events.Workflows { public sealed partial class UserConsoleInformationScavengerWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public UserConsoleInformationScavengerWorkflow() { InitializeComponent(); } private void OnInitializeTimeout(object sender, EventArgs e) { (sender as DelayActivity).TimeoutDuration = GlobalSettingsFacade.ConsoleTimeout; } private void scavengeCodeActivity_Scavenge_ExecuteCode(object sender, EventArgs e) { if (HostingEnvironment.ApplicationHost.ShutdownInitiated()) { return; } try { using (ThreadDataManager.Initialize()) { ConsoleFacade.Scavenge(); } } catch { // Ignore exceptions } } } } ================================================ FILE: Composite.Workflows/C1Console/Events/Workflows/UserConsoleInformationScavengerWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Events.Workflows { partial class UserConsoleInformationScavengerWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.scavengeCodeActivity_Scavenge = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.delayActivity1 = new System.Workflow.Activities.DelayActivity(); this.scavangeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.waitEventDrivenActivity_Timeout = new System.Workflow.Activities.EventDrivenActivity(); this.waitStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.scavengeStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.waitStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "waitStateActivity"; // // scavengeCodeActivity_Scavenge // this.scavengeCodeActivity_Scavenge.Name = "scavengeCodeActivity_Scavenge"; this.scavengeCodeActivity_Scavenge.ExecuteCode += new System.EventHandler(this.scavengeCodeActivity_Scavenge_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "scavengeStateActivity"; // // delayActivity1 // this.delayActivity1.Name = "delayActivity1"; this.delayActivity1.TimeoutDuration = System.TimeSpan.Parse("00:00:00"); this.delayActivity1.InitializeTimeoutDuration += new System.EventHandler(this.OnInitializeTimeout); // // scavangeStateInitializationActivity // this.scavangeStateInitializationActivity.Activities.Add(this.scavengeCodeActivity_Scavenge); this.scavangeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.scavangeStateInitializationActivity.Name = "scavangeStateInitializationActivity"; // // waitEventDrivenActivity_Timeout // this.waitEventDrivenActivity_Timeout.Activities.Add(this.delayActivity1); this.waitEventDrivenActivity_Timeout.Activities.Add(this.setStateActivity1); this.waitEventDrivenActivity_Timeout.Name = "waitEventDrivenActivity_Timeout"; // // waitStateInitializationActivity // this.waitStateInitializationActivity.Name = "waitStateInitializationActivity"; // // scavengeStateActivity // this.scavengeStateActivity.Activities.Add(this.scavangeStateInitializationActivity); this.scavengeStateActivity.Name = "scavengeStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // waitStateActivity // this.waitStateActivity.Activities.Add(this.waitStateInitializationActivity); this.waitStateActivity.Activities.Add(this.waitEventDrivenActivity_Timeout); this.waitStateActivity.Name = "waitStateActivity"; // // UserConsoleInformationScavengerWorkflow // this.Activities.Add(this.waitStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.scavengeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "waitStateActivity"; this.Name = "UserConsoleInformationScavengerWorkflow"; this.CanModifyActivities = false; } #endregion private StateInitializationActivity waitStateInitializationActivity; private StateActivity finalStateActivity; private DelayActivity delayActivity1; private StateInitializationActivity scavangeStateInitializationActivity; private EventDrivenActivity waitEventDrivenActivity_Timeout; private StateActivity scavengeStateActivity; private CodeActivity scavengeCodeActivity_Scavenge; private SetStateActivity setStateActivity1; private SetStateActivity setStateActivity2; private StateActivity waitStateActivity; } } ================================================ FILE: Composite.Workflows/C1Console/Events/Workflows/UserConsoleInformationScavengerWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="UserConsoleInformationScavengerWorkflow" Location="30; 30" Size="1182; 996" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="scavengeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="waitStateActivity" SourceConnectionEdge="Right" TargetActivity="scavengeStateActivity" SourceActivity="waitStateActivity" EventHandlerName="waitEventDrivenActivity_Timeout"> <StateDesignerConnector.Segments> <ns0:Point X="399" Y="254" /> <ns0:Point X="640" Y="254" /> <ns0:Point X="640" Y="389" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="waitStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="scavengeStateActivity" SourceConnectionEdge="Right" TargetActivity="waitStateActivity" SourceActivity="scavengeStateActivity" EventHandlerName="scavangeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="745" Y="430" /> <ns0:Point X="761" Y="430" /> <ns0:Point X="761" Y="181" /> <ns0:Point X="297" Y="181" /> <ns0:Point X="297" Y="189" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="waitStateActivity" Location="191; 189" Size="212; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 109" Name="waitStateInitializationActivity" Location="199; 220" /> <EventDrivenDesigner Size="150; 182" Name="waitEventDrivenActivity_Timeout" Location="199; 244"> <EventDrivenDesigner.Designers> <DelayDesigner Size="130; 41" Name="delayActivity1" Location="209; 306" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="209; 366" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="scavengeStateActivity" Location="532; 389" Size="217; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="scavangeStateInitializationActivity" Location="540; 420"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="scavengeCodeActivity_Scavenge" Location="550; 482" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="550; 542" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Scheduling/BaseSchedulerWorkflow.cs ================================================ using System; using System.ComponentModel; using System.Workflow.Activities; using Composite.C1Console.Workflow; using Composite.Core; using Composite.Core.Threading; namespace Composite.C1Console.Scheduling { [AllowPersistingWorkflow(WorkflowPersistingType.Shutdown)] public abstract partial class BaseSchedulerWorkflow : StateMachineWorkflowActivity { private static readonly string LogTitle = typeof(BaseSchedulerWorkflow).Name; [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DateTime Date { get; set; } [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string LocaleName { get; set; } protected BaseSchedulerWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { var delayActivity = (DelayActivity)GetActivityByName("waitDelayActivity"); var now = DateTime.Now; Log.LogVerbose(LogTitle, "Current time: {0}, Execution time: {1}", Date, now); delayActivity.TimeoutDuration = Date > now ? Date - now : new TimeSpan(0); Log.LogVerbose(LogTitle, "Timeout in: " + delayActivity.TimeoutDuration); } private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { using (ThreadDataManager.Initialize()) using (ServiceLocator.EnsureThreadDataServiceScope()) { Execute(); } } protected abstract void Execute(); } } ================================================ FILE: Composite.Workflows/C1Console/Scheduling/BaseSchedulerWorkflow.designer.cs ================================================ using System.Workflow.Activities; namespace Composite.C1Console.Scheduling { partial class BaseSchedulerWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.waitDelayActivity = new System.Workflow.Activities.DelayActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.waitEventDrivenActivity_Timeout = new System.Workflow.Activities.EventDrivenActivity(); this.waitStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity19 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.waitStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finishState = new System.Workflow.Activities.StateActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finishState"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalizeStateActivity"; // // waitDelayActivity // this.waitDelayActivity.Name = "waitDelayActivity"; this.waitDelayActivity.TimeoutDuration = System.TimeSpan.Parse("00:00:15"); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "waitStateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity3); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // waitEventDrivenActivity_Timeout // this.waitEventDrivenActivity_Timeout.Activities.Add(this.waitDelayActivity); this.waitEventDrivenActivity_Timeout.Activities.Add(this.setStateActivity2); this.waitEventDrivenActivity_Timeout.Name = "waitEventDrivenActivity_Timeout"; // // waitStateInitializationActivity // this.waitStateInitializationActivity.Name = "waitStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity1); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity19 // this.setStateActivity19.Name = "setStateActivity19"; this.setStateActivity19.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // waitStateActivity // this.waitStateActivity.Activities.Add(this.waitStateInitializationActivity); this.waitStateActivity.Activities.Add(this.waitEventDrivenActivity_Timeout); this.waitStateActivity.Name = "waitStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity19); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finishState // this.finishState.Name = "finishState"; // // PagePublishSchedulerWorkflow // this.Activities.Add(this.finishState); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.waitStateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finishState"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "PagePublishSchedulerWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity finishState; private SetStateActivity setStateActivity19; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity waitStateInitializationActivity; private StateInitializationActivity initializeStateInitializationActivity; private StateActivity waitStateActivity; private StateActivity initializeStateActivity; private DelayActivity waitDelayActivity; private SetStateActivity setStateActivity1; private EventDrivenActivity waitEventDrivenActivity_Timeout; private CodeActivity finalizeCodeActivity; private StateInitializationActivity finalizeStateInitializationActivity; private StateActivity finalizeStateActivity; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity2; private CodeActivity initializeCodeActivity; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Scheduling/DataPublishSchedulerWorkflow.cs ================================================ using System; using System.ComponentModel; using System.Globalization; using Composite.C1Console.Security; using Composite.Core; using Composite.Core.Types; using Composite.Data; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.PublishScheduling; using Composite.Data.Transactions; namespace Composite.C1Console.Scheduling { public sealed class DataPublishSchedulerWorkflow : BaseSchedulerWorkflow { private static readonly string LogTitle = typeof(DataPublishSchedulerWorkflow).Name; [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string DataType { get; set; } [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string DataId { get; set; } protected override void Execute() { Type type = TypeManager.GetType(DataType); using (new DataScope(DataScopeIdentifier.Administrated, CultureInfo.CreateSpecificCulture(LocaleName))) { DataEntityToken dataEntityToken; using (var transaction = TransactionsFacade.CreateNewScope()) { var publishSchedule = PublishScheduleHelper.GetPublishSchedule(type, DataId, LocaleName); DataFacade.Delete(publishSchedule); var data = (IPublishControlled)DataFacade.TryGetDataByUniqueKey(type, DataId); if (data == null) { Log.LogWarning(LogTitle, $"Failed to find data of type '{type}' by id '{DataId}'."); transaction.Complete(); return; } dataEntityToken = data.GetDataEntityToken(); var transitions = ProcessControllerFacade.GetValidTransitions(data).Keys; if (transitions.Contains(GenericPublishProcessController.Published)) { data.PublicationStatus = GenericPublishProcessController.Published; DataFacade.Update(data); Log.LogVerbose(LogTitle, $"Scheduled publishing of data with label '{data.GetLabel()}' is complete"); } else { Log.LogWarning(LogTitle, $"Scheduled publishing of data with label '{data.GetLabel()}' could not be done because the data is not in a publisheble state"); } transaction.Complete(); } EntityTokenCacheFacade.ClearCache(dataEntityToken); PublishControlledHelper.ReloadDataElementInConsole(dataEntityToken); } } } } ================================================ FILE: Composite.Workflows/C1Console/Scheduling/DataUnpublishSchedulerWorkflow.cs ================================================ using System.ComponentModel; using System.Globalization; using Composite.C1Console.Security; using Composite.Core; using Composite.Core.Types; using Composite.Data; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.PublishScheduling; using Composite.Data.Transactions; namespace Composite.C1Console.Scheduling { public sealed class DataUnpublishSchedulerWorkflow : BaseSchedulerWorkflow { private static readonly string LogTitle = typeof(DataUnpublishSchedulerWorkflow).Name; [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string DataType { get; set; } [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string DataId { get; set; } protected override void Execute() { var type = TypeManager.GetType(DataType); using (new DataScope(DataScopeIdentifier.Administrated, CultureInfo.CreateSpecificCulture(LocaleName))) { DataEntityToken dataEntityToken; using (var transaction = TransactionsFacade.CreateNewScope()) { var unpublishSchedule = PublishScheduleHelper.GetUnpublishSchedule(type, DataId, LocaleName); Verify.IsNotNull(unpublishSchedule, "Missing an unpublish data schedule record"); DataFacade.Delete(unpublishSchedule); var data = (IPublishControlled)DataFacade.TryGetDataByUniqueKey(type, DataId); if (data == null) { Log.LogWarning(LogTitle, $"Failed to find data of type '{type}' by id '{DataId}'."); transaction.Complete(); return; } var deletePublished = false; dataEntityToken = data.GetDataEntityToken(); var transitions = ProcessControllerFacade.GetValidTransitions(data).Keys; if (transitions.Contains(GenericPublishProcessController.Draft)) { data.PublicationStatus = GenericPublishProcessController.Draft; DataFacade.Update(data); deletePublished = true; } else { Log.LogWarning(LogTitle, $"Scheduled unpublishing of data with label '{data.GetLabel()}' could not be done because the data is not in a unpublisheble state"); } if (deletePublished) { using (new DataScope(DataScopeIdentifier.Public)) { var deletedData = (IPublishControlled)DataFacade.GetDataByUniqueKey(type, DataId); if (deletedData != null) { DataFacade.Delete(deletedData, CascadeDeleteType.Disable); Log.LogVerbose(LogTitle, $"Scheduled unpublishing of data with label '{deletedData.GetLabel()}' is complete"); } } } transaction.Complete(); } EntityTokenCacheFacade.ClearCache(dataEntityToken); PublishControlledHelper.ReloadDataElementInConsole(dataEntityToken); } } } } ================================================ FILE: Composite.Workflows/C1Console/Scheduling/PagePublishSchedulerWorkflow.cs ================================================ using System; using System.ComponentModel; using System.Globalization; using Composite.Data; using Composite.Data.PublishScheduling; using Composite.Data.Types; namespace Composite.C1Console.Scheduling { [Obsolete] public sealed class PagePublishSchedulerWorkflow : BaseSchedulerWorkflow { [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Guid PageId { get; set; } protected override void Execute() { using (new DataScope(DataScopeIdentifier.Administrated, CultureInfo.CreateSpecificCulture(LocaleName))) { var pagePublishSchedule = PublishScheduleHelper.GetPublishSchedule(typeof(IPage), PageId.ToString(), LocaleName); DataFacade.Delete(pagePublishSchedule); // NOTE: publication logic removed } } } } ================================================ FILE: Composite.Workflows/C1Console/Scheduling/PageUnpublishSchedulerWorkflow.cs ================================================ using System; using System.ComponentModel; using System.Globalization; using Composite.Data; using Composite.Data.PublishScheduling; using Composite.Data.Types; namespace Composite.C1Console.Scheduling { [Obsolete] public sealed class PageUnpublishSchedulerWorkflow : BaseSchedulerWorkflow { [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Guid PageId { get; set; } protected override void Execute() { using (new DataScope(DataScopeIdentifier.Administrated, CultureInfo.CreateSpecificCulture(LocaleName))) { var pageUnpublishSchedule = PublishScheduleHelper.GetUnpublishSchedule(typeof (IPage), PageId.ToString(), LocaleName); Verify.IsNotNull(pageUnpublishSchedule, "Missing an unpublish page schedule record."); DataFacade.Delete(pageUnpublishSchedule); // NOTE: Unpublication logic removed } } } } ================================================ FILE: Composite.Workflows/C1Console/Scheduling/PublishControlledHelper.cs ================================================ using System; using System.Collections.Generic; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.Data; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.PublishScheduling; using Composite.Data.Types; using Composite.Plugins.Elements.ElementProviders.PageElementProvider; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Management; namespace Composite.C1Console.Scheduling { public class PublishControlledHelper { public static void HandlePublishUnpublishWorkflows(IData selectedData, string cultureName, DateTime? publishDate, DateTime? unpublishDate, ref WorkflowInstance publishWorkflowInstance, ref WorkflowInstance unpublishWorkflowInstance) { var key = selectedData.GetUniqueKey().ToString(); var existingPublishSchedule = PublishScheduleHelper.GetPublishSchedule(selectedData.DataSourceId.InterfaceType, key, cultureName); if (existingPublishSchedule != null) { WorkflowFacade.AbortWorkflow(existingPublishSchedule.WorkflowInstanceId); DataFacade.Delete(existingPublishSchedule); } if (publishDate != null) { publishWorkflowInstance = WorkflowFacade.CreateNewWorkflow( typeof(DataPublishSchedulerWorkflow), new Dictionary<string, object> { { "Date", publishDate }, { "DataType", selectedData.DataSourceId.InterfaceType.FullName }, { "DataId", selectedData.GetUniqueKey().ToString() }, { "LocaleName", cultureName } } ); PublishScheduleHelper.CreatePublishSchedule(selectedData.DataSourceId.InterfaceType, selectedData.GetUniqueKey().ToString(), cultureName, publishDate.Value, publishWorkflowInstance); } var existingUnpublishSchedule = PublishScheduleHelper.GetUnpublishSchedule(selectedData.DataSourceId.InterfaceType, key, cultureName); if (existingUnpublishSchedule != null) { WorkflowFacade.AbortWorkflow(existingUnpublishSchedule.WorkflowInstanceId); DataFacade.Delete(existingUnpublishSchedule); } if (unpublishDate != null) { unpublishWorkflowInstance = WorkflowFacade.CreateNewWorkflow( typeof(DataUnpublishSchedulerWorkflow), new Dictionary<string, object> { { "Date", unpublishDate }, { "DataType", selectedData.DataSourceId.InterfaceType.FullName }, { "DataId", key }, { "LocaleName", cultureName } } ); PublishScheduleHelper.CreateUnpublishSchedule(selectedData.DataSourceId.InterfaceType, key, cultureName, unpublishDate.Value, unpublishWorkflowInstance); } } public static void ReloadPageElementInConsole(IPage page) { var parentPageId = PageManager.GetParentId(page.Id); var parentPage = parentPageId != Guid.Empty ? PageManager.GetPageById(parentPageId) : null; var parentEntityToken = (parentPage != null) ? parentPage.GetDataEntityToken() : (EntityToken)new PageElementProviderEntityToken("PageElementProvider"); ConsoleMessageQueueFacade.Enqueue(new RefreshTreeMessageQueueItem { EntityToken = parentEntityToken }, null); } public static void ReloadDataElementInConsole(DataEntityToken dataEntityToken) { if (dataEntityToken == null) throw new ArgumentNullException(nameof(dataEntityToken)); var parentEntityTokens = AuxiliarySecurityAncestorFacade.GetParents(dataEntityToken); if (parentEntityTokens != null) { foreach (var parentEntityToken in parentEntityTokens) { ConsoleMessageQueueFacade.Enqueue(new RefreshTreeMessageQueueItem { EntityToken = parentEntityToken }, null); } } } public static bool PublishIfNeeded(IData data, bool doPublish, IDictionary<string, object> binding, Action<DialogType, string, string> messageAction) { if (!(data is IPublishControlled)) { return false; } WorkflowInstance publishWorkflowInstance = null; WorkflowInstance unpublishWorkflowInstance = null; var publishDate = binding.ContainsKey("PublishDate") ? (DateTime?)binding["PublishDate"] : null; var unpublishDate = binding.ContainsKey("UnpublishDate") ? (DateTime?)binding["UnpublishDate"] : null; string cultureName = UserSettings.ActiveLocaleCultureInfo.Name; HandlePublishUnpublishWorkflows(data, cultureName, publishDate, unpublishDate, ref publishWorkflowInstance, ref unpublishWorkflowInstance); if (publishWorkflowInstance != null) { publishWorkflowInstance.Start(); WorkflowFacade.RunWorkflow(publishWorkflowInstance); } if (unpublishWorkflowInstance != null) { unpublishWorkflowInstance.Start(); WorkflowFacade.RunWorkflow(unpublishWorkflowInstance); } if (!doPublish) { return false; } if (publishWorkflowInstance == null || publishDate < DateTime.Now) { var actionToken = new GenericPublishProcessController.PublishActionToken(); var serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); ActionExecutorFacade.Execute(data.GetDataEntityToken(), actionToken, serviceContainer); return true; } var title = Texts.Website_Forms_Administrative_EditPage_PublishDatePreventPublishTitle; var message = Texts.Website_Forms_Administrative_EditPage_PublishDatePreventPublish; messageAction(DialogType.Warning, title, message); return false; } } } ================================================ FILE: Composite.Workflows/C1Console/Tools/SendMessageToConsolesWorkflow.cs ================================================ using System; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Workflow; namespace Composite.C1Console.Tools { public sealed partial class SendMessageToConsolesWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public SendMessageToConsolesWorkflow() { InitializeComponent(); } private void initializeCodeActivity_InitializeBindings_ExecuteCode(object sender, EventArgs e) { this.UpdateBinding("Title", ""); this.UpdateBinding("Message", ""); } private void sendMessageCodeActivity_SendMessage_ExecuteCode(object sender, EventArgs e) { this.CloseCurrentView(); string title = this.GetBinding<string>("Title"); string message = this.GetBinding<string>("Message"); FlowControllerServicesContainer flowControllerServicesContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); IManagementConsoleMessageService managementConsoleMessageService = flowControllerServicesContainer.GetService<IManagementConsoleMessageService>(); managementConsoleMessageService.ShowGlobalMessage(DialogType.Message, title, message); } } } ================================================ FILE: Composite.Workflows/C1Console/Tools/SendMessageToConsolesWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Tools { partial class SendMessageToConsolesWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.sendMessageCodeActivity_SendMessage = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.dataDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_InitializeBindings = new System.Workflow.Activities.CodeActivity(); this.sendMessageStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.enterMessageEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.enterMessageEventDrivenActivity_Ok = new System.Workflow.Activities.EventDrivenActivity(); this.enterMessageStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.sendMessageStateActivity = new System.Workflow.Activities.StateActivity(); this.enterMessageStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // sendMessageCodeActivity_SendMessage // this.sendMessageCodeActivity_SendMessage.Name = "sendMessageCodeActivity_SendMessage"; this.sendMessageCodeActivity_SendMessage.ExecuteCode += new System.EventHandler(this.sendMessageCodeActivity_SendMessage_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "sendMessageStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // dataDialogFormActivity1 // this.dataDialogFormActivity1.ContainerLabel = null; this.dataDialogFormActivity1.FormDefinitionFileName = "/Administrative/SendMessageToConsoles_EnterMessage.xml"; this.dataDialogFormActivity1.Name = "dataDialogFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "enterMessageStateActivity"; // // initializeCodeActivity_InitializeBindings // this.initializeCodeActivity_InitializeBindings.Name = "initializeCodeActivity_InitializeBindings"; this.initializeCodeActivity_InitializeBindings.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_InitializeBindings_ExecuteCode); // // sendMessageStateInitializationActivity // this.sendMessageStateInitializationActivity.Activities.Add(this.sendMessageCodeActivity_SendMessage); this.sendMessageStateInitializationActivity.Activities.Add(this.setStateActivity5); this.sendMessageStateInitializationActivity.Name = "sendMessageStateInitializationActivity"; // // enterMessageEventDrivenActivity_Cancel // this.enterMessageEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.enterMessageEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity3); this.enterMessageEventDrivenActivity_Cancel.Name = "enterMessageEventDrivenActivity_Cancel"; // // enterMessageEventDrivenActivity_Ok // this.enterMessageEventDrivenActivity_Ok.Activities.Add(this.finishHandleExternalEventActivity1); this.enterMessageEventDrivenActivity_Ok.Activities.Add(this.setStateActivity4); this.enterMessageEventDrivenActivity_Ok.Name = "enterMessageEventDrivenActivity_Ok"; // // enterMessageStateInitializationActivity // this.enterMessageStateInitializationActivity.Activities.Add(this.dataDialogFormActivity1); this.enterMessageStateInitializationActivity.Name = "enterMessageStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_InitializeBindings); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // sendMessageStateActivity // this.sendMessageStateActivity.Activities.Add(this.sendMessageStateInitializationActivity); this.sendMessageStateActivity.Name = "sendMessageStateActivity"; // // enterMessageStateActivity // this.enterMessageStateActivity.Activities.Add(this.enterMessageStateInitializationActivity); this.enterMessageStateActivity.Activities.Add(this.enterMessageEventDrivenActivity_Ok); this.enterMessageStateActivity.Activities.Add(this.enterMessageEventDrivenActivity_Cancel); this.enterMessageStateActivity.Name = "enterMessageStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // SendMessageToConsolesWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.enterMessageStateActivity); this.Activities.Add(this.sendMessageStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "SendMessageToConsolesWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private C1Console.Workflow.Activities.DataDialogFormActivity dataDialogFormActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity enterMessageEventDrivenActivity_Cancel; private EventDrivenActivity enterMessageEventDrivenActivity_Ok; private StateInitializationActivity enterMessageStateInitializationActivity; private StateActivity sendMessageStateActivity; private StateActivity enterMessageStateActivity; private SetStateActivity setStateActivity5; private CodeActivity initializeCodeActivity_InitializeBindings; private StateInitializationActivity sendMessageStateInitializationActivity; private CodeActivity sendMessageCodeActivity_SendMessage; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Tools/SendMessageToConsolesWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1146; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="SendMessageToConsolesWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 182" Location="98; 169"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_InitializeBindings" Size="130; 41" Location="108; 231" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="108; 291" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="253; 102" AutoSizeMargin="16; 24" Location="282; 345" Name="enterMessageStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="enterMessageStateInitializationActivity" Size="150; 122" Location="290; 376"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="dataDialogFormActivity1" Size="130; 41" Location="300; 438" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="enterMessageEventDrivenActivity_Ok" Size="150; 182" Location="290; 400"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="300; 462" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="300; 522" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="enterMessageEventDrivenActivity_Cancel" Size="150; 182" Location="290; 424"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="300; 486" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="300; 546" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="237; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="578; 573" Name="sendMessageStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="sendMessageStateInitializationActivity" Size="150; 182" Location="521; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Name="sendMessageCodeActivity_SendMessage" Size="130; 41" Location="531; 210" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="531; 270" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="SendMessageToConsolesWorkflow" TargetConnectionIndex="0" SourceStateName="SendMessageToConsolesWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="enterMessageStateActivity" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="enterMessageStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="408" Y="179" /> <ns0:Point X="408" Y="345" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity3" SourceActivity="enterMessageStateActivity" TargetConnectionIndex="0" SourceStateName="enterMessageStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="enterMessageEventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="531" Y="434" /> <ns0:Point X="1058" Y="434" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="sendMessageStateActivity" SetStateName="setStateActivity4" SourceActivity="enterMessageStateActivity" TargetConnectionIndex="0" SourceStateName="enterMessageStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="enterMessageEventDrivenActivity_Ok" SourceConnectionIndex="1" TargetStateName="sendMessageStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="512" Y="410" /> <ns0:Point X="696" Y="410" /> <ns0:Point X="696" Y="573" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity5" SourceActivity="sendMessageStateActivity" TargetConnectionIndex="0" SourceStateName="sendMessageStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="sendMessageStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="811" Y="614" /> <ns0:Point X="1058" Y="614" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Tools/SetTimeZoneWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web.Hosting; using System.Workflow.Runtime; using System.Xml.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Workflow; using Composite.Core.Configuration; using Composite.Core.ResourceSystem; namespace Composite.C1Console.Tools { public sealed partial class SetTimeZoneWorkflow : Workflow.Activities.FormsWorkflow { private const string TimezoneXslt = @"<?xml version=""1.0"" encoding=""utf-8""?> <xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" xmlns:msxsl=""urn:schemas-microsoft-com:xslt"" exclude-result-prefixes=""msxsl""> <xsl:param name = ""theTimezone"" select='""{0}""'/> <xsl:output method = ""xml"" indent=""yes""/> <xsl:template match = ""@* | node()"" > <xsl:copy> <xsl:apply-templates select = ""@* | node()""/> </xsl:copy> </xsl:template> <xsl:template match = ""GlobalSettingsProviderPlugins/add/@timezone""> <xsl:attribute name = ""timezone""> <xsl:value-of select = ""$theTimezone""/> </xsl:attribute> </xsl:template> <xsl:template match = ""GlobalSettingsProviderPlugins/add[not(@timezone)]""> <xsl:copy> <xsl:attribute name = ""timezone"" > <xsl:value-of select = ""$theTimezone""/> </xsl:attribute> <xsl:apply-templates select = ""@*|node()""/> </xsl:copy> </xsl:template> </xsl:stylesheet>"; public SetTimeZoneWorkflow() { InitializeComponent(); } private void initializeCodeActivity_InitializeBindings_ExecuteCode(object sender, EventArgs e) { string label; var tzs = TimeZoneInfo.GetSystemTimeZones().ToDictionary(systemTimeZone => systemTimeZone.Id, systemTimeZone => StringResourceSystemFacade.TryGetString("Composite.Plugins.TimezoneDisplayNames", "TimezoneDisplayName." + systemTimeZone.Id, out label) ? label : systemTimeZone.DisplayName); var bindings = new Dictionary<string, object> { {"TimeZones", tzs}, {"TimeZonesSelected",GlobalSettingsFacade.TimeZone.Id } }; Bindings = bindings; } private void sendMessageCodeActivity_SendMessage_ExecuteCode(object sender, EventArgs e) { CloseCurrentView(); var timeZoneStandardName = GetBinding<string>("TimeZonesSelected"); var timezoneId = TimeZoneInfo.FindSystemTimeZoneById(timeZoneStandardName); var timezoneTransform = XDocument.Parse(String.Format(TimezoneXslt, timezoneId.Id)); ConfigurationServices.TransformConfiguration(timezoneTransform,false); HostingEnvironment.InitiateShutdown(); FlowControllerServicesContainer flowControllerServicesContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); IManagementConsoleMessageService managementConsoleMessageService = flowControllerServicesContainer.GetService<IManagementConsoleMessageService>(); managementConsoleMessageService.ShowGlobalMessage(DialogType.Message, StringResourceSystemFacade.GetString("Composite.Management", "SendMessageToConsolesWorkflow.SuccessMessage.TimezoneChangedTitle"), StringResourceSystemFacade.GetString("Composite.Management", "SendMessageToConsolesWorkflow.SuccessMessage.TimezoneChangedMessage")); managementConsoleMessageService.RebootConsole(); } } } ================================================ FILE: Composite.Workflows/C1Console/Tools/SetTimeZoneWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Tools { partial class SetTimeZoneWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.sendMessageCodeActivity_SendMessage = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.dataDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_InitializeBindings = new System.Workflow.Activities.CodeActivity(); this.sendMessageStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.enterMessageEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.enterMessageEventDrivenActivity_Ok = new System.Workflow.Activities.EventDrivenActivity(); this.enterMessageStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.sendMessageStateActivity = new System.Workflow.Activities.StateActivity(); this.enterMessageStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // sendMessageCodeActivity_SendMessage // this.sendMessageCodeActivity_SendMessage.Name = "sendMessageCodeActivity_SendMessage"; this.sendMessageCodeActivity_SendMessage.ExecuteCode += new System.EventHandler(this.sendMessageCodeActivity_SendMessage_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "sendMessageStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // dataDialogFormActivity1 // this.dataDialogFormActivity1.ContainerLabel = null; this.dataDialogFormActivity1.FormDefinitionFileName = "/Administrative/SetTimeZone_select.xml"; this.dataDialogFormActivity1.Name = "dataDialogFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "enterMessageStateActivity"; // // initializeCodeActivity_InitializeBindings // this.initializeCodeActivity_InitializeBindings.Name = "initializeCodeActivity_InitializeBindings"; this.initializeCodeActivity_InitializeBindings.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_InitializeBindings_ExecuteCode); // // sendMessageStateInitializationActivity // this.sendMessageStateInitializationActivity.Activities.Add(this.sendMessageCodeActivity_SendMessage); this.sendMessageStateInitializationActivity.Activities.Add(this.setStateActivity5); this.sendMessageStateInitializationActivity.Name = "sendMessageStateInitializationActivity"; // // enterMessageEventDrivenActivity_Cancel // this.enterMessageEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.enterMessageEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity3); this.enterMessageEventDrivenActivity_Cancel.Name = "enterMessageEventDrivenActivity_Cancel"; // // enterMessageEventDrivenActivity_Ok // this.enterMessageEventDrivenActivity_Ok.Activities.Add(this.finishHandleExternalEventActivity1); this.enterMessageEventDrivenActivity_Ok.Activities.Add(this.setStateActivity4); this.enterMessageEventDrivenActivity_Ok.Name = "enterMessageEventDrivenActivity_Ok"; // // enterMessageStateInitializationActivity // this.enterMessageStateInitializationActivity.Activities.Add(this.dataDialogFormActivity1); this.enterMessageStateInitializationActivity.Name = "enterMessageStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_InitializeBindings); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // sendMessageStateActivity // this.sendMessageStateActivity.Activities.Add(this.sendMessageStateInitializationActivity); this.sendMessageStateActivity.Name = "sendMessageStateActivity"; // // enterMessageStateActivity // this.enterMessageStateActivity.Activities.Add(this.enterMessageStateInitializationActivity); this.enterMessageStateActivity.Activities.Add(this.enterMessageEventDrivenActivity_Ok); this.enterMessageStateActivity.Activities.Add(this.enterMessageEventDrivenActivity_Cancel); this.enterMessageStateActivity.Name = "enterMessageStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // SendMessageToConsolesWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.enterMessageStateActivity); this.Activities.Add(this.sendMessageStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "SendMessageToConsolesWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private C1Console.Workflow.Activities.DataDialogFormActivity dataDialogFormActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity enterMessageEventDrivenActivity_Cancel; private EventDrivenActivity enterMessageEventDrivenActivity_Ok; private StateInitializationActivity enterMessageStateInitializationActivity; private StateActivity sendMessageStateActivity; private StateActivity enterMessageStateActivity; private SetStateActivity setStateActivity5; private CodeActivity initializeCodeActivity_InitializeBindings; private StateInitializationActivity sendMessageStateInitializationActivity; private CodeActivity sendMessageCodeActivity_SendMessage; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/AddApplicationWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Transactions; using System.Workflow.Activities; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Elements.Plugins.ElementAttachingProvider; using Composite.Data.Transactions; using Composite.C1Console.Trees; using Composite.Core.Types; using Composite.C1Console.Workflow; namespace Composite.C1Console.Trees.Workflows { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddApplicationWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddApplicationWorkflow() { InitializeComponent(); } private void IsThereAnyTrees(object sender, ConditionalEventArgs e) { e.Result = this.BindingExist("SelectedTreeId"); } private void initializeCodeActivity_UpdateBindings_ExecuteCode(object sender, EventArgs e) { Dictionary<string, string> selectableTreeIds = new Dictionary<string, string>(); foreach (Tree tree in TreeFacade.AllTrees) { if (tree.HasPossibleAttachmentPoints(this.EntityToken) == false) continue; if (tree.HasAttachmentPoints(this.EntityToken)) continue; selectableTreeIds.Add(tree.TreeId, tree.AllowedAttachmentApplicationName); } if (selectableTreeIds.Count > 0) { this.UpdateBinding("SelectedTreeId", selectableTreeIds.First().Key); this.UpdateBinding("SelectableTreeIds", selectableTreeIds); Dictionary<string, string> selectablePositions = Enum.GetNames(typeof(ElementAttachingProviderPosition)).ToDictionary(f => f); this.UpdateBinding("SelectedPosition", selectablePositions.First().Key); this.UpdateBinding("SelectablePositions", selectablePositions); } } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; object keyValue = dataEntityToken.DataSourceId.GetKeyValue(); string treeId = this.GetBinding<string>("SelectedTreeId"); string serializedPosition = this.GetBinding<string>("SelectedPosition"); ElementAttachingProviderPosition position = (ElementAttachingProviderPosition)Enum.Parse(typeof(ElementAttachingProviderPosition), serializedPosition); TreeFacade.AddPersistedAttachmentPoint(treeId, dataEntityToken.InterfaceType, keyValue, position); this.RefreshCurrentEntityToken(); } private void initializeCodeActivity_ShowNoTreesMessage_ExecuteCode(object sender, EventArgs e) { this.ShowMessage(DialogType.Message, "${Composite.C1Console.Trees, AddApplication.NoTrees.Title}", "${Composite.C1Console.Trees, AddApplication.NoTrees.Message}"); } } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/AddApplicationWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Trees.Workflows { partial class AddApplicationWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_ShowNoTreesMessage = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step1WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.initializeIfElseActivity_AnyTrees = new System.Workflow.Activities.IfElseActivity(); this.initializeCodeActivity_UpdateBindings = new System.Workflow.Activities.CodeActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // initializeCodeActivity_ShowNoTreesMessage // this.initializeCodeActivity_ShowNoTreesMessage.Name = "initializeCodeActivity_ShowNoTreesMessage"; this.initializeCodeActivity_ShowNoTreesMessage.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ShowNoTreesMessage_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.initializeCodeActivity_ShowNoTreesMessage); this.ifElseBranchActivity2.Activities.Add(this.setStateActivity6); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity2); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsThereAnyTrees); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // step1WizardFormActivity // this.step1WizardFormActivity.ContainerLabel = null; this.step1WizardFormActivity.FormDefinitionFileName = "\\Administrative\\TreeAddApplication.xml"; this.step1WizardFormActivity.Name = "step1WizardFormActivity"; // // initializeIfElseActivity_AnyTrees // this.initializeIfElseActivity_AnyTrees.Activities.Add(this.ifElseBranchActivity1); this.initializeIfElseActivity_AnyTrees.Activities.Add(this.ifElseBranchActivity2); this.initializeIfElseActivity_AnyTrees.Name = "initializeIfElseActivity_AnyTrees"; // // initializeCodeActivity_UpdateBindings // this.initializeCodeActivity_UpdateBindings.Name = "initializeCodeActivity_UpdateBindings"; this.initializeCodeActivity_UpdateBindings.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_UpdateBindings_ExecuteCode); // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity5); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity3); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1WizardFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_UpdateBindings); this.initializeStateInitializationActivity.Activities.Add(this.initializeIfElseActivity_AnyTrees); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // AddApplicationWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddApplicationWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity5; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private C1Console.Workflow.Activities.WizardFormActivity step1WizardFormActivity; private SetStateActivity setStateActivity2; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Finish; private EventDrivenActivity step1EventDrivenActivity_Cancel; private StateInitializationActivity step1StateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private CodeActivity initializeCodeActivity_UpdateBindings; private CodeActivity finalizeCodeActivity_Finalize; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity initializeIfElseActivity_AnyTrees; private SetStateActivity setStateActivity6; private CodeActivity initializeCodeActivity_ShowNoTreesMessage; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/AddApplicationWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1196; 959" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="AddApplicationWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="63; 105" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="381; 423" Location="437; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_UpdateBindings" Size="130; 41" Location="562; 210" /> <IfElseDesigner Name="initializeIfElseActivity_AnyTrees" Size="361; 282" Location="447; 270"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 182" Location="466; 341"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="476; 433" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 182" Location="639; 341"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_ShowNoTreesMessage" Size="130; 41" Location="649; 403" /> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="649; 463" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="860; 730" Name="finalStateActivity" /> <StateDesigner Size="211; 118" AutoSizeMargin="16; 24" AutoSize="False" Location="271; 317" Name="step1StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1StateInitializationActivity" Size="150; 122" Location="279; 348"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="step1WizardFormActivity" Size="130; 41" Location="289; 410" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Cancel" Size="150; 182" Location="279; 372"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="289; 434" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="289; 494" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Finish" Size="150; 182" Location="279; 396"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="289; 458" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="289; 518" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" Location="567; 532" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 182" Location="575; 563"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity_Finalize" Size="130; 41" Location="585; 625" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="585; 685" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="AddApplicationWorkflow" TargetConnectionIndex="0" SourceStateName="AddApplicationWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="940" Y="71" /> <ns0:Point X="940" Y="730" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="269" Y="146" /> <ns0:Point X="376" Y="146" /> <ns0:Point X="376" Y="317" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity3" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Cancel" SourceConnectionIndex="1" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="478" Y="382" /> <ns0:Point X="940" Y="382" /> <ns0:Point X="940" Y="730" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity5" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="2" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="474" Y="406" /> <ns0:Point X="669" Y="406" /> <ns0:Point X="669" Y="532" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity4" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="768" Y="573" /> <ns0:Point X="940" Y="573" /> <ns0:Point X="940" Y="730" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/AddTreeDefinitionWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.IO; using Composite.C1Console.Workflow; using Composite.Core.Configuration; using Composite.Core.IO; namespace Composite.C1Console.Trees.Workflows { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddTreeDefinitionWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddTreeDefinitionWorkflow() { InitializeComponent(); } private void initializeCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { this.Bindings.Add("DefinitionName", ""); this.Bindings.Add("TemplatesList", new Dictionary<string, string> { { "Empty", "Empty" }, { "Folder grouping", "Folder grouping" }, { "Parent filtering", "Parent filtering" } }); this.Bindings.Add("TemplateName", "Empty"); this.Bindings.Add("PositionsList", new Dictionary<string, string> { { "Content", "Content" }, { "Media", "Media" }, { "Layout", "Layout" }, { "Data", "Data" }, { "Function", "Function" }, { "User", "User" }, { "System", "System" }, { "PerspectivesRoot", "PerspectivesRoot" } }); this.Bindings.Add("PositionName", "Content"); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { string definitionName = this.GetBinding<string>("DefinitionName"); string templateName = this.GetBinding<string>("TemplateName"); string positionName = this.GetBinding<string>("PositionName"); string template; switch (templateName) { case "Empty": template = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?> <ElementStructure xmlns=""http://http://www.composite.net/ns/management/trees/treemarkup/1.0"" xmlns:f=""http://www.composite.net/ns/function/1.0""> <ElementStructure.AutoAttachments> <NamedParent Name=""{0}"" Position=""Top""/> </ElementStructure.AutoAttachments> <ElementRoot> <Children> <Element Label=""Simple tree"" Id=""SimpleTree"" /> </Children> </ElementRoot> </ElementStructure>", positionName); break; case "Folder grouping": template = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?> <ElementStructure xmlns=""http://http://www.composite.net/ns/management/trees/treemarkup/1.0"" xmlns:f=""http://www.composite.net/ns/function/1.0""> <ElementStructure.AutoAttachments> <NamedParent Name=""{0}"" Position=""Top""/> </ElementStructure.AutoAttachments> <ElementRoot> <Children> <Element Label=""My DSL Tree Demo"" Id=""FolderGroupingId1""> <Children> <Element Label=""Simple Element"" Id=""FolderGroupingId2""> <Children> <DataFolderElements Type=""Composite.Data.Types.IPage"" FieldGroupingName=""ChangeDate"" DateFormat=""yyyy - MMMM""> <Children> <DataFolderElements FieldGroupingName=""Description""> <Children> <DataElements Type=""Composite.Data.Types.IPage""> </DataElements> </Children> </DataFolderElements> </Children> </DataFolderElements> </Children> </Element> </Children> </Element> </Children> </ElementRoot> </ElementStructure>", positionName); break; case "Parent filtering": template = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?> <ElementStructure xmlns=""http://http://www.composite.net/ns/management/trees/treemarkup/1.0"" xmlns:f=""http://www.composite.net/ns/function/1.0""> <ElementStructure.AutoAttachments> <NamedParent Name=""{0}"" Position=""Top""/> </ElementStructure.AutoAttachments> <ElementRoot> <Children> <Element Label=""My DSL Tree Demo"" Id=""ParentFilteringId1""> <Children> <Element Label=""Simple Element"" Id=""ParentFilteringId2""> <Children> <DataElements Type=""Composite.Data.Types.IPageTemplate""> <Children> <DataElements Type=""Composite.Data.Types.IPage""> <Filters> <ParentIdFilter ParentType=""Composite.Data.Types.IPageTemplate"" ReferenceFieldName=""TemplateId"" /> </Filters> </DataElements> </Children> </DataElements> </Children> </Element> </Children> </Element> </Children> </ElementRoot> </ElementStructure>", positionName); break; default: throw new InvalidOperationException(); } string filename = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.TreeDefinitionsDirectory), definitionName + ".xml"); C1File.WriteAllText(filename, template); this.RefreshRootEntityToken(); } private void IsTreeIdFree(object sender, System.Workflow.Activities.ConditionalEventArgs e) { string definitionName = this.GetBinding<string>("DefinitionName"); string filename = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.TreeDefinitionsDirectory), definitionName + ".xml"); e.Result = C1File.Exists(filename) == false; if (e.Result == false) { this.ShowFieldMessage("DefinitionName", "Definition name is already used"); } } } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/AddTreeDefinitionWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Trees.Workflows { partial class AddTreeDefinitionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.selectIfElseActivity_TreeIdFree = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizardFormActivity1 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.selectTemplateEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.selectTemplateStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.selectTemplateStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "selectTemplateStateActivity"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity5); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity3); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsTreeIdFree); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // selectIfElseActivity_TreeIdFree // this.selectIfElseActivity_TreeIdFree.Activities.Add(this.ifElseBranchActivity1); this.selectIfElseActivity_TreeIdFree.Activities.Add(this.ifElseBranchActivity2); this.selectIfElseActivity_TreeIdFree.Name = "selectIfElseActivity_TreeIdFree"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // wizardFormActivity1 // this.wizardFormActivity1.ContainerLabel = null; this.wizardFormActivity1.FormDefinitionFileName = "/Administrative/TreeAddTreeDefinition.xml"; this.wizardFormActivity1.Name = "wizardFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "selectTemplateStateActivity"; // // initializeCodeActivity_Initialize // this.initializeCodeActivity_Initialize.Name = "initializeCodeActivity_Initialize"; this.initializeCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_Initialize_ExecuteCode); // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // selectTemplateEventDrivenActivity_Finish // this.selectTemplateEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.selectTemplateEventDrivenActivity_Finish.Activities.Add(this.selectIfElseActivity_TreeIdFree); this.selectTemplateEventDrivenActivity_Finish.Name = "selectTemplateEventDrivenActivity_Finish"; // // selectTemplateStateInitializationActivity // this.selectTemplateStateInitializationActivity.Activities.Add(this.wizardFormActivity1); this.selectTemplateStateInitializationActivity.Name = "selectTemplateStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_Initialize); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // selectTemplateStateActivity // this.selectTemplateStateActivity.Activities.Add(this.selectTemplateStateInitializationActivity); this.selectTemplateStateActivity.Activities.Add(this.selectTemplateEventDrivenActivity_Finish); this.selectTemplateStateActivity.Name = "selectTemplateStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // AddTreeDefinitionWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.selectTemplateStateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddTreeDefinitionWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private StateActivity selectTemplateStateActivity; private SetStateActivity setStateActivity2; private StateInitializationActivity selectTemplateStateInitializationActivity; private C1Console.Workflow.Activities.WizardFormActivity wizardFormActivity1; private SetStateActivity setStateActivity4; private CodeActivity finalizeCodeActivity_Finalize; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity selectTemplateEventDrivenActivity_Finish; private StateActivity finalizeStateActivity; private SetStateActivity setStateActivity5; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity selectIfElseActivity_TreeIdFree; private CodeActivity initializeCodeActivity_Initialize; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/AddTreeDefinitionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1164; 986" AutoSizeMargin="16; 24" Location="30; 30" Name="AddTreeDefinitionWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 182" Location="98; 169"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_Initialize" Size="130; 41" Location="108; 231" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="108; 291" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="255; 80" AutoSizeMargin="16; 24" Location="292; 369" Name="selectTemplateStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="selectTemplateStateInitializationActivity" Size="150; 122" Location="300; 400"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizardFormActivity1" Size="130; 41" Location="310; 462" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="selectTemplateEventDrivenActivity_Finish" Size="381; 363" Location="300; 424"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="425; 486" /> <IfElseDesigner Name="selectIfElseActivity_TreeIdFree" Size="361; 222" Location="310; 546"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 122" Location="329; 617"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="339; 679" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 122" Location="502; 617"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="512; 679" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="680; 550" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 182" Location="688; 581"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity_Finalize" Size="130; 41" Location="698; 643" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="698; 703" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="AddTreeDefinitionWorkflow" TargetConnectionIndex="0" SourceStateName="AddTreeDefinitionWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="selectTemplateStateActivity" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="selectTemplateStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="419" Y="179" /> <ns0:Point X="419" Y="369" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity3" SourceActivity="selectTemplateStateActivity" TargetConnectionIndex="0" SourceStateName="selectTemplateStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="selectTemplateEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="543" Y="434" /> <ns0:Point X="782" Y="434" /> <ns0:Point X="782" Y="550" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="selectTemplateStateActivity" SetStateName="setStateActivity5" SourceActivity="selectTemplateStateActivity" TargetConnectionIndex="0" SourceStateName="selectTemplateStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="selectTemplateEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="selectTemplateStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="543" Y="434" /> <ns0:Point X="555" Y="434" /> <ns0:Point X="555" Y="361" /> <ns0:Point X="419" Y="361" /> <ns0:Point X="419" Y="369" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity4" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="881" Y="591" /> <ns0:Point X="1058" Y="591" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/ConfirmActionWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Xml.Linq; using Composite.C1Console.Elements; using Composite.Functions; using Composite.Core.ResourceSystem; using Composite.C1Console.Trees; using Composite.Data; namespace Composite.C1Console.Trees.Workflows { public sealed partial class ConfirmActionWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public ConfirmActionWorkflow() { InitializeComponent(); } private void initializeCodeActivity_UpdateBinding_ExecuteCode(object sender, EventArgs e) { ConfirmActionNode confirmActionNode = (ConfirmActionNode)ActionNode.Deserialize(this.Payload); DynamicValuesHelperReplaceContext dynamicValuesHelperReplaceContext = CreateDynamicValuesHelperReplaceContext(); this.Bindings.Add("Label", confirmActionNode.ConfirmTitleDynamicValuesHelper.ReplaceValues(dynamicValuesHelperReplaceContext)); this.Bindings.Add("Message", confirmActionNode.ConfirmMessageDynamicValuesHelper.ReplaceValues(dynamicValuesHelperReplaceContext)); } private void showConfirmCodeActivity_ExecuteFunction_ExecuteCode(object sender, EventArgs e) { ConfirmActionNode confirmActionNode = (ConfirmActionNode)ActionNode.Deserialize(this.Payload); DynamicValuesHelperReplaceContext dynamicValuesHelperReplaceContext = CreateDynamicValuesHelperReplaceContext(); AttributeDynamicValuesHelper attributeDynamicValuesHelper = new AttributeDynamicValuesHelper(confirmActionNode.FunctionMarkup); attributeDynamicValuesHelper.Initialize(confirmActionNode.OwnerNode); XElement markup = confirmActionNode.FunctionMarkupDynamicValuesHelper.ReplaceValues(dynamicValuesHelperReplaceContext); BaseRuntimeTreeNode baseRuntimeTreeNode = FunctionTreeBuilder.Build(markup); object value = baseRuntimeTreeNode.GetValue(); } } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/ConfirmActionWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Trees.Workflows { partial class ConfirmActionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.showConfirmCodeActivity_ExecuteFunction = new System.Workflow.Activities.CodeActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_UpdateBinding = new System.Workflow.Activities.CodeActivity(); this.showConfirmEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.showConfirmEventDrivenActivity_Ok = new System.Workflow.Activities.EventDrivenActivity(); this.showConfirmStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.showConfirmStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // showConfirmCodeActivity_ExecuteFunction // this.showConfirmCodeActivity_ExecuteFunction.Name = "showConfirmCodeActivity_ExecuteFunction"; this.showConfirmCodeActivity_ExecuteFunction.ExecuteCode += new System.EventHandler(this.showConfirmCodeActivity_ExecuteFunction_ExecuteCode); // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "/Administrative/TreeConfirmActionConfirm.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "showConfirmStateActivity"; // // initializeCodeActivity_UpdateBinding // this.initializeCodeActivity_UpdateBinding.Name = "initializeCodeActivity_UpdateBinding"; this.initializeCodeActivity_UpdateBinding.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_UpdateBinding_ExecuteCode); // // showConfirmEventDrivenActivity_Cancel // this.showConfirmEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.showConfirmEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity3); this.showConfirmEventDrivenActivity_Cancel.Name = "showConfirmEventDrivenActivity_Cancel"; // // showConfirmEventDrivenActivity_Ok // this.showConfirmEventDrivenActivity_Ok.Activities.Add(this.finishHandleExternalEventActivity1); this.showConfirmEventDrivenActivity_Ok.Activities.Add(this.showConfirmCodeActivity_ExecuteFunction); this.showConfirmEventDrivenActivity_Ok.Activities.Add(this.setStateActivity4); this.showConfirmEventDrivenActivity_Ok.Name = "showConfirmEventDrivenActivity_Ok"; // // showConfirmStateInitializationActivity // this.showConfirmStateInitializationActivity.Activities.Add(this.confirmDialogFormActivity1); this.showConfirmStateInitializationActivity.Name = "showConfirmStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_UpdateBinding); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // showConfirmStateActivity // this.showConfirmStateActivity.Activities.Add(this.showConfirmStateInitializationActivity); this.showConfirmStateActivity.Activities.Add(this.showConfirmEventDrivenActivity_Ok); this.showConfirmStateActivity.Activities.Add(this.showConfirmEventDrivenActivity_Cancel); this.showConfirmStateActivity.Name = "showConfirmStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // ConfirmActionWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.showConfirmStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "ConfirmActionWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private StateActivity showConfirmStateActivity; private C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private StateInitializationActivity showConfirmStateInitializationActivity; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity showConfirmEventDrivenActivity_Cancel; private EventDrivenActivity showConfirmEventDrivenActivity_Ok; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity4; private CodeActivity showConfirmCodeActivity_ExecuteFunction; private CodeActivity initializeCodeActivity_UpdateBinding; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/ConfirmActionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1146; 970" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="ConfirmActionWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 182" Location="512; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_UpdateBinding" Size="130; 41" Location="522; 210" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="522; 270" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="249; 102" AutoSizeMargin="16; 24" AutoSize="False" Location="334; 357" Name="showConfirmStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="showConfirmStateInitializationActivity" Size="150; 122" Location="342; 388"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="confirmDialogFormActivity1" Size="130; 41" Location="352; 450" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="showConfirmEventDrivenActivity_Ok" Size="150; 242" Location="342; 412"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="352; 474" /> <CodeDesigner Name="showConfirmCodeActivity_ExecuteFunction" Size="130; 41" Location="352; 534" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="352; 594" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="showConfirmEventDrivenActivity_Cancel" Size="150; 182" Location="342; 436"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="352; 498" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="352; 558" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="ConfirmActionWorkflow" TargetConnectionIndex="0" SourceStateName="ConfirmActionWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="showConfirmStateActivity" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="showConfirmStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="458" Y="179" /> <ns0:Point X="458" Y="357" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity4" SourceActivity="showConfirmStateActivity" TargetConnectionIndex="0" SourceStateName="showConfirmStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="showConfirmEventDrivenActivity_Ok" SourceConnectionIndex="1" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="559" Y="422" /> <ns0:Point X="1058" Y="422" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity3" SourceActivity="showConfirmStateActivity" TargetConnectionIndex="0" SourceStateName="showConfirmStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="showConfirmEventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="579" Y="446" /> <ns0:Point X="1058" Y="446" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/DeleteTreeDefinitionWorkflow.cs ================================================ using System; using Composite.C1Console.Workflow; using Composite.Core.IO; using Composite.Plugins.Elements.ElementProviders.DeveloperApplicationProvider; namespace Composite.C1Console.Trees.Workflows { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteTreeDefinitionWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeleteTreeDefinitionWorkflow() { InitializeComponent(); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { DeveloperApplicationProviderEntityToken castedEntityToken = (DeveloperApplicationProviderEntityToken)this.EntityToken; FileUtils.Delete(castedEntityToken.FullTreePath); this.RefreshRootEntityToken(); } } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/DeleteTreeDefinitionWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Trees.Workflows { partial class DeleteTreeDefinitionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity2 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.confirmEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.confirmEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.confirmStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.confirmStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // confirmDialogFormActivity2 // this.confirmDialogFormActivity2.ContainerLabel = null; this.confirmDialogFormActivity2.FormDefinitionFileName = "/Administrative/TreeDeleteTreeDefinition.xml"; this.confirmDialogFormActivity2.Name = "confirmDialogFormActivity2"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "confirmStateActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // confirmEventDrivenActivity_Cancel // this.confirmEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.confirmEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity5); this.confirmEventDrivenActivity_Cancel.Name = "confirmEventDrivenActivity_Cancel"; // // confirmEventDrivenActivity_Finish // this.confirmEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.confirmEventDrivenActivity_Finish.Activities.Add(this.setStateActivity2); this.confirmEventDrivenActivity_Finish.Name = "confirmEventDrivenActivity_Finish"; // // confirmStateInitializationActivity // this.confirmStateInitializationActivity.Activities.Add(this.confirmDialogFormActivity2); this.confirmStateInitializationActivity.Name = "confirmStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity3); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // confirmStateActivity // this.confirmStateActivity.Activities.Add(this.confirmStateInitializationActivity); this.confirmStateActivity.Activities.Add(this.confirmEventDrivenActivity_Finish); this.confirmStateActivity.Activities.Add(this.confirmEventDrivenActivity_Cancel); this.confirmStateActivity.Name = "confirmStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // DeleteTreeDefinitionWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.confirmStateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "DeleteTreeDefinitionWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity2; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity confirmEventDrivenActivity_Finish; private StateInitializationActivity confirmStateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity confirmStateActivity; private SetStateActivity setStateActivity4; private CodeActivity finalizeCodeActivity_Finalize; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity5; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity confirmEventDrivenActivity_Cancel; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/DeleteTreeDefinitionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1164; 986" AutoSizeMargin="16; 24" Location="30; 30" Name="DeleteTreeDefinitionWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 122" Location="98; 169"> <StateInitializationDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="108; 231" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="221; 102" AutoSizeMargin="16; 24" Location="271; 354" Name="confirmStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="confirmStateInitializationActivity" Size="150; 122" Location="279; 385"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="confirmDialogFormActivity2" Size="130; 41" Location="289; 447" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="confirmEventDrivenActivity_Finish" Size="150; 182" Location="279; 409"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="289; 471" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="289; 531" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="confirmEventDrivenActivity_Cancel" Size="150; 182" Location="279; 433"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="289; 495" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="289; 555" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="566; 544" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 182" Location="574; 575"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity_Finalize" Size="130; 41" Location="584; 637" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="584; 697" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="DeleteTreeDefinitionWorkflow" TargetConnectionIndex="0" SourceStateName="DeleteTreeDefinitionWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="confirmStateActivity" SetStateName="setStateActivity3" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="confirmStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="381" Y="179" /> <ns0:Point X="381" Y="354" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity2" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="confirmEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="484" Y="419" /> <ns0:Point X="668" Y="419" /> <ns0:Point X="668" Y="544" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity4" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="767" Y="585" /> <ns0:Point X="1058" Y="585" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity5" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="confirmEventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="488" Y="443" /> <ns0:Point X="1058" Y="443" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/EditTreeDefinitionWorkflow.cs ================================================ using System; using System.IO; using System.Linq; using System.Text; using System.Xml.Linq; using Composite.C1Console.Events; using Composite.C1Console.Workflow; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Plugins.Elements.ElementProviders.DeveloperApplicationProvider; namespace Composite.C1Console.Trees.Workflows { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditTreeDefinitionWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditTreeDefinitionWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { string path = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.TreeDefinitionsDirectory), this.Filename); this.Bindings.Add("TreeId", Path.GetFileNameWithoutExtension(this.Filename)); this.Bindings.Add("TreeDefinitionMarkup", C1File.ReadAllText(path)); } private void saveStateCodeActivity_ExecuteCode(object sender, EventArgs e) { string content = this.GetBinding<string>("TreeDefinitionMarkup"); string path = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.TreeDefinitionsDirectory), this.Filename); FileUtils.RemoveReadOnly(path); C1File.WriteAllText(path, content); this.SetSaveStatus(true); this.RefreshCurrentEntityToken(); } private string Filename { get { DeveloperApplicationProviderEntityToken castedEntityToken = (DeveloperApplicationProviderEntityToken)this.EntityToken; return castedEntityToken.FullTreePath; } } private void IsMarkupValid(object sender, System.Workflow.Activities.ConditionalEventArgs e) { DeveloperApplicationProviderEntityToken castedEntityToken = (DeveloperApplicationProviderEntityToken)this.EntityToken; string content = this.GetBinding<string>("TreeDefinitionMarkup"); this.UpdateBinding("Errors", ""); XDocument document = null; try { document = XDocument.Parse(content); } catch (Exception ex) { this.UpdateBinding("Errors", ex.Message); e.Result = false; return; } Tree tree = TreeFacade.LoadTreeFromDom(castedEntityToken.Filename, document); ValidationError validationError = tree.BuildResult.ValidationErrors.FirstOrDefault(); if (validationError != null) { StringBuilder sb = new StringBuilder(); if (string.IsNullOrEmpty(validationError.XPath) == false) { sb.Append(validationError.Message); sb.Append(" at XPath: "); sb.Append(validationError.XPath); } else { sb.Append(validationError.Message); } this.UpdateBinding("Errors", sb.ToString()); } e.Result = tree.BuildResult.ValidationErrors.Count() == 0; } private void editCodeActivity_ShowErrorMessage_ExecuteCode(object sender, EventArgs e) { this.ShowMessage(DialogType.Error, "Error", this.GetBinding<string>("Errors")); } } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/EditTreeDefinitionWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Trees.Workflows { partial class EditTreeDefinitionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.editCodeActivity_ShowErrorMessage = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.saveStateCodeActivity = new System.Workflow.Activities.CodeActivity(); this.editIfElseActivity_IsValidMarkup = new System.Workflow.Activities.IfElseActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editEventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "editStateActivity"; // // editCodeActivity_ShowErrorMessage // this.editCodeActivity_ShowErrorMessage.Name = "editCodeActivity_ShowErrorMessage"; this.editCodeActivity_ShowErrorMessage.ExecuteCode += new System.EventHandler(this.editCodeActivity_ShowErrorMessage_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "saveStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.editCodeActivity_ShowErrorMessage); this.ifElseBranchActivity2.Activities.Add(this.setStateActivity3); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity4); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsMarkupValid); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "editStateActivity"; // // saveStateCodeActivity // this.saveStateCodeActivity.Name = "saveStateCodeActivity"; this.saveStateCodeActivity.ExecuteCode += new System.EventHandler(this.saveStateCodeActivity_ExecuteCode); // // editIfElseActivity_IsValidMarkup // this.editIfElseActivity_IsValidMarkup.Activities.Add(this.ifElseBranchActivity1); this.editIfElseActivity_IsValidMarkup.Activities.Add(this.ifElseBranchActivity2); this.editIfElseActivity_IsValidMarkup.Name = "editIfElseActivity_IsValidMarkup"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.CustomToolbarDefinitionFileName = null; this.documentFormActivity1.FormDefinitionFileName = "\\Administrative\\TreeEditDefinition.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.saveStateCodeActivity); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity5); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // editEventDrivenActivity_Save // this.editEventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.editEventDrivenActivity_Save.Activities.Add(this.editIfElseActivity_IsValidMarkup); this.editEventDrivenActivity_Save.Name = "editEventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.saveStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_Save); this.editStateActivity.Name = "editStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // EditTreeDefinitionWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "EditTreeDefinitionWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private StateInitializationActivity editStateInitializationActivity; private StateActivity editStateActivity; private CodeActivity initializeCodeActivity; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity4; private StateInitializationActivity saveStateInitializationActivity; private EventDrivenActivity editEventDrivenActivity_Save; private StateActivity saveStateActivity; private C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private CodeActivity saveStateCodeActivity; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity editIfElseActivity_IsValidMarkup; private SetStateActivity setStateActivity3; private CodeActivity editCodeActivity_ShowErrorMessage; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/EditTreeDefinitionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1164; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="EditTreeDefinitionWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 182" Location="98; 169"> <StateInitializationDesigner.Designers> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="108; 231" /> <CodeDesigner Name="initializeCodeActivity" Size="130; 41" Location="108; 291" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="208; 102" AutoSizeMargin="16; 24" AutoSize="False" Location="240; 340" Name="editStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="editStateInitializationActivity" Size="150; 122" Location="413; 135"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="documentFormActivity1" Size="130; 41" Location="423; 197" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="editEventDrivenActivity_Save" Size="381; 423" Location="421; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130; 41" Location="546; 210" /> <IfElseDesigner Name="editIfElseActivity_IsValidMarkup" Size="361; 282" Location="431; 270"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 182" Location="450; 341"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="460; 433" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 182" Location="623; 341"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="editCodeActivity_ShowErrorMessage" Size="130; 41" Location="633; 403" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="633; 463" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="199; 80" AutoSizeMargin="16; 24" Location="535; 561" Name="saveStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="saveStateInitializationActivity" Size="150; 182" Location="543; 592"> <StateInitializationDesigner.Designers> <CodeDesigner Name="saveStateCodeActivity" Size="130; 41" Location="553; 654" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="553; 714" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="EditTreeDefinitionWorkflow" TargetConnectionIndex="0" SourceStateName="EditTreeDefinitionWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="344" Y="179" /> <ns0:Point X="344" Y="340" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" SetStateName="setStateActivity4" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editEventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="429" Y="405" /> <ns0:Point X="634" Y="405" /> <ns0:Point X="634" Y="561" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity5" SourceActivity="saveStateActivity" TargetConnectionIndex="0" SourceStateName="saveStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="saveStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="724" Y="602" /> <ns0:Point X="744" Y="602" /> <ns0:Point X="744" Y="332" /> <ns0:Point X="344" Y="332" /> <ns0:Point X="344" Y="340" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/GenericAddDataWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Elements; using Composite.C1Console.Scheduling; using Composite.C1Console.Workflow; using Composite.Core.Serialization; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.Types; using Composite.C1Console.Security; using Composite.C1Console.Workflow.Foundation; namespace Composite.C1Console.Trees.Workflows { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class GenericAddDataWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { [NonSerialized] private bool _doPublish; [NonSerialized] private IDictionary<string, string> _dataPayload; [NonSerialized] private DataTypeDescriptorFormsHelper _dataTypeDescriptorFormsHelper; [NonSerialized] private string _typeName; private string TypeName { get { return _typeName; } set { _typeName = value; } } private Type InterfaceType { get { return StringConversionServices.DeserializeValueType(DataPayload["_InterfaceType_"]); } } private string CustomFormMarkupPath { get { if (DataPayload.ContainsKey("_CustomFormMarkupPath_")) { return StringConversionServices.DeserializeValueString(DataPayload["_CustomFormMarkupPath_"]); } return null; } } private string IconResourceName { get { return StringConversionServices.DeserializeValueString(DataPayload["_IconResourceName_"]); } } private void Initialize() { if (_dataTypeDescriptorFormsHelper == null) { if (String.IsNullOrEmpty(this.Payload)) { throw new InvalidOperationException("The interface type should be a part of the workflows payload"); } Dictionary<string, string> serializedValues = StringConversionServices.ParseKeyValueCollection(this.Payload); _dataPayload = serializedValues; } if (!PermissionsFacade.GetPermissionsForCurrentUser(EntityToken).Contains(PermissionType.Publish) || !typeof(IPublishControlled).IsAssignableFrom(InterfaceType)) { FormData formData = WorkflowFacade.GetFormData(InstanceId, true); if (formData.ExcludedEvents == null) formData.ExcludedEvents = new List<string>(); formData.ExcludedEvents.Add("SaveAndPublish"); } } private IDictionary<string, string> DataPayload { get { return _dataPayload; } } private DataTypeDescriptorFormsHelper FormsHelper { get { if (_dataTypeDescriptorFormsHelper == null) { DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(InterfaceType); this.TypeName = dataTypeDescriptor.Name; var generatedTypesHelper = new GeneratedTypesHelper(dataTypeDescriptor) { AllowForeignKeyEditing = true }; _dataTypeDescriptorFormsHelper = new DataTypeDescriptorFormsHelper(dataTypeDescriptor, true, this.EntityToken); if (!string.IsNullOrEmpty(CustomFormMarkupPath)) { _dataTypeDescriptorFormsHelper.CustomFormDefinition = XDocument.Load(CustomFormMarkupPath, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo); } _dataTypeDescriptorFormsHelper.LayoutIconHandle = IconResourceName; _dataTypeDescriptorFormsHelper.AddReadOnlyFields(generatedTypesHelper.NotEditableDataFieldDescriptorNames); } return _dataTypeDescriptorFormsHelper; } } public GenericAddDataWorkflow() { InitializeComponent(); } private void initializeCodeActivity_BuildNewData_ExecuteCode(object sender, EventArgs e) { Initialize(); this.FormsHelper.UpdateWithNewBindings(this.Bindings); IData newData = DataFacade.BuildNew(InterfaceType); if (PageFolderFacade.GetAllFolderTypes().Contains(InterfaceType)) { Dictionary<string, string> piggybag = PiggybagSerializer.Deserialize(this.ExtraPayload); var piggybagDataFinder = new PiggybagDataFinder(piggybag, this.EntityToken); IPage page = (IPage)piggybagDataFinder.TryGetData(typeof(IPage)); if (page != null) { PageFolderFacade.AssignFolderDataSpecificValues(newData, page); } } var publishControlled = newData as IPublishControlled; if (publishControlled != null) { publishControlled.PublicationStatus = GenericPublishProcessController.Draft; } var values = new Dictionary<string, string>(); var castedEntityToken = this.EntityToken as TreeDataFieldGroupingElementEntityToken; if (castedEntityToken != null) { Tree tree = TreeFacade.GetTree(castedEntityToken.Source); var treeNode = (DataFolderElementsTreeNode)tree.GetTreeNode(castedEntityToken.TreeNodeId); if (treeNode.Range == null && !treeNode.FirstLetterOnly) { foreach (var kvp in castedEntityToken.DeserializedGroupingValues) { values.Add(kvp.Key, ValueTypeConverter.Convert<string>(kvp.Value)); } } } var props = InterfaceType.GetPropertiesRecursively().ToDictionary(prop => prop.Name); foreach (var kvp in this.DataPayload) { // Filtering payload data which is not default field values if (props.ContainsKey(kvp.Key)) { values[kvp.Key] = StringConversionServices.DeserializeValueString(kvp.Value); } } newData.SetValues(values); this.FormsHelper.ObjectToBindings(newData, this.Bindings); GeneratedTypesHelper.SetNewIdFieldValue(newData); this.Bindings.Add("NewData", newData); } private void step1CodeActivity_DisplayForm_ExecuteCode(object sender, EventArgs e) { Initialize(); if (!BindingExist("DataAdded")) { this.FormsHelper.LayoutLabel = this.FormsHelper.DataTypeDescriptor.Name; } IData newData = this.GetBinding<IData>("NewData"); this.DeliverFormData( this.TypeName, StandardUiContainerTypes.Document, this.FormsHelper.GetForm(), this.Bindings, this.FormsHelper.GetBindingsValidationRules(newData) ); } private void saveCodeActivity_SaveData_ExecuteCode(object sender, EventArgs e) { Initialize(); bool isValid = ValidateBindings(); IData newData = this.GetBinding<IData>("NewData"); if (!BindAndValidate(FormsHelper, newData)) { isValid = false; } if (!isValid) { SetSaveStatus(false); return; } this.RefreshCurrentEntityToken(); if (!this.BindingExist("DataAdded")) { newData = DataFacade.AddNew(newData); this.AcquireLock(newData.GetDataEntityToken()); this.UpdateBinding("NewData", newData); this.Bindings.Add("DataAdded", true); SetSaveStatus(true, newData); } else { DataFacade.Update(newData); SetSaveStatus(true); } PublishControlledHelper.PublishIfNeeded(newData, _doPublish, Bindings, ShowMessage); } private void enablePublishCodeActivity_ExecuteCode(object sender, EventArgs e) { _doPublish = true; } } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/GenericAddDataWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Trees.Workflows { partial class GenericAddDataWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity_SaveData = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.enablePublishCodeActivity = new System.Workflow.Activities.CodeActivity(); this.saveAndPublishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveAndPublishHandleExternalEventActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.step1CodeActivity_DisplayForm = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_BuildNewData = new System.Workflow.Activities.CodeActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_SaveAndPublish = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "step1StateActivity"; // // saveCodeActivity_SaveData // this.saveCodeActivity_SaveData.Name = "saveCodeActivity_SaveData"; this.saveCodeActivity_SaveData.ExecuteCode += new System.EventHandler(this.saveCodeActivity_SaveData_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "saveStateActivity"; // // enablePublishCodeActivity // this.enablePublishCodeActivity.Name = "enablePublishCodeActivity"; this.enablePublishCodeActivity.ExecuteCode += new System.EventHandler(this.enablePublishCodeActivity_ExecuteCode); // // saveAndPublishHandleExternalEventActivity1 // this.saveAndPublishHandleExternalEventActivity1.EventName = "SaveAndPublish"; this.saveAndPublishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveAndPublishHandleExternalEventActivity1.Name = "saveAndPublishHandleExternalEventActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "saveStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // step1CodeActivity_DisplayForm // this.step1CodeActivity_DisplayForm.Name = "step1CodeActivity_DisplayForm"; this.step1CodeActivity_DisplayForm.ExecuteCode += new System.EventHandler(this.step1CodeActivity_DisplayForm_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "step1StateActivity"; // // initializeCodeActivity_BuildNewData // this.initializeCodeActivity_BuildNewData.Name = "initializeCodeActivity_BuildNewData"; this.initializeCodeActivity_BuildNewData.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_BuildNewData_ExecuteCode); // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.saveCodeActivity_SaveData); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity3); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // step1EventDrivenActivity_SaveAndPublish // this.step1EventDrivenActivity_SaveAndPublish.Activities.Add(this.saveAndPublishHandleExternalEventActivity1); this.step1EventDrivenActivity_SaveAndPublish.Activities.Add(this.enablePublishCodeActivity); this.step1EventDrivenActivity_SaveAndPublish.Activities.Add(this.setStateActivity5); this.step1EventDrivenActivity_SaveAndPublish.Name = "step1EventDrivenActivity_SaveAndPublish"; // // step1EventDrivenActivity_Save // this.step1EventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.step1EventDrivenActivity_Save.Activities.Add(this.setStateActivity2); this.step1EventDrivenActivity_Save.Name = "step1EventDrivenActivity_Save"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1CodeActivity_DisplayForm); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_BuildNewData); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.saveStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Save); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_SaveAndPublish); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // GenericAddDataWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.saveStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "GenericAddDataWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity5; private CodeActivity enablePublishCodeActivity; private Workflow.Activities.SaveAndPublishHandleExternalEventActivity saveAndPublishHandleExternalEventActivity1; private EventDrivenActivity step1EventDrivenActivity_SaveAndPublish; private Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private StateActivity saveStateActivity; private StateActivity step1StateActivity; private CodeActivity initializeCodeActivity_BuildNewData; private CodeActivity step1CodeActivity_DisplayForm; private StateInitializationActivity step1StateInitializationActivity; private CodeActivity saveCodeActivity_SaveData; private StateInitializationActivity saveStateInitializationActivity; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity2; private Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity4; private EventDrivenActivity step1EventDrivenActivity_Save; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/GenericAddDataWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1199; 932" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="GenericAddDataWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 209" Location="38; 63"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 44" Location="48; 128" /> <SetStateDesigner Name="setStateActivity1" Size="130; 62" Location="48; 191" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="227; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 209" Location="98; 171"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_BuildNewData" Size="130; 44" Location="108; 236" /> <SetStateDesigner Name="setStateActivity4" Size="130; 62" Location="108; 299" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="275; 110" AutoSizeMargin="16; 24" AutoSize="False" Location="269; 373" Name="step1StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1StateInitializationActivity" Size="150; 128" Location="546; 141"> <StateInitializationDesigner.Designers> <CodeDesigner Name="step1CodeActivity_DisplayForm" Size="130; 44" Location="556; 206" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Save" Size="150; 209" Location="546; 167"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130; 44" Location="556; 232" /> <SetStateDesigner Name="setStateActivity2" Size="130; 62" Location="556; 295" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_SaveAndPublish" Size="150; 272" Location="554; 154"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveAndPublishHandleExternalEventActivity1" Size="130; 44" Location="564; 219" /> <CodeDesigner Name="enablePublishCodeActivity" Size="130; 44" Location="564; 282" /> <SetStateDesigner Name="setStateActivity5" Size="130; 62" Location="564; 345" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="206; 80" AutoSizeMargin="16; 24" Location="553; 561" Name="saveStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="saveStateInitializationActivity" Size="150; 209" Location="561; 594"> <StateInitializationDesigner.Designers> <CodeDesigner Name="saveCodeActivity_SaveData" Size="130; 44" Location="571; 659" /> <SetStateDesigner Name="setStateActivity3" Size="130; 62" Location="571; 722" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="GenericAddDataWorkflow" TargetConnectionIndex="0" SourceStateName="GenericAddDataWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="74" /> <ns0:Point X="1058" Y="74" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity4" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="313" Y="182" /> <ns0:Point X="406" Y="182" /> <ns0:Point X="406" Y="373" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" SetStateName="setStateActivity2" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="479" Y="443" /> <ns0:Point X="656" Y="443" /> <ns0:Point X="656" Y="561" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity3" SourceActivity="saveStateActivity" TargetConnectionIndex="0" SourceStateName="saveStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="saveStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="755" Y="605" /> <ns0:Point X="766" Y="605" /> <ns0:Point X="766" Y="365" /> <ns0:Point X="406" Y="365" /> <ns0:Point X="406" Y="373" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" SetStateName="setStateActivity5" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_SaveAndPublish" SourceConnectionIndex="2" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="540" Y="469" /> <ns0:Point X="656" Y="469" /> <ns0:Point X="656" Y="561" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/GenericDeleteDataWorkflow.cs ================================================ using System.Collections.Generic; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.ProcessControlled; using Composite.Core.ResourceSystem; using Composite.C1Console.Workflow; namespace Composite.C1Console.Trees.Workflows { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class GenericDeleteDataWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public GenericDeleteDataWorkflow() { InitializeComponent(); } private void HasDataReferences(object sender, ConditionalEventArgs e) { IData data = ((DataEntityToken)this.EntityToken).Data; this.Bindings.Add("Text", string.Format("{0}: {1}", Composite.Core.ResourceSystem.StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeGenericDeleteConfirm.Text"), data.GetLabel())); var brokenReferences = new List<IData>(); List<IData> references = DataReferenceFacade.GetNotOptionalReferences(data); foreach (IData reference in references) { DataSourceId dataSourceId = reference.DataSourceId; if (brokenReferences.Any(brokenRef => brokenRef.DataSourceId == dataSourceId)) { continue; } brokenReferences.Add(reference); } e.Result = brokenReferences.Count > 0; if (brokenReferences.Count == 0) { return; } Bindings.Add("ReferencedData", DataReferenceFacade.GetBrokenReferencesReport(brokenReferences)); } private void finalizeCodeActivity_DeteleData_ExecuteCode(object sender, System.EventArgs e) { DeleteTreeRefresher deleteTreeRefresher = this.CreateDeleteTreeRefresher(this.EntityToken); IData data = ((DataEntityToken)this.EntityToken).Data; if (DataFacade.WillDeleteSucceed(data)) { ProcessControllerFacade.FullDelete(data); deleteTreeRefresher.PostRefreshMesseges(true); } else { this.ShowMessage( DialogType.Error, StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeGenericDelete.CascadeDeleteErrorTitle"), StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeGenericDelete.CascadeDeleteErrorMessage") ); } } } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/GenericDeleteDataWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Trees.Workflows { partial class GenericDeleteDataWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.confirmConfirmDialogFormActivity_ShowConfirmDialog = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.confirmConfirmDialogFormActivity_ShowDataReferenceDialog = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_DeteleData = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmIfElseActivity_HasDataReferences = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.confirmEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.confirmEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.confirmStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.confirmStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // confirmConfirmDialogFormActivity_ShowConfirmDialog // this.confirmConfirmDialogFormActivity_ShowConfirmDialog.ContainerLabel = null; this.confirmConfirmDialogFormActivity_ShowConfirmDialog.FormDefinitionFileName = "/Administrative/TreeGenericDeleteConfirm.xml"; this.confirmConfirmDialogFormActivity_ShowConfirmDialog.Name = "confirmConfirmDialogFormActivity_ShowConfirmDialog"; // // confirmConfirmDialogFormActivity_ShowDataReferenceDialog // this.confirmConfirmDialogFormActivity_ShowDataReferenceDialog.ContainerLabel = null; this.confirmConfirmDialogFormActivity_ShowDataReferenceDialog.FormDefinitionFileName = "/Administrative/TreeGenericDeleteConfirmDeletingRelatedData.xml"; this.confirmConfirmDialogFormActivity_ShowDataReferenceDialog.Name = "confirmConfirmDialogFormActivity_ShowDataReferenceDialog"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.confirmConfirmDialogFormActivity_ShowConfirmDialog); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.confirmConfirmDialogFormActivity_ShowDataReferenceDialog); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.HasDataReferences); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_DeteleData // this.finalizeCodeActivity_DeteleData.Name = "finalizeCodeActivity_DeteleData"; this.finalizeCodeActivity_DeteleData.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_DeteleData_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // confirmIfElseActivity_HasDataReferences // this.confirmIfElseActivity_HasDataReferences.Activities.Add(this.ifElseBranchActivity1); this.confirmIfElseActivity_HasDataReferences.Activities.Add(this.ifElseBranchActivity2); this.confirmIfElseActivity_HasDataReferences.Name = "confirmIfElseActivity_HasDataReferences"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "confirmStateActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_DeteleData); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity6); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // confirmEventDrivenActivity_Cancel // this.confirmEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.confirmEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity2); this.confirmEventDrivenActivity_Cancel.Name = "confirmEventDrivenActivity_Cancel"; // // confirmEventDrivenActivity_Finish // this.confirmEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.confirmEventDrivenActivity_Finish.Activities.Add(this.setStateActivity5); this.confirmEventDrivenActivity_Finish.Name = "confirmEventDrivenActivity_Finish"; // // confirmStateInitializationActivity // this.confirmStateInitializationActivity.Activities.Add(this.confirmIfElseActivity_HasDataReferences); this.confirmStateInitializationActivity.Name = "confirmStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity3); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // confirmStateActivity // this.confirmStateActivity.Activities.Add(this.confirmStateInitializationActivity); this.confirmStateActivity.Activities.Add(this.confirmEventDrivenActivity_Finish); this.confirmStateActivity.Activities.Add(this.confirmEventDrivenActivity_Cancel); this.confirmStateActivity.Name = "confirmStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // GenericDeleteDataWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.confirmStateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "GenericDeleteDataWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private StateActivity finalizeStateActivity; private StateActivity confirmStateActivity; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity confirmEventDrivenActivity_Cancel; private EventDrivenActivity confirmEventDrivenActivity_Finish; private StateInitializationActivity confirmStateInitializationActivity; private SetStateActivity setStateActivity2; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private SetStateActivity setStateActivity6; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity confirmIfElseActivity_HasDataReferences; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmConfirmDialogFormActivity_ShowConfirmDialog; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmConfirmDialogFormActivity_ShowDataReferenceDialog; private SetStateActivity setStateActivity3; private CodeActivity finalizeCodeActivity_DeteleData; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/GenericDeleteDataWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="GenericDeleteDataWorkflow" Location="30; 30" Size="1202; 996" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="GenericDeleteDataWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="GenericDeleteDataWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="confirmStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="confirmStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="398" Y="179" /> <ns0:Point X="398" Y="315" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="confirmStateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="confirmStateActivity" EventHandlerName="confirmEventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="501" Y="380" /> <ns0:Point X="552" Y="380" /> <ns0:Point X="552" Y="585" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="confirmStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="confirmStateActivity" EventHandlerName="confirmEventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="505" Y="404" /> <ns0:Point X="1058" Y="404" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="651" Y="626" /> <ns0:Point X="1058" Y="626" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="108; 231" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="confirmStateActivity" Location="288; 315" Size="221; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 303" Name="confirmStateInitializationActivity" Location="296; 346"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="361; 222" Name="confirmIfElseActivity_HasDataReferences" Location="306; 408"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity1" Location="325; 479"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="confirmConfirmDialogFormActivity_ShowDataReferenceDialog" Location="335; 541" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity2" Location="498; 479"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="confirmConfirmDialogFormActivity_ShowConfirmDialog" Location="508; 541" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="confirmEventDrivenActivity_Finish" Location="296; 370"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity2" Location="306; 432" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="306; 492" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="confirmEventDrivenActivity_Cancel" Location="296; 394"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity3" Location="306; 456" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="306; 516" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="450; 585" Size="205; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="finalizeStateInitializationActivity" Location="556; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity_DeteleData" Location="566; 210" /> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="566; 270" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/GenericEditDataWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Scheduling; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.C1Console.Workflow.Foundation; using Composite.Core.ResourceSystem; using Composite.Core.Serialization; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; namespace Composite.C1Console.Trees.Workflows { [EntityTokenLock] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class GenericEditDataWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { [NonSerialized] private bool _doPublish; [NonSerialized] private DataTypeDescriptorFormsHelper _dataTypeDescriptorFormsHelper; [NonSerialized] private string _typeName; private DataTypeDescriptorFormsHelper FormsHelper { get { if (_dataTypeDescriptorFormsHelper == null) { if (String.IsNullOrEmpty(this.Payload)) { throw new InvalidOperationException("Action token's 'Payload' property is null or empty"); } Dictionary<string, string> serializedValues = StringConversionServices.ParseKeyValueCollection(this.Payload); string iconResourceName = StringConversionServices.DeserializeValueString(serializedValues["_IconResourceName_"]); string customFormMarkupPath = null; if (serializedValues.ContainsKey("_CustomFormMarkupPath_")) { customFormMarkupPath = StringConversionServices.DeserializeValueString(serializedValues["_CustomFormMarkupPath_"]); } DataEntityToken dataEntityToken = this.EntityToken as DataEntityToken; Verify.IsNotNull(dataEntityToken, "The given entity token is of wrong type"); Type interfaceType = dataEntityToken.InterfaceType; DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(interfaceType); Verify.IsNotNull(dataTypeDescriptor, "Can not find the type descriptor for the type '{0}'", interfaceType); _typeName = dataTypeDescriptor.Name; var generatedTypesHelper = new GeneratedTypesHelper(dataTypeDescriptor) { AllowForeignKeyEditing = true }; _dataTypeDescriptorFormsHelper = new DataTypeDescriptorFormsHelper(dataTypeDescriptor, true, this.EntityToken); if (!string.IsNullOrEmpty(customFormMarkupPath)) { _dataTypeDescriptorFormsHelper.CustomFormDefinition = XDocument.Load(customFormMarkupPath, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo); } _dataTypeDescriptorFormsHelper.LayoutIconHandle = iconResourceName; _dataTypeDescriptorFormsHelper.AddReadOnlyFields(generatedTypesHelper.NotEditableDataFieldDescriptorNames); } return _dataTypeDescriptorFormsHelper; } } private string TypeName { get { return _typeName; } } public GenericEditDataWorkflow() { InitializeComponent(); } private void editCodeActivity_DisplayForm_ExecuteCode(object sender, EventArgs e) { IData data = ((DataEntityToken)this.EntityToken).Data; if (!PermissionsFacade.GetPermissionsForCurrentUser(EntityToken).Contains(PermissionType.Publish) || !(data is IPublishControlled)) { FormData formData = WorkflowFacade.GetFormData(InstanceId, true); if (formData.ExcludedEvents == null) formData.ExcludedEvents = new List<string>(); formData.ExcludedEvents.Add("SaveAndPublish"); } if (data is IPublishControlled) { IPublishControlled publishControlledData = (IPublishControlled)data; if (publishControlledData.PublicationStatus == GenericPublishProcessController.Published) { publishControlledData.PublicationStatus = GenericPublishProcessController.Draft; } } this.FormsHelper.UpdateWithBindings(data, this.Bindings); this.FormsHelper.LayoutLabel = data.GetLabel(true); this.DeliverFormData( this.TypeName, StandardUiContainerTypes.Document, this.FormsHelper.GetForm(), this.Bindings, this.FormsHelper.GetBindingsValidationRules(data) ); } private void saveCodeActivity_UpdateData_ExecuteCode(object sender, EventArgs e) { UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken); IData data = ((DataEntityToken)this.EntityToken).Data; bool isValid = ValidateBindings(); if (!BindAndValidate(this.FormsHelper, data)) { isValid = false; } var fieldsWithBrokenReferences = new List<string>(); if (!data.TryValidateForeignKeyIntegrity(fieldsWithBrokenReferences)) { isValid = false; foreach (string fieldName in fieldsWithBrokenReferences) { ShowFieldMessage(fieldName, LocalizationFiles.Composite_Management.Validation_BrokenReference); } } if (isValid) { if (data is IPublishControlled) { IPublishControlled publishControlledData = (IPublishControlled)data; if (publishControlledData.PublicationStatus == GenericPublishProcessController.Published) { publishControlledData.PublicationStatus = GenericPublishProcessController.Draft; } } DataFacade.Update(data); EntityTokenCacheFacade.ClearCache(EntityToken); updateTreeRefresher.PostRefreshMesseges(this.EntityToken); PublishControlledHelper.PublishIfNeeded(data, _doPublish, Bindings, ShowMessage); } SetSaveStatus(isValid); } private void enablePublishCodeActivity_ExecuteCode(object sender, EventArgs e) { _doPublish = true; } } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/GenericEditDataWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Trees.Workflows { partial class GenericEditDataWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity_UpdateData = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.enablePublishCodeActivity = new System.Workflow.Activities.CodeActivity(); this.saveAndPublishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveAndPublishHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.editCodeActivity_DisplayForm = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editEventDrivenActivity_SaveAndPublish = new System.Workflow.Activities.EventDrivenActivity(); this.editEventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // saveCodeActivity_UpdateData // this.saveCodeActivity_UpdateData.Name = "saveCodeActivity_UpdateData"; this.saveCodeActivity_UpdateData.ExecuteCode += new System.EventHandler(this.saveCodeActivity_UpdateData_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "saveStateActivity"; // // enablePublishCodeActivity // this.enablePublishCodeActivity.Name = "enablePublishCodeActivity"; this.enablePublishCodeActivity.ExecuteCode += new System.EventHandler(this.enablePublishCodeActivity_ExecuteCode); // // saveAndPublishHandleExternalEventActivity1 // this.saveAndPublishHandleExternalEventActivity1.EventName = "SaveAndPublish"; this.saveAndPublishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveAndPublishHandleExternalEventActivity1.Name = "saveAndPublishHandleExternalEventActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "saveStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // editCodeActivity_DisplayForm // this.editCodeActivity_DisplayForm.Name = "editCodeActivity_DisplayForm"; this.editCodeActivity_DisplayForm.ExecuteCode += new System.EventHandler(this.editCodeActivity_DisplayForm_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.saveCodeActivity_UpdateData); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity4); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // editEventDrivenActivity_SaveAndPublish // this.editEventDrivenActivity_SaveAndPublish.Activities.Add(this.saveAndPublishHandleExternalEventActivity1); this.editEventDrivenActivity_SaveAndPublish.Activities.Add(this.enablePublishCodeActivity); this.editEventDrivenActivity_SaveAndPublish.Activities.Add(this.setStateActivity5); this.editEventDrivenActivity_SaveAndPublish.Name = "editEventDrivenActivity_SaveAndPublish"; // // editEventDrivenActivity_Save // this.editEventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.editEventDrivenActivity_Save.Activities.Add(this.setStateActivity3); this.editEventDrivenActivity_Save.Name = "editEventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.editCodeActivity_DisplayForm); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.saveStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_Save); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_SaveAndPublish); this.editStateActivity.Name = "editStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // GenericEditDataWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "GenericEditDataWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity5; private CodeActivity enablePublishCodeActivity; private Workflow.Activities.SaveAndPublishHandleExternalEventActivity saveAndPublishHandleExternalEventActivity1; private EventDrivenActivity editEventDrivenActivity_SaveAndPublish; private Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private StateActivity editStateActivity; private CodeActivity editCodeActivity_DisplayForm; private SetStateActivity setStateActivity2; private StateInitializationActivity saveStateInitializationActivity; private EventDrivenActivity editEventDrivenActivity_Save; private StateInitializationActivity editStateInitializationActivity; private StateActivity saveStateActivity; private CodeActivity saveCodeActivity_UpdateData; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity3; private Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/GenericEditDataWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1199; 932" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="GenericEditDataWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 209" Location="38; 63"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 44" Location="48; 128" /> <SetStateDesigner Name="setStateActivity1" Size="130; 62" Location="48; 191" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="227; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 146" Location="98; 171"> <StateInitializationDesigner.Designers> <SetStateDesigner Name="setStateActivity2" Size="130; 62" Location="108; 236" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="267; 110" AutoSizeMargin="16; 24" AutoSize="False" Location="237; 396" Name="editStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="editStateInitializationActivity" Size="150; 128" Location="546; 141"> <StateInitializationDesigner.Designers> <CodeDesigner Name="editCodeActivity_DisplayForm" Size="130; 44" Location="556; 206" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="editEventDrivenActivity_Save" Size="150; 209" Location="546; 167"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130; 44" Location="556; 232" /> <SetStateDesigner Name="setStateActivity3" Size="130; 62" Location="556; 295" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="editEventDrivenActivity_SaveAndPublish" Size="150; 272" Location="554; 154"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveAndPublishHandleExternalEventActivity1" Size="130; 44" Location="564; 219" /> <CodeDesigner Name="enablePublishCodeActivity" Size="130; 44" Location="564; 282" /> <SetStateDesigner Name="setStateActivity5" Size="130; 62" Location="564; 345" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="206; 80" AutoSizeMargin="16; 24" Location="558; 492" Name="saveStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="saveStateInitializationActivity" Size="150; 209" Location="566; 525"> <StateInitializationDesigner.Designers> <CodeDesigner Name="saveCodeActivity_UpdateData" Size="130; 44" Location="576; 590" /> <SetStateDesigner Name="setStateActivity4" Size="130; 62" Location="576; 653" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="GenericEditDataWorkflow" TargetConnectionIndex="0" SourceStateName="GenericEditDataWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="74" /> <ns0:Point X="1058" Y="74" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="313" Y="182" /> <ns0:Point X="370" Y="182" /> <ns0:Point X="370" Y="396" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" SetStateName="setStateActivity3" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editEventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="438" Y="466" /> <ns0:Point X="661" Y="466" /> <ns0:Point X="661" Y="492" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity4" SourceActivity="saveStateActivity" TargetConnectionIndex="0" SourceStateName="saveStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="saveStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="760" Y="536" /> <ns0:Point X="770" Y="536" /> <ns0:Point X="770" Y="388" /> <ns0:Point X="370" Y="388" /> <ns0:Point X="370" Y="396" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" SetStateName="setStateActivity5" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editEventDrivenActivity_SaveAndPublish" SourceConnectionIndex="2" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="500" Y="492" /> <ns0:Point X="516" Y="492" /> <ns0:Point X="516" Y="484" /> <ns0:Point X="661" Y="484" /> <ns0:Point X="661" Y="492" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/LocalizeDataWorkflow.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Transactions; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Core.Linq; using Composite.Core.ResourceSystem; using Composite.Data.Transactions; using Composite.Core.Types; using Composite.C1Console.Users; using Composite.C1Console.Security; namespace Composite.C1Console.Trees.Workflows { public sealed partial class LocalizeDataWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public LocalizeDataWorkflow() { InitializeComponent(); } private void ValidateReferencingProperties(object sender, ConditionalEventArgs e) { var dataEntityToken = (DataEntityToken)this.EntityToken; var data = dataEntityToken.Data as ILocalizedControlled; IEnumerable<ReferenceFailingPropertyInfo> referenceFailingProperties = DataLocalizationFacade.GetReferencingLocalizeFailingProperties(data).Evaluate(); if (referenceFailingProperties.Any(f => f.OptionalReferenceWithValue == false)) { List<string> row = new List<string>(); row.Add(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "LocalizeData.ShowError.Description")); foreach (ReferenceFailingPropertyInfo referenceFailingPropertyInfo in referenceFailingProperties.Where(f => f.OptionalReferenceWithValue == false)) { row.Add(string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "LocalizeData.ShowError.FieldErrorFormat"), referenceFailingPropertyInfo.DataFieldDescriptor.Name, referenceFailingPropertyInfo.ReferencedType.GetTypeTitle(), referenceFailingPropertyInfo.OriginLocaleDataValue.GetLabel())); } List<List<string>> rows = new List<List<string>> { row }; this.UpdateBinding("ErrorHeader", new List<string> { "Fields" }); this.UpdateBinding("Errors", rows); e.Result = false; } else { e.Result = true; } } private void localizeDataCodeActivity_Localize_ExecuteCode(object sender, EventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; ILocalizedControlled data = dataEntityToken.Data as ILocalizedControlled; CultureInfo targetCultureInfo = UserSettings.ActiveLocaleCultureInfo; if (ExistsInLocale(data, targetCultureInfo)) { this.ShowMessage( DialogType.Message, StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "LocalizeData.ShowError.Layout.Label"), StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "LocalizeData.ShowError.AlreadyTranslated") ); return; } IEnumerable<ReferenceFailingPropertyInfo> referenceFailingPropertyInfos = DataLocalizationFacade.GetReferencingLocalizeFailingProperties(data).Evaluate(); IData newData; using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { data = data.GetTranslationSource(); using (new DataScope(targetCultureInfo)) { newData = DataFacade.BuildNew(data.DataSourceId.InterfaceType); data.ProjectedCopyTo(newData); ILocalizedControlled localizedControlled = newData as ILocalizedControlled; localizedControlled.SourceCultureName = targetCultureInfo.Name; if (newData is IPublishControlled) { IPublishControlled publishControlled = newData as IPublishControlled; publishControlled.PublicationStatus = GenericPublishProcessController.Draft; } foreach (ReferenceFailingPropertyInfo referenceFailingPropertyInfo in referenceFailingPropertyInfos) { PropertyInfo propertyInfo = data.DataSourceId.InterfaceType.GetPropertiesRecursively().Single(f => f.Name == referenceFailingPropertyInfo.DataFieldDescriptor.Name); if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { propertyInfo.SetValue(newData, null, null); } else if (propertyInfo.PropertyType == typeof(string)) { propertyInfo.SetValue(newData, null, null); } else { propertyInfo.SetValue(newData, referenceFailingPropertyInfo.DataFieldDescriptor.DefaultValue.Value, null); } } newData = DataFacade.AddNew(newData); } EntityTokenCacheFacade.ClearCache(data.GetDataEntityToken()); EntityTokenCacheFacade.ClearCache(newData.GetDataEntityToken()); transactionScope.Complete(); } ParentTreeRefresher parentTreeRefresher = this.CreateParentTreeRefresher(); parentTreeRefresher.PostRefreshMesseges(newData.GetDataEntityToken(), 2); } private static bool ExistsInLocale(IData data, CultureInfo locale) { Type dataType = data.DataSourceId.InterfaceType; MethodInfo getDataFromOtherScopeMethodInfo = typeof(DataFacade).GetMethod("GetDataFromOtherLocale", BindingFlags.Public | BindingFlags.Static); MethodInfo genericMethod = getDataFromOtherScopeMethodInfo.MakeGenericMethod(new[] { dataType }); object result = genericMethod.Invoke(null, new object[] { data, locale }); if (result == null) return false; var enumerable = result as IEnumerable; Verify.IsNotNull(enumerable, "Enumeration expected"); return enumerable.Cast<object>().Any(); } } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/LocalizeDataWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Trees.Workflows { partial class LocalizeDataWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.localizeDataCodeActivity_Localize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizardFormActivity1 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.initializeIfElseActivity_ValidateReferencingPropertyies = new System.Workflow.Activities.IfElseActivity(); this.localizeDataStateInitializationActivity_Localize = new System.Workflow.Activities.StateInitializationActivity(); this.showErrorEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.showErrorStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.localizeDataStateActivity = new System.Workflow.Activities.StateActivity(); this.showErrorStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "showErrorStateActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "localizeDataStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity3); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity2); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateReferencingProperties); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // localizeDataCodeActivity_Localize // this.localizeDataCodeActivity_Localize.Name = "localizeDataCodeActivity_Localize"; this.localizeDataCodeActivity_Localize.ExecuteCode += new System.EventHandler(this.localizeDataCodeActivity_Localize_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // wizardFormActivity1 // this.wizardFormActivity1.ContainerLabel = null; this.wizardFormActivity1.FormDefinitionFileName = "\\Administrative\\TreeLocalizeData.xml"; this.wizardFormActivity1.Name = "wizardFormActivity1"; // // initializeIfElseActivity_ValidateReferencingPropertyies // this.initializeIfElseActivity_ValidateReferencingPropertyies.Activities.Add(this.ifElseBranchActivity1); this.initializeIfElseActivity_ValidateReferencingPropertyies.Activities.Add(this.ifElseBranchActivity2); this.initializeIfElseActivity_ValidateReferencingPropertyies.Name = "initializeIfElseActivity_ValidateReferencingPropertyies"; // // localizeDataStateInitializationActivity_Localize // this.localizeDataStateInitializationActivity_Localize.Activities.Add(this.localizeDataCodeActivity_Localize); this.localizeDataStateInitializationActivity_Localize.Activities.Add(this.setStateActivity5); this.localizeDataStateInitializationActivity_Localize.Name = "localizeDataStateInitializationActivity_Localize"; // // showErrorEventDrivenActivity_Finish // this.showErrorEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.showErrorEventDrivenActivity_Finish.Activities.Add(this.setStateActivity4); this.showErrorEventDrivenActivity_Finish.Name = "showErrorEventDrivenActivity_Finish"; // // showErrorStateInitializationActivity // this.showErrorStateInitializationActivity.Activities.Add(this.wizardFormActivity1); this.showErrorStateInitializationActivity.Name = "showErrorStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeIfElseActivity_ValidateReferencingPropertyies); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // localizeDataStateActivity // this.localizeDataStateActivity.Activities.Add(this.localizeDataStateInitializationActivity_Localize); this.localizeDataStateActivity.Name = "localizeDataStateActivity"; // // showErrorStateActivity // this.showErrorStateActivity.Activities.Add(this.showErrorStateInitializationActivity); this.showErrorStateActivity.Activities.Add(this.showErrorEventDrivenActivity_Finish); this.showErrorStateActivity.Name = "showErrorStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // LocalizeDataWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.showErrorStateActivity); this.Activities.Add(this.localizeDataStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "LocalizeDataWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity2; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity initializeIfElseActivity_ValidateReferencingPropertyies; private StateActivity localizeDataStateActivity; private StateActivity showErrorStateActivity; private StateInitializationActivity localizeDataStateInitializationActivity_Localize; private StateInitializationActivity showErrorStateInitializationActivity; private SetStateActivity setStateActivity5; private CodeActivity localizeDataCodeActivity_Localize; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private C1Console.Workflow.Activities.WizardFormActivity wizardFormActivity1; private EventDrivenActivity showErrorEventDrivenActivity_Finish; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/LocalizeDataWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1115; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="LocalizeDataWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="381; 303" Location="98; 169"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="initializeIfElseActivity_ValidateReferencingPropertyies" Size="361; 222" Location="108; 231"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 122" Location="127; 302"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="137; 364" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 122" Location="300; 302"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="310; 364" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="936; 799" Name="finalStateActivity" /> <StateDesigner Size="230; 80" AutoSizeMargin="16; 24" Location="201; 487" Name="showErrorStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="showErrorStateInitializationActivity" Size="150; 122" Location="209; 518"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizardFormActivity1" Size="130; 41" Location="219; 580" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="showErrorEventDrivenActivity_Finish" Size="150; 182" Location="209; 542"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="219; 604" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="219; 664" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="275; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="525; 327" Name="localizeDataStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="localizeDataStateInitializationActivity_Localize" Size="150; 182" Location="512; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Name="localizeDataCodeActivity_Localize" Size="130; 41" Location="522; 210" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="522; 270" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="LocalizeDataWorkflow" TargetConnectionIndex="0" SourceStateName="LocalizeDataWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1023" Y="71" /> <ns0:Point X="1023" Y="799" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="localizeDataStateActivity" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="localizeDataStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="662" Y="179" /> <ns0:Point X="662" Y="327" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="showErrorStateActivity" SetStateName="setStateActivity3" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="showErrorStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="316" Y="179" /> <ns0:Point X="316" Y="487" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity4" SourceActivity="showErrorStateActivity" TargetConnectionIndex="0" SourceStateName="showErrorStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="showErrorEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="427" Y="552" /> <ns0:Point X="1023" Y="552" /> <ns0:Point X="1023" Y="799" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity5" SourceActivity="localizeDataStateActivity" TargetConnectionIndex="0" SourceStateName="localizeDataStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="localizeDataStateInitializationActivity_Localize" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="796" Y="368" /> <ns0:Point X="1023" Y="368" /> <ns0:Point X="1023" Y="799" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/RemoveApplicationWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Transactions; using System.Workflow.Activities; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.Types; using Composite.Data.Transactions; using Composite.C1Console.Trees; using Composite.C1Console.Trees.Foundation.AttachmentPoints; using Composite.Core.Types; using Composite.C1Console.Workflow; namespace Composite.C1Console.Trees.Workflows { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class RemoveApplicationWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public RemoveApplicationWorkflow() { InitializeComponent(); } private void IsThereAnyTrees(object sender, ConditionalEventArgs e) { e.Result = this.BindingExist("SelectedTreeId"); } private void initializeCodeActivity_UpdateBindings_ExecuteCode(object sender, EventArgs e) { Dictionary<string, string> selectableTreeIds = new Dictionary<string, string>(); foreach (Tree tree in TreeFacade.AllTrees) { if (!tree.HasAttachmentPoints(this.EntityToken)) continue; if (!tree.HasPossibleAttachmentPoints(this.EntityToken)) continue; selectableTreeIds.Add(tree.TreeId, tree.AllowedAttachmentApplicationName); } if (selectableTreeIds.Count > 0) { this.UpdateBinding("SelectedTreeId", selectableTreeIds.First().Key); this.UpdateBinding("SelectableTreeIds", selectableTreeIds); } } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { string treeId = this.GetBinding<string>("SelectedTreeId"); Tree tree = TreeFacade.GetTree(treeId); DynamicDataItemAttachmentPoint dataItemAttachmentPoint = (DynamicDataItemAttachmentPoint)tree.GetAttachmentPoints(this.EntityToken).Single(); TreeFacade.RemovePersistedAttachmentPoint(treeId, dataItemAttachmentPoint.InterfaceType, dataItemAttachmentPoint.KeyValue); this.RefreshCurrentEntityToken(); } private void initializeCodeActivity_ShowNoTreesMessage_ExecuteCode(object sender, EventArgs e) { this.ShowMessage(DialogType.Message, "${Composite.C1Console.Trees, RemoveApplication.NoTrees.Title}", "${Composite.C1Console.Trees, RemoveApplication.NoTrees.Message}"); } } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/RemoveApplicationWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Trees.Workflows { partial class RemoveApplicationWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_ShowNoTreesMessage = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.wizardFormActivity1 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.initializeIfElseActivity_IsThereAnyTrees = new System.Workflow.Activities.IfElseActivity(); this.initializeCodeActivity_UpdateBindings = new System.Workflow.Activities.CodeActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // initializeCodeActivity_ShowNoTreesMessage // this.initializeCodeActivity_ShowNoTreesMessage.Name = "initializeCodeActivity_ShowNoTreesMessage"; this.initializeCodeActivity_ShowNoTreesMessage.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ShowNoTreesMessage_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "step1StateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.initializeCodeActivity_ShowNoTreesMessage); this.ifElseBranchActivity2.Activities.Add(this.setStateActivity6); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity5); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsThereAnyTrees); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // wizardFormActivity1 // this.wizardFormActivity1.ContainerLabel = null; this.wizardFormActivity1.FormDefinitionFileName = "\\Administrative\\TreeRemoveApplication.xml"; this.wizardFormActivity1.Name = "wizardFormActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // initializeIfElseActivity_IsThereAnyTrees // this.initializeIfElseActivity_IsThereAnyTrees.Activities.Add(this.ifElseBranchActivity1); this.initializeIfElseActivity_IsThereAnyTrees.Activities.Add(this.ifElseBranchActivity2); this.initializeIfElseActivity_IsThereAnyTrees.Name = "initializeIfElseActivity_IsThereAnyTrees"; // // initializeCodeActivity_UpdateBindings // this.initializeCodeActivity_UpdateBindings.Name = "initializeCodeActivity_UpdateBindings"; this.initializeCodeActivity_UpdateBindings.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_UpdateBindings_ExecuteCode); // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity3); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.wizardFormActivity1); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity4); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity2); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_UpdateBindings); this.initializeStateInitializationActivity.Activities.Add(this.initializeIfElseActivity_IsThereAnyTrees); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Activities.Add(this.stateInitializationActivity1); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // RemoveApplicationWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "RemoveApplicationWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity6; private CodeActivity initializeCodeActivity_ShowNoTreesMessage; private SetStateActivity setStateActivity5; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private IfElseActivity initializeIfElseActivity_IsThereAnyTrees; private StateInitializationActivity finalizeStateInitializationActivity; private StateInitializationActivity stateInitializationActivity1; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private CodeActivity initializeCodeActivity_UpdateBindings; private CodeActivity finalizeCodeActivity_Finalize; private C1Console.Workflow.Activities.WizardFormActivity wizardFormActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/RemoveApplicationWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1196; 965" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="RemoveApplicationWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="381; 423" Location="98; 169"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_UpdateBindings" Size="130; 41" Location="223; 231" /> <IfElseDesigner Name="initializeIfElseActivity_IsThereAnyTrees" Size="361; 282" Location="108; 291"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 182" Location="127; 362"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="137; 454" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 182" Location="300; 362"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_ShowNoTreesMessage" Size="130; 41" Location="310; 424" /> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="310; 484" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="211; 102" AutoSizeMargin="16; 24" AutoSize="False" Location="371; 368" Name="step1StateActivity"> <StateDesigner.Designers> <EventDrivenDesigner Name="step1EventDrivenActivity_Finish" Size="150; 182" Location="545; 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="555; 221" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="555; 281" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Cancel" Size="150; 182" Location="545; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="555; 245" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="555; 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateInitializationDesigner Name="stateInitializationActivity1" Size="150; 122" Location="553; 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizardFormActivity1" Size="130; 41" Location="563; 210" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" Location="619; 558" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 182" Location="627; 589"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity_Finalize" Size="130; 41" Location="637; 651" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="637; 711" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="RemoveApplicationWorkflow" TargetConnectionIndex="0" SourceStateName="RemoveApplicationWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity2" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="574" Y="433" /> <ns0:Point X="721" Y="433" /> <ns0:Point X="721" Y="558" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity3" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="820" Y="599" /> <ns0:Point X="1058" Y="599" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity4" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="578" Y="457" /> <ns0:Point X="1058" Y="457" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity5" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="476" Y="179" /> <ns0:Point X="476" Y="368" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity6" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="1058" Y="179" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/ReportFunctionActionWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Xml.Linq; using Composite.C1Console.Elements; using Composite.Functions; using Composite.C1Console.Workflow; using Composite.Core.ResourceSystem; using Composite.Core; namespace Composite.C1Console.Trees.Workflows { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class ReportFunctionActionWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public ReportFunctionActionWorkflow() { InitializeComponent(); } private void initializeCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { ReportFunctionActionNode reportFunctionActionNode = (ReportFunctionActionNode)ActionNode.Deserialize(this.Payload); Dictionary<string, string> piggybag = PiggybagSerializer.Deserialize(this.ExtraPayload); var replaceContext = new DynamicValuesHelperReplaceContext(this.EntityToken, piggybag); XElement markup = reportFunctionActionNode.FunctionMarkupDynamicValuesHelper.ReplaceValues(replaceContext); BaseRuntimeTreeNode baseRuntimeTreeNode = FunctionTreeBuilder.Build(markup); XDocument result = baseRuntimeTreeNode.GetValue() as XDocument; if (result == null) { string message = string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeValidationError.ReportFunctionAction.WrongReturnValue"), "XDocument"); Log.LogError("TreeFacade", message); throw new InvalidOperationException(message); } this.Bindings.Add("Label", reportFunctionActionNode.DocumentLabelDynamicValueHelper.ReplaceValues(replaceContext)); this.Bindings.Add("Icon", reportFunctionActionNode.DocumentIcon.ResourceName); this.Bindings.Add("HtmlBlob", result.ToString()); } } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/ReportFunctionActionWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Trees.Workflows { partial class ReportFunctionActionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.EmptyDocumentFormActivity(); this.initializeCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.FormDefinitionFileName = "/Administrative/ReportFunctionAction.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // initializeCodeActivity_Initialize // this.initializeCodeActivity_Initialize.Name = "initializeCodeActivity_Initialize"; this.initializeCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_Initialize_ExecuteCode); // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_Initialize); this.initializeStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // ReportFunctionActionWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "ReportFunctionActionWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private Composite.C1Console.Workflow.Activities.EmptyDocumentFormActivity documentFormActivity1; private CodeActivity initializeCodeActivity_Initialize; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Trees/Workflows/ReportFunctionActionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="ReportFunctionActionWorkflow" Location="30; 30" Size="1155; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="ReportFunctionActionWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="ReportFunctionActionWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initializeStateInitializationActivity" Location="532; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity_Initialize" Location="542; 210" /> <ActivityDesigner Size="130; 41" Name="documentFormActivity1" Location="542; 270" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Users/Workflows/ChangeOwnActiveLocaleWorkflow.cs ================================================ using System; using System.Globalization; using Composite.C1Console.Events; using Composite.C1Console.Workflow; using Composite.Core.ResourceSystem; namespace Composite.C1Console.Users.Workflows { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class ChangeOwnActiveLocaleWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public ChangeOwnActiveLocaleWorkflow() { InitializeComponent(); } private void changeLocaleCodeActivity_Execute_ExecuteCode(object sender, EventArgs e) { WorkflowActionToken workflowActionToken = (WorkflowActionToken)this.ActionToken; CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture(workflowActionToken.Payload); UserSettings.ActiveLocaleCultureInfo = cultureInfo; string currentConsoleId = GetCurrentConsoleId(); foreach (string consoleId in GetConsoleIdsOpenedByCurrentUser()) { if (consoleId != currentConsoleId) { ConsoleMessageQueueFacade.Enqueue(new CloseAllViewsMessageQueueItem { Reason = StringResourceSystemFacade.GetString("Composite.C1Console.Users", "ChangeOwnActiveLocaleWorkflow.CloseAllViews.Message") }, consoleId); } ConsoleMessageQueueFacade.Enqueue(new CollapseAndRefreshConsoleMessageQueueItem(), consoleId); ConsoleMessageQueueFacade.Enqueue(new BroadcastMessageQueueItem { Name = "ActiveLocaleChanged", Value = "" }, consoleId); } } } } ================================================ FILE: Composite.Workflows/C1Console/Users/Workflows/ChangeOwnActiveLocaleWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Users.Workflows { partial class ChangeOwnActiveLocaleWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.changeLocaleCodeActivity_Execute = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.changeLocaleStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.changeLocaleStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // changeLocaleCodeActivity_Execute // this.changeLocaleCodeActivity_Execute.Name = "changeLocaleCodeActivity_Execute"; this.changeLocaleCodeActivity_Execute.ExecuteCode += new System.EventHandler(this.changeLocaleCodeActivity_Execute_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "changeLocaleStateActivity"; // // changeLocaleStateInitializationActivity // this.changeLocaleStateInitializationActivity.Activities.Add(this.changeLocaleCodeActivity_Execute); this.changeLocaleStateInitializationActivity.Activities.Add(this.setStateActivity3); this.changeLocaleStateInitializationActivity.Name = "changeLocaleStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // changeLocaleStateActivity // this.changeLocaleStateActivity.Activities.Add(this.changeLocaleStateInitializationActivity); this.changeLocaleStateActivity.Name = "changeLocaleStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // ChangeOwnActiveLocaleWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.changeLocaleStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "ChangeOwnActiveLocaleWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private CodeActivity changeLocaleCodeActivity_Execute; private StateInitializationActivity changeLocaleStateInitializationActivity; private StateActivity changeLocaleStateActivity; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity2; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Users/Workflows/ChangeOwnActiveLocaleWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="ChangeOwnActiveLocaleWorkflow" Location="30; 30" Size="1162; 996" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="ChangeOwnActiveLocaleWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="ChangeOwnActiveLocaleWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="changeLocaleStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="changeLocaleStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="476" Y="179" /> <ns0:Point X="476" Y="381" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="changeLocaleStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="changeLocaleStateActivity" EventHandlerName="changeLocaleStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="591" Y="422" /> <ns0:Point X="1058" Y="422" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="108; 231" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="changeLocaleStateActivity" Location="357; 381" Size="238; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="changeLocaleStateInitializationActivity" Location="365; 412"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="changeLocaleCodeActivity_Execute" Location="375; 474" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="375; 534" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Users/Workflows/ChangeOwnCultureWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Workflow.Activities; using Composite.Core.Logging; using Composite.Core.ResourceSystem; using Composite.Core.Types; using Composite.C1Console.Workflow; using Composite.Data; namespace Composite.C1Console.Users.Workflows { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class ChangeOwnCultureWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public ChangeOwnCultureWorkflow() { InitializeComponent(); } private void stepInitialize_codeActivity_ExecuteCode(object sender, EventArgs e) { CultureInfo userCulture = UserSettings.CultureInfo; // Copy admins settings CultureInfo c1ConsoleUiLanguage = UserSettings.C1ConsoleUiLanguage; // Copy admins settings List<KeyValuePair> regionLanguageList = StringResourceSystemFacade.GetSupportedCulturesList(); Dictionary<string, string> culturesDictionary = StringResourceSystemFacade.GetAllCultures(); this.Bindings.Add("AllCultures", culturesDictionary); this.Bindings.Add("CultureName", userCulture.Name); this.Bindings.Add("C1ConsoleUiCultures", regionLanguageList); this.Bindings.Add("C1ConsoleUiLanguageName", c1ConsoleUiLanguage.Name); } private void stepFinalize_codeActivity_ExecuteCode(object sender, EventArgs e) { string cultureName = this.GetBinding<string>("CultureName"); string c1ConsoleUiLanguageName = this.GetBinding<string>("C1ConsoleUiLanguageName"); UserSettings.CultureInfo = new CultureInfo(cultureName); UserSettings.C1ConsoleUiLanguage = new CultureInfo(c1ConsoleUiLanguageName); LoggingService.LogVerbose("ChangeOwnCultureWorkflow", string.Format("Changed culture for user to {0}", cultureName)); } private void CultureHasChanged(object sender, ConditionalEventArgs e) { string cultureName = this.GetBinding<string>("CultureName"); string c1ConsoleUiLanguageName = this.GetBinding<string>("C1ConsoleUiLanguageName"); e.Result = UserSettings.CultureInfo.Name != cultureName || UserSettings.C1ConsoleUiLanguage.Name != c1ConsoleUiLanguageName; } private void rebootConsoleActivity_ExecuteCode(object sender, EventArgs e) { this.RebootConsole(); } } } ================================================ FILE: Composite.Workflows/C1Console/Users/Workflows/ChangeOwnCultureWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Users.Workflows { partial class ChangeOwnCultureWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.handleExternalEventActivity1 = new System.Workflow.Activities.HandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.stepInitialize_codeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity11 = new System.Workflow.Activities.SetStateActivity(); this.handleExternalEventActivity3 = new System.Workflow.Activities.HandleExternalEventActivity(); this.step1WizardFormActivity = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.rebootConsoleActivity = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.stepFinalize_codeActivity = new System.Workflow.Activities.CodeActivity(); this.confirm_eventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.confirm_eventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity19 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1_eventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1_eventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.confirmChangeAndReboot = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.initializeActivity = new System.Workflow.Activities.StateActivity(); this.step1State = new System.Workflow.Activities.StateActivity(); this.finalizeActivity = new System.Workflow.Activities.StateActivity(); this.finishState = new System.Workflow.Activities.StateActivity(); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finishState"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "\\Administrative\\ChangeOwnCultureConfirmReboot.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity6); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.confirmDialogFormActivity1); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CultureHasChanged); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalizeActivity"; // // handleExternalEventActivity1 // this.handleExternalEventActivity1.EventName = "Finish"; this.handleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.handleExternalEventActivity1.Name = "handleExternalEventActivity1"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "step1State"; // // stepInitialize_codeActivity // this.stepInitialize_codeActivity.Name = "stepInitialize_codeActivity"; this.stepInitialize_codeActivity.ExecuteCode += new System.EventHandler(this.stepInitialize_codeActivity_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // setStateActivity11 // this.setStateActivity11.Name = "setStateActivity11"; this.setStateActivity11.TargetStateName = "confirmChangeAndReboot"; // // handleExternalEventActivity3 // this.handleExternalEventActivity3.EventName = "Finish"; this.handleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.handleExternalEventActivity3.Name = "handleExternalEventActivity3"; // // step1WizardFormActivity // this.step1WizardFormActivity.ContainerLabel = "Add new"; this.step1WizardFormActivity.FormDefinitionFileName = "\\Administrative\\ChangeOwnCulture.xml"; this.step1WizardFormActivity.Name = "step1WizardFormActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finishState"; // // rebootConsoleActivity // this.rebootConsoleActivity.Name = "rebootConsoleActivity"; this.rebootConsoleActivity.ExecuteCode += new System.EventHandler(this.rebootConsoleActivity_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // stepFinalize_codeActivity // this.stepFinalize_codeActivity.Name = "stepFinalize_codeActivity"; this.stepFinalize_codeActivity.ExecuteCode += new System.EventHandler(this.stepFinalize_codeActivity_ExecuteCode); // // confirm_eventDrivenActivity_Cancel // this.confirm_eventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.confirm_eventDrivenActivity_Cancel.Activities.Add(this.setStateActivity3); this.confirm_eventDrivenActivity_Cancel.Name = "confirm_eventDrivenActivity_Cancel"; // // confirm_eventDrivenActivity_Finish // this.confirm_eventDrivenActivity_Finish.Activities.Add(this.handleExternalEventActivity1); this.confirm_eventDrivenActivity_Finish.Activities.Add(this.setStateActivity2); this.confirm_eventDrivenActivity_Finish.Name = "confirm_eventDrivenActivity_Finish"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.ifElseActivity1); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // setStateActivity19 // this.setStateActivity19.Name = "setStateActivity19"; this.setStateActivity19.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.stepInitialize_codeActivity); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // step1_eventDrivenActivity_Cancel // this.step1_eventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.step1_eventDrivenActivity_Cancel.Activities.Add(this.setStateActivity5); this.step1_eventDrivenActivity_Cancel.Name = "step1_eventDrivenActivity_Cancel"; // // step1_eventDrivenActivity_Finish // this.step1_eventDrivenActivity_Finish.Activities.Add(this.handleExternalEventActivity3); this.step1_eventDrivenActivity_Finish.Activities.Add(this.setStateActivity11); this.step1_eventDrivenActivity_Finish.Name = "step1_eventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1WizardFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.stepFinalize_codeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.rebootConsoleActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity1); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // confirmChangeAndReboot // this.confirmChangeAndReboot.Activities.Add(this.stateInitializationActivity1); this.confirmChangeAndReboot.Activities.Add(this.confirm_eventDrivenActivity_Finish); this.confirmChangeAndReboot.Activities.Add(this.confirm_eventDrivenActivity_Cancel); this.confirmChangeAndReboot.Name = "confirmChangeAndReboot"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity19); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // initializeActivity // this.initializeActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeActivity.Name = "initializeActivity"; // // step1State // this.step1State.Activities.Add(this.step1StateInitializationActivity); this.step1State.Activities.Add(this.step1_eventDrivenActivity_Finish); this.step1State.Activities.Add(this.step1_eventDrivenActivity_Cancel); this.step1State.Name = "step1State"; // // finalizeActivity // this.finalizeActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeActivity.Name = "finalizeActivity"; // // finishState // this.finishState.Name = "finishState"; // // ChangeOwnCultureWorkflow // this.Activities.Add(this.finishState); this.Activities.Add(this.finalizeActivity); this.Activities.Add(this.step1State); this.Activities.Add(this.initializeActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.confirmChangeAndReboot); this.CompletedStateName = "finishState"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeActivity"; this.Name = "ChangeOwnCultureWorkflow"; this.CanModifyActivities = false; } #endregion private StateInitializationActivity step1StateInitializationActivity; private HandleExternalEventActivity handleExternalEventActivity3; private EventDrivenActivity step1_eventDrivenActivity_Finish; private StateActivity finishState; private StateActivity finalizeActivity; private StateInitializationActivity finalizeStateInitializationActivity; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private CodeActivity stepFinalize_codeActivity; private SetStateActivity setStateActivity4; private StateInitializationActivity initializeStateInitializationActivity; private StateActivity initializeActivity; private CodeActivity stepInitialize_codeActivity; private SetStateActivity setStateActivity11; private Composite.C1Console.Workflow.Activities.DataDialogFormActivity step1WizardFormActivity; private SetStateActivity setStateActivity1; private SetStateActivity setStateActivity19; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private SetStateActivity setStateActivity2; private HandleExternalEventActivity handleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private EventDrivenActivity confirm_eventDrivenActivity_Finish; private StateInitializationActivity stateInitializationActivity1; private StateActivity confirmChangeAndReboot; private CodeActivity rebootConsoleActivity; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private EventDrivenActivity confirm_eventDrivenActivity_Cancel; private EventDrivenActivity step1_eventDrivenActivity_Cancel; private SetStateActivity setStateActivity6; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private StateActivity step1State; } } ================================================ FILE: Composite.Workflows/C1Console/Users/Workflows/ChangeOwnForeignLocaleWorkflow.cs ================================================ using System; using System.Linq; using Composite.Data; using System.Collections.Generic; using System.Globalization; using Composite.Core.ResourceSystem; using Composite.C1Console.Events; namespace Composite.C1Console.Users.Workflows { public sealed partial class ChangeOwnForeignLocaleWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public ChangeOwnForeignLocaleWorkflow() { InitializeComponent(); } private void HasActiveLocales(object sender, System.Workflow.Activities.ConditionalEventArgs e) { e.Result = DataLocalizationFacade.ActiveLocalizationCultures.Count() > 1; } private void step1CodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { IEnumerable<CultureInfo> foreignCultures = from l in DataLocalizationFacade.ActiveLocalizationCultures select l; List<KeyValuePair<string, string>> foreignCulturesDictionary = foreignCultures.Select(f => new KeyValuePair<string, string>(f.Name, DataLocalizationFacade.GetCultureTitle(f))).OrderBy(f => f.Value).ToList(); foreignCulturesDictionary.Insert(0, new KeyValuePair<string, string>("NONE", StringResourceSystemFacade.GetString("Composite.C1Console.Users", "ChangeForeignLocaleWorkflow.NoForeignLocaleLabel"))); string selectedForeignCultureName = "NONE"; if (UserSettings.ForeignLocaleCultureInfo != null) { selectedForeignCultureName = UserSettings.ForeignLocaleCultureInfo.Name; } this.Bindings.Add("ForeignCultureName", selectedForeignCultureName); this.Bindings.Add("ForeignCulturesList", foreignCulturesDictionary); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { string foreignCultureName = this.GetBinding<string>("ForeignCultureName"); CultureInfo foreignCultureInfo = null; if (foreignCultureName != "NONE") { foreignCultureInfo = CultureInfo.CreateSpecificCulture(foreignCultureName); } UserSettings.ForeignLocaleCultureInfo = foreignCultureInfo; foreach (string consoleId in GetConsoleIdsOpenedByCurrentUser()) { ConsoleMessageQueueFacade.Enqueue(new BroadcastMessageQueueItem { Name = "ForeignLocaleChanged", Value = "" }, consoleId); } this.CloseCurrentView(); this.CollapseAndRefresh(); } } } ================================================ FILE: Composite.Workflows/C1Console/Users/Workflows/ChangeOwnForeignLocaleWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Users.Workflows { partial class ChangeOwnForeignLocaleWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.dataDialogFormActivity2 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.step1CodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.dataDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.ifElseActivity_HasActiveLocales = new System.Workflow.Activities.IfElseActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.noOrOneActiveLocaleEventDrivenActivit_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.noOrOneActiveLocaleStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.noOrOneActiveLocaleStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "noOrOneActiveLocaleStateActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity3); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity2); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.HasActiveLocales); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // dataDialogFormActivity2 // this.dataDialogFormActivity2.ContainerLabel = null; this.dataDialogFormActivity2.FormDefinitionFileName = "\\Administrative\\ChangeOwnForeignLocaleStep1.xml"; this.dataDialogFormActivity2.Name = "dataDialogFormActivity2"; // // step1CodeActivity_Initialize // this.step1CodeActivity_Initialize.Name = "step1CodeActivity_Initialize"; this.step1CodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.step1CodeActivity_Initialize_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // dataDialogFormActivity1 // this.dataDialogFormActivity1.ContainerLabel = null; this.dataDialogFormActivity1.FormDefinitionFileName = "\\Administrative\\ChangeOwnForeignLocaleNoOrOneActiveLocale.xml"; this.dataDialogFormActivity1.Name = "dataDialogFormActivity1"; // // ifElseActivity_HasActiveLocales // this.ifElseActivity_HasActiveLocales.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity_HasActiveLocales.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity_HasActiveLocales.Name = "ifElseActivity_HasActiveLocales"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity7); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity5); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity6); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1CodeActivity_Initialize); this.step1StateInitializationActivity.Activities.Add(this.dataDialogFormActivity2); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // noOrOneActiveLocaleEventDrivenActivit_Finish // this.noOrOneActiveLocaleEventDrivenActivit_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.noOrOneActiveLocaleEventDrivenActivit_Finish.Activities.Add(this.setStateActivity4); this.noOrOneActiveLocaleEventDrivenActivit_Finish.Name = "noOrOneActiveLocaleEventDrivenActivit_Finish"; // // noOrOneActiveLocaleStateInitializationActivity // this.noOrOneActiveLocaleStateInitializationActivity.Activities.Add(this.dataDialogFormActivity1); this.noOrOneActiveLocaleStateInitializationActivity.Name = "noOrOneActiveLocaleStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.ifElseActivity_HasActiveLocales); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // noOrOneActiveLocaleStateActivity // this.noOrOneActiveLocaleStateActivity.Activities.Add(this.noOrOneActiveLocaleStateInitializationActivity); this.noOrOneActiveLocaleStateActivity.Activities.Add(this.noOrOneActiveLocaleEventDrivenActivit_Finish); this.noOrOneActiveLocaleStateActivity.Name = "noOrOneActiveLocaleStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // ChangeOwnForeignLocaleWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.noOrOneActiveLocaleStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "ChangeOwnForeignLocaleWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private StateActivity noOrOneActiveLocaleStateActivity; private StateInitializationActivity finalizeStateInitializationActivity; private StateInitializationActivity step1StateInitializationActivity; private StateInitializationActivity noOrOneActiveLocaleStateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity_HasActiveLocales; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity2; private Composite.C1Console.Workflow.Activities.DataDialogFormActivity dataDialogFormActivity1; private Composite.C1Console.Workflow.Activities.DataDialogFormActivity dataDialogFormActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Finish; private CodeActivity finalizeCodeActivity_Finalize; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity6; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private CodeActivity step1CodeActivity_Initialize; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private EventDrivenActivity noOrOneActiveLocaleEventDrivenActivit_Finish; private SetStateActivity setStateActivity7; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/C1Console/Users/Workflows/ChangeOwnForeignLocaleWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="ChangeOwnForeignLocaleWorkflow" Location="30; 30" Size="1162; 996" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="ChangeOwnForeignLocaleWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="ChangeOwnForeignLocaleWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="593" Y="179" /> <ns0:Point X="593" Y="285" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="noOrOneActiveLocaleStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="noOrOneActiveLocaleStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="306" Y="179" /> <ns0:Point X="306" Y="447" /> <ns0:Point X="282" Y="447" /> <ns0:Point X="282" Y="459" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="691" Y="350" /> <ns0:Point X="796" Y="350" /> <ns0:Point X="796" Y="525" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="695" Y="374" /> <ns0:Point X="1058" Y="374" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="noOrOneActiveLocaleStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="noOrOneActiveLocaleStateActivity" EventHandlerName="noOrOneActiveLocaleEventDrivenActivit_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="418" Y="524" /> <ns0:Point X="434" Y="524" /> <ns0:Point X="434" Y="786" /> <ns0:Point X="1058" Y="786" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="895" Y="566" /> <ns0:Point X="1058" Y="566" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 303" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="361; 222" Name="ifElseActivity_HasActiveLocales" Location="108; 231"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity1" Location="127; 302"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="137; 364" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity2" Location="300; 302"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="310; 364" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="noOrOneActiveLocaleStateActivity" Location="142; 459" Size="280; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="noOrOneActiveLocaleStateInitializationActivity" Location="150; 490"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="dataDialogFormActivity1" Location="160; 552" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="noOrOneActiveLocaleEventDrivenActivit_Finish" Location="150; 514"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity2" Location="160; 576" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="160; 636" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="step1StateActivity" Location="488; 285" Size="211; 102" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="step1StateInitializationActivity" Location="496; 316"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="step1CodeActivity_Initialize" Location="506; 378" /> <ActivityDesigner Size="130; 41" Name="dataDialogFormActivity2" Location="506; 438" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Finish" Location="496; 340"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="506; 402" /> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="506; 462" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="496; 364"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="506; 426" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="506; 486" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="694; 525" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="finalizeStateInitializationActivity" Location="702; 556"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity_Finalize" Location="712; 618" /> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="712; 678" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/C1Console/Users/Workflows/ChangeOwnPasswordWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Workflow.Activities; using Composite.C1Console.Events; using Composite.Core.Linq; using Composite.Core.Logging; using Composite.C1Console.Security; using Composite.Data; using Composite.Data.Types; using Composite.Data.Validation.ClientValidationRules; using Composite.C1Console.Workflow; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_C1Console_Users; namespace Composite.C1Console.Users.Workflows { [EntityTokenLock] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class ChangeOwnPasswordWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public ChangeOwnPasswordWorkflow() { InitializeComponent(); } private static class Fields { public const string OldPassword = "OldPassword"; public const string NewPassword = "NewPassword"; public const string NewPasswordConfirmed = "NewPasswordConfirmed"; } private void ChangePasswordWorkflow_Initialize_ExecuteCode(object sender, EventArgs e) { this.Bindings.Add(Fields.OldPassword, ""); this.Bindings.Add(Fields.NewPassword, ""); this.Bindings.Add(Fields.NewPasswordConfirmed, ""); this.BindingsValidationRules.Add(Fields.OldPassword, new List<ClientValidationRule>{ new NotNullClientValidationRule() }); this.BindingsValidationRules.Add(Fields.NewPassword, new List<ClientValidationRule>{new NotNullClientValidationRule()}); this.BindingsValidationRules.Add(Fields.NewPasswordConfirmed, new List<ClientValidationRule>{new NotNullClientValidationRule()}); } private void stepFinalize_codeActivity_ExecuteCode(object sender, EventArgs e) { string newPassword = this.GetBinding<string>(Fields.NewPassword); string currentUserName = UserValidationFacade.GetUsername(); UserValidationFacade.FormSetUserPassword(currentUserName, newPassword); LoggingService.LogVerbose("ChangeOwnPasswordWorkflow", string.Format("User '{0}' has changed password.", UserValidationFacade.GetUsername()), LoggingService.Category.Audit); } private void EnsurePasswordUpdatesAreSupported(object sender, ConditionalEventArgs e) { e.Result = UserValidationFacade.CanSetUserPassword; } private void ValidateSpecifiedPasswords(object sender, ConditionalEventArgs e) { string oldPassword = this.GetBinding<string>(Fields.OldPassword); string newPassword = this.GetBinding<string>(Fields.NewPassword); string newPasswordConfirmed = this.GetBinding<string>(Fields.NewPasswordConfirmed); e.Result = ValidateSpecifiedPasswords(oldPassword, newPassword, newPasswordConfirmed); } private bool ValidateSpecifiedPasswords(string oldPassword, string newPassword, string newPasswordConfirmed) { string currentUserName = UserValidationFacade.GetUsername(); bool oldPasswordCorrect = UserValidationFacade.FormValidateUserWithoutLogin(currentUserName, oldPassword); if (!oldPasswordCorrect) { this.ShowFieldMessage(Fields.OldPassword, Texts.ChangeOwnPasswordWorkflow_Dialog_Validation_IncorrectPassword); return false; } if (newPassword != newPasswordConfirmed) { this.ShowFieldMessage(Fields.NewPasswordConfirmed, Texts.ChangeOwnPasswordWorkflow_Dialog_Validation_NewPasswordFieldsNotMatch); return false; } if (newPassword == oldPassword) { this.ShowFieldMessage(Fields.NewPassword, Texts.ChangeOwnPasswordWorkflow_Dialog_Validation_PasswordsAreTheSame); return false; } if (string.IsNullOrEmpty(newPassword)) { this.ShowFieldMessage(Fields.NewPassword, Texts.ChangeOwnPasswordWorkflow_Dialog_Validation_NewPasswordIsEmpty); return false; } string userName = UserValidationFacade.GetUsername(); var user = DataFacade.GetData<IUser>(u => string.Compare(u.Username, userName, StringComparison.InvariantCultureIgnoreCase) == 0) .FirstOrException("No user found with name '{0}'", userName); IList<string> newPasswordValidationMessages; if (!PasswordPolicyFacade.ValidatePassword(user, newPassword, out newPasswordValidationMessages)) { foreach (var message in newPasswordValidationMessages) { this.ShowFieldMessage(Fields.NewPassword, message); } return false; } return true; } private void InitializeConditionsNotMetAlertActivity_ExecuteCode(object sender, EventArgs e) { this.ShowMessage(DialogType.Error, Texts.ChangeOwnPasswordWorkflow_NotSupportedErrorLabel, Texts.ChangeOwnPasswordWorkflow_NotSupportedErrorText); } } } ================================================ FILE: Composite.Workflows/C1Console/Users/Workflows/ChangeOwnPasswordWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.C1Console.Users.Workflows { partial class ChangeOwnPasswordWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity20 = new System.Workflow.Activities.SetStateActivity(); this.InitializeConditionsNotMetAlertActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.ChangePasswordWorkflow_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.initializeConditionsNotMetBranchActivity = new System.Workflow.Activities.IfElseBranchActivity(); this.initializeConditionsMetBranchActivity = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.initializeConditionsMetIfElseActivity = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.handleExternalEventActivity2 = new System.Workflow.Activities.HandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.handleExternalEventActivity1 = new System.Workflow.Activities.HandleExternalEventActivity(); this.dataDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.stepFinalize_codeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity19 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1_eventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1_eventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.initializeActivity = new System.Workflow.Activities.StateActivity(); this.step1State = new System.Workflow.Activities.StateActivity(); this.finalizeActivity = new System.Workflow.Activities.StateActivity(); this.finishState = new System.Workflow.Activities.StateActivity(); // // setStateActivity20 // this.setStateActivity20.Name = "setStateActivity20"; this.setStateActivity20.TargetStateName = "finishState"; // // InitializeConditionsNotMetAlertActivity // this.InitializeConditionsNotMetAlertActivity.Name = "InitializeConditionsNotMetAlertActivity"; this.InitializeConditionsNotMetAlertActivity.ExecuteCode += new System.EventHandler(this.InitializeConditionsNotMetAlertActivity_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1State"; // // ChangePasswordWorkflow_Initialize // this.ChangePasswordWorkflow_Initialize.Name = "ChangePasswordWorkflow_Initialize"; this.ChangePasswordWorkflow_Initialize.ExecuteCode += new System.EventHandler(this.ChangePasswordWorkflow_Initialize_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "step1State"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalizeActivity"; // // initializeConditionsNotMetBranchActivity // this.initializeConditionsNotMetBranchActivity.Activities.Add(this.InitializeConditionsNotMetAlertActivity); this.initializeConditionsNotMetBranchActivity.Activities.Add(this.setStateActivity20); this.initializeConditionsNotMetBranchActivity.Name = "initializeConditionsNotMetBranchActivity"; // // initializeConditionsMetBranchActivity // this.initializeConditionsMetBranchActivity.Activities.Add(this.ChangePasswordWorkflow_Initialize); this.initializeConditionsMetBranchActivity.Activities.Add(this.setStateActivity2); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.EnsurePasswordUpdatesAreSupported); this.initializeConditionsMetBranchActivity.Condition = codecondition1; this.initializeConditionsMetBranchActivity.Name = "initializeConditionsMetBranchActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity5); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity4); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateSpecifiedPasswords); this.ifElseBranchActivity1.Condition = codecondition2; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // initializeConditionsMetIfElseActivity // this.initializeConditionsMetIfElseActivity.Activities.Add(this.initializeConditionsMetBranchActivity); this.initializeConditionsMetIfElseActivity.Activities.Add(this.initializeConditionsNotMetBranchActivity); this.initializeConditionsMetIfElseActivity.Name = "initializeConditionsMetIfElseActivity"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finishState"; // // handleExternalEventActivity2 // this.handleExternalEventActivity2.EventName = "Cancel"; this.handleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.handleExternalEventActivity2.Name = "handleExternalEventActivity2"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // handleExternalEventActivity1 // this.handleExternalEventActivity1.EventName = "Finish"; this.handleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.handleExternalEventActivity1.Name = "handleExternalEventActivity1"; // // dataDialogFormActivity1 // this.dataDialogFormActivity1.ContainerLabel = null; this.dataDialogFormActivity1.FormDefinitionFileName = "\\Administrative\\ChangeOwnPassword.xml"; this.dataDialogFormActivity1.Name = "dataDialogFormActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finishState"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // stepFinalize_codeActivity // this.stepFinalize_codeActivity.Name = "stepFinalize_codeActivity"; this.stepFinalize_codeActivity.ExecuteCode += new System.EventHandler(this.stepFinalize_codeActivity_ExecuteCode); // // setStateActivity19 // this.setStateActivity19.Name = "setStateActivity19"; this.setStateActivity19.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeConditionsMetIfElseActivity); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // step1_eventDrivenActivity_Cancel // this.step1_eventDrivenActivity_Cancel.Activities.Add(this.handleExternalEventActivity2); this.step1_eventDrivenActivity_Cancel.Activities.Add(this.setStateActivity3); this.step1_eventDrivenActivity_Cancel.Name = "step1_eventDrivenActivity_Cancel"; // // step1_eventDrivenActivity_Finish // this.step1_eventDrivenActivity_Finish.Activities.Add(this.handleExternalEventActivity1); this.step1_eventDrivenActivity_Finish.Activities.Add(this.ifElseActivity1); this.step1_eventDrivenActivity_Finish.Name = "step1_eventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.dataDialogFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.stepFinalize_codeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity1); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity19); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // initializeActivity // this.initializeActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeActivity.Name = "initializeActivity"; // // step1State // this.step1State.Activities.Add(this.step1StateInitializationActivity); this.step1State.Activities.Add(this.step1_eventDrivenActivity_Finish); this.step1State.Activities.Add(this.step1_eventDrivenActivity_Cancel); this.step1State.Name = "step1State"; // // finalizeActivity // this.finalizeActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeActivity.Name = "finalizeActivity"; // // finishState // this.finishState.Name = "finishState"; // // ChangeOwnPasswordWorkflow // this.Activities.Add(this.finishState); this.Activities.Add(this.finalizeActivity); this.Activities.Add(this.step1State); this.Activities.Add(this.initializeActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.CompletedStateName = "finishState"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeActivity"; this.Name = "ChangeOwnPasswordWorkflow"; this.CanModifyActivities = false; } #endregion private StateInitializationActivity step1StateInitializationActivity; private HandleExternalEventActivity handleExternalEventActivity1; private EventDrivenActivity step1_eventDrivenActivity_Finish; private StateActivity finishState; private StateActivity finalizeActivity; private StateInitializationActivity finalizeStateInitializationActivity; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private CodeActivity stepFinalize_codeActivity; private StateInitializationActivity initializeStateInitializationActivity; private StateActivity initializeActivity; private SetStateActivity setStateActivity1; private SetStateActivity setStateActivity19; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private CodeActivity ChangePasswordWorkflow_Initialize; private Composite.C1Console.Workflow.Activities.DataDialogFormActivity dataDialogFormActivity1; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity3; private HandleExternalEventActivity handleExternalEventActivity2; private EventDrivenActivity step1_eventDrivenActivity_Cancel; private SetStateActivity setStateActivity4; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity20; private CodeActivity InitializeConditionsNotMetAlertActivity; private IfElseBranchActivity initializeConditionsNotMetBranchActivity; private IfElseBranchActivity initializeConditionsMetBranchActivity; private IfElseActivity initializeConditionsMetIfElseActivity; private StateActivity step1State; } } ================================================ FILE: Composite.Workflows/Composite.Workflows.csproj ================================================ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.30729</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{1FE08476-346A-4053-813D-8807C0E0FC36}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Composite</RootNamespace> <AssemblyName>Composite.Workflows</AssemblyName> <ProjectTypeGuids>{14822709-B5A1-4724-98CA-57A101D1B079};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <TargetFrameworkVersion>v4.8</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <SccProjectName>SAK</SccProjectName> <SccLocalPath>SAK</SccLocalPath> <SccAuxPath>SAK</SccAuxPath> <SccProvider>SAK</SccProvider> <FileUpgradeFlags> </FileUpgradeFlags> <OldToolsVersion>3.5</OldToolsVersion> <UpgradeBackupLocation /> <PublishUrl>publish\</PublishUrl> <Install>true</Install> <InstallFrom>Disk</InstallFrom> <UpdateEnabled>false</UpdateEnabled> <UpdateMode>Foreground</UpdateMode> <UpdateInterval>7</UpdateInterval> <UpdateIntervalUnits>Days</UpdateIntervalUnits> <UpdatePeriodically>false</UpdatePeriodically> <UpdateRequired>false</UpdateRequired> <MapFileExtensions>true</MapFileExtensions> <ApplicationRevision>0</ApplicationRevision> <ApplicationVersion>1.0.0.%2a</ApplicationVersion> <IsWebBootstrapper>false</IsWebBootstrapper> <UseApplicationTrust>false</UseApplicationTrust> <BootstrapperEnabled>true</BootstrapperEnabled> <TargetFrameworkProfile /> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> <Prefer32Bit>false</Prefer32Bit> <NoWarn>618</NoWarn> <LangVersion>7</LangVersion> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> <Prefer32Bit>false</Prefer32Bit> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.Practices.EnterpriseLibrary.Common, Version=3.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\bin\Microsoft.Practices.EnterpriseLibrary.Common.dll</HintPath> </Reference> <Reference Include="Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\bin\Microsoft.Practices.EnterpriseLibrary.Logging.dll</HintPath> </Reference> <Reference Include="Microsoft.Practices.EnterpriseLibrary.Validation, Version=3.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\bin\Microsoft.Practices.EnterpriseLibrary.Validation.dll</HintPath> </Reference> <Reference Include="Microsoft.Practices.ObjectBuilder, Version=1.0.51206.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\bin\Microsoft.Practices.ObjectBuilder.dll</HintPath> </Reference> <Reference Include="Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\bin\Microsoft.SqlServer.ConnectionInfo.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.configuration" /> <Reference Include="System.Configuration.Install" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> <Reference Include="System.Drawing.Design" /> <Reference Include="System.IO.Compression" /> <Reference Include="System.Management" /> <Reference Include="System.Runtime.Serialization"> <RequiredTargetFramework>3.0</RequiredTargetFramework> </Reference> <Reference Include="System.Security" /> <Reference Include="System.ServiceModel"> <RequiredTargetFramework>3.0</RequiredTargetFramework> </Reference> <Reference Include="System.ServiceModel.Web"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Transactions" /> <Reference Include="System.Web" /> <Reference Include="System.Web.Extensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Web.Services" /> <Reference Include="System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <HintPath>..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.dll</HintPath> <Private>True</Private> </Reference> <Reference Include="System.Workflow.Activities"> <RequiredTargetFramework>3.0</RequiredTargetFramework> </Reference> <Reference Include="System.Workflow.ComponentModel"> <RequiredTargetFramework>3.0</RequiredTargetFramework> </Reference> <Reference Include="System.Workflow.Runtime"> <RequiredTargetFramework>3.0</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> <Reference Include="TidyNet, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\bin\TidyNet.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> <Compile Include="C1Console\Actions\Workflows\EntityTokenLockedWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Actions\Workflows\EntityTokenLockedWorkflow.designer.cs"> <DependentUpon>EntityTokenLockedWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Actions\Workflows\FlowInformationScavengerWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Actions\Workflows\FlowInformationScavengerWorkflow.designer.cs"> <DependentUpon>FlowInformationScavengerWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Actions\Workflows\SecurityViolationWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Actions\Workflows\SecurityViolationWorkflow.designer.cs"> <DependentUpon>SecurityViolationWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Events\Workflows\UserConsoleInformationScavengerWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Events\Workflows\UserConsoleInformationScavengerWorkflow.designer.cs"> <DependentUpon>UserConsoleInformationScavengerWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\AddAssociatedDataWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\AddAssociatedDataWorkflow.designer.cs"> <DependentUpon>AddAssociatedDataWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\AddDataFolderExWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\AddDataFolderExWorkflow.designer.cs"> <DependentUpon>AddDataFolderExWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\AddMetaDataWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\AddMetaDataWorkflow.designer.cs"> <DependentUpon>AddMetaDataWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\DeleteAssociatedDataWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\DeleteAssociatedDataWorkflow.designer.cs"> <DependentUpon>DeleteAssociatedDataWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\DeleteDataFolderWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\DeleteDataFolderWorkflow.designer.cs"> <DependentUpon>DeleteDataFolderWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\DeleteMetaDataWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\DeleteMetaDataWorkflow.designer.cs"> <DependentUpon>DeleteMetaDataWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\EditAssociatedDataWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\EditAssociatedDataWorkflow.designer.cs"> <DependentUpon>EditAssociatedDataWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\EditMetaDataWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\EditMetaDataWorkflow.designer.cs"> <DependentUpon>EditMetaDataWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Scheduling\BaseSchedulerWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Scheduling\BaseSchedulerWorkflow.designer.cs"> <DependentUpon>BaseSchedulerWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Scheduling\DataPublishSchedulerWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Scheduling\DataUnpublishSchedulerWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Scheduling\PagePublishSchedulerWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Scheduling\PageUnpublishSchedulerWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Scheduling\PublishControlledHelper.cs" /> <Compile Include="C1Console\Tools\SetTimeZoneWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Tools\SetTimeZoneWorkflow.designer.cs"> <DependentUpon>SetTimeZoneWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\AllFunctionsElementProvider\FunctionTesterWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\AllFunctionsElementProvider\FunctionTesterWorkflow.designer.cs"> <DependentUpon>FunctionTesterWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\Common\BaseFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\Common\KeyFieldHelper.cs" /> <Compile Include="Plugins\Elements\ElementProviders\Common\PageTemplateHelper.cs" /> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\AddTypeToWhiteListWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\AddTypeToWhiteListWorkflow.designer.cs"> <DependentUpon>AddTypeToWhiteListWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\RemoveTypeFromWhiteListWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\RemoveTypeFromWhiteListWorkflow.designer.cs"> <DependentUpon>RemoveTypeFromWhiteListWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\LocalizationElementProvider\AddSystemLocaleWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\LocalizationElementProvider\AddSystemLocaleWorkflow.designer.cs"> <DependentUpon>AddSystemLocaleWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\LocalizationElementProvider\DefineDefaultActiveLocaleWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\LocalizationElementProvider\DefineDefaultActiveLocaleWorkflow.designer.cs"> <DependentUpon>DefineDefaultActiveLocaleWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\LocalizationElementProvider\EditSystemLocaleWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\LocalizationElementProvider\EditSystemLocaleWorkflow.designer.cs"> <DependentUpon>EditSystemLocaleWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\LocalizationElementProvider\RemoveSystemLocaleWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\LocalizationElementProvider\RemoveSystemLocaleWorkflow.designer.cs"> <DependentUpon>RemoveSystemLocaleWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\AddMediaZipFileWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\AddMediaZipFileWorkflow.Designer.cs"> <DependentUpon>AddMediaZipFileWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\AddNewMediaFileWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\AddNewMediaFileWorkflow.designer.cs"> <DependentUpon>AddNewMediaFileWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\AddNewMediaFolderWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\AddNewMediaFolderWorkflow.Designer.cs"> <DependentUpon>AddNewMediaFolderWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\EditMediaFileContentWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\EditMediaFileContentWorkflow.designer.cs"> <DependentUpon>EditMediaFileContentWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\DeleteMediaFileWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\DeleteMediaFileWorkflow.Designer.cs"> <DependentUpon>DeleteMediaFileWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\DeleteMediaFolderWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\DeleteMediaFolderWorkflow.Designer.cs"> <DependentUpon>DeleteMediaFolderWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\EditMediaFileTextContentWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\EditMediaFileTextContentWorkflow.designer.cs"> <DependentUpon>EditMediaFileTextContentWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\EditMediaFileWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\EditMediaFileWorkflow.Designer.cs"> <DependentUpon>EditMediaFileWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\EditMediaFolderWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\EditMediaFolderWorkflow.Designer.cs"> <DependentUpon>EditMediaFolderWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\UploadNewMediaFileWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\UploadNewMediaFileWorkflow.Designer.cs"> <DependentUpon>UploadNewMediaFileWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MethodBasedFunctionProviderElementProvider\AddNewMethodBasedFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MethodBasedFunctionProviderElementProvider\AddNewMethodBasedFunctionWorkflow.Designer.cs"> <DependentUpon>AddNewMethodBasedFunctionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MethodBasedFunctionProviderElementProvider\AddInlineFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MethodBasedFunctionProviderElementProvider\AddInlineFunctionWorkflow.Designer.cs"> <DependentUpon>AddInlineFunctionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MethodBasedFunctionProviderElementProvider\DeleteInlineFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MethodBasedFunctionProviderElementProvider\DeleteInlineFunctionWorkflow.designer.cs"> <DependentUpon>DeleteInlineFunctionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MethodBasedFunctionProviderElementProvider\DeleteMethodBasedFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MethodBasedFunctionProviderElementProvider\DeleteMethodBasedFunctionWorkflow.Designer.cs"> <DependentUpon>DeleteMethodBasedFunctionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MethodBasedFunctionProviderElementProvider\EditInlineFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MethodBasedFunctionProviderElementProvider\EditInlineFunctionWorkflow.designer.cs"> <DependentUpon>EditInlineFunctionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MethodBasedFunctionProviderElementProvider\EditMethodBasedFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\MethodBasedFunctionProviderElementProvider\EditMethodBasedFunctionWorkflow.Designer.cs"> <DependentUpon>EditMethodBasedFunctionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PackageElementProvider\AddPackageSourceWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PackageElementProvider\AddPackageSourceWorkflow.designer.cs"> <DependentUpon>AddPackageSourceWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PackageElementProvider\DeletePackageSourceWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PackageElementProvider\DeletePackageSourceWorkflow.designer.cs"> <DependentUpon>DeletePackageSourceWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PackageElementProvider\InstallLocalPackageWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PackageElementProvider\InstallLocalPackageWorkflow.designer.cs"> <DependentUpon>InstallLocalPackageWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PackageElementProvider\InstallRemotePackageWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PackageElementProvider\InstallRemotePackageWorkflow.designer.cs"> <DependentUpon>InstallRemotePackageWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PackageElementProvider\UninstallLocalPackageWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PackageElementProvider\UninstallLocalPackageWorkflow.designer.cs"> <DependentUpon>UninstallLocalPackageWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PackageElementProvider\UninstallRemotePackageWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PackageElementProvider\UninstallRemotePackageWorkflow.designer.cs"> <DependentUpon>UninstallRemotePackageWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PackageElementProvider\ViewAvailablePackageInfoWorkflowWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PackageElementProvider\ViewAvailablePackageInfoWorkflowWorkflow.designer.cs"> <DependentUpon>ViewAvailablePackageInfoWorkflowWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PackageElementProvider\ViewInstalledPackageInfoWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PackageElementProvider\ViewInstalledPackageInfoWorkflow.designer.cs"> <DependentUpon>ViewInstalledPackageInfoWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageElementProvider\AddNewPageWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageElementProvider\AddNewPageWorkflow.Designer.cs"> <DependentUpon>AddNewPageWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageElementProvider\DeletePageWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageElementProvider\DeletePageWorkflow.Designer.cs"> <DependentUpon>DeletePageWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageElementProvider\EditPageWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageElementProvider\EditPageWorkflow.Designer.cs"> <DependentUpon>EditPageWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageElementProvider\UnLocalizePageWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageElementProvider\UnLocalizePageWorkflow.designer.cs"> <DependentUpon>UnLocalizePageWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageElementProvider\LocalizePageWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageElementProvider\LocalizePageWorkflow.designer.cs"> <DependentUpon>LocalizePageWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageElementProvider\UndoUnpublishedChangesWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageElementProvider\UndoUnpublishedChangesWorkflow.designer.cs"> <DependentUpon>UndoUnpublishedChangesWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\AddNewPageTemplateWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\AddNewPageTemplateWorkflow.Designer.cs"> <DependentUpon>AddNewPageTemplateWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\AddNewRazorPageTemplateWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\AddNewRazorPageTemplateWorkflow.Designer.cs"> <DependentUpon>AddNewRazorPageTemplateWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\AddNewMasterPagePageTemplateWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\AddNewMasterPagePageTemplateWorkflow.Designer.cs"> <DependentUpon>AddNewMasterPagePageTemplateWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\AddNewXmlPageTemplateWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\AddNewXmlPageTemplateWorkflow.Designer.cs"> <DependentUpon>AddNewXmlPageTemplateWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\EditMasterPageWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\EditMasterPageWorkflow.designer.cs"> <DependentUpon>EditMasterPageWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\DeletePageTemplateWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\DeletePageTemplateWorkflow.Designer.cs"> <DependentUpon>DeletePageTemplateWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\EditXmlPageTemplateWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\EditXmlPageTemplateWorkflow.Designer.cs"> <DependentUpon>EditXmlPageTemplateWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\EditRazorPageTemplateWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\EditRazorPageTemplateWorkflow.designer.cs"> <DependentUpon>EditRazorPageTemplateWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\EditSharedCodeFileWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\EditSharedCodeFileWorkflow.designer.cs"> <DependentUpon>EditSharedCodeFileWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateFeatureElementProvider\TogglePageTemplateFeatureEditorWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateFeatureElementProvider\TogglePageTemplateFeatureEditorWorkflow.designer.cs"> <DependentUpon>TogglePageTemplateFeatureEditorWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\AddNewPageTypeWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\AddNewPageTypeWorkflow.designer.cs"> <DependentUpon>AddNewPageTypeWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\AddPageTypeDefaultPageContentWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\AddPageTypeDefaultPageContentWorkflow.designer.cs"> <DependentUpon>AddPageTypeDefaultPageContentWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\AddPageTypeMetaDataFieldWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\AddPageTypeMetaDataFieldWorkflow.designer.cs"> <DependentUpon>AddPageTypeMetaDataFieldWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\DeletePageTypeMetaDataFieldWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\DeletePageTypeMetaDataFieldWorkflow.designer.cs"> <DependentUpon>DeletePageTypeMetaDataFieldWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\DeletePageTypeWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\DeletePageTypeWorkflow.designer.cs"> <DependentUpon>DeletePageTypeWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\EditPageTypeDefaultPageContentWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\EditPageTypeDefaultPageContentWorkflow.designer.cs"> <DependentUpon>EditPageTypeDefaultPageContentWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\EditPageTypeMetaDataFieldWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\EditPageTypeMetaDataFieldWorkflow.designer.cs"> <DependentUpon>EditPageTypeMetaDataFieldWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\EditPageTypeWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\EditPageTypeWorkflow.designer.cs"> <DependentUpon>EditPageTypeWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\RazorFunctionProviderElementProvider\AddNewRazorFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\RazorFunctionProviderElementProvider\AddNewRazorFunctionWorkflow.Designer.cs"> <DependentUpon>AddNewRazorFunctionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\RazorFunctionProviderElementProvider\DeleteRazorFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\RazorFunctionProviderElementProvider\DeleteRazorFunctionWorkflow.Designer.cs"> <DependentUpon>DeleteRazorFunctionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\RazorFunctionProviderElementProvider\EditRazorFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\RazorFunctionProviderElementProvider\EditRazorFunctionWorkflow.designer.cs"> <DependentUpon>EditRazorFunctionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\SqlFunctionElementProvider\AddNewSqlConnectionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\SqlFunctionElementProvider\AddNewSqlConnectionWorkflow.Designer.cs"> <DependentUpon>AddNewSqlConnectionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\SqlFunctionElementProvider\AddNewSqlFunctionProviderWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\SqlFunctionElementProvider\AddNewSqlFunctionProviderWorkflow.Designer.cs"> <DependentUpon>AddNewSqlFunctionProviderWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\SqlFunctionElementProvider\DeleteSqlConnectionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\SqlFunctionElementProvider\DeleteSqlConnectionWorkflow.Designer.cs"> <DependentUpon>DeleteSqlConnectionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\SqlFunctionElementProvider\DeleteSqlFunctionProviderWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\SqlFunctionElementProvider\DeleteSqlFunctionProviderWorkflow.Designer.cs"> <DependentUpon>DeleteSqlFunctionProviderWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\SqlFunctionElementProvider\EditSqlConnectionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\SqlFunctionElementProvider\EditSqlConnectionWorkflow.Designer.cs"> <DependentUpon>EditSqlConnectionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\SqlFunctionElementProvider\EditSqlFunctionProviderWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\SqlFunctionElementProvider\EditSqlFunctionProviderWorkflow.Designer.cs"> <DependentUpon>EditSqlFunctionProviderWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\UserControlFunctionProviderElementProvider\AddNewUserControlFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\UserControlFunctionProviderElementProvider\AddNewUserControlFunctionWorkflow.Designer.cs"> <DependentUpon>AddNewUserControlFunctionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\UserControlFunctionProviderElementProvider\DeleteUserControlFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\UserControlFunctionProviderElementProvider\DeleteUserControlFunctionWorkflow.Designer.cs"> <DependentUpon>DeleteUserControlFunctionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\UserControlFunctionProviderElementProvider\EditUserControlFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\UserControlFunctionProviderElementProvider\EditUserControlFunctionWorkflow.designer.cs"> <DependentUpon>EditUserControlFunctionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\UserElementProvider\AddNewUserWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\UserElementProvider\AddNewUserWorkflow.designer.cs"> <DependentUpon>AddNewUserWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\UserElementProvider\DeleteUserWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\UserElementProvider\DeleteUserWorkflow.designer.cs"> <DependentUpon>DeleteUserWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\UserElementProvider\EditUserWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\UserElementProvider\EditUserWorkflow.designer.cs"> <DependentUpon>EditUserWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\UserGroupElementProvider\AddNewUserGroupWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\UserGroupElementProvider\AddNewUserGroupWorkflow.Designer.cs"> <DependentUpon>AddNewUserGroupWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\UserGroupElementProvider\DeleteUserGroupWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\UserGroupElementProvider\DeleteUserGroupWorkflow.designer.cs"> <DependentUpon>DeleteUserGroupWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\UserGroupElementProvider\EditUserGroupWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\UserGroupElementProvider\EditUserGroupWorkflow.designer.cs"> <DependentUpon>EditUserGroupWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\VisualFunctionProviderElementProvider\AddNewVisualFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\VisualFunctionProviderElementProvider\AddNewVisualFunctionWorkflow.designer.cs"> <DependentUpon>AddNewVisualFunctionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\VisualFunctionProviderElementProvider\DeleteVisualFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\VisualFunctionProviderElementProvider\DeleteVisualFunctionWorkflow.designer.cs"> <DependentUpon>DeleteVisualFunctionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\VisualFunctionProviderElementProvider\EditVisualFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\VisualFunctionProviderElementProvider\EditVisualFunctionWorkflow.designer.cs"> <DependentUpon>EditVisualFunctionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\UploadAndExtractZipFileWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\UploadAndExtractZipFileWorkflow.Designer.cs"> <DependentUpon>UploadAndExtractZipFileWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\AddNewWebsiteFileWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\AddNewWebsiteFileWorkflow.designer.cs"> <DependentUpon>AddNewWebsiteFileWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\AddNewWebsiteFolderWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\AddNewWebsiteFolderWorkflow.designer.cs"> <DependentUpon>AddNewWebsiteFolderWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\AddWebsiteFolderToWhiteListWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\AddWebsiteFolderToWhiteListWorkflow.designer.cs"> <DependentUpon>AddWebsiteFolderToWhiteListWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\DeleteWebsiteFileWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\DeleteWebsiteFileWorkflow.designer.cs"> <DependentUpon>DeleteWebsiteFileWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\DeleteWebsiteFolderWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\DeleteWebsiteFolderWorkflow.designer.cs"> <DependentUpon>DeleteWebsiteFolderWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\EditWebsiteFileTextContentWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\EditWebsiteFileTextContentWorkflow.designer.cs"> <DependentUpon>EditWebsiteFileTextContentWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\RemoveWebsiteFolderFromWhiteListWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\RemoveWebsiteFolderFromWhiteListWorkflow.designer.cs"> <DependentUpon>RemoveWebsiteFolderFromWhiteListWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\UploadWebsiteFileWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\UploadWebsiteFileWorkflow.designer.cs"> <DependentUpon>UploadWebsiteFileWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateFeatureElementProvider\AddPageTemplateFeatureWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateFeatureElementProvider\AddPageTemplateFeatureWorkflow.designer.cs"> <DependentUpon>AddPageTemplateFeatureWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateFeatureElementProvider\DeletePageTemplateFeatureWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateFeatureElementProvider\DeletePageTemplateFeatureWorkflow.designer.cs"> <DependentUpon>DeletePageTemplateFeatureWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateFeatureElementProvider\EditPageTemplateFeatureWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\PageTemplateFeatureElementProvider\EditPageTemplateFeatureWorkflow.designer.cs"> <DependentUpon>EditPageTemplateFeatureWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\XsltBasedFunctionProviderElementProvider\AddNewXsltFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\XsltBasedFunctionProviderElementProvider\AddNewXsltFunctionWorkflow.Designer.cs"> <DependentUpon>AddNewXsltFunctionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\XsltBasedFunctionProviderElementProvider\Common.cs" /> <Compile Include="Plugins\Elements\ElementProviders\XsltBasedFunctionProviderElementProvider\DeleteXsltFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\XsltBasedFunctionProviderElementProvider\DeleteXsltFunctionWorkflow.Designer.cs"> <DependentUpon>DeleteXsltFunctionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\XsltBasedFunctionProviderElementProvider\EditXsltFunctionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\XsltBasedFunctionProviderElementProvider\EditXsltFunctionWorkflow.Designer.cs"> <DependentUpon>EditXsltFunctionWorkflow.cs</DependentUpon> </Compile> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="..\Composite\Properties\SharedAssemblyInfo.cs"> <Link>Properties\SharedAssemblyInfo.cs</Link> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\AddNewCompositionTypeWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\AddNewCompositionTypeWorkflow.designer.cs"> <DependentUpon>AddNewCompositionTypeWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\AddNewDataWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\AddNewDataWorkflow.Designer.cs"> <DependentUpon>AddNewDataWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\AddNewInterfaceTypeWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\AddNewInterfaceTypeWorkflow.designer.cs"> <DependentUpon>AddNewInterfaceTypeWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\DeleteAggregationTypeWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\DeleteAggregationTypeWorkflow.designer.cs"> <DependentUpon>DeleteAggregationTypeWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\DeleteCompositionTypeWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\DeleteCompositionTypeWorkflow.designer.cs"> <DependentUpon>DeleteCompositionTypeWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\DeleteDataWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\DeleteDataWorkflow.designer.cs"> <DependentUpon>DeleteDataWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\DeleteInterfaceTypeWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\DeleteInterfaceTypeWorkflow.designer.cs"> <DependentUpon>DeleteInterfaceTypeWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\DisableTypeLocalizationWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\DisableTypeLocalizationWorkflow.designer.cs"> <DependentUpon>DisableTypeLocalizationWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\EditCompositionTypeWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\EditCompositionTypeWorkflow.designer.cs"> <DependentUpon>EditCompositionTypeWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\EditDataWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\EditDataWorkflow.Designer.cs"> <DependentUpon>EditDataWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\EditFormWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\EditFormWorkflow.designer.cs"> <DependentUpon>EditFormWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\EditInterfaceTypeWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\EditInterfaceTypeWorkflow.Designer.cs"> <DependentUpon>EditInterfaceTypeWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\EnableTypeLocalizationWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\EnableTypeLocalizationWorkflow.designer.cs"> <DependentUpon>EnableTypeLocalizationWorkflow.cs</DependentUpon> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\LocalizeDataWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\LocalizeDataWorkflow.designer.cs"> <DependentUpon>LocalizeDataWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Tools\SendMessageToConsolesWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Tools\SendMessageToConsolesWorkflow.designer.cs"> <DependentUpon>SendMessageToConsolesWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Trees\Workflows\AddApplicationWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Trees\Workflows\AddApplicationWorkflow.designer.cs"> <DependentUpon>AddApplicationWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Trees\Workflows\AddTreeDefinitionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Trees\Workflows\AddTreeDefinitionWorkflow.designer.cs"> <DependentUpon>AddTreeDefinitionWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Trees\Workflows\ConfirmActionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Trees\Workflows\ConfirmActionWorkflow.designer.cs"> <DependentUpon>ConfirmActionWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Trees\Workflows\DeleteTreeDefinitionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Trees\Workflows\DeleteTreeDefinitionWorkflow.designer.cs"> <DependentUpon>DeleteTreeDefinitionWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Trees\Workflows\EditTreeDefinitionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Trees\Workflows\EditTreeDefinitionWorkflow.designer.cs"> <DependentUpon>EditTreeDefinitionWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Trees\Workflows\GenericAddDataWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Trees\Workflows\GenericAddDataWorkflow.designer.cs"> <DependentUpon>GenericAddDataWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Trees\Workflows\GenericDeleteDataWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Trees\Workflows\GenericDeleteDataWorkflow.designer.cs"> <DependentUpon>GenericDeleteDataWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Trees\Workflows\GenericEditDataWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Trees\Workflows\GenericEditDataWorkflow.designer.cs"> <DependentUpon>GenericEditDataWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Trees\Workflows\LocalizeDataWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Trees\Workflows\LocalizeDataWorkflow.designer.cs"> <DependentUpon>LocalizeDataWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Trees\Workflows\RemoveApplicationWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Trees\Workflows\RemoveApplicationWorkflow.designer.cs"> <DependentUpon>RemoveApplicationWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Trees\Workflows\ReportFunctionActionWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Trees\Workflows\ReportFunctionActionWorkflow.designer.cs"> <DependentUpon>ReportFunctionActionWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Users\Workflows\ChangeOwnActiveLocaleWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Users\Workflows\ChangeOwnActiveLocaleWorkflow.designer.cs"> <DependentUpon>ChangeOwnActiveLocaleWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Users\Workflows\ChangeOwnCultureWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Users\Workflows\ChangeOwnCultureWorkflow.designer.cs"> <DependentUpon>ChangeOwnCultureWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Users\Workflows\ChangeOwnForeignLocaleWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Users\Workflows\ChangeOwnForeignLocaleWorkflow.designer.cs"> <DependentUpon>ChangeOwnForeignLocaleWorkflow.cs</DependentUpon> </Compile> <Compile Include="C1Console\Users\Workflows\ChangeOwnPasswordWorkflow.cs"> <SubType>Component</SubType> </Compile> <Compile Include="C1Console\Users\Workflows\ChangeOwnPasswordWorkflow.designer.cs"> <DependentUpon>ChangeOwnPasswordWorkflow.cs</DependentUpon> </Compile> <Compile Include="Properties\GitCommitInfo.cs" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="C1Console\Actions\Workflows\EntityTokenLockedWorkflow.layout"> <DependentUpon>EntityTokenLockedWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Actions\Workflows\FlowInformationScavengerWorkflow.layout"> <DependentUpon>FlowInformationScavengerWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Actions\Workflows\SecurityViolationWorkflow.layout"> <DependentUpon>SecurityViolationWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Events\Workflows\UserConsoleInformationScavengerWorkflow.layout"> <DependentUpon>UserConsoleInformationScavengerWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\AddAssociatedDataWorkflow.layout"> <DependentUpon>AddAssociatedDataWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\AddDataFolderExWorkflow.layout"> <DependentUpon>AddDataFolderExWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\AddMetaDataWorkflow.layout"> <DependentUpon>AddMetaDataWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\DeleteAssociatedDataWorkflow.layout"> <DependentUpon>DeleteAssociatedDataWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\DeleteDataFolderWorkflow.layout"> <DependentUpon>DeleteDataFolderWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\DeleteMetaDataWorkflow.layout"> <DependentUpon>DeleteMetaDataWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\EditAssociatedDataWorkflow.layout"> <DependentUpon>EditAssociatedDataWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Elements\ElementProviderHelpers\AssociatedDataElementProviderHelper\EditMetaDataWorkflow.layout"> <DependentUpon>EditMetaDataWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\AllFunctionsElementProvider\FunctionTesterWorkflow.layout"> <DependentUpon>FunctionTesterWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\AddTypeToWhiteListWorkflow.layout"> <DependentUpon>AddTypeToWhiteListWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\DeleteDataWorkflow.layout"> <DependentUpon>DeleteDataWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\RemoveTypeFromWhiteListWorkflow.layout"> <DependentUpon>RemoveTypeFromWhiteListWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\LocalizationElementProvider\AddSystemLocaleWorkflow.layout"> <DependentUpon>AddSystemLocaleWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\LocalizationElementProvider\DefineDefaultActiveLocaleWorkflow.layout"> <DependentUpon>DefineDefaultActiveLocaleWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\LocalizationElementProvider\EditSystemLocaleWorkflow.layout"> <DependentUpon>EditSystemLocaleWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\LocalizationElementProvider\RemoveSystemLocaleWorkflow.layout"> <DependentUpon>RemoveSystemLocaleWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\AddMediaZipFileWorkflow.layout"> <DependentUpon>AddMediaZipFileWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\AddNewMediaFileWorkflow.layout"> <DependentUpon>AddNewMediaFileWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\AddNewMediaFolderWorkflow.layout"> <DependentUpon>AddNewMediaFolderWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\DeleteMediaFileWorkflow.layout"> <DependentUpon>DeleteMediaFileWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\DeleteMediaFolderWorkflow.layout"> <DependentUpon>DeleteMediaFolderWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\EditMediaFileContentWorkflow.layout"> <DependentUpon>EditMediaFileContentWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\EditMediaFileWorkflow.layout"> <DependentUpon>EditMediaFileWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\EditMediaFolderWorkflow.layout"> <DependentUpon>EditMediaFolderWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\MediaFileProviderElementProvider\UploadNewMediaFileWorkflow.layout"> <DependentUpon>UploadNewMediaFileWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\MethodBasedFunctionProviderElementProvider\AddInlineFunctionWorkflow.layout"> <DependentUpon>AddInlineFunctionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\MethodBasedFunctionProviderElementProvider\AddNewMethodBasedFunctionWorkflow.layout"> <DependentUpon>AddNewMethodBasedFunctionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\MethodBasedFunctionProviderElementProvider\DeleteInlineFunctionWorkflow.layout"> <DependentUpon>DeleteMethodBasedFunctionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\MethodBasedFunctionProviderElementProvider\DeleteMethodBasedFunctionWorkflow.layout"> <DependentUpon>DeleteInlineFunctionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\MethodBasedFunctionProviderElementProvider\EditInlineFunctionWorkflow.layout"> <DependentUpon>EditInlineFunctionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\MethodBasedFunctionProviderElementProvider\EditMethodBasedFunctionWorkflow.layout"> <DependentUpon>EditMethodBasedFunctionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PackageElementProvider\AddPackageSourceWorkflow.layout"> <DependentUpon>AddPackageSourceWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PackageElementProvider\DeletePackageSourceWorkflow.layout"> <DependentUpon>DeletePackageSourceWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PackageElementProvider\InstallLocalPackageWorkflow.layout"> <DependentUpon>InstallLocalPackageWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PackageElementProvider\InstallRemotePackageWorkflow.layout"> <DependentUpon>InstallRemotePackageWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PackageElementProvider\UninstallLocalPackageWorkflow.layout"> <DependentUpon>UninstallLocalPackageWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PackageElementProvider\UninstallRemotePackageWorkflow.layout"> <DependentUpon>UninstallRemotePackageWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PackageElementProvider\ViewAvailablePackageInfoWorkflowWorkflow.layout"> <DependentUpon>ViewAvailablePackageInfoWorkflowWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PackageElementProvider\ViewInstalledPackageInfoWorkflow.layout"> <DependentUpon>ViewInstalledPackageInfoWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageElementProvider\AddNewPageWorkflow.layout"> <DependentUpon>AddNewPageWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageElementProvider\DeletePageWorkflow.layout"> <DependentUpon>DeletePageWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageElementProvider\EditPageWorkflow.layout"> <DependentUpon>EditPageWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageElementProvider\LocalizePageWorkflow.layout"> <DependentUpon>LocalizePageWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageElementProvider\UndoUnpublishedChangesWorkflow.layout"> <DependentUpon>UndoUnpublishedChangesWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageElementProvider\UnLocalizePageWorkflow.layout"> <DependentUpon>UnLocalizePageWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\AddNewMasterPagePageTemplateWorkflow.layout"> <DependentUpon>AddNewMasterPagePageTemplateWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\AddNewPageTemplateWorkflow.layout"> <DependentUpon>AddNewPageTemplateWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\AddNewRazorPageTemplateWorkflow.layout"> <DependentUpon>AddNewRazorPageTemplateWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\DeletePageTemplateWorkflow.layout"> <DependentUpon>DeletePageTemplateWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\EditMasterPageWorkflow.layout"> <DependentUpon>EditMasterPageWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\EditRazorPageTemplateWorkflow.layout"> <DependentUpon>EditRazorPageTemplateWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTemplateElementProvider\EditSharedCodeFileWorkflow.layout"> <DependentUpon>EditSharedCodeFileWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTemplateFeatureElementProvider\AddPageTemplateFeatureWorkflow.layout"> <DependentUpon>AddPageTemplateFeatureWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTemplateFeatureElementProvider\DeletePageTemplateFeatureWorkflow.layout"> <DependentUpon>DeletePageTemplateFeatureWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTemplateFeatureElementProvider\TogglePageTemplateFeatureEditorWorkflow.layout"> <DependentUpon>TogglePageTemplateFeatureEditorWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\AddNewPageTypeWorkflow.layout"> <DependentUpon>AddNewPageTypeWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\AddPageTypeDefaultPageContentWorkflow.layout"> <DependentUpon>AddPageTypeDefaultPageContentWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\AddPageTypeMetaDataFieldWorkflow.layout"> <DependentUpon>AddPageTypeMetaDataFieldWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\DeletePageTypeMetaDataFieldWorkflow.layout"> <DependentUpon>DeletePageTypeMetaDataFieldWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\DeletePageTypeWorkflow.layout"> <DependentUpon>DeletePageTypeWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\EditPageTypeDefaultPageContentWorkflow.layout"> <DependentUpon>EditPageTypeDefaultPageContentWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\EditPageTypeMetaDataFieldWorkflow.layout"> <DependentUpon>EditPageTypeMetaDataFieldWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTypeElementProvider\EditPageTypeWorkflow.layout"> <DependentUpon>EditPageTypeWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\RazorFunctionProviderElementProvider\AddNewRazorFunctionWorkflow.layout"> <DependentUpon>AddNewRazorFunctionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\RazorFunctionProviderElementProvider\DeleteRazorFunctionWorkflow.layout"> <DependentUpon>DeleteRazorFunctionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\SqlFunctionElementProvider\AddNewSqlConnectionWorkflow.layout"> <DependentUpon>AddNewSqlConnectionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\SqlFunctionElementProvider\AddNewSqlFunctionProviderWorkflow.layout"> <DependentUpon>AddNewSqlFunctionProviderWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\SqlFunctionElementProvider\DeleteSqlConnectionWorkflow.layout"> <DependentUpon>DeleteSqlConnectionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\SqlFunctionElementProvider\DeleteSqlFunctionProviderWorkflow.layout"> <DependentUpon>DeleteSqlFunctionProviderWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\SqlFunctionElementProvider\EditSqlConnectionWorkflow.layout"> <DependentUpon>EditSqlConnectionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\SqlFunctionElementProvider\EditSqlFunctionProviderWorkflow.layout"> <DependentUpon>EditSqlFunctionProviderWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\UserControlFunctionProviderElementProvider\AddNewUserControlFunctionWorkflow.layout"> <DependentUpon>AddNewUserControlFunctionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\UserControlFunctionProviderElementProvider\DeleteUserControlFunctionWorkflow.layout"> <DependentUpon>DeleteUserControlFunctionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\UserElementProvider\AddNewUserWorkflow.layout"> <DependentUpon>AddNewUserWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\UserElementProvider\DeleteUserWorkflow.layout"> <DependentUpon>DeleteUserWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\UserElementProvider\EditUserWorkflow.layout"> <DependentUpon>EditUserWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\UserGroupElementProvider\AddNewUserGroupWorkflow.layout"> <DependentUpon>AddNewUserGroupWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\UserGroupElementProvider\DeleteUserGroupWorkflow.layout"> <DependentUpon>DeleteUserGroupWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\UserGroupElementProvider\EditUserGroupWorkflow.layout"> <DependentUpon>EditUserGroupWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\VisualFunctionProviderElementProvider\AddNewVisualFunctionWorkflow.layout"> <DependentUpon>AddNewVisualFunctionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\VisualFunctionProviderElementProvider\EditVisualFunctionWorkflow.layout"> <DependentUpon>EditVisualFunctionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\UploadAndExtractZipFileWorkflow.layout"> <DependentUpon>UploadAndExtractZipFileWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\AddNewWebsiteFileWorkflow.layout"> <DependentUpon>AddNewWebsiteFileWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\AddNewWebsiteFolderWorkflow.layout"> <DependentUpon>AddNewWebsiteFolderWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\DeleteWebsiteFileWorkflow.layout"> <DependentUpon>DeleteWebsiteFileWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\DeleteWebsiteFolderWorkflow.layout"> <DependentUpon>DeleteWebsiteFolderWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\EditWebsiteFileTextContentWorkflow.layout"> <DependentUpon>EditWebsiteFileTextContentWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\WebsiteFileElementProvider\UploadWebsiteFileWorkflow.layout"> <DependentUpon>UploadWebsiteFileWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\AddNewCompositionTypeWorkflow.layout"> <DependentUpon>AddNewCompositionTypeWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\AddNewDataWorkflow.layout"> <DependentUpon>AddNewDataWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\AddNewInterfaceTypeWorkflow.layout"> <DependentUpon>AddNewInterfaceTypeWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\DeleteAggregationTypeWorkflow.layout"> <DependentUpon>DeleteAggregationTypeWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\DeleteCompositionTypeWorkflow.layout"> <DependentUpon>DeleteCompositionTypeWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\DeleteInterfaceTypeWorkflow.layout"> <DependentUpon>DeleteInterfaceTypeWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\DisableTypeLocalizationWorkflow.layout"> <DependentUpon>DisableTypeLocalizationWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\EditCompositionTypeWorkflow.layout"> <DependentUpon>EditCompositionTypeWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\EditDataWorkflow.layout"> <DependentUpon>EditDataWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\EditInterfaceTypeWorkflow.layout"> <DependentUpon>EditInterfaceTypeWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\EnableTypeLocalizationWorkflow.layout"> <DependentUpon>EnableTypeLocalizationWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\GeneratedDataTypesElementProvider\LocalizeDataWorkflow.layout"> <DependentUpon>LocalizeDataWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\PageTemplateFeatureElementProvider\EditTreeDefinitionWorkflow.layout"> <DependentUpon>EditPageTemplateFeatureWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\XsltBasedFunctionProviderElementProvider\AddNewXsltFunctionWorkflow.layout"> <DependentUpon>AddNewXsltFunctionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Plugins\Elements\ElementProviders\XsltBasedFunctionProviderElementProvider\EditXsltFunctionWorkflow.layout"> <DependentUpon>EditXsltFunctionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Tools\SendMessageToConsolesWorkflow.layout"> <DependentUpon>SendMessageToConsolesWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Trees\Workflows\AddApplicationWorkflow.layout"> <DependentUpon>AddApplicationWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Trees\Workflows\AddTreeDefinitionWorkflow.layout"> <DependentUpon>AddTreeDefinitionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Trees\Workflows\ConfirmActionWorkflow.layout"> <DependentUpon>ConfirmActionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Trees\Workflows\DeleteTreeDefinitionWorkflow.layout"> <DependentUpon>DeleteTreeDefinitionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Trees\Workflows\EditTreeDefinitionWorkflow.layout"> <DependentUpon>EditTreeDefinitionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Trees\Workflows\GenericAddDataWorkflow.layout"> <DependentUpon>GenericAddDataWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Trees\Workflows\GenericDeleteDataWorkflow.layout"> <DependentUpon>GenericDeleteDataWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Trees\Workflows\GenericEditDataWorkflow.layout"> <DependentUpon>GenericEditDataWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Trees\Workflows\LocalizeDataWorkflow.layout"> <DependentUpon>LocalizeDataWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Trees\Workflows\RemoveApplicationWorkflow.layout"> <DependentUpon>RemoveApplicationWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Trees\Workflows\ReportFunctionActionWorkflow.layout"> <DependentUpon>ReportFunctionActionWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Users\Workflows\ChangeOwnActiveLocaleWorkflow.layout"> <DependentUpon>ChangeOwnActiveLocaleWorkflow.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="C1Console\Users\Workflows\ChangeOwnForeignLocaleWorkflow.layout"> <DependentUpon>ChangeOwnForeignLocaleWorkflow.cs</DependentUpon> </EmbeddedResource> </ItemGroup> <ItemGroup> <BootstrapperPackage Include="Microsoft.Net.Client.3.5"> <Visible>False</Visible> <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName> <Install>false</Install> </BootstrapperPackage> <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1"> <Visible>False</Visible> <ProductName>.NET Framework 3.5 SP1</ProductName> <Install>true</Install> </BootstrapperPackage> <BootstrapperPackage Include="Microsoft.VisualBasic.PowerPacks.10.0"> <Visible>False</Visible> <ProductName>Microsoft Visual Basic PowerPacks 10.0</ProductName> <Install>true</Install> </BootstrapperPackage> <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1"> <Visible>False</Visible> <ProductName>Windows Installer 3.1</ProductName> <Install>true</Install> </BootstrapperPackage> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Composite\Composite.csproj"> <Project>{F8D87A5F-D090-4D24-80C1-DBCD938C6CAB}</Project> <Name>Composite</Name> </ProjectReference> </ItemGroup> <ItemGroup> <None Include="packages.config" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="AfterBuild"> </Target> --> <Target Name="BeforeBuild"> <PropertyGroup> <GitBranchFile>$(ProjectDir)git_branch.txt</GitBranchFile> <GitCommitHashFile>$(ProjectDir)git_commithash.txt</GitCommitHashFile> </PropertyGroup> <Exec Condition="Exists('$(SolutionDir)\.git')" Command="git -C $(ProjectDir) rev-parse --abbrev-ref HEAD> "$(GitBranchFile)"" /> <Exec Condition="Exists('$(SolutionDir)\.git')" Command="git -C $(ProjectDir) rev-parse HEAD> "$(GitCommitHashFile)"" /> <Exec Condition="!Exists('$(SolutionDir)\.git')" Command="@echo unknown branch > "$(GitBranchFile)"" /> <Exec Condition="!Exists('$(SolutionDir)\.git')" Command="@echo unknown commit > "$(GitCommitHashFile)"" /> <PropertyGroup> <GitBranch>$([System.IO.File]::ReadAllText("$(GitBranchFile)").Trim())</GitBranch> <GitCommitHash>$([System.IO.File]::ReadAllText("$(GitCommitHashFile)").Trim())</GitCommitHash> <AssemblyInformationalVersionAttribute>[assembly: System.Reflection.AssemblyInformationalVersion("$(GitBranch). Commit Hash: $(GitCommitHash)")]</AssemblyInformationalVersionAttribute> </PropertyGroup> <WriteLinesToFile File="Properties\GitCommitInfo.cs" Lines="$(AssemblyInformationalVersionAttribute)" Overwrite="true"> </WriteLinesToFile> <Exec Command="del "$(GitBranchFile)"" /> <Exec Command="del "$(GitCommitHashFile)"" /> </Target> <PropertyGroup> <PostBuildEvent>copy "$(TargetPath)" "$(ProjectDir)..\bin\" copy "$(TargetPath)" "$(ProjectDir)..\Website\bin\"</PostBuildEvent> </PropertyGroup> </Project> ================================================ FILE: Composite.Workflows/Composite.Workflows.csproj.vspscc ================================================ "" { "FILE_VERSION" = "9237" "ENLISTMENT_CHOICE" = "NEVER" "PROJECT_FILE_RELATIVE_PATH" = "" "NUMBER_OF_EXCLUDED_FILES" = "0" "ORIGINAL_PROJECT_FILE_PATH" = "" "NUMBER_OF_NESTED_PROJECTS" = "0" "SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER" } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/AllFunctionsElementProvider/FunctionTesterWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Workflow.Runtime; using System.Xml.Serialization; using Composite.C1Console.Actions; using Composite.C1Console.Workflow; using Composite.C1Console.Workflow.Foundation; using Composite.Core.Serialization; using Composite.Core.WebClient.FlowMediators.FormFlowRendering; using Composite.Core.WebClient.FunctionCallEditor; using Composite.Core.WebClient.State; using Composite.Functions; using Composite.Functions.ManagedParameters; using Composite.Core.WebClient.Renderings.Page; using Composite.C1Console.Users; using Composite.Data; using Composite.Core.ResourceSystem; using System.Globalization; using System.Threading; using Composite.Data.Types; namespace Composite.Workflows.Plugins.Elements.ElementProviders.AllFunctionsElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class FunctionTesterWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public FunctionTesterWorkflow() { InitializeComponent(); } private void initalizeStateCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { List<NamedFunctionCall> namedFunctionCalls = new List<NamedFunctionCall>(); if (Payload != "") { IFunction function = FunctionFacade.GetFunction(Payload); BaseRuntimeTreeNode baseRuntimeTreeNode = FunctionFacade.BuildTree(function, new Dictionary<string, object>()); NamedFunctionCall namedFunctionCall = new NamedFunctionCall("", (BaseFunctionRuntimeTreeNode)baseRuntimeTreeNode); namedFunctionCalls.Add(namedFunctionCall); string layoutLabel = string.Format(StringResourceSystemFacade.GetString("Composite.Plugins.AllFunctionsElementProvider", "FunctionTesterWorkflow.Layout.Label"), function.Name); this.Bindings.Add("LayoutLabel", layoutLabel); } this.Bindings.Add("FunctionCalls", namedFunctionCalls); this.Bindings.Add("Parameters", new List<ManagedParameterDefinition>()); this.Bindings.Add("PageId", PageManager.GetChildrenIDs(Guid.Empty).FirstOrDefault()); if (UserSettings.ActiveLocaleCultureInfo != null) { List<KeyValuePair<string, string>> activeCulturesDictionary = UserSettings.ActiveLocaleCultureInfos.Select(f => new KeyValuePair<string, string>(f.Name, DataLocalizationFacade.GetCultureTitle(f))).ToList(); this.Bindings.Add("ActiveCultureName", UserSettings.ActiveLocaleCultureInfo.Name); this.Bindings.Add("ActiveCulturesList", activeCulturesDictionary); } this.Bindings.Add("PageDataScopeName", DataScopeIdentifier.AdministratedName); this.Bindings.Add("PageDataScopeList", new Dictionary<string, string> { { DataScopeIdentifier.AdministratedName, StringResourceSystemFacade.GetString("Composite.Plugins.AllFunctionsElementProvider", "FunctionTesterWorkflow.AdminitrativeScope.Label") }, { DataScopeIdentifier.PublicName, StringResourceSystemFacade.GetString("Composite.Plugins.AllFunctionsElementProvider", "FunctionTesterWorkflow.PublicScope.Label") } }); Guid stateId = Guid.NewGuid(); var state = new FunctionCallDesignerState { WorkflowId = WorkflowInstanceId, ConsoleIdInternal = GetCurrentConsoleId() }; SessionStateManager.DefaultProvider.AddState<IFunctionCallEditorState>(stateId, state, DateTime.Now.AddDays(7.0)); this.Bindings.Add("SessionStateProvider", SessionStateManager.DefaultProviderName); this.Bindings.Add("SessionStateId", stateId); } private void editCodeActivity_Preview_ExecuteCode(object sender, EventArgs e) { Guid pageId; if (this.GetBinding<object>("PageId") == null) pageId = Guid.Empty; else pageId = this.GetBinding<Guid>("PageId"); string dataScopeName = this.GetBinding<string>("PageDataScopeName"); string cultureName = this.GetBinding<string>("ActiveCultureName"); // Setting debug page IPage oldPage = PageRenderer.CurrentPage; IPage page = DataFacade.GetData<IPage>(f => f.Id == pageId).FirstOrDefault(); if (page != null) PageRenderer.CurrentPage = page; // Setting debug culture CultureInfo oldCurrentCulture = Thread.CurrentThread.CurrentCulture; CultureInfo oldCurrentUICulture = Thread.CurrentThread.CurrentUICulture; CultureInfo cultureInfo = null; if (cultureName != null) cultureInfo = CultureInfo.CreateSpecificCulture(cultureName); if (cultureInfo != null) { Thread.CurrentThread.CurrentCulture = cultureInfo; Thread.CurrentThread.CurrentUICulture = cultureInfo; } List<NamedFunctionCall> namedFunctionCalls = GetBinding<List<NamedFunctionCall>>("FunctionCalls"); StringBuilder output = new StringBuilder(); foreach (NamedFunctionCall namedFunctionCall in namedFunctionCalls) { output.AppendLine(namedFunctionCall.FunctionCall.GetCompositeName() + " result:"); object functionResult; try { // Setting debug data scope using (new DataScope(DataScopeIdentifier.Deserialize(dataScopeName), cultureInfo)) { functionResult = namedFunctionCall.FunctionCall.GetValue(); } } catch(Exception ex) { StringBuilder sb = new StringBuilder(); while (ex != null) { sb.AppendLine(ex.ToString()); ex = ex.InnerException; } functionResult = sb.ToString(); } output.AppendLine(PrettyPrinter.Print(functionResult)); output.AppendLine(); } // Restore culture Thread.CurrentThread.CurrentCulture = oldCurrentCulture; Thread.CurrentThread.CurrentUICulture = oldCurrentUICulture; // Page should not be restored FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); IFormFlowWebRenderingService formFlowWebRenderingService = serviceContainer.GetService<IFormFlowWebRenderingService>(); Control outputControl = new LiteralControl("<pre>" + HttpUtility.HtmlEncode(output) + "</pre>"); formFlowWebRenderingService.SetNewPageOutput(outputControl); } [Serializable] public sealed class FunctionCallDesignerState : IFunctionCallEditorState { public Guid WorkflowId { get; set; } public string ConsoleIdInternal { get; set; } private FormData GetFormData() { return WorkflowFacade.GetFormData(WorkflowId); } #region IFunctionCallEditorState Members [XmlIgnore] public List<NamedFunctionCall> FunctionCalls { get { return GetFormData().Bindings["FunctionCalls"] as List<NamedFunctionCall>; } set { GetFormData().Bindings["FunctionCalls"] = value; } } [XmlIgnore] public List<ManagedParameterDefinition> Parameters { get { return GetFormData().Bindings["Parameters"] as List<ManagedParameterDefinition>; } set { GetFormData().Bindings["Parameters"] = value; } } [XmlIgnore] public List<Type> ParameterTypeOptions { get { return (GetFormData().Bindings["ParameterTypeOptions"] as IEnumerable<Type>).ToList(); } set { GetFormData().Bindings["ParameterTypeOptions"] = value.ToList(); } } public string ConsoleId { get { return ConsoleIdInternal; } } public bool StartInSourceMode { get { return true; } } public bool ShowLocalFunctionNames { get { return false; } } public bool AllowLocalFunctionNameEditing { get { return false; } } public bool WidgetFunctionSelection { get { return false; } } public bool AllowSelectingInputParameters { get { return true; } } public Type[] AllowedResultTypes { get { return new[] { typeof(object) }; } } public int MaxFunctionAllowed { get { return 1000; } } #endregion } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/AllFunctionsElementProvider/FunctionTesterWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Workflows.Plugins.Elements.ElementProviders.AllFunctionsElementProvider { partial class FunctionTesterWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.editCodeActivity_Preview = new System.Workflow.Activities.CodeActivity(); this.editPreviewHandleExternalEventActivity = new Composite.C1Console.Workflow.Activities.PreviewHandleExternalEventActivity(); this.editDocumentFormActivity = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initalizeStateCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.editEventDrivenActivity_Preview = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "editStateActivity"; // // editCodeActivity_Preview // this.editCodeActivity_Preview.Name = "editCodeActivity_Preview"; this.editCodeActivity_Preview.ExecuteCode += new System.EventHandler(this.editCodeActivity_Preview_ExecuteCode); // // editPreviewHandleExternalEventActivity // this.editPreviewHandleExternalEventActivity.EventName = "Preview"; this.editPreviewHandleExternalEventActivity.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.editPreviewHandleExternalEventActivity.Name = "editPreviewHandleExternalEventActivity"; // // editDocumentFormActivity // this.editDocumentFormActivity.ContainerLabel = null; this.editDocumentFormActivity.CustomToolbarDefinitionFileName = null; this.editDocumentFormActivity.FormDefinitionFileName = "\\Administrative\\FunctionTesterEditFunction.xml"; this.editDocumentFormActivity.Name = "editDocumentFormActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // initalizeStateCodeActivity_Initialize // this.initalizeStateCodeActivity_Initialize.Name = "initalizeStateCodeActivity_Initialize"; this.initalizeStateCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initalizeStateCodeActivity_Initialize_ExecuteCode); // // editEventDrivenActivity_Preview // this.editEventDrivenActivity_Preview.Activities.Add(this.editPreviewHandleExternalEventActivity); this.editEventDrivenActivity_Preview.Activities.Add(this.editCodeActivity_Preview); this.editEventDrivenActivity_Preview.Activities.Add(this.setStateActivity3); this.editEventDrivenActivity_Preview.Name = "editEventDrivenActivity_Preview"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.editDocumentFormActivity); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initalizeStateCodeActivity_Initialize); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_Preview); this.editStateActivity.Name = "editStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // FunctionTesterWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.editStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "FunctionTesterWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private C1Console.Workflow.Activities.DocumentFormActivity editDocumentFormActivity; private StateInitializationActivity editStateInitializationActivity; private StateActivity editStateActivity; private CodeActivity initalizeStateCodeActivity_Initialize; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity3; private CodeActivity editCodeActivity_Preview; private C1Console.Workflow.Activities.PreviewHandleExternalEventActivity editPreviewHandleExternalEventActivity; private EventDrivenActivity editEventDrivenActivity_Preview; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/AllFunctionsElementProvider/FunctionTesterWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1185; 932" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="FunctionTesterWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 209" Location="38; 63"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 44" Location="48; 128" /> <SetStateDesigner Name="setStateActivity1" Size="130; 62" Location="48; 191" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="227; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 209" Location="98; 171"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initalizeStateCodeActivity_Initialize" Size="130; 44" Location="108; 236" /> <SetStateDesigner Name="setStateActivity2" Size="130; 62" Location="108; 299" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="222; 84" AutoSizeMargin="16; 24" AutoSize="False" Location="291; 318" Name="editStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="editStateInitializationActivity" Size="150; 128" Location="539; 141"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="editDocumentFormActivity" Size="130; 44" Location="549; 206" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="editEventDrivenActivity_Preview" Size="150; 272" Location="547; 154"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="editPreviewHandleExternalEventActivity" Size="130; 44" Location="557; 219" /> <CodeDesigner Name="editCodeActivity_Preview" Size="130; 44" Location="557; 282" /> <SetStateDesigner Name="setStateActivity3" Size="130; 62" Location="557; 345" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="FunctionTesterWorkflow" TargetConnectionIndex="0" SourceStateName="FunctionTesterWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="74" /> <ns0:Point X="1058" Y="74" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="313" Y="182" /> <ns0:Point X="402" Y="182" /> <ns0:Point X="402" Y="318" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity3" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editEventDrivenActivity_Preview" SourceConnectionIndex="1" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="749" Y="178" /> <ns0:Point X="762" Y="178" /> <ns0:Point X="762" Y="100" /> <ns0:Point X="642" Y="100" /> <ns0:Point X="642" Y="108" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/Common/BaseFunctionWorkflow.cs ================================================ using System; using System.IO; using System.Linq; using Composite.AspNet.Security; using Composite.C1Console.Actions; using Composite.C1Console.Elements.Foundation.PluginFacades; using Composite.C1Console.Workflow; using Composite.C1Console.Workflow.Activities; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Functions; using Composite.Functions.Foundation.PluginFacades; using Composite.Functions.Plugins.FunctionProvider; using Composite.Functions.Plugins.FunctionProvider.Runtime; using Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider; using Composite.Plugins.Functions.FunctionProviders.FileBasedFunctionProvider; using BaseFunctionElementProvider = Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider.BaseFunctionProviderElementProvider; namespace Composite.Plugins.Elements.ElementProviders.Common { /// <summary> /// </summary> /// <exclude /> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class BaseFunctionWorkflow : FormsWorkflow { /// <summary> /// Refreshed function tree for the currently used function provider element provider. /// </summary> public void RefreshFunctionTree() { WorkflowActionToken actionToken = (WorkflowActionToken)this.ActionToken; var entityToken = new BaseFunctionFolderElementEntityToken(actionToken.Payload, string.Empty); SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(entityToken); } public T GetFunctionProvider<T>() where T: class, IFunctionProvider { var functionFolderEntityToken = (this.EntityToken as BaseFunctionFolderElementEntityToken); if (functionFolderEntityToken != null) { var elementProvider = ElementProviderPluginFacade.GetElementProvider(functionFolderEntityToken.ElementProviderName) as BaseFunctionElementProvider; if (elementProvider != null) { var provider = FunctionProviderPluginFacade.GetFunctionProvider(elementProvider.FunctionProviderName); if (provider is T) { return provider as T; } } } var functionProviderSettings = ConfigurationServices.ConfigurationSource.GetSection(FunctionProviderSettings.SectionName) as FunctionProviderSettings; var providerNames = functionProviderSettings.FunctionProviderPlugins.Select(plugin => plugin.Name); foreach (string providerName in providerNames) { var provider = FunctionProviderPluginFacade.GetFunctionProvider(providerName); if (provider is T) { return provider as T; } } throw new InvalidOperationException("Failed to get instance of " + typeof(T).Name); } internal void GetProviderAndFunction<FunctionType>( FileBasedFunctionEntityToken entityToken, out FileBasedFunctionProvider<FunctionType> provider, out FileBasedFunction<FunctionType> function) where FunctionType : FileBasedFunction<FunctionType> { string functionProviderName = entityToken.FunctionProviderName; provider = (FileBasedFunctionProvider<FunctionType>)FunctionProviderPluginFacade.GetFunctionProvider(functionProviderName); IFunction func = FunctionFacade.GetFunction(entityToken.FunctionName); Verify.IsNotNull(func, "Failed to get function '{0}'", entityToken.FunctionName); if (func is FunctionWrapper) { func = (func as FunctionWrapper).InnerFunction; } function = (FileBasedFunction<FunctionType>) func; } internal static void DeleteEmptyAncestorFolders(string filePath) { string folder = Path.GetDirectoryName(filePath); while (!C1Directory.GetFiles(folder).Any() && !C1Directory.GetDirectories(folder).Any()) { C1Directory.Delete(folder); folder = folder.Substring(0, folder.LastIndexOf('\\')); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/Common/KeyFieldHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Plugins_GeneratedDataTypesElementProvider; namespace Composite.Plugins.Elements.ElementProviders.Common { public static class KeyFieldHelper { public static Dictionary<string, string> GetKeyFieldOptions() { return new Dictionary<string, string> { {GeneratedTypesHelper.KeyFieldType.Guid.ToString(), Texts.EditorCommon_KeyFieldType_Guid}, {GeneratedTypesHelper.KeyFieldType.RandomString4.ToString(), Texts.EditorCommon_KeyFieldType_RandomString4}, {GeneratedTypesHelper.KeyFieldType.RandomString8.ToString(), Texts.EditorCommon_KeyFieldType_RandomString8} }; } //public static GeneratedTypesHelper.KeyFieldType ParseKeyFieldType(string keyFieldTypeStr) //{ // return (GeneratedTypesHelper.KeyFieldType) Enum.Parse(typeof (GeneratedTypesHelper.KeyFieldType), keyFieldTypeStr); //} public static GeneratedTypesHelper.KeyFieldType GetKeyFieldType(DataTypeDescriptor dataTypeDescriptor) { var idField = dataTypeDescriptor.Fields.Single(f => f.Name == "Id"); if (idField != null) { return GetKeyFieldType(idField); } return GeneratedTypesHelper.KeyFieldType.Undefined; } public static GeneratedTypesHelper.KeyFieldType GetKeyFieldType(DataFieldDescriptor field) { if (field.InstanceType == typeof(Guid)) { return GeneratedTypesHelper.KeyFieldType.Guid; } if (field.InstanceType == typeof(string) && field.DefaultValue != null) { if (field.DefaultValue.Equals(DefaultValue.RandomString(4, true))) { return GeneratedTypesHelper.KeyFieldType.RandomString4; } if (field.DefaultValue.Equals(DefaultValue.RandomString(8, false))) { return GeneratedTypesHelper.KeyFieldType.RandomString8; } } return GeneratedTypesHelper.KeyFieldType.Undefined; } public static void UpdateKeyType(DataFieldDescriptor idField, GeneratedTypesHelper.KeyFieldType selectedFieldType) { switch (selectedFieldType) { case GeneratedTypesHelper.KeyFieldType.Guid: idField.StoreType = StoreFieldType.Guid; idField.InstanceType = typeof(Guid); idField.DefaultValue = null; break; case GeneratedTypesHelper.KeyFieldType.RandomString4: idField.StoreType = StoreFieldType.String(22); idField.InstanceType = typeof(string); idField.DefaultValue = DefaultValue.RandomString(4, true); break; case GeneratedTypesHelper.KeyFieldType.RandomString8: idField.StoreType = StoreFieldType.String(22); idField.InstanceType = typeof(string); idField.DefaultValue = DefaultValue.RandomString(8, false); break; } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/Common/PageTemplateHelper.cs ================================================ using System; using System.Collections.Generic; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Data; using Composite.Data.Types; namespace Composite.Plugins.Elements.ElementProviders.Common { internal class PageTemplateHelper { public static string LoadDefaultTemplateFile(string fileName) { return C1File.ReadAllText(PathUtil.Resolve("~/Composite/templates/PageTemplates/" + fileName)) .Replace(" ", "\t"); } /// <summary> /// Replaces html escape sequences with their XML alternative. /// Fixes casing in DOCTYPE declaration /// </summary> public static string FixHtmlEscapeSequences(string xhtml) { return xhtml .Replace(" ", " ", StringComparison.OrdinalIgnoreCase) .Replace("“", "“", StringComparison.OrdinalIgnoreCase) .Replace("&rdguo;", "”", StringComparison.OrdinalIgnoreCase) .Replace("‘", "‘", StringComparison.OrdinalIgnoreCase) .Replace("’", "’", StringComparison.OrdinalIgnoreCase) .Replace("«", "«", StringComparison.OrdinalIgnoreCase) .Replace("»", "»", StringComparison.OrdinalIgnoreCase) .Replace("‹", "‹", StringComparison.OrdinalIgnoreCase) .Replace("›", "›", StringComparison.OrdinalIgnoreCase) .Replace("•", "•", StringComparison.OrdinalIgnoreCase) .Replace("°", "°", StringComparison.OrdinalIgnoreCase) .Replace("…", "…", StringComparison.OrdinalIgnoreCase) .Replace("™", "™", StringComparison.OrdinalIgnoreCase) .Replace("©", "©", StringComparison.OrdinalIgnoreCase) .Replace("®", "®", StringComparison.OrdinalIgnoreCase) .Replace("—", "—", StringComparison.OrdinalIgnoreCase) .Replace("–", "–", StringComparison.OrdinalIgnoreCase) .Replace("²", "²", StringComparison.OrdinalIgnoreCase) .Replace("³", "³", StringComparison.OrdinalIgnoreCase) .Replace("¼", "¼", StringComparison.OrdinalIgnoreCase) .Replace("½", "½", StringComparison.OrdinalIgnoreCase) .Replace("¾", "¾", StringComparison.OrdinalIgnoreCase) .Replace("×", "×", StringComparison.OrdinalIgnoreCase) .Replace("←", "←", StringComparison.OrdinalIgnoreCase) .Replace("→", "→", StringComparison.OrdinalIgnoreCase) .Replace("↑", "↑", StringComparison.OrdinalIgnoreCase) .Replace("↓", "↓", StringComparison.OrdinalIgnoreCase) .Replace("·", "·", StringComparison.OrdinalIgnoreCase) .Replace("<!doctype", "<!DOCTYPE", StringComparison.OrdinalIgnoreCase); } public static Guid GetTheMostUsedTemplate(IEnumerable<Guid> templateIds) { IDictionary<Guid, int> usageStats = TemplateUsageStatictic(); Guid mostUsed = Guid.Empty; int usages = 0; foreach (Guid templateId in templateIds) { if (usageStats.ContainsKey(templateId) && usages < usageStats[templateId]) { mostUsed = templateId; usages = usageStats[templateId]; } else if(usages == 0 && mostUsed == Guid.Empty) { mostUsed = templateId; } } return mostUsed; } private static IDictionary<Guid, int> TemplateUsageStatictic() { var result = new Dictionary<Guid, int>(); foreach (IPage page in DataFacade.GetData<IPage>()) { Guid templateId = page.TemplateId; if (!result.ContainsKey(templateId)) { result.Add(templateId, 1); } else { result[templateId] = result[templateId] + 1; } } return result; } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/AddNewCompositionTypeWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; using Composite.Data.ProcessControlled; using Composite.Core.Logging; using Composite.C1Console.Security; using Composite.Core.Types; using Composite.C1Console.Users; using Composite.Data.Validation.ClientValidationRules; using Composite.C1Console.Workflow; using Composite.Data.ExtendedDataType.Debug; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewCompositionTypeWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { private string NewTypeNameBindingName { get { return "NewTypeName"; } } private string NewTypeNamespaceBindingName { get { return "NewTypeNamespace"; } } private string NewTypeTitleBindingName { get { return "NewTypeTitle"; } } private string DataFieldDescriptorsBindingName { get { return "DataFieldDescriptors"; } } private string LabelFieldNameBindingName { get { return "LabelFieldName"; } } private string HasCachingNameBindingName { get { return "HasCaching"; } } private string HasPublishingBindingName { get { return "HasPublishing"; } } public AddNewCompositionTypeWorkflow() { InitializeComponent(); } private void initializeStateCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { Type targetType = TypeManager.GetType(this.Payload); this.Bindings.Add(this.NewTypeNameBindingName, ""); this.Bindings.Add(this.NewTypeNamespaceBindingName, UserSettings.LastSpecifiedNamespace); this.Bindings.Add(this.NewTypeTitleBindingName, ""); this.Bindings.Add(this.DataFieldDescriptorsBindingName, new List<DataFieldDescriptor>()); this.Bindings.Add(this.LabelFieldNameBindingName, ""); this.Bindings.Add(this.HasCachingNameBindingName, false); this.Bindings.Add(this.HasPublishingBindingName, typeof(IPublishControlled).IsAssignableFrom(targetType)); this.Bindings.Add("HasLocalization", true); this.BindingsValidationRules.Add(this.NewTypeNameBindingName, new List<ClientValidationRule> { new NotNullClientValidationRule() }); this.BindingsValidationRules.Add(this.NewTypeNamespaceBindingName, new List<ClientValidationRule> { new NotNullClientValidationRule() }); this.BindingsValidationRules.Add(this.NewTypeTitleBindingName, new List<ClientValidationRule> { new NotNullClientValidationRule() }); if ((RuntimeInformation.IsDebugBuild) && (DynamicTempTypeCreator.UseTempTypeCreator)) { DynamicTempTypeCreator dynamicTempTypeCreator = new DynamicTempTypeCreator("PageMetaData"); this.UpdateBinding(this.NewTypeNameBindingName, dynamicTempTypeCreator.TypeName); this.UpdateBinding(this.NewTypeTitleBindingName, dynamicTempTypeCreator.TypeTitle); this.UpdateBinding(this.DataFieldDescriptorsBindingName, dynamicTempTypeCreator.DataFieldDescriptors); this.UpdateBinding(this.LabelFieldNameBindingName, dynamicTempTypeCreator.DataFieldDescriptors.First().Name); } } 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.SetCacheable(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); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/AddNewCompositionTypeWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { partial class AddNewCompositionTypeWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.saveTypeCodeActivity_Save = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.editTypeDocumentFormActivity = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeStateCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.saveTypeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editTypeEventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editTypeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveTypeStateActivity = new System.Workflow.Activities.StateActivity(); this.editTypeStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editTypeStateActivity"; // // saveTypeCodeActivity_Save // this.saveTypeCodeActivity_Save.Name = "saveTypeCodeActivity_Save"; this.saveTypeCodeActivity_Save.ExecuteCode += new System.EventHandler(this.saveTypeCodeActivity_Save_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "saveTypeStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // editTypeDocumentFormActivity // this.editTypeDocumentFormActivity.ContainerLabel = null; this.editTypeDocumentFormActivity.FormDefinitionFileName = "\\Administrative\\AddNewCompositionTypeStep1.xml"; this.editTypeDocumentFormActivity.Name = "editTypeDocumentFormActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editTypeStateActivity"; // // initializeStateCodeActivity_Initialize // this.initializeStateCodeActivity_Initialize.Name = "initializeStateCodeActivity_Initialize"; this.initializeStateCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeStateCodeActivity_Initialize_ExecuteCode); // // saveTypeStateInitializationActivity // this.saveTypeStateInitializationActivity.Activities.Add(this.saveTypeCodeActivity_Save); this.saveTypeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.saveTypeStateInitializationActivity.Name = "saveTypeStateInitializationActivity"; // // editTypeEventDrivenActivity_Save // this.editTypeEventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.editTypeEventDrivenActivity_Save.Activities.Add(this.setStateActivity3); this.editTypeEventDrivenActivity_Save.Name = "editTypeEventDrivenActivity_Save"; // // editTypeStateInitializationActivity // this.editTypeStateInitializationActivity.Activities.Add(this.editTypeDocumentFormActivity); this.editTypeStateInitializationActivity.Name = "editTypeStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeStateCodeActivity_Initialize); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveTypeStateActivity // this.saveTypeStateActivity.Activities.Add(this.saveTypeStateInitializationActivity); this.saveTypeStateActivity.Name = "saveTypeStateActivity"; // // editTypeStateActivity // this.editTypeStateActivity.Activities.Add(this.editTypeStateInitializationActivity); this.editTypeStateActivity.Activities.Add(this.editTypeEventDrivenActivity_Save); this.editTypeStateActivity.Name = "editTypeStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // AddNewCompositionTypeWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.editTypeStateActivity); this.Activities.Add(this.saveTypeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddNewCompositionTypeWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private Composite.C1Console.Workflow.Activities.DocumentFormActivity editTypeDocumentFormActivity; private SetStateActivity setStateActivity2; private StateInitializationActivity editTypeStateInitializationActivity; private StateActivity editTypeStateActivity; private CodeActivity initializeStateCodeActivity_Initialize; private Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private EventDrivenActivity editTypeEventDrivenActivity_Save; private CodeActivity saveTypeCodeActivity_Save; private StateInitializationActivity saveTypeStateInitializationActivity; private StateActivity saveTypeStateActivity; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity3; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/AddNewCompositionTypeWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="AddNewCompositionTypeWorkflow" Location="30; 30" Size="1154; 974" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="AddNewCompositionTypeWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="AddNewCompositionTypeWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editTypeStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="editTypeStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="383" Y="179" /> <ns0:Point X="383" Y="369" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="saveTypeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="editTypeStateActivity" SourceConnectionEdge="Right" TargetActivity="saveTypeStateActivity" SourceActivity="editTypeStateActivity" EventHandlerName="editTypeEventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="488" Y="434" /> <ns0:Point X="739" Y="434" /> <ns0:Point X="739" Y="446" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editTypeStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="saveTypeStateActivity" SourceConnectionEdge="Right" TargetActivity="editTypeStateActivity" SourceActivity="saveTypeStateActivity" EventHandlerName="saveTypeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="844" Y="487" /> <ns0:Point X="855" Y="487" /> <ns0:Point X="855" Y="361" /> <ns0:Point X="383" Y="361" /> <ns0:Point X="383" Y="369" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeStateCodeActivity_Initialize" Location="108; 231" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="108; 291" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="editTypeStateActivity" Location="274; 369" Size="218; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="editTypeStateInitializationActivity" Location="282; 400"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="editTypeDocumentFormActivity" Location="292; 462" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="editTypeEventDrivenActivity_Save" Location="282; 424"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="saveHandleExternalEventActivity1" Location="292; 486" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="292; 546" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="saveTypeStateActivity" Location="630; 446" Size="218; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="saveTypeStateInitializationActivity" Location="638; 477"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="saveTypeCodeActivity_Save" Location="648; 539" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="648; 599" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/AddNewDataWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { partial class AddNewDataWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.setEnablePublishCodeActivity = new System.Workflow.Activities.CodeActivity(); this.saveAndPublishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveAndPublishHandleExternalEventActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.step1CodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.initialCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finializeDtateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.saveAndPublishEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.saveStep1EventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.initialStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "saveStateActivity"; // // setEnablePublishCodeActivity // this.setEnablePublishCodeActivity.Name = "setEnablePublishCodeActivity"; this.setEnablePublishCodeActivity.ExecuteCode += new System.EventHandler(this.setEnablePublishCodeActivity_ExecuteCode); // // saveAndPublishHandleExternalEventActivity1 // this.saveAndPublishHandleExternalEventActivity1.EventName = "SaveAndPublish"; this.saveAndPublishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveAndPublishHandleExternalEventActivity1.Name = "saveAndPublishHandleExternalEventActivity1"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "saveStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // step1CodeActivity // this.step1CodeActivity.Name = "step1CodeActivity"; this.step1CodeActivity.ExecuteCode += new System.EventHandler(this.step1CodeActivity_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "step1StateActivity"; // // initialCodeActivity_Initialize // this.initialCodeActivity_Initialize.Name = "initialCodeActivity_Initialize"; this.initialCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initialCodeActivity_Initialize_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finializeDtateInitializationActivity // this.finializeDtateInitializationActivity.Activities.Add(this.finalizeCodeActivity); this.finializeDtateInitializationActivity.Activities.Add(this.setStateActivity2); this.finializeDtateInitializationActivity.Name = "finializeDtateInitializationActivity"; // // saveAndPublishEventDrivenActivity // this.saveAndPublishEventDrivenActivity.Activities.Add(this.saveAndPublishHandleExternalEventActivity1); this.saveAndPublishEventDrivenActivity.Activities.Add(this.setEnablePublishCodeActivity); this.saveAndPublishEventDrivenActivity.Activities.Add(this.setStateActivity3); this.saveAndPublishEventDrivenActivity.Name = "saveAndPublishEventDrivenActivity"; // // saveStep1EventDrivenActivity // this.saveStep1EventDrivenActivity.Activities.Add(this.saveHandleExternalEventActivity1); this.saveStep1EventDrivenActivity.Activities.Add(this.setStateActivity6); this.saveStep1EventDrivenActivity.Name = "saveStep1EventDrivenActivity"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1CodeActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.initialCodeActivity_Initialize); this.initialStateInitializationActivity.Activities.Add(this.setStateActivity4); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity1); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.finializeDtateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.saveStep1EventDrivenActivity); this.step1StateActivity.Activities.Add(this.saveAndPublishEventDrivenActivity); this.step1StateActivity.Name = "step1StateActivity"; // // initialStateActivity // this.initialStateActivity.Activities.Add(this.initialStateInitializationActivity); this.initialStateActivity.Name = "initialStateActivity"; // // AddNewDataWorkflow // this.Activities.Add(this.initialStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.saveStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelEventDrivenActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialStateActivity"; this.Name = "AddNewDataWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity3; private CodeActivity setEnablePublishCodeActivity; private C1Console.Workflow.Activities.SaveAndPublishHandleExternalEventActivity saveAndPublishHandleExternalEventActivity1; private EventDrivenActivity saveAndPublishEventDrivenActivity; private SetStateActivity setStateActivity1; private StateInitializationActivity finializeDtateInitializationActivity; private EventDrivenActivity saveStep1EventDrivenActivity; private StateInitializationActivity step1StateInitializationActivity; private StateInitializationActivity initialStateInitializationActivity; private EventDrivenActivity cancelEventDrivenActivity; private StateActivity finalStateActivity; private StateActivity saveStateActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private CodeActivity step1CodeActivity; private CodeActivity finalizeCodeActivity; private C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity6; private CodeActivity initialCodeActivity_Initialize; private StateActivity initialStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/AddNewDataWorkflow.cs ================================================  using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Elements.ElementProviderHelpers.DataGroupingProviderHelper; using Composite.C1Console.Scheduling; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.C1Console.Workflow.Activities; using Composite.Core.Serialization; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewDataWorkflow : FormsWorkflow { [NonSerialized] private bool _doPublish; [NonSerialized] private DataTypeDescriptorFormsHelper _helper; [NonSerialized] private string _typeName; public AddNewDataWorkflow() { InitializeComponent(); } private Type GetInterfaceType() { Type type; if (EntityToken is GeneratedDataTypesElementProviderTypeEntityToken) { var entityToken = EntityToken as GeneratedDataTypesElementProviderTypeEntityToken; type = TypeManager.GetType(entityToken.SerializedTypeName); } else if (EntityToken is DataGroupingProviderHelperEntityToken) { var entityToken = EntityToken as DataGroupingProviderHelperEntityToken; type = TypeManager.GetType(entityToken.Type); } else { throw new NotImplementedException(); } return type; } private DataTypeDescriptorFormsHelper GetDataTypeDescriptorFormsHelper() { if (_helper == null) { var type = GetInterfaceType(); var guid = type.GetImmutableTypeId(); var typeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(guid); if (typeDescriptor == null) { throw new InvalidOperationException(string.Format("Can not find the type descriptor for the type '{0}'", type)); } var generatedTypesHelper = new GeneratedTypesHelper(typeDescriptor) { AllowForeignKeyEditing = true }; _helper = new DataTypeDescriptorFormsHelper(typeDescriptor, true, EntityToken) { LayoutIconHandle = "generated-type-data-add" }; _helper.AddReadOnlyFields(generatedTypesHelper.NotEditableDataFieldDescriptorNames); _typeName = typeDescriptor.Name; } return _helper; } private void initialCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { var type = GetInterfaceType(); if (!PermissionsFacade.GetPermissionsForCurrentUser(EntityToken).Contains(PermissionType.Publish) || !typeof(IPublishControlled).IsAssignableFrom(type)) { var formData = WorkflowFacade.GetFormData(InstanceId, true); if (formData.ExcludedEvents == null) { formData.ExcludedEvents = new List<string>(); } formData.ExcludedEvents.Add("SaveAndPublish"); } var helper = GetDataTypeDescriptorFormsHelper(); helper.UpdateWithNewBindings(Bindings); var newData = DataFacade.BuildNew(type); var publishControlled = newData as IPublishControlled; if (publishControlled != null) { publishControlled.PublicationStatus = GenericPublishProcessController.Draft; } if (!string.IsNullOrEmpty(Payload)) { var values = new Dictionary<string, string>(); var serializedValues = StringConversionServices.ParseKeyValueCollection(Payload); foreach (var kvp in serializedValues) { values.Add(kvp.Key, StringConversionServices.DeserializeValueString(kvp.Value)); } newData.SetValues(values); } helper.ObjectToBindings(newData, Bindings); GeneratedTypesHelper.SetNewIdFieldValue(newData); Bindings.Add("NewData", newData); } private void step1CodeActivity_ExecuteCode(object sender, EventArgs e) { var helper = GetDataTypeDescriptorFormsHelper(); if (!BindingExist("DataAdded")) { helper.LayoutLabel = helper.DataTypeDescriptor.Name; } var newData = GetBinding<IData>("NewData"); DeliverFormData( _typeName, StandardUiContainerTypes.Document, helper.GetForm(), Bindings, helper.GetBindingsValidationRules(newData) ); } private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { var justAdded = false; var isValid = ValidateBindings(); var helper = GetDataTypeDescriptorFormsHelper(); var newData = GetBinding<IData>("NewData"); if (!BindAndValidate(helper, newData)) { isValid = false; } if (isValid) { if (!BindingExist("DataAdded")) { newData = DataFacade.AddNew(newData); justAdded = true; AcquireLock(newData.GetDataEntityToken()); UpdateBinding("NewData", newData); Bindings.Add("DataAdded", true); PublishControlledHelper.PublishIfNeeded(newData, _doPublish, Bindings, ShowMessage); var specificTreeRefresher = CreateParentTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(EntityToken); } else { var updateTreeRefresher = CreateUpdateTreeRefresher(EntityToken); DataFacade.Update(newData); EntityTokenCacheFacade.ClearCache(newData.GetDataEntityToken()); var published = PublishControlledHelper.PublishIfNeeded(newData, _doPublish, Bindings, ShowMessage); if (!published) { updateTreeRefresher.PostRefreshMesseges(EntityToken); } } } if (justAdded) { SetSaveStatus(true, newData); } else { SetSaveStatus(isValid); } } private void setEnablePublishCodeActivity_ExecuteCode(object sender, EventArgs e) { _doPublish = true; } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/AddNewDataWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1199; 932" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="AddNewDataWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="212; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="79; 119" Name="initialStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initialStateInitializationActivity" Size="150; 209" Location="87; 152"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initialCodeActivity_Initialize" Size="130; 44" Location="97; 217" /> <SetStateDesigner Name="setStateActivity4" Size="130; 62" Location="97; 280" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="239; 110" AutoSizeMargin="16; 24" AutoSize="False" Location="139; 318" Name="step1StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1StateInitializationActivity" Size="150; 128" Location="546; 141"> <StateInitializationDesigner.Designers> <CodeDesigner Name="step1CodeActivity" Size="130; 44" Location="556; 206" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="saveStep1EventDrivenActivity" Size="150; 209" Location="546; 167"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130; 44" Location="556; 232" /> <SetStateDesigner Name="setStateActivity6" Size="130; 62" Location="556; 295" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="saveAndPublishEventDrivenActivity" Size="150; 272" Location="554; 154"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveAndPublishHandleExternalEventActivity1" Size="130; 44" Location="564; 219" /> <CodeDesigner Name="setEnablePublishCodeActivity" Size="130; 44" Location="564; 282" /> <SetStateDesigner Name="setStateActivity3" Size="130; 62" Location="564; 345" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="225; 80" AutoSizeMargin="16; 24" Location="456; 436" Name="saveStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finializeDtateInitializationActivity" Size="150; 209" Location="464; 469"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity" Size="130; 44" Location="474; 534" /> <SetStateDesigner Name="setStateActivity2" Size="130; 62" Location="474; 597" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="754; 652" Name="finalStateActivity" /> <EventDrivenDesigner Name="cancelEventDrivenActivity" Size="150; 209" Location="38; 63"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 44" Location="48; 128" /> <SetStateDesigner Name="setStateActivity1" Size="130; 62" Location="48; 191" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="AddNewDataWorkflow" TargetConnectionIndex="0" SourceStateName="AddNewDataWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="cancelEventDrivenActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="214" Y="74" /> <ns0:Point X="834" Y="74" /> <ns0:Point X="834" Y="652" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity4" SourceActivity="initialStateActivity" TargetConnectionIndex="0" SourceStateName="initialStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initialStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="287" Y="163" /> <ns0:Point X="298" Y="163" /> <ns0:Point X="298" Y="306" /> <ns0:Point X="258" Y="306" /> <ns0:Point X="258" Y="318" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" SetStateName="setStateActivity6" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="saveStep1EventDrivenActivity" SourceConnectionIndex="1" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="344" Y="388" /> <ns0:Point X="568" Y="388" /> <ns0:Point X="568" Y="436" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity2" SourceActivity="saveStateActivity" TargetConnectionIndex="0" SourceStateName="saveStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finializeDtateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="677" Y="480" /> <ns0:Point X="690" Y="480" /> <ns0:Point X="690" Y="310" /> <ns0:Point X="258" Y="310" /> <ns0:Point X="258" Y="318" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" SetStateName="setStateActivity3" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="saveAndPublishEventDrivenActivity" SourceConnectionIndex="2" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="374" Y="414" /> <ns0:Point X="568" Y="414" /> <ns0:Point X="568" Y="436" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/AddNewInterfaceTypeWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Events; using Composite.Core; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.ExtendedDataType.Debug; using Composite.Data.GeneratedTypes; using Composite.C1Console.Security; using Composite.Core.Types; using Composite.C1Console.Users; using Composite.Data.Validation.ClientValidationRules; using Composite.C1Console.Workflow; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Plugins_GeneratedDataTypesElementProvider; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewInterfaceTypeWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddNewInterfaceTypeWorkflow() { InitializeComponent(); } private static class BindingNames { public const string ViewLabel = "ViewLabel"; public const string InterfaceType = "InterfaceType"; public const string NewTypeName = "NewTypeName"; public const string NewTypeNamespace = "NewTypeNamespace"; public const string NewTypeTitle = "NewTypeTitle"; public const string DataFieldDescriptors = "DataFieldDescriptors"; public const string KeyFieldName = "KeyFieldName"; public const string LabelFieldName = "LabelFieldName"; public const string InternalUrlPrefix = "InternalUrlPrefix"; public const string HasCaching = "HasCaching"; public const string HasPublishing = "HasPublishing"; public const string HasLocalization = "HasLocalization"; public const string IsSearchable = nameof(IsSearchable); public const string KeyFieldReadOnly = "KeyFieldReadOnly"; } private bool IsPageDataFolder { get { return this.EntityToken.Id == GeneratedDataTypesElementProviderRootEntityToken.PageDataFolderTypeFolderId; } } private void initialStateCodeActivity_ExecuteCode(object sender, EventArgs e) { var dataFieldDescriptors = new List<DataFieldDescriptor> { GeneratedTypesHelper.BuildIdField() }; this.Bindings = new Dictionary<string, object> { {BindingNames.ViewLabel, IsPageDataFolder ? Texts.AddNewAggregationTypeWorkflow_DocumentTitle : Texts.AddNewInterfaceTypeStep1_DocumentTitle}, {BindingNames.NewTypeName, ""}, {BindingNames.NewTypeNamespace, UserSettings.LastSpecifiedNamespace}, {BindingNames.NewTypeTitle, ""}, {BindingNames.DataFieldDescriptors, dataFieldDescriptors}, {BindingNames.HasCaching, false}, {BindingNames.HasPublishing, false}, {BindingNames.HasLocalization, false}, {BindingNames.IsSearchable, true}, {BindingNames.KeyFieldName, dataFieldDescriptors.First().Name}, {BindingNames.LabelFieldName, ""}, {BindingNames.KeyFieldReadOnly, false} }; this.BindingsValidationRules = new Dictionary<string, List<ClientValidationRule>> { {BindingNames.NewTypeName, new List<ClientValidationRule> {new NotNullClientValidationRule()}}, {BindingNames.NewTypeNamespace, new List<ClientValidationRule> {new NotNullClientValidationRule()}}, {BindingNames.NewTypeTitle, new List<ClientValidationRule> {new NotNullClientValidationRule()}} }; if (RuntimeInformation.IsDebugBuild && DynamicTempTypeCreator.UseTempTypeCreator) { var dynamicTempTypeCreator = new DynamicTempTypeCreator(IsPageDataFolder ? "PageFolder" : "GlobalTest"); dataFieldDescriptors.AddRange(dynamicTempTypeCreator.DataFieldDescriptors); this.UpdateBinding(BindingNames.NewTypeName, dynamicTempTypeCreator.TypeName); this.UpdateBinding(BindingNames.NewTypeTitle, dynamicTempTypeCreator.TypeTitle); this.UpdateBinding(BindingNames.LabelFieldName, dynamicTempTypeCreator.DataFieldDescriptors.First().Name); } } 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); bool isSearchable = this.GetBinding<bool>(BindingNames.IsSearchable); 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.SetCacheable(hasCaching); helper.SetPublishControlled(hasPublishing); helper.SetLocalizedControlled(hasLocalization); helper.SetSearchable(isSearchable); } 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); } } private void codeActivity_RefreshViewHandler(object sender, EventArgs e) { RerenderView(); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/AddNewInterfaceTypeWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { partial class AddNewInterfaceTypeWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finalizeStateCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity_RefreshView = new System.Workflow.Activities.CodeActivity(); this.customEvent01HandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CustomEvent01HandleExternalEventActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.initialStateCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editType_IsSearchableChanged = new System.Workflow.Activities.EventDrivenActivity(); this.saveStep1EventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.editTypePropertiesStateActivity = new System.Workflow.Activities.StateActivity(); this.initialStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "editTypePropertiesStateActivity"; // // finalizeStateCodeActivity // this.finalizeStateCodeActivity.Name = "finalizeStateCodeActivity"; this.finalizeStateCodeActivity.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "editTypePropertiesStateActivity"; // // codeActivity_RefreshView // this.codeActivity_RefreshView.Name = "codeActivity_RefreshView"; this.codeActivity_RefreshView.ExecuteCode += new System.EventHandler(this.codeActivity_RefreshViewHandler); // // customEvent01HandleExternalEventActivity1 // this.customEvent01HandleExternalEventActivity1.EventName = "CustomEvent01"; this.customEvent01HandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.customEvent01HandleExternalEventActivity1.Name = "customEvent01HandleExternalEventActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalizeStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.CustomToolbarDefinitionFileName = null; this.documentFormActivity1.FormDefinitionFileName = "/Administrative/AddNewInterfaceTypeStep1.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "editTypePropertiesStateActivity"; // // initialStateCodeActivity // this.initialStateCodeActivity.Name = "initialStateCodeActivity"; this.initialStateCodeActivity.ExecuteCode += new System.EventHandler(this.initialStateCodeActivity_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeStateCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity5); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // editType_IsSearchableChanged // this.editType_IsSearchableChanged.Activities.Add(this.customEvent01HandleExternalEventActivity1); this.editType_IsSearchableChanged.Activities.Add(this.codeActivity_RefreshView); this.editType_IsSearchableChanged.Activities.Add(this.setStateActivity1); this.editType_IsSearchableChanged.Name = "editType_IsSearchableChanged"; // // saveStep1EventDrivenActivity // this.saveStep1EventDrivenActivity.Activities.Add(this.saveHandleExternalEventActivity1); this.saveStep1EventDrivenActivity.Activities.Add(this.setStateActivity2); this.saveStep1EventDrivenActivity.Name = "saveStep1EventDrivenActivity"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.documentFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.initialStateCodeActivity); this.initialStateInitializationActivity.Activities.Add(this.setStateActivity3); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity4); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // editTypePropertiesStateActivity // this.editTypePropertiesStateActivity.Activities.Add(this.step1StateInitializationActivity); this.editTypePropertiesStateActivity.Activities.Add(this.saveStep1EventDrivenActivity); this.editTypePropertiesStateActivity.Activities.Add(this.editType_IsSearchableChanged); this.editTypePropertiesStateActivity.Name = "editTypePropertiesStateActivity"; // // initialStateActivity // this.initialStateActivity.Activities.Add(this.initialStateInitializationActivity); this.initialStateActivity.Name = "initialStateActivity"; // // AddNewInterfaceTypeWorkflow // this.Activities.Add(this.initialStateActivity); this.Activities.Add(this.editTypePropertiesStateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelEventDrivenActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialStateActivity"; this.Name = "AddNewInterfaceTypeWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity2; private StateInitializationActivity step1StateInitializationActivity; private StateActivity editTypePropertiesStateActivity; private StateActivity finalizeStateActivity; private StateInitializationActivity finalizeStateInitializationActivity; private StateActivity finalStateActivity; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initialStateInitializationActivity; private EventDrivenActivity cancelEventDrivenActivity; private SetStateActivity setStateActivity4; private CodeActivity initialStateCodeActivity; private C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private EventDrivenActivity saveStep1EventDrivenActivity; private CodeActivity finalizeStateCodeActivity; private SetStateActivity setStateActivity1; private CodeActivity codeActivity_RefreshView; private C1Console.Workflow.Activities.CustomEvent01HandleExternalEventActivity customEvent01HandleExternalEventActivity1; private EventDrivenActivity editType_IsSearchableChanged; private StateActivity initialStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/AddNewInterfaceTypeWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="898, 547" AutoSizeMargin="16, 24" Location="30, 30" Name="AddNewInterfaceTypeWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="AddNewInterfaceTypeWorkflow" TargetConnectionIndex="0" SourceStateName="AddNewInterfaceTypeWorkflow" SourceConnectionEdge="Right" EventHandlerName="cancelEventDrivenActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="214" Y="74" /> <ns0:Point X="214" Y="66" /> <ns0:Point X="286" Y="66" /> <ns0:Point X="286" Y="402" /> <ns0:Point X="143" Y="402" /> <ns0:Point X="143" Y="414" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editTypePropertiesStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="initialStateActivity" TargetConnectionIndex="0" SourceStateName="initialStateActivity" SourceConnectionEdge="Right" EventHandlerName="initialStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editTypePropertiesStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="271" Y="150" /> <ns0:Point X="280" Y="150" /> <ns0:Point X="280" Y="194" /> <ns0:Point X="172" Y="194" /> <ns0:Point X="172" Y="202" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="editTypePropertiesStateActivity" TargetConnectionIndex="0" SourceStateName="editTypePropertiesStateActivity" SourceConnectionEdge="Right" EventHandlerName="saveStep1EventDrivenActivity" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="268" Y="272" /> <ns0:Point X="472" Y="272" /> <ns0:Point X="472" Y="286" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editTypePropertiesStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editTypePropertiesStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="578" Y="330" /> <ns0:Point X="588" Y="330" /> <ns0:Point X="588" Y="194" /> <ns0:Point X="172" Y="194" /> <ns0:Point X="172" Y="202" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editTypePropertiesStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="editTypePropertiesStateActivity" TargetConnectionIndex="0" SourceStateName="editTypePropertiesStateActivity" SourceConnectionEdge="Right" EventHandlerName="editType_IsSearchableChanged" SourceConnectionIndex="2" TargetStateName="editTypePropertiesStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="277" Y="298" /> <ns0:Point X="288" Y="298" /> <ns0:Point X="288" Y="194" /> <ns0:Point X="172" Y="194" /> <ns0:Point X="172" Y="202" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="212, 80" AutoSizeMargin="16, 24" Location="63, 106" Name="initialStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initialStateInitializationActivity" Size="150, 209" Location="71, 139"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initialStateCodeActivity" Size="130, 44" Location="81, 204" /> <SetStateDesigner Name="setStateActivity3" Size="130, 62" Location="81, 267" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="218, 110" AutoSizeMargin="16, 24" Location="63, 202" Name="editTypePropertiesStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1StateInitializationActivity" Size="150, 128" Location="71, 235"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="documentFormActivity1" Size="130, 44" Location="81, 300" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="saveStep1EventDrivenActivity" Size="150, 209" Location="71, 261"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130, 44" Location="81, 326" /> <SetStateDesigner Name="setStateActivity2" Size="130, 62" Location="81, 389" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="editType_IsSearchableChanged" Size="150, 272" Location="71, 287"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="customEvent01HandleExternalEventActivity1" Size="130, 44" Location="81, 352" /> <CodeDesigner Name="codeActivity_RefreshView" Size="130, 44" Location="81, 415" /> <SetStateDesigner Name="setStateActivity1" Size="130, 62" Location="81, 478" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="220, 80" AutoSizeMargin="16, 24" Location="362, 286" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150, 209" Location="370, 319"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeStateCodeActivity" Size="130, 44" Location="380, 384" /> <SetStateDesigner Name="setStateActivity5" Size="130, 62" Location="380, 447" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160, 80" AutoSizeMargin="16, 24" Location="63, 414" Name="finalStateActivity" /> <EventDrivenDesigner Name="cancelEventDrivenActivity" Size="150, 209" Location="38, 63"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130, 44" Location="48, 128" /> <SetStateDesigner Name="setStateActivity4" Size="130, 62" Location="48, 191" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/AddTypeToWhiteListWorkflow.cs ================================================ using System; using Composite.C1Console.Actions; using Composite.Data; using Composite.Data.Types; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { public sealed partial class AddTypeToWhiteListWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddTypeToWhiteListWorkflow() { InitializeComponent(); } private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { GeneratedDataTypesElementProviderTypeEntityToken castedEntityToken = (GeneratedDataTypesElementProviderTypeEntityToken)this.EntityToken; IGeneratedTypeWhiteList generatedTypeWhiteList = DataFacade.BuildNew<IGeneratedTypeWhiteList>(); generatedTypeWhiteList.TypeManagerTypeName = castedEntityToken.SerializedTypeName; DataFacade.AddNew<IGeneratedTypeWhiteList>(generatedTypeWhiteList); ParentTreeRefresher parentTreeRefresher = this.CreateParentTreeRefresher(); parentTreeRefresher.PostRefreshMesseges(this.EntityToken, 3); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/AddTypeToWhiteListWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { partial class AddTypeToWhiteListWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalizeStateActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity3); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // AddTypeToWhiteListWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddTypeToWhiteListWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity3; private CodeActivity finalizeCodeActivity; private SetStateActivity setStateActivity2; private StateInitializationActivity finalizeStateInitializationActivity; private StateActivity finalizeStateActivity; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/AddTypeToWhiteListWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="AddTypeToWhiteListWorkflow" Location="30; 30" Size="1183; 996" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="AddTypeToWhiteListWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="AddTypeToWhiteListWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="435" Y="179" /> <ns0:Point X="435" Y="360" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="534" Y="401" /> <ns0:Point X="1058" Y="401" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="108; 231" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="finalizeStateActivity" Location="333; 360" Size="205; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="finalizeStateInitializationActivity" Location="546; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity" Location="556; 210" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="556; 270" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/DeleteAggregationTypeWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Transactions; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; using Composite.Data.Transactions; using Composite.Core.Types; using Composite.C1Console.Workflow; using Composite.Data.Types; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteAggregationTypeWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeleteAggregationTypeWorkflow() { InitializeComponent(); } private DataTypeDescriptor GetDataTypeDescriptor() { Type type = TypeManager.GetType(this.Payload); Guid guid = type.GetImmutableTypeId(); return DataMetaDataFacade.GetDataTypeDescriptor(guid); } private void DoesTypeExists(object sender, System.Workflow.Activities.ConditionalEventArgs e) { e.Result = GetDataTypeDescriptor() != null; } private void TypeIsReferenced(object sender, System.Workflow.Activities.ConditionalEventArgs e) { var descriptor = GetDataTypeDescriptor(); Type interfaceType = descriptor.GetInterfaceType(); // NOTE: Type could reference to itself e.Result = interfaceType.GetRefereeTypes().Where(type => type != interfaceType).Any(); } private void IsUsedByPageType(object sender, System.Workflow.Activities.ConditionalEventArgs e) { DataTypeDescriptor dataTypeDescriptor = GetDataTypeDescriptor(); bool isUsed = DataFacade.GetData<IPageTypeDataFolderTypeLink>().Where(f => f.DataTypeId == dataTypeDescriptor.DataTypeId).Any(); if (isUsed) { Type interfaceType = GetDataTypeDescriptor().GetInterfaceType(); this.ShowMessage(DialogType.Warning, GetLocalizedText("DeleteAggregationTypeWorkflow.ErrorTitle"), GetLocalizedText("DeleteAggregationTypeWorkflow.IsUsedByPageType").FormatWith(interfaceType.FullName)); } e.Result = isUsed; } private void codeActivity_ShowTypeIsReferencedWarning(object sender, EventArgs e) { Type interfaceType = GetDataTypeDescriptor().GetInterfaceType(); this.ShowMessage(DialogType.Warning, GetLocalizedText("DeleteCompositionTypeWorkflow.ErrorTitle"), GetLocalizedText("DeleteCompositionTypeWorkflow.TypeIsReferenced").FormatWith(interfaceType.FullName)); return; } private static string GetLocalizedText(string key) { return StringResourceSystemFacade.GetString("Composite.Plugins.GeneratedDataTypesElementProvider", key); } private void initializeStateCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { DataTypeDescriptor dataTypeDescriptor = GetDataTypeDescriptor(); string interfaceName = StringExtensionMethods.CreateNamespace(dataTypeDescriptor.Namespace, dataTypeDescriptor.Name, '.'); interfaceName = string.Format("{0} {1}?", StringResourceSystemFacade.GetString("Composite.Plugins.GeneratedDataTypesElementProvider", "DeleteAggregationTypeWorkflow.Text"), interfaceName); this.Bindings.Add("InterfaceName", interfaceName); } private void finalizeStateCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { DataTypeDescriptor dataTypeDescriptor = GetDataTypeDescriptor(); string errorMessage; if (!GeneratedTypesFacade.CanDeleteType(dataTypeDescriptor, out errorMessage)) { this.ShowMessage(DialogType.Warning, "${Composite.Plugins.GeneratedDataTypesElementProvider, DeleteCompositionTypeWorkflow.ErrorTitle}", errorMessage); return; } GeneratedTypesFacade.DeleteType(dataTypeDescriptor); GeneratedDataTypesElementProviderRootEntityToken entityToken = new GeneratedDataTypesElementProviderRootEntityToken(this.EntityToken.Source, GeneratedDataTypesElementProviderRootEntityToken.PageDataFolderTypeFolderId); SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(entityToken); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/DeleteAggregationTypeWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { partial class DeleteAggregationTypeWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.initializeStateCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.caShowMessageBox = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finalizeStateCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.ifTypeIsReferenced = new System.Workflow.Activities.IfElseActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "step1StateActivity"; // // initializeStateCodeActivity_Initialize // this.initializeStateCodeActivity_Initialize.Name = "initializeStateCodeActivity_Initialize"; this.initializeStateCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeStateCodeActivity_Initialize_ExecuteCode); // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.initializeStateCodeActivity_Initialize); this.ifElseBranchActivity4.Activities.Add(this.setStateActivity4); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.setStateActivity7); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsUsedByPageType); this.ifElseBranchActivity3.Condition = codecondition1; this.ifElseBranchActivity3.Description = "IsUsedByPageType"; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity4); this.ifElseActivity1.Name = "ifElseActivity1"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // caShowMessageBox // this.caShowMessageBox.Name = "caShowMessageBox"; this.caShowMessageBox.ExecuteCode += new System.EventHandler(this.codeActivity_ShowTypeIsReferencedWarning); // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.ifElseActivity1); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.caShowMessageBox); this.ifElseBranchActivity1.Activities.Add(this.setStateActivity6); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.TypeIsReferenced); this.ifElseBranchActivity1.Condition = codecondition2; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // finalizeStateCodeActivity_Finalize // this.finalizeStateCodeActivity_Finalize.Name = "finalizeStateCodeActivity_Finalize"; this.finalizeStateCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeStateCodeActivity_Finalize_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "\\Administrative\\DeleteAggregationTypeStep1.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // ifTypeIsReferenced // this.ifTypeIsReferenced.Activities.Add(this.ifElseBranchActivity1); this.ifTypeIsReferenced.Activities.Add(this.ifElseBranchActivity2); this.ifTypeIsReferenced.Name = "ifTypeIsReferenced"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.finalizeStateCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity5); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity2); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity3); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.confirmDialogFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.ifTypeIsReferenced); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // DeleteAggregationTypeWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "DeleteAggregationTypeWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity4; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateInitializationActivity step1StateInitializationActivity; private CodeActivity initializeStateCodeActivity_Initialize; private SetStateActivity setStateActivity5; private CodeActivity finalizeStateCodeActivity_Finalize; private C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifTypeIsReferenced; private SetStateActivity setStateActivity6; private CodeActivity caShowMessageBox; private SetStateActivity setStateActivity7; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElseActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/DeleteAggregationTypeWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1221; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="DeleteAggregationTypeWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="612; 544" Location="334; 148"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="ifTypeIsReferenced" Size="592; 463" Location="344; 210"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 363" Location="363; 281"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="caShowMessageBox" Size="130; 41" Location="373; 343" /> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="373; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="381; 363" Location="536; 281"> <IfElseBranchDesigner.Designers> <IfElseDesigner Name="ifElseActivity1" Size="361; 282" Location="546; 343"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity3" Size="150; 182" Location="565; 414"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity7" Size="130; 41" Location="575; 506" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity4" Size="150; 182" Location="738; 414"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="initializeStateCodeActivity_Initialize" Size="130; 41" Location="748; 476" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="748; 536" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="211; 102" AutoSizeMargin="16; 24" AutoSize="False" Location="239; 333" Name="step1StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1StateInitializationActivity" Size="150; 122" Location="247; 364"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="confirmDialogFormActivity1" Size="130; 41" Location="257; 426" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Finish" Size="150; 182" Location="247; 388"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="257; 450" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="257; 510" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Cancel" Size="150; 182" Location="247; 412"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="257; 474" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="257; 534" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="538; 482" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 242" Location="546; 513"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="closeCurrentViewActivity1" Size="130; 41" Location="556; 575" /> <CodeDesigner Name="finalizeStateCodeActivity_Finalize" Size="130; 41" Location="556; 635" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="556; 695" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="DeleteAggregationTypeWorkflow" TargetConnectionIndex="0" SourceStateName="DeleteAggregationTypeWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity6" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="1058" Y="179" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity4" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="344" Y="179" /> <ns0:Point X="344" Y="333" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity3" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="442" Y="398" /> <ns0:Point X="640" Y="398" /> <ns0:Point X="640" Y="482" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity2" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="446" Y="422" /> <ns0:Point X="1058" Y="422" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity5" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="739" Y="523" /> <ns0:Point X="1058" Y="523" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/DeleteCompositionTypeWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Transactions; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; using Composite.Data.Transactions; using Composite.Core.Types; using Composite.C1Console.Workflow; using System.Workflow.Activities; using Composite.Data.Types; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteCompositionTypeWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeleteCompositionTypeWorkflow() { InitializeComponent(); } private DataTypeDescriptor GetDataTypeDescriptor() { Type type = TypeManager.GetType(this.Payload); Guid guid = type.GetImmutableTypeId(); return DataMetaDataFacade.GetDataTypeDescriptor(guid); } private void DoesTypeExists(object sender, ConditionalEventArgs e) { e.Result = GetDataTypeDescriptor() != null; } private void IsUsedByPageType(object sender, ConditionalEventArgs e) { DataTypeDescriptor dataTypeDescriptor = GetDataTypeDescriptor(); bool isUsed = DataFacade.GetData<IPageTypeMetaDataTypeLink>().Where(f => f.DataTypeId == dataTypeDescriptor.DataTypeId).Any(); if (isUsed) { Type interfaceType = GetDataTypeDescriptor().GetInterfaceType(); this.ShowMessage(DialogType.Warning, GetLocalizedText("DeleteCompositionTypeWorkflow.ErrorTitle"), GetLocalizedText("DeleteCompositionTypeWorkflow.IsUsedByPageType").FormatWith(interfaceType.FullName)); } e.Result = isUsed; } private void initializeStateCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { DataTypeDescriptor dataTypeDescriptor = GetDataTypeDescriptor(); string interfaceName = StringExtensionMethods.CreateNamespace(dataTypeDescriptor.Namespace, dataTypeDescriptor.Name, '.'); interfaceName = string.Format("{0} {1}?", StringResourceSystemFacade.GetString("Composite.Plugins.GeneratedDataTypesElementProvider", "DeleteCompositionTypeWorkflow.Text"), interfaceName); this.Bindings.Add("InterfaceName", interfaceName); } private void TypeIsReferenced(object sender, System.Workflow.Activities.ConditionalEventArgs e) { var descriptor = GetDataTypeDescriptor(); Type interfaceType = descriptor.GetInterfaceType(); // NOTE: Type could reference to itself e.Result = interfaceType.GetRefereeTypes().Where(type => type != interfaceType).Any(); } private void codeActivity_ShowTypeIsReferencedWarning(object sender, EventArgs e) { Type interfaceType = GetDataTypeDescriptor().GetInterfaceType(); this.ShowMessage(DialogType.Warning, GetLocalizedText("DeleteCompositionTypeWorkflow.ErrorTitle"), GetLocalizedText("DeleteCompositionTypeWorkflow.TypeIsReferenced").FormatWith(interfaceType.FullName)); return; } private static string GetLocalizedText(string key) { return StringResourceSystemFacade.GetString("Composite.Plugins.GeneratedDataTypesElementProvider", key); } private void finalizeStateCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { DataTypeDescriptor dataTypeDescriptor = GetDataTypeDescriptor(); string errorMessage; if (!GeneratedTypesFacade.CanDeleteType(dataTypeDescriptor, out errorMessage)) { this.ShowMessage(DialogType.Warning, "${Composite.Plugins.GeneratedDataTypesElementProvider, DeleteCompositionTypeWorkflow.ErrorTitle}", errorMessage); return; } using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { PageMetaDataFacade.RemoveAllDefinitions(dataTypeDescriptor.DataTypeId, false); transactionScope.Complete(); } GeneratedTypesFacade.DeleteType(dataTypeDescriptor); GeneratedDataTypesElementProviderRootEntityToken entityToken = new GeneratedDataTypesElementProviderRootEntityToken(this.EntityToken.Source, GeneratedDataTypesElementProviderRootEntityToken.PageMetaDataTypeFolderId); SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(entityToken); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/DeleteCompositionTypeWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { partial class DeleteCompositionTypeWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.initializeStateCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.caShowWarning = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finalizeStateCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.ifTypeIsReferenced = new System.Workflow.Activities.IfElseActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "step1StateActivity"; // // initializeStateCodeActivity_Initialize // this.initializeStateCodeActivity_Initialize.Name = "initializeStateCodeActivity_Initialize"; this.initializeStateCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeStateCodeActivity_Initialize_ExecuteCode); // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.initializeStateCodeActivity_Initialize); this.ifElseBranchActivity4.Activities.Add(this.setStateActivity4); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.setStateActivity7); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsUsedByPageType); this.ifElseBranchActivity3.Condition = codecondition1; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity4); this.ifElseActivity1.Name = "ifElseActivity1"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // caShowWarning // this.caShowWarning.Name = "caShowWarning"; this.caShowWarning.ExecuteCode += new System.EventHandler(this.codeActivity_ShowTypeIsReferencedWarning); // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.ifElseActivity1); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.caShowWarning); this.ifElseBranchActivity1.Activities.Add(this.setStateActivity6); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.TypeIsReferenced); this.ifElseBranchActivity1.Condition = codecondition2; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // finalizeStateCodeActivity_Finalize // this.finalizeStateCodeActivity_Finalize.Name = "finalizeStateCodeActivity_Finalize"; this.finalizeStateCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeStateCodeActivity_Finalize_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "\\Administrative\\DeleteCompositionTypeStep1.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // ifTypeIsReferenced // this.ifTypeIsReferenced.Activities.Add(this.ifElseBranchActivity1); this.ifTypeIsReferenced.Activities.Add(this.ifElseBranchActivity2); this.ifTypeIsReferenced.Name = "ifTypeIsReferenced"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.finalizeStateCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity5); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity2); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity3); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.confirmDialogFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.ifTypeIsReferenced); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // DeleteCompositionTypeWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "DeleteCompositionTypeWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity4; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateInitializationActivity step1StateInitializationActivity; private CodeActivity initializeStateCodeActivity_Initialize; private SetStateActivity setStateActivity5; private CodeActivity finalizeStateCodeActivity_Finalize; private C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity6; private CodeActivity caShowWarning; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifTypeIsReferenced; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElseActivity1; private SetStateActivity setStateActivity7; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/DeleteCompositionTypeWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1221; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="DeleteCompositionTypeWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="612; 544" Location="334; 148"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="ifTypeIsReferenced" Size="592; 463" Location="344; 210"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 363" Location="363; 281"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="caShowWarning" Size="130; 41" Location="373; 343" /> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="373; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="381; 363" Location="536; 281"> <IfElseBranchDesigner.Designers> <IfElseDesigner Name="ifElseActivity1" Size="361; 282" Location="546; 343"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity3" Size="150; 182" Location="565; 414"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity7" Size="130; 41" Location="575; 506" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity4" Size="150; 182" Location="738; 414"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="initializeStateCodeActivity_Initialize" Size="130; 41" Location="748; 476" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="748; 536" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="211; 102" AutoSizeMargin="16; 24" AutoSize="False" Location="239; 333" Name="step1StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1StateInitializationActivity" Size="150; 122" Location="247; 364"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="confirmDialogFormActivity1" Size="130; 41" Location="257; 426" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Finish" Size="150; 182" Location="247; 388"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="257; 450" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="257; 510" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Cancel" Size="150; 182" Location="247; 412"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="257; 474" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="257; 534" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="538; 482" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 242" Location="546; 513"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="closeCurrentViewActivity1" Size="130; 41" Location="556; 575" /> <CodeDesigner Name="finalizeStateCodeActivity_Finalize" Size="130; 41" Location="556; 635" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="556; 695" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="DeleteCompositionTypeWorkflow" TargetConnectionIndex="0" SourceStateName="DeleteCompositionTypeWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity6" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="1058" Y="179" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity4" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="344" Y="179" /> <ns0:Point X="344" Y="333" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity3" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="442" Y="398" /> <ns0:Point X="640" Y="398" /> <ns0:Point X="640" Y="482" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity2" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="446" Y="422" /> <ns0:Point X="1058" Y="422" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity5" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="739" Y="523" /> <ns0:Point X="1058" Y="523" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/DeleteDataWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.DynamicTypes.Foundation; using Composite.Data.ProcessControlled; using Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper; using Composite.Core.ResourceSystem; using Composite.C1Console.Workflow; using Composite.Core.Extensions; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteDataWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeleteDataWorkflow() { InitializeComponent(); } private void HasDataReferences(object sender, ConditionalEventArgs e) { IData data = ((DataEntityToken)this.EntityToken).Data; var brokenReferences = new List<IData>(); var references = DataReferenceFacade.GetNotOptionalReferences(data); foreach (var reference in references) { DataSourceId referenceDataSourceId = reference.DataSourceId; if (brokenReferences.Any(brokenRef => brokenRef.DataSourceId == referenceDataSourceId)) { continue; } brokenReferences.Add(reference); } e.Result = brokenReferences.Count > 0; if (brokenReferences.Count == 0) { return; } Bindings.Add("ReferencedData", DataReferenceFacade.GetBrokenReferencesReport(brokenReferences)); } private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { DeleteTreeRefresher deleteTreeRefresher = this.CreateDeleteTreeRefresher(this.EntityToken); IData data = ((DataEntityToken)this.EntityToken).Data; if (DataFacade.WillDeleteSucceed(data)) { ProcessControllerFacade.FullDelete(data); deleteTreeRefresher.PostRefreshMesseges(true); } else { this.ShowMessage( DialogType.Error, StringResourceSystemFacade.GetString("Composite.Plugins.GeneratedDataTypesElementProvider", "CascadeDeleteErrorTitle"), StringResourceSystemFacade.GetString("Composite.Plugins.GeneratedDataTypesElementProvider", "CascadeDeleteErrorMessage") ); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/DeleteDataWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { partial class DeleteDataWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.confirmDialogFormActivity2 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.branchHasNoRelatedData = new System.Workflow.Activities.IfElseBranchActivity(); this.branchHasRelatedData = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.ifElseHasRelatedData = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.eventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.eventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1SventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.checkRelatedDataStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.finializeStateActivity = new System.Workflow.Activities.StateActivity(); this.initialstateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "step1StateActivity"; // // confirmDialogFormActivity2 // this.confirmDialogFormActivity2.ContainerLabel = null; this.confirmDialogFormActivity2.FormDefinitionFileName = "/Administrative/DeleteGeneratedDataStep2.xml"; this.confirmDialogFormActivity2.Name = "confirmDialogFormActivity2"; // // branchHasNoRelatedData // this.branchHasNoRelatedData.Activities.Add(this.setStateActivity6); this.branchHasNoRelatedData.Name = "branchHasNoRelatedData"; // // branchHasRelatedData // this.branchHasRelatedData.Activities.Add(this.confirmDialogFormActivity2); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.HasDataReferences); this.branchHasRelatedData.Condition = codecondition1; this.branchHasRelatedData.Name = "branchHasRelatedData"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finializeStateActivity"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // ifElseHasRelatedData // this.ifElseHasRelatedData.Activities.Add(this.branchHasRelatedData); this.ifElseHasRelatedData.Activities.Add(this.branchHasNoRelatedData); this.ifElseHasRelatedData.Name = "ifElseHasRelatedData"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finializeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "/Administrative/DeleteGeneratedDataStep1.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "checkRelatedDataStateActivity"; // // eventDrivenActivity_Finish // this.eventDrivenActivity_Finish.Activities.Add(this.cancelHandleExternalEventActivity3); this.eventDrivenActivity_Finish.Activities.Add(this.setStateActivity8); this.eventDrivenActivity_Finish.Name = "eventDrivenActivity_Finish"; // // eventDrivenActivity_Cancel // this.eventDrivenActivity_Cancel.Activities.Add(this.finishHandleExternalEventActivity2); this.eventDrivenActivity_Cancel.Activities.Add(this.setStateActivity7); this.eventDrivenActivity_Cancel.Name = "eventDrivenActivity_Cancel"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.ifElseHasRelatedData); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity4); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1SventDrivenActivity_Finish // this.step1SventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1SventDrivenActivity_Finish.Activities.Add(this.setStateActivity5); this.step1SventDrivenActivity_Finish.Name = "step1SventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.confirmDialogFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.setStateActivity3); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // checkRelatedDataStateActivity // this.checkRelatedDataStateActivity.Activities.Add(this.stateInitializationActivity1); this.checkRelatedDataStateActivity.Activities.Add(this.eventDrivenActivity_Cancel); this.checkRelatedDataStateActivity.Activities.Add(this.eventDrivenActivity_Finish); this.checkRelatedDataStateActivity.Name = "checkRelatedDataStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1SventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity1); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // finializeStateActivity // this.finializeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finializeStateActivity.Name = "finializeStateActivity"; // // initialstateActivity // this.initialstateActivity.Activities.Add(this.initialStateInitializationActivity); this.initialstateActivity.Name = "initialstateActivity"; // // DeleteDataWorkflow // this.Activities.Add(this.initialstateActivity); this.Activities.Add(this.finializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelEventDrivenActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.checkRelatedDataStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialstateActivity"; this.Name = "DeleteDataWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initialStateInitializationActivity; private EventDrivenActivity cancelEventDrivenActivity; private StateActivity finalStateActivity; private StateActivity finializeStateActivity; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity1; private StateInitializationActivity finalizeStateInitializationActivity; private CodeActivity finalizeCodeActivity; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private StateInitializationActivity step1StateInitializationActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity3; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1SventDrivenActivity_Finish; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity6; private IfElseBranchActivity branchHasNoRelatedData; private IfElseBranchActivity branchHasRelatedData; private IfElseActivity ifElseHasRelatedData; private StateInitializationActivity stateInitializationActivity1; private StateActivity checkRelatedDataStateActivity; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity2; private SetStateActivity setStateActivity8; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private SetStateActivity setStateActivity7; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private EventDrivenActivity eventDrivenActivity_Finish; private EventDrivenActivity eventDrivenActivity_Cancel; private StateActivity initialstateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/DeleteDataWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="DeleteDataWorkflow" Location="30; 30" Size="1202; 996" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="DeleteDataWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="DeleteDataWorkflow" EventHandlerName="cancelEventDrivenActivity"> <StateDesignerConnector.Segments> <ns0:Point X="202" Y="71" /> <ns0:Point X="1051" Y="71" /> <ns0:Point X="1051" Y="777" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="checkRelatedDataStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="initialstateActivity" SourceConnectionEdge="Right" TargetActivity="checkRelatedDataStateActivity" SourceActivity="initialstateActivity" EventHandlerName="initialStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="146" /> <ns0:Point X="292" Y="146" /> <ns0:Point X="292" Y="273" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="finializeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finializeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="642" Y="655" /> <ns0:Point X="1051" Y="655" /> <ns0:Point X="1051" Y="777" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finializeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finializeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1SventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="824" Y="475" /> <ns0:Point X="839" Y="475" /> <ns0:Point X="839" Y="602" /> <ns0:Point X="543" Y="602" /> <ns0:Point X="543" Y="614" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="828" Y="499" /> <ns0:Point X="1051" Y="499" /> <ns0:Point X="1051" Y="777" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="checkRelatedDataStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="checkRelatedDataStateActivity" EventHandlerName="stateInitializationActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="372" Y="314" /> <ns0:Point X="726" Y="314" /> <ns0:Point X="726" Y="410" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finializeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="checkRelatedDataStateActivity" SourceConnectionEdge="Right" TargetActivity="finializeStateActivity" SourceActivity="checkRelatedDataStateActivity" EventHandlerName="eventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="380" Y="338" /> <ns0:Point X="543" Y="338" /> <ns0:Point X="543" Y="614" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity8" SourceStateName="checkRelatedDataStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="checkRelatedDataStateActivity" EventHandlerName="eventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="376" Y="362" /> <ns0:Point X="1051" Y="362" /> <ns0:Point X="1051" Y="777" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initialstateActivity" Location="63; 105" Size="197; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="initialStateInitializationActivity" Location="71; 136"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="81; 198" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finializeStateActivity" Location="441; 614" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="finalizeStateInitializationActivity" Location="449; 645"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="459; 707" /> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity" Location="459; 767" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="459; 827" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 777" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="cancelEventDrivenActivity" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="step1StateActivity" Location="621; 410" Size="211; 118" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="629; 441"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="confirmDialogFormActivity1" Location="639; 503" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1SventDrivenActivity_Finish" Location="629; 465"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="639; 527" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="639; 587" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="629; 489"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="639; 551" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="639; 611" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="checkRelatedDataStateActivity" Location="201; 273" Size="183; 102" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 303" Name="stateInitializationActivity1" Location="440; 148"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="361; 222" Name="ifElseHasRelatedData" Location="450; 210"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="branchHasRelatedData" Location="469; 281"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="confirmDialogFormActivity2" Location="479; 343" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="branchHasNoRelatedData" Location="642; 281"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="652; 343" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_Cancel" Location="432; 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity2" Location="442; 221" /> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="442; 281" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_Finish" Location="432; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity3" Location="442; 245" /> <SetStateDesigner Size="130; 41" Name="setStateActivity8" Location="442; 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/DeleteInterfaceTypeWorkflow.cs ================================================ using System; using System.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; using Composite.Core.Types; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteInterfaceTypeWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeleteInterfaceTypeWorkflow() { InitializeComponent(); } private DataTypeDescriptor GetDataTypeDescriptor() { GeneratedDataTypesElementProviderTypeEntityToken entityToken = (GeneratedDataTypesElementProviderTypeEntityToken)this.EntityToken; Type type = TypeManager.GetType(entityToken.SerializedTypeName); Guid guid = type.GetImmutableTypeId(); return DataMetaDataFacade.GetDataTypeDescriptor(guid); } private void DoesTypeExists(object sender, System.Workflow.Activities.ConditionalEventArgs e) { e.Result = GetDataTypeDescriptor() != null; } private void TypeIsReferenced(object sender, System.Workflow.Activities.ConditionalEventArgs e) { var descriptor = GetDataTypeDescriptor(); Type interfaceType = descriptor.GetInterfaceType(); // NOTE: Type could reference to itself e.Result = interfaceType.GetRefereeTypes().Where(type => type != interfaceType).Any(); } private void initialStateCodeActivity_ExecuteCode(object sender, EventArgs e) { DataTypeDescriptor dataTypeDescriptor = GetDataTypeDescriptor(); string interfaceName = StringExtensionMethods.CreateNamespace(dataTypeDescriptor.Namespace, dataTypeDescriptor.Name, '.'); interfaceName = string.Format("{0} {1}?", StringResourceSystemFacade.GetString("Composite.Plugins.GeneratedDataTypesElementProvider", "DeleteGeneratedInterfaceStep1.Text"), interfaceName); this.Bindings.Add("InterfaceType", interfaceName); } private void codeActivity_ShowTypeIsReferencedWarning(object sender, EventArgs e) { Type interfaceType = GetDataTypeDescriptor().GetInterfaceType(); this.ShowMessage(DialogType.Warning, GetLocalizedText("DeleteCompositionTypeWorkflow.ErrorTitle"), GetLocalizedText("DeleteCompositionTypeWorkflow.TypeIsReferenced").FormatWith(interfaceType.FullName)); return; } private void codeActivity_finalize_ExecuteCode(object sender, EventArgs e) { DataTypeDescriptor dataTypeDescriptor = GetDataTypeDescriptor(); string errorMessage; if (!GeneratedTypesFacade.CanDeleteType(dataTypeDescriptor, out errorMessage)) { this.ShowMessage(DialogType.Warning, "${Composite.Plugins.GeneratedDataTypesElementProvider, DeleteCompositionTypeWorkflow.ErrorTitle}", errorMessage); return; } GeneratedTypesFacade.DeleteType(dataTypeDescriptor); GeneratedDataTypesElementProviderRootEntityToken entityToken = new GeneratedDataTypesElementProviderRootEntityToken(this.EntityToken.Source, GeneratedDataTypesElementProviderRootEntityToken.GlobalDataTypeFolderId); ParentTreeRefresher parentTreeRefresher = this.CreateParentTreeRefresher(); parentTreeRefresher.PostRefreshMesseges(entityToken, 2); } private static string GetLocalizedText(string key) { return StringResourceSystemFacade.GetString("Composite.Plugins.GeneratedDataTypesElementProvider", key); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/DeleteInterfaceTypeWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { partial class DeleteInterfaceTypeWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.initialStateCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.caShowWarning = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity_finalize = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.ifTypeIsReferenced = new System.Workflow.Activities.IfElseActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.initialStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "step1StateActivity"; // // initialStateCodeActivity // this.initialStateCodeActivity.Name = "initialStateCodeActivity"; this.initialStateCodeActivity.ExecuteCode += new System.EventHandler(this.initialStateCodeActivity_ExecuteCode); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // caShowWarning // this.caShowWarning.Name = "caShowWarning"; this.caShowWarning.ExecuteCode += new System.EventHandler(this.codeActivity_ShowTypeIsReferencedWarning); // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.initialStateCodeActivity); this.ifElseBranchActivity2.Activities.Add(this.setStateActivity3); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.caShowWarning); this.ifElseBranchActivity1.Activities.Add(this.setStateActivity6); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.TypeIsReferenced); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "/Administrative/DeleteGeneratedInteraceStep1.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // codeActivity_finalize // this.codeActivity_finalize.Name = "codeActivity_finalize"; this.codeActivity_finalize.ExecuteCode += new System.EventHandler(this.codeActivity_finalize_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // ifTypeIsReferenced // this.ifTypeIsReferenced.Activities.Add(this.ifElseBranchActivity1); this.ifTypeIsReferenced.Activities.Add(this.ifElseBranchActivity2); this.ifTypeIsReferenced.Name = "ifTypeIsReferenced"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity4); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity5); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.confirmDialogFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.codeActivity_finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.ifTypeIsReferenced); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity1); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // initialStateActivity // this.initialStateActivity.Activities.Add(this.initialStateInitializationActivity); this.initialStateActivity.Name = "initialStateActivity"; // // DeleteInterfaceTypeWorkflow // this.Activities.Add(this.initialStateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelEventDrivenActivity); this.Activities.Add(this.step1StateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialStateActivity"; this.Name = "DeleteInterfaceTypeWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity1; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity finalizeStateInitializationActivity; private StateInitializationActivity initialStateInitializationActivity; private EventDrivenActivity cancelEventDrivenActivity; private StateActivity finalStateActivity; private StateActivity finalizeStateActivity; private CodeActivity initialStateCodeActivity; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity3; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateInitializationActivity step1StateInitializationActivity; private StateActivity step1StateActivity; private CodeActivity codeActivity_finalize; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifTypeIsReferenced; private SetStateActivity setStateActivity6; private CodeActivity caShowWarning; private StateActivity initialStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/DeleteInterfaceTypeWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="DeleteInterfaceTypeWorkflow" Location="30; 30" Size="1161; 817" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="DeleteInterfaceTypeWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="DeleteInterfaceTypeWorkflow" EventHandlerName="cancelEventDrivenActivity"> <StateDesignerConnector.Segments> <ns0:Point X="202" Y="71" /> <ns0:Point X="908" Y="71" /> <ns0:Point X="908" Y="737" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="initialStateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="initialStateActivity" EventHandlerName="initialStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="293" Y="173" /> <ns0:Point X="625" Y="173" /> <ns0:Point X="625" Y="540" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="initialStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initialStateActivity" EventHandlerName="initialStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="293" Y="173" /> <ns0:Point X="388" Y="173" /> <ns0:Point X="388" Y="336" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="724" Y="581" /> <ns0:Point X="908" Y="581" /> <ns0:Point X="908" Y="737" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="486" Y="401" /> <ns0:Point X="625" Y="401" /> <ns0:Point X="625" Y="540" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="490" Y="425" /> <ns0:Point X="908" Y="425" /> <ns0:Point X="908" Y="737" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initialStateActivity" Location="100; 132" Size="197; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 363" Name="initialStateInitializationActivity" Location="420; 148"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="361; 282" Name="ifTypeIsReferenced" Location="430; 210"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity1" Location="449; 281"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="caShowWarning" Location="459; 343" /> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="459; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity2" Location="622; 281"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="initialStateCodeActivity" Location="632; 343" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="632; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="523; 540" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="finalizeStateInitializationActivity" Location="531; 571"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="541; 633" /> <CodeDesigner Size="130; 41" Name="codeActivity_finalize" Location="541; 693" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="541; 753" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="828; 737" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="cancelEventDrivenActivity" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="step1StateActivity" Location="283; 336" Size="211; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="291; 367"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="confirmDialogFormActivity1" Location="301; 429" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Finish" Location="291; 391"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="301; 453" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="301; 513" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="291; 415"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="301; 477" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="301; 537" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/DisableTypeLocalizationWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Transactions; using System.Workflow.Activities; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; using Composite.Data.ProcessControlled; using Composite.Core.ResourceSystem; using Composite.C1Console.Security; using Composite.Data.Transactions; using Composite.Core.Types; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DisableTypeLocalizationWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DisableTypeLocalizationWorkflow() { InitializeComponent(); } private DataTypeDescriptor GetDataTypeDescriptor() { Type type; if ((this.EntityToken is Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper.AssociatedDataElementProviderHelperEntityToken)) { Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper.AssociatedDataElementProviderHelperEntityToken castedEntityToken = this.EntityToken as Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper.AssociatedDataElementProviderHelperEntityToken; type = TypeManager.GetType(castedEntityToken.Payload); } else { GeneratedDataTypesElementProviderTypeEntityToken entityToken = (GeneratedDataTypesElementProviderTypeEntityToken)this.EntityToken; type = TypeManager.GetType(entityToken.SerializedTypeName); } Guid guid = type.GetImmutableTypeId(); return DataMetaDataFacade.GetDataTypeDescriptor(guid); } private void DataExists(object sender, ConditionalEventArgs e) { DataTypeDescriptor dataTypeDescriptor = GetDataTypeDescriptor(); Type interfaceType = TypeManager.GetType(dataTypeDescriptor.TypeManagerTypeName); foreach (CultureInfo cultureInfo in DataLocalizationFacade.ActiveLocalizationCultures) { using (new DataScope(cultureInfo)) { e.Result = DataFacade.GetData(interfaceType).ToDataEnumerable().Any(); if (e.Result) { return; } } } } private void step1CodeActivity_InitializeBindings_ExecuteCode(object sender, EventArgs e) { DataTypeDescriptor dataTypeDescriptor = GetDataTypeDescriptor(); Type interfaceType = TypeManager.GetType(dataTypeDescriptor.TypeManagerTypeName); List<CultureInfo> culturesWithData = new List<CultureInfo>(); foreach (CultureInfo cultureInfo in DataLocalizationFacade.ActiveLocalizationCultures) { using (DataScope localeScope = new DataScope(cultureInfo)) { bool dataExists = DataFacade.GetData(interfaceType).ToDataEnumerable().Any(); if (dataExists) { culturesWithData.Add(cultureInfo); } } } Dictionary<string, string> culturesDictionary = culturesWithData.ToDictionary(f => f.Name, DataLocalizationFacade.GetCultureTitle); this.Bindings.Add("CultureName", culturesDictionary.First().Key); this.Bindings.Add("CultureNameList", culturesDictionary); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { DataTypeDescriptor dataTypeDescriptor = GetDataTypeDescriptor(); DataTypeDescriptor newDataTypeDescriptor = dataTypeDescriptor.Clone(); newDataTypeDescriptor.RemoveSuperInterface(typeof(ILocalizedControlled)); UpdateDataTypeDescriptor updateDataTypeDescriptor = new UpdateDataTypeDescriptor(dataTypeDescriptor, newDataTypeDescriptor, false); if (this.BindingExist("CultureName")) { string cultureName = this.GetBinding<string>("CultureName"); CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture(cultureName); updateDataTypeDescriptor.LocaleToCopyFrom = cultureInfo; } GeneratedTypesFacade.UpdateType(updateDataTypeDescriptor); this.CloseCurrentView(); this.CollapseAndRefresh(); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/DisableTypeLocalizationWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { partial class DisableTypeLocalizationWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step2WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.nextHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.step1WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.step1CodeActivity_InitializeBindings = new System.Workflow.Activities.CodeActivity(); this.initializeIfElseActivity_DataExists = new System.Workflow.Activities.IfElseActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step2EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step2EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step2StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step2StateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "step2StateActivity"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "step1StateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity8); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity6); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DataExists); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // step2WizardFormActivity // this.step2WizardFormActivity.ContainerLabel = null; this.step2WizardFormActivity.FormDefinitionFileName = "/Administrative/DisableTypeLocalizationStep2.xml"; this.step2WizardFormActivity.Name = "step2WizardFormActivity"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "step2StateActivity"; // // nextHandleExternalEventActivity1 // this.nextHandleExternalEventActivity1.EventName = "Next"; this.nextHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity1.Name = "nextHandleExternalEventActivity1"; // // step1WizardFormActivity // this.step1WizardFormActivity.ContainerLabel = null; this.step1WizardFormActivity.FormDefinitionFileName = "/Administrative/DisableTypeLocalizationStep1.xml"; this.step1WizardFormActivity.Name = "step1WizardFormActivity"; // // step1CodeActivity_InitializeBindings // this.step1CodeActivity_InitializeBindings.Name = "step1CodeActivity_InitializeBindings"; this.step1CodeActivity_InitializeBindings.ExecuteCode += new System.EventHandler(this.step1CodeActivity_InitializeBindings_ExecuteCode); // // initializeIfElseActivity_DataExists // this.initializeIfElseActivity_DataExists.Activities.Add(this.ifElseBranchActivity1); this.initializeIfElseActivity_DataExists.Activities.Add(this.ifElseBranchActivity2); this.initializeIfElseActivity_DataExists.Name = "initializeIfElseActivity_DataExists"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity7); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step2EventDrivenActivity_Cancel // this.step2EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.step2EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity2); this.step2EventDrivenActivity_Cancel.Name = "step2EventDrivenActivity_Cancel"; // // step2EventDrivenActivity_Finish // this.step2EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step2EventDrivenActivity_Finish.Activities.Add(this.setStateActivity4); this.step2EventDrivenActivity_Finish.Name = "step2EventDrivenActivity_Finish"; // // step2StateInitializationActivity // this.step2StateInitializationActivity.Activities.Add(this.step2WizardFormActivity); this.step2StateInitializationActivity.Name = "step2StateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity3); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Next // this.step1EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity1); this.step1EventDrivenActivity_Next.Activities.Add(this.setStateActivity5); this.step1EventDrivenActivity_Next.Name = "step1EventDrivenActivity_Next"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1CodeActivity_InitializeBindings); this.step1StateInitializationActivity.Activities.Add(this.step1WizardFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeIfElseActivity_DataExists); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step2StateActivity // this.step2StateActivity.Activities.Add(this.step2StateInitializationActivity); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Finish); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Cancel); this.step2StateActivity.Name = "step2StateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Next); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // DisableTypeLocalizationWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.step2StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "DisableTypeLocalizationWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private CodeActivity finalizeCodeActivity_Finalize; private SetStateActivity setStateActivity2; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity1; private SetStateActivity setStateActivity6; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step2EventDrivenActivity_Cancel; private EventDrivenActivity step2EventDrivenActivity_Finish; private StateInitializationActivity step2StateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Next; private StateInitializationActivity step1StateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity step2StateActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity7; private Composite.C1Console.Workflow.Activities.WizardFormActivity step1WizardFormActivity; private CodeActivity step1CodeActivity_InitializeBindings; private Composite.C1Console.Workflow.Activities.WizardFormActivity step2WizardFormActivity; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity initializeIfElseActivity_DataExists; private SetStateActivity setStateActivity8; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/DisableTypeLocalizationWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="DisableTypeLocalizationWorkflow" Location="30; 30" Size="1146; 980" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="DisableTypeLocalizationWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="DisableTypeLocalizationWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="352" Y="179" /> <ns0:Point X="352" Y="295" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step2StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity8" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step2StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="539" Y="179" /> <ns0:Point X="539" Y="432" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step2StateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="step2StateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="444" Y="360" /> <ns0:Point X="539" Y="360" /> <ns0:Point X="539" Y="432" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="454" Y="384" /> <ns0:Point X="1058" Y="384" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step2StateActivity" EventHandlerName="step2EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="637" Y="497" /> <ns0:Point X="783" Y="497" /> <ns0:Point X="783" Y="608" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step2StateActivity" EventHandlerName="step2EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="641" Y="521" /> <ns0:Point X="1058" Y="521" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="882" Y="649" /> <ns0:Point X="1058" Y="649" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 303" Name="initializeStateInitializationActivity" Location="412; 148"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="361; 222" Name="initializeIfElseActivity_DataExists" Location="422; 210"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity1" Location="441; 281"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="451; 343" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity2" Location="614; 281"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity8" Location="624; 343" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="step1StateActivity" Location="247; 295" Size="211; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="step1StateInitializationActivity" Location="255; 326"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="step1CodeActivity_InitializeBindings" Location="265; 388" /> <ActivityDesigner Size="130; 41" Name="step1WizardFormActivity" Location="265; 448" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Next" Location="255; 350"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="nextHandleExternalEventActivity1" Location="265; 412" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="265; 472" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="255; 374"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="265; 436" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="265; 496" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="step2StateActivity" Location="434; 432" Size="211; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step2StateInitializationActivity" Location="442; 463"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step2WizardFormActivity" Location="452; 525" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step2EventDrivenActivity_Finish" Location="442; 487"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="452; 549" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="452; 609" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step2EventDrivenActivity_Cancel" Location="442; 511"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity3" Location="452; 573" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="452; 633" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="681; 608" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="finalizeStateInitializationActivity" Location="689; 639"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity_Finalize" Location="699; 701" /> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="699; 761" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/EditCompositionTypeWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Core; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.DynamicTypes.Foundation; using Composite.Data.GeneratedTypes; using Composite.Core.Types; using Composite.Data.Types; using Composite.Data.Validation.ClientValidationRules; using Composite.C1Console.Workflow; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Plugins_GeneratedDataTypesElementProvider; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { [EntityTokenLock] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditCompositionTypeWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { private string NewTypeNameBindingName { get { return "NewTypeName"; } } private string NewTypeNamespaceBindingName { get { return "NewTypeNamespace"; } } private string NewTypeTitleBindingName { get { return "NewTypeTitle"; } } private string DataFieldDescriptorsBindingName { get { return "DataFieldDescriptors"; } } private string LabelFieldNameBindingName { get { return "LabelFieldName"; } } private string HasCachingBindingName { get { return "HasCaching"; } } private string HasPublishingBindingName { get { return "HasPublishing"; } } public EditCompositionTypeWorkflow() { InitializeComponent(); } private DataTypeDescriptor GetDataTypeDescriptor() { Type type = TypeManager.GetType(this.Payload); Guid guid = type.GetImmutableTypeId(); return DataMetaDataFacade.GetDataTypeDescriptor(guid); } private void initializeStateCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { DataTypeDescriptor dataTypeDescriptor = GetDataTypeDescriptor(); var helper = new GeneratedTypesHelper(dataTypeDescriptor); var fieldDescriptors = helper.EditableInDesignerOwnDataFields.ToList(); this.Bindings = new Dictionary<string, object> { {"TypeName", dataTypeDescriptor.Name}, {"TypeNamespace", dataTypeDescriptor.Namespace}, {"TypeTitle", dataTypeDescriptor.Title}, {"LabelFieldName", dataTypeDescriptor.LabelFieldName}, {"HasCaching", helper.IsCacheable}, {"HasPublishing", helper.IsPublishControlled}, {"DataFieldDescriptors", fieldDescriptors}, {"OldTypeName", dataTypeDescriptor.Name}, {"OldTypeNamespace", dataTypeDescriptor.Namespace} }; this.BindingsValidationRules = new Dictionary<string, List<ClientValidationRule>> { {this.NewTypeNameBindingName, new List<ClientValidationRule> {new NotNullClientValidationRule()}}, {this.NewTypeNamespaceBindingName, new List<ClientValidationRule> {new NotNullClientValidationRule()}}, {this.NewTypeTitleBindingName, new List<ClientValidationRule> {new NotNullClientValidationRule()}} }; } private Type GetOldTypeFromBindings() { string typeFullName = GetBinding<string>("OldTypeNamespace") + "." + GetBinding<string>("OldTypeName"); return TypeManager.GetType(typeFullName); } private void saveTypeCodeActivity_Save_ExecuteCode(object sender, EventArgs e) { try { Type oldType = GetOldTypeFromBindings(); string typeName = this.GetBinding<string>("TypeName"); string typeNamespace = this.GetBinding<string>("TypeNamespace"); string typeTitle = this.GetBinding<string>("TypeTitle"); bool hasCaching = this.GetBinding<bool>("HasCaching"); bool hasPublishing = this.GetBinding<bool>("HasPublishing"); string labelFieldName = this.GetBinding<string>("LabelFieldName"); var dataFieldDescriptors = this.GetBinding<List<DataFieldDescriptor>>("DataFieldDescriptors"); var helper = new GeneratedTypesHelper(oldType); 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, Texts.EditCompositionTypeWorkflow_ErrorTitle, errorMessage ); return; } helper.SetNewTypeFullName(typeName, typeNamespace); helper.SetNewTypeTitle(typeTitle); // TODO: fix helper.SetNewFieldDescriptors(dataFieldDescriptors, null, labelFieldName); helper.SetCacheable(hasCaching); if (helper.IsEditProcessControlledAllowed) { helper.SetPublishControlled(hasPublishing); } bool originalTypeDataExists = DataFacade.HasDataInAnyScope(oldType); if (!helper.TryValidateUpdate(originalTypeDataExists, out errorMessage)) { this.ShowMessage( DialogType.Warning, Texts.EditCompositionTypeWorkflow_ErrorTitle, errorMessage ); return; } helper.CreateType(originalTypeDataExists); UpdateBinding("OldTypeName", typeName); UpdateBinding("OldTypeNamespace", typeNamespace); SetSaveStatus(true); var rootEntityToken = new GeneratedDataTypesElementProviderRootEntityToken(this.EntityToken.Source, GeneratedDataTypesElementProviderRootEntityToken.PageMetaDataTypeFolderId); SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(rootEntityToken); IFile markupFile = DynamicTypesCustomFormFacade.GetCustomFormMarkupFile(typeNamespace, typeName); if (markupFile != null) { ShowMessage(DialogType.Message, Texts.FormMarkupInfo_Dialog_Label, Texts.FormMarkupInfo_Message(Texts.EditFormMarkup, markupFile.GetRelativeFilePath())); } } catch (Exception ex) { Log.LogCritical("EditCompositionTypeWorkflow", ex); this.ShowMessage(DialogType.Error, ex.Message, ex.Message); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/EditCompositionTypeWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { partial class EditCompositionTypeWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveTypeCodeActivity_Save = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.editTypeDocumentFormActivity = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.initializeStateCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.saveTypeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editTypeEventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editTypeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveTypeStateActivity = new System.Workflow.Activities.StateActivity(); this.editTypeStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "editTypeStateActivity"; // // saveTypeCodeActivity_Save // this.saveTypeCodeActivity_Save.Name = "saveTypeCodeActivity_Save"; this.saveTypeCodeActivity_Save.ExecuteCode += new System.EventHandler(this.saveTypeCodeActivity_Save_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "saveTypeStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // editTypeDocumentFormActivity // this.editTypeDocumentFormActivity.ContainerLabel = null; this.editTypeDocumentFormActivity.FormDefinitionFileName = "\\Administrative\\EditCompositionTypeStep1.xml"; this.editTypeDocumentFormActivity.Name = "editTypeDocumentFormActivity"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editTypeStateActivity"; // // initializeStateCodeActivity_Initialize // this.initializeStateCodeActivity_Initialize.Name = "initializeStateCodeActivity_Initialize"; this.initializeStateCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeStateCodeActivity_Initialize_ExecuteCode); // // saveTypeStateInitializationActivity // this.saveTypeStateInitializationActivity.Activities.Add(this.saveTypeCodeActivity_Save); this.saveTypeStateInitializationActivity.Activities.Add(this.setStateActivity3); this.saveTypeStateInitializationActivity.Name = "saveTypeStateInitializationActivity"; // // editTypeEventDrivenActivity_Save // this.editTypeEventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.editTypeEventDrivenActivity_Save.Activities.Add(this.setStateActivity2); this.editTypeEventDrivenActivity_Save.Name = "editTypeEventDrivenActivity_Save"; // // editTypeStateInitializationActivity // this.editTypeStateInitializationActivity.Activities.Add(this.editTypeDocumentFormActivity); this.editTypeStateInitializationActivity.Name = "editTypeStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeStateCodeActivity_Initialize); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveTypeStateActivity // this.saveTypeStateActivity.Activities.Add(this.saveTypeStateInitializationActivity); this.saveTypeStateActivity.Name = "saveTypeStateActivity"; // // editTypeStateActivity // this.editTypeStateActivity.Activities.Add(this.editTypeStateInitializationActivity); this.editTypeStateActivity.Activities.Add(this.editTypeEventDrivenActivity_Save); this.editTypeStateActivity.Name = "editTypeStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // EditCompositionTypeWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.editTypeStateActivity); this.Activities.Add(this.saveTypeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "EditCompositionTypeWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity2; private Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity4; private StateInitializationActivity saveTypeStateInitializationActivity; private EventDrivenActivity editTypeEventDrivenActivity_Save; private StateInitializationActivity editTypeStateInitializationActivity; private StateActivity saveTypeStateActivity; private StateActivity editTypeStateActivity; private CodeActivity initializeStateCodeActivity_Initialize; private Composite.C1Console.Workflow.Activities.DocumentFormActivity editTypeDocumentFormActivity; private CodeActivity saveTypeCodeActivity_Save; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/EditCompositionTypeWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="EditCompositionTypeWorkflow" Location="30; 30" Size="1154; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="EditCompositionTypeWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="EditCompositionTypeWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editTypeStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="editTypeStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="322" Y="179" /> <ns0:Point X="322" Y="370" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="saveTypeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="editTypeStateActivity" SourceConnectionEdge="Right" TargetActivity="saveTypeStateActivity" SourceActivity="editTypeStateActivity" EventHandlerName="editTypeEventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="427" Y="435" /> <ns0:Point X="693" Y="435" /> <ns0:Point X="693" Y="455" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editTypeStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="saveTypeStateActivity" SourceConnectionEdge="Right" TargetActivity="editTypeStateActivity" SourceActivity="saveTypeStateActivity" EventHandlerName="saveTypeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="798" Y="496" /> <ns0:Point X="810" Y="496" /> <ns0:Point X="810" Y="362" /> <ns0:Point X="322" Y="362" /> <ns0:Point X="322" Y="370" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeStateCodeActivity_Initialize" Location="108; 231" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="108; 291" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="editTypeStateActivity" Location="213; 370" Size="218; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="editTypeStateInitializationActivity" Location="532; 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="editTypeDocumentFormActivity" Location="542; 210" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="editTypeEventDrivenActivity_Save" Location="524; 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="saveHandleExternalEventActivity1" Location="534; 221" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="534; 281" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="saveTypeStateActivity" Location="584; 455" Size="218; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="saveTypeStateInitializationActivity" Location="592; 486"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="saveTypeCodeActivity_Save" Location="602; 548" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="602; 608" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/EditDataWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { partial class EditDataWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.enablePublishCodeActivity = new System.Workflow.Activities.CodeActivity(); this.saveAndPublishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveAndPublishHandleExternalEventActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.editCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveAndPublishEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.saveEditEventDrivenActivity1 = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.initialStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // saveCodeActivity // this.saveCodeActivity.Name = "saveCodeActivity"; this.saveCodeActivity.ExecuteCode += new System.EventHandler(this.saveCodeActivity_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "saveStateActivity"; // // enablePublishCodeActivity // this.enablePublishCodeActivity.Name = "enablePublishCodeActivity"; this.enablePublishCodeActivity.ExecuteCode += new System.EventHandler(this.enablePublishCodeActivity_ExecuteCode); // // saveAndPublishHandleExternalEventActivity1 // this.saveAndPublishHandleExternalEventActivity1.EventName = "SaveAndPublish"; this.saveAndPublishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveAndPublishHandleExternalEventActivity1.Name = "saveAndPublishHandleExternalEventActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "saveStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // editCodeActivity // this.editCodeActivity.Name = "editCodeActivity"; this.editCodeActivity.ExecuteCode += new System.EventHandler(this.editCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "editStateActivity"; // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.saveCodeActivity); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity4); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveAndPublishEventDrivenActivity // this.saveAndPublishEventDrivenActivity.Activities.Add(this.saveAndPublishHandleExternalEventActivity1); this.saveAndPublishEventDrivenActivity.Activities.Add(this.enablePublishCodeActivity); this.saveAndPublishEventDrivenActivity.Activities.Add(this.setStateActivity5); this.saveAndPublishEventDrivenActivity.Name = "saveAndPublishEventDrivenActivity"; // // saveEditEventDrivenActivity1 // this.saveEditEventDrivenActivity1.Activities.Add(this.saveHandleExternalEventActivity1); this.saveEditEventDrivenActivity1.Activities.Add(this.setStateActivity1); this.saveEditEventDrivenActivity1.Name = "saveEditEventDrivenActivity1"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.editCodeActivity); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.setStateActivity3); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.saveStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity2); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.saveEditEventDrivenActivity1); this.editStateActivity.Activities.Add(this.saveAndPublishEventDrivenActivity); this.editStateActivity.Name = "editStateActivity"; // // initialStateActivity // this.initialStateActivity.Activities.Add(this.initialStateInitializationActivity); this.initialStateActivity.Name = "initialStateActivity"; // // EditDataWorkflow // this.Activities.Add(this.initialStateActivity); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelEventDrivenActivity); this.Activities.Add(this.saveStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialStateActivity"; this.Name = "EditDataWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity5; private CodeActivity enablePublishCodeActivity; private C1Console.Workflow.Activities.SaveAndPublishHandleExternalEventActivity saveAndPublishHandleExternalEventActivity1; private EventDrivenActivity saveAndPublishEventDrivenActivity; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity editStateInitializationActivity; private StateInitializationActivity initialStateInitializationActivity; private EventDrivenActivity cancelEventDrivenActivity; private StateActivity finalStateActivity; private StateActivity editStateActivity; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private CodeActivity editCodeActivity; private SetStateActivity setStateActivity3; private StateInitializationActivity saveStateInitializationActivity; private EventDrivenActivity saveEditEventDrivenActivity1; private StateActivity saveStateActivity; private CodeActivity saveCodeActivity; private SetStateActivity setStateActivity1; private StateActivity initialStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/EditDataWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Scheduling; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.C1Console.Workflow.Activities; using Composite.Core.ResourceSystem; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { [EntityTokenLock] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditDataWorkflow : FormsWorkflow { [NonSerialized] private bool _doPublish; [NonSerialized] private DataTypeDescriptorFormsHelper _helper; [NonSerialized] private string _typeName; public EditDataWorkflow() { InitializeComponent(); } private DataTypeDescriptorFormsHelper GetDataTypeDescriptorFormsHelper() { if (_helper == null) { var dataEntityToken = (DataEntityToken)EntityToken; var guid = dataEntityToken.Data.DataSourceId.InterfaceType.GetImmutableTypeId(); var typeDescriptor = DataMetaDataFacade.GetDataTypeDescriptor(guid); var generatedTypesHelper = new GeneratedTypesHelper(typeDescriptor) { AllowForeignKeyEditing = true }; _helper = new DataTypeDescriptorFormsHelper(typeDescriptor, true, EntityToken) { LayoutIconHandle = "generated-type-data-edit" }; _helper.AddReadOnlyFields(generatedTypesHelper.NotEditableDataFieldDescriptorNames); _typeName = typeDescriptor.Name; } return _helper; } private void editCodeActivity_ExecuteCode(object sender, EventArgs e) { var data = ((DataEntityToken)EntityToken).Data; var publishedControlled = data as IPublishControlled; if (!PermissionsFacade.GetPermissionsForCurrentUser(EntityToken).Contains(PermissionType.Publish) || publishedControlled == null) { var formData = WorkflowFacade.GetFormData(InstanceId, true); if (formData.ExcludedEvents == null) { formData.ExcludedEvents = new List<string>(); } formData.ExcludedEvents.Add("SaveAndPublish"); } var helper = GetDataTypeDescriptorFormsHelper(); if (publishedControlled != null) { if (publishedControlled.PublicationStatus == GenericPublishProcessController.Published) { publishedControlled.PublicationStatus = GenericPublishProcessController.Draft; } } helper.UpdateWithBindings(data, Bindings); helper.LayoutLabel = data.GetLabel(true); DeliverFormData( _typeName, StandardUiContainerTypes.Document, helper.GetForm(), Bindings, helper.GetBindingsValidationRules(data) ); } private void saveCodeActivity_ExecuteCode(object sender, EventArgs e) { var isValid = ValidateBindings(); var updateTreeRefresher = CreateUpdateTreeRefresher(EntityToken); var helper = GetDataTypeDescriptorFormsHelper(); var data = ((DataEntityToken)EntityToken).Data; if (!BindAndValidate(helper, data)) { isValid = false; } var fieldsWithBrokenReferences = new List<string>(); if (!data.TryValidateForeignKeyIntegrity(fieldsWithBrokenReferences)) { isValid = false; foreach (var fieldName in fieldsWithBrokenReferences) { ShowFieldMessage(fieldName, StringResourceSystemFacade.GetString("Composite.Management", "Validation.BrokenReference")); } } if (isValid) { // published data stayed as published data - change to draft if status is published if (data is IPublishControlled) { var publishControlledData = (IPublishControlled)data; if (publishControlledData.PublicationStatus == GenericPublishProcessController.Published) { publishControlledData.PublicationStatus = GenericPublishProcessController.Draft; } } DataFacade.Update(data); EntityTokenCacheFacade.ClearCache(EntityToken); updateTreeRefresher.PostRefreshMesseges(EntityToken); PublishControlledHelper.PublishIfNeeded(data, _doPublish, Bindings, ShowMessage); SetSaveStatus(true); } else { SetSaveStatus(false); } } private void enablePublishCodeActivity_ExecuteCode(object sender, EventArgs e) { _doPublish = true; } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/EditDataWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1199; 932" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="EditDataWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="212; 80" AutoSizeMargin="16; 24" Location="117; 131" Name="initialStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initialStateInitializationActivity" Size="150; 146" Location="125; 164"> <StateInitializationDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130; 62" Location="135; 229" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="239; 110" AutoSizeMargin="16; 24" AutoSize="False" Location="102; 382" Name="editStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="editStateInitializationActivity" Size="150; 125" Location="546; 141"> <StateInitializationDesigner.Designers> <CodeDesigner Name="editCodeActivity" Size="130; 41" Location="556; 206" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="saveEditEventDrivenActivity1" Size="150; 209" Location="546; 167"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130; 44" Location="556; 232" /> <SetStateDesigner Name="setStateActivity1" Size="130; 62" Location="556; 295" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="saveAndPublishEventDrivenActivity" Size="150; 272" Location="554; 154"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveAndPublishHandleExternalEventActivity1" Size="130; 44" Location="564; 219" /> <CodeDesigner Name="enablePublishCodeActivity" Size="130; 44" Location="564; 282" /> <SetStateDesigner Name="setStateActivity5" Size="130; 62" Location="564; 345" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="544; 144" Name="finalStateActivity" /> <EventDrivenDesigner Name="cancelEventDrivenActivity" Size="150; 209" Location="38; 63"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 44" Location="48; 128" /> <SetStateDesigner Name="setStateActivity2" Size="130; 62" Location="48; 191" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="206; 80" AutoSizeMargin="16; 24" Location="392; 366" Name="saveStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="saveStateInitializationActivity" Size="150; 209" Location="400; 399"> <StateInitializationDesigner.Designers> <CodeDesigner Name="saveCodeActivity" Size="130; 44" Location="410; 464" /> <SetStateDesigner Name="setStateActivity4" Size="130; 62" Location="410; 527" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity2" SourceActivity="EditDataWorkflow" TargetConnectionIndex="0" SourceStateName="EditDataWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="cancelEventDrivenActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="214" Y="74" /> <ns0:Point X="624" Y="74" /> <ns0:Point X="624" Y="144" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity3" SourceActivity="initialStateActivity" TargetConnectionIndex="0" SourceStateName="initialStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initialStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="325" Y="175" /> <ns0:Point X="341" Y="175" /> <ns0:Point X="341" Y="370" /> <ns0:Point X="221" Y="370" /> <ns0:Point X="221" Y="382" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" SetStateName="setStateActivity1" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Bottom" SourceConnectionEdge="Right" EventHandlerName="saveEditEventDrivenActivity1" SourceConnectionIndex="1" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="303" Y="452" /> <ns0:Point X="495" Y="452" /> <ns0:Point X="495" Y="446" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity4" SourceActivity="saveStateActivity" TargetConnectionIndex="0" SourceStateName="saveStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="saveStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="594" Y="410" /> <ns0:Point X="605" Y="410" /> <ns0:Point X="605" Y="358" /> <ns0:Point X="221" Y="358" /> <ns0:Point X="221" Y="382" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" SetStateName="setStateActivity5" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Bottom" SourceConnectionEdge="Right" EventHandlerName="saveAndPublishEventDrivenActivity" SourceConnectionIndex="2" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="337" Y="478" /> <ns0:Point X="495" Y="478" /> <ns0:Point X="495" Y="446" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/EditFormWorkflow.cs ================================================ using System; using System.Linq; using System.Workflow.Runtime; using System.Xml.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.DynamicTypes.Foundation; using Composite.Data.GeneratedTypes; using Composite.Core.Types; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditFormWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditFormWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { DataTypeDescriptor dataTypeDescriptor = GetDataTypeDescriptor(); string formMarkup; XDocument formMarkupDocument = DynamicTypesCustomFormFacade.GetCustomFormMarkup(dataTypeDescriptor); if (formMarkupDocument != null) { formMarkup = formMarkupDocument.ToString(); } else { bool isMetaDataType = dataTypeDescriptor.SuperInterfaces.Contains(typeof(IPageMetaData)); var formsHelper = new DataTypeDescriptorFormsHelper(dataTypeDescriptor, null, !isMetaDataType, null); var generatedTypesHelper = new GeneratedTypesHelper(dataTypeDescriptor); formsHelper.AddReadOnlyFields(generatedTypesHelper.NotEditableDataFieldDescriptorNames); formMarkup = formsHelper.GetForm(); } this.Bindings.Add("Title", string.Format("{0}.{1} XML", dataTypeDescriptor.Namespace, dataTypeDescriptor.Name)); this.Bindings.Add("FileContent", formMarkup); } private void saveCodeActivity_ExecuteCode(object sender, EventArgs e) { string fileContent = this.GetBinding<string>("FileContent"); DataTypeDescriptor dataTypeDescriptor = GetDataTypeDescriptor(); try { DynamicTypesAlternateFormFacade.SetAlternateForm(dataTypeDescriptor, fileContent); SetSaveStatus(true); } catch (Exception ex) { FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); var consoleMessageService = serviceContainer.GetService<IManagementConsoleMessageService>(); consoleMessageService.ShowMessage( DialogType.Error, "Error", ex.Message); } } private DataTypeDescriptor GetDataTypeDescriptor() { var entityToken = (GeneratedDataTypesElementProviderTypeEntityToken)this.EntityToken; Type type = TypeManager.GetType(entityToken.SerializedTypeName); Guid guid = type.GetImmutableTypeId(); return DataMetaDataFacade.GetDataTypeDescriptor(guid); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/EditFormWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { partial class EditFormWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.initialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // saveCodeActivity // this.saveCodeActivity.Name = "saveCodeActivity"; this.saveCodeActivity.ExecuteCode += new System.EventHandler(this.saveCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "saveStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.FormDefinitionFileName = "/Administrative/EditDynamicTypeFormMarkup.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.saveCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // eventDrivenActivity_Save // this.eventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.eventDrivenActivity_Save.Activities.Add(this.setStateActivity3); this.eventDrivenActivity_Save.Name = "eventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initialStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity1); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.eventDrivenActivity_Save); this.editStateActivity.Name = "editStateActivity"; // // initialState // this.initialState.Activities.Add(this.initialStateInitializationActivity); this.initialState.Name = "initialState"; // // EditFormWorkflow // this.Activities.Add(this.initialState); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelEventDrivenActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialState"; this.Name = "EditFormWorkflow"; this.CanModifyActivities = false; } #endregion private CodeActivity initializeCodeActivity; private SetStateActivity setStateActivity1; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initialStateInitializationActivity; private EventDrivenActivity cancelEventDrivenActivity; private StateActivity finalStateActivity; private StateActivity saveStateActivity; private StateActivity editStateActivity; private Composite.C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private StateInitializationActivity editStateInitializationActivity; private StateInitializationActivity finalizeStateInitializationActivity; private CodeActivity saveCodeActivity; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity eventDrivenActivity_Save; private SetStateActivity setStateActivity4; private StateActivity initialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/EditInterfaceTypeWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { partial class EditInterfaceTypeWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finalizeStateCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity_refreshView = new System.Workflow.Activities.CodeActivity(); this.customEvent01HandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CustomEvent01HandleExternalEventActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.initialStateCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editState_IsSearchableChanged = new System.Workflow.Activities.EventDrivenActivity(); this.saveStep1StateEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.initialStateActivity1 = new System.Workflow.Activities.StateActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "step1StateActivity"; // // finalizeStateCodeActivity // this.finalizeStateCodeActivity.Name = "finalizeStateCodeActivity"; this.finalizeStateCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeStateCodeActivity_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "step1StateActivity"; // // codeActivity_refreshView // this.codeActivity_refreshView.Name = "codeActivity_refreshView"; this.codeActivity_refreshView.ExecuteCode += new System.EventHandler(this.codeActivity_refreshViewHandler); // // customEvent01HandleExternalEventActivity1 // this.customEvent01HandleExternalEventActivity1.EventName = "CustomEvent01"; this.customEvent01HandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.customEvent01HandleExternalEventActivity1.Name = "customEvent01HandleExternalEventActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalizeStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.CustomToolbarDefinitionFileName = null; this.documentFormActivity1.FormDefinitionFileName = "/Administrative/EditInterfaceTypeStep1.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "step1StateActivity"; // // initialStateCodeActivity // this.initialStateCodeActivity.Name = "initialStateCodeActivity"; this.initialStateCodeActivity.ExecuteCode += new System.EventHandler(this.initialStateCodeActivity_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeStateCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity3); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // editState_IsSearchableChanged // this.editState_IsSearchableChanged.Activities.Add(this.customEvent01HandleExternalEventActivity1); this.editState_IsSearchableChanged.Activities.Add(this.codeActivity_refreshView); this.editState_IsSearchableChanged.Activities.Add(this.setStateActivity5); this.editState_IsSearchableChanged.Name = "editState_IsSearchableChanged"; // // saveStep1StateEventDrivenActivity // this.saveStep1StateEventDrivenActivity.Activities.Add(this.saveHandleExternalEventActivity1); this.saveStep1StateEventDrivenActivity.Activities.Add(this.setStateActivity2); this.saveStep1StateEventDrivenActivity.Name = "saveStep1StateEventDrivenActivity"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.documentFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.initialStateCodeActivity); this.initialStateInitializationActivity.Activities.Add(this.setStateActivity4); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity1); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.saveStep1StateEventDrivenActivity); this.step1StateActivity.Activities.Add(this.editState_IsSearchableChanged); this.step1StateActivity.Name = "step1StateActivity"; // // initialStateActivity1 // this.initialStateActivity1.Activities.Add(this.initialStateInitializationActivity); this.initialStateActivity1.Name = "initialStateActivity1"; // // EditInterfaceTypeWorkflow // this.Activities.Add(this.initialStateActivity1); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelEventDrivenActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialStateActivity1"; this.Name = "EditInterfaceTypeWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity1; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity cancelEventDrivenActivity; private StateActivity finalStateActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity4; private StateInitializationActivity finalizeStateInitializationActivity; private StateInitializationActivity step1StateInitializationActivity; private StateInitializationActivity initialStateInitializationActivity; private C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private CodeActivity initialStateCodeActivity; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private EventDrivenActivity saveStep1StateEventDrivenActivity; private CodeActivity finalizeStateCodeActivity; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity5; private CodeActivity codeActivity_refreshView; private C1Console.Workflow.Activities.CustomEvent01HandleExternalEventActivity customEvent01HandleExternalEventActivity1; private EventDrivenActivity editState_IsSearchableChanged; private StateActivity initialStateActivity1; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/EditInterfaceTypeWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Core; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.DynamicTypes.Foundation; using Composite.Data.GeneratedTypes; using Composite.Core.Types; using Composite.Data.ProcessControlled; using Composite.Data.Types; using Composite.Data.Validation.ClientValidationRules; using Composite.C1Console.Workflow; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Plugins_GeneratedDataTypesElementProvider; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { [EntityTokenLock] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditInterfaceTypeWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditInterfaceTypeWorkflow() { InitializeComponent(); } private bool IsPageFolder { get { return this.EntityToken.Id == GeneratedDataTypesElementProviderRootEntityToken.PageDataFolderTypeFolderId; } } private static class BindingNames { public const string TypeName = "TypeName"; public const string TypeNamespace = "TypeNamespace"; public const string TypeTitle = "TypeTitle"; public const string DataFieldDescriptors = "DataFieldDescriptors"; public const string KeyFieldName = "KeyFieldName"; public const string LabelFieldName = "LabelFieldName"; public const string InternalUrlPrefix = "InternalUrlPrefix"; public const string HasCaching = "HasCaching"; public const string HasPublishing = "HasPublishing"; public const string IsSearchable = "IsSearchable"; public const string OldTypeName = "OldTypeName"; public const string OldTypeNamespace = "OldTypeNamespace"; } private DataTypeDescriptor GetDataTypeDescriptor() { Type type = GetTypeFromEntityToken(); Guid guid = type.GetImmutableTypeId(); return DataMetaDataFacade.GetDataTypeDescriptor(guid); } private Type GetTypeFromEntityToken() { var entityToken = (GeneratedDataTypesElementProviderTypeEntityToken)this.EntityToken; return TypeManager.GetType(entityToken.SerializedTypeName); } private void initialStateCodeActivity_ExecuteCode(object sender, EventArgs e) { DataTypeDescriptor dataTypeDescriptor = GetDataTypeDescriptor(); var helper = new GeneratedTypesHelper(dataTypeDescriptor); List<DataFieldDescriptor> fieldDescriptors = helper.EditableInDesignerOwnDataFields.ToList(); this.Bindings = new Dictionary<string, object> { {BindingNames.TypeName, dataTypeDescriptor.Name}, {BindingNames.TypeNamespace, dataTypeDescriptor.Namespace}, {BindingNames.TypeTitle, dataTypeDescriptor.Title}, {BindingNames.KeyFieldName, dataTypeDescriptor.KeyPropertyNames.Single() }, {BindingNames.LabelFieldName, dataTypeDescriptor.LabelFieldName}, {BindingNames.InternalUrlPrefix, dataTypeDescriptor.InternalUrlPrefix}, {BindingNames.HasCaching, helper.IsCacheable}, {BindingNames.HasPublishing, helper.IsPublishControlled}, {BindingNames.IsSearchable, helper.IsSearchable}, {BindingNames.DataFieldDescriptors, fieldDescriptors}, {BindingNames.OldTypeName, dataTypeDescriptor.Name}, {BindingNames.OldTypeNamespace, dataTypeDescriptor.Namespace} }; this.BindingsValidationRules = new Dictionary<string, List<ClientValidationRule>> { {BindingNames.TypeName, new List<ClientValidationRule> {new NotNullClientValidationRule()}}, {BindingNames.TypeNamespace, new List<ClientValidationRule> {new NotNullClientValidationRule()}}, {BindingNames.TypeTitle, new List<ClientValidationRule> {new NotNullClientValidationRule()}} }; } private Type GetOldTypeFromBindings() { string typeFullName = GetBinding<string>(BindingNames.OldTypeNamespace) + "." + GetBinding<string>(BindingNames.OldTypeName); return TypeManager.GetType(typeFullName); } private void finalizeStateCodeActivity_ExecuteCode(object sender, EventArgs e) { try { Type oldType = GetOldTypeFromBindings(); string typeName = this.GetBinding<string>(BindingNames.TypeName); string typeNamespace = this.GetBinding<string>(BindingNames.TypeNamespace); string typeTitle = this.GetBinding<string>(BindingNames.TypeTitle); bool hasCaching = this.GetBinding<bool>(BindingNames.HasCaching); bool hasPublishing = this.GetBinding<bool>(BindingNames.HasPublishing); bool isSearchable = this.GetBinding<bool>(BindingNames.IsSearchable); 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); var helper = new GeneratedTypesHelper(oldType); bool hasLocalization = typeof(ILocalizedControlled).IsAssignableFrom(oldType); string errorMessage; if (!helper.ValidateNewTypeName(typeName, out errorMessage)) { this.ShowFieldMessage(BindingNames.TypeName, errorMessage); return; } if (!helper.ValidateNewTypeNamespace(typeNamespace, out errorMessage)) { this.ShowFieldMessage(BindingNames.TypeNamespace, errorMessage); return; } if (!helper.ValidateNewTypeFullName(typeName, typeNamespace, out errorMessage)) { this.ShowFieldMessage(BindingNames.TypeName, errorMessage); return; } if (!helper.ValidateNewFieldDescriptors(dataFieldDescriptors, keyFieldName, out errorMessage)) { this.ShowMessage( DialogType.Warning, Texts.EditInterfaceTypeStep1_ErrorTitle, errorMessage ); return; } helper.SetNewTypeFullName(typeName, typeNamespace); helper.SetNewTypeTitle(typeTitle); helper.SetNewInternalUrlPrefix(internalUrlPrefix); helper.SetNewFieldDescriptors(dataFieldDescriptors, keyFieldName, labelFieldName); if (helper.IsEditProcessControlledAllowed) { helper.SetCacheable(hasCaching); helper.SetSearchable(isSearchable); helper.SetPublishControlled(hasPublishing); helper.SetLocalizedControlled(hasLocalization); } bool originalTypeHasData = DataFacade.HasDataInAnyScope(oldType); if (!helper.TryValidateUpdate(originalTypeHasData, out errorMessage)) { this.ShowMessage( DialogType.Warning, Texts.EditInterfaceTypeStep1_ErrorTitle, errorMessage ); return; } if (!IsPageFolder) { string oldSerializedTypeName = GetSerializedTypeName(GetBinding<string>(BindingNames.OldTypeNamespace), GetBinding<string>(BindingNames.OldTypeName)); string newSerializedTypeName = GetSerializedTypeName(typeNamespace, typeName); if (newSerializedTypeName != oldSerializedTypeName) { UpdateWhiteListedGeneratedTypes(oldSerializedTypeName, newSerializedTypeName); } } helper.CreateType(originalTypeHasData); UpdateBinding(BindingNames.OldTypeName, typeName); UpdateBinding(BindingNames.OldTypeNamespace, typeNamespace); SetSaveStatus(true); var rootEntityToken = new GeneratedDataTypesElementProviderRootEntityToken(this.EntityToken.Source, IsPageFolder ? GeneratedDataTypesElementProviderRootEntityToken.PageDataFolderTypeFolderId : GeneratedDataTypesElementProviderRootEntityToken.GlobalDataTypeFolderId); SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(rootEntityToken); IFile markupFile = DynamicTypesAlternateFormFacade.GetAlternateFormMarkupFile(typeNamespace, typeName); if (markupFile != null) { ShowMessage(DialogType.Message, Texts.FormMarkupInfo_Dialog_Label, Texts.FormMarkupInfo_Message(Texts.EditFormMarkup, markupFile.GetRelativeFilePath())); } } catch (Exception ex) { Log.LogCritical(this.GetType().Name, ex); this.ShowMessage(DialogType.Error, ex.Message, ex.Message); } } private static void UpdateWhiteListedGeneratedTypes(string oldTypeName, string newTypeName) { var referencesToOldTypeName = DataFacade.GetData<IGeneratedTypeWhiteList>(item => item.TypeManagerTypeName == oldTypeName).ToList(); if (!referencesToOldTypeName.Any()) { return; } if (!DataFacade.GetData<IGeneratedTypeWhiteList>(item => item.TypeManagerTypeName == newTypeName).Any()) { var newWhiteListItem = DataFacade.BuildNew<IGeneratedTypeWhiteList>(); newWhiteListItem.TypeManagerTypeName = newTypeName; DataFacade.AddNew(newWhiteListItem); } DataFacade.Delete<IGeneratedTypeWhiteList>(referencesToOldTypeName); } private static string GetSerializedTypeName(string typeNamespace, string typeName) { return "DynamicType:" + (typeName.Length == 0 ? typeName : typeNamespace + "." + typeName); } private void codeActivity_refreshViewHandler(object sender, EventArgs e) { RerenderView(); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/EditInterfaceTypeWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="955, 547" AutoSizeMargin="16, 24" Location="30, 30" Name="EditInterfaceTypeWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="EditInterfaceTypeWorkflow" TargetConnectionIndex="0" SourceStateName="EditInterfaceTypeWorkflow" SourceConnectionEdge="Right" EventHandlerName="cancelEventDrivenActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="214" Y="74" /> <ns0:Point X="214" Y="66" /> <ns0:Point X="302" Y="66" /> <ns0:Point X="302" Y="401" /> <ns0:Point X="139" Y="401" /> <ns0:Point X="139" Y="413" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="initialStateActivity1" TargetConnectionIndex="0" SourceStateName="initialStateActivity1" SourceConnectionEdge="Right" EventHandlerName="initialStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="267" Y="149" /> <ns0:Point X="283" Y="149" /> <ns0:Point X="283" Y="190" /> <ns0:Point X="177" Y="190" /> <ns0:Point X="177" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" EventHandlerName="saveStep1StateEventDrivenActivity" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="291" Y="271" /> <ns0:Point X="456" Y="271" /> <ns0:Point X="456" Y="339" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="562" Y="383" /> <ns0:Point X="578" Y="383" /> <ns0:Point X="578" Y="193" /> <ns0:Point X="177" Y="193" /> <ns0:Point X="177" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" EventHandlerName="editState_IsSearchableChanged" SourceConnectionIndex="2" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="274" Y="297" /> <ns0:Point X="306" Y="297" /> <ns0:Point X="306" Y="193" /> <ns0:Point X="177" Y="193" /> <ns0:Point X="177" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="212, 80" AutoSizeMargin="16, 24" Location="59, 105" Name="initialStateActivity1"> <StateDesigner.Designers> <StateInitializationDesigner Name="initialStateInitializationActivity" Size="150, 209" Location="67, 138"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initialStateCodeActivity" Size="130, 44" Location="77, 203" /> <SetStateDesigner Name="setStateActivity4" Size="130, 62" Location="77, 266" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="236, 136" AutoSizeMargin="16, 24" Location="59, 201" Name="step1StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1StateInitializationActivity" Size="150, 128" Location="67, 234"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="documentFormActivity1" Size="130, 44" Location="77, 299" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="saveStep1StateEventDrivenActivity" Size="150, 209" Location="67, 260"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130, 44" Location="77, 325" /> <SetStateDesigner Name="setStateActivity2" Size="130, 62" Location="77, 388" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="editState_IsSearchableChanged" Size="150, 272" Location="67, 286"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="customEvent01HandleExternalEventActivity1" Size="130, 44" Location="77, 351" /> <CodeDesigner Name="codeActivity_refreshView" Size="130, 44" Location="77, 414" /> <SetStateDesigner Name="setStateActivity5" Size="130, 62" Location="77, 477" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="220, 80" AutoSizeMargin="16, 24" AutoSize="False" Location="346, 339" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150, 209" Location="354, 372"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeStateCodeActivity" Size="130, 44" Location="364, 437" /> <SetStateDesigner Name="setStateActivity3" Size="130, 62" Location="364, 500" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160, 80" AutoSizeMargin="16, 24" Location="59, 413" Name="finalStateActivity" /> <EventDrivenDesigner Name="cancelEventDrivenActivity" Size="150, 209" Location="38, 63"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130, 44" Location="48, 128" /> <SetStateDesigner Name="setStateActivity1" Size="130, 62" Location="48, 191" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/EnableTypeLocalizationWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; using Composite.Data.ProcessControlled; using Composite.Core.Types; using Composite.C1Console.Workflow; using Composite.C1Console.Users; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EnableTypeLocalizationWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EnableTypeLocalizationWorkflow() { InitializeComponent(); } private DataTypeDescriptor GetDataTypeDescriptor() { Type type; if (this.EntityToken is AssociatedDataElementProviderHelperEntityToken) { var castedEntityToken = this.EntityToken as AssociatedDataElementProviderHelperEntityToken; type = TypeManager.GetType(castedEntityToken.Payload); } else { var entityToken = (GeneratedDataTypesElementProviderTypeEntityToken)this.EntityToken; type = TypeManager.GetType(entityToken.SerializedTypeName); } Guid guid = type.GetImmutableTypeId(); return DataMetaDataFacade.GetDataTypeDescriptor(guid); } private void LocalesExists(object sender, ConditionalEventArgs e) { e.Result = DataLocalizationFacade.ActiveLocalizationCultures.Any(); } private void step1CodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { var culturesDictionary = DataLocalizationFacade.ActiveLocalizationCultures.ToDictionary(f => f.Name, DataLocalizationFacade.GetCultureTitle); this.UpdateBinding("CultureName", (UserSettings.ForeignLocaleCultureInfo ?? UserSettings.ActiveLocaleCultureInfo).Name); this.UpdateBinding("CultureNameList", culturesDictionary); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { DataTypeDescriptor dataTypeDescriptor = GetDataTypeDescriptor(); // Making changes to type DataTypeDescriptor newDataTypeDescriptor = dataTypeDescriptor.Clone(); newDataTypeDescriptor.AddSuperInterface(typeof(ILocalizedControlled)); List<CultureInfo> localesToCopyTo = new List<CultureInfo>(); if (ThereAreReferencesInLocalizedData()) { localesToCopyTo.AddRange(DataLocalizationFacade.ActiveLocalizationCultures); } else { string cultureName = this.GetBinding<string>("CultureName"); localesToCopyTo.Add(CultureInfo.CreateSpecificCulture(cultureName)); } var updateDataTypeDescriptor = new UpdateDataTypeDescriptor(dataTypeDescriptor, newDataTypeDescriptor, false) { LocalesToCopyTo = localesToCopyTo }; GeneratedTypesFacade.UpdateType(updateDataTypeDescriptor); this.CloseCurrentView(); this.CollapseAndRefresh(); } private bool ThereAreReferencesInLocalizedData() { if (DataLocalizationFacade.ActiveLocalizationCultures.Count() == 1) { return false; } Type type = GetDataTypeDescriptor().GetInterfaceType(); return type.GetRefereeTypes().Any(DataLocalizationFacade.IsLocalized); } private void ThereAreReferencesInLocalizedData(object sender, ConditionalEventArgs e) { e.Result = ThereAreReferencesInLocalizedData(); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/EnableTypeLocalizationWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { partial class EnableTypeLocalizationWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.NoReferencesInLocalizedDataActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.ThereAreReferencesInLocalizedDataActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity12 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity4 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity11 = new System.Workflow.Activities.SetStateActivity(); this.nextHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.wizardFormActivity1 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.noLocalesDataDialogFormActivity = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.previousHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.PreviousHandleExternalEventActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step2WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.nextHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.step1WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.step1CodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.initializeIfElseActivity_LocalesExists = new System.Workflow.Activities.IfElseActivity(); this.eventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.eventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.noLocalesEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.noLocalesStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step2EventDrivenActivity_Previous = new System.Workflow.Activities.EventDrivenActivity(); this.step2EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step2EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step2StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.referencesExistsStateActivity = new System.Workflow.Activities.StateActivity(); this.noLocalesStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step2StateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "step1StateActivity"; // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "referencesExistsStateActivity"; // // NoReferencesInLocalizedDataActivity3 // this.NoReferencesInLocalizedDataActivity3.Activities.Add(this.setStateActivity6); this.NoReferencesInLocalizedDataActivity3.Name = "NoReferencesInLocalizedDataActivity3"; // // ThereAreReferencesInLocalizedDataActivity4 // this.ThereAreReferencesInLocalizedDataActivity4.Activities.Add(this.setStateActivity10); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ThereAreReferencesInLocalizedData); this.ThereAreReferencesInLocalizedDataActivity4.Condition = codecondition1; this.ThereAreReferencesInLocalizedDataActivity4.Name = "ThereAreReferencesInLocalizedDataActivity4"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "noLocalesStateActivity"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ThereAreReferencesInLocalizedDataActivity4); this.ifElseActivity1.Activities.Add(this.NoReferencesInLocalizedDataActivity3); this.ifElseActivity1.Name = "ifElseActivity1"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity8); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.ifElseActivity1); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.LocalesExists); this.ifElseBranchActivity1.Condition = codecondition2; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity12 // this.setStateActivity12.Name = "setStateActivity12"; this.setStateActivity12.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity4 // this.cancelHandleExternalEventActivity4.EventName = "Cancel"; this.cancelHandleExternalEventActivity4.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity4.Name = "cancelHandleExternalEventActivity4"; // // setStateActivity11 // this.setStateActivity11.Name = "setStateActivity11"; this.setStateActivity11.TargetStateName = "step2StateActivity"; // // nextHandleExternalEventActivity2 // this.nextHandleExternalEventActivity2.EventName = "Next"; this.nextHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity2.Name = "nextHandleExternalEventActivity2"; // // wizardFormActivity1 // this.wizardFormActivity1.ContainerLabel = null; this.wizardFormActivity1.FormDefinitionFileName = "/Administrative/EnableTypeLocalizationStep3.xml"; this.wizardFormActivity1.Name = "wizardFormActivity1"; // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "finalStateActivity"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // noLocalesDataDialogFormActivity // this.noLocalesDataDialogFormActivity.ContainerLabel = null; this.noLocalesDataDialogFormActivity.FormDefinitionFileName = "/Administrative/EnableTypeLocalizationNoLocales.xml"; this.noLocalesDataDialogFormActivity.Name = "noLocalesDataDialogFormActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "step1StateActivity"; // // previousHandleExternalEventActivity1 // this.previousHandleExternalEventActivity1.EventName = "Previous"; this.previousHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.previousHandleExternalEventActivity1.Name = "previousHandleExternalEventActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // step2WizardFormActivity // this.step2WizardFormActivity.ContainerLabel = null; this.step2WizardFormActivity.FormDefinitionFileName = "/Administrative/EnableTypeLocalizationStep2.xml"; this.step2WizardFormActivity.Name = "step2WizardFormActivity"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "step2StateActivity"; // // nextHandleExternalEventActivity1 // this.nextHandleExternalEventActivity1.EventName = "Next"; this.nextHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity1.Name = "nextHandleExternalEventActivity1"; // // step1WizardFormActivity // this.step1WizardFormActivity.ContainerLabel = null; this.step1WizardFormActivity.FormDefinitionFileName = "/Administrative/EnableTypeLocalizationStep1.xml"; this.step1WizardFormActivity.Name = "step1WizardFormActivity"; // // step1CodeActivity_Initialize // this.step1CodeActivity_Initialize.Name = "step1CodeActivity_Initialize"; this.step1CodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.step1CodeActivity_Initialize_ExecuteCode); // // initializeIfElseActivity_LocalesExists // this.initializeIfElseActivity_LocalesExists.Activities.Add(this.ifElseBranchActivity1); this.initializeIfElseActivity_LocalesExists.Activities.Add(this.ifElseBranchActivity2); this.initializeIfElseActivity_LocalesExists.Name = "initializeIfElseActivity_LocalesExists"; // // eventDrivenActivity_Cancel // this.eventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity4); this.eventDrivenActivity_Cancel.Activities.Add(this.setStateActivity12); this.eventDrivenActivity_Cancel.Name = "eventDrivenActivity_Cancel"; // // eventDrivenActivity_Next // this.eventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity2); this.eventDrivenActivity_Next.Activities.Add(this.setStateActivity11); this.eventDrivenActivity_Next.Name = "eventDrivenActivity_Next"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.wizardFormActivity1); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // noLocalesEventDrivenActivity_Finish // this.noLocalesEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.noLocalesEventDrivenActivity_Finish.Activities.Add(this.setStateActivity9); this.noLocalesEventDrivenActivity_Finish.Name = "noLocalesEventDrivenActivity_Finish"; // // noLocalesStateInitializationActivity // this.noLocalesStateInitializationActivity.Activities.Add(this.noLocalesDataDialogFormActivity); this.noLocalesStateInitializationActivity.Name = "noLocalesStateInitializationActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step2EventDrivenActivity_Previous // this.step2EventDrivenActivity_Previous.Activities.Add(this.previousHandleExternalEventActivity1); this.step2EventDrivenActivity_Previous.Activities.Add(this.setStateActivity7); this.step2EventDrivenActivity_Previous.Name = "step2EventDrivenActivity_Previous"; // // step2EventDrivenActivity_Cancel // this.step2EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.step2EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity5); this.step2EventDrivenActivity_Cancel.Name = "step2EventDrivenActivity_Cancel"; // // step2EventDrivenActivity_Finish // this.step2EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step2EventDrivenActivity_Finish.Activities.Add(this.setStateActivity2); this.step2EventDrivenActivity_Finish.Name = "step2EventDrivenActivity_Finish"; // // step2StateInitializationActivity // this.step2StateInitializationActivity.Activities.Add(this.step2WizardFormActivity); this.step2StateInitializationActivity.Name = "step2StateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity4); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Next // this.step1EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity1); this.step1EventDrivenActivity_Next.Activities.Add(this.setStateActivity3); this.step1EventDrivenActivity_Next.Name = "step1EventDrivenActivity_Next"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1CodeActivity_Initialize); this.step1StateInitializationActivity.Activities.Add(this.step1WizardFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeIfElseActivity_LocalesExists); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // referencesExistsStateActivity // this.referencesExistsStateActivity.Activities.Add(this.stateInitializationActivity1); this.referencesExistsStateActivity.Activities.Add(this.eventDrivenActivity_Next); this.referencesExistsStateActivity.Activities.Add(this.eventDrivenActivity_Cancel); this.referencesExistsStateActivity.Name = "referencesExistsStateActivity"; // // noLocalesStateActivity // this.noLocalesStateActivity.Activities.Add(this.noLocalesStateInitializationActivity); this.noLocalesStateActivity.Activities.Add(this.noLocalesEventDrivenActivity_Finish); this.noLocalesStateActivity.Name = "noLocalesStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step2StateActivity // this.step2StateActivity.Activities.Add(this.step2StateInitializationActivity); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Finish); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Cancel); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Previous); this.step2StateActivity.Name = "step2StateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Next); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // EnableTypeLocalizationWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.step2StateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.noLocalesStateActivity); this.Activities.Add(this.referencesExistsStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "EnableTypeLocalizationWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity1; private EventDrivenActivity step2EventDrivenActivity_Cancel; private EventDrivenActivity step2EventDrivenActivity_Finish; private StateInitializationActivity step2StateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Next; private StateInitializationActivity step1StateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity step2StateActivity; private StateActivity step1StateActivity; private CodeActivity finalizeCodeActivity_Finalize; private StateInitializationActivity finalizeStateInitializationActivity; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity6; private Composite.C1Console.Workflow.Activities.WizardFormActivity step2WizardFormActivity; private Composite.C1Console.Workflow.Activities.WizardFormActivity step1WizardFormActivity; private SetStateActivity setStateActivity7; private Composite.C1Console.Workflow.Activities.PreviousHandleExternalEventActivity previousHandleExternalEventActivity1; private CodeActivity step1CodeActivity_Initialize; private EventDrivenActivity step2EventDrivenActivity_Previous; private IfElseBranchActivity ifElseBranchActivity1; private Composite.C1Console.Workflow.Activities.DataDialogFormActivity noLocalesDataDialogFormActivity; private IfElseActivity initializeIfElseActivity_LocalesExists; private StateInitializationActivity noLocalesStateInitializationActivity; private StateActivity noLocalesStateActivity; private SetStateActivity setStateActivity9; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private EventDrivenActivity noLocalesEventDrivenActivity_Finish; private StateActivity referencesExistsStateActivity; private StateInitializationActivity stateInitializationActivity1; private SetStateActivity setStateActivity8; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ThereAreReferencesInLocalizedDataActivity4; private IfElseBranchActivity NoReferencesInLocalizedDataActivity3; private IfElseActivity ifElseActivity1; private SetStateActivity setStateActivity10; private Composite.C1Console.Workflow.Activities.WizardFormActivity wizardFormActivity1; private EventDrivenActivity eventDrivenActivity_Next; private SetStateActivity setStateActivity11; private Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity2; private SetStateActivity setStateActivity12; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity4; private EventDrivenActivity eventDrivenActivity_Cancel; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/EnableTypeLocalizationWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="EnableTypeLocalizationWorkflow" Location="30; 30" Size="1079; 914" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="EnableTypeLocalizationWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="EnableTypeLocalizationWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="991" Y="71" /> <ns0:Point X="991" Y="834" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="noLocalesStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity8" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="noLocalesStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="238" /> <ns0:Point X="456" Y="238" /> <ns0:Point X="456" Y="491" /> <ns0:Point X="220" Y="491" /> <ns0:Point X="220" Y="570" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="238" /> <ns0:Point X="343" Y="238" /> <ns0:Point X="343" Y="345" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="referencesExistsStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity10" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="referencesExistsStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="238" /> <ns0:Point X="312" Y="238" /> <ns0:Point X="312" Y="195" /> <ns0:Point X="637" Y="195" /> <ns0:Point X="637" Y="203" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step2StateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="step2StateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="435" Y="410" /> <ns0:Point X="546" Y="410" /> <ns0:Point X="546" Y="503" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="445" Y="434" /> <ns0:Point X="991" Y="434" /> <ns0:Point X="991" Y="834" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step2StateActivity" EventHandlerName="step2EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="639" Y="568" /> <ns0:Point X="811" Y="568" /> <ns0:Point X="811" Y="670" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step2StateActivity" EventHandlerName="step2EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="643" Y="592" /> <ns0:Point X="991" Y="592" /> <ns0:Point X="991" Y="834" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="3" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="step2StateActivity" EventHandlerName="step2EventDrivenActivity_Previous"> <StateDesignerConnector.Segments> <ns0:Point X="652" Y="616" /> <ns0:Point X="663" Y="616" /> <ns0:Point X="663" Y="337" /> <ns0:Point X="343" Y="337" /> <ns0:Point X="343" Y="345" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity9" SourceStateName="noLocalesStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="noLocalesStateActivity" EventHandlerName="noLocalesEventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="331" Y="635" /> <ns0:Point X="991" Y="635" /> <ns0:Point X="991" Y="834" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step2StateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity11" SourceStateName="referencesExistsStateActivity" SourceConnectionEdge="Right" TargetActivity="step2StateActivity" SourceActivity="referencesExistsStateActivity" EventHandlerName="eventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="715" Y="268" /> <ns0:Point X="738" Y="268" /> <ns0:Point X="738" Y="491" /> <ns0:Point X="546" Y="491" /> <ns0:Point X="546" Y="503" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity12" SourceStateName="referencesExistsStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="referencesExistsStateActivity" EventHandlerName="eventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="725" Y="292" /> <ns0:Point X="991" Y="292" /> <ns0:Point X="991" Y="834" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 197" Size="210; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="612; 496" Name="initializeStateInitializationActivity" Location="112; 148"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="592; 415" Name="initializeIfElseActivity_LocalesExists" Location="122; 210"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="381; 315" Name="ifElseBranchActivity1" Location="141; 281"> <IfElseBranchDesigner.Designers> <IfElseDesigner Size="361; 234" Name="ifElseActivity1" Location="151; 343"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 134" Name="ThereAreReferencesInLocalizedDataActivity4" Location="170; 414"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 53" Name="setStateActivity10" Location="180; 476" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 134" Name="NoReferencesInLocalizedDataActivity3" Location="343; 414"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="353; 482" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 315" Name="ifElseBranchActivity2" Location="545; 281"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity8" Location="555; 440" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="904; 834" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="step1StateActivity" Location="238; 345" Size="211; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="step1StateInitializationActivity" Location="246; 376"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="step1CodeActivity_Initialize" Location="256; 438" /> <ActivityDesigner Size="130; 41" Name="step1WizardFormActivity" Location="256; 498" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Next" Location="246; 400"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="nextHandleExternalEventActivity1" Location="256; 462" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="256; 522" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="246; 424"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="256; 486" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="256; 546" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="step2StateActivity" Location="436; 503" Size="220; 126" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step2StateInitializationActivity" Location="444; 534"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step2WizardFormActivity" Location="454; 596" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step2EventDrivenActivity_Finish" Location="444; 558"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="454; 620" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="454; 680" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step2EventDrivenActivity_Cancel" Location="444; 582"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity3" Location="454; 644" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="454; 704" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step2EventDrivenActivity_Previous" Location="444; 606"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="previousHandleExternalEventActivity1" Location="454; 668" /> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="454; 728" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="709; 670" Size="205; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="finalizeStateInitializationActivity" Location="717; 701"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity_Finalize" Location="727; 763" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="noLocalesStateActivity" Location="106; 570" Size="229; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="noLocalesStateInitializationActivity" Location="114; 601"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="noLocalesDataDialogFormActivity" Location="124; 663" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="noLocalesEventDrivenActivity_Finish" Location="114; 625"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity2" Location="124; 687" /> <SetStateDesigner Size="130; 41" Name="setStateActivity9" Location="124; 747" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="referencesExistsStateActivity" Location="546; 203" Size="183; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="stateInitializationActivity1" Location="554; 234"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="wizardFormActivity1" Location="564; 296" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 194" Name="eventDrivenActivity_Next" Location="554; 258"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="nextHandleExternalEventActivity2" Location="564; 320" /> <SetStateDesigner Size="130; 53" Name="setStateActivity11" Location="564; 380" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 194" Name="eventDrivenActivity_Cancel" Location="554; 282"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity4" Location="564; 344" /> <SetStateDesigner Size="130; 53" Name="setStateActivity12" Location="564; 404" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/LocalizeDataWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Transactions; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.Core.Linq; using Composite.Core.Types; using Composite.Data; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.Transactions; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Plugins_GeneratedDataTypesElementProvider; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { public sealed partial class LocalizeDataWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public LocalizeDataWorkflow() { InitializeComponent(); } private void ValidateLocalizeProcess(object sender, ConditionalEventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; ILocalizedControlled data = dataEntityToken.Data as ILocalizedControlled; IEnumerable<ReferenceFailingPropertyInfo> referenceFailingPropertyInfos = DataLocalizationFacade.GetReferencingLocalizeFailingProperties(data).Evaluate(); if (referenceFailingPropertyInfos.Any(f => f.OptionalReferenceWithValue == false)) { List<string> row = new List<string>(); row.Add(Texts.LocalizeDataWorkflow_ShowError_Description); foreach (ReferenceFailingPropertyInfo referenceFailingPropertyInfo in referenceFailingPropertyInfos.Where(f => f.OptionalReferenceWithValue == false)) { row.Add(Texts.LocalizeDataWorkflow_ShowError_FieldErrorFormat( referenceFailingPropertyInfo.DataFieldDescriptor.Name, referenceFailingPropertyInfo.ReferencedType.GetTypeTitle(), referenceFailingPropertyInfo.OriginLocaleDataValue.GetLabel())); } List<List<string>> rows = new List<List<string>> { row }; this.UpdateBinding("ErrorHeader", new List<string> { "Fields" }); this.UpdateBinding("Errors", rows); e.Result = false; } else { e.Result = true; } } private void localizeCodeActivity_ExecuteCode(object sender, EventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; ILocalizedControlled data = dataEntityToken.Data as ILocalizedControlled; CultureInfo targetCultureInfo = UserSettings.ActiveLocaleCultureInfo; if (ExistsInLocale(data, targetCultureInfo)) { string title = Texts.LocalizeDataWorkflow_ShowError_LayoutLabel; string description = Texts.LocalizeDataWorkflow_ShowError_AlreadyTranslated; var messageBox = new MessageBoxMessageQueueItem { DialogType = DialogType.Message, Message = description, Title = title }; ConsoleMessageQueueFacade.Enqueue(messageBox, GetCurrentConsoleId()); return; } IEnumerable<ReferenceFailingPropertyInfo> referenceFailingPropertyInfos = DataLocalizationFacade.GetReferencingLocalizeFailingProperties(data).Evaluate(); IData newData; using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { data = data.GetTranslationSource(); using (new DataScope(targetCultureInfo)) { newData = DataFacade.BuildNew(data.DataSourceId.InterfaceType); data.ProjectedCopyTo(newData); ILocalizedControlled localizedControlled = newData as ILocalizedControlled; localizedControlled.SourceCultureName = targetCultureInfo.Name; if (newData is IPublishControlled) { IPublishControlled publishControlled = newData as IPublishControlled; publishControlled.PublicationStatus = GenericPublishProcessController.Draft; } foreach (ReferenceFailingPropertyInfo referenceFailingPropertyInfo in referenceFailingPropertyInfos) { PropertyInfo propertyInfo = data.DataSourceId.InterfaceType.GetPropertiesRecursively().Single(f => f.Name == referenceFailingPropertyInfo.DataFieldDescriptor.Name); if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { propertyInfo.SetValue(newData, null, null); } else if (propertyInfo.PropertyType == typeof(string)) { propertyInfo.SetValue(newData, null, null); } else { propertyInfo.SetValue(newData, referenceFailingPropertyInfo.DataFieldDescriptor.DefaultValue.Value, null); } } newData = DataFacade.AddNew(newData, false, false, true); } EntityTokenCacheFacade.ClearCache(data.GetDataEntityToken()); EntityTokenCacheFacade.ClearCache(newData.GetDataEntityToken()); transactionScope.Complete(); } ParentTreeRefresher parentTreeRefresher = this.CreateParentTreeRefresher(); parentTreeRefresher.PostRefreshMesseges(newData.GetDataEntityToken()); if (this.Payload == "Global") { this.ExecuteWorklow(newData.GetDataEntityToken(), typeof(EditDataWorkflow)); } else if (this.Payload == "Pagefolder") { this.ExecuteWorklow(newData.GetDataEntityToken(), WorkflowFacade.GetWorkflowType("Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper.EditAssociatedDataWorkflow")); } } private static bool ExistsInLocale(IData data, CultureInfo locale) { Type dataType = data.DataSourceId.InterfaceType; MethodInfo method = StaticReflection.GetGenericMethodInfo(a => DataFacade.GetDataFromOtherLocale((IData)null, null)) .MakeGenericMethod(new[] { dataType }); object result = method.Invoke(null, new object[] { data, locale }); if (result == null) return false; var enumerable = result as IEnumerable<object>; Verify.IsNotNull(enumerable, "Enumeration expected"); return enumerable.Any(); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/LocalizeDataWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { partial class LocalizeDataWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.wizardFormActivity1 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.localizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElseActivity_ValidateLocalizeProcess = new System.Workflow.Activities.IfElseActivity(); this.showErrorStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.showErrorEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.localizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.showErrorStateActivity = new System.Workflow.Activities.StateActivity(); this.localizeStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "showErrorStateActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "localizeStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity5); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity2); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateLocalizeProcess); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // wizardFormActivity1 // this.wizardFormActivity1.ContainerLabel = null; this.wizardFormActivity1.FormDefinitionFileName = "\\Administrative\\LocalizeData.xml"; this.wizardFormActivity1.Name = "wizardFormActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // localizeCodeActivity // this.localizeCodeActivity.Name = "localizeCodeActivity"; this.localizeCodeActivity.ExecuteCode += new System.EventHandler(this.localizeCodeActivity_ExecuteCode); // // ifElseActivity_ValidateLocalizeProcess // this.ifElseActivity_ValidateLocalizeProcess.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity_ValidateLocalizeProcess.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity_ValidateLocalizeProcess.Name = "ifElseActivity_ValidateLocalizeProcess"; // // showErrorStateInitializationActivity // this.showErrorStateInitializationActivity.Activities.Add(this.wizardFormActivity1); this.showErrorStateInitializationActivity.Name = "showErrorStateInitializationActivity"; // // showErrorEventDrivenActivity_Finish // this.showErrorEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.showErrorEventDrivenActivity_Finish.Activities.Add(this.setStateActivity4); this.showErrorEventDrivenActivity_Finish.Name = "showErrorEventDrivenActivity_Finish"; // // localizeStateInitializationActivity // this.localizeStateInitializationActivity.Activities.Add(this.localizeCodeActivity); this.localizeStateInitializationActivity.Activities.Add(this.setStateActivity3); this.localizeStateInitializationActivity.Name = "localizeStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.ifElseActivity_ValidateLocalizeProcess); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // showErrorStateActivity // this.showErrorStateActivity.Activities.Add(this.showErrorEventDrivenActivity_Finish); this.showErrorStateActivity.Activities.Add(this.showErrorStateInitializationActivity); this.showErrorStateActivity.Name = "showErrorStateActivity"; // // localizeStateActivity // this.localizeStateActivity.Activities.Add(this.localizeStateInitializationActivity); this.localizeStateActivity.Name = "localizeStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // LocalizeDataWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.localizeStateActivity); this.Activities.Add(this.showErrorStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "LocalizeDataWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private CodeActivity localizeCodeActivity; private SetStateActivity setStateActivity2; private StateInitializationActivity localizeStateInitializationActivity; private StateActivity localizeStateActivity; private SetStateActivity setStateActivity3; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity_ValidateLocalizeProcess; private EventDrivenActivity showErrorEventDrivenActivity_Finish; private StateActivity showErrorStateActivity; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private StateInitializationActivity showErrorStateInitializationActivity; private Composite.C1Console.Workflow.Activities.WizardFormActivity wizardFormActivity1; private SetStateActivity setStateActivity5; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/LocalizeDataWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1146; 986" AutoSizeMargin="16; 24" Location="30; 30" Name="LocalizeDataWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="381; 303" Location="98; 169"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="ifElseActivity_ValidateLocalizeProcess" Size="361; 222" Location="108; 231"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 122" Location="127; 302"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="137; 364" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 122" Location="300; 302"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="310; 364" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="207; 80" AutoSizeMargin="16; 24" Location="330; 388" Name="localizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="localizeStateInitializationActivity" Size="150; 182" Location="338; 419"> <StateInitializationDesigner.Designers> <CodeDesigner Name="localizeCodeActivity" Size="130; 41" Location="348; 481" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="348; 541" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="230; 80" AutoSizeMargin="16; 24" Location="233; 576" Name="showErrorStateActivity"> <StateDesigner.Designers> <EventDrivenDesigner Name="showErrorEventDrivenActivity_Finish" Size="150; 182" Location="241; 631"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="251; 693" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="251; 753" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateInitializationDesigner Name="showErrorStateInitializationActivity" Size="150; 122" Location="241; 607"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizardFormActivity1" Size="130; 41" Location="251; 669" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="LocalizeDataWorkflow" TargetConnectionIndex="0" SourceStateName="LocalizeDataWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="localizeStateActivity" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="localizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="433" Y="179" /> <ns0:Point X="433" Y="388" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="showErrorStateActivity" SetStateName="setStateActivity5" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="showErrorStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="312" Y="179" /> <ns0:Point X="312" Y="564" /> <ns0:Point X="348" Y="564" /> <ns0:Point X="348" Y="576" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity3" SourceActivity="localizeStateActivity" TargetConnectionIndex="0" SourceStateName="localizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="localizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="533" Y="429" /> <ns0:Point X="1058" Y="429" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity4" SourceActivity="showErrorStateActivity" TargetConnectionIndex="0" SourceStateName="showErrorStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="showErrorEventDrivenActivity_Finish" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="459" Y="641" /> <ns0:Point X="1058" Y="641" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/RemoveTypeFromWhiteListWorkflow.cs ================================================ using System; using Composite.C1Console.Actions; using Composite.Data; using Composite.Data.Types; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { public sealed partial class RemoveTypeFromWhiteListWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public RemoveTypeFromWhiteListWorkflow() { InitializeComponent(); } private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { GeneratedDataTypesElementProviderTypeEntityToken castedEntityToken = (GeneratedDataTypesElementProviderTypeEntityToken)this.EntityToken; DataFacade.Delete<IGeneratedTypeWhiteList>(f => f.TypeManagerTypeName == castedEntityToken.SerializedTypeName); ParentTreeRefresher parentTreeRefresher = this.CreateParentTreeRefresher(); parentTreeRefresher.PostRefreshMesseges(this.EntityToken, 3); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/RemoveTypeFromWhiteListWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.GeneratedDataTypesElementProvider { partial class RemoveTypeFromWhiteListWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalizeStateActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity3); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // RemoveTypeFromWhiteListWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "RemoveTypeFromWhiteListWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity3; private CodeActivity finalizeCodeActivity; private SetStateActivity setStateActivity2; private StateInitializationActivity finalizeStateInitializationActivity; private StateActivity finalizeStateActivity; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/GeneratedDataTypesElementProvider/RemoveTypeFromWhiteListWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="RemoveTypeFromWhiteListWorkflow" Location="30; 30" Size="1183; 996" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="RemoveTypeFromWhiteListWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="RemoveTypeFromWhiteListWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="464" Y="179" /> <ns0:Point X="464" Y="341" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="563" Y="382" /> <ns0:Point X="1058" Y="382" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="108; 231" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="finalizeStateActivity" Location="362; 341" Size="205; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="finalizeStateInitializationActivity" Location="546; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity" Location="556; 210" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="556; 270" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/LocalizationElementProvider/AddSystemLocaleWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Events; using Composite.C1Console.Workflow; using Composite.Core.Localization; using Composite.Core.ResourceSystem; using Composite.Data; using Composite.Data.Types; namespace Composite.Plugins.Elements.ElementProviders.LocalizationElementProvider { [EntityTokenLock] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddSystemLocaleWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddSystemLocaleWorkflow() { InitializeComponent(); } private void HasAnyWhiteListedLocales(object sender, ConditionalEventArgs e) { List<string> alreadyAddedCultureNames = (from d in DataFacade.GetData<ISystemActiveLocale>() select d.CultureName).ToList(); IEnumerable<CultureInfo> cultures = from cul in DataLocalizationFacade.WhiteListedLocales where !alreadyAddedCultureNames.Contains(cul.Name) orderby cul.DisplayName select cul; e.Result = cultures.Any(); } private void UrlMappingNameInUse(object sender, ConditionalEventArgs e) { string urlMappingName = this.GetBinding<string>("UrlMappingName"); e.Result = LocalizationFacade.IsUrlMappingNameInUse(urlMappingName); } private void initializeCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { List<string> alreadyAddedCultureNames = (from d in DataFacade.GetData<ISystemActiveLocale>() select d.CultureName).ToList(); IEnumerable<CultureInfo> cultures = from cul in DataLocalizationFacade.WhiteListedLocales where alreadyAddedCultureNames.Contains(cul.Name) == false orderby cul.DisplayName select cul; var culturesDictionary = cultures.ToDictionary(f => f.Name, DataLocalizationFacade.GetCultureTitle); this.Bindings = new Dictionary<string, object> { {"CultureName", ""}, {"RegionLanguageList", culturesDictionary}, {"UrlMappingName", ""}, {"AccessToAllUsers", true} }; } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { string cultureName = this.GetBinding<string>("CultureName"); string urlMappingName = this.GetBinding<string>("UrlMappingName"); bool accessToAllUsers = this.GetBinding<bool>("AccessToAllUsers"); LocalizationFacade.AddLocale(cultureName, urlMappingName, accessToAllUsers); this.CloseCurrentView(); ConsoleMessageQueueFacade.Enqueue(new BroadcastMessageQueueItem { Name = "LocalesUpdated", Value = "" }, null); var specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(this.EntityToken); var newLocaleDataItem = DataFacade.GetData<ISystemActiveLocale>().FirstOrDefault(l => l.CultureName == cultureName); if (newLocaleDataItem != null) { SelectElement(newLocaleDataItem.GetDataEntityToken()); } } private void updateRulMappingNameCodeActivity_Update_ExecuteCode(object sender, EventArgs e) { string urlMappingName = GetDefaultUrlMappingNameFromCultureName( this.GetBinding<string>("CultureName") ); this.UpdateBinding("UrlMappingName", urlMappingName); } private string GetDefaultUrlMappingNameFromCultureName(string cultureName) { string urlMappingName = cultureName; if (urlMappingName.Contains("-")) { urlMappingName = urlMappingName.Substring(0, urlMappingName.IndexOf("-", StringComparison.Ordinal)); } return urlMappingName; } private void codeActivity_ShowBalloon_ExecuteCode(object sender, EventArgs e) { this.ShowFieldMessage("UrlMappingName", StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "AddSystemLocaleWorkflow.UrlMappingName.InUseMessage")); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/LocalizationElementProvider/AddSystemLocaleWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.LocalizationElementProvider { partial class AddSystemLocaleWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity_ShowBalloon = new System.Workflow.Activities.CodeActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.showConsoleMessageBoxActivity1 = new Composite.C1Console.Workflow.Activities.ShowConsoleMessageBoxActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.rerenderViewActivity1 = new Composite.C1Console.Workflow.Activities.RerenderViewActivity(); this.updateRulMappingNameCodeActivity_Update = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.customEvent01HandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CustomEvent01HandleExternalEventActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElse_UrlMappingNameInUse = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step1DataDialogFormActivity = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.ifElseActivity_HasAnyWhiteListedLocales = new System.Workflow.Activities.IfElseActivity(); this.updateUrlMappingNameStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_SelectionChange = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Ok = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.updateUrlMappingNameStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // codeActivity_ShowBalloon // this.codeActivity_ShowBalloon.Name = "codeActivity_ShowBalloon"; this.codeActivity_ShowBalloon.ExecuteCode += new System.EventHandler(this.codeActivity_ShowBalloon_ExecuteCode); // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "finalStateActivity"; // // showConsoleMessageBoxActivity1 // this.showConsoleMessageBoxActivity1.DialogType = Composite.C1Console.Events.DialogType.Warning; this.showConsoleMessageBoxActivity1.Message = "${Composite.Plugins.LocalizationElementProvider, AddSystemLocaleWorkflow." + "NoMoreLocalesMessage}"; this.showConsoleMessageBoxActivity1.Name = "showConsoleMessageBoxActivity1"; this.showConsoleMessageBoxActivity1.Title = "${Composite.Plugins.LocalizationElementProvider, AddSystemLocaleWorkflow." + "NoMoreLocalesTitle}"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // initializeCodeActivity_Initialize // this.initializeCodeActivity_Initialize.Name = "initializeCodeActivity_Initialize"; this.initializeCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_Initialize_ExecuteCode); // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity3); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.codeActivity_ShowBalloon); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.UrlMappingNameInUse); this.ifElseBranchActivity3.Condition = codecondition1; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.showConsoleMessageBoxActivity1); this.ifElseBranchActivity2.Activities.Add(this.setStateActivity8); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.initializeCodeActivity_Initialize); this.ifElseBranchActivity1.Activities.Add(this.setStateActivity2); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.HasAnyWhiteListedLocales); this.ifElseBranchActivity1.Condition = codecondition2; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "step1StateActivity"; // // rerenderViewActivity1 // this.rerenderViewActivity1.Name = "rerenderViewActivity1"; // // updateRulMappingNameCodeActivity_Update // this.updateRulMappingNameCodeActivity_Update.Name = "updateRulMappingNameCodeActivity_Update"; this.updateRulMappingNameCodeActivity_Update.ExecuteCode += new System.EventHandler(this.updateRulMappingNameCodeActivity_Update_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "updateUrlMappingNameStateActivity"; // // customEvent01HandleExternalEventActivity1 // this.customEvent01HandleExternalEventActivity1.EventName = "CustomEvent01"; this.customEvent01HandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.customEvent01HandleExternalEventActivity1.Name = "customEvent01HandleExternalEventActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // ifElse_UrlMappingNameInUse // this.ifElse_UrlMappingNameInUse.Activities.Add(this.ifElseBranchActivity3); this.ifElse_UrlMappingNameInUse.Activities.Add(this.ifElseBranchActivity4); this.ifElse_UrlMappingNameInUse.Name = "ifElse_UrlMappingNameInUse"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // step1DataDialogFormActivity // this.step1DataDialogFormActivity.ContainerLabel = null; this.step1DataDialogFormActivity.FormDefinitionFileName = "\\Administrative\\AddSystemLocaleStep1.xml"; this.step1DataDialogFormActivity.Name = "step1DataDialogFormActivity"; // // ifElseActivity_HasAnyWhiteListedLocales // this.ifElseActivity_HasAnyWhiteListedLocales.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity_HasAnyWhiteListedLocales.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity_HasAnyWhiteListedLocales.Name = "ifElseActivity_HasAnyWhiteListedLocales"; // // updateUrlMappingNameStateInitializationActivity // this.updateUrlMappingNameStateInitializationActivity.Activities.Add(this.updateRulMappingNameCodeActivity_Update); this.updateUrlMappingNameStateInitializationActivity.Activities.Add(this.rerenderViewActivity1); this.updateUrlMappingNameStateInitializationActivity.Activities.Add(this.setStateActivity7); this.updateUrlMappingNameStateInitializationActivity.Name = "updateUrlMappingNameStateInitializationActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_SelectionChange // this.step1EventDrivenActivity_SelectionChange.Activities.Add(this.customEvent01HandleExternalEventActivity1); this.step1EventDrivenActivity_SelectionChange.Activities.Add(this.setStateActivity6); this.step1EventDrivenActivity_SelectionChange.Name = "step1EventDrivenActivity_SelectionChange"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity5); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Ok // this.step1EventDrivenActivity_Ok.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Ok.Activities.Add(this.ifElse_UrlMappingNameInUse); this.step1EventDrivenActivity_Ok.Name = "step1EventDrivenActivity_Ok"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1DataDialogFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.ifElseActivity_HasAnyWhiteListedLocales); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // updateUrlMappingNameStateActivity // this.updateUrlMappingNameStateActivity.Activities.Add(this.updateUrlMappingNameStateInitializationActivity); this.updateUrlMappingNameStateActivity.Name = "updateUrlMappingNameStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Ok); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_SelectionChange); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // AddSystemLocaleWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.updateUrlMappingNameStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddSystemLocaleWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private CodeActivity finalizeCodeActivity_Finalize; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.DataDialogFormActivity step1DataDialogFormActivity; private SetStateActivity setStateActivity2; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Ok; private StateInitializationActivity step1StateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity4; private CodeActivity initializeCodeActivity_Initialize; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private SetStateActivity setStateActivity7; private CodeActivity updateRulMappingNameCodeActivity_Update; private SetStateActivity setStateActivity6; private Composite.C1Console.Workflow.Activities.CustomEvent01HandleExternalEventActivity customEvent01HandleExternalEventActivity1; private StateInitializationActivity updateUrlMappingNameStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_SelectionChange; private StateActivity updateUrlMappingNameStateActivity; private Composite.C1Console.Workflow.Activities.RerenderViewActivity rerenderViewActivity1; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity_HasAnyWhiteListedLocales; private SetStateActivity setStateActivity8; private Composite.C1Console.Workflow.Activities.ShowConsoleMessageBoxActivity showConsoleMessageBoxActivity1; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElse_UrlMappingNameInUse; private CodeActivity codeActivity_ShowBalloon; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/LocalizationElementProvider/AddSystemLocaleWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="AddSystemLocaleWorkflow" Location="30; 30" Size="1146; 878" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="AddSystemLocaleWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="AddSystemLocaleWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="389" Y="179" /> <ns0:Point X="389" Y="371" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity8" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="1058" Y="179" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Ok"> <StateDesignerConnector.Segments> <ns0:Point X="447" Y="436" /> <ns0:Point X="741" Y="436" /> <ns0:Point X="741" Y="529" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="466" Y="460" /> <ns0:Point X="1058" Y="460" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="updateUrlMappingNameStateActivity" SourceConnectionIndex="3" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="updateUrlMappingNameStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_SelectionChange"> <StateDesignerConnector.Segments> <ns0:Point X="516" Y="484" /> <ns0:Point X="943" Y="484" /> <ns0:Point X="943" Y="237" /> <ns0:Point X="736" Y="237" /> <ns0:Point X="736" Y="245" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="840" Y="570" /> <ns0:Point X="1058" Y="570" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="updateUrlMappingNameStateActivity" SourceConnectionEdge="Left" TargetActivity="step1StateActivity" SourceActivity="updateUrlMappingNameStateActivity" EventHandlerName="updateUrlMappingNameStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="595" Y="286" /> <ns0:Point X="389" Y="286" /> <ns0:Point X="389" Y="371" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 363" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="361; 282" Name="ifElseActivity_HasAnyWhiteListedLocales" Location="108; 231"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity1" Location="127; 302"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity_Initialize" Location="137; 364" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="137; 424" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity2" Location="300; 302"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="showConsoleMessageBoxActivity1" Location="310; 364" /> <SetStateDesigner Size="130; 41" Name="setStateActivity8" Location="310; 424" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="step1StateActivity" Location="259; 371" Size="261; 126" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="267; 402"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step1DataDialogFormActivity" Location="277; 464" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="381; 363" Name="step1EventDrivenActivity_Ok" Location="267; 426"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="392; 488" /> <IfElseDesigner Size="361; 222" Name="ifElse_UrlMappingNameInUse" Location="277; 548"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity3" Location="296; 619"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="codeActivity_ShowBalloon" Location="306; 681" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity4" Location="469; 619"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="479; 681" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="267; 450"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="277; 512" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="277; 572" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_SelectionChange" Location="267; 474"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="customEvent01HandleExternalEventActivity1" Location="277; 536" /> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="277; 596" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="639; 529" Size="205; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="finalizeStateInitializationActivity" Location="338; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity_Finalize" Location="348; 210" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="348; 270" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="updateUrlMappingNameStateActivity" Location="591; 245" Size="290; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="updateUrlMappingNameStateInitializationActivity" Location="599; 276"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="updateRulMappingNameCodeActivity_Update" Location="609; 338" /> <ActivityDesigner Size="130; 41" Name="rerenderViewActivity1" Location="609; 398" /> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="609; 458" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/LocalizationElementProvider/DefineDefaultActiveLocaleWorkflow.cs ================================================ using System; using System.Globalization; using Composite.C1Console.Actions; using Composite.Data; using Composite.Data.Types; using Composite.Core.Localization; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.LocalizationElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DefineDefaultActiveLocaleWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DefineDefaultActiveLocaleWorkflow() { InitializeComponent(); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; ISystemActiveLocale systemActiveLocale = (ISystemActiveLocale)dataEntityToken.Data; CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture(systemActiveLocale.CultureName); if (LocalizationFacade.SetDefaultLocale(cultureInfo)) { ParentTreeRefresher parentTreeRefresher = this.CreateParentTreeRefresher(); parentTreeRefresher.PostRefreshMesseges(this.EntityToken); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/LocalizationElementProvider/DefineDefaultActiveLocaleWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.LocalizationElementProvider { partial class DefineDefaultActiveLocaleWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalizeStateActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity5); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // DefineDefaultActiveLocaleWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "DefineDefaultActiveLocaleWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity5; private StateInitializationActivity finalizeStateInitializationActivity; private StateActivity finalizeStateActivity; private CodeActivity finalizeCodeActivity_Finalize; private SetStateActivity setStateActivity2; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/LocalizationElementProvider/DefineDefaultActiveLocaleWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="DefineDefaultActiveLocaleWorkflow" Location="30; 30" Size="1146; 980" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="DefineDefaultActiveLocaleWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="DefineDefaultActiveLocaleWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="662" Y="481" /> <ns0:Point X="1058" Y="481" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="563" Y="179" /> <ns0:Point X="563" Y="440" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="108; 231" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="finalizeStateActivity" Location="461; 440" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="finalizeStateInitializationActivity" Location="469; 471"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity_Finalize" Location="479; 533" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="479; 593" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/LocalizationElementProvider/EditSystemLocaleWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Workflow.Activities; using Composite.Data; using Composite.Data.Types; using Composite.Core.ResourceSystem; using Composite.C1Console.Workflow; using Composite.Core.Localization; namespace Composite.Plugins.Elements.ElementProviders.LocalizationElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditSystemLocaleWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditSystemLocaleWorkflow() { InitializeComponent(); } private void UrlMappingNameInUse(object sender, ConditionalEventArgs e) { ISystemActiveLocale systemActiveLocale = this.GetBinding<ISystemActiveLocale>("SystemActiveLocale"); e.Result = LocalizationFacade.IsUrlMappingNameInUse(systemActiveLocale.CultureName, systemActiveLocale.UrlMappingName); } private void initializeCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; ISystemActiveLocale systemActiveLocale = (ISystemActiveLocale)dataEntityToken.Data; this.Bindings.Add("SystemActiveLocale", systemActiveLocale); } private void saveCodeActivity_Save_ExecuteCode(object sender, EventArgs e) { ISystemActiveLocale systemActiveLocale = this.GetBinding<ISystemActiveLocale>("SystemActiveLocale"); DataFacade.Update(systemActiveLocale); SetSaveStatus(true); } private void editCodeActivity_ShowBaloon_ExecuteCode(object sender, EventArgs e) { this.ShowFieldMessage("SystemActiveLocale.UrlMappingName", StringResourceSystemFacade.GetString("Composite.Plugins.LocalizationElementProvider", "EditSystemLocaleWorkflow.UrlMappingName.InUseMessage")); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/LocalizationElementProvider/EditSystemLocaleWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.LocalizationElementProvider { partial class EditSystemLocaleWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.editCodeActivity_ShowBaloon = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity_Save = new System.Workflow.Activities.CodeActivity(); this.ifElse_UrlMappingNameInUse = new System.Workflow.Activities.IfElseActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.editDocumentFormActivity = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editEventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "saveStateActivity"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "editStateActivity"; // // editCodeActivity_ShowBaloon // this.editCodeActivity_ShowBaloon.Name = "editCodeActivity_ShowBaloon"; this.editCodeActivity_ShowBaloon.ExecuteCode += new System.EventHandler(this.editCodeActivity_ShowBaloon_ExecuteCode); // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity2); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.editCodeActivity_ShowBaloon); this.ifElseBranchActivity1.Activities.Add(this.setStateActivity5); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.UrlMappingNameInUse); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "editStateActivity"; // // saveCodeActivity_Save // this.saveCodeActivity_Save.Name = "saveCodeActivity_Save"; this.saveCodeActivity_Save.ExecuteCode += new System.EventHandler(this.saveCodeActivity_Save_ExecuteCode); // // ifElse_UrlMappingNameInUse // this.ifElse_UrlMappingNameInUse.Activities.Add(this.ifElseBranchActivity1); this.ifElse_UrlMappingNameInUse.Activities.Add(this.ifElseBranchActivity2); this.ifElse_UrlMappingNameInUse.Name = "ifElse_UrlMappingNameInUse"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // editDocumentFormActivity // this.editDocumentFormActivity.ContainerLabel = null; this.editDocumentFormActivity.CustomToolbarDefinitionFileName = null; this.editDocumentFormActivity.FormDefinitionFileName = "\\Administrative\\EditSystemLocaleEdit.xml"; this.editDocumentFormActivity.Name = "editDocumentFormActivity"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // initializeCodeActivity_Initialize // this.initializeCodeActivity_Initialize.Name = "initializeCodeActivity_Initialize"; this.initializeCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_Initialize_ExecuteCode); // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.saveCodeActivity_Save); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity3); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // editEventDrivenActivity_Save // this.editEventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.editEventDrivenActivity_Save.Activities.Add(this.ifElse_UrlMappingNameInUse); this.editEventDrivenActivity_Save.Name = "editEventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.editDocumentFormActivity); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_Initialize); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.saveStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_Save); this.editStateActivity.Name = "editStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // EditSystemLocaleWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "EditSystemLocaleWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity2; private Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity4; private CodeActivity initializeCodeActivity_Initialize; private StateInitializationActivity saveStateInitializationActivity; private EventDrivenActivity editEventDrivenActivity_Save; private StateInitializationActivity editStateInitializationActivity; private StateActivity saveStateActivity; private StateActivity editStateActivity; private CodeActivity saveCodeActivity_Save; private Composite.C1Console.Workflow.Activities.DocumentFormActivity editDocumentFormActivity; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElse_UrlMappingNameInUse; private SetStateActivity setStateActivity5; private CodeActivity editCodeActivity_ShowBaloon; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/LocalizationElementProvider/EditSystemLocaleWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="EditSystemLocaleWorkflow" Location="30; 30" Size="1148; 996" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="EditSystemLocaleWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="EditSystemLocaleWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="324" Y="179" /> <ns0:Point X="324" Y="358" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="editStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="editStateActivity" EventHandlerName="editEventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="586" Y="169" /> <ns0:Point X="597" Y="169" /> <ns0:Point X="597" Y="96" /> <ns0:Point X="493" Y="96" /> <ns0:Point X="493" Y="104" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="saveStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="editStateActivity" SourceConnectionEdge="Right" TargetActivity="saveStateActivity" SourceActivity="editStateActivity" EventHandlerName="editEventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="417" Y="423" /> <ns0:Point X="617" Y="423" /> <ns0:Point X="617" Y="516" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="saveStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="saveStateActivity" EventHandlerName="saveStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="710" Y="557" /> <ns0:Point X="724" Y="557" /> <ns0:Point X="724" Y="350" /> <ns0:Point X="324" Y="350" /> <ns0:Point X="324" Y="358" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity_Initialize" Location="108; 231" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="108; 291" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="editStateActivity" Location="228; 358" Size="193; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="editStateInitializationActivity" Location="405; 135"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="editDocumentFormActivity" Location="415; 197" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="381; 423" Name="editEventDrivenActivity_Save" Location="413; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="saveHandleExternalEventActivity1" Location="538; 210" /> <IfElseDesigner Size="361; 282" Name="ifElse_UrlMappingNameInUse" Location="423; 270"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity1" Location="442; 341"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="editCodeActivity_ShowBaloon" Location="452; 403" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="452; 463" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity2" Location="615; 341"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="625; 433" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="saveStateActivity" Location="521; 516" Size="193; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="saveStateInitializationActivity" Location="529; 547"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="saveCodeActivity_Save" Location="539; 609" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="539; 669" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/LocalizationElementProvider/RemoveSystemLocaleWorkflow.cs ================================================ using System; using System.Globalization; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.Types; using Composite.Core.Localization; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.LocalizationElementProvider { [EntityTokenLock] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class RemoveSystemLocaleWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public RemoveSystemLocaleWorkflow() { InitializeComponent(); } private CultureInfo CreateCultureInfo() { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; ISystemActiveLocale systemActiveLocale = (ISystemActiveLocale)dataEntityToken.Data; CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture(systemActiveLocale.CultureName); return cultureInfo; } private void IsLastLocale(object sender, ConditionalEventArgs e) { e.Result = LocalizationFacade.IsLastLocale(); } private void IsTypesUsingLocalization(object sender, ConditionalEventArgs e) { e.Result = LocalizationFacade.IsTypesUsingLocalization(); } private void IsOnlyActiveLocaleForSomeUsers(object sender, ConditionalEventArgs e) { CultureInfo cultureInfo = CreateCultureInfo(); e.Result = LocalizationFacade.IsOnlyActiveLocaleForSomeUsers(cultureInfo); } private void IsCurrentDefaultLocale(object sender, ConditionalEventArgs e) { CultureInfo cultureInfo = CreateCultureInfo(); e.Result = LocalizationFacade.IsDefaultLocale(cultureInfo); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { DeleteTreeRefresher deleteTreeRefresher = this.CreateDeleteTreeRefresher(this.EntityToken); ISystemActiveLocale systemActiveLocale = this.GetDataItemFromEntityToken<ISystemActiveLocale>(); var cultureName = systemActiveLocale.CultureName; var consolesToBeUpdated = (from consoleInformation in DataFacade.GetData<IUserConsoleInformation>() join userSettings in DataFacade.GetData<IUserSettings>() on consoleInformation.Username equals userSettings.Username where userSettings.CurrentActiveLocaleCultureName == cultureName || userSettings.ForeignLocaleCultureName == cultureName select consoleInformation.ConsoleId).ToList(); LocalizationFacade.RemoveLocale(cultureName); foreach (var consoleId in consolesToBeUpdated) { ConsoleMessageQueueFacade.Enqueue(new CollapseAndRefreshConsoleMessageQueueItem(), consoleId); } ConsoleMessageQueueFacade.Enqueue(new BroadcastMessageQueueItem { Name = "LocalesUpdated", Value = "" }, null); SelectElement(new LocalizationElementProviderRootEntityToken()); deleteTreeRefresher.PostRefreshMesseges(); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/LocalizationElementProvider/RemoveSystemLocaleWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.LocalizationElementProvider { partial class RemoveSystemLocaleWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition3 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition4 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity11 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.if_IsCurrentDefaultLocale = new System.Workflow.Activities.IfElseActivity(); this.if_IsTypesUsingLocalization = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity6 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity5 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity8 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity7 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step2WizardFormActivity = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity14 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.abortWizardFormActivity = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.if_IsLastLocale = new System.Workflow.Activities.IfElseActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step3EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step2EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step2StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.abortEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.abortStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step2StateActivity = new System.Workflow.Activities.StateActivity(); this.abortStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "step2StateActivity"; // // setStateActivity11 // this.setStateActivity11.Name = "setStateActivity11"; this.setStateActivity11.TargetStateName = "abortStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsCurrentDefaultLocale); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity10); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.setStateActivity11); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsTypesUsingLocalization); this.ifElseBranchActivity3.Condition = codecondition2; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // if_IsCurrentDefaultLocale // this.if_IsCurrentDefaultLocale.Activities.Add(this.ifElseBranchActivity1); this.if_IsCurrentDefaultLocale.Activities.Add(this.ifElseBranchActivity2); this.if_IsCurrentDefaultLocale.Name = "if_IsCurrentDefaultLocale"; // // if_IsTypesUsingLocalization // this.if_IsTypesUsingLocalization.Activities.Add(this.ifElseBranchActivity3); this.if_IsTypesUsingLocalization.Activities.Add(this.ifElseBranchActivity4); this.if_IsTypesUsingLocalization.Name = "if_IsTypesUsingLocalization"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "step2StateActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "abortStateActivity"; // // ifElseBranchActivity6 // this.ifElseBranchActivity6.Activities.Add(this.if_IsCurrentDefaultLocale); this.ifElseBranchActivity6.Name = "ifElseBranchActivity6"; // // ifElseBranchActivity5 // this.ifElseBranchActivity5.Activities.Add(this.if_IsTypesUsingLocalization); codecondition3.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsCurrentDefaultLocale); this.ifElseBranchActivity5.Condition = codecondition3; this.ifElseBranchActivity5.Name = "ifElseBranchActivity5"; // // ifElseBranchActivity8 // this.ifElseBranchActivity8.Activities.Add(this.setStateActivity3); this.ifElseBranchActivity8.Name = "ifElseBranchActivity8"; // // ifElseBranchActivity7 // this.ifElseBranchActivity7.Activities.Add(this.setStateActivity2); codecondition4.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsOnlyActiveLocaleForSomeUsers); this.ifElseBranchActivity7.Condition = codecondition4; this.ifElseBranchActivity7.Name = "ifElseBranchActivity7"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // step2WizardFormActivity // this.step2WizardFormActivity.ContainerLabel = null; this.step2WizardFormActivity.FormDefinitionFileName = "\\Administrative\\RemoveSystemLocaleStep2.xml"; this.step2WizardFormActivity.Name = "step2WizardFormActivity"; // // setStateActivity14 // this.setStateActivity14.Name = "setStateActivity14"; this.setStateActivity14.TargetStateName = "finalStateActivity"; // // finishHandleExternalEventActivity3 // this.finishHandleExternalEventActivity3.EventName = "Finish"; this.finishHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity3.Name = "finishHandleExternalEventActivity3"; // // abortWizardFormActivity // this.abortWizardFormActivity.ContainerLabel = null; this.abortWizardFormActivity.FormDefinitionFileName = "\\Administrative\\RemoveSystemLocaleAbort.xml"; this.abortWizardFormActivity.Name = "abortWizardFormActivity"; // // if_IsLastLocale // this.if_IsLastLocale.Activities.Add(this.ifElseBranchActivity5); this.if_IsLastLocale.Activities.Add(this.ifElseBranchActivity6); this.if_IsLastLocale.Enabled = false; this.if_IsLastLocale.Name = "if_IsLastLocale"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity7); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity8); this.ifElseActivity1.Name = "ifElseActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity8); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step3EventDrivenActivity_Cancel // this.step3EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.step3EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity7); this.step3EventDrivenActivity_Cancel.Name = "step3EventDrivenActivity_Cancel"; // // step2EventDrivenActivity_Finish // this.step2EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step2EventDrivenActivity_Finish.Activities.Add(this.setStateActivity6); this.step2EventDrivenActivity_Finish.Name = "step2EventDrivenActivity_Finish"; // // step2StateInitializationActivity // this.step2StateInitializationActivity.Activities.Add(this.step2WizardFormActivity); this.step2StateInitializationActivity.Name = "step2StateInitializationActivity"; // // abortEventDrivenActivity_Finish // this.abortEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity3); this.abortEventDrivenActivity_Finish.Activities.Add(this.setStateActivity14); this.abortEventDrivenActivity_Finish.Name = "abortEventDrivenActivity_Finish"; // // abortStateInitializationActivity // this.abortStateInitializationActivity.Activities.Add(this.abortWizardFormActivity); this.abortStateInitializationActivity.Name = "abortStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.ifElseActivity1); this.initializeStateInitializationActivity.Activities.Add(this.if_IsLastLocale); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step2StateActivity // this.step2StateActivity.Activities.Add(this.step2StateInitializationActivity); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Finish); this.step2StateActivity.Activities.Add(this.step3EventDrivenActivity_Cancel); this.step2StateActivity.Name = "step2StateActivity"; // // abortStateActivity // this.abortStateActivity.Activities.Add(this.abortStateInitializationActivity); this.abortStateActivity.Activities.Add(this.abortEventDrivenActivity_Finish); this.abortStateActivity.Name = "abortStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // RemoveSystemLocaleWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.abortStateActivity); this.Activities.Add(this.step2StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "RemoveSystemLocaleWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private StateActivity abortStateActivity; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity step2WizardFormActivity; private StateInitializationActivity finalizeStateInitializationActivity; private StateInitializationActivity step2StateInitializationActivity; private StateInitializationActivity abortStateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity step2StateActivity; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity abortWizardFormActivity; private EventDrivenActivity step2EventDrivenActivity_Finish; private SetStateActivity setStateActivity7; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private SetStateActivity setStateActivity6; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private EventDrivenActivity step3EventDrivenActivity_Cancel; private SetStateActivity setStateActivity8; private CodeActivity finalizeCodeActivity_Finalize; private EventDrivenActivity abortEventDrivenActivity_Finish; private SetStateActivity setStateActivity14; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity3; private SetStateActivity setStateActivity10; private SetStateActivity setStateActivity11; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private SetStateActivity setStateActivity3; private IfElseActivity if_IsTypesUsingLocalization; private IfElseBranchActivity ifElseBranchActivity6; private IfElseBranchActivity ifElseBranchActivity5; private IfElseActivity if_IsLastLocale; private SetStateActivity setStateActivity2; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity if_IsCurrentDefaultLocale; private IfElseBranchActivity ifElseBranchActivity8; private IfElseBranchActivity ifElseBranchActivity7; private IfElseActivity ifElseActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/LocalizationElementProvider/RemoveSystemLocaleWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="RemoveSystemLocaleWorkflow" Location="30; 30" Size="1146; 980" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="RemoveSystemLocaleWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="RemoveSystemLocaleWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity14" SourceStateName="abortStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="abortStateActivity" EventHandlerName="abortEventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="434" Y="581" /> <ns0:Point X="1058" Y="581" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step2StateActivity" EventHandlerName="step2EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="688" Y="394" /> <ns0:Point X="784" Y="394" /> <ns0:Point X="784" Y="605" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="3" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step2StateActivity" EventHandlerName="step3EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="692" Y="418" /> <ns0:Point X="1058" Y="418" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity8" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="883" Y="646" /> <ns0:Point X="1058" Y="646" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step2StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step2StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="595" Y="179" /> <ns0:Point X="595" Y="329" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="abortStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity11" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="abortStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="335" Y="179" /> <ns0:Point X="335" Y="516" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step2StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity10" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step2StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="595" Y="179" /> <ns0:Point X="595" Y="329" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="abortStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="abortStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="335" Y="179" /> <ns0:Point X="335" Y="516" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="843; 496" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="823; 415" Name="if_IsLastLocale" Location="108; 231"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="381; 315" Name="ifElseBranchActivity5" Location="127; 302"> <IfElseBranchDesigner.Designers> <IfElseDesigner Size="361; 234" Name="if_IsTypesUsingLocalization" Location="137; 364"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 134" Name="ifElseBranchActivity3" Location="156; 435"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 53" Name="setStateActivity11" Location="166; 497" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 134" Name="ifElseBranchActivity4" Location="329; 435"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 53" Name="setStateActivity10" Location="339; 497" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="381; 315" Name="ifElseBranchActivity6" Location="531; 302"> <IfElseBranchDesigner.Designers> <IfElseDesigner Size="361; 222" Name="if_IsCurrentDefaultLocale" Location="541; 370"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity1" Location="560; 441"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="570; 503" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity2" Location="733; 441"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="743; 503" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="abortStateActivity" Location="232; 516" Size="206; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="abortStateInitializationActivity" Location="240; 547"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="abortWizardFormActivity" Location="250; 609" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 194" Name="abortEventDrivenActivity_Finish" Location="240; 571"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity3" Location="250; 633" /> <SetStateDesigner Size="130; 53" Name="setStateActivity14" Location="250; 693" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="step2StateActivity" Location="485; 329" Size="220; 126" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step2StateInitializationActivity" Location="493; 360"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step2WizardFormActivity" Location="503; 422" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step2EventDrivenActivity_Finish" Location="493; 384"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="503; 446" /> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="503; 506" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step3EventDrivenActivity_Cancel" Location="493; 408"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity3" Location="503; 470" /> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="503; 530" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="682; 605" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="finalizeStateInitializationActivity" Location="690; 636"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity_Finalize" Location="700; 698" /> <SetStateDesigner Size="130; 41" Name="setStateActivity8" Location="700; 758" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/AddMediaZipFileWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { partial class AddMediaZipFileWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity3 = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseActivity2 = new System.Workflow.Activities.IfElseActivity(); this.codeActivity2 = new System.Workflow.Activities.CodeActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity1 = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finishEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.selectZipStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity1 = new System.Workflow.Activities.EventDrivenActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.selectZipFileStateActivity = new System.Workflow.Activities.StateActivity(); this.initialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "selectZipFileStateActivity"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "selectZipFileStateActivity"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // codeActivity3 // this.codeActivity3.Name = "codeActivity3"; this.codeActivity3.ExecuteCode += new System.EventHandler(this.HandleFinish_ExecuteCode); // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity7); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.closeCurrentViewActivity1); this.ifElseBranchActivity3.Activities.Add(this.setStateActivity4); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ZipWasUploaded); this.ifElseBranchActivity3.Condition = codecondition1; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity5); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.codeActivity3); this.ifElseBranchActivity1.Activities.Add(this.setStateActivity3); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.HasUserUploaded); this.ifElseBranchActivity1.Condition = codecondition2; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // ifElseActivity2 // this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity4); this.ifElseActivity2.Name = "ifElseActivity2"; // // codeActivity2 // this.codeActivity2.Name = "codeActivity2"; this.codeActivity2.ExecuteCode += new System.EventHandler(this.FinalizeCodeActivity_ExecuteCode); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = null; this.wizzardFormActivity1.FormDefinitionFileName = "/Administrative/AddZipMediaFile.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "selectZipFileStateActivity"; // // codeActivity1 // this.codeActivity1.Name = "codeActivity1"; this.codeActivity1.ExecuteCode += new System.EventHandler(this.InitializeCodeActivity_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.codeActivity2); this.finalizeStateInitializationActivity.Activities.Add(this.ifElseActivity2); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity2); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity6); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finishEventDrivenActivity // this.finishEventDrivenActivity.Activities.Add(this.finishHandleExternalEventActivity1); this.finishEventDrivenActivity.Activities.Add(this.ifElseActivity1); this.finishEventDrivenActivity.Name = "finishEventDrivenActivity"; // // selectZipStateInitializationActivity // this.selectZipStateInitializationActivity.Activities.Add(this.wizzardFormActivity1); this.selectZipStateInitializationActivity.Name = "selectZipStateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.codeActivity1); this.initialStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // eventDrivenActivity1 // this.eventDrivenActivity1.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity1.Activities.Add(this.setStateActivity1); this.eventDrivenActivity1.Name = "eventDrivenActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // selectZipFileStateActivity // this.selectZipFileStateActivity.Activities.Add(this.selectZipStateInitializationActivity); this.selectZipFileStateActivity.Activities.Add(this.finishEventDrivenActivity); this.selectZipFileStateActivity.Activities.Add(this.cancelEventDrivenActivity); this.selectZipFileStateActivity.Name = "selectZipFileStateActivity"; // // initialState // this.initialState.Activities.Add(this.initialStateInitializationActivity); this.initialState.Name = "initialState"; // // AddMediaZipFileWorkflow // this.Activities.Add(this.initialState); this.Activities.Add(this.selectZipFileStateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.eventDrivenActivity1); this.Activities.Add(this.finalStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialState"; this.Name = "AddMediaZipFileWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity selectZipFileStateActivity; private StateActivity finalizeStateActivity; private EventDrivenActivity eventDrivenActivity1; private StateInitializationActivity initialStateInitializationActivity; private StateActivity finalStateActivity; private CodeActivity codeActivity1; private StateInitializationActivity finalizeStateInitializationActivity; private StateInitializationActivity selectZipStateInitializationActivity; private C1Console.Workflow.Activities.DataDialogFormActivity wizzardFormActivity1; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity1; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private SetStateActivity setStateActivity4; private CodeActivity codeActivity2; private SetStateActivity setStateActivity3; private CodeActivity codeActivity3; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private EventDrivenActivity finishEventDrivenActivity; private SetStateActivity setStateActivity5; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity6; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity cancelEventDrivenActivity; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElseActivity2; private SetStateActivity setStateActivity7; private StateActivity initialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/AddMediaZipFileWorkflow.cs ================================================ using System; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Workflow; using Composite.C1Console.Workflow.Activities; using Composite.Core; using Composite.Data; using Composite.Data.Types; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Management; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Never)] public sealed partial class AddMediaZipFileWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { [NonSerialized] bool _zipHasBeenUploaded = false; public AddMediaZipFileWorkflow() { InitializeComponent(); } private void InitializeCodeActivity_ExecuteCode(object sender, EventArgs e) { FormsWorkflow workflow = this.GetRoot<FormsWorkflow>(); string parentFolderPath; string storeId; if (this.EntityToken is MediaRootFolderProviderEntityToken) { var token = (MediaRootFolderProviderEntityToken)this.EntityToken; parentFolderPath = "/"; storeId = token.Id; } else { var token = (DataEntityToken)this.EntityToken; IMediaFileFolder parentFolder = (IMediaFileFolder)token.Data; parentFolderPath = parentFolder.Path; storeId = parentFolder.StoreId; } string providerName = DataFacade.GetData<IMediaFileStore>().First(x => x.Id == storeId).DataSourceId.ProviderName; UploadedFile file = new UploadedFile(); workflow.Bindings.Add("UploadedFile", file); workflow.Bindings.Add("RecreateFolders", true); workflow.Bindings.Add("OverwriteExisting", false); workflow.Bindings.Add("ParentFolderPath", parentFolderPath); workflow.Bindings.Add("ProviderName", providerName); } private void HandleFinish_ExecuteCode(object sender, EventArgs e) { UploadedFile uploadedFile = this.GetBinding<UploadedFile>("UploadedFile"); bool recreateFolders = this.GetBinding<bool>("RecreateFolders"); bool overwrite = this.GetBinding<bool>("OverwriteExisting"); string parentFolderPath = this.GetBinding<string>("ParentFolderPath"); string providerName = this.GetBinding<string>("ProviderName"); if (uploadedFile.HasFile) { if(uploadedFile.FileName.EndsWith(".docx")) { ShowUploadError(Texts.Website_Forms_Administrative_AddZipMediaFile_CannotUploadDocxFile); return; } using (System.IO.Stream readStream = uploadedFile.FileStream) { try { ZipMediaFileExtractor.AddZip(providerName, parentFolderPath, readStream, recreateFolders, overwrite); _zipHasBeenUploaded = true; } catch (Exception ex) { Log.LogError(nameof(AddMediaZipFileWorkflow), ex); } } } if (!_zipHasBeenUploaded) { ShowUploadError(Texts.Website_Forms_Administrative_AddZipMediaFile_WrongUploadedFile_Message); } } private void ZipWasUploaded(object sender, ConditionalEventArgs e) { e.Result = _zipHasBeenUploaded; } private void FinalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken); addNewTreeRefresher.PostRefreshMesseges(this.EntityToken); } private void HasUserUploaded(object sender, System.Workflow.Activities.ConditionalEventArgs e) { UploadedFile uploadedFile = this.GetBinding<UploadedFile>("UploadedFile"); if (!uploadedFile.HasFile) { ShowUploadError(Texts.Website_Forms_Administrative_AddZipMediaFile_MissingUploadedFile_Message); e.Result = false; return; } e.Result = true; } private void ShowUploadError(string message) { //TODO: Cannot show an error bubble on file selector since the control doesn't support it. Should be fixed on client js //this.ShowFieldMessage("UploadedFile", "${Composite.Management, Website.Forms.Administrative.AddZipMediaFile.MissingUploadedFile.Message}"); this.ShowMessage(DialogType.Error, Texts.Website_Forms_Administrative_AddZipMediaFile_Error_Title, message); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/AddMediaZipFileWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1220; 986" AutoSizeMargin="16; 24" Location="30; 30" Name="AddMediaZipFileWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="197; 80" AutoSizeMargin="16; 24" Location="63; 105" Name="initialState"> <StateDesigner.Designers> <StateInitializationDesigner Name="initialStateInitializationActivity" Size="150; 182" Location="71; 136"> <StateInitializationDesigner.Designers> <CodeDesigner Name="codeActivity1" Size="130; 41" Location="81; 198" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="81; 258" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="214; 102" AutoSizeMargin="16; 24" AutoSize="False" Location="240; 344" Name="selectZipFileStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="selectZipStateInitializationActivity" Size="150; 122" Location="248; 375"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizzardFormActivity1" Size="130; 41" Location="258; 437" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="finishEventDrivenActivity" Size="381; 423" Location="248; 399"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="373; 461" /> <IfElseDesigner Name="ifElseActivity1" Size="361; 282" Location="258; 521"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 182" Location="277; 592"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="codeActivity3" Size="130; 41" Location="287; 654" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="287; 714" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 182" Location="450; 592"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="460; 684" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="cancelEventDrivenActivity" Size="150; 182" Location="248; 423"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="258; 485" /> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="258; 545" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" Location="534; 592" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="381; 423" Location="542; 623"> <StateInitializationDesigner.Designers> <CodeDesigner Name="codeActivity2" Size="130; 41" Location="667; 685" /> <IfElseDesigner Name="ifElseActivity2" Size="361; 282" Location="552; 745"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity3" Size="150; 182" Location="571; 816"> <IfElseBranchDesigner.Designers> <ActivityDesigner Name="closeCurrentViewActivity1" Size="130; 41" Location="581; 878" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="581; 938" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity4" Size="150; 182" Location="744; 816"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity7" Size="130; 41" Location="754; 908" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <EventDrivenDesigner Name="eventDrivenActivity1" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="859; 784" Name="finalStateActivity" /> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="AddMediaZipFileWorkflow" TargetConnectionIndex="0" SourceStateName="AddMediaZipFileWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity1" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="176" Y="71" /> <ns0:Point X="939" Y="71" /> <ns0:Point X="939" Y="784" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="selectZipFileStateActivity" SetStateName="setStateActivity2" SourceActivity="initialState" TargetConnectionIndex="0" SourceStateName="initialState" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initialStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="selectZipFileStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="146" /> <ns0:Point X="347" Y="146" /> <ns0:Point X="347" Y="344" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity3" SourceActivity="selectZipFileStateActivity" TargetConnectionIndex="0" SourceStateName="selectZipFileStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finishEventDrivenActivity" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="407" Y="409" /> <ns0:Point X="636" Y="409" /> <ns0:Point X="636" Y="592" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="selectZipFileStateActivity" SetStateName="setStateActivity5" SourceActivity="selectZipFileStateActivity" TargetConnectionIndex="0" SourceStateName="selectZipFileStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finishEventDrivenActivity" SourceConnectionIndex="1" TargetStateName="selectZipFileStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="407" Y="409" /> <ns0:Point X="459" Y="409" /> <ns0:Point X="459" Y="336" /> <ns0:Point X="347" Y="336" /> <ns0:Point X="347" Y="344" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity6" SourceActivity="selectZipFileStateActivity" TargetConnectionIndex="0" SourceStateName="selectZipFileStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="cancelEventDrivenActivity" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="412" Y="433" /> <ns0:Point X="939" Y="433" /> <ns0:Point X="939" Y="784" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity4" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="735" Y="633" /> <ns0:Point X="939" Y="633" /> <ns0:Point X="939" Y="784" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="selectZipFileStateActivity" SetStateName="setStateActivity7" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="selectZipFileStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="735" Y="633" /> <ns0:Point X="747" Y="633" /> <ns0:Point X="747" Y="336" /> <ns0:Point X="347" Y="336" /> <ns0:Point X="347" Y="344" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/AddNewMediaFileWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { partial class AddNewMediaFileWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition3 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity12 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity11 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity6 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity5 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step2IfElseActivity_ValidateStep2Bindings = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.previousHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.PreviousHandleExternalEventActivity(); this.wizardFormActivity2 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.step2CodeActivity_UpdateBindings = new System.Workflow.Activities.CodeActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step1IfElseActivity_Finish_ValidateStep1Bindings = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step1IfElseActivity_Next_ValidateStep1Bindings = new System.Workflow.Activities.IfElseActivity(); this.nextHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.wizardFormActivity1 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_InitializeBindings = new System.Workflow.Activities.CodeActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step2EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step2EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step2EventDrivenActivity_Previous = new System.Workflow.Activities.EventDrivenActivity(); this.step2StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.stepEventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step2StateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity12 // this.setStateActivity12.Name = "setStateActivity12"; this.setStateActivity12.TargetStateName = "step2StateActivity"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalizeStateActivity"; // // setStateActivity11 // this.setStateActivity11.Name = "setStateActivity11"; this.setStateActivity11.TargetStateName = "step1StateActivity"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalizeStateActivity"; // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "step1StateActivity"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "step2StateActivity"; // // ifElseBranchActivity6 // this.ifElseBranchActivity6.Activities.Add(this.setStateActivity12); this.ifElseBranchActivity6.Name = "ifElseBranchActivity6"; // // ifElseBranchActivity5 // this.ifElseBranchActivity5.Activities.Add(this.setStateActivity4); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateStep2Bindings); this.ifElseBranchActivity5.Condition = codecondition1; this.ifElseBranchActivity5.Description = "ValidateStep2Bindings"; this.ifElseBranchActivity5.Name = "ifElseBranchActivity5"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity11); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.setStateActivity7); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateStep1Bindings_Finish); this.ifElseBranchActivity3.Condition = codecondition2; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity10); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity8); codecondition3.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateStep1Bindings_Next); this.ifElseBranchActivity1.Condition = codecondition3; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // step2IfElseActivity_ValidateStep2Bindings // this.step2IfElseActivity_ValidateStep2Bindings.Activities.Add(this.ifElseBranchActivity5); this.step2IfElseActivity_ValidateStep2Bindings.Activities.Add(this.ifElseBranchActivity6); this.step2IfElseActivity_ValidateStep2Bindings.Name = "step2IfElseActivity_ValidateStep2Bindings"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "step1StateActivity"; // // previousHandleExternalEventActivity1 // this.previousHandleExternalEventActivity1.EventName = "Previous"; this.previousHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.previousHandleExternalEventActivity1.Name = "previousHandleExternalEventActivity1"; // // wizardFormActivity2 // this.wizardFormActivity2.ContainerLabel = null; this.wizardFormActivity2.FormDefinitionFileName = "/Administrative/AddMediaFileStep2.xml"; this.wizardFormActivity2.Name = "wizardFormActivity2"; // // step2CodeActivity_UpdateBindings // this.step2CodeActivity_UpdateBindings.Name = "step2CodeActivity_UpdateBindings"; this.step2CodeActivity_UpdateBindings.ExecuteCode += new System.EventHandler(this.step2CodeActivity_UpdateBindings_ExecuteCode); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // step1IfElseActivity_Finish_ValidateStep1Bindings // this.step1IfElseActivity_Finish_ValidateStep1Bindings.Activities.Add(this.ifElseBranchActivity3); this.step1IfElseActivity_Finish_ValidateStep1Bindings.Activities.Add(this.ifElseBranchActivity4); this.step1IfElseActivity_Finish_ValidateStep1Bindings.Name = "step1IfElseActivity_Finish_ValidateStep1Bindings"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // step1IfElseActivity_Next_ValidateStep1Bindings // this.step1IfElseActivity_Next_ValidateStep1Bindings.Activities.Add(this.ifElseBranchActivity1); this.step1IfElseActivity_Next_ValidateStep1Bindings.Activities.Add(this.ifElseBranchActivity2); this.step1IfElseActivity_Next_ValidateStep1Bindings.Name = "step1IfElseActivity_Next_ValidateStep1Bindings"; // // nextHandleExternalEventActivity1 // this.nextHandleExternalEventActivity1.EventName = "Next"; this.nextHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity1.Name = "nextHandleExternalEventActivity1"; // // wizardFormActivity1 // this.wizardFormActivity1.ContainerLabel = null; this.wizardFormActivity1.FormDefinitionFileName = "/Administrative/AddMediaFileStep1.xml"; this.wizardFormActivity1.Name = "wizardFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // initializeCodeActivity_InitializeBindings // this.initializeCodeActivity_InitializeBindings.Name = "initializeCodeActivity_InitializeBindings"; this.initializeCodeActivity_InitializeBindings.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_InitializeBindings_ExecuteCode); // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity3); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step2EventDrivenActivity_Cancel // this.step2EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.step2EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity5); this.step2EventDrivenActivity_Cancel.Name = "step2EventDrivenActivity_Cancel"; // // step2EventDrivenActivity_Finish // this.step2EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.step2EventDrivenActivity_Finish.Activities.Add(this.step2IfElseActivity_ValidateStep2Bindings); this.step2EventDrivenActivity_Finish.Name = "step2EventDrivenActivity_Finish"; // // step2EventDrivenActivity_Previous // this.step2EventDrivenActivity_Previous.Activities.Add(this.previousHandleExternalEventActivity1); this.step2EventDrivenActivity_Previous.Activities.Add(this.setStateActivity9); this.step2EventDrivenActivity_Previous.Name = "step2EventDrivenActivity_Previous"; // // step2StateInitializationActivity // this.step2StateInitializationActivity.Activities.Add(this.step2CodeActivity_UpdateBindings); this.step2StateInitializationActivity.Activities.Add(this.wizardFormActivity2); this.step2StateInitializationActivity.Name = "step2StateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity6); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.step1IfElseActivity_Finish_ValidateStep1Bindings); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // stepEventDrivenActivity_Next // this.stepEventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity1); this.stepEventDrivenActivity_Next.Activities.Add(this.step1IfElseActivity_Next_ValidateStep1Bindings); this.stepEventDrivenActivity_Next.Name = "stepEventDrivenActivity_Next"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.wizardFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_InitializeBindings); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step2StateActivity // this.step2StateActivity.Activities.Add(this.step2StateInitializationActivity); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Previous); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Finish); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Cancel); this.step2StateActivity.Name = "step2StateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.stepEventDrivenActivity_Next); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // AddNewMediaFileWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.step2StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddNewMediaFileWorkflow"; this.CanModifyActivities = false; } #endregion private CodeActivity step2CodeActivity_UpdateBindings; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity9; private SetStateActivity setStateActivity6; private SetStateActivity setStateActivity7; private SetStateActivity setStateActivity8; private SetStateActivity setStateActivity2; private CodeActivity initializeCodeActivity_InitializeBindings; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step2EventDrivenActivity_Cancel; private EventDrivenActivity step2EventDrivenActivity_Finish; private EventDrivenActivity step2EventDrivenActivity_Previous; private StateInitializationActivity step2StateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Finish; private EventDrivenActivity stepEventDrivenActivity_Next; private StateInitializationActivity step1StateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity step2StateActivity; private StateActivity step1StateActivity; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity step1IfElseActivity_Next_ValidateStep1Bindings; private C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity1; private SetStateActivity setStateActivity12; private SetStateActivity setStateActivity11; private SetStateActivity setStateActivity10; private IfElseBranchActivity ifElseBranchActivity6; private IfElseBranchActivity ifElseBranchActivity5; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity step2IfElseActivity_ValidateStep2Bindings; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private C1Console.Workflow.Activities.PreviousHandleExternalEventActivity previousHandleExternalEventActivity1; private C1Console.Workflow.Activities.WizardFormActivity wizardFormActivity2; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private IfElseActivity step1IfElseActivity_Finish_ValidateStep1Bindings; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private C1Console.Workflow.Activities.WizardFormActivity wizardFormActivity1; private CodeActivity finalizeCodeActivity_Finalize; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/AddNewMediaFileWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Workflow; using Composite.Core.IO; using Composite.Data; using Composite.Data.Types; using Composite.Data.Validation.ClientValidationRules; using Composite.Data.Transactions; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Never)] public sealed partial class AddNewMediaFileWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddNewMediaFileWorkflow() { InitializeComponent(); } private void Initialize() { if (this.EntityToken is MediaRootFolderProviderEntityToken token) { _storeId = token.Id; _folderPath = "/"; } else { var dataEntityToken = (DataEntityToken)this.EntityToken; var parentFolder = (IMediaFileFolder)dataEntityToken.Data; _storeId = parentFolder.StoreId; _folderPath = parentFolder.Path; } } [NonSerialized] private string _folderPath; internal string FolderPath { get { if (_folderPath == null) { Initialize(); } return _folderPath; } } [NonSerialized] private string _storeId; internal string StoreId { get { if (_storeId == null) { Initialize(); } return _storeId; } } private IMediaFile GetExistingFile(string folderPath, string filename) { return DataFacade.GetData<IMediaFile>().FirstOrDefault(file => string.Compare(file.FolderPath, folderPath, StringComparison.OrdinalIgnoreCase) == 0 && string.Compare(file.FileName, filename, StringComparison.OrdinalIgnoreCase) == 0); } private void initializeCodeActivity_InitializeBindings_ExecuteCode(object sender, EventArgs e) { this.Bindings.Add("UploadedFile", new UploadedFile()); this.Bindings.Add("AllowOverwrite", false); this.Bindings.Add("Title", ""); this.Bindings.Add("Description", ""); this.Bindings.Add("Tags", ""); } private void ValidateStep1Bindings_Next(object sender, ConditionalEventArgs e) { UploadedFile uploadedFile = this.GetBinding<UploadedFile>("UploadedFile"); if (!uploadedFile.HasFile) { this.ShowFieldMessage("UploadedFile", "${Composite.Management, Website.Forms.Administrative.AddNewMediaFile.MissingUploadedFile.Message}"); e.Result = false; return; } e.Result = true; } private void ValidateStep1Bindings_Finish(object sender, ConditionalEventArgs e) { ValidateStep1Bindings_Next(sender, e); if (!e.Result) return; UploadedFile uploadedFile = this.GetBinding<UploadedFile>("UploadedFile"); string filename = uploadedFile.FileName; bool allowOverwrite = this.GetBinding<bool>("AllowOverwrite"); IMediaFile existingFile = GetExistingFile(this.FolderPath, filename); if (existingFile != null && !allowOverwrite) { this.ShowFieldMessage("UploadedFile", "${Composite.Management, Website.Forms.Administrative.AddNewMediaFile.FileExists.Message}"); e.Result = false; return; } string compositePath = IMediaFileExtensions.GetCompositePath(this.StoreId, this.FolderPath, filename); if (compositePath.Length > 2048) { this.ShowFieldMessage("UploadedFile", "${Composite.Management, Website.Forms.Administrative.AddNewMediaFile.TotalFilenameToLong.Message}"); e.Result = false; return; } e.Result = true; } private void step2CodeActivity_UpdateBindings_ExecuteCode(object sender, EventArgs e) { if (!this.BindingExist("Filename")) { UploadedFile uploadedFile = this.GetBinding<UploadedFile>("UploadedFile"); this.Bindings.Add("Filename", uploadedFile.FileName); this.BindingsValidationRules.Add("Title", new List<ClientValidationRule> { new StringLengthClientValidationRule(0, 256) }); } } private void ValidateStep2Bindings(object sender, ConditionalEventArgs e) { string filename = this.GetBinding<string>("Filename"); bool allowOverwrite = this.GetBinding<bool>("AllowOverwrite"); IMediaFile existingFile = GetExistingFile(this.FolderPath, filename); if (existingFile != null && !allowOverwrite) { this.ShowFieldMessage("Filename", "${Composite.Management, Website.Forms.Administrative.AddNewMediaFile.FileExists.Message}"); e.Result = false; return; } string compositePath = IMediaFileExtensions.GetCompositePath(this.StoreId, this.FolderPath, filename); if (compositePath.Length > 2048) { this.ShowFieldMessage("Filename", "${Composite.Management, Website.Forms.Administrative.AddNewMediaFile.TotalFilenameToLong.Message}"); e.Result = false; return; } e.Result = true; } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { var addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken); DataEntityToken focusEntityToken; UploadedFile uploadedFile = this.GetBinding<UploadedFile>("UploadedFile"); var filename = this.BindingExist("Filename") ? this.GetBinding<string>("Filename") : uploadedFile.FileName; using (var transactionScope = TransactionsFacade.CreateNewScope()) { IMediaFileStore store = DataFacade.GetData<IMediaFileStore>(x => x.Id == this.StoreId).First(); IMediaFile existingFile = GetExistingFile(this.FolderPath, filename); if (existingFile == null) { var mediaFile = new WorkflowMediaFile { FileName = System.IO.Path.GetFileName(filename), FolderPath = this.FolderPath, Title = this.GetBinding<string>("Title"), Description = this.GetBinding<string>("Description"), Tags = this.GetBinding<string>("Tags"), Culture = C1Console.Users.UserSettings.ActiveLocaleCultureInfo.Name, Length = uploadedFile.ContentLength, MimeType = MimeTypeInfo.GetMimeType(uploadedFile) }; using (var readStream = uploadedFile.FileStream) { using (var writeStream = mediaFile.GetNewWriteStream()) { readStream.CopyTo(writeStream); } } IMediaFile addedFile = DataFacade.AddNew<IMediaFile>(mediaFile, store.DataSourceId.ProviderName); focusEntityToken = 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 (var readStream = uploadedFile.FileStream) { using (var writeStream = existingFile.GetNewWriteStream()) { readStream.CopyTo(writeStream); } } DataFacade.Update(existingFile); DataFacade.Update(fileData); focusEntityToken = existingFile.GetDataEntityToken(); } transactionScope.Complete(); } addNewTreeRefresher.PostRefreshMesseges(focusEntityToken); SelectElement(focusEntityToken); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/AddNewMediaFileWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1190; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="AddNewMediaFileWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 182" Location="98; 169"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_InitializeBindings" Size="130; 41" Location="108; 231" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="108; 291" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="211; 126" AutoSizeMargin="16; 24" Location="146; 317" Name="step1StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1StateInitializationActivity" Size="150; 122" Location="154; 348"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizardFormActivity1" Size="130; 41" Location="164; 410" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="stepEventDrivenActivity_Next" Size="381; 375" Location="154; 372"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="nextHandleExternalEventActivity1" Size="130; 41" Location="279; 434" /> <IfElseDesigner Name="step1IfElseActivity_Next_ValidateStep1Bindings" Size="361; 234" Location="164; 494"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 134" Location="183; 565"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity8" Size="130; 41" Location="193; 633" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 134" Location="356; 565"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity10" Size="130; 53" Location="366; 627" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Finish" Size="381; 375" Location="154; 396"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="279; 458" /> <IfElseDesigner Name="step1IfElseActivity_Finish_ValidateStep1Bindings" Size="361; 234" Location="164; 518"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity3" Size="150; 134" Location="183; 589"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity7" Size="130; 41" Location="193; 657" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity4" Size="150; 134" Location="356; 589"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity11" Size="130; 53" Location="366; 651" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Cancel" Size="150; 182" Location="154; 420"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="164; 482" /> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="164; 542" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="220; 126" AutoSizeMargin="16; 24" AutoSize="False" Location="424; 472" Name="step2StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step2StateInitializationActivity" Size="150; 182" Location="550; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Name="step2CodeActivity_UpdateBindings" Size="130; 41" Location="560; 210" /> <ActivityDesigner Name="wizardFormActivity2" Size="130; 41" Location="560; 270" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step2EventDrivenActivity_Previous" Size="150; 182" Location="542; 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="previousHandleExternalEventActivity1" Size="130; 41" Location="552; 221" /> <SetStateDesigner Name="setStateActivity9" Size="130; 41" Location="552; 281" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step2EventDrivenActivity_Finish" Size="381; 375" Location="542; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity2" Size="130; 41" Location="667; 245" /> <IfElseDesigner Name="step2IfElseActivity_ValidateStep2Bindings" Size="361; 234" Location="552; 305"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity5" Size="150; 134" Location="571; 376"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="581; 444" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity6" Size="150; 134" Location="744; 376"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity12" Size="130; 53" Location="754; 438" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step2EventDrivenActivity_Cancel" Size="150; 182" Location="542; 207"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity3" Size="130; 41" Location="552; 269" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="552; 329" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="711; 618" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 182" Location="719; 649"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity_Finalize" Size="130; 41" Location="729; 711" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="729; 771" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="AddNewMediaFileWorkflow" TargetConnectionIndex="0" SourceStateName="AddNewMediaFileWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="307" Y="179" /> <ns0:Point X="307" Y="305" /> <ns0:Point X="251" Y="305" /> <ns0:Point X="251" Y="317" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step2StateActivity" SetStateName="setStateActivity8" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="stepEventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="step2StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="337" Y="382" /> <ns0:Point X="534" Y="382" /> <ns0:Point X="534" Y="472" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity10" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="stepEventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="337" Y="382" /> <ns0:Point X="363" Y="382" /> <ns0:Point X="363" Y="309" /> <ns0:Point X="251" Y="309" /> <ns0:Point X="251" Y="317" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity7" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="2" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="349" Y="406" /> <ns0:Point X="813" Y="406" /> <ns0:Point X="813" Y="618" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity11" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="2" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="349" Y="406" /> <ns0:Point X="363" Y="406" /> <ns0:Point X="363" Y="309" /> <ns0:Point X="251" Y="309" /> <ns0:Point X="251" Y="317" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity6" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Cancel" SourceConnectionIndex="3" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="353" Y="430" /> <ns0:Point X="1058" Y="430" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity9" SourceActivity="step2StateActivity" TargetConnectionIndex="0" SourceStateName="step2StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step2EventDrivenActivity_Previous" SourceConnectionIndex="1" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="640" Y="537" /> <ns0:Point X="651" Y="537" /> <ns0:Point X="651" Y="309" /> <ns0:Point X="251" Y="309" /> <ns0:Point X="251" Y="317" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity4" SourceActivity="step2StateActivity" TargetConnectionIndex="0" SourceStateName="step2StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step2EventDrivenActivity_Finish" SourceConnectionIndex="2" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="627" Y="561" /> <ns0:Point X="813" Y="561" /> <ns0:Point X="813" Y="618" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step2StateActivity" SetStateName="setStateActivity12" SourceActivity="step2StateActivity" TargetConnectionIndex="0" SourceStateName="step2StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step2EventDrivenActivity_Finish" SourceConnectionIndex="2" TargetStateName="step2StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="737" Y="193" /> <ns0:Point X="764" Y="193" /> <ns0:Point X="764" Y="96" /> <ns0:Point X="644" Y="96" /> <ns0:Point X="644" Y="104" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity5" SourceActivity="step2StateActivity" TargetConnectionIndex="0" SourceStateName="step2StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step2EventDrivenActivity_Cancel" SourceConnectionIndex="3" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="631" Y="585" /> <ns0:Point X="1058" Y="585" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity3" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="912" Y="659" /> <ns0:Point X="1058" Y="659" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/AddNewMediaFolderWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { partial class AddNewMediaFolderWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.step1IfElseBranchActivity_DoesFolderExist = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeAddNewfolderCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.stateInitializationActivity3 = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity2 = new System.Workflow.Activities.StateInitializationActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.cancelActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.AddNewMediaFolderWorkflowInitialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "step1StateActivity"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalizeStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity3); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // step1IfElseBranchActivity_DoesFolderExist // this.step1IfElseBranchActivity_DoesFolderExist.Activities.Add(this.setStateActivity6); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateInputs); this.step1IfElseBranchActivity_DoesFolderExist.Condition = codecondition1; this.step1IfElseBranchActivity_DoesFolderExist.Name = "step1IfElseBranchActivity_DoesFolderExist"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.step1IfElseBranchActivity_DoesFolderExist); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = null; this.wizzardFormActivity1.FormDefinitionFileName = "/Administrative/AddNewMediaFolder.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // initializeAddNewfolderCodeActivity // this.initializeAddNewfolderCodeActivity.Name = "initializeAddNewfolderCodeActivity"; this.initializeAddNewfolderCodeActivity.ExecuteCode += new System.EventHandler(this.initializeAddNewfolderCodeActivity_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // stateInitializationActivity3 // this.stateInitializationActivity3.Activities.Add(this.finalizeCodeActivity); this.stateInitializationActivity3.Activities.Add(this.closeCurrentViewActivity1); this.stateInitializationActivity3.Activities.Add(this.setStateActivity4); this.stateInitializationActivity3.Name = "stateInitializationActivity3"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity5); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.ifElseActivity1); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // stateInitializationActivity2 // this.stateInitializationActivity2.Activities.Add(this.wizzardFormActivity1); this.stateInitializationActivity2.Name = "stateInitializationActivity2"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.initializeAddNewfolderCodeActivity); this.stateInitializationActivity1.Activities.Add(this.setStateActivity2); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // cancelActivity // this.cancelActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelActivity.Activities.Add(this.setStateActivity1); this.cancelActivity.Name = "cancelActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.stateInitializationActivity3); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.stateInitializationActivity2); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // AddNewMediaFolderWorkflowInitialState // this.AddNewMediaFolderWorkflowInitialState.Activities.Add(this.stateInitializationActivity1); this.AddNewMediaFolderWorkflowInitialState.Name = "AddNewMediaFolderWorkflowInitialState"; // // AddNewMediaFolderWorkflow // this.Activities.Add(this.AddNewMediaFolderWorkflowInitialState); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "AddNewMediaFolderWorkflowInitialState"; this.Name = "AddNewMediaFolderWorkflow"; this.CanModifyActivities = false; } #endregion private CodeActivity initializeAddNewfolderCodeActivity; private StateInitializationActivity stateInitializationActivity1; private StateActivity finalStateActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private StateInitializationActivity stateInitializationActivity3; private StateInitializationActivity stateInitializationActivity2; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.DataDialogFormActivity wizzardFormActivity1; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity1; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity step1EventDrivenActivity_Finish; private EventDrivenActivity cancelActivity; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private CodeActivity finalizeCodeActivity; private SetStateActivity setStateActivity5; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity step1IfElseBranchActivity_DoesFolderExist; private IfElseActivity ifElseActivity1; private SetStateActivity setStateActivity6; private StateActivity AddNewMediaFolderWorkflowInitialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/AddNewMediaFolderWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Workflow.Activities; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.Types; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; using Composite.Data.Validation.ClientValidationRules; using Composite.C1Console.Workflow; using Composite.C1Console.Workflow.Activities; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewMediaFolderWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddNewMediaFolderWorkflow() { InitializeComponent(); } private void initializeAddNewfolderCodeActivity_ExecuteCode(object sender, EventArgs e) { FormsWorkflow workflow = this.GetRoot<FormsWorkflow>(); string parentFolderPath; string storeId; if (this.EntityToken is MediaRootFolderProviderEntityToken) { MediaRootFolderProviderEntityToken token = (MediaRootFolderProviderEntityToken)this.EntityToken; storeId = token.Id; parentFolderPath = "/"; } else { DataEntityToken token = (DataEntityToken)this.EntityToken; IMediaFileFolder parentFolder = (IMediaFileFolder)token.Data; storeId = parentFolder.StoreId; parentFolderPath = parentFolder.Path; } IMediaFileStore store = DataFacade.GetData<IMediaFileStore>(x => x.Id == storeId).First(); IMediaFileFolder folder = DataFacade.BuildNew<IMediaFileFolder>(); folder.Path = parentFolderPath; workflow.Bindings.Add("NewFolder", folder); workflow.Bindings.Add("FolderName", ""); workflow.Bindings.Add("ProviderName", store.DataSourceId.ProviderName); workflow.Bindings.Add("ProvidesMetaData", false); workflow.BindingsValidationRules.Add("FolderName", new List<ClientValidationRule> { new NotNullClientValidationRule() }); } /*private string CreateFolderPath(IMediaFileFolder folder) { string folderName = this.GetBinding<string>("FolderName"); string folderPath = folder.Path; if (folderPath == "/") { folderPath = folderPath + folderName; } else { folderPath = folderPath + "/" + folderName; } folderPath = folderPath.Replace('\\', '/'); while (folderPath.Contains("//")) { folderPath.Replace("//", "/"); } if ((folderPath != "/") && (folderPath.StartsWith("/"))) { folderPath.Remove(0, 1); } return folderPath; }*/ private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken); IMediaFileFolder folder = this.GetBinding<IMediaFileFolder>("NewFolder"); string folderName = this.GetBinding<string>("FolderName"); string providerName = this.GetBinding<string>("ProviderName"); string folderPath = folder.CreateFolderPath(folderName); folder.Path = folderPath; if (folder.Title == string.Empty) { folder.Title = folderPath.GetFolderName('/'); } CreateParentFolder(folder.GetParentFolderPath(), providerName); folder = DataFacade.AddNew<IMediaFileFolder>(folder, providerName); addNewTreeRefresher.PostRefreshMesseges(folder.GetDataEntityToken()); SelectElement(folder.GetDataEntityToken()); } private void CreateParentFolder(string parentFolder, string providerName) { if (IMediaFileFolderUtils.DoesFolderExists(parentFolder)) return; CreateParentFolder(IMediaFileFolderUtils.GetParentFolderPath(parentFolder), providerName); IMediaFileFolder folder = DataFacade.BuildNew<IMediaFileFolder>(); folder.Path = parentFolder; DataFacade.AddNew<IMediaFileFolder>(folder, providerName); } private void ValidateInputs(object sender, ConditionalEventArgs e) { e.Result = true; IMediaFileFolder folder = this.GetBinding<IMediaFileFolder>("NewFolder"); string folderName = this.GetBinding<string>("FolderName"); string folderPath = folder.CreateFolderPath(folderName); string tempFolderName = folderName.Replace('\\', '/').Trim(); while (tempFolderName.Contains("//")) { tempFolderName = tempFolderName.Replace("//", "/"); } if (tempFolderName == "/") { e.Result = false; ShowFieldMessage("FolderName", StringResourceSystemFacade.GetString("Composite.Management", "Website.Forms.Administrative.AddNewMediaFolder.FolderNotOnlySlash")); return; } if (DataFacade.GetData<IMediaFileFolder>().Any(f => string.Compare(f.Path, folderPath, StringComparison.InvariantCultureIgnoreCase) == 0)) { e.Result = false; ShowFieldMessage("FolderName", StringResourceSystemFacade.GetString("Composite.Management", "Website.Forms.Administrative.AddNewMediaFolder.FolderNameAlreadyUsed")); } if (folderPath.Length > 2048) { e.Result = false; ShowFieldMessage("FolderName", StringResourceSystemFacade.GetString("Composite.Management", "Website.Forms.Administrative.AddNewMediaFolder.FolderNameTooLong")); } folderPath.IsCorrectFolderName('/'); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/AddNewMediaFolderWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1220; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="AddNewMediaFolderWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="235; 80" AutoSizeMargin="16; 24" Location="59; 101" Name="AddNewMediaFolderWorkflowInitialState"> <StateDesigner.Designers> <StateInitializationDesigner Name="stateInitializationActivity1" Size="150; 182" Location="67; 132"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeAddNewfolderCodeActivity" Size="130; 41" Location="77; 194" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="77; 254" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="211; 102" AutoSizeMargin="16; 24" AutoSize="False" Location="265; 263" Name="step1StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="stateInitializationActivity2" Size="150; 122" Location="441; 135"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizzardFormActivity1" Size="130; 41" Location="451; 197" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Finish" Size="381; 363" Location="449; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="574; 210" /> <IfElseDesigner Name="ifElseActivity1" Size="361; 222" Location="459; 270"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="step1IfElseBranchActivity_DoesFolderExist" Size="150; 122" Location="478; 341"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="488; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 122" Location="651; 341"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="661; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Cancel" Size="150; 182" Location="441; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="451; 245" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="451; 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="453; 472" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="stateInitializationActivity3" Size="150; 242" Location="461; 503"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity" Size="130; 41" Location="471; 565" /> <ActivityDesigner Name="closeCurrentViewActivity1" Size="130; 41" Location="471; 625" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="471; 685" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="868; 599" Name="finalStateActivity" /> <EventDrivenDesigner Name="cancelActivity" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="AddNewMediaFolderWorkflow" TargetConnectionIndex="0" SourceStateName="AddNewMediaFolderWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="cancelActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="142" Y="71" /> <ns0:Point X="948" Y="71" /> <ns0:Point X="948" Y="599" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity2" SourceActivity="AddNewMediaFolderWorkflowInitialState" TargetConnectionIndex="0" SourceStateName="AddNewMediaFolderWorkflowInitialState" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="stateInitializationActivity1" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="230" Y="142" /> <ns0:Point X="370" Y="142" /> <ns0:Point X="370" Y="263" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity6" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="468" Y="328" /> <ns0:Point X="540" Y="328" /> <ns0:Point X="540" Y="472" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity3" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="636" Y="169" /> <ns0:Point X="650" Y="169" /> <ns0:Point X="650" Y="96" /> <ns0:Point X="538" Y="96" /> <ns0:Point X="538" Y="104" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity5" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="472" Y="352" /> <ns0:Point X="948" Y="352" /> <ns0:Point X="948" Y="599" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity4" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="stateInitializationActivity3" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="624" Y="513" /> <ns0:Point X="948" Y="513" /> <ns0:Point X="948" Y="599" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/DeleteMediaFileWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { partial class DeleteMediaFileWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.branchHasNoRelatedData = new System.Workflow.Activities.IfElseBranchActivity(); this.branchHasRelatedData = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.ifElseHasRelatedData = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.deleteCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.eventDrivenActivity2 = new System.Workflow.Activities.EventDrivenActivity(); this.eventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity2 = new System.Workflow.Activities.StateInitializationActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.deleteEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.initializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.deleteEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.checkRelatedDataStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity1 = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.DeleteMediaFileWorkflowInitialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "DeleteMediaFileWorkflowInitialState"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "/Administrative/DeleteMediaFileConfirmRemovingRelatedData.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // branchHasNoRelatedData // this.branchHasNoRelatedData.Activities.Add(this.setStateActivity6); this.branchHasNoRelatedData.Name = "branchHasNoRelatedData"; // // branchHasRelatedData // this.branchHasRelatedData.Activities.Add(this.confirmDialogFormActivity1); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.HasDataReferences); this.branchHasRelatedData.Condition = codecondition1; this.branchHasRelatedData.Name = "branchHasRelatedData"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // ifElseHasRelatedData // this.ifElseHasRelatedData.Activities.Add(this.branchHasRelatedData); this.ifElseHasRelatedData.Activities.Add(this.branchHasNoRelatedData); this.ifElseHasRelatedData.Name = "ifElseHasRelatedData"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // deleteCodeActivity // this.deleteCodeActivity.Name = "deleteCodeActivity"; this.deleteCodeActivity.ExecuteCode += new System.EventHandler(this.deleteCodeActivity_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = null; this.wizzardFormActivity1.FormDefinitionFileName = "\\Administrative\\DeleteMediaFile.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // eventDrivenActivity2 // this.eventDrivenActivity2.Activities.Add(this.cancelHandleExternalEventActivity3); this.eventDrivenActivity2.Activities.Add(this.setStateActivity7); this.eventDrivenActivity2.Name = "eventDrivenActivity2"; // // eventDrivenActivity_Finish // this.eventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.eventDrivenActivity_Finish.Activities.Add(this.setStateActivity5); this.eventDrivenActivity_Finish.Name = "eventDrivenActivity_Finish"; // // stateInitializationActivity2 // this.stateInitializationActivity2.Activities.Add(this.ifElseHasRelatedData); this.stateInitializationActivity2.Name = "stateInitializationActivity2"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.deleteCodeActivity); this.stateInitializationActivity1.Activities.Add(this.closeCurrentViewActivity1); this.stateInitializationActivity1.Activities.Add(this.setStateActivity2); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // deleteEventDrivenActivity_Cancel // this.deleteEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.deleteEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity4); this.deleteEventDrivenActivity_Cancel.Name = "deleteEventDrivenActivity_Cancel"; // // initializationActivity // this.initializationActivity.Activities.Add(this.wizzardFormActivity1); this.initializationActivity.Name = "initializationActivity"; // // deleteEventDrivenActivity_Finish // this.deleteEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.deleteEventDrivenActivity_Finish.Activities.Add(this.setStateActivity3); this.deleteEventDrivenActivity_Finish.Name = "deleteEventDrivenActivity_Finish"; // // checkRelatedDataStateActivity // this.checkRelatedDataStateActivity.Activities.Add(this.stateInitializationActivity2); this.checkRelatedDataStateActivity.Activities.Add(this.eventDrivenActivity_Finish); this.checkRelatedDataStateActivity.Activities.Add(this.eventDrivenActivity2); this.checkRelatedDataStateActivity.Name = "checkRelatedDataStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.stateInitializationActivity1); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // eventDrivenActivity1 // this.eventDrivenActivity1.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity1.Activities.Add(this.setStateActivity1); this.eventDrivenActivity1.Name = "eventDrivenActivity1"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // DeleteMediaFileWorkflowInitialState // this.DeleteMediaFileWorkflowInitialState.Activities.Add(this.deleteEventDrivenActivity_Finish); this.DeleteMediaFileWorkflowInitialState.Activities.Add(this.initializationActivity); this.DeleteMediaFileWorkflowInitialState.Activities.Add(this.deleteEventDrivenActivity_Cancel); this.DeleteMediaFileWorkflowInitialState.Name = "DeleteMediaFileWorkflowInitialState"; // // DeleteMediaFileWorkflow // this.Activities.Add(this.DeleteMediaFileWorkflowInitialState); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity1); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.checkRelatedDataStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "checkRelatedDataStateActivity"; this.Name = "DeleteMediaFileWorkflow"; this.CanModifyActivities = false; } #endregion private EventDrivenActivity eventDrivenActivity1; private StateActivity finalStateActivity; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private CodeActivity deleteCodeActivity; private SetStateActivity setStateActivity1; private StateInitializationActivity stateInitializationActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity deleteEventDrivenActivity_Finish; private StateActivity finalizeStateActivity; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity wizzardFormActivity1; private StateInitializationActivity initializationActivity; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity deleteEventDrivenActivity_Cancel; private SetStateActivity setStateActivity6; private IfElseBranchActivity branchHasNoRelatedData; private IfElseBranchActivity branchHasRelatedData; private IfElseActivity ifElseHasRelatedData; private StateInitializationActivity stateInitializationActivity2; private StateActivity checkRelatedDataStateActivity; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private EventDrivenActivity eventDrivenActivity_Finish; private SetStateActivity setStateActivity7; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private EventDrivenActivity eventDrivenActivity2; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private StateActivity DeleteMediaFileWorkflowInitialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/DeleteMediaFileWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper; using Composite.Core.ResourceSystem; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteMediaFileWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeleteMediaFileWorkflow() { InitializeComponent(); } private void HasDataReferences(object sender, ConditionalEventArgs e) { IData mediaFile = ((DataEntityToken)this.EntityToken).Data; var brokenReferences = new List<IData>(); var references = DataReferenceFacade.GetNotOptionalReferences(mediaFile); foreach (var reference in references) { DataSourceId dataSourceId = reference.DataSourceId; if (brokenReferences.Any(brokenRef => brokenRef.DataSourceId == dataSourceId)) { continue; } brokenReferences.Add(reference); } e.Result = brokenReferences.Count > 0; if (brokenReferences.Count == 0) { return; } Bindings.Add("ReferencedData", DataReferenceFacade.GetBrokenReferencesReport(brokenReferences)); } private void deleteCodeActivity_ExecuteCode(object sender, EventArgs e) { DeleteTreeRefresher treeRefresher = this.CreateDeleteTreeRefresher(this.EntityToken); DataEntityToken token = (DataEntityToken)this.EntityToken; IMediaFile file = (IMediaFile)token.Data; if (DataFacade.WillDeleteSucceed(file)) { DataFacade.Delete(file); treeRefresher.PostRefreshMesseges(true); } else { this.ShowMessage( DialogType.Error, StringResourceSystemFacade.GetString("Composite.Management", "DeleteMediaFileWorkflow.CascadeDeleteErrorTitle"), StringResourceSystemFacade.GetString("Composite.Management", "DeleteMediaFileWorkflow.CascadeDeleteErrorMessage") ); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/DeleteMediaFileWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="DeleteMediaFileWorkflow" Location="30; 30" Size="904; 530" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="DeleteMediaFileWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="DeleteMediaFileWorkflow" EventHandlerName="eventDrivenActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="176" Y="71" /> <ns0:Point X="819" Y="71" /> <ns0:Point X="819" Y="235" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="DeleteMediaFileWorkflowInitialState" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="DeleteMediaFileWorkflowInitialState" EventHandlerName="deleteEventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="283" Y="493" /> <ns0:Point X="319" Y="493" /> <ns0:Point X="319" Y="436" /> <ns0:Point X="816" Y="436" /> <ns0:Point X="816" Y="444" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="DeleteMediaFileWorkflowInitialState" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="DeleteMediaFileWorkflowInitialState" EventHandlerName="deleteEventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="287" Y="517" /> <ns0:Point X="335" Y="517" /> <ns0:Point X="335" Y="227" /> <ns0:Point X="819" Y="227" /> <ns0:Point X="819" Y="235" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="stateInitializationActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="900" Y="485" /> <ns0:Point X="915" Y="485" /> <ns0:Point X="915" Y="227" /> <ns0:Point X="819" Y="227" /> <ns0:Point X="819" Y="235" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="DeleteMediaFileWorkflowInitialState" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="checkRelatedDataStateActivity" SourceConnectionEdge="Right" TargetActivity="DeleteMediaFileWorkflowInitialState" SourceActivity="checkRelatedDataStateActivity" EventHandlerName="stateInitializationActivity2"> <StateDesignerConnector.Segments> <ns0:Point X="234" Y="169" /> <ns0:Point X="288" Y="169" /> <ns0:Point X="288" Y="416" /> <ns0:Point X="184" Y="416" /> <ns0:Point X="184" Y="428" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="checkRelatedDataStateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="checkRelatedDataStateActivity" EventHandlerName="eventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="238" Y="193" /> <ns0:Point X="258" Y="193" /> <ns0:Point X="258" Y="416" /> <ns0:Point X="816" Y="416" /> <ns0:Point X="816" Y="444" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="checkRelatedDataStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="checkRelatedDataStateActivity" EventHandlerName="eventDrivenActivity2"> <StateDesignerConnector.Segments> <ns0:Point X="209" Y="217" /> <ns0:Point X="819" Y="217" /> <ns0:Point X="819" Y="235" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="DeleteMediaFileWorkflowInitialState" Location="77; 428" Size="214; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="deleteEventDrivenActivity_Finish" Location="85; 483"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="95; 545" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="95; 605" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateInitializationDesigner Size="150; 122" Name="initializationActivity" Location="85; 459"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="wizzardFormActivity1" Location="95; 521" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="deleteEventDrivenActivity_Cancel" Location="85; 507"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="95; 569" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="95; 629" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="739; 235" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity1" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="finalizeStateActivity" Location="729; 444" Size="175; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="stateInitializationActivity1" Location="737; 475"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="deleteCodeActivity" Location="747; 537" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="747; 597" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="747; 657" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="checkRelatedDataStateActivity" Location="63; 128" Size="183; 118" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 303" Name="stateInitializationActivity2" Location="250; 148"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="361; 222" Name="ifElseHasRelatedData" Location="260; 210"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="branchHasRelatedData" Location="279; 281"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="confirmDialogFormActivity1" Location="289; 343" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="branchHasNoRelatedData" Location="452; 281"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="462; 343" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_Finish" Location="242; 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity2" Location="252; 221" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="252; 281" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity2" Location="242; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity3" Location="252; 245" /> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="252; 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/DeleteMediaFolderWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { partial class DeleteMediaFolderWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.branchHasNoRelatedData = new System.Workflow.Activities.IfElseBranchActivity(); this.branchHasRelatedData = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseHasRelatedData = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.codeActivity1 = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.deleteCodeActivity = new System.Workflow.Activities.CodeActivity(); this.eventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.eventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity2 = new System.Workflow.Activities.StateInitializationActivity(); this.deleteEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.deleteEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.checkRelatedDataStateActivity = new System.Workflow.Activities.StateActivity(); this.confirmationStateActivity = new System.Workflow.Activities.StateActivity(); this.stateActivity1 = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity1 = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "confirmationStateActivity"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "/Administrative/DeleteMediaFolderConfirmDeletingRelatedData.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // branchHasNoRelatedData // this.branchHasNoRelatedData.Activities.Add(this.setStateActivity6); this.branchHasNoRelatedData.Name = "branchHasNoRelatedData"; // // branchHasRelatedData // this.branchHasRelatedData.Activities.Add(this.confirmDialogFormActivity1); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.HasDataReferences); this.branchHasRelatedData.Condition = codecondition1; this.branchHasRelatedData.Name = "branchHasRelatedData"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "stateActivity1"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // ifElseHasRelatedData // this.ifElseHasRelatedData.Activities.Add(this.branchHasRelatedData); this.ifElseHasRelatedData.Activities.Add(this.branchHasNoRelatedData); this.ifElseHasRelatedData.Name = "ifElseHasRelatedData"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "stateActivity1"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = null; this.wizzardFormActivity1.FormDefinitionFileName = "\\Administrative\\DeleteMediaFolder.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // codeActivity1 // this.codeActivity1.Name = "codeActivity1"; this.codeActivity1.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // deleteCodeActivity // this.deleteCodeActivity.Name = "deleteCodeActivity"; this.deleteCodeActivity.ExecuteCode += new System.EventHandler(this.deleteCodeActivity_ExecuteCode); // // eventDrivenActivity_Finish // this.eventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.eventDrivenActivity_Finish.Activities.Add(this.setStateActivity5); this.eventDrivenActivity_Finish.Name = "eventDrivenActivity_Finish"; // // eventDrivenActivity_Cancel // this.eventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.eventDrivenActivity_Cancel.Activities.Add(this.setStateActivity7); this.eventDrivenActivity_Cancel.Name = "eventDrivenActivity_Cancel"; // // stateInitializationActivity2 // this.stateInitializationActivity2.Activities.Add(this.ifElseHasRelatedData); this.stateInitializationActivity2.Name = "stateInitializationActivity2"; // // deleteEventDrivenActivity_Cancel // this.deleteEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.deleteEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity4); this.deleteEventDrivenActivity_Cancel.Name = "deleteEventDrivenActivity_Cancel"; // // deleteEventDrivenActivity_Finish // this.deleteEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.deleteEventDrivenActivity_Finish.Activities.Add(this.setStateActivity2); this.deleteEventDrivenActivity_Finish.Name = "deleteEventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.codeActivity1); this.step1StateInitializationActivity.Activities.Add(this.wizzardFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // finalizeActivity // this.finalizeActivity.Activities.Add(this.deleteCodeActivity); this.finalizeActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeActivity.Activities.Add(this.setStateActivity3); this.finalizeActivity.Name = "finalizeActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // checkRelatedDataStateActivity // this.checkRelatedDataStateActivity.Activities.Add(this.stateInitializationActivity2); this.checkRelatedDataStateActivity.Activities.Add(this.eventDrivenActivity_Cancel); this.checkRelatedDataStateActivity.Activities.Add(this.eventDrivenActivity_Finish); this.checkRelatedDataStateActivity.Name = "checkRelatedDataStateActivity"; // // confirmationStateActivity // this.confirmationStateActivity.Activities.Add(this.step1StateInitializationActivity); this.confirmationStateActivity.Activities.Add(this.deleteEventDrivenActivity_Finish); this.confirmationStateActivity.Activities.Add(this.deleteEventDrivenActivity_Cancel); this.confirmationStateActivity.Name = "confirmationStateActivity"; // // stateActivity1 // this.stateActivity1.Activities.Add(this.finalizeActivity); this.stateActivity1.Name = "stateActivity1"; // // eventDrivenActivity1 // this.eventDrivenActivity1.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity1.Activities.Add(this.setStateActivity1); this.eventDrivenActivity1.Name = "eventDrivenActivity1"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // DeleteMediaFolderWorkflow // this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity1); this.Activities.Add(this.stateActivity1); this.Activities.Add(this.confirmationStateActivity); this.Activities.Add(this.checkRelatedDataStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "checkRelatedDataStateActivity"; this.Name = "DeleteMediaFolderWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity3; private CodeActivity deleteCodeActivity; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity finalizeActivity; private EventDrivenActivity eventDrivenActivity1; private StateActivity finalStateActivity; private SetStateActivity setStateActivity1; private StateActivity stateActivity1; private StateInitializationActivity step1StateInitializationActivity; private SetStateActivity setStateActivity2; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity wizzardFormActivity1; private EventDrivenActivity deleteEventDrivenActivity_Finish; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity deleteEventDrivenActivity_Cancel; private CodeActivity codeActivity1; private SetStateActivity setStateActivity6; private IfElseBranchActivity branchHasNoRelatedData; private IfElseBranchActivity branchHasRelatedData; private SetStateActivity setStateActivity7; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private IfElseActivity ifElseHasRelatedData; private EventDrivenActivity eventDrivenActivity_Cancel; private StateInitializationActivity stateInitializationActivity2; private StateActivity checkRelatedDataStateActivity; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private EventDrivenActivity eventDrivenActivity_Finish; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private StateActivity confirmationStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/DeleteMediaFolderWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.Types; using Composite.Data.Types.StoreIdFilter; using Composite.Core.Linq; using Composite.Data.Transactions; using Composite.C1Console.Workflow; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Management; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteMediaFolderWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeleteMediaFolderWorkflow() { InitializeComponent(); } private void HasDataReferences(object sender, ConditionalEventArgs e) { var token = (DataEntityToken)this.EntityToken; var folder = (IMediaFileFolder)token.Data; string storeId = folder.StoreId; string parentPath = folder.Path; string innerElementsPathPrefix = $"{parentPath}/"; var fileQueryable = new StoreIdFilterQueryable<IMediaFile>(DataFacade.GetData<IMediaFile>(), storeId); IEnumerable<IMediaFile> childFiles = (from item in fileQueryable where item.FolderPath.StartsWith(innerElementsPathPrefix) || item.FolderPath == parentPath select item).Evaluate(); var brokenReferences = new List<IData>(); foreach (IMediaFile mediaFile in childFiles) { List<IData> references = DataReferenceFacade.GetNotOptionalReferences(mediaFile); foreach (IData reference in references) { if (brokenReferences.Any(data => data.DataSourceId.Equals(reference.DataSourceId))) { continue; } brokenReferences.Add(reference); } } e.Result = brokenReferences.Count > 0; if (brokenReferences.Count == 0) { return; } Bindings.Add("ReferencedData", DataReferenceFacade.GetBrokenReferencesReport(brokenReferences)); } private void deleteCodeActivity_ExecuteCode(object sender, EventArgs e) { DeleteTreeRefresher treeRefresher = this.CreateDeleteTreeRefresher(this.EntityToken); DataEntityToken token = (DataEntityToken)this.EntityToken; using (var transactionScope = TransactionsFacade.CreateNewScope()) { IMediaFileFolder folder = DataFacade.GetDataFromDataSourceId(token.DataSourceId, false) as IMediaFileFolder; // Media folder may already be deleted at this point if (folder != null) { if (!DataFacade.WillDeleteSucceed(folder)) { this.ShowMessage(DialogType.Error, Texts.DeleteMediaFolderWorkflow_CascadeDeleteErrorTitle, Texts.DeleteMediaFolderWorkflow_CascadeDeleteErrorMessage); return; } DataFacade.Delete(folder); } transactionScope.Complete(); } treeRefresher.PostRefreshMesseges(); } private void codeActivity1_ExecuteCode(object sender, EventArgs e) { var token = (DataEntityToken)this.EntityToken; var folder = (IMediaFileFolder)token.Data; string storeId = folder.StoreId; string parentPath = folder.Path; var folderQueryable = new StoreIdFilterQueryable<IMediaFileFolder>(DataFacade.GetData<IMediaFileFolder>(), storeId); var fileQueryable = new StoreIdFilterQueryable<IMediaFile>(DataFacade.GetData<IMediaFile>(), storeId); string innerElementsPathPrefix = $"{parentPath}/"; bool anyFiles = (from item in fileQueryable where item.FolderPath.StartsWith(innerElementsPathPrefix) || item.FolderPath == parentPath select item).Any(); bool anyFolders = (from item in folderQueryable where item.Path.StartsWith(innerElementsPathPrefix) select item).Any(); var message = !anyFiles && !anyFolders ? Texts.Website_Forms_Administrative_DeleteMediaFolder_Text : Texts.Website_Forms_Administrative_DeleteMediaFolder_HasChildringText; this.Bindings.Add("MessageText", message); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/DeleteMediaFolderWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="DeleteMediaFolderWorkflow" Location="30; 30" Size="948; 486" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="DeleteMediaFolderWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="DeleteMediaFolderWorkflow" EventHandlerName="eventDrivenActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="176" Y="71" /> <ns0:Point X="868" Y="71" /> <ns0:Point X="868" Y="406" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="stateActivity1" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="stateActivity1" EventHandlerName="finalizeActivity"> <StateDesignerConnector.Segments> <ns0:Point X="607" Y="256" /> <ns0:Point X="868" Y="256" /> <ns0:Point X="868" Y="406" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="stateActivity1" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="confirmationStateActivity" SourceConnectionEdge="Right" TargetActivity="stateActivity1" SourceActivity="confirmationStateActivity" EventHandlerName="deleteEventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="302" Y="411" /> <ns0:Point X="322" Y="411" /> <ns0:Point X="322" Y="207" /> <ns0:Point X="572" Y="207" /> <ns0:Point X="572" Y="215" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="confirmationStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="confirmationStateActivity" EventHandlerName="deleteEventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="306" Y="435" /> <ns0:Point X="322" Y="435" /> <ns0:Point X="322" Y="398" /> <ns0:Point X="868" Y="398" /> <ns0:Point X="868" Y="406" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="confirmationStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="checkRelatedDataStateActivity" SourceConnectionEdge="Right" TargetActivity="confirmationStateActivity" SourceActivity="checkRelatedDataStateActivity" EventHandlerName="stateInitializationActivity2"> <StateDesignerConnector.Segments> <ns0:Point X="287" Y="150" /> <ns0:Point X="307" Y="150" /> <ns0:Point X="307" Y="334" /> <ns0:Point X="203" Y="334" /> <ns0:Point X="203" Y="346" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="checkRelatedDataStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="checkRelatedDataStateActivity" EventHandlerName="eventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="295" Y="174" /> <ns0:Point X="868" Y="174" /> <ns0:Point X="868" Y="406" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="stateActivity1" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="checkRelatedDataStateActivity" SourceConnectionEdge="Right" TargetActivity="stateActivity1" SourceActivity="checkRelatedDataStateActivity" EventHandlerName="eventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="291" Y="198" /> <ns0:Point X="572" Y="198" /> <ns0:Point X="572" Y="215" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="finalStateActivity" Location="788; 406" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity1" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="stateActivity1" Location="492; 215" Size="160; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="finalizeActivity" Location="500; 246"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="deleteCodeActivity" Location="510; 308" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="510; 368" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="510; 428" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="confirmationStateActivity" Location="96; 346" Size="214; 102" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="step1StateInitializationActivity" Location="104; 377"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="codeActivity1" Location="114; 439" /> <ActivityDesigner Size="130; 41" Name="wizzardFormActivity1" Location="114; 499" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="deleteEventDrivenActivity_Finish" Location="104; 401"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="114; 463" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="114; 523" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="deleteEventDrivenActivity_Cancel" Location="104; 425"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="114; 487" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="114; 547" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="checkRelatedDataStateActivity" Location="116; 109" Size="183; 118" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 303" Name="stateInitializationActivity2" Location="250; 148"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="361; 222" Name="ifElseHasRelatedData" Location="260; 210"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="branchHasRelatedData" Location="279; 281"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="confirmDialogFormActivity1" Location="289; 343" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="branchHasNoRelatedData" Location="452; 281"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="462; 343" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_Cancel" Location="242; 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity3" Location="252; 221" /> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="252; 281" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_Finish" Location="242; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity2" Location="252; 245" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="252; 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/EditMediaFileContentWorkflow.cs ================================================ using System; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] /// <summary> /// Fictive workflow. Is used by ImageManipulatior in order to raise events in task system /// </summary> public sealed partial class EditMediaFileContentWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditMediaFileContentWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { DataEntityToken token = (DataEntityToken)this.EntityToken; IMediaFile file = (IMediaFile)token.Data; this.Bindings.Add("FileName", file.FileName); this.Bindings.Add("FileMimeType", file.MimeType); SetSaveStatus(true); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/EditMediaFileContentWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { partial class EditMediaFileContentWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initialStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity1); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initialState // this.initialState.Activities.Add(this.initialStateInitializationActivity); this.initialState.Name = "initialState"; // // EditMediaFileContentWorkflow // this.Activities.Add(this.initialState); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelEventDrivenActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialState"; this.Name = "EditMediaFileContentWorkflow"; this.CanModifyActivities = false; } #endregion private CodeActivity initializeCodeActivity; private SetStateActivity setStateActivity1; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initialStateInitializationActivity; private EventDrivenActivity cancelEventDrivenActivity; private StateActivity finalStateActivity; private SetStateActivity setStateActivity2; private StateActivity initialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/EditMediaFileContentWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="EditMediaFileContentWorkflow" Location="30; 30" Size="1086; 642" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="EditMediaFileContentWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="EditMediaFileContentWorkflow" EventHandlerName="cancelEventDrivenActivity"> <StateDesignerConnector.Segments> <ns0:Point X="202" Y="71" /> <ns0:Point X="664" Y="71" /> <ns0:Point X="664" Y="285" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Bottom" SetStateName="setStateActivity2" SourceStateName="initialState" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="initialState" EventHandlerName="initialStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="238" /> <ns0:Point X="578" Y="238" /> <ns0:Point X="578" Y="389" /> <ns0:Point X="653" Y="389" /> <ns0:Point X="653" Y="365" /> <ns0:Point X="664" Y="365" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initialState" Location="63; 197" Size="197; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initialStateInitializationActivity" Location="71; 228"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity" Location="81; 290" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="81; 350" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="584; 285" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="cancelEventDrivenActivity" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/EditMediaFileTextContentWorkflow.cs ================================================ using System; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditMediaFileTextContentWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditMediaFileTextContentWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { DataEntityToken token = (DataEntityToken)this.EntityToken; IMediaFile file = (IMediaFile)token.Data; string content = file.ReadAllText(); this.Bindings.Add("FileContent", content); this.Bindings.Add("FileName", file.FileName); this.Bindings.Add("FileMimeType", file.MimeType); } private void saveCodeActivity_ExecuteCode(object sender, EventArgs e) { DataEntityToken token = (DataEntityToken)this.EntityToken; IMediaFile file = (IMediaFile)token.Data; string content = this.GetBinding<string>("FileContent"); file.SetNewContent(content); DataFacade.Update(file); SetSaveStatus(true); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/EditMediaFileTextContentWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { partial class EditMediaFileTextContentWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.initialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // saveCodeActivity // this.saveCodeActivity.Name = "saveCodeActivity"; this.saveCodeActivity.ExecuteCode += new System.EventHandler(this.saveCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "saveStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.FormDefinitionFileName = "/Administrative/EditMediaFileTextContent.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.saveCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // eventDrivenActivity_Save // this.eventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.eventDrivenActivity_Save.Activities.Add(this.setStateActivity3); this.eventDrivenActivity_Save.Name = "eventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initialStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity1); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.eventDrivenActivity_Save); this.editStateActivity.Name = "editStateActivity"; // // initialState // this.initialState.Activities.Add(this.initialStateInitializationActivity); this.initialState.Name = "initialState"; // // EditMediaFileTextContentWorkflow // this.Activities.Add(this.initialState); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelEventDrivenActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialState"; this.Name = "EditMediaFileTextContentWorkflow"; this.CanModifyActivities = false; } #endregion private CodeActivity initializeCodeActivity; private SetStateActivity setStateActivity1; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initialStateInitializationActivity; private EventDrivenActivity cancelEventDrivenActivity; private StateActivity finalStateActivity; private StateActivity saveStateActivity; private StateActivity editStateActivity; private Composite.C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private StateInitializationActivity editStateInitializationActivity; private StateInitializationActivity finalizeStateInitializationActivity; private CodeActivity saveCodeActivity; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity eventDrivenActivity_Save; private SetStateActivity setStateActivity4; private StateActivity initialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/EditMediaFileWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { partial class EditMediaFileWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity1 = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.editMediaFileStateActivity = new System.Workflow.Activities.StateActivity(); this.initialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "editMediaFileStateActivity"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity5); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity3); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateInputs); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editMediaFileStateActivity"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ExecuteCode); // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.CustomToolbarDefinitionFileName = null; this.documentFormActivity1.FormDefinitionFileName = "/Administrative/EditMediaFile.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editMediaFileStateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // eventDrivenActivity_Save // this.eventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.eventDrivenActivity_Save.Activities.Add(this.ifElseActivity1); this.eventDrivenActivity_Save.Name = "eventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initialStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // eventDrivenActivity1 // this.eventDrivenActivity1.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity1.Activities.Add(this.setStateActivity1); this.eventDrivenActivity1.Name = "eventDrivenActivity1"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // editMediaFileStateActivity // this.editMediaFileStateActivity.Activities.Add(this.editStateInitializationActivity); this.editMediaFileStateActivity.Activities.Add(this.eventDrivenActivity_Save); this.editMediaFileStateActivity.Name = "editMediaFileStateActivity"; // // initialState // this.initialState.Activities.Add(this.initialStateInitializationActivity); this.initialState.Name = "initialState"; // // EditMediaFileWorkflow // this.Activities.Add(this.initialState); this.Activities.Add(this.editMediaFileStateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity1); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialState"; this.Name = "EditMediaFileWorkflow"; this.CanModifyActivities = false; } #endregion private CodeActivity initializeCodeActivity; private SetStateActivity setStateActivity1; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initialStateInitializationActivity; private EventDrivenActivity eventDrivenActivity1; private StateActivity finalStateActivity; private StateActivity finalizeStateActivity; private StateActivity editMediaFileStateActivity; private Composite.C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private StateInitializationActivity editStateInitializationActivity; private StateInitializationActivity finalizeStateInitializationActivity; private CodeActivity finalizeCodeActivity; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity eventDrivenActivity_Save; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity5; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private StateActivity initialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/EditMediaFileWorkflow.cs ================================================ using System; using System.Linq; using Composite.C1Console.Actions; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Workflow; using System.Workflow.Activities; using System.Collections.Generic; using Composite.Data.Validation.ClientValidationRules; using Composite.Data.Validation; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditMediaFileWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditMediaFileWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { DataEntityToken token = (DataEntityToken)this.EntityToken; IMediaFile file = (IMediaFile)token.Data; IMediaFileStore store = DataFacade.GetData<IMediaFileStore>(x => x.Id == file.StoreId).First(); var mediaURL = Composite.Core.Routing.MediaUrls.BuildUrl(file); this.Bindings.Add("FileDataFileName", file.FileName); this.Bindings.Add("FileDataTitle", file.Title); this.Bindings.Add("FileDataURL", mediaURL); this.Bindings.Add("FileDataDescription", file.Description); this.Bindings.Add("FileDataTags", file.Tags); this.Bindings.Add("ProvidesMetaData", store.ProvidesMetadata); this.BindingsValidationRules.Add("FileDataTitle", new List<ClientValidationRule> { new StringLengthClientValidationRule(0, 256) }); } private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken); DataEntityToken token = (DataEntityToken)this.EntityToken; IMediaFile file = (IMediaFile)token.Data; IMediaFileStore store = DataFacade.GetData<IMediaFileStore>(x => x.Id == file.StoreId).First(); file.FileName = this.GetBinding<string>("FileDataFileName"); file.Title = this.GetBinding<string>("FileDataTitle"); file.Description = this.GetBinding<string>("FileDataDescription"); file.Tags = this.GetBinding<string>("FileDataTags"); DataFacade.Update(file); SetSaveStatus(true); updateTreeRefresher.PostRefreshMesseges(file.GetDataEntityToken()); } private void ValidateInputs(object sender, ConditionalEventArgs e) { IMediaFile file = this.GetDataItemFromEntityToken<IMediaFile>(); string filename = this.GetBinding<string>("FileDataFileName"); string compositePath = IMediaFileExtensions.GetCompositePath(file.StoreId, file.FolderPath, filename); if (compositePath.Length > 2048) { this.ShowFieldMessage("FileDataFileName", "${Composite.Management, Website.Forms.Administrative.EditMediaFile.TotalFilenameToLong.Message}"); e.Result = false; return; } Guid mediaFileId = file.Id; if(DataFacade.GetData<IMediaFile>() .Any(mediaFile => string.Compare(mediaFile.CompositePath, compositePath, StringComparison.InvariantCultureIgnoreCase) == 0 && mediaFile.Id != mediaFileId)) { this.ShowFieldMessage("FileDataFileName", "${Composite.Management, Website.Forms.Administrative.EditMediaFile.FileExists.Message}"); e.Result = false; return; } e.Result = true; } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/EditMediaFileWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1190; 986" AutoSizeMargin="16; 24" Location="30; 30" Name="EditMediaFileWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="197; 80" AutoSizeMargin="16; 24" Location="84; 105" Name="initialState"> <StateDesigner.Designers> <StateInitializationDesigner Name="initialStateInitializationActivity" Size="150; 182" Location="92; 136"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity" Size="130; 41" Location="102; 198" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="102; 258" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="189; 94" AutoSizeMargin="16; 24" Location="269; 290" Name="editMediaFileStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="editStateInitializationActivity" Size="150; 122" Location="277; 321"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="documentFormActivity1" Size="130; 41" Location="287; 383" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="eventDrivenActivity_Save" Size="381; 363" Location="277; 345"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130; 41" Location="402; 407" /> <IfElseDesigner Name="ifElseActivity1" Size="361; 222" Location="287; 467"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 122" Location="306; 538"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="316; 600" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 122" Location="479; 538"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="489; 600" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" Location="608; 408" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 182" Location="616; 439"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity" Size="130; 41" Location="626; 501" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="626; 561" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="1017; 853" Name="finalStateActivity" /> <EventDrivenDesigner Name="eventDrivenActivity1" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="EditMediaFileWorkflow" TargetConnectionIndex="0" SourceStateName="EditMediaFileWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity1" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="176" Y="71" /> <ns0:Point X="1097" Y="71" /> <ns0:Point X="1097" Y="853" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editMediaFileStateActivity" SetStateName="setStateActivity2" SourceActivity="initialState" TargetConnectionIndex="0" SourceStateName="initialState" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initialStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editMediaFileStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="277" Y="146" /> <ns0:Point X="363" Y="146" /> <ns0:Point X="363" Y="290" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity3" SourceActivity="editMediaFileStateActivity" TargetConnectionIndex="0" SourceStateName="editMediaFileStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="439" Y="355" /> <ns0:Point X="710" Y="355" /> <ns0:Point X="710" Y="408" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editMediaFileStateActivity" SetStateName="setStateActivity5" SourceActivity="editMediaFileStateActivity" TargetConnectionIndex="0" SourceStateName="editMediaFileStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="editMediaFileStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="439" Y="355" /> <ns0:Point X="467" Y="355" /> <ns0:Point X="467" Y="282" /> <ns0:Point X="363" Y="282" /> <ns0:Point X="363" Y="290" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editMediaFileStateActivity" SetStateName="setStateActivity4" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editMediaFileStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="809" Y="449" /> <ns0:Point X="819" Y="449" /> <ns0:Point X="819" Y="282" /> <ns0:Point X="363" Y="282" /> <ns0:Point X="363" Y="290" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/EditMediaFolderWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { partial class EditMediaFolderWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.saveEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializationStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity1 = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.eidtStateActivity = new System.Workflow.Activities.StateActivity(); this.initialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "eidtStateActivity"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalizeStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity2); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity5); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateInputs); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "eidtStateActivity"; // // saveCodeActivity // this.saveCodeActivity.Name = "saveCodeActivity"; this.saveCodeActivity.ExecuteCode += new System.EventHandler(this.saveCodeActivity_ExecuteCode); // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.CustomToolbarDefinitionFileName = null; this.documentFormActivity1.FormDefinitionFileName = "\\Administrative\\EditMediaFolder.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "eidtStateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.saveCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // saveEventDrivenActivity // this.saveEventDrivenActivity.Activities.Add(this.saveHandleExternalEventActivity1); this.saveEventDrivenActivity.Activities.Add(this.ifElseActivity1); this.saveEventDrivenActivity.Name = "saveEventDrivenActivity"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initializationStateInitializationActivity // this.initializationStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initializationStateInitializationActivity.Activities.Add(this.setStateActivity3); this.initializationStateInitializationActivity.Name = "initializationStateInitializationActivity"; // // eventDrivenActivity1 // this.eventDrivenActivity1.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity1.Activities.Add(this.setStateActivity1); this.eventDrivenActivity1.Name = "eventDrivenActivity1"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // eidtStateActivity // this.eidtStateActivity.Activities.Add(this.editStateInitializationActivity); this.eidtStateActivity.Activities.Add(this.saveEventDrivenActivity); this.eidtStateActivity.Name = "eidtStateActivity"; // // initialState // this.initialState.Activities.Add(this.initializationStateInitializationActivity); this.initialState.Name = "initialState"; // // EditMediaFolderWorkflow // this.Activities.Add(this.initialState); this.Activities.Add(this.eidtStateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity1); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialState"; this.Name = "EditMediaFolderWorkflow"; this.CanModifyActivities = false; } #endregion private StateInitializationActivity finalizeStateInitializationActivity; private StateInitializationActivity editStateInitializationActivity; private StateInitializationActivity initializationStateInitializationActivity; private StateActivity finalStateActivity; private StateActivity finalizeStateActivity; private StateActivity eidtStateActivity; private CodeActivity initializeCodeActivity; private SetStateActivity setStateActivity1; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity1; private SetStateActivity setStateActivity2; private Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private EventDrivenActivity saveEventDrivenActivity; private Composite.C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private SetStateActivity setStateActivity3; private CodeActivity saveCodeActivity; private SetStateActivity setStateActivity4; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private SetStateActivity setStateActivity5; private StateActivity initialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/EditMediaFolderWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.Data; using Composite.Data.Types; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; using Composite.Data.Validation.ClientValidationRules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditMediaFolderWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditMediaFolderWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { IMediaFileFolder folder = this.GetDataItemFromEntityToken<IMediaFileFolder>(); IMediaFileStore store = DataFacade.GetData<IMediaFileStore>(x => x.Id == folder.StoreId).First(); this.Bindings.Add("FolderTitle", folder.Title); this.Bindings.Add("FolderDescription", folder.Description); this.Bindings.Add("FolderName", folder.Path.GetFolderName('/')); this.Bindings.Add("ProvidesMetaData", store.ProvidesMetadata); this.Bindings.Add("OldFolderPath", folder.Path); this.BindingsValidationRules.Add("FolderName", new List<ClientValidationRule> { new NotNullClientValidationRule() }); this.BindingsValidationRules.Add("FolderTitle", new List<ClientValidationRule> { new StringLengthClientValidationRule(0, 256) }); } private string CreateFolderPath() { string updatedFoldername = this.GetBinding<string>("FolderName"); string folderPath = this.GetBinding<string>("OldFolderPath"); string currentName = folderPath.GetFolderName('/'); folderPath = folderPath.Remove(folderPath.Length - currentName.Length); folderPath = folderPath + updatedFoldername; return folderPath; } private void saveCodeActivity_ExecuteCode(object sender, EventArgs e) { UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken); IMediaFileFolder folder = this.GetDataItemFromEntityToken<IMediaFileFolder>(); folder.Path = CreateFolderPath(); folder.Title = this.GetBinding<string>("FolderTitle"); folder.Description = this.GetBinding<string>("FolderDescription"); DataFacade.Update(folder); SetSaveStatus(true); updateTreeRefresher.PostRefreshMesseges(folder.GetDataEntityToken()); } private void ValidateInputs(object sender, ConditionalEventArgs e) { IMediaFileFolder folder = this.GetDataItemFromEntityToken<IMediaFileFolder>(); string oldFolderPath = this.GetBinding<string>("OldFolderPath"); string folderPath = CreateFolderPath(); if (oldFolderPath != folderPath) { Guid folderId = folder.Id; if (DataFacade.GetData<IMediaFileFolder>() .Any(f => string.Compare(f.Path, folderPath, StringComparison.OrdinalIgnoreCase) == 0 && f.Id != folderId)) { ShowFieldMessage("FolderName", StringResourceSystemFacade.GetString("Composite.Management", "Website.Forms.Administrative.AddNewMediaFolder.FolderNameAlreadyUsed")); e.Result = false; return; } IEnumerable<string> filenames = DataFacade.GetData<IMediaFile>().Where(f => f.FolderPath == oldFolderPath).Select(f => f.FileName); foreach (string filename in filenames) { string compositePath = IMediaFileExtensions.GetCompositePath(folder.StoreId, folderPath, filename); if (compositePath.Length > 2048) { this.ShowFieldMessage("FolderName", "${Composite.Management, Website.Forms.Administrative.EditMediaFolder.TotalFilenameToLong.Message}"); e.Result = false; return; } } } e.Result = true; } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/EditMediaFolderWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1190; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="EditMediaFolderWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="229; 80" AutoSizeMargin="16; 24" Location="63; 105" Name="initialState"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializationStateInitializationActivity" Size="150; 182" Location="71; 136"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity" Size="130; 41" Location="81; 198" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="81; 258" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="189; 94" AutoSizeMargin="16; 24" AutoSize="False" Location="155; 346" Name="eidtStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="editStateInitializationActivity" Size="150; 122" Location="426; 135"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="documentFormActivity1" Size="130; 41" Location="436; 197" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="saveEventDrivenActivity" Size="381; 363" Location="434; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130; 41" Location="559; 210" /> <IfElseDesigner Name="ifElseActivity1" Size="361; 222" Location="444; 270"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 122" Location="463; 341"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="473; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 122" Location="636; 341"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="646; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="485; 491" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 182" Location="493; 522"> <StateInitializationDesigner.Designers> <CodeDesigner Name="saveCodeActivity" Size="130; 41" Location="503; 584" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="503; 644" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="733; 624" Name="finalStateActivity" /> <EventDrivenDesigner Name="eventDrivenActivity1" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="EditMediaFolderWorkflow" TargetConnectionIndex="0" SourceStateName="EditMediaFolderWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity1" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="176" Y="71" /> <ns0:Point X="813" Y="71" /> <ns0:Point X="813" Y="624" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="eidtStateActivity" SetStateName="setStateActivity3" SourceActivity="initialState" TargetConnectionIndex="0" SourceStateName="initialState" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializationStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="eidtStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="288" Y="146" /> <ns0:Point X="297" Y="146" /> <ns0:Point X="297" Y="334" /> <ns0:Point X="249" Y="334" /> <ns0:Point X="249" Y="346" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity5" SourceActivity="eidtStateActivity" TargetConnectionIndex="0" SourceStateName="eidtStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="saveEventDrivenActivity" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="318" Y="411" /> <ns0:Point X="587" Y="411" /> <ns0:Point X="587" Y="491" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="eidtStateActivity" SetStateName="setStateActivity2" SourceActivity="eidtStateActivity" TargetConnectionIndex="0" SourceStateName="eidtStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="saveEventDrivenActivity" SourceConnectionIndex="1" TargetStateName="eidtStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="581" Y="169" /> <ns0:Point X="616" Y="169" /> <ns0:Point X="616" Y="96" /> <ns0:Point X="512" Y="96" /> <ns0:Point X="512" Y="104" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="eidtStateActivity" SetStateName="setStateActivity4" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="eidtStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="686" Y="532" /> <ns0:Point X="697" Y="532" /> <ns0:Point X="697" Y="338" /> <ns0:Point X="249" Y="338" /> <ns0:Point X="249" Y="346" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/UploadNewMediaFileWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { partial class UploadNewMediaFileWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.showConsoleMessageBoxActivity1 = new Composite.C1Console.Workflow.Activities.ShowConsoleMessageBoxActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.codeActivity1 = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity2 = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finishEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity2 = new System.Workflow.Activities.StateInitializationActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity1 = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.showUploadStateActivity = new System.Workflow.Activities.StateActivity(); this.initialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "showUploadStateActivity"; // // showConsoleMessageBoxActivity1 // this.showConsoleMessageBoxActivity1.DialogType = Composite.C1Console.Events.DialogType.Error; this.showConsoleMessageBoxActivity1.Message = "${Composite.Management,Website.Forms.Administrative.UploadMediaFile.EmptyFileErro" + "rMessage}"; this.showConsoleMessageBoxActivity1.Name = "showConsoleMessageBoxActivity1"; this.showConsoleMessageBoxActivity1.Title = "${Composite.Management,Website.Forms.Administrative.UploadMediaFile.EmptyFileErro" + "rTitle}"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // codeActivity1 // this.codeActivity1.Name = "codeActivity1"; this.codeActivity1.ExecuteCode += new System.EventHandler(this.uploadCodeActivity_ExecuteCode); // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.showConsoleMessageBoxActivity1); this.ifElseBranchActivity2.Activities.Add(this.setStateActivity4); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.codeActivity1); this.ifElseBranchActivity1.Activities.Add(this.closeCurrentViewActivity1); this.ifElseBranchActivity1.Activities.Add(this.setStateActivity3); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.HasUserUploaded); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = null; this.wizzardFormActivity1.FormDefinitionFileName = "/Administrative/UploadNewMediaFile.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "showUploadStateActivity"; // // codeActivity2 // this.codeActivity2.Name = "codeActivity2"; this.codeActivity2.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity2); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity5); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finishEventDrivenActivity // this.finishEventDrivenActivity.Activities.Add(this.finishHandleExternalEventActivity1); this.finishEventDrivenActivity.Activities.Add(this.ifElseActivity1); this.finishEventDrivenActivity.Name = "finishEventDrivenActivity"; // // stateInitializationActivity2 // this.stateInitializationActivity2.Activities.Add(this.wizzardFormActivity1); this.stateInitializationActivity2.Name = "stateInitializationActivity2"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.codeActivity2); this.stateInitializationActivity1.Activities.Add(this.setStateActivity2); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // eventDrivenActivity1 // this.eventDrivenActivity1.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity1.Activities.Add(this.setStateActivity1); this.eventDrivenActivity1.Name = "eventDrivenActivity1"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // showUploadStateActivity // this.showUploadStateActivity.Activities.Add(this.stateInitializationActivity2); this.showUploadStateActivity.Activities.Add(this.finishEventDrivenActivity); this.showUploadStateActivity.Activities.Add(this.cancelEventDrivenActivity); this.showUploadStateActivity.Name = "showUploadStateActivity"; // // initialState // this.initialState.Activities.Add(this.stateInitializationActivity1); this.initialState.Name = "initialState"; // // UploadNewMediaFileWorkflow // this.Activities.Add(this.initialState); this.Activities.Add(this.showUploadStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity1); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialState"; this.Name = "UploadNewMediaFileWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity finalStateActivity; private StateActivity showUploadStateActivity; private StateInitializationActivity stateInitializationActivity1; private CodeActivity codeActivity1; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.DataDialogFormActivity wizzardFormActivity1; private SetStateActivity setStateActivity2; private CodeActivity codeActivity2; private SetStateActivity setStateActivity1; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity finishEventDrivenActivity; private StateInitializationActivity stateInitializationActivity2; private EventDrivenActivity eventDrivenActivity1; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity4; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity cancelEventDrivenActivity; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private Composite.C1Console.Workflow.Activities.ShowConsoleMessageBoxActivity showConsoleMessageBoxActivity1; private StateActivity initialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/UploadNewMediaFileWorkflow.cs ================================================ using System; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Workflow; using Composite.C1Console.Workflow.Activities; using Composite.Core.IO; using Composite.Core.ResourceSystem; using Composite.Data; using Composite.Data.Types; namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Never)] public sealed partial class UploadNewMediaFileWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public UploadNewMediaFileWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { FormsWorkflow workflow = this.GetRoot<FormsWorkflow>(); DataEntityToken token = (DataEntityToken)this.EntityToken; IMediaFile mediaFile = (IMediaFile)token.Data; UploadedFile file = new UploadedFile(); workflow.Bindings.Add("UploadedFile", file); workflow.Bindings.Add("File", mediaFile); } private void uploadCodeActivity_ExecuteCode(object sender, EventArgs e) { UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken); FlowControllerServicesContainer flowControllerServicesContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); var managementConsoleMessageService = flowControllerServicesContainer.GetService<IManagementConsoleMessageService>(); UploadedFile uploadedFile = this.GetBinding<UploadedFile>("UploadedFile"); IMediaFile mediaFile = this.GetBinding<IMediaFile>("File"); if (uploadedFile.HasFile) { string mimeType = MimeTypeInfo.GetMimeType(uploadedFile); // Image cannot be replaced with a file of not image mime type string imageMimeTypePrefix = "image/"; if ((mediaFile.MimeType.StartsWith(imageMimeTypePrefix, StringComparison.OrdinalIgnoreCase) && !mimeType.StartsWith(imageMimeTypePrefix, StringComparison.OrdinalIgnoreCase))) { managementConsoleMessageService.CloseCurrentView(); string failure = StringResourceSystemFacade.GetString("Composite.Management", "UploadNewMediaFileWorkflow.UploadFailure"); string failureMessage = StringResourceSystemFacade.GetString("Composite.Management", "UploadNewMediaFileWorkflow.UploadFailureMessage"); managementConsoleMessageService.ShowMessage(DialogType.Message, failure, failureMessage); return; } using (System.IO.Stream readStream = uploadedFile.FileStream) { using (System.IO.Stream writeStream = mediaFile.GetNewWriteStream()) { readStream.CopyTo(writeStream); } } } DataFacade.Update(mediaFile); SetSaveStatus(true); SelectElement(mediaFile.GetDataEntityToken()); updateTreeRefresher.PostRefreshMesseges(mediaFile.GetDataEntityToken()); } private void HasUserUploaded(object sender, System.Workflow.Activities.ConditionalEventArgs e) { UploadedFile uploadedFile = this.GetBinding<UploadedFile>("UploadedFile"); e.Result = uploadedFile.HasFile; } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MediaFileProviderElementProvider/UploadNewMediaFileWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="UploadNewMediaFileWorkflow" Location="30; 30" Size="1251; 601" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="UploadNewMediaFileWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="UploadNewMediaFileWorkflow" EventHandlerName="eventDrivenActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="176" Y="71" /> <ns0:Point X="675" Y="71" /> <ns0:Point X="675" Y="233" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="showUploadStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initialState" SourceConnectionEdge="Right" TargetActivity="showUploadStateActivity" SourceActivity="initialState" EventHandlerName="stateInitializationActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="228" Y="142" /> <ns0:Point X="241" Y="142" /> <ns0:Point X="241" Y="272" /> <ns0:Point X="169" Y="272" /> <ns0:Point X="169" Y="284" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="showUploadStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="showUploadStateActivity" EventHandlerName="finishEventDrivenActivity"> <StateDesignerConnector.Segments> <ns0:Point X="248" Y="349" /> <ns0:Point X="269" Y="349" /> <ns0:Point X="269" Y="225" /> <ns0:Point X="675" Y="225" /> <ns0:Point X="675" Y="233" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="showUploadStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="showUploadStateActivity" SourceConnectionEdge="Right" TargetActivity="showUploadStateActivity" SourceActivity="showUploadStateActivity" EventHandlerName="finishEventDrivenActivity"> <StateDesignerConnector.Segments> <ns0:Point X="616" Y="169" /> <ns0:Point X="633" Y="169" /> <ns0:Point X="633" Y="96" /> <ns0:Point X="537" Y="96" /> <ns0:Point X="537" Y="104" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="showUploadStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="showUploadStateActivity" EventHandlerName="cancelEventDrivenActivity"> <StateDesignerConnector.Segments> <ns0:Point X="253" Y="373" /> <ns0:Point X="269" Y="373" /> <ns0:Point X="269" Y="225" /> <ns0:Point X="675" Y="225" /> <ns0:Point X="675" Y="233" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initialState" Location="57; 101" Size="175; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="stateInitializationActivity1" Location="65; 132"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="codeActivity2" Location="75; 194" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="75; 254" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="showUploadStateActivity" Location="81; 284" Size="176; 102" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="stateInitializationActivity2" Location="457; 135"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="wizzardFormActivity1" Location="467; 197" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="381; 483" Name="finishEventDrivenActivity" Location="465; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="590; 210" /> <IfElseDesigner Size="361; 342" Name="ifElseActivity1" Location="475; 270"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 242" Name="ifElseBranchActivity1" Location="494; 341"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="codeActivity1" Location="504; 403" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="504; 463" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="504; 523" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 242" Name="ifElseBranchActivity2" Location="667; 341"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="showConsoleMessageBoxActivity1" Location="677; 403" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="677; 463" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="cancelEventDrivenActivity" Location="457; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="467; 245" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="467; 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="595; 233" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity1" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/AddInlineFunctionWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Workflows.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider { partial class AddInlineFunctionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.wizardFormActivity1 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity_ValidateFunctionName = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_InitBindings = new System.Workflow.Activities.CodeActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "step1StateActivity"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalizeStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity6); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity4); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateFunctionName); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // wizardFormActivity1 // this.wizardFormActivity1.ContainerLabel = null; this.wizardFormActivity1.FormDefinitionFileName = "\\Administrative\\InlineFunctionAddFunctionStep1.xml"; this.wizardFormActivity1.Name = "wizardFormActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // ifElseActivity_ValidateFunctionName // this.ifElseActivity_ValidateFunctionName.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity_ValidateFunctionName.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity_ValidateFunctionName.Name = "ifElseActivity_ValidateFunctionName"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // initializeCodeActivity_InitBindings // this.initializeCodeActivity_InitBindings.Name = "initializeCodeActivity_InitBindings"; this.initializeCodeActivity_InitBindings.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_InitBindings_ExecuteCode); // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity5); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.wizardFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity3); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.ifElseActivity_ValidateFunctionName); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_InitBindings); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // AddInlineFunctionWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddInlineFunctionWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity6; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity_ValidateFunctionName; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity2; private StateInitializationActivity finalizeStateInitializationActivity; private StateInitializationActivity step1StateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private C1Console.Workflow.Activities.WizardFormActivity wizardFormActivity1; private CodeActivity initializeCodeActivity_InitBindings; private CodeActivity finalizeCodeActivity_Finalize; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/AddInlineFunctionWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Transactions; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.Core.ResourceSystem; using Composite.Data; using Composite.Data.Transactions; using Composite.Data.Types; using Composite.Functions.Inline; using Composite.Functions.ManagedParameters; using System.Workflow.Activities; using Composite.Functions; using Microsoft.Practices.EnterpriseLibrary.Validation; using Composite.Data.Validation; namespace Composite.Workflows.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider { public sealed partial class AddInlineFunctionWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddInlineFunctionWorkflow() { InitializeComponent(); } private void initializeCodeActivity_InitBindings_ExecuteCode(object sender, EventArgs e) { IInlineFunction function = DataFacade.BuildNew<IInlineFunction>(); function.Id = Guid.NewGuid(); function.Namespace = UserSettings.LastSpecifiedNamespace; this.Bindings.Add("NewFunction", function); Dictionary<string, string> templates = new Dictionary<string, string>(); templates.Add("clean", StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "InlineFunctionMethodTemplate.Clean")); templates.Add("parameter", StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "InlineFunctionMethodTemplate.WithParameters")); templates.Add("dataconnection", StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "InlineFunctionMethodTemplate.DataConnection")); this.Bindings.Add("TemplateOptions", templates); this.Bindings.Add("SelectedTemplate", "clean"); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { IInlineFunction function = this.GetBinding<IInlineFunction>("NewFunction"); function.UpdateCodePath(); string selectedTemplate = this.GetBinding<string>("SelectedTemplate"); string codeTemplate; switch (selectedTemplate) { case "clean": codeTemplate = _cleanTemplate; break; case "parameter": codeTemplate = _parameterTemplate; List<ManagedParameterDefinition> parameters = new List<ManagedParameterDefinition>(); ManagedParameterDefinition parameter1 = new ManagedParameterDefinition(); parameter1.Id = Guid.NewGuid(); parameter1.Name = "myIntValue"; parameter1.Label = "myIntValue"; parameter1.HelpText = "myIntValue"; parameter1.Position = 0; parameter1.Type = typeof(int); parameter1.TestValueFunctionMarkup = "<f:function xmlns:f=\"http://www.composite.net/ns/function/1.0\" name=\"Composite.Constant.Integer\"><f:param name=\"Constant\" value=\"0\" /></f:function>"; parameter1.WidgetFunctionMarkup = "<f:widgetfunction xmlns:f=\"http://www.composite.net/ns/function/1.0\" name=\"Composite.Widgets.Integer.TextBox\" label=\"myIntValue\" bindingsourcename=\"\"><f:helpdefinition xmlns:f=\"http://www.composite.net/ns/function/1.0\" helptext=\"myIntValue\" /></f:widgetfunction>"; parameters.Add(parameter1); ManagedParameterDefinition parameter2 = new ManagedParameterDefinition(); parameter2.Id = Guid.NewGuid(); parameter2.Name = "myStringValue"; parameter2.Label = "myStringValue"; parameter2.HelpText = "myStringValue"; parameter2.Position = 1; parameter2.Type = typeof(string); parameter2.TestValueFunctionMarkup = "<f:function xmlns:f=\"http://www.composite.net/ns/function/1.0\" name=\"Composite.Constant.String\"><f:param name=\"Constant\" value=\"Hello world!\" /></f:function>"; parameter2.WidgetFunctionMarkup = "<f:widgetfunction xmlns:f=\"http://www.composite.net/ns/function/1.0\" name=\"Composite.Widgets.String.TextBox\" label=\"myStringValue\" bindingsourcename=\"\"><f:helpdefinition xmlns:f=\"http://www.composite.net/ns/function/1.0\" helptext=\"myStringValue\" /></f:widgetfunction>"; parameters.Add(parameter2); ManagedParameterManager.Save(function.Id, parameters); break; case "dataconnection": codeTemplate = _dataConnectionTemplate; break; default: throw new NotImplementedException(); } string code = string.Format(codeTemplate, function.Namespace, InlineFunctionHelper.MethodClassContainerName, function.Name); code = code.Replace('', '\t'); using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { foreach (string assemblyPath in InlineFunctionHelper.DefaultAssemblies) { IInlineFunctionAssemblyReference reference = DataFacade.BuildNew<IInlineFunctionAssemblyReference>(); reference.Id = Guid.NewGuid(); reference.Function = function.Id; reference.Name = System.IO.Path.GetFileName(assemblyPath); reference.Location = InlineFunctionHelper.GetAssemblyLocation(assemblyPath); DataFacade.AddNew(reference); } function.SetFunctionCode(code); function = DataFacade.AddNew(function); UserSettings.LastSpecifiedNamespace = function.Namespace; transactionScope.Complete(); } this.CloseCurrentView(); this.CreateAddNewTreeRefresher(this.EntityToken).PostRefreshMesseges(function.GetDataEntityToken()); this.ExecuteWorklow(function.GetDataEntityToken(), WorkflowFacade.GetWorkflowType("Composite.Workflows.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider.EditInlineFunctionWorkflow")); } private void ValidateFunctionName(object sender, ConditionalEventArgs e) { IInlineFunction function = this.GetBinding<IInlineFunction>("NewFunction"); bool exists = FunctionFacade.FunctionExists(function.Namespace, function.Name); if (exists) { string errorMessage = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "AddFunction.NameAlreadyUsed"); errorMessage = string.Format(errorMessage, FunctionFacade.GetFunctionCompositionName(function.Namespace, function.Name)); ShowFieldMessage("NewFunction.Name", errorMessage); e.Result = false; return; } ValidationResults validationResults = ValidationFacade.Validate<IInlineFunction>(function); if (!validationResults.IsValid) { foreach (ValidationResult result in validationResults) { this.ShowFieldMessage(string.Format("{0}.{1}", "NewFunction", result.Key), result.Message); } e.Result = false; return; } e.Result = true; } private static string _cleanTemplate = @"using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.Data; using Composite.Data.Types; namespace {0} {{ public static class {1} {{ public static bool {2}() {{ return true; }} }} }} "; private static string _parameterTemplate = @"using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.Data; using Composite.Data.Types; namespace {0} {{ public static class {1} {{ public static bool {2}(int myIntValue, string myStringValue) {{ return true; }} }} }} "; private static string _dataConnectionTemplate = @"using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Composite.Data; using Composite.Data.Types; namespace {0} {{ public static class {1} {{ public static XElement {2}() {{ using (DataConnection connection = new DataConnection()) {{ XElement element = new XElement(""Pages""); foreach (IPage page in connection.Get<IPage>()) {{ element.Add( new XElement(""Page"", new XAttribute(""title"", page.Title)) ); }} return element; }} }} }} }} "; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/AddInlineFunctionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1151; 965" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="AddInlineFunctionWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="63; 105" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 182" Location="71; 136"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_InitBindings" Size="130; 41" Location="81; 198" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="81; 258" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="809; 776" Name="finalStateActivity" /> <StateDesigner Size="211; 118" AutoSizeMargin="16; 24" AutoSize="False" Location="273; 303" Name="step1StateActivity"> <StateDesigner.Designers> <EventDrivenDesigner Name="step1EventDrivenActivity_Finish" Size="381; 363" Location="415; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="540; 210" /> <IfElseDesigner Name="ifElseActivity_ValidateFunctionName" Size="361; 222" Location="425; 270"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 122" Location="444; 341"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="454; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 122" Location="617; 341"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="627; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Cancel" Size="150; 182" Location="407; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="417; 245" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="417; 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateInitializationDesigner Name="step1StateInitializationActivity" Size="150; 122" Location="407; 135"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizardFormActivity1" Size="130; 41" Location="417; 197" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" Location="548; 547" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 182" Location="556; 578"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity_Finalize" Size="130; 41" Location="566; 640" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="566; 700" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="AddInlineFunctionWorkflow" TargetConnectionIndex="0" SourceStateName="AddInlineFunctionWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="889" Y="71" /> <ns0:Point X="889" Y="776" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="269" Y="146" /> <ns0:Point X="378" Y="146" /> <ns0:Point X="378" Y="303" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity4" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="476" Y="368" /> <ns0:Point X="650" Y="368" /> <ns0:Point X="650" Y="547" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity3" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="480" Y="392" /> <ns0:Point X="889" Y="392" /> <ns0:Point X="889" Y="776" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity5" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="749" Y="588" /> <ns0:Point X="889" Y="588" /> <ns0:Point X="889" Y="776" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/AddNewMethodBasedFunctionWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider { partial class AddNewMethodBasedFunctionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity12 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity4 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizzardFormActivity2 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity11 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.step2CodeActivity = new System.Workflow.Activities.CodeActivity(); this.nextHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.wizzardFormActivity3 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity2 = new System.Workflow.Activities.IfElseActivity(); this.nextHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.checkMethodNameStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step3EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step3EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step3StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step2EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step2EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step2StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.checkMethodNameStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.step3StateActivity = new System.Workflow.Activities.StateActivity(); this.step2StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "step3StateActivity"; // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "finalizeStateActivity"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "step1StateActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step2StateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity5); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity9); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsValidMethodName); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity7); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.setStateActivity2); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckType); this.ifElseBranchActivity3.Condition = codecondition2; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // setStateActivity12 // this.setStateActivity12.Name = "setStateActivity12"; this.setStateActivity12.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity4 // this.cancelHandleExternalEventActivity4.EventName = "Cancel"; this.cancelHandleExternalEventActivity4.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity4.Name = "cancelHandleExternalEventActivity4"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "checkMethodNameStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // wizzardFormActivity2 // this.wizzardFormActivity2.ContainerLabel = "Add new"; this.wizzardFormActivity2.FormDefinitionFileName = "\\Administrative\\AddNewMethodBasedFunctionStep3.xml"; this.wizzardFormActivity2.Name = "wizzardFormActivity2"; // // setStateActivity11 // this.setStateActivity11.Name = "setStateActivity11"; this.setStateActivity11.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "step3StateActivity"; // // step2CodeActivity // this.step2CodeActivity.Name = "step2CodeActivity"; this.step2CodeActivity.ExecuteCode += new System.EventHandler(this.step2CodeActivity_ExecuteCode); // // nextHandleExternalEventActivity2 // this.nextHandleExternalEventActivity2.EventName = "Next"; this.nextHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity2.Name = "nextHandleExternalEventActivity2"; // // wizzardFormActivity3 // this.wizzardFormActivity3.ContainerLabel = "Add new"; this.wizzardFormActivity3.FormDefinitionFileName = "\\Administrative\\AddNewMethodBasedFunctionStep2.xml"; this.wizzardFormActivity3.Name = "wizzardFormActivity3"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ExecuteCode); // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // ifElseActivity2 // this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity4); this.ifElseActivity2.Name = "ifElseActivity2"; // // nextHandleExternalEventActivity1 // this.nextHandleExternalEventActivity1.EventName = "Next"; this.nextHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity1.Name = "nextHandleExternalEventActivity1"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = "Add new"; this.wizzardFormActivity1.FormDefinitionFileName = "\\Administrative\\AddNewMethodBasedFunctionStep1.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "step1StateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // checkMethodNameStateInitializationActivity // this.checkMethodNameStateInitializationActivity.Activities.Add(this.ifElseActivity1); this.checkMethodNameStateInitializationActivity.Name = "checkMethodNameStateInitializationActivity"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // step3EventDrivenActivity_Cancel // this.step3EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity4); this.step3EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity12); this.step3EventDrivenActivity_Cancel.Name = "step3EventDrivenActivity_Cancel"; // // step3EventDrivenActivity_Finish // this.step3EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step3EventDrivenActivity_Finish.Activities.Add(this.setStateActivity4); this.step3EventDrivenActivity_Finish.Name = "step3EventDrivenActivity_Finish"; // // step3StateInitializationActivity // this.step3StateInitializationActivity.Activities.Add(this.wizzardFormActivity2); this.step3StateInitializationActivity.Name = "step3StateInitializationActivity"; // // step2EventDrivenActivity_Cancel // this.step2EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.step2EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity11); this.step2EventDrivenActivity_Cancel.Name = "step2EventDrivenActivity_Cancel"; // // step2EventDrivenActivity_Next // this.step2EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity2); this.step2EventDrivenActivity_Next.Activities.Add(this.step2CodeActivity); this.step2EventDrivenActivity_Next.Activities.Add(this.setStateActivity10); this.step2EventDrivenActivity_Next.Name = "step2EventDrivenActivity_Next"; // // step2StateInitializationActivity // this.step2StateInitializationActivity.Activities.Add(this.wizzardFormActivity3); this.step2StateInitializationActivity.Name = "step2StateInitializationActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity3); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity8); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Next // this.step1EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity1); this.step1EventDrivenActivity_Next.Activities.Add(this.ifElseActivity2); this.step1EventDrivenActivity_Next.Name = "step1EventDrivenActivity_Next"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.wizzardFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initalizeStateInitializationActivity // this.initalizeStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initalizeStateInitializationActivity.Activities.Add(this.setStateActivity1); this.initalizeStateInitializationActivity.Name = "initalizeStateInitializationActivity"; // // checkMethodNameStateActivity // this.checkMethodNameStateActivity.Activities.Add(this.checkMethodNameStateInitializationActivity); this.checkMethodNameStateActivity.Name = "checkMethodNameStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity6); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // step3StateActivity // this.step3StateActivity.Activities.Add(this.step3StateInitializationActivity); this.step3StateActivity.Activities.Add(this.step3EventDrivenActivity_Finish); this.step3StateActivity.Activities.Add(this.step3EventDrivenActivity_Cancel); this.step3StateActivity.Name = "step3StateActivity"; // // step2StateActivity // this.step2StateActivity.Activities.Add(this.step2StateInitializationActivity); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Next); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Cancel); this.step2StateActivity.Name = "step2StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Next); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initalizeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // AddNewMethodBasedFunctionWorkflow // this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step2StateActivity); this.Activities.Add(this.step3StateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.checkMethodNameStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddNewMethodBasedFunctionWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private C1Console.Workflow.Activities.WizardFormActivity wizzardFormActivity1; private SetStateActivity setStateActivity1; private StateInitializationActivity finalizeStateInitializationActivity; private StateInitializationActivity step1StateInitializationActivity; private StateInitializationActivity initalizeStateInitializationActivity; private StateActivity finalStateActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private CodeActivity initializeCodeActivity; private CodeActivity finalizeCodeActivity; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity1; private StateInitializationActivity step2StateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Next; private StateActivity step2StateActivity; private C1Console.Workflow.Activities.WizardFormActivity wizzardFormActivity2; private C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity2; private C1Console.Workflow.Activities.WizardFormActivity wizzardFormActivity3; private EventDrivenActivity step3EventDrivenActivity_Finish; private StateInitializationActivity step3StateInitializationActivity; private EventDrivenActivity step2EventDrivenActivity_Next; private StateActivity step3StateActivity; private SetStateActivity setStateActivity7; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElseActivity2; private CodeActivity step2CodeActivity; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private SetStateActivity setStateActivity6; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private StateInitializationActivity checkMethodNameStateInitializationActivity; private StateActivity checkMethodNameStateActivity; private SetStateActivity setStateActivity9; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity10; private EventDrivenActivity step3EventDrivenActivity_Cancel; private EventDrivenActivity step2EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Cancel; private SetStateActivity setStateActivity12; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity4; private SetStateActivity setStateActivity11; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private SetStateActivity setStateActivity8; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private StateActivity initializeStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/AddNewMethodBasedFunctionWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Workflow.Activities; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Forms.Flows; using Composite.C1Console.Workflow; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; using Composite.Core.Types; using Composite.Data; using Composite.Data.Types; using Composite.Functions; using Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider; namespace Composite.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewMethodBasedFunctionWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddNewMethodBasedFunctionWorkflow() { InitializeComponent(); } private static string _lastAddedType; private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { IMethodBasedFunctionInfo function = DataFacade.BuildNew<IMethodBasedFunctionInfo>(); BaseFunctionFolderElementEntityToken token = (BaseFunctionFolderElementEntityToken)this.EntityToken; string namespaceName = ""; int index = token.Id.IndexOf('.'); if (index > 0) { namespaceName = token.Id.Substring(index + 1); } function.Namespace = namespaceName; if (_lastAddedType != null) { function.Type = _lastAddedType; } this.Bindings.Add("UserMethodName", ""); this.Bindings.Add("NewMethodBasedFunction", function); } private void CheckType(object sender, ConditionalEventArgs e) { IMethodBasedFunctionInfo function = this.GetBinding<IMethodBasedFunctionInfo>("NewMethodBasedFunction"); Type type = TypeManager.TryGetType(function.Type); if (type == null) { string errorMessage = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "AddFunction.CouldNotFindType"); ShowFieldMessage("NewMethodBasedFunction.Type", errorMessage); e.Result = false; return; } List<string> methodNames = (from methodInfo in type.GetMethods(BindingFlags.Static | BindingFlags.Public) select methodInfo.Name).ToList(); if (methodNames.Count == 0) { string errorMessage = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "AddFunction.TypeHasNoValidMethod"); ShowFieldMessage("NewMethodBasedFunction.Type", errorMessage); e.Result = false; return; } int destinctCount = methodNames.Distinct().Count(); if (destinctCount != methodNames.Count) { string errorMessage = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "AddFunction.TypeMustNotHaveOverloads"); ShowFieldMessage("NewMethodBasedFunction.Type", errorMessage); e.Result = false; return; } this.UpdateBinding("MethodNames", methodNames); this.UpdateBinding("SelectedMethodName", ""); _lastAddedType = type.FullName; e.Result = true; } private void step2CodeActivity_ExecuteCode(object sender, EventArgs e) { IMethodBasedFunctionInfo function = this.GetBinding<IMethodBasedFunctionInfo>("NewMethodBasedFunction"); Type type = TypeManager.TryGetType(function.Type); string methodName = this.GetBinding<string>("SelectedMethodName"); function.MethodName = methodName; function.UserMethodName = methodName; function.Namespace = type.Namespace + "." + type.Name; } private void IsValidMethodName(object sender, ConditionalEventArgs e) { IMethodBasedFunctionInfo function = this.GetBinding<IMethodBasedFunctionInfo>("NewMethodBasedFunction"); FlowControllerServicesContainer container = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); var flowRenderingService = container.GetService<IFormFlowRenderingService>(); if (function.UserMethodName == String.Empty) { string errorMessage = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "AddFunction.MethodNameIsEmpty"); ShowFieldMessage("NewMethodBasedFunction", errorMessage); e.Result = false; return; } if (!function.Namespace.IsCorrectNamespace('.')) { string errorMessage = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "AddFunction.InvalidNamespace"); ShowFieldMessage("NewMethodBasedFunction", errorMessage); e.Result = false; return; } bool exists = FunctionFacade.FunctionExists(function.Namespace, function.UserMethodName); if (exists) { string errorMessage = StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "AddFunction.NameAlreadyUsed"); errorMessage = string.Format(errorMessage, StringExtensionMethods.CreateNamespace(function.Namespace, function.UserMethodName)); ShowFieldMessage("NewMethodBasedFunction.UserMethodName", errorMessage); e.Result = false; return; } e.Result = true; } private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken); IMethodBasedFunctionInfo methodBasedFunctionInfo = this.GetBinding<IMethodBasedFunctionInfo>("NewMethodBasedFunction"); methodBasedFunctionInfo.Id = Guid.NewGuid(); methodBasedFunctionInfo = DataFacade.AddNew<IMethodBasedFunctionInfo>(methodBasedFunctionInfo); addNewTreeRefresher.PostRefreshMesseges(methodBasedFunctionInfo.GetDataEntityToken()); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/AddNewMethodBasedFunctionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1151; 965" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="AddNewMethodBasedFunctionWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="208; 80" AutoSizeMargin="16; 24" Location="156; 107" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initalizeStateInitializationActivity" Size="150; 182" Location="164; 138"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity" Size="130; 41" Location="174; 200" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="174; 260" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="211; 102" AutoSizeMargin="16; 24" Location="166; 244" Name="step1StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1StateInitializationActivity" Size="150; 122" Location="174; 275"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizzardFormActivity1" Size="130; 41" Location="184; 337" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Next" Size="381; 363" Location="174; 299"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="nextHandleExternalEventActivity1" Size="130; 41" Location="299; 361" /> <IfElseDesigner Name="ifElseActivity2" Size="361; 222" Location="184; 421"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity3" Size="150; 122" Location="203; 492"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="213; 554" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity4" Size="150; 122" Location="376; 492"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity7" Size="130; 41" Location="386; 554" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Cancel" Size="150; 182" Location="174; 323"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="184; 385" /> <SetStateDesigner Name="setStateActivity8" Size="130; 41" Location="184; 445" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="649; 764" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 242" Location="657; 795"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity" Size="130; 41" Location="667; 857" /> <ActivityDesigner Name="closeCurrentViewActivity1" Size="130; 41" Location="667; 917" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="667; 977" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="953; 852" Name="finalStateActivity" /> <StateDesigner Size="211; 126" AutoSizeMargin="16; 24" Location="466; 232" Name="step2StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step2StateInitializationActivity" Size="150; 122" Location="474; 263"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizzardFormActivity3" Size="130; 41" Location="484; 325" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step2EventDrivenActivity_Next" Size="150; 254" Location="474; 287"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="nextHandleExternalEventActivity2" Size="130; 41" Location="484; 349" /> <CodeDesigner Name="step2CodeActivity" Size="130; 41" Location="484; 409" /> <SetStateDesigner Name="setStateActivity10" Size="130; 53" Location="484; 469" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step2EventDrivenActivity_Cancel" Size="150; 194" Location="474; 311"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity3" Size="130; 41" Location="484; 373" /> <SetStateDesigner Name="setStateActivity11" Size="130; 53" Location="484; 433" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="211; 102" AutoSizeMargin="16; 24" Location="749; 241" Name="step3StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step3StateInitializationActivity" Size="150; 122" Location="757; 272"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizzardFormActivity2" Size="130; 41" Location="767; 334" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step3EventDrivenActivity_Finish" Size="150; 182" Location="757; 296"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="767; 358" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="767; 418" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step3EventDrivenActivity_Cancel" Size="150; 194" Location="757; 320"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity4" Size="130; 41" Location="767; 382" /> <SetStateDesigner Name="setStateActivity12" Size="130; 53" Location="767; 442" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="265; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="59; 591" Name="checkMethodNameStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="checkMethodNameStateInitializationActivity" Size="381; 303" Location="415; 148"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="ifElseActivity1" Size="361; 222" Location="425; 210"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 122" Location="444; 281"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity9" Size="130; 41" Location="454; 343" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 122" Location="617; 281"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="627; 343" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity6" SourceActivity="AddNewMethodBasedFunctionWorkflow" TargetConnectionIndex="0" SourceStateName="AddNewMethodBasedFunctionWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1033" Y="71" /> <ns0:Point X="1033" Y="852" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity1" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="360" Y="148" /> <ns0:Point X="375" Y="148" /> <ns0:Point X="375" Y="232" /> <ns0:Point X="271" Y="232" /> <ns0:Point X="271" Y="244" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step2StateActivity" SetStateName="setStateActivity2" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="step2StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="363" Y="309" /> <ns0:Point X="389" Y="309" /> <ns0:Point X="389" Y="224" /> <ns0:Point X="571" Y="224" /> <ns0:Point X="571" Y="232" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity7" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="363" Y="309" /> <ns0:Point X="383" Y="309" /> <ns0:Point X="383" Y="236" /> <ns0:Point X="271" Y="236" /> <ns0:Point X="271" Y="244" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity8" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="373" Y="333" /> <ns0:Point X="389" Y="333" /> <ns0:Point X="389" Y="752" /> <ns0:Point X="1033" Y="752" /> <ns0:Point X="1033" Y="852" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity3" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="850" Y="805" /> <ns0:Point X="1033" Y="805" /> <ns0:Point X="1033" Y="852" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step3StateActivity" SetStateName="setStateActivity10" SourceActivity="step2StateActivity" TargetConnectionIndex="0" SourceStateName="step2StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step2EventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="step3StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="663" Y="297" /> <ns0:Point X="689" Y="297" /> <ns0:Point X="689" Y="233" /> <ns0:Point X="854" Y="233" /> <ns0:Point X="854" Y="241" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity11" SourceActivity="step2StateActivity" TargetConnectionIndex="0" SourceStateName="step2StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step2EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="673" Y="321" /> <ns0:Point X="689" Y="321" /> <ns0:Point X="689" Y="752" /> <ns0:Point X="1033" Y="752" /> <ns0:Point X="1033" Y="852" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="checkMethodNameStateActivity" SetStateName="setStateActivity4" SourceActivity="step3StateActivity" TargetConnectionIndex="0" SourceStateName="step3StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step3EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="checkMethodNameStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="952" Y="306" /> <ns0:Point X="967" Y="306" /> <ns0:Point X="967" Y="579" /> <ns0:Point X="191" Y="579" /> <ns0:Point X="191" Y="591" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity12" SourceActivity="step3StateActivity" TargetConnectionIndex="0" SourceStateName="step3StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step3EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="956" Y="330" /> <ns0:Point X="1033" Y="330" /> <ns0:Point X="1033" Y="852" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity9" SourceActivity="checkMethodNameStateActivity" TargetConnectionIndex="0" SourceStateName="checkMethodNameStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="checkMethodNameStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="320" Y="632" /> <ns0:Point X="751" Y="632" /> <ns0:Point X="751" Y="764" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step3StateActivity" SetStateName="setStateActivity5" SourceActivity="checkMethodNameStateActivity" TargetConnectionIndex="0" SourceStateName="checkMethodNameStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="checkMethodNameStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step3StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="320" Y="632" /> <ns0:Point X="966" Y="632" /> <ns0:Point X="966" Y="233" /> <ns0:Point X="854" Y="233" /> <ns0:Point X="854" Y="241" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/DeleteInlineFunctionWorkflow.cs ================================================ using System; using System.Transactions; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Core.ResourceSystem; using Composite.Data; using Composite.Data.Transactions; using Composite.Data.Types; using Composite.Functions.Inline; namespace Composite.Workflows.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider { public sealed partial class DeleteInlineFunctionWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeleteInlineFunctionWorkflow() { InitializeComponent(); } private void finalizeCodeActivity_DeleteFunction_ExecuteCode(object sender, EventArgs e) { IInlineFunction function = GetDataItemFromEntityToken<IInlineFunction>(); if (DataFacade.WillDeleteSucceed(function)) { DeleteTreeRefresher treeRefresher = this.CreateDeleteTreeRefresher(this.EntityToken); using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { DataFacade.Delete<IInlineFunctionAssemblyReference>(f => f.Function == function.Id); DataFacade.Delete<IParameter>(f => f.OwnerId == function.Id); function.DeleteFunctionCode(); DataFacade.Delete(function); transactionScope.Complete(); } treeRefresher.PostRefreshMesseges(); } else { this.ShowMessage( DialogType.Error, StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "CascadeDeleteErrorTitle"), StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "CascadeDeleteErrorMessage") ); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/DeleteInlineFunctionWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Workflows.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider { partial class DeleteInlineFunctionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_DeleteFunction = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.confirmEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.confirmEventDrivenActivity_Ok = new System.Workflow.Activities.EventDrivenActivity(); this.confirmStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.confirmStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_DeleteFunction // this.finalizeCodeActivity_DeleteFunction.Name = "finalizeCodeActivity_DeleteFunction"; this.finalizeCodeActivity_DeleteFunction.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_DeleteFunction_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "\\Administrative\\InlineFunctionDeleteFunction.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "confirmStateActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_DeleteFunction); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity5); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // confirmEventDrivenActivity_Cancel // this.confirmEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.confirmEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity2); this.confirmEventDrivenActivity_Cancel.Name = "confirmEventDrivenActivity_Cancel"; // // confirmEventDrivenActivity_Ok // this.confirmEventDrivenActivity_Ok.Activities.Add(this.finishHandleExternalEventActivity1); this.confirmEventDrivenActivity_Ok.Activities.Add(this.setStateActivity6); this.confirmEventDrivenActivity_Ok.Name = "confirmEventDrivenActivity_Ok"; // // confirmStateInitializationActivity // this.confirmStateInitializationActivity.Activities.Add(this.confirmDialogFormActivity1); this.confirmStateInitializationActivity.Name = "confirmStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // confirmStateActivity // this.confirmStateActivity.Activities.Add(this.confirmStateInitializationActivity); this.confirmStateActivity.Activities.Add(this.confirmEventDrivenActivity_Ok); this.confirmStateActivity.Activities.Add(this.confirmEventDrivenActivity_Cancel); this.confirmStateActivity.Name = "confirmStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // DeleteInlineFunctionWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.confirmStateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "DeleteInlineFunctionWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity5; private CodeActivity finalizeCodeActivity_DeleteFunction; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity6; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private SetStateActivity setStateActivity4; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity confirmEventDrivenActivity_Cancel; private EventDrivenActivity confirmEventDrivenActivity_Ok; private StateInitializationActivity confirmStateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity confirmStateActivity; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/DeleteInlineFunctionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1146; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="DeleteInlineFunctionWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 122" Location="98; 169"> <StateInitializationDesigner.Designers> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="108; 231" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="221; 102" AutoSizeMargin="16; 24" Location="303; 359" Name="confirmStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="confirmStateInitializationActivity" Size="150; 122" Location="311; 390"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="confirmDialogFormActivity1" Size="130; 41" Location="321; 452" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="confirmEventDrivenActivity_Ok" Size="150; 182" Location="311; 414"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="321; 476" /> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="321; 536" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="confirmEventDrivenActivity_Cancel" Size="150; 182" Location="311; 438"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="321; 500" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="321; 560" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="632; 530" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 182" Location="515; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity_DeleteFunction" Size="130; 41" Location="525; 210" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="525; 270" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="DeleteInlineFunctionWorkflow" TargetConnectionIndex="0" SourceStateName="DeleteInlineFunctionWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity2" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="confirmEventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="520" Y="448" /> <ns0:Point X="1058" Y="448" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="confirmStateActivity" SetStateName="setStateActivity4" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="confirmStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="413" Y="179" /> <ns0:Point X="413" Y="359" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity5" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="833" Y="571" /> <ns0:Point X="1058" Y="571" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity6" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="confirmEventDrivenActivity_Ok" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="501" Y="424" /> <ns0:Point X="734" Y="424" /> <ns0:Point X="734" Y="530" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/DeleteMethodBasedFunctionWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider { partial class DeleteMethodBasedFunctionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.deleteStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.deleteStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "/Administrative/MethodBasedFunctionProviderElementProviderDeleteStep1.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "step1StateActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity5); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity1); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity3); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.confirmDialogFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // deleteStateInitializationActivity // this.deleteStateInitializationActivity.Activities.Add(this.setStateActivity4); this.deleteStateInitializationActivity.Name = "deleteStateInitializationActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity2); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // deleteStateActivity // this.deleteStateActivity.Activities.Add(this.deleteStateInitializationActivity); this.deleteStateActivity.Name = "deleteStateActivity"; // // DeleteMethodBasedFunctionWorkflow // this.Activities.Add(this.deleteStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "deleteStateActivity"; this.Name = "DeleteMethodBasedFunctionWorkflow"; this.CanModifyActivities = false; } #endregion private StateInitializationActivity deleteStateInitializationActivity; private StateActivity finalStateActivity; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private CodeActivity finalizeCodeActivity; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateInitializationActivity step1StateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity1; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity5; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private StateActivity deleteStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/DeleteMethodBasedFunctionWorkflow.cs ================================================ using System; using System.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.Types; using Composite.Core.ResourceSystem; using Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider; using Composite.C1Console.Workflow; using Composite.Plugins.Elements.ElementProviders.Common; namespace Composite.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteMethodBasedFunctionWorkflow : BaseFunctionWorkflow { public DeleteMethodBasedFunctionWorkflow() { InitializeComponent(); } private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { DataEntityToken token = (DataEntityToken)this.EntityToken; IMethodBasedFunctionInfo methodBasedFunctionInfo = (IMethodBasedFunctionInfo)token.Data; if (DataFacade.WillDeleteSucceed(methodBasedFunctionInfo)) { DeleteTreeRefresher treeRefresher = this.CreateDeleteTreeRefresher(this.EntityToken); DataFacade.Delete(token.Data); int count = (from info in DataFacade.GetData<IMethodBasedFunctionInfo>() where info.Namespace == methodBasedFunctionInfo.Namespace select info).Count(); if (count == 0) { RefreshFunctionTree(); } else { treeRefresher.PostRefreshMesseges(); } } else { this.ShowMessage( DialogType.Error, StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "CascadeDeleteErrorTitle"), StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", "CascadeDeleteErrorMessage") ); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/DeleteMethodBasedFunctionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1120; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="DeleteMethodBasedFunctionWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="201; 80" AutoSizeMargin="16; 24" Location="63; 105" Name="deleteStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="deleteStateInitializationActivity" Size="150; 122" Location="71; 136"> <StateInitializationDesigner.Designers> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="81; 198" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="797; 591" Name="finalStateActivity" /> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="211; 102" AutoSizeMargin="16; 24" AutoSize="False" Location="212; 278" Name="step1StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1StateInitializationActivity" Size="150; 122" Location="515; 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="confirmDialogFormActivity1" Size="130; 41" Location="525; 210" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Finish" Size="150; 182" Location="507; 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="517; 221" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="517; 281" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Cancel" Size="150; 182" Location="507; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="517; 245" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="517; 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="453; 456" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 242" Location="461; 487"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity" Size="130; 41" Location="471; 549" /> <ActivityDesigner Name="closeCurrentViewActivity1" Size="130; 41" Location="471; 609" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="471; 669" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity2" SourceActivity="DeleteMethodBasedFunctionWorkflow" TargetConnectionIndex="0" SourceStateName="DeleteMethodBasedFunctionWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="877" Y="71" /> <ns0:Point X="877" Y="591" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity4" SourceActivity="deleteStateActivity" TargetConnectionIndex="0" SourceStateName="deleteStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="deleteStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="260" Y="146" /> <ns0:Point X="317" Y="146" /> <ns0:Point X="317" Y="278" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity3" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="415" Y="343" /> <ns0:Point X="555" Y="343" /> <ns0:Point X="555" Y="456" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="419" Y="367" /> <ns0:Point X="877" Y="367" /> <ns0:Point X="877" Y="591" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity5" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="654" Y="497" /> <ns0:Point X="877" Y="497" /> <ns0:Point X="877" Y="591" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/EditInlineFunctionWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Transactions; using System.Web; using System.Web.UI; using System.Workflow.Runtime; using System.Xml.Linq; using System.Xml.Serialization; using Composite.C1Console.Actions; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.C1Console.Workflow.Foundation; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.ResourceSystem; using Composite.Core.Types; using Composite.Core.WebClient.FlowMediators.FormFlowRendering; using Composite.Core.WebClient.FunctionCallEditor; using Composite.Core.WebClient.Renderings.Page; using Composite.Core.WebClient.State; using Composite.Data; using Composite.Data.Transactions; using Composite.Data.Types; using Composite.Functions; using Composite.Functions.Inline; using Composite.Functions.ManagedParameters; using Composite.Core.Serialization; namespace Composite.Workflows.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider { [EntityTokenLock] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditInlineFunctionWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditInlineFunctionWorkflow() { InitializeComponent(); } private void initializeCodeActivity_InitBindings_ExecuteCode(object sender, EventArgs e) { IInlineFunction functionInfo = this.GetDataItemFromEntityToken<IInlineFunction>(); this.Bindings.Add("Function", functionInfo); this.Bindings.Add("PageId", PageManager.GetChildrenIDs(Guid.Empty).FirstOrDefault()); if (UserSettings.ActiveLocaleCultureInfo != null) { List<KeyValuePair<string, string>> activeCulturesDictionary = UserSettings.ActiveLocaleCultureInfos.Select(f => new KeyValuePair<string, string>(f.Name, DataLocalizationFacade.GetCultureTitle(f))).ToList(); this.Bindings.Add("ActiveCultureName", UserSettings.ActiveLocaleCultureInfo.Name); this.Bindings.Add("ActiveCulturesList", activeCulturesDictionary); } this.Bindings.Add("PageDataScopeName", DataScopeIdentifier.AdministratedName); this.Bindings.Add("PageDataScopeList", new Dictionary<string, string> { { DataScopeIdentifier.AdministratedName, GetText("EditInlineFunctionWorkflow.AdminitrativeScope.Label") }, { DataScopeIdentifier.PublicName, GetText("EditInlineFunctionWorkflow.PublicScope.Label") } }); this.Bindings.Add("FunctionCode", functionInfo.GetFunctionCode()); List<KeyValuePair> assemblies = new List<KeyValuePair>(); foreach (string assembly in InlineFunctionHelper.GetReferencableAssemblies()) { assemblies.Add(new KeyValuePair(assembly.ToLowerInvariant(), System.IO.Path.GetFileName(assembly))); } assemblies.Sort(delegate(KeyValuePair kvp1, KeyValuePair kvp2) { return kvp1.Value.CompareTo(kvp2.Value); }); this.Bindings.Add("Assemblies", assemblies); List<string> selectedAssemblies = DataFacade.GetData<IInlineFunctionAssemblyReference>(). Where(f => f.Function == functionInfo.Id). OrderBy(f => f.Name). Evaluate(). Select(f => InlineFunctionHelper.GetAssemblyFullPath(f.Name, f.Location).ToLowerInvariant()). ToList(); this.Bindings.Add("SelectedAssemblies", selectedAssemblies); List<ManagedParameterDefinition> parameters = ManagedParameterManager.Load(functionInfo.Id).ToList(); ; this.Bindings.Add("Parameters", parameters); IEnumerable<Type> popularWidgetTypes = FunctionFacade.WidgetFunctionSupportedTypes.Where(f => f.GetGenericArguments().Any(g => DataFacade.GetAllInterfaces(UserType.Developer).Any(h => h.IsAssignableFrom(g)))); List<Type> parameterTypeOptions = FunctionFacade.FunctionSupportedTypes.Union(popularWidgetTypes).Union(FunctionFacade.WidgetFunctionSupportedTypes).ToList(); this.Bindings.Add("ParameterTypeOptions", parameterTypeOptions); Guid stateId = Guid.NewGuid(); ParameterEditorState parameterEditorState = new ParameterEditorState { WorkflowId = WorkflowInstanceId }; SessionStateManager.DefaultProvider.AddState<IParameterEditorState>(stateId, parameterEditorState, DateTime.Now.AddDays(7.0)); this.Bindings.Add("SessionStateProvider", SessionStateManager.DefaultProviderName); this.Bindings.Add("SessionStateId", stateId); } private void saveCodeActivity_Save_ExecuteCode(object sender, EventArgs e) { IInlineFunction function = this.GetBinding<IInlineFunction>("Function"); string code = this.GetBinding<string>("FunctionCode"); List<string> selectedAssemblies = this.GetBinding<List<string>>("SelectedAssemblies"); using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { IEnumerable<IInlineFunctionAssemblyReference> assemblyReferences = DataFacade.GetData<IInlineFunctionAssemblyReference>(f => f.Function == function.Id).Evaluate(); foreach (string selectedAssembly in selectedAssemblies) { string name = System.IO.Path.GetFileName(selectedAssembly).ToLowerInvariant(); string location = InlineFunctionHelper.GetAssemblyLocation(selectedAssembly).ToLowerInvariant(); if (assemblyReferences .Any(f => (string.Compare(f.Name, name, StringComparison.InvariantCultureIgnoreCase) == 0) && (string.Compare(f.Location, location, StringComparison.InvariantCultureIgnoreCase) == 0)) == false) { IInlineFunctionAssemblyReference assemblyReference = DataFacade.BuildNew<IInlineFunctionAssemblyReference>(); assemblyReference.Id = Guid.NewGuid(); assemblyReference.Function = function.Id; assemblyReference.Name = name; assemblyReference.Location = location; DataFacade.AddNew(assemblyReference); } } foreach (IInlineFunctionAssemblyReference assemblyReference in assemblyReferences) { string fullPath = InlineFunctionHelper.GetAssemblyFullPath(assemblyReference.Name, assemblyReference.Location); if (selectedAssemblies.Any(f => string.Compare(f, fullPath, StringComparison.InvariantCultureIgnoreCase) == 0) == false) { DataFacade.Delete(assemblyReference); } } IInlineFunction oldFunction = DataFacade.GetData<IInlineFunction>(f => f.Id == function.Id).Single(); if ((oldFunction.Name != function.Name) || (oldFunction.Namespace != function.Namespace)) { InlineFunctionHelper.FunctionRenamed(function, oldFunction); } List<ManagedParameterDefinition> parameters = this.GetBinding<List<ManagedParameterDefinition>>("Parameters"); ManagedParameterManager.Save(function.Id, parameters); DataFacade.Update(function); function.SetFunctionCode(code); transactionScope.Complete(); } SetSaveStatus(true); UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken); updateTreeRefresher.PostRefreshMesseges(function.GetDataEntityToken()); } private void editCodeActivity_Preview_ExecuteCode(object sender, EventArgs e) { IInlineFunction functionInfo = this.GetBinding<IInlineFunction>("Function"); string code = this.GetBinding<string>("FunctionCode"); List<string> selectedAssemblies = this.GetBinding<List<string>>("SelectedAssemblies"); StringInlineFunctionCreateMethodErrorHandler handler = new StringInlineFunctionCreateMethodErrorHandler(); MethodInfo methodInfo = InlineFunctionHelper.Create(functionInfo, code, handler, selectedAssemblies); FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); IFormFlowWebRenderingService formFlowWebRenderingService = serviceContainer.GetService<IFormFlowWebRenderingService>(); if (handler.HasErrors) { StringBuilder sb = new StringBuilder(); if (!string.IsNullOrWhiteSpace(handler.MissingContainerType)) { AddFormattedTextBlock(sb, handler.MissingContainerType); } if (!string.IsNullOrWhiteSpace(handler.NamespaceMismatch)) { AddFormattedTextBlock(sb, handler.NamespaceMismatch); } if (!string.IsNullOrWhiteSpace(handler.MissionMethod)) { AddFormattedTextBlock(sb, handler.MissionMethod); } if (handler.LoadingException != null) { AddFormattedTextBlock(sb, handler.LoadingException.ToString()); } foreach (Tuple<int, string, string> compileError in handler.CompileErrors) { AddFormattedTextBlock(sb, "{0} : {1} : {2}".FormatWith(compileError.Item1, compileError.Item2, compileError.Item3)); } formFlowWebRenderingService.SetNewPageOutput(new LiteralControl(sb.ToString())); return; } List<ManagedParameterDefinition> parameters = this.GetBinding<List<ManagedParameterDefinition>>("Parameters"); List<object> parameterValues = new List<object>(); bool parameterErrors = false; StringBuilder parameterErrorMessages = new StringBuilder(); foreach (ParameterInfo parameterInfo in methodInfo.GetParameters()) { ManagedParameterDefinition parameter = parameters.FirstOrDefault(f => f.Name == parameterInfo.Name); if (parameter == null) { string message = string.Format(GetText("CSharpInlineFunction.MissingParameterDefinition"), parameterInfo.Name); parameterErrors = true; AddFormattedTextBlock(parameterErrorMessages, message); } else if (parameter.Type != parameterInfo.ParameterType) { string message = string.Format(GetText("CSharpInlineFunction.WrongParameterTestValueType"), parameterInfo.Name, parameterInfo.ParameterType, parameter.Type); parameterErrors = true; AddFormattedTextBlock(parameterErrorMessages, message); } else { string previewValueFunctionMarkup = (string.IsNullOrEmpty(parameter.TestValueFunctionMarkup) ? parameter.DefaultValueFunctionMarkup : parameter.TestValueFunctionMarkup); if (string.IsNullOrEmpty(previewValueFunctionMarkup)) { string message = string.Format(GetText("CSharpInlineFunction.MissingParameterTestOrDefaultValue"), parameterInfo.Name, parameterInfo.ParameterType, parameter.Type); parameterErrors = true; AddFormattedTextBlock(parameterErrorMessages, message); } else { try { BaseRuntimeTreeNode treeNode = FunctionFacade.BuildTree(XElement.Parse(previewValueFunctionMarkup)); object value = treeNode.GetValue(); object typedValue = ValueTypeConverter.Convert(value, parameter.Type); parameterValues.Add(typedValue); } catch (Exception ex) { string message = string.Format("Error setting '{0}'. {1}", parameterInfo.Name, ex.Message); parameterErrors = true; AddFormattedTextBlock(parameterErrorMessages, message); } } } } if (parameterErrors) { formFlowWebRenderingService.SetNewPageOutput(new LiteralControl(parameterErrorMessages.ToString())); return; } CultureInfo oldCurrentCulture = Thread.CurrentThread.CurrentCulture; CultureInfo oldCurrentUICulture = Thread.CurrentThread.CurrentUICulture; try { Guid pageId; if (this.GetBinding<object>("PageId") == null) { pageId = Guid.Empty; } else { pageId = this.GetBinding<Guid>("PageId"); } string dataScopeName = this.GetBinding<string>("PageDataScopeName"); string cultureName = this.GetBinding<string>("ActiveCultureName"); CultureInfo cultureInfo = null; if (cultureName != null) { cultureInfo = CultureInfo.CreateSpecificCulture(cultureName); } using (new DataScope(DataScopeIdentifier.Deserialize(dataScopeName), cultureInfo)) { Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = cultureInfo; IPage page = DataFacade.GetData<IPage>(f => f.Id == pageId).FirstOrDefault(); if (page != null) { PageRenderer.CurrentPage = page; } object result = methodInfo.Invoke(null, parameterValues.ToArray()); string resultString; try { resultString = PrettyPrinter.Print(result); } catch(Exception ex) { throw new TargetInvocationException(ex); } SetOutput(formFlowWebRenderingService, resultString); } } catch (TargetInvocationException ex) { SetOutput(formFlowWebRenderingService, ex.InnerException.ToString()); } finally { Thread.CurrentThread.CurrentCulture = oldCurrentCulture; Thread.CurrentThread.CurrentUICulture = oldCurrentUICulture; } } private void AddFormattedTextBlock(StringBuilder sb, string text) { sb.Append("<pre>"); sb.Append(HttpUtility.HtmlEncode(text)); sb.AppendLine("</pre>"); } private void SetOutput(IFormFlowWebRenderingService formFlowWebRenderingService, string text) { Control output = new LiteralControl("<pre>" + HttpUtility.HtmlEncode(text) + "</pre>"); formFlowWebRenderingService.SetNewPageOutput(output); } private string GetText(string key) { return StringResourceSystemFacade.GetString("Composite.Plugins.MethodBasedFunctionProviderElementProvider", key); } } [Serializable] public sealed class ParameterEditorState : IParameterEditorState { public Guid WorkflowId { get; set; } private FormData GetFormData() { return WorkflowFacade.GetFormData(WorkflowId); } [XmlIgnore] public List<ManagedParameterDefinition> Parameters { get { return GetFormData().Bindings["Parameters"] as List<ManagedParameterDefinition>; } set { GetFormData().Bindings["Parameters"] = value; } } [XmlIgnore] public List<Type> ParameterTypeOptions { get { return (GetFormData().Bindings["ParameterTypeOptions"] as IEnumerable<Type>).ToList(); } set { GetFormData().Bindings["ParameterTypeOptions"] = value.ToList(); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/EditInlineFunctionWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Workflows.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider { partial class EditInlineFunctionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity_Save = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.editCodeActivity_Preview = new System.Workflow.Activities.CodeActivity(); this.previewHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.PreviewHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_InitBindings = new System.Workflow.Activities.CodeActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editEventDrivenActivity_Preview = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editEventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "editStateActivity"; // // saveCodeActivity_Save // this.saveCodeActivity_Save.Name = "saveCodeActivity_Save"; this.saveCodeActivity_Save.ExecuteCode += new System.EventHandler(this.saveCodeActivity_Save_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // editCodeActivity_Preview // this.editCodeActivity_Preview.Name = "editCodeActivity_Preview"; this.editCodeActivity_Preview.ExecuteCode += new System.EventHandler(this.editCodeActivity_Preview_ExecuteCode); // // previewHandleExternalEventActivity1 // this.previewHandleExternalEventActivity1.EventName = "Preview"; this.previewHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.previewHandleExternalEventActivity1.Name = "previewHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.CustomToolbarDefinitionFileName = null; this.documentFormActivity1.FormDefinitionFileName = "\\Administrative\\InlineFunctionEditFunction.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "saveStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // initializeCodeActivity_InitBindings // this.initializeCodeActivity_InitBindings.Name = "initializeCodeActivity_InitBindings"; this.initializeCodeActivity_InitBindings.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_InitBindings_ExecuteCode); // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.saveCodeActivity_Save); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity5); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // editEventDrivenActivity_Preview // this.editEventDrivenActivity_Preview.Activities.Add(this.previewHandleExternalEventActivity1); this.editEventDrivenActivity_Preview.Activities.Add(this.editCodeActivity_Preview); this.editEventDrivenActivity_Preview.Activities.Add(this.setStateActivity2); this.editEventDrivenActivity_Preview.Name = "editEventDrivenActivity_Preview"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // editEventDrivenActivity_Save // this.editEventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.editEventDrivenActivity_Save.Activities.Add(this.setStateActivity3); this.editEventDrivenActivity_Save.Name = "editEventDrivenActivity_Save"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_InitBindings); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.saveStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editEventDrivenActivity_Save); this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_Preview); this.editStateActivity.Name = "editStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // EditInlineFunctionWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "EditInlineFunctionWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity5; private C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity4; private CodeActivity initializeCodeActivity_InitBindings; private StateInitializationActivity saveStateInitializationActivity; private StateInitializationActivity editStateInitializationActivity; private EventDrivenActivity editEventDrivenActivity_Save; private StateActivity saveStateActivity; private StateActivity editStateActivity; private CodeActivity saveCodeActivity_Save; private SetStateActivity setStateActivity2; private CodeActivity editCodeActivity_Preview; private C1Console.Workflow.Activities.PreviewHandleExternalEventActivity previewHandleExternalEventActivity1; private EventDrivenActivity editEventDrivenActivity_Preview; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/EditInlineFunctionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1120; 986" AutoSizeMargin="16; 24" Location="30; 30" Name="EditInlineFunctionWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="63; 105" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 182" Location="71; 136"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_InitBindings" Size="130; 41" Location="81; 198" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="81; 258" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="805; 634" Name="finalStateActivity" /> <StateDesigner Size="208; 118" AutoSizeMargin="16; 24" Location="197; 388" Name="editStateActivity"> <StateDesigner.Designers> <EventDrivenDesigner Name="editEventDrivenActivity_Save" Size="150; 182" Location="205; 443"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130; 41" Location="215; 505" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="215; 565" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateInitializationDesigner Name="editStateInitializationActivity" Size="150; 122" Location="205; 419"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="documentFormActivity1" Size="130; 41" Location="215; 481" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="editEventDrivenActivity_Preview" Size="150; 242" Location="205; 467"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="previewHandleExternalEventActivity1" Size="130; 41" Location="215; 529" /> <CodeDesigner Name="editCodeActivity_Preview" Size="130; 41" Location="215; 589" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="215; 649" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="193; 80" AutoSizeMargin="16; 24" Location="500; 387" Name="saveStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="saveStateInitializationActivity" Size="150; 182" Location="508; 418"> <StateInitializationDesigner.Designers> <CodeDesigner Name="saveCodeActivity_Save" Size="130; 41" Location="518; 480" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="518; 540" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="EditInlineFunctionWorkflow" TargetConnectionIndex="0" SourceStateName="EditInlineFunctionWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="885" Y="71" /> <ns0:Point X="885" Y="634" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity4" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="269" Y="146" /> <ns0:Point X="301" Y="146" /> <ns0:Point X="301" Y="388" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" SetStateName="setStateActivity3" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editEventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="386" Y="453" /> <ns0:Point X="417" Y="453" /> <ns0:Point X="417" Y="379" /> <ns0:Point X="596" Y="379" /> <ns0:Point X="596" Y="387" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity2" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editEventDrivenActivity_Preview" SourceConnectionIndex="2" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="401" Y="477" /> <ns0:Point X="413" Y="477" /> <ns0:Point X="413" Y="380" /> <ns0:Point X="301" Y="380" /> <ns0:Point X="301" Y="388" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity5" SourceActivity="saveStateActivity" TargetConnectionIndex="0" SourceStateName="saveStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="saveStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="689" Y="428" /> <ns0:Point X="701" Y="428" /> <ns0:Point X="701" Y="380" /> <ns0:Point X="301" Y="380" /> <ns0:Point X="301" Y="388" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/EditMethodBasedFunctionWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider { partial class EditMethodBasedFunctionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.validateStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editEventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.validateStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "editStateActivity"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "saveStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity5); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity6); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsValidData); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // saveCodeActivity // this.saveCodeActivity.Name = "saveCodeActivity"; this.saveCodeActivity.ExecuteCode += new System.EventHandler(this.saveCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "validateStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.FormDefinitionFileName = "\\Administrative\\EditMethodBasedFunction.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "editStateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // validateStateInitializationActivity // this.validateStateInitializationActivity.Activities.Add(this.ifElseActivity1); this.validateStateInitializationActivity.Name = "validateStateInitializationActivity"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.saveCodeActivity); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity2); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // editEventDrivenActivity_Save // this.editEventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.editEventDrivenActivity_Save.Activities.Add(this.setStateActivity3); this.editEventDrivenActivity_Save.Name = "editEventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initalizeStateInitializationActivity // this.initalizeStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initalizeStateInitializationActivity.Activities.Add(this.setStateActivity1); this.initalizeStateInitializationActivity.Name = "initalizeStateInitializationActivity"; // // validateStateActivity // this.validateStateActivity.Activities.Add(this.validateStateInitializationActivity); this.validateStateActivity.Name = "validateStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity4); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.saveStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_Save); this.editStateActivity.Name = "editStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initalizeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // EditMethodBasedFunctionWorkflow // this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.validateStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "EditMethodBasedFunctionWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity1; private CodeActivity initializeCodeActivity; private StateInitializationActivity saveStateInitializationActivity; private EventDrivenActivity editEventDrivenActivity_Save; private StateInitializationActivity editStateInitializationActivity; private StateInitializationActivity initalizeStateInitializationActivity; private StateActivity saveStateActivity; private StateActivity editStateActivity; private CodeActivity saveCodeActivity; private Composite.C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateActivity finalStateActivity; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity6; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private StateInitializationActivity validateStateInitializationActivity; private StateActivity validateStateActivity; private StateActivity initializeStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/EditMethodBasedFunctionWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.Data; using Composite.Data.Types; using Composite.Core.Extensions; using Composite.Core.Types; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.MethodBasedFunctionProviderElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditMethodBasedFunctionWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditMethodBasedFunctionWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; this.Bindings.Add("CurrentMethodFunctionInfo", dataEntityToken.Data); this.Bindings.Add("ErrorMessage", null); } private void IsValidData(object sender, ConditionalEventArgs e) { e.Result = false; IMethodBasedFunctionInfo function = this.GetBinding<IMethodBasedFunctionInfo>("CurrentMethodFunctionInfo"); if (function.UserMethodName == String.Empty) { this.ShowFieldMessage("CurrentMethodFunctionInfo.UserMethodName", "${Composite.Plugins.MethodBasedFunctionProviderElementProvider, EditFunction.MethodNameEmpty}"); return; } if (!function.Namespace.IsCorrectNamespace('.')) { this.ShowFieldMessage("CurrentMethodFunctionInfo.UserMethodName", "${Composite.Plugins.MethodBasedFunctionProviderElementProvider, EditFunction.InvalidNamespace}"); return; } Type type = TypeManager.TryGetType(function.Type); if (type == null) { this.ShowFieldMessage("CurrentMethodFunctionInfo.Type", "${Composite.Plugins.MethodBasedFunctionProviderElementProvider, EditFunction.TypeNotFound}"); return; } List<string> methodNames = (from methodInfo in type.GetMethods() select methodInfo.Name).ToList(); if (!methodNames.Contains(function.MethodName)) { this.ShowFieldMessage("CurrentMethodFunctionInfo.MethodName", "${Composite.Plugins.MethodBasedFunctionProviderElementProvider, EditFunction.MethodNotInType}"); return; } if (methodNames.Count == 0) { this.ShowFieldMessage("CurrentMethodFunctionInfo.Type", "${Composite.Plugins.MethodBasedFunctionProviderElementProvider, EditFunction.NoValidMethod}"); return; } int destinctCount = methodNames.Distinct().Count(); if (destinctCount != methodNames.Count) { this.ShowFieldMessage("CurrentMethodFunctionInfo.Type", "${Composite.Plugins.MethodBasedFunctionProviderElementProvider, EditFunction.MethodOverloadsNotAllowed}"); return; } e.Result = true; } private void saveCodeActivity_ExecuteCode(object sender, EventArgs e) { UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken); IMethodBasedFunctionInfo methodBasedFunctionInfo = this.GetBinding<IMethodBasedFunctionInfo>("CurrentMethodFunctionInfo"); DataFacade.Update(methodBasedFunctionInfo); SetSaveStatus(true); updateTreeRefresher.PostRefreshMesseges(methodBasedFunctionInfo.GetDataEntityToken()); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/MethodBasedFunctionProviderElementProvider/EditMethodBasedFunctionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="EditMethodBasedFunctionWorkflow" Location="30; 30" Size="1132; 974" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="EditMethodBasedFunctionWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="EditMethodBasedFunctionWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="876" Y="71" /> <ns0:Point X="876" Y="731" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="261" Y="142" /> <ns0:Point X="273" Y="142" /> <ns0:Point X="273" Y="334" /> <ns0:Point X="169" Y="334" /> <ns0:Point X="169" Y="346" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="validateStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="editStateActivity" SourceConnectionEdge="Right" TargetActivity="validateStateActivity" SourceActivity="editStateActivity" EventHandlerName="editEventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="262" Y="411" /> <ns0:Point X="431" Y="411" /> <ns0:Point X="431" Y="452" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="saveStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="saveStateActivity" EventHandlerName="saveStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="775" Y="354" /> <ns0:Point X="785" Y="354" /> <ns0:Point X="785" Y="306" /> <ns0:Point X="169" Y="306" /> <ns0:Point X="169" Y="346" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="saveStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="validateStateActivity" SourceConnectionEdge="Right" TargetActivity="saveStateActivity" SourceActivity="validateStateActivity" EventHandlerName="validateStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="532" Y="493" /> <ns0:Point X="548" Y="493" /> <ns0:Point X="548" Y="305" /> <ns0:Point X="682" Y="305" /> <ns0:Point X="682" Y="313" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="validateStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="validateStateActivity" EventHandlerName="validateStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="532" Y="493" /> <ns0:Point X="545" Y="493" /> <ns0:Point X="545" Y="338" /> <ns0:Point X="169" Y="338" /> <ns0:Point X="169" Y="346" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initializeStateActivity" Location="57; 101" Size="208; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initalizeStateInitializationActivity" Location="65; 132"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity" Location="75; 194" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="75; 254" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="editStateActivity" Location="73; 346" Size="193; 94" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="editStateInitializationActivity" Location="81; 377"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="documentFormActivity1" Location="91; 439" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="editEventDrivenActivity_Save" Location="81; 401"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="saveHandleExternalEventActivity1" Location="91; 463" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="91; 523" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="saveStateActivity" Location="586; 313" Size="193; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="saveStateInitializationActivity" Location="594; 344"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="saveCodeActivity" Location="604; 406" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="604; 466" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="finalStateActivity" Location="796; 731" Size="160; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="validateStateActivity" Location="327; 452" Size="209; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 303" Name="validateStateInitializationActivity" Location="335; 483"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="361; 222" Name="ifElseActivity1" Location="345; 545"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity1" Location="364; 616"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="374; 678" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity2" Location="537; 616"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="547; 678" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/AddPackageSourceWorkflow.cs ================================================ using System; using Composite.C1Console.Workflow; using Composite.Core; using Composite.Core.PackageSystem; using Composite.Data.Types; using Composite.Data; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Plugins_PackageElementProvider; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddPackageSourceWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { private static readonly string LogTitle = typeof (AddPackageSourceWorkflow).Name; private bool _urlIsValid; private static class BindingNames { public const string Url = "Url"; public const string HttpOnly = "HttpOnly"; public const string CleanedUrl = "CleanedUrl"; } public AddPackageSourceWorkflow() { InitializeComponent(); } private void IsUrlValid(object sender, System.Workflow.Activities.ConditionalEventArgs e) { e.Result = _urlIsValid; } private void initializeCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { this.Bindings[BindingNames.Url] = ""; this.Bindings[BindingNames.HttpOnly] = true; } private void step1CodeActivity_ValidateServerUrl_ExecuteCode(object sender, EventArgs e) { string url = this.GetBinding<string>("Url"); try { var uriBuilder = new UriBuilder(url); string cleanedUrl = uriBuilder.Uri.ToString().Remove(0, uriBuilder.Scheme.Length + 3); if (cleanedUrl.EndsWith("/")) { cleanedUrl = cleanedUrl.Remove(cleanedUrl.Length - 1); } ServerUrlValidationResult serverUrlValidationResult = PackageServerFacade.ValidateServerUrl(cleanedUrl); _urlIsValid = true; if (serverUrlValidationResult == ServerUrlValidationResult.Invalid) { this.ShowFieldMessage(BindingNames.Url, Texts.AddPackageSource_Step1_UrlNonPackageServer); _urlIsValid = false; } else if (serverUrlValidationResult == ServerUrlValidationResult.Https) { cleanedUrl = string.Format("https://{0}", cleanedUrl); this.UpdateBinding(BindingNames.HttpOnly, false); } else if (serverUrlValidationResult == ServerUrlValidationResult.Http) { cleanedUrl = string.Format("http://{0}", cleanedUrl); } this.UpdateBinding(BindingNames.CleanedUrl, cleanedUrl); } catch (Exception ex) { Log.LogWarning(LogTitle, "Failed to validate package source '{0}'", url); Log.LogWarning(LogTitle, ex); this.ShowFieldMessage(BindingNames.Url, Texts.AddPackageSource_Step1_UrlNotValid); } } private void step2CodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { var packageServerSource = DataFacade.BuildNew<IPackageServerSource>(); packageServerSource.Id = Guid.NewGuid(); packageServerSource.Url = this.GetBinding<string>(BindingNames.CleanedUrl); DataFacade.AddNew(packageServerSource); this.CreateSpecificTreeRefresher().PostRefreshMesseges(new PackageElementProviderRootEntityToken()); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/AddPackageSourceWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { partial class AddPackageSourceWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.step2CodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.step2CloseCurrentViewActivity = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step2WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step1IfElseActivity_IsUrlValid = new System.Workflow.Activities.IfElseActivity(); this.step1CodeActivity_ValidateServerUrl = new System.Workflow.Activities.CodeActivity(); this.nextHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.step1WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.step2EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step2StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step2EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step2StateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "step1StateActivity"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "step2StateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity3); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity5); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsUrlValid); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // step2CodeActivity_Finalize // this.step2CodeActivity_Finalize.Name = "step2CodeActivity_Finalize"; this.step2CodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.step2CodeActivity_Finalize_ExecuteCode); // // step2CloseCurrentViewActivity // this.step2CloseCurrentViewActivity.Name = "step2CloseCurrentViewActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // step2WizardFormActivity // this.step2WizardFormActivity.ContainerLabel = null; this.step2WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderAddPackageSourceStep2.xml"; this.step2WizardFormActivity.Name = "step2WizardFormActivity"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // step1IfElseActivity_IsUrlValid // this.step1IfElseActivity_IsUrlValid.Activities.Add(this.ifElseBranchActivity1); this.step1IfElseActivity_IsUrlValid.Activities.Add(this.ifElseBranchActivity2); this.step1IfElseActivity_IsUrlValid.Name = "step1IfElseActivity_IsUrlValid"; // // step1CodeActivity_ValidateServerUrl // this.step1CodeActivity_ValidateServerUrl.Name = "step1CodeActivity_ValidateServerUrl"; this.step1CodeActivity_ValidateServerUrl.ExecuteCode += new System.EventHandler(this.step1CodeActivity_ValidateServerUrl_ExecuteCode); // // nextHandleExternalEventActivity1 // this.nextHandleExternalEventActivity1.EventName = "Next"; this.nextHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity1.Name = "nextHandleExternalEventActivity1"; // // step1WizardFormActivity // this.step1WizardFormActivity.ContainerLabel = null; this.step1WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderAddPackageSourceStep1.xml"; this.step1WizardFormActivity.Name = "step1WizardFormActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // initializeCodeActivity_Initialize // this.initializeCodeActivity_Initialize.Name = "initializeCodeActivity_Initialize"; this.initializeCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_Initialize_ExecuteCode); // // step2EventDrivenActivity_Finish // this.step2EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step2EventDrivenActivity_Finish.Activities.Add(this.step2CloseCurrentViewActivity); this.step2EventDrivenActivity_Finish.Activities.Add(this.step2CodeActivity_Finalize); this.step2EventDrivenActivity_Finish.Activities.Add(this.setStateActivity4); this.step2EventDrivenActivity_Finish.Name = "step2EventDrivenActivity_Finish"; // // step2StateInitializationActivity // this.step2StateInitializationActivity.Activities.Add(this.step2WizardFormActivity); this.step2StateInitializationActivity.Name = "step2StateInitializationActivity"; // // step2EventDrivenActivity_Cancel // this.step2EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step2EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity6); this.step2EventDrivenActivity_Cancel.Name = "step2EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Next // this.step1EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity1); this.step1EventDrivenActivity_Next.Activities.Add(this.step1CodeActivity_ValidateServerUrl); this.step1EventDrivenActivity_Next.Activities.Add(this.step1IfElseActivity_IsUrlValid); this.step1EventDrivenActivity_Next.Name = "step1EventDrivenActivity_Next"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1WizardFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_Initialize); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // step2StateActivity // this.step2StateActivity.Activities.Add(this.step2StateInitializationActivity); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Finish); this.step2StateActivity.Name = "step2StateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Next); this.step1StateActivity.Activities.Add(this.step2EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // AddPackageSourceWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.step2StateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddPackageSourceWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private Composite.C1Console.Workflow.Activities.WizardFormActivity step1WizardFormActivity; private StateInitializationActivity step1StateInitializationActivity; private StateActivity step1StateActivity; private CodeActivity initializeCodeActivity_Initialize; private CodeActivity step1CodeActivity_ValidateServerUrl; private Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity step1EventDrivenActivity_Next; private SetStateActivity setStateActivity3; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private CodeActivity step2CodeActivity_Finalize; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.WizardFormActivity step2WizardFormActivity; private IfElseActivity step1IfElseActivity_IsUrlValid; private EventDrivenActivity step2EventDrivenActivity_Finish; private StateInitializationActivity step2StateInitializationActivity; private StateActivity step2StateActivity; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity step2CloseCurrentViewActivity; private SetStateActivity setStateActivity6; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step2EventDrivenActivity_Cancel; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/AddPackageSourceWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="AddPackageSourceWorkflow" Location="30; 30" Size="1068; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="AddPackageSourceWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="AddPackageSourceWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="143" Y="71" /> <ns0:Point X="143" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="269" Y="146" /> <ns0:Point X="285" Y="146" /> <ns0:Point X="285" Y="286" /> <ns0:Point X="168" Y="286" /> <ns0:Point X="168" Y="297" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step2StateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="step2StateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="260" Y="362" /> <ns0:Point X="284" Y="362" /> <ns0:Point X="284" Y="422" /> <ns0:Point X="166" Y="422" /> <ns0:Point X="166" Y="431" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="260" Y="362" /> <ns0:Point X="284" Y="362" /> <ns0:Point X="284" Y="290" /> <ns0:Point X="168" Y="290" /> <ns0:Point X="168" Y="297" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step2EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="270" Y="386" /> <ns0:Point X="286" Y="386" /> <ns0:Point X="286" Y="194" /> <ns0:Point X="143" Y="194" /> <ns0:Point X="143" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step2StateActivity" EventHandlerName="step2EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="266" Y="496" /> <ns0:Point X="282" Y="496" /> <ns0:Point X="282" Y="192" /> <ns0:Point X="143" Y="192" /> <ns0:Point X="143" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="63; 105" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initializeStateInitializationActivity" Location="71; 136"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity_Initialize" Location="81; 198" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="81; 258" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="63; 201" Size="160; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="step1StateActivity" Location="63; 297" Size="211; 118" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="71; 328"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step1WizardFormActivity" Location="81; 390" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="381; 423" Name="step1EventDrivenActivity_Next" Location="71; 352"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="nextHandleExternalEventActivity1" Location="196; 414" /> <CodeDesigner Size="130; 41" Name="step1CodeActivity_ValidateServerUrl" Location="196; 474" /> <IfElseDesigner Size="361; 222" Name="step1IfElseActivity_IsUrlValid" Location="81; 534"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity1" Location="100; 605"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="110; 667" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity2" Location="273; 605"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="283; 667" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step2EventDrivenActivity_Cancel" Location="71; 376"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="81; 438" /> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="81; 498" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="step2StateActivity" Location="63; 431" Size="207; 94" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step2StateInitializationActivity" Location="481; 135"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step2WizardFormActivity" Location="491; 197" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 302" Name="step2EventDrivenActivity_Finish" Location="489; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="499; 210" /> <ActivityDesigner Size="130; 41" Name="step2CloseCurrentViewActivity" Location="499; 270" /> <CodeDesigner Size="130; 41" Name="step2CodeActivity_Finalize" Location="499; 330" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="499; 390" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/DeletePackageSourceWorkflow.cs ================================================ using System; using Composite.Data; using Composite.C1Console.Workflow; using Composite.C1Console.Actions; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeletePackageSourceWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeletePackageSourceWorkflow() { InitializeComponent(); } private void step1CodeActivity_Delete_ExecuteCode(object sender, EventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; DataFacade.Delete(dataEntityToken.Data); SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(new PackageElementProviderRootEntityToken()); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/DeletePackageSourceWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { partial class DeletePackageSourceWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.step1CodeActivity_Delete = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.step1FinishHandleExternalEventActivity = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step1ConfirmDialogFormActivity = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EentDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // step1CodeActivity_Delete // this.step1CodeActivity_Delete.Name = "step1CodeActivity_Delete"; this.step1CodeActivity_Delete.ExecuteCode += new System.EventHandler(this.step1CodeActivity_Delete_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // step1FinishHandleExternalEventActivity // this.step1FinishHandleExternalEventActivity.EventName = "Finish"; this.step1FinishHandleExternalEventActivity.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.step1FinishHandleExternalEventActivity.Name = "step1FinishHandleExternalEventActivity"; // // step1ConfirmDialogFormActivity // this.step1ConfirmDialogFormActivity.ContainerLabel = null; this.step1ConfirmDialogFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderDeletePackageSourceStep1.xml"; this.step1ConfirmDialogFormActivity.Name = "step1ConfirmDialogFormActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity4); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EentDrivenActivity_Finish // this.step1EentDrivenActivity_Finish.Activities.Add(this.step1FinishHandleExternalEventActivity); this.step1EentDrivenActivity_Finish.Activities.Add(this.closeCurrentViewActivity1); this.step1EentDrivenActivity_Finish.Activities.Add(this.step1CodeActivity_Delete); this.step1EentDrivenActivity_Finish.Activities.Add(this.setStateActivity3); this.step1EentDrivenActivity_Finish.Name = "step1EentDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1ConfirmDialogFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EentDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // DeletePackageSourceWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "DeletePackageSourceWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity2; private StateInitializationActivity step1StateInitializationActivity; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity step1ConfirmDialogFormActivity; private CodeActivity step1CodeActivity_Delete; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity step1FinishHandleExternalEventActivity; private EventDrivenActivity step1EentDrivenActivity_Finish; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/DeletePackageSourceWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="DeletePackageSourceWorkflow" Location="30; 30" Size="1148; 996" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="DeletePackageSourceWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="DeletePackageSourceWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="757" Y="71" /> <ns0:Point X="757" Y="490" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="269" Y="146" /> <ns0:Point X="288" Y="146" /> <ns0:Point X="288" Y="330" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EentDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="380" Y="395" /> <ns0:Point X="757" Y="395" /> <ns0:Point X="757" Y="490" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="390" Y="419" /> <ns0:Point X="757" Y="419" /> <ns0:Point X="757" Y="490" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="63; 105" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="initializeStateInitializationActivity" Location="71; 136"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="81; 198" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="677; 490" Size="160; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="step1StateActivity" Location="183; 330" Size="211; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="191; 361"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step1ConfirmDialogFormActivity" Location="201; 423" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 302" Name="step1EentDrivenActivity_Finish" Location="191; 385"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="step1FinishHandleExternalEventActivity" Location="201; 447" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="201; 507" /> <CodeDesigner Size="130; 41" Name="step1CodeActivity_Delete" Location="201; 567" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="201; 627" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="191; 409"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="201; 471" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="201; 531" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/InstallLocalPackageWorkflow.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Forms.CoreUiControls; using Composite.Core.PackageSystem; using Composite.Core.ResourceSystem; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class InstallLocalPackageWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public InstallLocalPackageWorkflow() { InitializeComponent(); } private void WasFileSelected(object sender, System.Workflow.Activities.ConditionalEventArgs e) { UploadedFile uploadedFile = this.GetBinding<UploadedFile>("UploadedFile"); e.Result = uploadedFile.HasFile; } private void DidValidate(object sender, System.Workflow.Activities.ConditionalEventArgs e) { e.Result = this.BindingExist("Errors") == false; } private void initializeCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { this.UpdateBinding("LayoutLabel", StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallLocalPackage.ShowError.LayoutLabel")); this.UpdateBinding("TableCaption", StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallLocalPackage.ShowError.InfoTableCaption")); this.Bindings.Add("UploadedFile", new UploadedFile()); } private void step1CodeActivity_ValidateInstallation_ExecuteCode(object sender, EventArgs e) { try { UploadedFile uploadedFile = this.GetBinding<UploadedFile>("UploadedFile"); PackageManagerInstallProcess packageManagerInstallProcess = PackageManager.Install(uploadedFile.FileStream, true); if (packageManagerInstallProcess.PreInstallValidationResult.Count > 0) { this.UpdateBinding("Errors", WorkflowHelper.ValidationResultToBinding(packageManagerInstallProcess.PreInstallValidationResult)); } else { List<PackageFragmentValidationResult> validationResult = packageManagerInstallProcess.Validate(); if (validationResult.Count > 0) { this.UpdateBinding("LayoutLabel", StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallLocalPackage.ShowWarning.LayoutLabel")); this.UpdateBinding("TableCaption", StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallLocalPackage.ShowWarning.InfoTableCaption")); this.UpdateBinding("Errors", WorkflowHelper.ValidationResultToBinding(validationResult)); } else { this.Bindings.Add("PackageManagerInstallProcess", packageManagerInstallProcess); this.Bindings.Add("FlushOnCompletion", packageManagerInstallProcess.FlushOnCompletion); this.Bindings.Add("ReloadConsoleOnCompletion", packageManagerInstallProcess.ReloadConsoleOnCompletion); } } } catch (Exception ex) { this.UpdateBinding("Errors", new List<List<string>> { new List<string> { ex.Message, "" } }); } } private void step2CodeActivity_Install_ExecuteCode(object sender, EventArgs e) { try { PackageManagerInstallProcess packageManagerInstallProcess = this.GetBinding<PackageManagerInstallProcess>("PackageManagerInstallProcess"); List<PackageFragmentValidationResult> installResult = packageManagerInstallProcess.Install(); if (installResult.Count > 0) { this.UpdateBinding("Errors", WorkflowHelper.ValidationResultToBinding(installResult)); } } catch (Exception ex) { this.UpdateBinding("Errors", new List<List<string>> { new List<string> { ex.Message, "" } }); } } private void cleanupCodeActivity_Cleanup_ExecuteCode(object sender, EventArgs e) { PackageManagerInstallProcess packageManagerInstallProcess; if (this.TryGetBinding<PackageManagerInstallProcess>("PackageManagerInstallProcess", out packageManagerInstallProcess)) { packageManagerInstallProcess.CancelInstallation(); } } private void step3CodeActivity_RefreshTree_ExecuteCode(object sender, EventArgs e) { if (this.GetBinding<bool>("ReloadConsoleOnCompletion")) { ConsoleMessageQueueFacade.Enqueue(new RebootConsoleMessageQueueItem(), null); } if (this.GetBinding<bool>("FlushOnCompletion")) { GlobalEventSystemFacade.FlushTheSystem(); } SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(new PackageElementProviderRootEntityToken()); } private void showErrorCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { List<string> rowHeader = new List<string>(); rowHeader.Add(StringResourceSystemFacade.ParseString("${Composite.Plugins.PackageElementProvider, InstallLocalPackage.ShowError.MessageTitle}")); this.UpdateBinding("ErrorHeader", rowHeader); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/InstallLocalPackageWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { partial class InstallLocalPackageWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity5 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.step1If_DidValidate = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity2 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.cleanupCodeActivity_Cleanup = new System.Workflow.Activities.CodeActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.step3CodeActivity_RefreshTree = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step3WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.showErrorWizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.showErrorCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity11 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step2IfElseActivity_DidValidate = new System.Workflow.Activities.IfElseActivity(); this.step2CodeActivity_Install = new System.Workflow.Activities.CodeActivity(); this.nextHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.step2WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.step1CodeActivity_ValidateInstallation = new System.Workflow.Activities.CodeActivity(); this.nextHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.step1WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.cleanupStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step3EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step3StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.showErrorEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.showErrorStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step2EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step2EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step2StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.cleanupStateActivity = new System.Workflow.Activities.StateActivity(); this.step3StateActivity = new System.Workflow.Activities.StateActivity(); this.showErrorStateActivity = new System.Workflow.Activities.StateActivity(); this.step2StateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "showErrorStateActivity"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "step3StateActivity"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "showErrorStateActivity"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "step2StateActivity"; // // ifElseBranchActivity5 // this.ifElseBranchActivity5.Activities.Add(this.setStateActivity9); this.ifElseBranchActivity5.Name = "ifElseBranchActivity5"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity6); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DidValidate); this.ifElseBranchActivity4.Condition = codecondition1; this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity4); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // step1If_DidValidate // this.step1If_DidValidate.Activities.Add(this.setStateActivity3); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DidValidate); this.step1If_DidValidate.Condition = codecondition2; this.step1If_DidValidate.Name = "step1If_DidValidate"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity2 // this.closeCurrentViewActivity2.Name = "closeCurrentViewActivity2"; // // cleanupCodeActivity_Cleanup // this.cleanupCodeActivity_Cleanup.Name = "cleanupCodeActivity_Cleanup"; this.cleanupCodeActivity_Cleanup.ExecuteCode += new System.EventHandler(this.cleanupCodeActivity_Cleanup_ExecuteCode); // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // step3CodeActivity_RefreshTree // this.step3CodeActivity_RefreshTree.Name = "step3CodeActivity_RefreshTree"; this.step3CodeActivity_RefreshTree.ExecuteCode += new System.EventHandler(this.step3CodeActivity_RefreshTree_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // step3WizardFormActivity // this.step3WizardFormActivity.ContainerLabel = null; this.step3WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallLocalPackageStep3.xml"; this.step3WizardFormActivity.Name = "step3WizardFormActivity"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "finalStateActivity"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // showErrorWizardFormActivity // this.showErrorWizardFormActivity.ContainerLabel = null; this.showErrorWizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallLocalPackageShowError.xml"; this.showErrorWizardFormActivity.Name = "showErrorWizardFormActivity"; // // showErrorCodeActivity_Initialize // this.showErrorCodeActivity_Initialize.Name = "showErrorCodeActivity_Initialize"; this.showErrorCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.showErrorCodeActivity_Initialize_ExecuteCode); // // setStateActivity11 // this.setStateActivity11.Name = "setStateActivity11"; this.setStateActivity11.TargetStateName = "cleanupStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // step2IfElseActivity_DidValidate // this.step2IfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity4); this.step2IfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity5); this.step2IfElseActivity_DidValidate.Name = "step2IfElseActivity_DidValidate"; // // step2CodeActivity_Install // this.step2CodeActivity_Install.Name = "step2CodeActivity_Install"; this.step2CodeActivity_Install.ExecuteCode += new System.EventHandler(this.step2CodeActivity_Install_ExecuteCode); // // nextHandleExternalEventActivity2 // this.nextHandleExternalEventActivity2.EventName = "Next"; this.nextHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity2.Name = "nextHandleExternalEventActivity2"; // // step2WizardFormActivity // this.step2WizardFormActivity.ContainerLabel = null; this.step2WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallLocalPackageStep2.xml"; this.step2WizardFormActivity.Name = "step2WizardFormActivity"; // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "cleanupStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.step1If_DidValidate); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // step1CodeActivity_ValidateInstallation // this.step1CodeActivity_ValidateInstallation.Name = "step1CodeActivity_ValidateInstallation"; this.step1CodeActivity_ValidateInstallation.ExecuteCode += new System.EventHandler(this.step1CodeActivity_ValidateInstallation_ExecuteCode); // // nextHandleExternalEventActivity1 // this.nextHandleExternalEventActivity1.EventName = "Next"; this.nextHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity1.Name = "nextHandleExternalEventActivity1"; // // step1WizardFormActivity // this.step1WizardFormActivity.ContainerLabel = null; this.step1WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallLocalPackageStep1.xml"; this.step1WizardFormActivity.Name = "step1WizardFormActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // initializeCodeActivity_Initialize // this.initializeCodeActivity_Initialize.Name = "initializeCodeActivity_Initialize"; this.initializeCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_Initialize_ExecuteCode); // // cleanupStateInitializationActivity // this.cleanupStateInitializationActivity.Activities.Add(this.cleanupCodeActivity_Cleanup); this.cleanupStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity2); this.cleanupStateInitializationActivity.Activities.Add(this.setStateActivity5); this.cleanupStateInitializationActivity.Name = "cleanupStateInitializationActivity"; // // step3EventDrivenActivity_Finish // this.step3EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step3EventDrivenActivity_Finish.Activities.Add(this.closeCurrentViewActivity1); this.step3EventDrivenActivity_Finish.Activities.Add(this.step3CodeActivity_RefreshTree); this.step3EventDrivenActivity_Finish.Activities.Add(this.setStateActivity7); this.step3EventDrivenActivity_Finish.Name = "step3EventDrivenActivity_Finish"; // // step3StateInitializationActivity // this.step3StateInitializationActivity.Activities.Add(this.step3WizardFormActivity); this.step3StateInitializationActivity.Name = "step3StateInitializationActivity"; // // showErrorEventDrivenActivity_Finish // this.showErrorEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.showErrorEventDrivenActivity_Finish.Activities.Add(this.setStateActivity8); this.showErrorEventDrivenActivity_Finish.Name = "showErrorEventDrivenActivity_Finish"; // // showErrorStateInitializationActivity // this.showErrorStateInitializationActivity.Activities.Add(this.showErrorCodeActivity_Initialize); this.showErrorStateInitializationActivity.Activities.Add(this.showErrorWizardFormActivity); this.showErrorStateInitializationActivity.Name = "showErrorStateInitializationActivity"; // // step2EventDrivenActivity_Cancel // this.step2EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.step2EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity11); this.step2EventDrivenActivity_Cancel.Name = "step2EventDrivenActivity_Cancel"; // // step2EventDrivenActivity_Next // this.step2EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity2); this.step2EventDrivenActivity_Next.Activities.Add(this.step2CodeActivity_Install); this.step2EventDrivenActivity_Next.Activities.Add(this.step2IfElseActivity_DidValidate); this.step2EventDrivenActivity_Next.Name = "step2EventDrivenActivity_Next"; // // step2StateInitializationActivity // this.step2StateInitializationActivity.Activities.Add(this.step2WizardFormActivity); this.step2StateInitializationActivity.Name = "step2StateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity10); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Next // this.step1EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity1); this.step1EventDrivenActivity_Next.Activities.Add(this.step1CodeActivity_ValidateInstallation); this.step1EventDrivenActivity_Next.Activities.Add(this.ifElseActivity1); this.step1EventDrivenActivity_Next.Name = "step1EventDrivenActivity_Next"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1WizardFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_Initialize); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "cleanupStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // cleanupStateActivity // this.cleanupStateActivity.Activities.Add(this.cleanupStateInitializationActivity); this.cleanupStateActivity.Name = "cleanupStateActivity"; // // step3StateActivity // this.step3StateActivity.Activities.Add(this.step3StateInitializationActivity); this.step3StateActivity.Activities.Add(this.step3EventDrivenActivity_Finish); this.step3StateActivity.Name = "step3StateActivity"; // // showErrorStateActivity // this.showErrorStateActivity.Activities.Add(this.showErrorStateInitializationActivity); this.showErrorStateActivity.Activities.Add(this.showErrorEventDrivenActivity_Finish); this.showErrorStateActivity.Name = "showErrorStateActivity"; // // step2StateActivity // this.step2StateActivity.Activities.Add(this.step2StateInitializationActivity); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Next); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Cancel); this.step2StateActivity.Name = "step2StateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Next); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // InstallLocalPackageWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.step2StateActivity); this.Activities.Add(this.showErrorStateActivity); this.Activities.Add(this.step3StateActivity); this.Activities.Add(this.cleanupStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "InstallLocalPackageWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private Composite.C1Console.Workflow.Activities.WizardFormActivity step1WizardFormActivity; private EventDrivenActivity step1EventDrivenActivity_Next; private StateInitializationActivity step1StateInitializationActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity2; private CodeActivity initializeCodeActivity_Initialize; private CodeActivity step1CodeActivity_ValidateInstallation; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity3; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity step1If_DidValidate; private IfElseActivity ifElseActivity1; private Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity1; private StateActivity showErrorStateActivity; private StateActivity step2StateActivity; private Composite.C1Console.Workflow.Activities.WizardFormActivity step2WizardFormActivity; private StateInitializationActivity step2StateInitializationActivity; private CodeActivity step2CodeActivity_Install; private Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity2; private EventDrivenActivity step2EventDrivenActivity_Next; private Composite.C1Console.Workflow.Activities.WizardFormActivity step3WizardFormActivity; private StateInitializationActivity step3StateInitializationActivity; private StateActivity step3StateActivity; private SetStateActivity setStateActivity7; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity6; private EventDrivenActivity step3EventDrivenActivity_Finish; private EventDrivenActivity showErrorEventDrivenActivity_Finish; private StateInitializationActivity showErrorStateInitializationActivity; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private Composite.C1Console.Workflow.Activities.WizardFormActivity showErrorWizardFormActivity; private SetStateActivity setStateActivity8; private CodeActivity step3CodeActivity_RefreshTree; private SetStateActivity setStateActivity9; private IfElseBranchActivity ifElseBranchActivity5; private IfElseBranchActivity ifElseBranchActivity4; private IfElseActivity step2IfElseActivity_DidValidate; private CodeActivity showErrorCodeActivity_Initialize; private SetStateActivity setStateActivity5; private CodeActivity cleanupCodeActivity_Cleanup; private StateInitializationActivity cleanupStateInitializationActivity; private StateActivity cleanupStateActivity; private SetStateActivity setStateActivity11; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private SetStateActivity setStateActivity10; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step2EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Cancel; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity2; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/InstallLocalPackageWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="InstallLocalPackageWorkflow" Location="30; 30" Size="1068; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="cleanupStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="InstallLocalPackageWorkflow" SourceConnectionEdge="Right" TargetActivity="cleanupStateActivity" SourceActivity="InstallLocalPackageWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="240" Y="93" /> <ns0:Point X="285" Y="93" /> <ns0:Point X="285" Y="709" /> <ns0:Point X="736" Y="709" /> <ns0:Point X="736" Y="721" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="269" Y="146" /> <ns0:Point X="279" Y="146" /> <ns0:Point X="279" Y="243" /> <ns0:Point X="167" Y="243" /> <ns0:Point X="167" Y="255" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step2StateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="step2StateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="259" Y="320" /> <ns0:Point X="396" Y="320" /> <ns0:Point X="396" Y="400" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="showErrorStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="showErrorStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="259" Y="320" /> <ns0:Point X="283" Y="320" /> <ns0:Point X="283" Y="796" /> <ns0:Point X="195" Y="796" /> <ns0:Point X="195" Y="808" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="cleanupStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity10" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="cleanupStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="269" Y="344" /> <ns0:Point X="285" Y="344" /> <ns0:Point X="285" Y="709" /> <ns0:Point X="736" Y="709" /> <ns0:Point X="736" Y="721" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step3StateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="step3StateActivity" SourceActivity="step2StateActivity" EventHandlerName="step2EventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="488" Y="465" /> <ns0:Point X="661" Y="465" /> <ns0:Point X="661" Y="504" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="showErrorStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity9" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="showErrorStateActivity" SourceActivity="step2StateActivity" EventHandlerName="step2EventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="488" Y="465" /> <ns0:Point X="507" Y="465" /> <ns0:Point X="507" Y="796" /> <ns0:Point X="195" Y="796" /> <ns0:Point X="195" Y="808" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="cleanupStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity11" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="cleanupStateActivity" SourceActivity="step2StateActivity" EventHandlerName="step2EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="498" Y="489" /> <ns0:Point X="514" Y="489" /> <ns0:Point X="514" Y="709" /> <ns0:Point X="736" Y="709" /> <ns0:Point X="736" Y="721" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity8" SourceStateName="showErrorStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="showErrorStateActivity" EventHandlerName="showErrorEventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="306" Y="873" /> <ns0:Point X="322" Y="873" /> <ns0:Point X="322" Y="715" /> <ns0:Point X="928" Y="715" /> <ns0:Point X="928" Y="811" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="step3StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step3StateActivity" EventHandlerName="step3EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="761" Y="569" /> <ns0:Point X="928" Y="569" /> <ns0:Point X="928" Y="811" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="cleanupStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="cleanupStateActivity" EventHandlerName="cleanupStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="837" Y="762" /> <ns0:Point X="928" Y="762" /> <ns0:Point X="928" Y="811" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="63; 105" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initializeStateInitializationActivity" Location="71; 136"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity_Initialize" Location="81; 198" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="81; 258" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="848; 811" Size="160; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="step1StateActivity" Location="62; 255" Size="211; 118" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="70; 286"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step1WizardFormActivity" Location="80; 348" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="381; 423" Name="step1EventDrivenActivity_Next" Location="70; 310"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="nextHandleExternalEventActivity1" Location="195; 372" /> <CodeDesigner Size="130; 41" Name="step1CodeActivity_ValidateInstallation" Location="195; 432" /> <IfElseDesigner Size="361; 222" Name="ifElseActivity1" Location="80; 492"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="step1If_DidValidate" Location="99; 563"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="109; 625" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity2" Location="272; 563"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="282; 625" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 194" Name="step1EventDrivenActivity_Cancel" Location="70; 334"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="80; 396" /> <SetStateDesigner Size="130; 53" Name="setStateActivity10" Location="80; 456" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="step2StateActivity" Location="291; 400" Size="211; 118" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step2StateInitializationActivity" Location="299; 431"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step2WizardFormActivity" Location="309; 493" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="381; 423" Name="step2EventDrivenActivity_Next" Location="299; 455"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="nextHandleExternalEventActivity2" Location="424; 517" /> <CodeDesigner Size="130; 41" Name="step2CodeActivity_Install" Location="424; 577" /> <IfElseDesigner Size="361; 222" Name="step2IfElseActivity_DidValidate" Location="309; 637"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity4" Location="328; 708"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="338; 770" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity5" Location="501; 708"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity9" Location="511; 770" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 194" Name="step2EventDrivenActivity_Cancel" Location="299; 479"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity3" Location="309; 541" /> <SetStateDesigner Size="130; 53" Name="setStateActivity11" Location="309; 601" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="showErrorStateActivity" Location="80; 808" Size="230; 94" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="showErrorStateInitializationActivity" Location="88; 839"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="showErrorCodeActivity_Initialize" Location="98; 901" /> <ActivityDesigner Size="130; 41" Name="showErrorWizardFormActivity" Location="98; 961" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="showErrorEventDrivenActivity_Finish" Location="88; 863"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity2" Location="98; 925" /> <SetStateDesigner Size="130; 41" Name="setStateActivity8" Location="98; 985" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="step3StateActivity" Location="558; 504" Size="207; 94" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step3StateInitializationActivity" Location="566; 535"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step3WizardFormActivity" Location="576; 597" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 302" Name="step3EventDrivenActivity_Finish" Location="566; 559"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="576; 621" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="576; 681" /> <CodeDesigner Size="130; 41" Name="step3CodeActivity_RefreshTree" Location="576; 741" /> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="576; 801" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="cleanupStateActivity" Location="632; 721" Size="209; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="cleanupStateInitializationActivity" Location="489; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="cleanupCodeActivity_Cleanup" Location="499; 210" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity2" Location="499; 270" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="499; 330" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/InstallRemotePackageWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.Core.Configuration; using Composite.Core.Logging; using Composite.Core.PackageSystem; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { /// <exlude /> [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class InstallRemotePackageWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { bool _packageIsFree = false; public InstallRemotePackageWorkflow() { InitializeComponent(); } private PackageDescription GetPackageDescription() { PackageElementProviderAvailablePackagesItemEntityToken castedEntityToken = (PackageElementProviderAvailablePackagesItemEntityToken)this.EntityToken; PackageDescription packageDescription = (from description in PackageSystemServices.GetFilteredAllAvailablePackages() where description.Id == castedEntityToken.PackageId select description).SingleOrDefault(); if (packageDescription == null) { this.UpdateBinding("ServerError", true); } return packageDescription; } private void IsPackageFree(object sender, ConditionalEventArgs e) { e.Result = _packageIsFree; } private void EulaAccepted(object sender, ConditionalEventArgs e) { e.Result = this.GetBinding<bool>("EulaAccepted"); } private void DidValidate(object sender, System.Workflow.Activities.ConditionalEventArgs e) { e.Result = this.BindingExist("Errors") == false; } private void initializeStateCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { this.UpdateBinding("LayoutLabel", StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallRemotePackage.ShowError.LayoutLabel")); this.UpdateBinding("TableCaption", StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallRemotePackage.ShowError.InfoTableCaption")); try { _packageIsFree = GetPackageDescription().IsFree; } catch (Exception ex) { LoggingService.LogVerbose("InstallRemotePackageWorkflowRGB(100, 100, 255)", ex.Message); this.UpdateBinding("Errors", new List<List<string>> { new List<string> { ex.Message, "" } }); } } private void step2StateStepcodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { try { if (this.BindingExist("EulaText") == false) { PackageDescription packageDescription = GetPackageDescription(); string eulaText = PackageSystemServices.GetEulaText(packageDescription); this.Bindings.Add("EulaText", eulaText); } if (this.BindingExist("EulaAccepted") == false) { this.Bindings.Add("EulaAccepted", false); } } catch (Exception ex) { this.UpdateBinding("Errors", new List<List<string>> { new List<string> { ex.Message, "" } }); } } private void step3CodeActivity_DownloadAndValidate_ExecuteCode(object sender, EventArgs e) { try { PackageDescription packageDescription = GetPackageDescription(); string packageServerSource = PackageSystemServices.GetPackageSourceNameByPackageId(packageDescription.Id, InstallationInformationFacade.InstallationId, UserSettings.CultureInfo); System.IO.Stream installFileStream = PackageServerFacade.GetInstallFileStream(packageDescription.PackageFileDownloadUrl); PackageManagerInstallProcess packageManagerInstallProcess = PackageManager.Install(installFileStream, false, packageServerSource); this.Bindings.Add("PackageManagerInstallProcess", packageManagerInstallProcess); this.Bindings.Add("FlushOnCompletion", packageManagerInstallProcess.FlushOnCompletion); this.Bindings.Add("ReloadConsoleOnCompletion", packageManagerInstallProcess.ReloadConsoleOnCompletion); if (packageManagerInstallProcess.PreInstallValidationResult.Count > 0) { this.UpdateBinding("Errors", WorkflowHelper.ValidationResultToBinding(packageManagerInstallProcess.PreInstallValidationResult)); } else { List<PackageFragmentValidationResult> validationResult = packageManagerInstallProcess.Validate(); if (validationResult.Count > 0) { this.UpdateBinding("LayoutLabel", StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallRemotePackage.ShowWarning.LayoutLabel")); this.UpdateBinding("TableCaption", StringResourceSystemFacade.GetString("Composite.Plugins.PackageElementProvider", "InstallRemotePackage.ShowWarning.InfoTableCaption")); this.UpdateBinding("Errors", WorkflowHelper.ValidationResultToBinding(validationResult)); } else { this.UpdateBinding("Uninstallable", packageManagerInstallProcess.CanBeUninstalled == false); } } } catch (Exception ex) { this.UpdateBinding("Errors", new List<List<string>> { new List<string> { ex.Message, "" } }); } } private void showErrorCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { List<string> rowHeader = new List<string>(); rowHeader.Add(StringResourceSystemFacade.ParseString("${Composite.Plugins.PackageElementProvider, InstallRemotePackage.ShowError.MessageTitle}")); this.UpdateBinding("ErrorHeader", rowHeader); } private void step4CodeActivity_Install_ExecuteCode(object sender, EventArgs e) { PackageDescription packageDescription = GetPackageDescription(); PackageManagerInstallProcess packageManagerInstallProcess = this.GetBinding<PackageManagerInstallProcess>("PackageManagerInstallProcess"); bool installOk = false; string packageServerUrl = null; Exception exception = null; try { packageServerUrl = PackageSystemServices.GetPackageSourceNameByPackageId(packageDescription.Id, InstallationInformationFacade.InstallationId, UserSettings.CultureInfo); List<PackageFragmentValidationResult> installResult = packageManagerInstallProcess.Install(); if (installResult.Count > 0) { this.UpdateBinding("Errors", WorkflowHelper.ValidationResultToBinding(installResult)); } else { installOk = true; } } catch (Exception ex) { exception = ex; this.UpdateBinding("Errors", new List<List<string>> { new List<string> { ex.Message, "" } }); } try { if (installOk) { PackageServerFacade.RegisterPackageInstallationCompletion(packageServerUrl, InstallationInformationFacade.InstallationId, packageDescription.Id, UserSettings.Username, UserSettings.UserIPAddress.ToString()); } else { StringBuilder sb = new StringBuilder(); if (exception != null) { sb.Append(exception.ToString()); } else { List<List<string>> errors = this.GetBinding<List<List<string>>>("Errors"); foreach (List<string> list in errors) { sb.AppendLine(list[0]); } } PackageServerFacade.RegisterPackageInstallationFailure(packageServerUrl, InstallationInformationFacade.InstallationId, packageDescription.Id, UserSettings.Username, UserSettings.UserIPAddress.ToString(), sb.ToString()); } } catch (Exception ex) { LoggingService.LogWarning("InstallRemotePackageWorkflow", ex); } } private void cleanupCodeActivity_Cleanup_ExecuteCode(object sender, EventArgs e) { PackageManagerInstallProcess packageManagerInstallProcess; if (this.TryGetBinding<PackageManagerInstallProcess>("PackageManagerInstallProcess", out packageManagerInstallProcess)) { packageManagerInstallProcess.CancelInstallation(); } } private void step5CodeActivity_RefreshTree_ExecuteCode(object sender, EventArgs e) { if (this.GetBinding<bool>("ReloadConsoleOnCompletion")) { ConsoleMessageQueueFacade.Enqueue(new RebootConsoleMessageQueueItem(), null); } if (this.GetBinding<bool>("FlushOnCompletion")) { GlobalEventSystemFacade.FlushTheSystem(); } SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(new PackageElementProviderRootEntityToken()); if (this.GetBinding<bool>("ReloadConsoleOnCompletion") == false) { PackageElementProviderAvailablePackagesItemEntityToken castedEntityToken = (PackageElementProviderAvailablePackagesItemEntityToken)this.EntityToken; InstalledPackageInformation installedPackage = PackageManager.GetInstalledPackages().FirstOrDefault(f => f.Id == castedEntityToken.PackageId); var installedPackageEntityToken = new PackageElementProviderInstalledPackageItemEntityToken( installedPackage.Id, installedPackage.GroupName, installedPackage.IsLocalInstalled, installedPackage.CanBeUninstalled); ExecuteWorklow(installedPackageEntityToken, WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PackageElementProvider.ViewInstalledPackageInfoWorkflow")); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/InstallRemotePackageWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { partial class InstallRemotePackageWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition3 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition4 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition5 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition6 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity19 = new System.Workflow.Activities.SetStateActivity(); this.showFieldMessageActivity1 = new Composite.C1Console.Workflow.Activities.ShowFieldMessageActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity17 = new System.Workflow.Activities.SetStateActivity(); this.step2WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity18 = new System.Workflow.Activities.SetStateActivity(); this.initializeIfElseActivity_IsAddOnFree = new System.Workflow.Activities.IfElseActivity(); this.ifElseBranchActivity6 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity5 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity12 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity11 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity8 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity7 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity10 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity9 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity12 = new System.Workflow.Activities.SetStateActivity(); this.cleanupCodeActivity_Cleanup = new System.Workflow.Activities.CodeActivity(); this.setStateActivity11 = new System.Workflow.Activities.SetStateActivity(); this.step5CodeActivity_RefreshTree = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step5WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity16 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity5 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step4IfElseActivity_DidValidate = new System.Workflow.Activities.IfElseActivity(); this.step4CodeActivity_Install = new System.Workflow.Activities.CodeActivity(); this.nextHandleExternalEventActivity4 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.step4WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.showErrorWizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.showErrorCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity15 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity4 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step3IfElseActivity_DidValidate = new System.Workflow.Activities.IfElseActivity(); this.step3CodeActivity_DownloadAndValidate = new System.Workflow.Activities.CodeActivity(); this.nextHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.step3WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity14 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity2 = new System.Workflow.Activities.IfElseActivity(); this.nextHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.step2StateStepcodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity13 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.nextHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.step1WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.initializeIfElseActivity_DidValidate = new System.Workflow.Activities.IfElseActivity(); this.initializeStateCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.cleanupStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step5EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step5StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step4EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step4EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step4StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.showErrorEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.showErrorStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step3EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step3EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step3StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step2EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step2EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step2StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.cleanupStateActivity = new System.Workflow.Activities.StateActivity(); this.step5StateActivity = new System.Workflow.Activities.StateActivity(); this.step4StateActivity = new System.Workflow.Activities.StateActivity(); this.showErrorStateActivity = new System.Workflow.Activities.StateActivity(); this.step3StateActivity = new System.Workflow.Activities.StateActivity(); this.step2StateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "step1StateActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step2StateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity3); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity2); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsPackageFree); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "showErrorStateActivity"; // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "step5StateActivity"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "showErrorStateActivity"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "step4StateActivity"; // // setStateActivity19 // this.setStateActivity19.Name = "setStateActivity19"; this.setStateActivity19.TargetStateName = "step2StateActivity"; // // showFieldMessageActivity1 // this.showFieldMessageActivity1.FieldBindingPath = "EulaAccepted"; this.showFieldMessageActivity1.Message = "${Composite.Plugins.PackageElementProvider, InstallRemotePackage.Step2.AcceptMissin" + "g}"; this.showFieldMessageActivity1.Name = "showFieldMessageActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "step3StateActivity"; // // setStateActivity17 // this.setStateActivity17.Name = "setStateActivity17"; this.setStateActivity17.TargetStateName = "showErrorStateActivity"; // // step2WizardFormActivity // this.step2WizardFormActivity.ContainerLabel = null; this.step2WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallRemotePackageStep2.xml"; this.step2WizardFormActivity.Name = "step2WizardFormActivity"; // // setStateActivity18 // this.setStateActivity18.Name = "setStateActivity18"; this.setStateActivity18.TargetStateName = "showErrorStateActivity"; // // initializeIfElseActivity_IsAddOnFree // this.initializeIfElseActivity_IsAddOnFree.Activities.Add(this.ifElseBranchActivity1); this.initializeIfElseActivity_IsAddOnFree.Activities.Add(this.ifElseBranchActivity2); this.initializeIfElseActivity_IsAddOnFree.Name = "initializeIfElseActivity_IsAddOnFree"; // // ifElseBranchActivity6 // this.ifElseBranchActivity6.Activities.Add(this.setStateActivity10); this.ifElseBranchActivity6.Name = "ifElseBranchActivity6"; // // ifElseBranchActivity5 // this.ifElseBranchActivity5.Activities.Add(this.setStateActivity9); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DidValidate); this.ifElseBranchActivity5.Condition = codecondition2; this.ifElseBranchActivity5.Name = "ifElseBranchActivity5"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity7); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.setStateActivity6); codecondition3.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DidValidate); this.ifElseBranchActivity3.Condition = codecondition3; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // ifElseBranchActivity12 // this.ifElseBranchActivity12.Activities.Add(this.showFieldMessageActivity1); this.ifElseBranchActivity12.Activities.Add(this.setStateActivity19); this.ifElseBranchActivity12.Name = "ifElseBranchActivity12"; // // ifElseBranchActivity11 // this.ifElseBranchActivity11.Activities.Add(this.setStateActivity5); codecondition4.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.EulaAccepted); this.ifElseBranchActivity11.Condition = codecondition4; this.ifElseBranchActivity11.Name = "ifElseBranchActivity11"; // // ifElseBranchActivity8 // this.ifElseBranchActivity8.Activities.Add(this.setStateActivity17); this.ifElseBranchActivity8.Name = "ifElseBranchActivity8"; // // ifElseBranchActivity7 // this.ifElseBranchActivity7.Activities.Add(this.step2WizardFormActivity); codecondition5.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DidValidate); this.ifElseBranchActivity7.Condition = codecondition5; this.ifElseBranchActivity7.Name = "ifElseBranchActivity7"; // // ifElseBranchActivity10 // this.ifElseBranchActivity10.Activities.Add(this.setStateActivity18); this.ifElseBranchActivity10.Name = "ifElseBranchActivity10"; // // ifElseBranchActivity9 // this.ifElseBranchActivity9.Activities.Add(this.initializeIfElseActivity_IsAddOnFree); codecondition6.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DidValidate); this.ifElseBranchActivity9.Condition = codecondition6; this.ifElseBranchActivity9.Name = "ifElseBranchActivity9"; // // setStateActivity12 // this.setStateActivity12.Name = "setStateActivity12"; this.setStateActivity12.TargetStateName = "finalStateActivity"; // // cleanupCodeActivity_Cleanup // this.cleanupCodeActivity_Cleanup.Name = "cleanupCodeActivity_Cleanup"; this.cleanupCodeActivity_Cleanup.ExecuteCode += new System.EventHandler(this.cleanupCodeActivity_Cleanup_ExecuteCode); // // setStateActivity11 // this.setStateActivity11.Name = "setStateActivity11"; this.setStateActivity11.TargetStateName = "finalStateActivity"; // // step5CodeActivity_RefreshTree // this.step5CodeActivity_RefreshTree.Name = "step5CodeActivity_RefreshTree"; this.step5CodeActivity_RefreshTree.ExecuteCode += new System.EventHandler(this.step5CodeActivity_RefreshTree_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // step5WizardFormActivity // this.step5WizardFormActivity.ContainerLabel = null; this.step5WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallRemotePackageStep5.xml"; this.step5WizardFormActivity.Name = "step5WizardFormActivity"; // // setStateActivity16 // this.setStateActivity16.Name = "setStateActivity16"; this.setStateActivity16.TargetStateName = "cleanupStateActivity"; // // cancelHandleExternalEventActivity5 // this.cancelHandleExternalEventActivity5.EventName = "Cancel"; this.cancelHandleExternalEventActivity5.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity5.Name = "cancelHandleExternalEventActivity5"; // // step4IfElseActivity_DidValidate // this.step4IfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity5); this.step4IfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity6); this.step4IfElseActivity_DidValidate.Name = "step4IfElseActivity_DidValidate"; // // step4CodeActivity_Install // this.step4CodeActivity_Install.Name = "step4CodeActivity_Install"; this.step4CodeActivity_Install.ExecuteCode += new System.EventHandler(this.step4CodeActivity_Install_ExecuteCode); // // nextHandleExternalEventActivity4 // this.nextHandleExternalEventActivity4.EventName = "Next"; this.nextHandleExternalEventActivity4.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity4.Name = "nextHandleExternalEventActivity4"; // // step4WizardFormActivity // this.step4WizardFormActivity.ContainerLabel = null; this.step4WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallRemotePackageStep4.xml"; this.step4WizardFormActivity.Name = "step4WizardFormActivity"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "finalStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // showErrorWizardFormActivity // this.showErrorWizardFormActivity.ContainerLabel = null; this.showErrorWizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallRemotePackageShowError.xml"; this.showErrorWizardFormActivity.Name = "showErrorWizardFormActivity"; // // showErrorCodeActivity_Initialize // this.showErrorCodeActivity_Initialize.Name = "showErrorCodeActivity_Initialize"; this.showErrorCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.showErrorCodeActivity_Initialize_ExecuteCode); // // setStateActivity15 // this.setStateActivity15.Name = "setStateActivity15"; this.setStateActivity15.TargetStateName = "cleanupStateActivity"; // // cancelHandleExternalEventActivity4 // this.cancelHandleExternalEventActivity4.EventName = "Cancel"; this.cancelHandleExternalEventActivity4.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity4.Name = "cancelHandleExternalEventActivity4"; // // step3IfElseActivity_DidValidate // this.step3IfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity3); this.step3IfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity4); this.step3IfElseActivity_DidValidate.Name = "step3IfElseActivity_DidValidate"; // // step3CodeActivity_DownloadAndValidate // this.step3CodeActivity_DownloadAndValidate.Name = "step3CodeActivity_DownloadAndValidate"; this.step3CodeActivity_DownloadAndValidate.ExecuteCode += new System.EventHandler(this.step3CodeActivity_DownloadAndValidate_ExecuteCode); // // nextHandleExternalEventActivity3 // this.nextHandleExternalEventActivity3.EventName = "Next"; this.nextHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity3.Name = "nextHandleExternalEventActivity3"; // // step3WizardFormActivity // this.step3WizardFormActivity.ContainerLabel = null; this.step3WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallRemotePackageStep3.xml"; this.step3WizardFormActivity.Name = "step3WizardFormActivity"; // // setStateActivity14 // this.setStateActivity14.Name = "setStateActivity14"; this.setStateActivity14.TargetStateName = "cleanupStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // ifElseActivity2 // this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity11); this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity12); this.ifElseActivity2.Name = "ifElseActivity2"; // // nextHandleExternalEventActivity2 // this.nextHandleExternalEventActivity2.EventName = "Next"; this.nextHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity2.Name = "nextHandleExternalEventActivity2"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity7); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity8); this.ifElseActivity1.Name = "ifElseActivity1"; // // step2StateStepcodeActivity_Initialize // this.step2StateStepcodeActivity_Initialize.Name = "step2StateStepcodeActivity_Initialize"; this.step2StateStepcodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.step2StateStepcodeActivity_Initialize_ExecuteCode); // // setStateActivity13 // this.setStateActivity13.Name = "setStateActivity13"; this.setStateActivity13.TargetStateName = "cleanupStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "step2StateActivity"; // // nextHandleExternalEventActivity1 // this.nextHandleExternalEventActivity1.EventName = "Next"; this.nextHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity1.Name = "nextHandleExternalEventActivity1"; // // step1WizardFormActivity // this.step1WizardFormActivity.ContainerLabel = null; this.step1WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderInstallRemotePackageStep1.xml"; this.step1WizardFormActivity.Name = "step1WizardFormActivity"; // // initializeIfElseActivity_DidValidate // this.initializeIfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity9); this.initializeIfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity10); this.initializeIfElseActivity_DidValidate.Name = "initializeIfElseActivity_DidValidate"; // // initializeStateCodeActivity_Initialize // this.initializeStateCodeActivity_Initialize.Name = "initializeStateCodeActivity_Initialize"; this.initializeStateCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeStateCodeActivity_Initialize_ExecuteCode); // // cleanupStateInitializationActivity // this.cleanupStateInitializationActivity.Activities.Add(this.cleanupCodeActivity_Cleanup); this.cleanupStateInitializationActivity.Activities.Add(this.setStateActivity12); this.cleanupStateInitializationActivity.Name = "cleanupStateInitializationActivity"; // // step5EventDrivenActivity_Finish // this.step5EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.step5EventDrivenActivity_Finish.Activities.Add(this.closeCurrentViewActivity1); this.step5EventDrivenActivity_Finish.Activities.Add(this.step5CodeActivity_RefreshTree); this.step5EventDrivenActivity_Finish.Activities.Add(this.setStateActivity11); this.step5EventDrivenActivity_Finish.Name = "step5EventDrivenActivity_Finish"; // // step5StateInitializationActivity // this.step5StateInitializationActivity.Activities.Add(this.step5WizardFormActivity); this.step5StateInitializationActivity.Name = "step5StateInitializationActivity"; // // step4EventDrivenActivity_Cancel // this.step4EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity5); this.step4EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity16); this.step4EventDrivenActivity_Cancel.Name = "step4EventDrivenActivity_Cancel"; // // step4EventDrivenActivity_Next // this.step4EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity4); this.step4EventDrivenActivity_Next.Activities.Add(this.step4CodeActivity_Install); this.step4EventDrivenActivity_Next.Activities.Add(this.step4IfElseActivity_DidValidate); this.step4EventDrivenActivity_Next.Name = "step4EventDrivenActivity_Next"; // // step4StateInitializationActivity // this.step4StateInitializationActivity.Activities.Add(this.step4WizardFormActivity); this.step4StateInitializationActivity.Name = "step4StateInitializationActivity"; // // showErrorEventDrivenActivity_Finish // this.showErrorEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.showErrorEventDrivenActivity_Finish.Activities.Add(this.setStateActivity8); this.showErrorEventDrivenActivity_Finish.Name = "showErrorEventDrivenActivity_Finish"; // // showErrorStateInitializationActivity // this.showErrorStateInitializationActivity.Activities.Add(this.showErrorCodeActivity_Initialize); this.showErrorStateInitializationActivity.Activities.Add(this.showErrorWizardFormActivity); this.showErrorStateInitializationActivity.Name = "showErrorStateInitializationActivity"; // // step3EventDrivenActivity_Cancel // this.step3EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity4); this.step3EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity15); this.step3EventDrivenActivity_Cancel.Name = "step3EventDrivenActivity_Cancel"; // // step3EventDrivenActivity_Next // this.step3EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity3); this.step3EventDrivenActivity_Next.Activities.Add(this.step3CodeActivity_DownloadAndValidate); this.step3EventDrivenActivity_Next.Activities.Add(this.step3IfElseActivity_DidValidate); this.step3EventDrivenActivity_Next.Name = "step3EventDrivenActivity_Next"; // // step3StateInitializationActivity // this.step3StateInitializationActivity.Activities.Add(this.step3WizardFormActivity); this.step3StateInitializationActivity.Name = "step3StateInitializationActivity"; // // step2EventDrivenActivity_Cancel // this.step2EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.step2EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity14); this.step2EventDrivenActivity_Cancel.Name = "step2EventDrivenActivity_Cancel"; // // step2EventDrivenActivity_Next // this.step2EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity2); this.step2EventDrivenActivity_Next.Activities.Add(this.ifElseActivity2); this.step2EventDrivenActivity_Next.Name = "step2EventDrivenActivity_Next"; // // step2StateInitializationActivity // this.step2StateInitializationActivity.Activities.Add(this.step2StateStepcodeActivity_Initialize); this.step2StateInitializationActivity.Activities.Add(this.ifElseActivity1); this.step2StateInitializationActivity.Name = "step2StateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity13); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Next // this.step1EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity1); this.step1EventDrivenActivity_Next.Activities.Add(this.setStateActivity4); this.step1EventDrivenActivity_Next.Name = "step1EventDrivenActivity_Next"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1WizardFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeStateCodeActivity_Initialize); this.initializeStateInitializationActivity.Activities.Add(this.initializeIfElseActivity_DidValidate); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "cleanupStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // cleanupStateActivity // this.cleanupStateActivity.Activities.Add(this.cleanupStateInitializationActivity); this.cleanupStateActivity.Name = "cleanupStateActivity"; // // step5StateActivity // this.step5StateActivity.Activities.Add(this.step5StateInitializationActivity); this.step5StateActivity.Activities.Add(this.step5EventDrivenActivity_Finish); this.step5StateActivity.Name = "step5StateActivity"; // // step4StateActivity // this.step4StateActivity.Activities.Add(this.step4StateInitializationActivity); this.step4StateActivity.Activities.Add(this.step4EventDrivenActivity_Next); this.step4StateActivity.Activities.Add(this.step4EventDrivenActivity_Cancel); this.step4StateActivity.Name = "step4StateActivity"; // // showErrorStateActivity // this.showErrorStateActivity.Activities.Add(this.showErrorStateInitializationActivity); this.showErrorStateActivity.Activities.Add(this.showErrorEventDrivenActivity_Finish); this.showErrorStateActivity.Name = "showErrorStateActivity"; // // step3StateActivity // this.step3StateActivity.Activities.Add(this.step3StateInitializationActivity); this.step3StateActivity.Activities.Add(this.step3EventDrivenActivity_Next); this.step3StateActivity.Activities.Add(this.step3EventDrivenActivity_Cancel); this.step3StateActivity.Name = "step3StateActivity"; // // step2StateActivity // this.step2StateActivity.Activities.Add(this.step2StateInitializationActivity); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Next); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Cancel); this.step2StateActivity.Name = "step2StateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Next); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // InstallRemotePackageWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.step2StateActivity); this.Activities.Add(this.step3StateActivity); this.Activities.Add(this.showErrorStateActivity); this.Activities.Add(this.step4StateActivity); this.Activities.Add(this.step5StateActivity); this.Activities.Add(this.cleanupStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "InstallRemotePackageWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private CodeActivity initializeStateCodeActivity_Initialize; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity initializeIfElseActivity_IsAddOnFree; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.WizardFormActivity step1WizardFormActivity; private StateInitializationActivity step2StateInitializationActivity; private StateInitializationActivity step1StateInitializationActivity; private StateActivity step2StateActivity; private StateActivity step1StateActivity; private C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity2; private C1Console.Workflow.Activities.WizardFormActivity step2WizardFormActivity; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity1; private EventDrivenActivity step2EventDrivenActivity_Next; private EventDrivenActivity step1EventDrivenActivity_Next; private CodeActivity step2StateStepcodeActivity_Initialize; private StateActivity showErrorStateActivity; private StateActivity step3StateActivity; private C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity3; private C1Console.Workflow.Activities.WizardFormActivity step3WizardFormActivity; private SetStateActivity setStateActivity5; private EventDrivenActivity step3EventDrivenActivity_Next; private StateInitializationActivity step3StateInitializationActivity; private CodeActivity step3CodeActivity_DownloadAndValidate; private SetStateActivity setStateActivity7; private SetStateActivity setStateActivity6; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity step3IfElseActivity_DidValidate; private StateActivity step4StateActivity; private C1Console.Workflow.Activities.WizardFormActivity step4WizardFormActivity; private StateInitializationActivity step4StateInitializationActivity; private C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity4; private EventDrivenActivity step4EventDrivenActivity_Next; private C1Console.Workflow.Activities.WizardFormActivity showErrorWizardFormActivity; private StateInitializationActivity showErrorStateInitializationActivity; private CodeActivity showErrorCodeActivity_Initialize; private CodeActivity step4CodeActivity_Install; private SetStateActivity setStateActivity10; private SetStateActivity setStateActivity9; private IfElseBranchActivity ifElseBranchActivity6; private IfElseBranchActivity ifElseBranchActivity5; private SetStateActivity setStateActivity11; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private IfElseActivity step4IfElseActivity_DidValidate; private SetStateActivity setStateActivity8; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private EventDrivenActivity step5EventDrivenActivity_Finish; private StateInitializationActivity step5StateInitializationActivity; private EventDrivenActivity showErrorEventDrivenActivity_Finish; private StateActivity step5StateActivity; private C1Console.Workflow.Activities.WizardFormActivity step5WizardFormActivity; private CodeActivity step5CodeActivity_RefreshTree; private SetStateActivity setStateActivity12; private CodeActivity cleanupCodeActivity_Cleanup; private StateInitializationActivity cleanupStateInitializationActivity; private StateActivity cleanupStateActivity; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private SetStateActivity setStateActivity14; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private SetStateActivity setStateActivity13; private EventDrivenActivity step3EventDrivenActivity_Cancel; private EventDrivenActivity step2EventDrivenActivity_Cancel; private SetStateActivity setStateActivity16; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity5; private SetStateActivity setStateActivity15; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity4; private EventDrivenActivity step4EventDrivenActivity_Cancel; private SetStateActivity setStateActivity17; private IfElseBranchActivity ifElseBranchActivity8; private IfElseBranchActivity ifElseBranchActivity7; private IfElseActivity ifElseActivity1; private SetStateActivity setStateActivity18; private IfElseBranchActivity ifElseBranchActivity10; private IfElseBranchActivity ifElseBranchActivity9; private IfElseActivity initializeIfElseActivity_DidValidate; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private IfElseBranchActivity ifElseBranchActivity12; private IfElseBranchActivity ifElseBranchActivity11; private IfElseActivity ifElseActivity2; private SetStateActivity setStateActivity19; private C1Console.Workflow.Activities.ShowFieldMessageActivity showFieldMessageActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/InstallRemotePackageWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1130; 1129" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="InstallRemotePackageWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="51; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="61; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="61; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="59; 101" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="612; 544" Location="67; 132"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeStateCodeActivity_Initialize" Size="130; 41" Location="308; 194" /> <IfElseDesigner Name="initializeIfElseActivity_DidValidate" Size="592; 403" Location="77; 254"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity9" Size="381; 303" Location="96; 325"> <IfElseBranchDesigner.Designers> <IfElseDesigner Name="initializeIfElseActivity_IsAddOnFree" Size="361; 222" Location="106; 387"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 122" Location="125; 458"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="135; 520" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 122" Location="298; 458"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="308; 520" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity10" Size="150; 303" Location="500; 325"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity18" Size="130; 53" Location="510; 472" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="961; 890" Name="finalStateActivity" /> <StateDesigner Size="211; 118" AutoSizeMargin="16; 24" Location="59; 293" Name="step1StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1StateInitializationActivity" Size="150; 122" Location="67; 324"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="step1WizardFormActivity" Size="130; 41" Location="77; 386" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Next" Size="150; 182" Location="67; 348"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="nextHandleExternalEventActivity1" Size="130; 41" Location="77; 410" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="77; 470" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Cancel" Size="150; 194" Location="67; 372"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="77; 434" /> <SetStateDesigner Name="setStateActivity13" Size="130; 53" Location="77; 494" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="211; 118" AutoSizeMargin="16; 24" AutoSize="False" Location="353; 296" Name="step2StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step2StateInitializationActivity" Size="381; 375" Location="404; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Name="step2StateStepcodeActivity_Initialize" Size="130; 41" Location="529; 210" /> <IfElseDesigner Name="ifElseActivity1" Size="361; 234" Location="414; 270"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity7" Size="150; 134" Location="433; 341"> <IfElseBranchDesigner.Designers> <ActivityDesigner Name="step2WizardFormActivity" Size="130; 41" Location="443; 409" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity8" Size="150; 134" Location="606; 341"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity17" Size="130; 53" Location="616; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step2EventDrivenActivity_Next" Size="381; 435" Location="396; 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="nextHandleExternalEventActivity2" Size="130; 41" Location="521; 221" /> <IfElseDesigner Name="ifElseActivity2" Size="361; 294" Location="406; 281"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity11" Size="150; 194" Location="425; 352"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="435; 450" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity12" Size="150; 194" Location="598; 352"> <IfElseBranchDesigner.Designers> <ActivityDesigner Name="showFieldMessageActivity1" Size="130; 41" Location="608; 414" /> <SetStateDesigner Name="setStateActivity19" Size="130; 53" Location="608; 474" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step2EventDrivenActivity_Cancel" Size="150; 194" Location="396; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity3" Size="130; 41" Location="406; 245" /> <SetStateDesigner Name="setStateActivity14" Size="130; 53" Location="406; 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="211; 118" AutoSizeMargin="16; 24" Location="657; 293" Name="step3StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step3StateInitializationActivity" Size="150; 122" Location="665; 324"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="step3WizardFormActivity" Size="130; 41" Location="675; 386" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step3EventDrivenActivity_Next" Size="381; 423" Location="665; 348"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="nextHandleExternalEventActivity3" Size="130; 41" Location="790; 410" /> <CodeDesigner Name="step3CodeActivity_DownloadAndValidate" Size="130; 41" Location="790; 470" /> <IfElseDesigner Name="step3IfElseActivity_DidValidate" Size="361; 222" Location="675; 530"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity3" Size="150; 122" Location="694; 601"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="704; 663" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity4" Size="150; 122" Location="867; 601"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity7" Size="130; 41" Location="877; 663" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step3EventDrivenActivity_Cancel" Size="150; 194" Location="665; 372"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity4" Size="130; 41" Location="675; 434" /> <SetStateDesigner Name="setStateActivity15" Size="130; 53" Location="675; 494" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="230; 94" AutoSizeMargin="16; 24" Location="308; 715" Name="showErrorStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="showErrorStateInitializationActivity" Size="150; 182" Location="316; 746"> <StateInitializationDesigner.Designers> <CodeDesigner Name="showErrorCodeActivity_Initialize" Size="130; 41" Location="326; 808" /> <ActivityDesigner Name="showErrorWizardFormActivity" Size="130; 41" Location="326; 868" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="showErrorEventDrivenActivity_Finish" Size="150; 182" Location="316; 770"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="326; 832" /> <SetStateDesigner Name="setStateActivity8" Size="130; 41" Location="326; 892" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="211; 118" AutoSizeMargin="16; 24" Location="83; 487" Name="step4StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step4StateInitializationActivity" Size="150; 122" Location="91; 518"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="step4WizardFormActivity" Size="130; 41" Location="101; 580" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step4EventDrivenActivity_Next" Size="381; 435" Location="91; 542"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="nextHandleExternalEventActivity4" Size="130; 41" Location="216; 604" /> <CodeDesigner Name="step4CodeActivity_Install" Size="130; 41" Location="216; 664" /> <IfElseDesigner Name="step4IfElseActivity_DidValidate" Size="361; 234" Location="101; 724"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity5" Size="150; 134" Location="120; 795"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity9" Size="130; 41" Location="130; 863" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity6" Size="150; 134" Location="293; 795"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity10" Size="130; 53" Location="303; 857" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step4EventDrivenActivity_Cancel" Size="150; 194" Location="91; 566"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity5" Size="130; 41" Location="101; 628" /> <SetStateDesigner Name="setStateActivity16" Size="130; 53" Location="101; 688" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="207; 94" AutoSizeMargin="16; 24" AutoSize="False" Location="619; 523" Name="step5StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step5StateInitializationActivity" Size="150; 122" Location="627; 554"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="step5WizardFormActivity" Size="130; 41" Location="637; 616" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step5EventDrivenActivity_Finish" Size="150; 314" Location="627; 578"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity2" Size="130; 41" Location="637; 640" /> <ActivityDesigner Name="closeCurrentViewActivity1" Size="130; 41" Location="637; 700" /> <CodeDesigner Name="step5CodeActivity_RefreshTree" Size="130; 41" Location="637; 760" /> <SetStateDesigner Name="setStateActivity11" Size="130; 53" Location="637; 820" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="209; 80" AutoSizeMargin="16; 24" Location="59; 1049" Name="cleanupStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="cleanupStateInitializationActivity" Size="150; 194" Location="67; 1080"> <StateInitializationDesigner.Designers> <CodeDesigner Name="cleanupCodeActivity_Cleanup" Size="130; 41" Location="77; 1142" /> <SetStateDesigner Name="setStateActivity12" Size="130; 53" Location="77; 1202" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="cleanupStateActivity" SetStateName="setStateActivity1" SourceActivity="InstallRemotePackageWorkflow" TargetConnectionIndex="0" SourceStateName="InstallRemotePackageWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="cleanupStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="240" Y="93" /> <ns0:Point X="304" Y="93" /> <ns0:Point X="304" Y="703" /> <ns0:Point X="163" Y="703" /> <ns0:Point X="163" Y="1049" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="showErrorStateActivity" SetStateName="setStateActivity18" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="showErrorStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="265" Y="142" /> <ns0:Point X="341" Y="142" /> <ns0:Point X="341" Y="688" /> <ns0:Point X="423" Y="688" /> <ns0:Point X="423" Y="715" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step2StateActivity" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step2StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="265" Y="142" /> <ns0:Point X="458" Y="142" /> <ns0:Point X="458" Y="296" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity3" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="265" Y="142" /> <ns0:Point X="276" Y="142" /> <ns0:Point X="276" Y="281" /> <ns0:Point X="164" Y="281" /> <ns0:Point X="164" Y="293" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step2StateActivity" SetStateName="setStateActivity4" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="step2StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="358" /> <ns0:Point X="282" Y="358" /> <ns0:Point X="282" Y="288" /> <ns0:Point X="458" Y="288" /> <ns0:Point X="458" Y="296" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="cleanupStateActivity" SetStateName="setStateActivity13" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="cleanupStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="266" Y="382" /> <ns0:Point X="275" Y="382" /> <ns0:Point X="275" Y="285" /> <ns0:Point X="51" Y="285" /> <ns0:Point X="51" Y="1037" /> <ns0:Point X="163" Y="1037" /> <ns0:Point X="163" Y="1049" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="showErrorStateActivity" SetStateName="setStateActivity17" SourceActivity="step2StateActivity" TargetConnectionIndex="0" SourceStateName="step2StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step2StateInitializationActivity" SourceConnectionIndex="0" TargetStateName="showErrorStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="547" Y="337" /> <ns0:Point X="575" Y="337" /> <ns0:Point X="575" Y="680" /> <ns0:Point X="423" Y="680" /> <ns0:Point X="423" Y="715" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step3StateActivity" SetStateName="setStateActivity5" SourceActivity="step2StateActivity" TargetConnectionIndex="0" SourceStateName="step2StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step2EventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="step3StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="550" Y="361" /> <ns0:Point X="576" Y="361" /> <ns0:Point X="576" Y="285" /> <ns0:Point X="762" Y="285" /> <ns0:Point X="762" Y="293" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step2StateActivity" SetStateName="setStateActivity19" SourceActivity="step2StateActivity" TargetConnectionIndex="0" SourceStateName="step2StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step2EventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="step2StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="585" Y="169" /> <ns0:Point X="605" Y="169" /> <ns0:Point X="605" Y="96" /> <ns0:Point X="493" Y="96" /> <ns0:Point X="493" Y="104" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="cleanupStateActivity" SetStateName="setStateActivity14" SourceActivity="step2StateActivity" TargetConnectionIndex="0" SourceStateName="step2StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step2EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="cleanupStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="560" Y="385" /> <ns0:Point X="571" Y="385" /> <ns0:Point X="571" Y="1037" /> <ns0:Point X="163" Y="1037" /> <ns0:Point X="163" Y="1049" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step4StateActivity" SetStateName="setStateActivity6" SourceActivity="step3StateActivity" TargetConnectionIndex="0" SourceStateName="step3StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step3EventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="step4StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="854" Y="358" /> <ns0:Point X="876" Y="358" /> <ns0:Point X="876" Y="475" /> <ns0:Point X="188" Y="475" /> <ns0:Point X="188" Y="487" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="showErrorStateActivity" SetStateName="setStateActivity7" SourceActivity="step3StateActivity" TargetConnectionIndex="0" SourceStateName="step3StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step3EventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="showErrorStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="854" Y="358" /> <ns0:Point X="879" Y="358" /> <ns0:Point X="879" Y="702" /> <ns0:Point X="430" Y="702" /> <ns0:Point X="430" Y="715" /> <ns0:Point X="423" Y="715" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="cleanupStateActivity" SetStateName="setStateActivity15" SourceActivity="step3StateActivity" TargetConnectionIndex="0" SourceStateName="step3StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step3EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="cleanupStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="864" Y="382" /> <ns0:Point X="875" Y="382" /> <ns0:Point X="875" Y="1037" /> <ns0:Point X="163" Y="1037" /> <ns0:Point X="163" Y="1049" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity8" SourceActivity="showErrorStateActivity" TargetConnectionIndex="0" SourceStateName="showErrorStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="showErrorEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="534" Y="780" /> <ns0:Point X="1041" Y="780" /> <ns0:Point X="1041" Y="890" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step5StateActivity" SetStateName="setStateActivity9" SourceActivity="step4StateActivity" TargetConnectionIndex="0" SourceStateName="step4StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step4EventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="step5StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="280" Y="552" /> <ns0:Point X="306" Y="552" /> <ns0:Point X="306" Y="515" /> <ns0:Point X="722" Y="515" /> <ns0:Point X="722" Y="523" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="showErrorStateActivity" SetStateName="setStateActivity10" SourceActivity="step4StateActivity" TargetConnectionIndex="0" SourceStateName="step4StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step4EventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="showErrorStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="280" Y="552" /> <ns0:Point X="423" Y="552" /> <ns0:Point X="423" Y="715" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="cleanupStateActivity" SetStateName="setStateActivity16" SourceActivity="step4StateActivity" TargetConnectionIndex="0" SourceStateName="step4StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step4EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="cleanupStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="290" Y="576" /> <ns0:Point X="299" Y="576" /> <ns0:Point X="299" Y="477" /> <ns0:Point X="51" Y="477" /> <ns0:Point X="51" Y="1037" /> <ns0:Point X="163" Y="1037" /> <ns0:Point X="163" Y="1049" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity11" SourceActivity="step5StateActivity" TargetConnectionIndex="0" SourceStateName="step5StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step5EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="822" Y="588" /> <ns0:Point X="1041" Y="588" /> <ns0:Point X="1041" Y="890" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity12" SourceActivity="cleanupStateActivity" TargetConnectionIndex="0" SourceStateName="cleanupStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="cleanupStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="264" Y="1090" /> <ns0:Point X="280" Y="1090" /> <ns0:Point X="280" Y="882" /> <ns0:Point X="1041" Y="882" /> <ns0:Point X="1041" Y="890" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/UninstallLocalPackageWorkflow.cs ================================================ using System; using System.Collections.Generic; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Core.ResourceSystem; using Composite.Plugins.Elements.ElementProviders.PackageElementProvider; using Composite.C1Console.Workflow; namespace Composite.Core.PackageSystem.Workflow { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class UninstallLocalPackageWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public UninstallLocalPackageWorkflow() { InitializeComponent(); } private void DidValidate(object sender, System.Workflow.Activities.ConditionalEventArgs e) { e.Result = this.BindingExist("Errors") == false; } private void step2CodeActivity_Validate_ExecuteCode(object sender, EventArgs e) { PackageElementProviderInstalledPackageItemEntityToken castedEntityToken = (PackageElementProviderInstalledPackageItemEntityToken)this.EntityToken; PackageManagerUninstallProcess packageManagerUninstallProcess = PackageManager.Uninstall(castedEntityToken.PackageId); this.Bindings.Add("PackageManagerUninstallProcess", packageManagerUninstallProcess); this.Bindings.Add("FlushOnCompletion", packageManagerUninstallProcess.FlushOnCompletion); this.Bindings.Add("ReloadConsoleOnCompletion", packageManagerUninstallProcess.ReloadConsoleOnCompletion); if (packageManagerUninstallProcess.PreUninstallValidationResult.Count > 0) { this.UpdateBinding("Errors", WorkflowHelper.ValidationResultToBinding(packageManagerUninstallProcess.PreUninstallValidationResult)); } else { List<PackageFragmentValidationResult> validationResult = packageManagerUninstallProcess.Validate(); if (validationResult.Count > 0) { this.UpdateBinding("Errors", WorkflowHelper.ValidationResultToBinding(validationResult)); } } } private void step2CodeActivity_Uninstall_ExecuteCode(object sender, EventArgs e) { PackageManagerUninstallProcess packageManagerUninstallProcess = this.GetBinding<PackageManagerUninstallProcess>("PackageManagerUninstallProcess"); List<PackageFragmentValidationResult> uninstallResult = packageManagerUninstallProcess.Uninstall(); if (uninstallResult.Count > 0) { this.UpdateBinding("Errors", WorkflowHelper.ValidationResultToBinding(uninstallResult)); } } private void step3CodeActivity_RefreshTree_ExecuteCode(object sender, EventArgs e) { if (this.GetBinding<bool>("ReloadConsoleOnCompletion")) { ConsoleMessageQueueFacade.Enqueue(new RebootConsoleMessageQueueItem(), null); } if (this.GetBinding<bool>("FlushOnCompletion")) { GlobalEventSystemFacade.FlushTheSystem(); } SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(new PackageElementProviderRootEntityToken()); } private void showErrorCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { List<string> rowHeader = new List<string>(); rowHeader.Add(StringResourceSystemFacade.ParseString("${Composite.Plugins.PackageElementProvider, UninstallLocalPackage.ShowError.MessageTitle}")); this.UpdateBinding("ErrorHeader", rowHeader); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/UninstallLocalPackageWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Core.PackageSystem.Workflow { partial class UninstallLocalPackageWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.step2WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.ifElseBranchActivity6 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity5 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.step3CodeActivity_RefreshTree = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step3WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.showErrorWizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.showErrorCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step2IfElseActivity_DidValidate = new System.Workflow.Activities.IfElseActivity(); this.step2CodeActivity_Uninstall = new System.Workflow.Activities.CodeActivity(); this.nextHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.step2IfElseActivity_DidValidate_Old = new System.Workflow.Activities.IfElseActivity(); this.step2CodeActivity_Validate = new System.Workflow.Activities.CodeActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.nextHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.step1WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.step3EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step3StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.showErrorEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.showErrorStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step2EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step2EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step2StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step3StateActivity = new System.Workflow.Activities.StateActivity(); this.showErrorStateActivity = new System.Workflow.Activities.StateActivity(); this.step2StateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "showErrorStateActivity"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "step3StateActivity"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "showErrorStateActivity"; // // step2WizardFormActivity // this.step2WizardFormActivity.ContainerLabel = null; this.step2WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderUninstallLocalPackageStep2.xml"; this.step2WizardFormActivity.Name = "step2WizardFormActivity"; // // ifElseBranchActivity6 // this.ifElseBranchActivity6.Activities.Add(this.setStateActivity9); this.ifElseBranchActivity6.Name = "ifElseBranchActivity6"; // // ifElseBranchActivity5 // this.ifElseBranchActivity5.Activities.Add(this.setStateActivity6); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DidValidate); this.ifElseBranchActivity5.Condition = codecondition1; this.ifElseBranchActivity5.Name = "ifElseBranchActivity5"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity4); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.step2WizardFormActivity); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DidValidate); this.ifElseBranchActivity1.Condition = codecondition2; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "finalStateActivity"; // // step3CodeActivity_RefreshTree // this.step3CodeActivity_RefreshTree.Name = "step3CodeActivity_RefreshTree"; this.step3CodeActivity_RefreshTree.ExecuteCode += new System.EventHandler(this.step3CodeActivity_RefreshTree_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // step3WizardFormActivity // this.step3WizardFormActivity.ContainerLabel = null; this.step3WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderUninstallLocalPackageStep3.xml"; this.step3WizardFormActivity.Name = "step3WizardFormActivity"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // showErrorWizardFormActivity // this.showErrorWizardFormActivity.ContainerLabel = null; this.showErrorWizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderUninstallLocalPackageShowError.xml"; this.showErrorWizardFormActivity.Name = "showErrorWizardFormActivity"; // // showErrorCodeActivity_Initialize // this.showErrorCodeActivity_Initialize.Name = "showErrorCodeActivity_Initialize"; this.showErrorCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.showErrorCodeActivity_Initialize_ExecuteCode); // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // step2IfElseActivity_DidValidate // this.step2IfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity5); this.step2IfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity6); this.step2IfElseActivity_DidValidate.Name = "step2IfElseActivity_DidValidate"; // // step2CodeActivity_Uninstall // this.step2CodeActivity_Uninstall.Name = "step2CodeActivity_Uninstall"; this.step2CodeActivity_Uninstall.ExecuteCode += new System.EventHandler(this.step2CodeActivity_Uninstall_ExecuteCode); // // nextHandleExternalEventActivity2 // this.nextHandleExternalEventActivity2.EventName = "Next"; this.nextHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity2.Name = "nextHandleExternalEventActivity2"; // // step2IfElseActivity_DidValidate_Old // this.step2IfElseActivity_DidValidate_Old.Activities.Add(this.ifElseBranchActivity1); this.step2IfElseActivity_DidValidate_Old.Activities.Add(this.ifElseBranchActivity2); this.step2IfElseActivity_DidValidate_Old.Name = "step2IfElseActivity_DidValidate_Old"; // // step2CodeActivity_Validate // this.step2CodeActivity_Validate.Name = "step2CodeActivity_Validate"; this.step2CodeActivity_Validate.ExecuteCode += new System.EventHandler(this.step2CodeActivity_Validate_ExecuteCode); // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "step2StateActivity"; // // nextHandleExternalEventActivity1 // this.nextHandleExternalEventActivity1.EventName = "Next"; this.nextHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity1.Name = "nextHandleExternalEventActivity1"; // // step1WizardFormActivity // this.step1WizardFormActivity.ContainerLabel = null; this.step1WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderUninstallLocalPackageStep1.xml"; this.step1WizardFormActivity.Name = "step1WizardFormActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // step3EventDrivenActivity_Finish // this.step3EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.step3EventDrivenActivity_Finish.Activities.Add(this.closeCurrentViewActivity1); this.step3EventDrivenActivity_Finish.Activities.Add(this.step3CodeActivity_RefreshTree); this.step3EventDrivenActivity_Finish.Activities.Add(this.setStateActivity8); this.step3EventDrivenActivity_Finish.Name = "step3EventDrivenActivity_Finish"; // // step3StateInitializationActivity // this.step3StateInitializationActivity.Activities.Add(this.step3WizardFormActivity); this.step3StateInitializationActivity.Name = "step3StateInitializationActivity"; // // showErrorEventDrivenActivity_Finish // this.showErrorEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.showErrorEventDrivenActivity_Finish.Activities.Add(this.setStateActivity5); this.showErrorEventDrivenActivity_Finish.Name = "showErrorEventDrivenActivity_Finish"; // // showErrorStateInitializationActivity // this.showErrorStateInitializationActivity.Activities.Add(this.showErrorCodeActivity_Initialize); this.showErrorStateInitializationActivity.Activities.Add(this.showErrorWizardFormActivity); this.showErrorStateInitializationActivity.Name = "showErrorStateInitializationActivity"; // // step2EventDrivenActivity_Cancel // this.step2EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.step2EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity10); this.step2EventDrivenActivity_Cancel.Name = "step2EventDrivenActivity_Cancel"; // // step2EventDrivenActivity_Next // this.step2EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity2); this.step2EventDrivenActivity_Next.Activities.Add(this.step2CodeActivity_Uninstall); this.step2EventDrivenActivity_Next.Activities.Add(this.step2IfElseActivity_DidValidate); this.step2EventDrivenActivity_Next.Name = "step2EventDrivenActivity_Next"; // // step2StateInitializationActivity // this.step2StateInitializationActivity.Activities.Add(this.step2CodeActivity_Validate); this.step2StateInitializationActivity.Activities.Add(this.step2IfElseActivity_DidValidate_Old); this.step2StateInitializationActivity.Name = "step2StateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity7); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Next // this.step1EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity1); this.step1EventDrivenActivity_Next.Activities.Add(this.setStateActivity3); this.step1EventDrivenActivity_Next.Name = "step1EventDrivenActivity_Next"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1WizardFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // step3StateActivity // this.step3StateActivity.Activities.Add(this.step3StateInitializationActivity); this.step3StateActivity.Activities.Add(this.step3EventDrivenActivity_Finish); this.step3StateActivity.Name = "step3StateActivity"; // // showErrorStateActivity // this.showErrorStateActivity.Activities.Add(this.showErrorStateInitializationActivity); this.showErrorStateActivity.Activities.Add(this.showErrorEventDrivenActivity_Finish); this.showErrorStateActivity.Name = "showErrorStateActivity"; // // step2StateActivity // this.step2StateActivity.Activities.Add(this.step2StateInitializationActivity); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Next); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Cancel); this.step2StateActivity.Name = "step2StateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Next); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // UninstallLocalPackageWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.step2StateActivity); this.Activities.Add(this.showErrorStateActivity); this.Activities.Add(this.step3StateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "UninstallLocalPackageWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity2; private StateInitializationActivity step1StateInitializationActivity; private Composite.C1Console.Workflow.Activities.WizardFormActivity step1WizardFormActivity; private Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity1; private EventDrivenActivity step1EventDrivenActivity_Next; private StateActivity step2StateActivity; private CodeActivity step2CodeActivity_Validate; private SetStateActivity setStateActivity3; private StateInitializationActivity step2StateInitializationActivity; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.WizardFormActivity step2WizardFormActivity; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity step2IfElseActivity_DidValidate_Old; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private EventDrivenActivity showErrorEventDrivenActivity_Finish; private StateInitializationActivity showErrorStateInitializationActivity; private StateActivity showErrorStateActivity; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.WizardFormActivity showErrorWizardFormActivity; private Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity2; private EventDrivenActivity step2EventDrivenActivity_Next; private StateActivity step3StateActivity; private CodeActivity step2CodeActivity_Uninstall; private SetStateActivity setStateActivity6; private StateInitializationActivity step3StateInitializationActivity; private Composite.C1Console.Workflow.Activities.WizardFormActivity step3WizardFormActivity; private SetStateActivity setStateActivity8; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private EventDrivenActivity step3EventDrivenActivity_Finish; private CodeActivity step3CodeActivity_RefreshTree; private SetStateActivity setStateActivity9; private IfElseBranchActivity ifElseBranchActivity6; private IfElseBranchActivity ifElseBranchActivity5; private IfElseActivity step2IfElseActivity_DidValidate; private CodeActivity showErrorCodeActivity_Initialize; private EventDrivenActivity step1EventDrivenActivity_Cancel; private SetStateActivity setStateActivity10; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private SetStateActivity setStateActivity7; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step2EventDrivenActivity_Cancel; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/UninstallLocalPackageWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="UninstallLocalPackageWorkflow" Location="30; 30" Size="1146; 958" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="UninstallLocalPackageWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="UninstallLocalPackageWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="423" Y="179" /> <ns0:Point X="423" Y="286" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step2StateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="step2StateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="515" Y="351" /> <ns0:Point X="634" Y="351" /> <ns0:Point X="634" Y="424" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="525" Y="375" /> <ns0:Point X="1058" Y="375" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="showErrorStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="showErrorStateActivity" SourceActivity="step2StateActivity" EventHandlerName="step2StateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="723" Y="465" /> <ns0:Point X="741" Y="465" /> <ns0:Point X="741" Y="416" /> <ns0:Point X="277" Y="416" /> <ns0:Point X="277" Y="504" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step3StateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="step3StateActivity" SourceActivity="step2StateActivity" EventHandlerName="step2EventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="726" Y="489" /> <ns0:Point X="810" Y="489" /> <ns0:Point X="810" Y="576" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="showErrorStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity9" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="showErrorStateActivity" SourceActivity="step2StateActivity" EventHandlerName="step2EventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="726" Y="489" /> <ns0:Point X="741" Y="489" /> <ns0:Point X="741" Y="416" /> <ns0:Point X="277" Y="416" /> <ns0:Point X="277" Y="504" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity10" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step2StateActivity" EventHandlerName="step2EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="736" Y="513" /> <ns0:Point X="1058" Y="513" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="showErrorStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="showErrorStateActivity" EventHandlerName="showErrorEventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="388" Y="569" /> <ns0:Point X="464" Y="569" /> <ns0:Point X="464" Y="752" /> <ns0:Point X="1058" Y="752" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity8" SourceStateName="step3StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step3StateActivity" EventHandlerName="step3EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="910" Y="641" /> <ns0:Point X="1058" Y="641" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="108; 231" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="step1StateActivity" Location="318; 286" Size="211; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="326; 317"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step1WizardFormActivity" Location="336; 379" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Next" Location="326; 341"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="nextHandleExternalEventActivity1" Location="336; 403" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="336; 463" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="326; 365"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="336; 427" /> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="336; 487" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="step2StateActivity" Location="529; 424" Size="211; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 363" Name="step2StateInitializationActivity" Location="537; 455"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="step2CodeActivity_Validate" Location="662; 517" /> <IfElseDesigner Size="361; 222" Name="step2IfElseActivity_DidValidate_Old" Location="547; 577"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity1" Location="566; 648"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step2WizardFormActivity" Location="576; 710" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity2" Location="739; 648"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="749; 710" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="381; 423" Name="step2EventDrivenActivity_Next" Location="537; 479"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="nextHandleExternalEventActivity2" Location="662; 541" /> <CodeDesigner Size="130; 41" Name="step2CodeActivity_Uninstall" Location="662; 601" /> <IfElseDesigner Size="361; 222" Name="step2IfElseActivity_DidValidate" Location="547; 661"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity5" Location="566; 732"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="576; 794" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity6" Location="739; 732"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity9" Location="749; 794" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 194" Name="step2EventDrivenActivity_Cancel" Location="537; 503"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity3" Location="547; 565" /> <SetStateDesigner Size="130; 53" Name="setStateActivity10" Location="547; 625" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="showErrorStateActivity" Location="162; 504" Size="230; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="showErrorStateInitializationActivity" Location="170; 535"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="showErrorCodeActivity_Initialize" Location="180; 597" /> <ActivityDesigner Size="130; 41" Name="showErrorWizardFormActivity" Location="180; 657" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="showErrorEventDrivenActivity_Finish" Location="170; 559"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="180; 621" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="180; 681" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="step3StateActivity" Location="707; 576" Size="207; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step3StateInitializationActivity" Location="481; 135"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step3WizardFormActivity" Location="491; 197" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 302" Name="step3EventDrivenActivity_Finish" Location="489; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity2" Location="499; 210" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="499; 270" /> <CodeDesigner Size="130; 41" Name="step3CodeActivity_RefreshTree" Location="499; 330" /> <SetStateDesigner Size="130; 41" Name="setStateActivity8" Location="499; 390" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/UninstallRemotePackageWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.Core.Configuration; using Composite.Core.Logging; using Composite.Core.PackageSystem; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class UninstallRemotePackageWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public UninstallRemotePackageWorkflow() { InitializeComponent(); } private void DidValidate(object sender, ConditionalEventArgs e) { e.Result = this.BindingExist("Errors") == false; } private void DidUnregistre(object sender, ConditionalEventArgs e) { e.Result = this.BindingExist("UnregisterError") == false; } private void step2CodeActivity_Validate_ExecuteCode(object sender, EventArgs e) { PackageElementProviderInstalledPackageItemEntityToken castedEntityToken = (PackageElementProviderInstalledPackageItemEntityToken)this.EntityToken; PackageManagerUninstallProcess packageManagerUninstallProcess = PackageManager.Uninstall(castedEntityToken.PackageId); this.Bindings.Add("PackageManagerUninstallProcess", packageManagerUninstallProcess); this.Bindings.Add("FlushOnCompletion", packageManagerUninstallProcess.FlushOnCompletion); this.Bindings.Add("ReloadConsoleOnCompletion", packageManagerUninstallProcess.ReloadConsoleOnCompletion); if (packageManagerUninstallProcess.PreUninstallValidationResult.Count > 0) { this.UpdateBinding("Errors", WorkflowHelper.ValidationResultToBinding(packageManagerUninstallProcess.PreUninstallValidationResult)); } else { List<PackageFragmentValidationResult> validationResult = packageManagerUninstallProcess.Validate(); if (validationResult.Count > 0) { this.UpdateBinding("Errors", WorkflowHelper.ValidationResultToBinding(validationResult)); } } } private void step2CodeActivity_Uninstall_ExecuteCode(object sender, EventArgs e) { PackageElementProviderInstalledPackageItemEntityToken castedToken = (PackageElementProviderInstalledPackageItemEntityToken)this.EntityToken; PackageManagerUninstallProcess packageManagerUninstallProcess = this.GetBinding<PackageManagerUninstallProcess>("PackageManagerUninstallProcess"); Exception exception = null; try { string packageServerAddress = (from a in PackageManager.GetInstalledPackages() where a.Id == castedToken.PackageId select a.PackageServerAddress).Single(); List<PackageFragmentValidationResult> uninstallResult = packageManagerUninstallProcess.Uninstall(); try { PackageServerFacade.RegisterPackageUninstall(packageServerAddress, InstallationInformationFacade.InstallationId, castedToken.PackageId, UserSettings.Username, UserSettings.UserIPAddress.ToString()); } catch (Exception ex) { LoggingService.LogWarning("UninstallRemovePackageWorkflow", ex); this.UpdateBinding("UnregisterError", true); } if (uninstallResult.Count > 0) { this.UpdateBinding("Errors", WorkflowHelper.ValidationResultToBinding(uninstallResult)); } } catch (Exception ex) { exception = ex; this.UpdateBinding("Errors", new List<List<string>> { new List<string> { ex.Message, "" } }); } } private void step3CodeActivity_RefreshTree_ExecuteCode(object sender, EventArgs e) { if (this.GetBinding<bool>("ReloadConsoleOnCompletion")) { ConsoleMessageQueueFacade.Enqueue(new RebootConsoleMessageQueueItem(), null); } if (this.GetBinding<bool>("FlushOnCompletion")) { GlobalEventSystemFacade.FlushTheSystem(); } SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(new PackageElementProviderRootEntityToken()); } private void showErrorCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { List<string> rowHeader = new List<string>(); rowHeader.Add(StringResourceSystemFacade.ParseString("${Composite.Plugins.PackageElementProvider, UninstallRemotePackage.ShowError.MessageTitle}")); this.UpdateBinding("ErrorHeader", rowHeader); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/UninstallRemotePackageWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { partial class UninstallRemotePackageWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition3 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity11 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity6 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity5 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.ifElseActivity_DidUnregistre = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.step2WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity12 = new System.Workflow.Activities.SetStateActivity(); this.nextHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.showUnregistreErrorWizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.showErrorWizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.showErrorCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.step3CodeActivity_RefreshTree = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step3WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step2IfElseActivity_DidValidate = new System.Workflow.Activities.IfElseActivity(); this.step2CodeActivity_Uninstall = new System.Workflow.Activities.CodeActivity(); this.nextHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.step2IfElseActivity_Validate = new System.Workflow.Activities.IfElseActivity(); this.step2CodeActivity_Validate = new System.Workflow.Activities.CodeActivity(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.nextHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.step1WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.showUnregistreErrorEventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.showUnregistreErrorStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.showErrorEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.showErrorStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step3EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step3StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step2EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step2EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step2StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.showUnregistreErrorActivity = new System.Workflow.Activities.StateActivity(); this.showErrorStateActivity = new System.Workflow.Activities.StateActivity(); this.step3StateActivity = new System.Workflow.Activities.StateActivity(); this.step2StateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity11 // this.setStateActivity11.Name = "setStateActivity11"; this.setStateActivity11.TargetStateName = "showUnregistreErrorActivity"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "step3StateActivity"; // // ifElseBranchActivity6 // this.ifElseBranchActivity6.Activities.Add(this.setStateActivity11); this.ifElseBranchActivity6.Name = "ifElseBranchActivity6"; // // ifElseBranchActivity5 // this.ifElseBranchActivity5.Activities.Add(this.setStateActivity7); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DidUnregistre); this.ifElseBranchActivity5.Condition = codecondition1; this.ifElseBranchActivity5.Name = "ifElseBranchActivity5"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "showErrorStateActivity"; // // ifElseActivity_DidUnregistre // this.ifElseActivity_DidUnregistre.Activities.Add(this.ifElseBranchActivity5); this.ifElseActivity_DidUnregistre.Activities.Add(this.ifElseBranchActivity6); this.ifElseActivity_DidUnregistre.Name = "ifElseActivity_DidUnregistre"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "showErrorStateActivity"; // // step2WizardFormActivity // this.step2WizardFormActivity.ContainerLabel = null; this.step2WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderUninstallRemotePackageStep2.xml"; this.step2WizardFormActivity.Name = "step2WizardFormActivity"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity8); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.ifElseActivity_DidUnregistre); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DidValidate); this.ifElseBranchActivity3.Condition = codecondition2; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity5); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.step2WizardFormActivity); codecondition3.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DidValidate); this.ifElseBranchActivity1.Condition = codecondition3; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity12 // this.setStateActivity12.Name = "setStateActivity12"; this.setStateActivity12.TargetStateName = "step3StateActivity"; // // nextHandleExternalEventActivity3 // this.nextHandleExternalEventActivity3.EventName = "Next"; this.nextHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity3.Name = "nextHandleExternalEventActivity3"; // // showUnregistreErrorWizardFormActivity // this.showUnregistreErrorWizardFormActivity.ContainerLabel = null; this.showUnregistreErrorWizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderUninstallRemotePackageShowUnregistreError.x" + "ml"; this.showUnregistreErrorWizardFormActivity.Name = "showUnregistreErrorWizardFormActivity"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // showErrorWizardFormActivity // this.showErrorWizardFormActivity.ContainerLabel = null; this.showErrorWizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderUninstallRemotePackageShowError.xml"; this.showErrorWizardFormActivity.Name = "showErrorWizardFormActivity"; // // showErrorCodeActivity_Initialize // this.showErrorCodeActivity_Initialize.Name = "showErrorCodeActivity_Initialize"; this.showErrorCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.showErrorCodeActivity_Initialize_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // step3CodeActivity_RefreshTree // this.step3CodeActivity_RefreshTree.Name = "step3CodeActivity_RefreshTree"; this.step3CodeActivity_RefreshTree.ExecuteCode += new System.EventHandler(this.step3CodeActivity_RefreshTree_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // step3WizardFormActivity // this.step3WizardFormActivity.ContainerLabel = null; this.step3WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderUninstallRemotePackageStep3.xml"; this.step3WizardFormActivity.Name = "step3WizardFormActivity"; // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // step2IfElseActivity_DidValidate // this.step2IfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity3); this.step2IfElseActivity_DidValidate.Activities.Add(this.ifElseBranchActivity4); this.step2IfElseActivity_DidValidate.Name = "step2IfElseActivity_DidValidate"; // // step2CodeActivity_Uninstall // this.step2CodeActivity_Uninstall.Name = "step2CodeActivity_Uninstall"; this.step2CodeActivity_Uninstall.ExecuteCode += new System.EventHandler(this.step2CodeActivity_Uninstall_ExecuteCode); // // nextHandleExternalEventActivity2 // this.nextHandleExternalEventActivity2.EventName = "Next"; this.nextHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity2.Name = "nextHandleExternalEventActivity2"; // // step2IfElseActivity_Validate // this.step2IfElseActivity_Validate.Activities.Add(this.ifElseBranchActivity1); this.step2IfElseActivity_Validate.Activities.Add(this.ifElseBranchActivity2); this.step2IfElseActivity_Validate.Name = "step2IfElseActivity_Validate"; // // step2CodeActivity_Validate // this.step2CodeActivity_Validate.Name = "step2CodeActivity_Validate"; this.step2CodeActivity_Validate.ExecuteCode += new System.EventHandler(this.step2CodeActivity_Validate_ExecuteCode); // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "step2StateActivity"; // // nextHandleExternalEventActivity1 // this.nextHandleExternalEventActivity1.EventName = "Next"; this.nextHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity1.Name = "nextHandleExternalEventActivity1"; // // step1WizardFormActivity // this.step1WizardFormActivity.ContainerLabel = null; this.step1WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderUninstallRemotePackageStep1.xml"; this.step1WizardFormActivity.Name = "step1WizardFormActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // showUnregistreErrorEventDrivenActivity_Next // this.showUnregistreErrorEventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity3); this.showUnregistreErrorEventDrivenActivity_Next.Activities.Add(this.setStateActivity12); this.showUnregistreErrorEventDrivenActivity_Next.Name = "showUnregistreErrorEventDrivenActivity_Next"; // // showUnregistreErrorStateInitializationActivity // this.showUnregistreErrorStateInitializationActivity.Activities.Add(this.showUnregistreErrorWizardFormActivity); this.showUnregistreErrorStateInitializationActivity.Name = "showUnregistreErrorStateInitializationActivity"; // // showErrorEventDrivenActivity_Finish // this.showErrorEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.showErrorEventDrivenActivity_Finish.Activities.Add(this.setStateActivity3); this.showErrorEventDrivenActivity_Finish.Name = "showErrorEventDrivenActivity_Finish"; // // showErrorStateInitializationActivity // this.showErrorStateInitializationActivity.Activities.Add(this.showErrorCodeActivity_Initialize); this.showErrorStateInitializationActivity.Activities.Add(this.showErrorWizardFormActivity); this.showErrorStateInitializationActivity.Name = "showErrorStateInitializationActivity"; // // step3EventDrivenActivity_Finish // this.step3EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.step3EventDrivenActivity_Finish.Activities.Add(this.closeCurrentViewActivity1); this.step3EventDrivenActivity_Finish.Activities.Add(this.step3CodeActivity_RefreshTree); this.step3EventDrivenActivity_Finish.Activities.Add(this.setStateActivity4); this.step3EventDrivenActivity_Finish.Name = "step3EventDrivenActivity_Finish"; // // step3StateInitializationActivity // this.step3StateInitializationActivity.Activities.Add(this.step3WizardFormActivity); this.step3StateInitializationActivity.Name = "step3StateInitializationActivity"; // // step2EventDrivenActivity_Cancel // this.step2EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.step2EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity10); this.step2EventDrivenActivity_Cancel.Name = "step2EventDrivenActivity_Cancel"; // // step2EventDrivenActivity_Next // this.step2EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity2); this.step2EventDrivenActivity_Next.Activities.Add(this.step2CodeActivity_Uninstall); this.step2EventDrivenActivity_Next.Activities.Add(this.step2IfElseActivity_DidValidate); this.step2EventDrivenActivity_Next.Name = "step2EventDrivenActivity_Next"; // // step2StateInitializationActivity // this.step2StateInitializationActivity.Activities.Add(this.step2CodeActivity_Validate); this.step2StateInitializationActivity.Activities.Add(this.step2IfElseActivity_Validate); this.step2StateInitializationActivity.Name = "step2StateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity9); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Next // this.step1EventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity1); this.step1EventDrivenActivity_Next.Activities.Add(this.setStateActivity6); this.step1EventDrivenActivity_Next.Name = "step1EventDrivenActivity_Next"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1WizardFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // showUnregistreErrorActivity // this.showUnregistreErrorActivity.Activities.Add(this.showUnregistreErrorStateInitializationActivity); this.showUnregistreErrorActivity.Activities.Add(this.showUnregistreErrorEventDrivenActivity_Next); this.showUnregistreErrorActivity.Name = "showUnregistreErrorActivity"; // // showErrorStateActivity // this.showErrorStateActivity.Activities.Add(this.showErrorStateInitializationActivity); this.showErrorStateActivity.Activities.Add(this.showErrorEventDrivenActivity_Finish); this.showErrorStateActivity.Name = "showErrorStateActivity"; // // step3StateActivity // this.step3StateActivity.Activities.Add(this.step3StateInitializationActivity); this.step3StateActivity.Activities.Add(this.step3EventDrivenActivity_Finish); this.step3StateActivity.Name = "step3StateActivity"; // // step2StateActivity // this.step2StateActivity.Activities.Add(this.step2StateInitializationActivity); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Next); this.step2StateActivity.Activities.Add(this.step2EventDrivenActivity_Cancel); this.step2StateActivity.Name = "step2StateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Next); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // UninstallRemotePackageWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.step2StateActivity); this.Activities.Add(this.step3StateActivity); this.Activities.Add(this.showErrorStateActivity); this.Activities.Add(this.showUnregistreErrorActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "UninstallRemotePackageWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity2; private EventDrivenActivity showErrorEventDrivenActivity_Finish; private StateInitializationActivity showErrorStateInitializationActivity; private EventDrivenActivity step3EventDrivenActivity_Finish; private StateInitializationActivity step3StateInitializationActivity; private EventDrivenActivity step2EventDrivenActivity_Next; private StateInitializationActivity step2StateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Next; private StateInitializationActivity step1StateInitializationActivity; private StateActivity showErrorStateActivity; private StateActivity step3StateActivity; private StateActivity step2StateActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity2; private Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.WizardFormActivity step1WizardFormActivity; private Composite.C1Console.Workflow.Activities.WizardFormActivity step2WizardFormActivity; private CodeActivity step2CodeActivity_Validate; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity step2IfElseActivity_Validate; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity6; private CodeActivity step2CodeActivity_Uninstall; private SetStateActivity setStateActivity8; private SetStateActivity setStateActivity7; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity step2IfElseActivity_DidValidate; private Composite.C1Console.Workflow.Activities.WizardFormActivity step3WizardFormActivity; private CodeActivity step3CodeActivity_RefreshTree; private CodeActivity showErrorCodeActivity_Initialize; private Composite.C1Console.Workflow.Activities.WizardFormActivity showErrorWizardFormActivity; private SetStateActivity setStateActivity10; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private SetStateActivity setStateActivity9; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step2EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Cancel; private IfElseBranchActivity ifElseBranchActivity6; private IfElseBranchActivity ifElseBranchActivity5; private IfElseActivity ifElseActivity_DidUnregistre; private SetStateActivity setStateActivity11; private Composite.C1Console.Workflow.Activities.WizardFormActivity showUnregistreErrorWizardFormActivity; private EventDrivenActivity showUnregistreErrorEventDrivenActivity_Next; private StateInitializationActivity showUnregistreErrorStateInitializationActivity; private StateActivity showUnregistreErrorActivity; private SetStateActivity setStateActivity12; private Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity3; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/UninstallRemotePackageWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="UninstallRemotePackageWorkflow" Location="30; 30" Size="1068; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="UninstallRemotePackageWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="UninstallRemotePackageWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="143" Y="71" /> <ns0:Point X="143" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="269" Y="146" /> <ns0:Point X="285" Y="146" /> <ns0:Point X="285" Y="286" /> <ns0:Point X="168" Y="286" /> <ns0:Point X="168" Y="297" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step2StateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="step2StateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="260" Y="362" /> <ns0:Point X="284" Y="362" /> <ns0:Point X="284" Y="422" /> <ns0:Point X="168" Y="422" /> <ns0:Point X="168" Y="431" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity9" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="270" Y="386" /> <ns0:Point X="286" Y="386" /> <ns0:Point X="286" Y="194" /> <ns0:Point X="143" Y="194" /> <ns0:Point X="143" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="showErrorStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="showErrorStateActivity" SourceActivity="step2StateActivity" EventHandlerName="step2StateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="257" Y="472" /> <ns0:Point X="281" Y="472" /> <ns0:Point X="281" Y="670" /> <ns0:Point X="178" Y="670" /> <ns0:Point X="178" Y="675" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="showErrorStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity8" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="showErrorStateActivity" SourceActivity="step2StateActivity" EventHandlerName="step2EventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="260" Y="496" /> <ns0:Point X="284" Y="496" /> <ns0:Point X="284" Y="670" /> <ns0:Point X="178" Y="670" /> <ns0:Point X="178" Y="675" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step3StateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="step3StateActivity" SourceActivity="step2StateActivity" EventHandlerName="step2EventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="260" Y="496" /> <ns0:Point X="284" Y="496" /> <ns0:Point X="284" Y="558" /> <ns0:Point X="166" Y="558" /> <ns0:Point X="166" Y="565" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="showUnregistreErrorActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity11" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="showUnregistreErrorActivity" SourceActivity="step2StateActivity" EventHandlerName="step2EventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="260" Y="496" /> <ns0:Point X="284" Y="496" /> <ns0:Point X="284" Y="424" /> <ns0:Point X="52" Y="424" /> <ns0:Point X="52" Y="774" /> <ns0:Point X="201" Y="774" /> <ns0:Point X="201" Y="785" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity10" SourceStateName="step2StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step2StateActivity" EventHandlerName="step2EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="270" Y="520" /> <ns0:Point X="286" Y="520" /> <ns0:Point X="286" Y="192" /> <ns0:Point X="143" Y="192" /> <ns0:Point X="143" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="step3StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step3StateActivity" EventHandlerName="step3EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="266" Y="630" /> <ns0:Point X="282" Y="630" /> <ns0:Point X="282" Y="190" /> <ns0:Point X="143" Y="190" /> <ns0:Point X="143" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="showErrorStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="showErrorStateActivity" EventHandlerName="showErrorEventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="289" Y="740" /> <ns0:Point X="305" Y="740" /> <ns0:Point X="305" Y="196" /> <ns0:Point X="143" Y="196" /> <ns0:Point X="143" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step3StateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity12" SourceStateName="showUnregistreErrorActivity" SourceConnectionEdge="Right" TargetActivity="step3StateActivity" SourceActivity="showUnregistreErrorActivity" EventHandlerName="showUnregistreErrorEventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="335" Y="850" /> <ns0:Point X="351" Y="850" /> <ns0:Point X="351" Y="558" /> <ns0:Point X="166" Y="558" /> <ns0:Point X="166" Y="565" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="63; 105" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="initializeStateInitializationActivity" Location="71; 136"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="81; 198" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="63; 201" Size="160; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="step1StateActivity" Location="63; 297" Size="211; 118" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="71; 328"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step1WizardFormActivity" Location="81; 390" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Next" Location="71; 352"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="nextHandleExternalEventActivity1" Location="81; 414" /> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="81; 474" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="71; 376"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="81; 438" /> <SetStateDesigner Size="130; 41" Name="setStateActivity9" Location="81; 498" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="step2StateActivity" Location="63; 431" Size="211; 118" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 363" Name="step2StateInitializationActivity" Location="71; 462"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="step2CodeActivity_Validate" Location="196; 524" /> <IfElseDesigner Size="361; 222" Name="step2IfElseActivity_Validate" Location="81; 584"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity1" Location="100; 655"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step2WizardFormActivity" Location="110; 717" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity2" Location="273; 655"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="283; 717" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="612; 616" Name="step2EventDrivenActivity_Next" Location="71; 486"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="nextHandleExternalEventActivity2" Location="312; 548" /> <CodeDesigner Size="130; 41" Name="step2CodeActivity_Uninstall" Location="312; 608" /> <IfElseDesigner Size="592; 415" Name="step2IfElseActivity_DidValidate" Location="81; 668"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="381; 315" Name="ifElseBranchActivity3" Location="100; 739"> <IfElseBranchDesigner.Designers> <IfElseDesigner Size="361; 234" Name="ifElseActivity_DidUnregistre" Location="110; 801"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 134" Name="ifElseBranchActivity5" Location="129; 872"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="139; 940" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 134" Name="ifElseBranchActivity6" Location="302; 872"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 53" Name="setStateActivity11" Location="312; 934" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 315" Name="ifElseBranchActivity4" Location="504; 739"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity8" Location="514; 898" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 194" Name="step2EventDrivenActivity_Cancel" Location="71; 510"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity3" Location="81; 572" /> <SetStateDesigner Size="130; 53" Name="setStateActivity10" Location="81; 632" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="step3StateActivity" Location="63; 565" Size="207; 94" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step3StateInitializationActivity" Location="481; 135"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step3WizardFormActivity" Location="491; 197" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 302" Name="step3EventDrivenActivity_Finish" Location="489; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity2" Location="499; 210" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="499; 270" /> <CodeDesigner Size="130; 41" Name="step3CodeActivity_RefreshTree" Location="499; 330" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="499; 390" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="showErrorStateActivity" Location="63; 675" Size="230; 94" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="showErrorStateInitializationActivity" Location="71; 706"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="showErrorCodeActivity_Initialize" Location="81; 768" /> <ActivityDesigner Size="130; 41" Name="showErrorWizardFormActivity" Location="81; 828" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="showErrorEventDrivenActivity_Finish" Location="71; 730"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="81; 792" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="81; 852" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="showUnregistreErrorActivity" Location="63; 785" Size="276; 94" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="showUnregistreErrorStateInitializationActivity" Location="71; 816"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="showUnregistreErrorWizardFormActivity" Location="81; 878" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 194" Name="showUnregistreErrorEventDrivenActivity_Next" Location="71; 840"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="nextHandleExternalEventActivity3" Location="81; 902" /> <SetStateDesigner Size="130; 53" Name="setStateActivity12" Location="81; 962" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/ViewAvailablePackageInfoWorkflowWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Events; using Composite.C1Console.Forms.DataServices; using Composite.Core.Configuration; using Composite.Core.PackageSystem; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Plugins_PackageElementProvider; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class ViewAvailablePackageInfoWorkflowWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { const string CustomToolbarFormPath = @"\Administrative\PackageElementProviderViewAvailablePackageInformationToolbar.xml"; static class BindingNames { public const string PackageDescription = nameof(PackageDescription); public const string DocumentTitle = nameof(DocumentTitle); public const string AddOnServerSource = nameof(AddOnServerSource); public const string HasOwnPrice = nameof(HasOwnPrice); public const string PriceText = nameof(PriceText); public const string IsInPurchasableSubscriptions = nameof(IsInPurchasableSubscriptions); public const string PurchasableSubscriptions = nameof(PurchasableSubscriptions); public const string ShowTrialInfo = nameof(ShowTrialInfo); public const string ShowSubscriptionLicense = nameof(ShowSubscriptionLicense); public const string SubscriptionName = nameof(SubscriptionName); public const string LicenseExpirationDate = nameof(LicenseExpirationDate); } class SubscriptionLicense { public string Name { get; set; } public DateTime ExpirationDate { get; set; } public bool Expired { get; set; } } public ViewAvailablePackageInfoWorkflowWorkflow() { InitializeComponent(); } private void AddOnDescriptionExists(object sender, ConditionalEventArgs e) { this.TryGetBinding(BindingNames.PackageDescription, out PackageDescription packageDescription); e.Result = packageDescription != null; } private void viewStateCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { this.SetCustomToolbarDefinition(new FormDefinitionFileMarkupProvider(CustomToolbarFormPath)); if (this.BindingExist(BindingNames.PackageDescription)) { return; } var castedToken = (PackageElementProviderAvailablePackagesItemEntityToken)this.EntityToken; PackageDescription packageDescription = (from description in PackageSystemServices.GetFilteredAllAvailablePackages() where description.Id.ToString() == castedToken.Id select description).SingleOrDefault(); if (packageDescription == null) { return; } string packageSourceName = PackageSystemServices.GetPackageSourceNameByPackageId(packageDescription.Id, InstallationInformationFacade.InstallationId, UserSettings.CultureInfo); var purchasableSubscriptions = packageDescription.AvailableInSubscriptions.Where(f => f.Purchasable).ToList(); var licenses = GetSubscriptionLicenses(packageDescription.AvailableInSubscriptions); var validLicense = licenses.Where(l => !l.Expired) .OrderByDescending(l => l.ExpirationDate) .FirstOrDefault(); this.Bindings = new Dictionary<string, object> { {BindingNames.PackageDescription, packageDescription}, {BindingNames.DocumentTitle, GetDocumentTitle(packageDescription)}, {BindingNames.AddOnServerSource, packageSourceName}, {BindingNames.HasOwnPrice, packageDescription.PriceAmmount > 0}, {BindingNames.PriceText, $"{packageDescription.PriceAmmount} {packageDescription.PriceCurrency}"}, {BindingNames.IsInPurchasableSubscriptions, purchasableSubscriptions.Any()}, {BindingNames.PurchasableSubscriptions, string.Join(", \n", purchasableSubscriptions.Select(f => f.Name))}, {BindingNames.ShowTrialInfo, packageDescription.IsTrial && validLicense == null}, {BindingNames.ShowSubscriptionLicense, validLicense != null}, {BindingNames.SubscriptionName, validLicense?.Name}, {BindingNames.LicenseExpirationDate, validLicense?.ExpirationDate.ToLocalTime().ToString()} }; } private SubscriptionLicense[] GetSubscriptionLicenses(IEnumerable<Subscription> availableInSubscriptions) { return (from subscription in availableInSubscriptions let license = PackageLicenseHelper.GetLicenseDefinition(subscription.Id) where license != null select new SubscriptionLicense { Name = subscription.Name, ExpirationDate = license.Expires, Expired = !license.Permanent && license.Expires < DateTime.Now }).ToArray(); } private string GetDocumentTitle(PackageDescription packageDescription) { // Valid package names: // "Composite.Community.Versioning" // "C1 CMS 3.0" string name = packageDescription.Name.Trim(); string documentTitle = name; if (name.Contains(".") && !name.EndsWith(".")) { string packageName = name.Substring(name.LastIndexOf('.') + 1); string packageNamespace = name.Substring(0, name.LastIndexOf('.')); int temp; if (!int.TryParse(packageName, out temp)) { documentTitle = $"{packageName} ({packageNamespace})"; } } return documentTitle; } private void installAddOnCodeActivity_Execute_ExecuteCode(object sender, EventArgs e) { var castedToken = (PackageElementProviderAvailablePackagesItemEntityToken)this.EntityToken; PackageDescription packageDescription = (from description in PackageSystemServices.GetFilteredAllAvailablePackages() where description.Id.ToString() == castedToken.Id select description).FirstOrDefault(); if (packageDescription != null) { #pragma warning disable 436 this.ExecuteWorklow(this.EntityToken, typeof(InstallRemotePackageWorkflow)); #pragma warning restore 436 } else { this.ShowMessage(DialogType.Message, Texts.ViewAvailableInformation_ShowError_MessageTitle, Texts.ViewAvailableInformation_ShowError_MessageMessage); } } private void viewCodeActivity_ShowMessage_ExecuteCode(object sender, EventArgs e) { this.ShowMessage(DialogType.Error, Texts.ViewAvailableInformation_ShowServerError_MessageTitle, Texts.ViewAvailableInformation_ShowServerError_MessageMessage); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/ViewAvailablePackageInfoWorkflowWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { partial class ViewAvailablePackageInfoWorkflowWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.viewCodeActivity_ShowMessage = new System.Workflow.Activities.CodeActivity(); this.viewDocumentFormActivity = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.installAddOnCodeActivity_Execute = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.customEvent01HandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CustomEvent01HandleExternalEventActivity(); this.ifElseActivity_AddOnDescriptionExists = new System.Workflow.Activities.IfElseActivity(); this.viewStateCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.installAddOnStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.viewSateEventDrivenActivity_Install = new System.Workflow.Activities.EventDrivenActivity(); this.viewStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.installAddOnStateActivity = new System.Workflow.Activities.StateActivity(); this.viewStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // viewCodeActivity_ShowMessage // this.viewCodeActivity_ShowMessage.Name = "viewCodeActivity_ShowMessage"; this.viewCodeActivity_ShowMessage.ExecuteCode += new System.EventHandler(this.viewCodeActivity_ShowMessage_ExecuteCode); // // viewDocumentFormActivity // this.viewDocumentFormActivity.ContainerLabel = null; this.viewDocumentFormActivity.CustomToolbarDefinitionFileName = null; this.viewDocumentFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderViewAvailablePackageInformation.xml"; this.viewDocumentFormActivity.Name = "viewDocumentFormActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.viewCodeActivity_ShowMessage); this.ifElseBranchActivity2.Activities.Add(this.setStateActivity5); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.viewDocumentFormActivity); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.AddOnDescriptionExists); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "viewStateActivity"; // // installAddOnCodeActivity_Execute // this.installAddOnCodeActivity_Execute.Name = "installAddOnCodeActivity_Execute"; this.installAddOnCodeActivity_Execute.ExecuteCode += new System.EventHandler(this.installAddOnCodeActivity_Execute_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "installAddOnStateActivity"; // // customEvent01HandleExternalEventActivity1 // this.customEvent01HandleExternalEventActivity1.EventName = "CustomEvent01"; this.customEvent01HandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.customEvent01HandleExternalEventActivity1.Name = "customEvent01HandleExternalEventActivity1"; // // ifElseActivity_AddOnDescriptionExists // this.ifElseActivity_AddOnDescriptionExists.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity_AddOnDescriptionExists.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity_AddOnDescriptionExists.Name = "ifElseActivity_AddOnDescriptionExists"; // // viewStateCodeActivity_Initialize // this.viewStateCodeActivity_Initialize.Name = "viewStateCodeActivity_Initialize"; this.viewStateCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.viewStateCodeActivity_Initialize_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "viewStateActivity"; // // installAddOnStateInitializationActivity // this.installAddOnStateInitializationActivity.Activities.Add(this.installAddOnCodeActivity_Execute); this.installAddOnStateInitializationActivity.Activities.Add(this.setStateActivity4); this.installAddOnStateInitializationActivity.Name = "installAddOnStateInitializationActivity"; // // viewSateEventDrivenActivity_Install // this.viewSateEventDrivenActivity_Install.Activities.Add(this.customEvent01HandleExternalEventActivity1); this.viewSateEventDrivenActivity_Install.Activities.Add(this.setStateActivity3); this.viewSateEventDrivenActivity_Install.Name = "viewSateEventDrivenActivity_Install"; // // viewStateInitializationActivity // this.viewStateInitializationActivity.Activities.Add(this.viewStateCodeActivity_Initialize); this.viewStateInitializationActivity.Activities.Add(this.ifElseActivity_AddOnDescriptionExists); this.viewStateInitializationActivity.Name = "viewStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // installAddOnStateActivity // this.installAddOnStateActivity.Activities.Add(this.installAddOnStateInitializationActivity); this.installAddOnStateActivity.Name = "installAddOnStateActivity"; // // viewStateActivity // this.viewStateActivity.Activities.Add(this.viewStateInitializationActivity); this.viewStateActivity.Activities.Add(this.viewSateEventDrivenActivity_Install); this.viewStateActivity.Name = "viewStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // ViewAvailablePackageInfoWorkflowWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.viewStateActivity); this.Activities.Add(this.installAddOnStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "ViewAvailablePackageInfoWorkflowWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private StateInitializationActivity viewStateInitializationActivity; private StateActivity viewStateActivity; private C1Console.Workflow.Activities.DocumentFormActivity viewDocumentFormActivity; private CodeActivity viewStateCodeActivity_Initialize; private EventDrivenActivity viewSateEventDrivenActivity_Install; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.CustomEvent01HandleExternalEventActivity customEvent01HandleExternalEventActivity1; private CodeActivity installAddOnCodeActivity_Execute; private SetStateActivity setStateActivity3; private StateInitializationActivity installAddOnStateInitializationActivity; private StateActivity installAddOnStateActivity; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity5; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity_AddOnDescriptionExists; private CodeActivity viewCodeActivity_ShowMessage; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/ViewAvailablePackageInfoWorkflowWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1086; 690" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="ViewAvailablePackageInfoWorkflowWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="ViewAvailablePackageInfoWorkflowWorkflow" TargetConnectionIndex="0" SourceStateName="ViewAvailablePackageInfoWorkflowWorkflow" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="74" /> <ns0:Point X="944" Y="74" /> <ns0:Point X="944" Y="306" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="viewStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="viewStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="286" Y="150" /> <ns0:Point X="545" Y="150" /> <ns0:Point X="545" Y="183" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceActivity="viewStateActivity" TargetConnectionIndex="0" SourceStateName="viewStateActivity" SourceConnectionEdge="Right" EventHandlerName="viewStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="628" Y="227" /> <ns0:Point X="944" Y="227" /> <ns0:Point X="944" Y="306" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="installAddOnStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="viewStateActivity" TargetConnectionIndex="0" SourceStateName="viewStateActivity" SourceConnectionEdge="Right" EventHandlerName="viewSateEventDrivenActivity_Install" SourceConnectionIndex="1" TargetStateName="installAddOnStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="661" Y="253" /> <ns0:Point X="672" Y="253" /> <ns0:Point X="672" Y="323" /> <ns0:Point X="272" Y="323" /> <ns0:Point X="272" Y="335" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="viewStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="installAddOnStateActivity" TargetConnectionIndex="0" SourceStateName="installAddOnStateActivity" SourceConnectionEdge="Right" EventHandlerName="installAddOnStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="viewStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="395" Y="379" /> <ns0:Point X="411" Y="379" /> <ns0:Point X="411" Y="175" /> <ns0:Point X="545" Y="175" /> <ns0:Point X="545" Y="183" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 209" Location="38; 63"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 44" Location="48; 128" /> <SetStateDesigner Name="setStateActivity1" Size="130; 62" Location="48; 191" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="227; 80" AutoSizeMargin="16; 24" Location="63; 106" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 146" Location="71; 139"> <StateInitializationDesigner.Designers> <SetStateDesigner Name="setStateActivity2" Size="130; 62" Location="81; 204" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="864; 306" Name="finalStateActivity" /> <StateDesigner Size="239; 100" AutoSizeMargin="16; 24" AutoSize="False" Location="426; 183" Name="viewStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="viewStateInitializationActivity" Size="381; 459" Location="382; 154"> <StateInitializationDesigner.Designers> <CodeDesigner Name="viewStateCodeActivity_Initialize" Size="130; 44" Location="507; 219" /> <IfElseDesigner Name="ifElseActivity_AddOnDescriptionExists" Size="361; 312" Location="392; 282"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 209" Location="411; 356"> <IfElseBranchDesigner.Designers> <ActivityDesigner Name="viewDocumentFormActivity" Size="130; 44" Location="421; 461" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 209" Location="584; 356"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="viewCodeActivity_ShowMessage" Size="130; 44" Location="594; 421" /> <SetStateDesigner Name="setStateActivity5" Size="130; 62" Location="594; 484" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="viewSateEventDrivenActivity_Install" Size="150; 209" Location="374; 167"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="customEvent01HandleExternalEventActivity1" Size="130; 44" Location="384; 232" /> <SetStateDesigner Name="setStateActivity3" Size="130; 62" Location="384; 295" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="253; 80" AutoSizeMargin="16; 24" Location="146; 335" Name="installAddOnStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="installAddOnStateInitializationActivity" Size="150; 209" Location="154; 368"> <StateInitializationDesigner.Designers> <CodeDesigner Name="installAddOnCodeActivity_Execute" Size="130; 44" Location="164; 433" /> <SetStateDesigner Name="setStateActivity4" Size="130; 62" Location="164; 496" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/ViewInstalledPackageInfoWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Users; using Composite.Core.Configuration; using Composite.Core.PackageSystem; using Composite.Core.PackageSystem.Workflow; using Composite.C1Console.Forms.DataServices; using Composite.C1Console.Workflow; using Composite.C1Console.Events; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class ViewInstalledPackageInfoWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { const string CustomToolbarDefinitionPath = @"\Administrative\PackageElementProviderViewInstalledPackageInformationToolbar.xml"; public ViewInstalledPackageInfoWorkflow() { InitializeComponent(); } private static class BindingNames { public const string DocumentTitle = nameof(DocumentTitle); public const string InstalledPackageInformation = nameof(InstalledPackageInformation); public const string InstallDate = nameof(InstallDate); public const string IsTrial = nameof(IsTrial); public const string TrialPurchaseUrl = nameof(TrialPurchaseUrl); public const string ReadMoreUrl = nameof(ReadMoreUrl); public const string IsSubscription = nameof(IsSubscription); public const string SubscriptionName = nameof(SubscriptionName); public const string LicenseExpirationDate = nameof(LicenseExpirationDate); public const string ShowPurchaseThisButton = nameof(ShowPurchaseThisButton); } private class LicenseInformation { public bool IsSubscription { get; set; } public bool IsTrial { get; set; } public bool HasExpired { get; set; } public string Name { get; set; } public string PurchaseUrl { get; set; } public DateTime ExpirationDate { get; set; } } private void viewStateCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { var castedToken = (PackageElementProviderInstalledPackageItemEntityToken)this.EntityToken; Guid packageId = castedToken.PackageId; if (castedToken.CanBeUninstalled) { this.SetCustomToolbarDefinition(new FormDefinitionFileMarkupProvider(CustomToolbarDefinitionPath)); } if (this.BindingExist(BindingNames.InstalledPackageInformation)) { return; } InstalledPackageInformation installedAddOnInformation = PackageManager.GetInstalledPackages().Single(info => info.Id == packageId); string name = installedAddOnInformation.Name; string documentTitle = GetDocumentTitle(name); DateTime installationDate = installedAddOnInformation.InstallDate.ToLocalTime(); this.Bindings = new Dictionary<string, object> { {BindingNames.DocumentTitle, documentTitle}, {BindingNames.InstalledPackageInformation, installedAddOnInformation}, {BindingNames.InstallDate, installationDate.ToString()} }; PackageDescription packageDescription = null; try { var allPackages = PackageServerFacade.GetAllPackageDescriptions(InstallationInformationFacade.InstallationId, UserSettings.CultureInfo); packageDescription = allPackages.FirstOrDefault(p => p.Id == packageId); } catch { } if (!string.IsNullOrEmpty(packageDescription?.ReadMoreUrl)) { this.Bindings[BindingNames.ReadMoreUrl] = packageDescription.ReadMoreUrl; } var licenses = GetRelatedLicenses(packageId, packageDescription); var actualLicense = licenses.OrderBy(l => l.HasExpired).ThenByDescending(l => l.IsSubscription).FirstOrDefault(); if (actualLicense != null) { Bindings[BindingNames.LicenseExpirationDate] = actualLicense.ExpirationDate.ToLocalTime().ToString(); } bool isTrial = actualLicense != null && actualLicense.IsTrial; this.Bindings[BindingNames.IsTrial] = isTrial; bool showPurchaseButton = false; if (isTrial && !string.IsNullOrWhiteSpace(actualLicense.PurchaseUrl)) { string url = actualLicense.PurchaseUrl; this.Bindings[BindingNames.TrialPurchaseUrl] = url; showPurchaseButton = true; } this.Bindings[BindingNames.ShowPurchaseThisButton] = showPurchaseButton; bool isSubscription = actualLicense != null && actualLicense.IsSubscription; this.Bindings[BindingNames.IsSubscription] = isSubscription; if (isSubscription) { Bindings[BindingNames.SubscriptionName] = actualLicense.Name; } } private LicenseInformation[] GetRelatedLicenses(Guid packageId, PackageDescription packageDescription) { var result = new List<LicenseInformation>(); var licenseInfo = PackageLicenseHelper.GetLicenseDefinition(packageId); if (licenseInfo != null) { result.Add(new LicenseInformation { Name = licenseInfo.ProductName, IsSubscription = false, ExpirationDate = licenseInfo.Expires, HasExpired = !licenseInfo.Permanent && licenseInfo.Expires < DateTime.Now, IsTrial = !licenseInfo.Permanent, PurchaseUrl = licenseInfo.PurchaseUrl }); } if (packageDescription != null) { foreach (var subscription in packageDescription.AvailableInSubscriptions) { var subscriptionLicense = PackageLicenseHelper.GetLicenseDefinition(subscription.Id); if (subscriptionLicense == null) continue; result.Add(new LicenseInformation { Name = subscription.Name, IsSubscription = true, ExpirationDate = subscriptionLicense.Expires, HasExpired = !subscriptionLicense.Permanent && subscriptionLicense.Expires < DateTime.Now, IsTrial = false, PurchaseUrl = subscription.DetailsUrl, }); } } return result.ToArray(); } private string GetDocumentTitle(string name) { if (!name.Contains('.') || name.EndsWith(".")) { return name; } int nameOffset = name.LastIndexOf('.'); return $"{name.Substring(nameOffset + 1)} ({name.Substring(0, nameOffset)})"; } private void uninstallCodeActivity_ExecuteCode(object sender, EventArgs e) { var castedToken = (PackageElementProviderInstalledPackageItemEntityToken)this.EntityToken; InstalledPackageInformation installedAddOnInformation = (from info in PackageManager.GetInstalledPackages() where info.Id == castedToken.PackageId select info).FirstOrDefault(); if (installedAddOnInformation != null) { this.ExecuteWorklow(this.EntityToken, installedAddOnInformation.IsLocalInstalled ? typeof (UninstallLocalPackageWorkflow) : typeof (UninstallRemotePackageWorkflow)); } else { this.ShowMessage( DialogType.Message, "${Composite.Plugins.PackageElementProvider, ViewInstalledInformation.ShowError.MessageTitle}", "${Composite.Plugins.PackageElementProvider, ViewInstalledInformation.ShowError.MessageMessage}"); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/ViewInstalledPackageInfoWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PackageElementProvider { partial class ViewInstalledPackageInfoWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.uninstallCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.customEvent01HandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CustomEvent01HandleExternalEventActivity(); this.viewDocumentFormActivity = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.viewStateCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.uninstallStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_Uninstall = new System.Workflow.Activities.EventDrivenActivity(); this.viewStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.uninstallStateActivity = new System.Workflow.Activities.StateActivity(); this.viewStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "viewStateActivity"; // // uninstallCodeActivity // this.uninstallCodeActivity.Name = "uninstallCodeActivity"; this.uninstallCodeActivity.ExecuteCode += new System.EventHandler(this.uninstallCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "uninstallStateActivity"; // // customEvent01HandleExternalEventActivity1 // this.customEvent01HandleExternalEventActivity1.EventName = "CustomEvent01"; this.customEvent01HandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.customEvent01HandleExternalEventActivity1.Name = "customEvent01HandleExternalEventActivity1"; // // viewDocumentFormActivity // this.viewDocumentFormActivity.ContainerLabel = null; this.viewDocumentFormActivity.CustomToolbarDefinitionFileName = null; this.viewDocumentFormActivity.FormDefinitionFileName = "\\Administrative\\PackageElementProviderViewInstalledPackageInformation.xml"; this.viewDocumentFormActivity.Name = "viewDocumentFormActivity"; // // viewStateCodeActivity_Initialize // this.viewStateCodeActivity_Initialize.Name = "viewStateCodeActivity_Initialize"; this.viewStateCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.viewStateCodeActivity_Initialize_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "viewStateActivity"; // // uninstallStateInitializationActivity // this.uninstallStateInitializationActivity.Activities.Add(this.uninstallCodeActivity); this.uninstallStateInitializationActivity.Activities.Add(this.setStateActivity4); this.uninstallStateInitializationActivity.Name = "uninstallStateInitializationActivity"; // // eventDrivenActivity_Uninstall // this.eventDrivenActivity_Uninstall.Activities.Add(this.customEvent01HandleExternalEventActivity1); this.eventDrivenActivity_Uninstall.Activities.Add(this.setStateActivity3); this.eventDrivenActivity_Uninstall.Name = "eventDrivenActivity_Uninstall"; // // viewStateInitializationActivity // this.viewStateInitializationActivity.Activities.Add(this.viewStateCodeActivity_Initialize); this.viewStateInitializationActivity.Activities.Add(this.viewDocumentFormActivity); this.viewStateInitializationActivity.Name = "viewStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // uninstallStateActivity // this.uninstallStateActivity.Activities.Add(this.uninstallStateInitializationActivity); this.uninstallStateActivity.Name = "uninstallStateActivity"; // // viewStateActivity // this.viewStateActivity.Activities.Add(this.viewStateInitializationActivity); this.viewStateActivity.Activities.Add(this.eventDrivenActivity_Uninstall); this.viewStateActivity.Name = "viewStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // ViewInstalledAddOnInfoWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.viewStateActivity); this.Activities.Add(this.uninstallStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "ViewInstalledAddOnInfoWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private Composite.C1Console.Workflow.Activities.DocumentFormActivity viewDocumentFormActivity; private SetStateActivity setStateActivity2; private StateInitializationActivity viewStateInitializationActivity; private StateActivity viewStateActivity; private CodeActivity viewStateCodeActivity_Initialize; private EventDrivenActivity eventDrivenActivity_Uninstall; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.CustomEvent01HandleExternalEventActivity customEvent01HandleExternalEventActivity1; private StateInitializationActivity uninstallStateInitializationActivity; private StateActivity uninstallStateActivity; private CodeActivity uninstallCodeActivity; private SetStateActivity setStateActivity4; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PackageElementProvider/ViewInstalledPackageInfoWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="ViewInstalledAddOnInfoWorkflow" Location="30; 30" Size="1146; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="ViewInstalledAddOnInfoWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="ViewInstalledAddOnInfoWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="viewStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="viewStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="402" Y="179" /> <ns0:Point X="402" Y="432" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="uninstallStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="viewStateActivity" SourceConnectionEdge="Right" TargetActivity="uninstallStateActivity" SourceActivity="viewStateActivity" EventHandlerName="eventDrivenActivity_Uninstall"> <StateDesignerConnector.Segments> <ns0:Point X="495" Y="497" /> <ns0:Point X="767" Y="497" /> <ns0:Point X="767" Y="520" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="viewStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="uninstallStateActivity" SourceConnectionEdge="Right" TargetActivity="viewStateActivity" SourceActivity="uninstallStateActivity" EventHandlerName="uninstallStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="869" Y="561" /> <ns0:Point X="882" Y="561" /> <ns0:Point X="882" Y="424" /> <ns0:Point X="402" Y="424" /> <ns0:Point X="402" Y="432" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="108; 231" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="viewStateActivity" Location="306; 432" Size="193; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="viewStateInitializationActivity" Location="520; 135"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="viewStateCodeActivity_Initialize" Location="530; 197" /> <ActivityDesigner Size="130; 41" Name="viewDocumentFormActivity" Location="530; 257" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_Uninstall" Location="528; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="customEvent01HandleExternalEventActivity1" Location="538; 210" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="538; 270" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="uninstallStateActivity" Location="661; 520" Size="212; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="uninstallStateInitializationActivity" Location="669; 551"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="uninstallCodeActivity" Location="679; 613" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="679; 673" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/AddNewPageWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { partial class AddNewPageWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition3 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition4 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition5 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition6 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition7 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition8 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition9 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition10 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.RuleDontAllowPageAddCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.stepInitialize_codeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity14 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity13 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.MissingPageTypeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElse_RulesDontAllowPageAdd = new System.Workflow.Activities.IfElseActivity(); this.ifElseBranchActivity12 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity11 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.MissingActiveLanguageCodeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElse_CheckPageTypesExists = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity_GoToFinalize = new System.Workflow.Activities.SetStateActivity(); this.PresetCalculatedFields = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity6 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity5 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity10 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity9 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity20 = new System.Workflow.Activities.SetStateActivity(); this.MissingTemplateAlertActivity = new System.Workflow.Activities.CodeActivity(); this.ifElse_CheckActiveLanguagesExists = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity_GoToStep2 = new System.Workflow.Activities.SetStateActivity(); this.ifElseActivity4_ValidateUrlTitle = new System.Workflow.Activities.IfElseActivity(); this.ifElseBranchActivity8 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity7 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity11 = new System.Workflow.Activities.SetStateActivity(); this.ifElse_CheckTemplatesExists = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity14 = new System.Workflow.Activities.SetStateActivity(); this.ifElseActivity_CanSkipStep2 = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity13 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity_redoStep2 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity12 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity16 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseCheckPageTypesExist = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity19 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity18 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity17 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity15 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElse_FirstPageValid = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.ifFirstPageValid = new System.Workflow.Activities.IfElseActivity(); this.nextHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.step1WizzardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.stepFinalize_codeActivity = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity__ValidateUrlTitle = new System.Workflow.Activities.IfElseActivity(); this.handleExternalEventActivity5 = new System.Workflow.Activities.HandleExternalEventActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.handleExternalEventActivity2 = new System.Workflow.Activities.HandleExternalEventActivity(); this.step2WizzardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.PrepareStep2 = new System.Workflow.Activities.CodeActivity(); this.setStateActivity19 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1_eventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1_eventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1_eventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step2_eventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step2_eventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step2_eventDrivenActivity_Previous = new System.Workflow.Activities.EventDrivenActivity(); this.step2StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.initializeActivity = new System.Workflow.Activities.StateActivity(); this.step1State = new System.Workflow.Activities.StateActivity(); this.finalizeActivity = new System.Workflow.Activities.StateActivity(); this.finishState = new System.Workflow.Activities.StateActivity(); this.step2State = new System.Workflow.Activities.StateActivity(); // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "finishState"; // // RuleDontAllowPageAddCodeActivity // this.RuleDontAllowPageAddCodeActivity.Name = "RuleDontAllowPageAddCodeActivity"; this.RuleDontAllowPageAddCodeActivity.ExecuteCode += new System.EventHandler(this.RuleDontAllowPageAddCodeActivity_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "step1State"; // // stepInitialize_codeActivity // this.stepInitialize_codeActivity.Name = "stepInitialize_codeActivity"; this.stepInitialize_codeActivity.ExecuteCode += new System.EventHandler(this.stepInitialize_codeActivity_ExecuteCode); // // ifElseBranchActivity14 // this.ifElseBranchActivity14.Activities.Add(this.RuleDontAllowPageAddCodeActivity); this.ifElseBranchActivity14.Activities.Add(this.setStateActivity10); this.ifElseBranchActivity14.Name = "ifElseBranchActivity14"; // // ifElseBranchActivity13 // this.ifElseBranchActivity13.Activities.Add(this.stepInitialize_codeActivity); this.ifElseBranchActivity13.Activities.Add(this.setStateActivity4); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckRulesAllowPageAddExists); this.ifElseBranchActivity13.Condition = codecondition1; this.ifElseBranchActivity13.Name = "ifElseBranchActivity13"; // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "finishState"; // // MissingPageTypeCodeActivity // this.MissingPageTypeCodeActivity.Name = "MissingPageTypeCodeActivity"; this.MissingPageTypeCodeActivity.ExecuteCode += new System.EventHandler(this.MissingPageTypeCodeActivity_ExecuteCode); // // ifElse_RulesDontAllowPageAdd // this.ifElse_RulesDontAllowPageAdd.Activities.Add(this.ifElseBranchActivity13); this.ifElse_RulesDontAllowPageAdd.Activities.Add(this.ifElseBranchActivity14); this.ifElse_RulesDontAllowPageAdd.Name = "ifElse_RulesDontAllowPageAdd"; // // ifElseBranchActivity12 // this.ifElseBranchActivity12.Activities.Add(this.MissingPageTypeCodeActivity); this.ifElseBranchActivity12.Activities.Add(this.setStateActivity9); this.ifElseBranchActivity12.Name = "ifElseBranchActivity12"; // // ifElseBranchActivity11 // this.ifElseBranchActivity11.Activities.Add(this.ifElse_RulesDontAllowPageAdd); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckPageTypeExists); this.ifElseBranchActivity11.Condition = codecondition2; this.ifElseBranchActivity11.Name = "ifElseBranchActivity11"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finishState"; // // MissingActiveLanguageCodeActivity // this.MissingActiveLanguageCodeActivity.Name = "MissingActiveLanguageCodeActivity"; this.MissingActiveLanguageCodeActivity.ExecuteCode += new System.EventHandler(this.MissingActiveLanguageCodeActivity_ExecuteCode); // // ifElse_CheckPageTypesExists // this.ifElse_CheckPageTypesExists.Activities.Add(this.ifElseBranchActivity11); this.ifElse_CheckPageTypesExists.Activities.Add(this.ifElseBranchActivity12); this.ifElse_CheckPageTypesExists.Name = "ifElse_CheckPageTypesExists"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "step1State"; // // setStateActivity_GoToFinalize // this.setStateActivity_GoToFinalize.Name = "setStateActivity_GoToFinalize"; this.setStateActivity_GoToFinalize.TargetStateName = "finalizeActivity"; // // PresetCalculatedFields // this.PresetCalculatedFields.Name = "PresetCalculatedFields"; this.PresetCalculatedFields.ExecuteCode += new System.EventHandler(this.PresetCalculatedFields_ExecuteCode); // // ifElseBranchActivity6 // this.ifElseBranchActivity6.Activities.Add(this.MissingActiveLanguageCodeActivity); this.ifElseBranchActivity6.Activities.Add(this.setStateActivity6); this.ifElseBranchActivity6.Name = "ifElseBranchActivity6"; // // ifElseBranchActivity5 // this.ifElseBranchActivity5.Activities.Add(this.ifElse_CheckPageTypesExists); codecondition3.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckActiveLanguagesExists); this.ifElseBranchActivity5.Condition = codecondition3; this.ifElseBranchActivity5.Name = "ifElseBranchActivity5"; // // ifElseBranchActivity10 // this.ifElseBranchActivity10.Activities.Add(this.setStateActivity7); this.ifElseBranchActivity10.Name = "ifElseBranchActivity10"; // // ifElseBranchActivity9 // this.ifElseBranchActivity9.Activities.Add(this.PresetCalculatedFields); this.ifElseBranchActivity9.Activities.Add(this.setStateActivity_GoToFinalize); codecondition4.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateUrlTitle); this.ifElseBranchActivity9.Condition = codecondition4; this.ifElseBranchActivity9.Name = "ifElseBranchActivity9"; // // setStateActivity20 // this.setStateActivity20.Name = "setStateActivity20"; this.setStateActivity20.TargetStateName = "finishState"; // // MissingTemplateAlertActivity // this.MissingTemplateAlertActivity.Name = "MissingTemplateAlertActivity"; this.MissingTemplateAlertActivity.ExecuteCode += new System.EventHandler(this.MissingTemplateAlertActivity_ExecuteCode); // // ifElse_CheckActiveLanguagesExists // this.ifElse_CheckActiveLanguagesExists.Activities.Add(this.ifElseBranchActivity5); this.ifElse_CheckActiveLanguagesExists.Activities.Add(this.ifElseBranchActivity6); this.ifElse_CheckActiveLanguagesExists.Name = "ifElse_CheckActiveLanguagesExists"; // // setStateActivity_GoToStep2 // this.setStateActivity_GoToStep2.Name = "setStateActivity_GoToStep2"; this.setStateActivity_GoToStep2.TargetStateName = "step2State"; // // ifElseActivity4_ValidateUrlTitle // this.ifElseActivity4_ValidateUrlTitle.Activities.Add(this.ifElseBranchActivity9); this.ifElseActivity4_ValidateUrlTitle.Activities.Add(this.ifElseBranchActivity10); this.ifElseActivity4_ValidateUrlTitle.Description = "ValidateUrlTitle"; this.ifElseActivity4_ValidateUrlTitle.Name = "ifElseActivity4_ValidateUrlTitle"; // // ifElseBranchActivity8 // this.ifElseBranchActivity8.Activities.Add(this.MissingTemplateAlertActivity); this.ifElseBranchActivity8.Activities.Add(this.setStateActivity20); this.ifElseBranchActivity8.Name = "ifElseBranchActivity8"; // // ifElseBranchActivity7 // this.ifElseBranchActivity7.Activities.Add(this.ifElse_CheckActiveLanguagesExists); codecondition5.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckTemplatesExists); this.ifElseBranchActivity7.Condition = codecondition5; this.ifElseBranchActivity7.Name = "ifElseBranchActivity7"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity_GoToStep2); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.ifElseActivity4_ValidateUrlTitle); codecondition6.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CanSkipStep2); this.ifElseBranchActivity3.Condition = codecondition6; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // setStateActivity11 // this.setStateActivity11.Name = "setStateActivity11"; this.setStateActivity11.TargetStateName = "finishState"; // // ifElse_CheckTemplatesExists // this.ifElse_CheckTemplatesExists.Activities.Add(this.ifElseBranchActivity7); this.ifElse_CheckTemplatesExists.Activities.Add(this.ifElseBranchActivity8); this.ifElse_CheckTemplatesExists.Name = "ifElse_CheckTemplatesExists"; // // setStateActivity14 // this.setStateActivity14.Name = "setStateActivity14"; this.setStateActivity14.TargetStateName = "step1State"; // // ifElseActivity_CanSkipStep2 // this.ifElseActivity_CanSkipStep2.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity_CanSkipStep2.Activities.Add(this.ifElseBranchActivity4); this.ifElseActivity_CanSkipStep2.Name = "ifElseActivity_CanSkipStep2"; // // setStateActivity13 // this.setStateActivity13.Name = "setStateActivity13"; this.setStateActivity13.TargetStateName = "step1State"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "step2State"; // // setStateActivity_redoStep2 // this.setStateActivity_redoStep2.Name = "setStateActivity_redoStep2"; this.setStateActivity_redoStep2.TargetStateName = "step2State"; // // setStateActivity12 // this.setStateActivity12.Name = "setStateActivity12"; this.setStateActivity12.TargetStateName = "finalizeActivity"; // // ifElseBranchActivity16 // this.ifElseBranchActivity16.Activities.Add(this.setStateActivity11); this.ifElseBranchActivity16.Name = "ifElseBranchActivity16"; // // ifElseCheckPageTypesExist // this.ifElseCheckPageTypesExist.Activities.Add(this.ifElse_CheckTemplatesExists); codecondition7.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckPageTypesExist); this.ifElseCheckPageTypesExist.Condition = codecondition7; this.ifElseCheckPageTypesExist.Name = "ifElseCheckPageTypesExist"; // // ifElseBranchActivity19 // this.ifElseBranchActivity19.Activities.Add(this.setStateActivity14); this.ifElseBranchActivity19.Name = "ifElseBranchActivity19"; // // ifElseBranchActivity18 // this.ifElseBranchActivity18.Activities.Add(this.ifElseActivity_CanSkipStep2); codecondition8.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateFirstPage); this.ifElseBranchActivity18.Condition = codecondition8; this.ifElseBranchActivity18.Name = "ifElseBranchActivity18"; // // ifElseBranchActivity17 // this.ifElseBranchActivity17.Activities.Add(this.setStateActivity13); this.ifElseBranchActivity17.Name = "ifElseBranchActivity17"; // // ifElseBranchActivity15 // this.ifElseBranchActivity15.Activities.Add(this.setStateActivity3); codecondition9.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateFirstPage); this.ifElseBranchActivity15.Condition = codecondition9; this.ifElseBranchActivity15.Name = "ifElseBranchActivity15"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity_redoStep2); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity12); codecondition10.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateUrlTitle); this.ifElseBranchActivity1.Condition = codecondition10; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseCheckPageTypesExist); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity16); this.ifElseActivity1.Name = "ifElseActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // ifElse_FirstPageValid // this.ifElse_FirstPageValid.Activities.Add(this.ifElseBranchActivity18); this.ifElse_FirstPageValid.Activities.Add(this.ifElseBranchActivity19); this.ifElse_FirstPageValid.Name = "ifElse_FirstPageValid"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // ifFirstPageValid // this.ifFirstPageValid.Activities.Add(this.ifElseBranchActivity15); this.ifFirstPageValid.Activities.Add(this.ifElseBranchActivity17); this.ifFirstPageValid.Name = "ifFirstPageValid"; // // nextHandleExternalEventActivity1 // this.nextHandleExternalEventActivity1.EventName = "Next"; this.nextHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity1.Name = "nextHandleExternalEventActivity1"; // // step1WizzardFormActivity // this.step1WizzardFormActivity.ContainerLabel = "Add new"; this.step1WizzardFormActivity.FormDefinitionFileName = "\\Administrative\\AddNewPageStep1.xml"; this.step1WizzardFormActivity.Name = "step1WizzardFormActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finishState"; // // stepFinalize_codeActivity // this.stepFinalize_codeActivity.Name = "stepFinalize_codeActivity"; this.stepFinalize_codeActivity.ExecuteCode += new System.EventHandler(this.stepFinalize_codeActivity_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // ifElseActivity__ValidateUrlTitle // this.ifElseActivity__ValidateUrlTitle.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity__ValidateUrlTitle.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity__ValidateUrlTitle.Name = "ifElseActivity__ValidateUrlTitle"; // // handleExternalEventActivity5 // this.handleExternalEventActivity5.EventName = "Finish"; this.handleExternalEventActivity5.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.handleExternalEventActivity5.Name = "handleExternalEventActivity5"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "step1State"; // // handleExternalEventActivity2 // this.handleExternalEventActivity2.EventName = "Previous"; this.handleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.handleExternalEventActivity2.Name = "handleExternalEventActivity2"; // // step2WizzardFormActivity // this.step2WizzardFormActivity.ContainerLabel = "Add new"; this.step2WizzardFormActivity.FormDefinitionFileName = "\\Administrative\\AddNewPageStep2.xml"; this.step2WizzardFormActivity.Name = "step2WizzardFormActivity"; // // PrepareStep2 // this.PrepareStep2.Name = "PrepareStep2"; this.PrepareStep2.ExecuteCode += new System.EventHandler(this.PrepareStep2_ExecuteCode); // // setStateActivity19 // this.setStateActivity19.Name = "setStateActivity19"; this.setStateActivity19.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.ifElseActivity1); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // step1_eventDrivenActivity_Cancel // this.step1_eventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1_eventDrivenActivity_Cancel.Activities.Add(this.setStateActivity2); this.step1_eventDrivenActivity_Cancel.Name = "step1_eventDrivenActivity_Cancel"; // // step1_eventDrivenActivity_Finish // this.step1_eventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1_eventDrivenActivity_Finish.Activities.Add(this.ifElse_FirstPageValid); this.step1_eventDrivenActivity_Finish.Name = "step1_eventDrivenActivity_Finish"; // // step1_eventDrivenActivity_Next // this.step1_eventDrivenActivity_Next.Activities.Add(this.nextHandleExternalEventActivity1); this.step1_eventDrivenActivity_Next.Activities.Add(this.ifFirstPageValid); this.step1_eventDrivenActivity_Next.Name = "step1_eventDrivenActivity_Next"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1WizzardFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.stepFinalize_codeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity1); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step2_eventDrivenActivity_Cancel // this.step2_eventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.step2_eventDrivenActivity_Cancel.Activities.Add(this.setStateActivity5); this.step2_eventDrivenActivity_Cancel.Name = "step2_eventDrivenActivity_Cancel"; // // step2_eventDrivenActivity_Finish // this.step2_eventDrivenActivity_Finish.Activities.Add(this.handleExternalEventActivity5); this.step2_eventDrivenActivity_Finish.Activities.Add(this.ifElseActivity__ValidateUrlTitle); this.step2_eventDrivenActivity_Finish.Name = "step2_eventDrivenActivity_Finish"; // // step2_eventDrivenActivity_Previous // this.step2_eventDrivenActivity_Previous.Activities.Add(this.handleExternalEventActivity2); this.step2_eventDrivenActivity_Previous.Activities.Add(this.setStateActivity8); this.step2_eventDrivenActivity_Previous.Name = "step2_eventDrivenActivity_Previous"; // // step2StateInitializationActivity // this.step2StateInitializationActivity.Activities.Add(this.PrepareStep2); this.step2StateInitializationActivity.Activities.Add(this.step2WizzardFormActivity); this.step2StateInitializationActivity.Name = "step2StateInitializationActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity19); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // initializeActivity // this.initializeActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeActivity.Name = "initializeActivity"; // // step1State // this.step1State.Activities.Add(this.step1StateInitializationActivity); this.step1State.Activities.Add(this.step1_eventDrivenActivity_Next); this.step1State.Activities.Add(this.step1_eventDrivenActivity_Finish); this.step1State.Activities.Add(this.step1_eventDrivenActivity_Cancel); this.step1State.Name = "step1State"; // // finalizeActivity // this.finalizeActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeActivity.Name = "finalizeActivity"; // // finishState // this.finishState.Name = "finishState"; // // step2State // this.step2State.Activities.Add(this.step2StateInitializationActivity); this.step2State.Activities.Add(this.step2_eventDrivenActivity_Previous); this.step2State.Activities.Add(this.step2_eventDrivenActivity_Finish); this.step2State.Activities.Add(this.step2_eventDrivenActivity_Cancel); this.step2State.Name = "step2State"; // // AddNewPageWorkflow // this.Activities.Add(this.step2State); this.Activities.Add(this.finishState); this.Activities.Add(this.finalizeActivity); this.Activities.Add(this.step1State); this.Activities.Add(this.initializeActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.CompletedStateName = "finishState"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeActivity"; this.Name = "AddNewPageWorkflow"; this.CanModifyActivities = false; } #endregion private StateInitializationActivity step1StateInitializationActivity; private EventDrivenActivity step1_eventDrivenActivity_Next; private StateInitializationActivity step2StateInitializationActivity; private StateActivity step2State; private EventDrivenActivity step2_eventDrivenActivity_Previous; private HandleExternalEventActivity handleExternalEventActivity2; private SetStateActivity setStateActivity8; private SetStateActivity setStateActivity3; private EventDrivenActivity step2_eventDrivenActivity_Finish; private StateActivity finishState; private HandleExternalEventActivity handleExternalEventActivity5; private StateActivity finalizeActivity; private StateInitializationActivity finalizeStateInitializationActivity; private CodeActivity stepFinalize_codeActivity; private SetStateActivity setStateActivity4; private StateInitializationActivity initializeStateInitializationActivity; private StateActivity initializeActivity; private CodeActivity stepInitialize_codeActivity; private SetStateActivity setStateActivity12; private C1Console.Workflow.Activities.WizardFormActivity step1WizzardFormActivity; private C1Console.Workflow.Activities.WizardFormActivity step2WizzardFormActivity; private SetStateActivity setStateActivity1; private SetStateActivity setStateActivity19; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private IfElseBranchActivity ifElseBranchActivity8; private IfElseBranchActivity ifElseBranchActivity7; private IfElseActivity ifElse_CheckTemplatesExists; private CodeActivity MissingTemplateAlertActivity; private SetStateActivity setStateActivity20; private SetStateActivity setStateActivity_redoStep2; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity__ValidateUrlTitle; private EventDrivenActivity step1_eventDrivenActivity_Finish; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElseActivity_CanSkipStep2; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity_GoToStep2; private SetStateActivity setStateActivity_GoToFinalize; private CodeActivity PresetCalculatedFields; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity5; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private EventDrivenActivity step1_eventDrivenActivity_Cancel; private EventDrivenActivity step2_eventDrivenActivity_Cancel; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private IfElseBranchActivity ifElseBranchActivity6; private IfElseBranchActivity ifElseBranchActivity5; private IfElseActivity ifElse_CheckActiveLanguagesExists; private CodeActivity MissingActiveLanguageCodeActivity; private SetStateActivity setStateActivity6; private SetStateActivity setStateActivity7; private IfElseBranchActivity ifElseBranchActivity10; private IfElseBranchActivity ifElseBranchActivity9; private IfElseActivity ifElseActivity4_ValidateUrlTitle; private CodeActivity PrepareStep2; private SetStateActivity setStateActivity9; private CodeActivity MissingPageTypeCodeActivity; private IfElseBranchActivity ifElseBranchActivity12; private IfElseBranchActivity ifElseBranchActivity11; private IfElseActivity ifElse_CheckPageTypesExists; private IfElseBranchActivity ifElseBranchActivity14; private IfElseBranchActivity ifElseBranchActivity13; private IfElseActivity ifElse_RulesDontAllowPageAdd; private SetStateActivity setStateActivity10; private CodeActivity RuleDontAllowPageAddCodeActivity; private SetStateActivity setStateActivity11; private IfElseBranchActivity ifElseBranchActivity16; private IfElseBranchActivity ifElseCheckPageTypesExist; private IfElseActivity ifElseActivity1; private SetStateActivity setStateActivity13; private IfElseBranchActivity ifElseBranchActivity17; private IfElseBranchActivity ifElseBranchActivity15; private IfElseActivity ifFirstPageValid; private C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity1; private SetStateActivity setStateActivity14; private IfElseBranchActivity ifElseBranchActivity19; private IfElseBranchActivity ifElseBranchActivity18; private IfElseActivity ifElse_FirstPageValid; private StateActivity step1State; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/AddNewPageWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Core.PageTemplates; using Composite.Core.Routing.Foundation.PluginFacades; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.Types; using Composite.Data.Validation; using Composite.Core.ResourceSystem; using Composite.Core.Extensions; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.Core.Serialization; using Microsoft.Practices.EnterpriseLibrary.Validation; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewPageWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { [NonSerialized] private List<IPageType> _selectablePageTypes; private static class SortOrder { internal static string Bottom = "Bottom"; internal static string Top = "Top"; internal static string Relative = "Relative"; internal static string Alphabetic = "Alphabetic"; } public AddNewPageWorkflow() { InitializeComponent(); } private Guid GetParentId() { if (this.EntityToken is PageElementProviderEntityToken) { return Guid.Empty; } if (this.EntityToken is DataEntityToken dataEntityToken) { IPage selectedPage = (IPage)dataEntityToken.Data; return selectedPage.Id; } throw new NotSupportedException(); } private List<IPageType> GetSelectablePageTypes() { if (_selectablePageTypes == null) { if (this.EntityToken is PageElementProviderEntityToken) { _selectablePageTypes = DataFacade.GetData<IPageType>(). Where(f => f.Available && (f.HomepageRelation != PageTypeHomepageRelation.OnlySubPages.ToString())). OrderBy(f => f.Name). ToList(); } else { IPage page = this.GetDataItemFromEntityToken<IPage>(); _selectablePageTypes = page.GetChildPageSelectablePageTypes().ToList(); } } return _selectablePageTypes; } private Guid? GetDefaultPageTypeId(ICollection<IPageType> selectablePageTypes) { if (!string.IsNullOrEmpty(Payload)) { return ((IPage)SerializerHandlerFacade.Deserialize(Payload)).PageTypeId; } if (!(this.EntityToken is PageElementProviderEntityToken)) { IPage parentPage = this.GetDataItemFromEntityToken<IPage>(); IPageType parentPageType = DataFacade.GetData<IPageType>().FirstOrDefault(f => f.Id == parentPage.PageTypeId); if (parentPageType != null && parentPageType.DefaultChildPageType != Guid.Empty) { if (selectablePageTypes.Any(f => f.Id == parentPageType.DefaultChildPageType)) { return parentPageType.DefaultChildPageType; } } } return selectablePageTypes.FirstOrDefault()?.Id; } private void MissingTemplateAlertActivity_ExecuteCode(object sender, EventArgs e) { ShowMessage( DialogType.Message, GetText("PageElementProvider.MissingTemplateTitle"), GetText("PageElementProvider.MissingTemplateMessage")); } private void MissingActiveLanguageCodeActivity_ExecuteCode(object sender, EventArgs e) { ShowMessage( DialogType.Message, GetText("PageElementProvider.MissingActiveLanguageTitle"), GetText("PageElementProvider.MissingActiveLanguageMessage")); } private void MissingPageTypeCodeActivity_ExecuteCode(object sender, EventArgs e) { if (this.EntityToken is PageElementProviderEntityToken) { ShowMessage( DialogType.Message, GetText("PageElementProvider.MissingPageTypeTitle"), GetText("PageElementProvider.MissingPageTypeHomepageMessage")); } else { ShowMessage( DialogType.Message, GetText("PageElementProvider.MissingPageTypeTitle"), GetText("PageElementProvider.MissingPageTypeSubpageMessage")); } } private void RuleDontAllowPageAddCodeActivity_ExecuteCode(object sender, EventArgs e) { ShowMessage( DialogType.Message, GetText("PageElementProvider.RuleDontAllowPageAddTitle"), GetText("PageElementProvider.RuleDontAllowPageAddMessage")); } private static string GetText(string key) { return StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", key); } private void CheckTemplatesExists(object sender, ConditionalEventArgs e) { e.Result = PageTemplateFacade.ValidTemplateExists; } private void CheckActiveLanguagesExists(object sender, ConditionalEventArgs e) { e.Result = UserSettings.ActiveLocaleCultureInfo != null; } private void CheckPageTypeExists(object sender, ConditionalEventArgs e) { PageTypeHomepageRelation relationToExclude; if (this.EntityToken is PageElementProviderEntityToken) { relationToExclude = PageTypeHomepageRelation.OnlySubPages; } else { relationToExclude = PageTypeHomepageRelation.OnlyHomePages; } e.Result = DataFacade.GetData<IPageType>() .Any(f => f.Available && f.HomepageRelation != relationToExclude.ToString()); } private void CheckRulesAllowPageAddExists(object sender, ConditionalEventArgs e) { e.Result = GetSelectablePageTypes().Count > 0; } private void CheckPageTypesExist(object sender, ConditionalEventArgs e) { e.Result = GetSelectablePageTypes().Any(); if (!e.Result) { ShowMessage(DialogType.Error, GetText("PageElementProvider.NoPageTypesAvailableTitle"), GetText("PageElementProvider.NoPageTypesAvailableMessage")); } } private bool ThereAreOtherPages() { foreach (var cultureInfo in DataLocalizationFacade.ActiveLocalizationCultures) { using (new DataScope(PublicationScope.Unpublished, cultureInfo)) { if (DataFacade.GetData<IPageStructure>().Any()) { return true; } } } return false; } private void stepInitialize_codeActivity_ExecuteCode(object sender, EventArgs e) { Guid templateId; if (this.EntityToken is PageElementProviderEntityToken) { templateId = PageTemplateFacade.GetPageTemplates().Select(t => t.Id).FirstOrDefault(); } else if (this.EntityToken is DataEntityToken dataEntityToken) { IPage selectedPage = (IPage)dataEntityToken.Data; templateId = selectedPage.TemplateId; } else { throw new NotSupportedException(); } List<IPageType> selectablePageTypes = GetSelectablePageTypes(); Guid? pageTypeId = GetDefaultPageTypeId(selectablePageTypes); Verify.That(pageTypeId.HasValue, "Failed to get a page type"); Guid parentId = GetParentId(); string pageType = selectablePageTypes.First(f => f.Id == pageTypeId).Name; IPage newPage = DataFacade.BuildNew<IPage>(); newPage.Id = Guid.NewGuid(); newPage.TemplateId = templateId; newPage.PageTypeId = pageTypeId.Value; newPage.Title = ""; newPage.MenuTitle = ""; newPage.UrlTitle = ""; newPage.FriendlyUrl = ""; newPage.PublicationStatus = GenericPublishProcessController.Draft; int existingPagesCount = PageServices.GetChildrenCount(parentId); var sortOrder = new Dictionary<string, string> { {SortOrder.Bottom, GetText("AddNewPageStep1.LabelAddToBottom")} }; if (existingPagesCount > 0) { sortOrder.Add(SortOrder.Top, GetText("AddNewPageStep1.LabelAddToTop")); if (existingPagesCount > 1) { sortOrder.Add(SortOrder.Relative, GetText("AddNewPageStep1.LabelAddBelowOtherPage")); } bool isAlpabeticOrdered = PageServices.IsChildrenAlphabeticOrdered(parentId); if (isAlpabeticOrdered) { sortOrder.Add(SortOrder.Alphabetic, GetText("AddNewPageStep1.LabelAddAlphabetic")); } } var bindings = new Dictionary<string, object> { {"NewPage", newPage}, {"Title", string.Format(GetText("AddNewPageStep1.DialogLabelFormat"), pageType)}, {"UrlTitleIsRequired", true}, {"SortOrder", sortOrder}, {"SelectedSortOrder", sortOrder.Keys.First()} }; if (parentId == Guid.Empty) { bindings.Add("ShowCulture", true); bindings.Add("Cultures", DataLocalizationFacade.WhiteListedLocales .Select(f => new KeyValuePair<string, string>(f.Name, DataLocalizationFacade.GetCultureTitle(f))).ToList()); } else { bindings.Add("ShowCulture", false); } this.Bindings = bindings; } private void CanSkipStep2(object sender, ConditionalEventArgs e) { IPage newPage = this.GetBinding<IPage>("NewPage"); var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(typeof(IPage)); e.Result = this.GetBinding<string>("SelectedSortOrder") != SortOrder.Relative && UrlTitleIsUniqueAmongSiblings() && newPage.UrlTitle.Length <= dataTypeDescriptor.Fields["UrlTitle"].StoreType.MaximumLength && newPage.MenuTitle.Length <= dataTypeDescriptor.Fields["MenuTitle"].StoreType.MaximumLength; } private void ValidateUrlTitle(object sender, ConditionalEventArgs e) { IPage newPage = this.GetBinding<IPage>("NewPage"); if (this.CurrentStateName == "step1State") { SetDefaultValues(newPage); } e.Result = true; if (!UrlTitleIsUniqueAmongSiblings()) { string fieldName = "NewPage.UrlTitle"; if (this.CurrentStateName == "step1State") { fieldName = "NewPage.Title"; } this.ShowFieldMessage(fieldName, GetText("UrlTitleNotUniqueError")); e.Result = false; } else { ValidationResults validationResults = ValidationFacade.Validate<IPage>(newPage); if (!validationResults.IsValid && validationResults.Any(f => f.Key == "UrlTitle")) { this.ShowFieldMessage("NewPage.Title", "${Composite.Plugins.PageElementProvider, UrlTitleNotValidError}"); e.Result = false; } } var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(typeof(IPage)); if (newPage.UrlTitle.Length > dataTypeDescriptor.Fields["UrlTitle"].StoreType.MaximumLength) { this.ShowFieldMessage("NewPage.UrlTitle", GetText("UrlTitleTooLong")); e.Result = false; return; } if (newPage.MenuTitle.Length > dataTypeDescriptor.Fields["MenuTitle"].StoreType.MaximumLength) { this.ShowFieldMessage("NewPage.MenuTitle", GetText("AddNewPageStep1.MenuTitleTooLong")); e.Result = false; return; } } private bool UrlTitleIsUniqueAmongSiblings() { IPage newPage = this.GetBinding<IPage>("NewPage"); var siblingPageUrlTitles = (from page in PageServices.GetChildren(GetParentId()) select page.UrlTitle).ToList(); if (string.IsNullOrEmpty(newPage.UrlTitle) && ThereAreOtherPages()) { newPage.UrlTitle = GenerateUrlTitleFromTitle(newPage.Title); if (string.IsNullOrEmpty(newPage.UrlTitle)) { return false; } } return !siblingPageUrlTitles.Any(urlTitle => urlTitle.Equals(newPage.UrlTitle, StringComparison.InvariantCultureIgnoreCase)); } private void PrepareStep2_ExecuteCode(object sender, EventArgs e) { IPage newPage = this.GetBinding<IPage>("NewPage"); SetDefaultValues(newPage); if (this.GetBinding<string>("SelectedSortOrder") == SortOrder.Relative) { Dictionary<Guid, string> existingPages = PageServices.GetChildren(GetParentId()) .GroupBy(page => page.Id) .Select(group => group.First()) .ToDictionary(page => page.Id, page => page.Title); this.Bindings["ExistingPages"] = existingPages; this.Bindings["RelativeSelectedPageId"] = existingPages.First().Key; } else { this.Bindings.Remove("ExistingPages"); this.Bindings.Remove("RelativeSelectedPageId"); } } private void stepFinalize_codeActivity_ExecuteCode(object sender, EventArgs e) { AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken); IPage newPage = this.GetBinding<IPage>("NewPage"); newPage.SourceCultureName = UserSettings.ActiveLocaleCultureInfo.Name; Guid pageTypeId = newPage.PageTypeId; Guid? defaultPageTemplateId = PageServices.GetDefaultPageTemplateId(pageTypeId); if (defaultPageTemplateId != null) { newPage.TemplateId = defaultPageTemplateId.Value; } string sortOrder = this.GetBinding<string>("SelectedSortOrder"); Guid parentId = GetParentId(); using (new DataScope(DataScopeIdentifier.Administrated)) { IPageInsertionPosition position; if (sortOrder == SortOrder.Top) { position = PageInsertPosition.Top; } else if (sortOrder == SortOrder.Bottom) { position = PageInsertPosition.Bottom; } else if (sortOrder == SortOrder.Alphabetic) { position = PageInsertPosition.Alphabetic; } else if (sortOrder == SortOrder.Relative) { Guid relativeSelectedPageId = this.GetBinding<Guid>("RelativeSelectedPageId"); position = PageInsertPosition.After(relativeSelectedPageId); } else { throw new InvalidOperationException($"Not handled page insert position '{sortOrder}'"); } newPage = newPage.Add(parentId, position); } SetSaveStatus(true); addNewTreeRefresher.PostRefreshMesseges(newPage.GetDataEntityToken()); this.ExecuteWorklow(newPage.GetDataEntityToken(), typeof(EditPageWorkflow)); } private string GenerateUrlTitleFromTitle(string title) { return UrlFormattersPluginFacade.FormatUrl(title.Trim(), false); } private void PresetCalculatedFields_ExecuteCode(object sender, EventArgs e) { IPage newPage = this.GetBinding<IPage>("NewPage"); SetDefaultValues(newPage); } /// <summary> /// Sets default values for "MenuTitle" and "UrlTitle" fields if they were not set. /// </summary> /// <param name="page">The page.</param> private void SetDefaultValues(IPage page) { IPage newPage = this.GetBinding<IPage>("NewPage"); IPageType selectedPageType = DataFacade.GetData<IPageType>().Single(f => f.Id == newPage.PageTypeId); if (selectedPageType.PresetMenuTitle && page.MenuTitle.IsNullOrEmpty()) { page.MenuTitle = page.Title; } if (page.UrlTitle.IsNullOrEmpty()) { page.UrlTitle = GenerateUrlTitleFromTitle(page.Title); int i = 2; while (!UrlTitleIsUniqueAmongSiblings()) { page.UrlTitle = $"{GenerateUrlTitleFromTitle(page.Title)}{i}"; i++; } } } private void ValidateFirstPage(object sender, ConditionalEventArgs e) { IPage newPage = this.GetBinding<IPage>("NewPage"); var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(typeof(IPage)); if (newPage.Title.Length > dataTypeDescriptor.Fields["Title"].StoreType.MaximumLength) { this.ShowFieldMessage("NewPage.Title", GetText("AddNewPageStep1.TitleTooLong")); e.Result = false; return; } e.Result = true; } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/AddNewPageWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1144; 946" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="AddNewPageWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finishState" TargetConnectionEdge="Top" SetStateName="setStateActivity19" SourceActivity="AddNewPageWorkflow" TargetConnectionIndex="0" SourceStateName="AddNewPageWorkflow" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finishState"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1064" Y="71" /> <ns0:Point X="1064" Y="866" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1State" TargetConnectionEdge="Bottom" SetStateName="setStateActivity8" SourceActivity="step2State" TargetConnectionIndex="0" SourceStateName="step2State" SourceConnectionEdge="Left" EventHandlerName="step2_eventDrivenActivity_Previous" SourceConnectionIndex="1" TargetStateName="step1State"> <StateDesignerConnector.Segments> <ns0:Point X="451" Y="530" /> <ns0:Point X="261" Y="530" /> <ns0:Point X="261" Y="391" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity12" SourceActivity="step2State" TargetConnectionIndex="0" SourceStateName="step2State" SourceConnectionEdge="Right" EventHandlerName="step2_eventDrivenActivity_Finish" SourceConnectionIndex="2" TargetStateName="finalizeActivity"> <StateDesignerConnector.Segments> <ns0:Point X="656" Y="554" /> <ns0:Point X="682" Y="554" /> <ns0:Point X="682" Y="744" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step2State" TargetConnectionEdge="Bottom" SetStateName="setStateActivity_redoStep2" SourceActivity="step2State" TargetConnectionIndex="0" SourceStateName="step2State" SourceConnectionEdge="Right" EventHandlerName="step2_eventDrivenActivity_Finish" SourceConnectionIndex="2" TargetStateName="step2State"> <StateDesignerConnector.Segments> <ns0:Point X="656" Y="554" /> <ns0:Point X="680" Y="554" /> <ns0:Point X="680" Y="599" /> <ns0:Point X="560" Y="599" /> <ns0:Point X="560" Y="591" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finishState" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceActivity="step2State" TargetConnectionIndex="0" SourceStateName="step2State" SourceConnectionEdge="Right" EventHandlerName="step2_eventDrivenActivity_Cancel" SourceConnectionIndex="3" TargetStateName="finishState"> <StateDesignerConnector.Segments> <ns0:Point X="660" Y="578" /> <ns0:Point X="1064" Y="578" /> <ns0:Point X="1064" Y="866" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finishState" TargetConnectionEdge="Bottom" SetStateName="setStateActivity1" SourceActivity="finalizeActivity" TargetConnectionIndex="0" SourceStateName="finalizeActivity" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finishState"> <StateDesignerConnector.Segments> <ns0:Point X="781" Y="785" /> <ns0:Point X="797" Y="785" /> <ns0:Point X="797" Y="954" /> <ns0:Point X="1064" Y="954" /> <ns0:Point X="1064" Y="946" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step2State" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="step1State" TargetConnectionIndex="0" SourceStateName="step1State" SourceConnectionEdge="Right" EventHandlerName="step1_eventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="step2State"> <StateDesignerConnector.Segments> <ns0:Point X="356" Y="330" /> <ns0:Point X="560" Y="330" /> <ns0:Point X="560" Y="465" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1State" TargetConnectionEdge="Top" SetStateName="setStateActivity13" SourceActivity="step1State" TargetConnectionIndex="0" SourceStateName="step1State" SourceConnectionEdge="Right" EventHandlerName="step1_eventDrivenActivity_Next" SourceConnectionIndex="1" TargetStateName="step1State"> <StateDesignerConnector.Segments> <ns0:Point X="366" Y="169" /> <ns0:Point X="391" Y="169" /> <ns0:Point X="391" Y="96" /> <ns0:Point X="271" Y="96" /> <ns0:Point X="271" Y="104" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1State" TargetConnectionEdge="Top" SetStateName="setStateActivity14" SourceActivity="step1State" TargetConnectionIndex="0" SourceStateName="step1State" SourceConnectionEdge="Right" EventHandlerName="step1_eventDrivenActivity_Finish" SourceConnectionIndex="2" TargetStateName="step1State"> <StateDesignerConnector.Segments> <ns0:Point X="372" Y="193" /> <ns0:Point X="391" Y="193" /> <ns0:Point X="391" Y="96" /> <ns0:Point X="271" Y="96" /> <ns0:Point X="271" Y="104" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1State" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceActivity="step1State" TargetConnectionIndex="0" SourceStateName="step1State" SourceConnectionEdge="Right" EventHandlerName="step1_eventDrivenActivity_Finish" SourceConnectionIndex="2" TargetStateName="step1State"> <StateDesignerConnector.Segments> <ns0:Point X="372" Y="193" /> <ns0:Point X="391" Y="193" /> <ns0:Point X="391" Y="96" /> <ns0:Point X="271" Y="96" /> <ns0:Point X="271" Y="104" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity_GoToFinalize" SourceActivity="step1State" TargetConnectionIndex="0" SourceStateName="step1State" SourceConnectionEdge="Right" EventHandlerName="step1_eventDrivenActivity_Finish" SourceConnectionIndex="2" TargetStateName="finalizeActivity"> <StateDesignerConnector.Segments> <ns0:Point X="362" Y="354" /> <ns0:Point X="682" Y="354" /> <ns0:Point X="682" Y="744" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step2State" TargetConnectionEdge="Top" SetStateName="setStateActivity_GoToStep2" SourceActivity="step1State" TargetConnectionIndex="0" SourceStateName="step1State" SourceConnectionEdge="Right" EventHandlerName="step1_eventDrivenActivity_Finish" SourceConnectionIndex="2" TargetStateName="step2State"> <StateDesignerConnector.Segments> <ns0:Point X="362" Y="354" /> <ns0:Point X="560" Y="354" /> <ns0:Point X="560" Y="465" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finishState" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="step1State" TargetConnectionIndex="0" SourceStateName="step1State" SourceConnectionEdge="Right" EventHandlerName="step1_eventDrivenActivity_Cancel" SourceConnectionIndex="3" TargetStateName="finishState"> <StateDesignerConnector.Segments> <ns0:Point X="366" Y="378" /> <ns0:Point X="1064" Y="378" /> <ns0:Point X="1064" Y="866" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finishState" TargetConnectionEdge="Top" SetStateName="setStateActivity11" SourceActivity="initializeActivity" TargetConnectionIndex="0" SourceStateName="initializeActivity" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finishState"> <StateDesignerConnector.Segments> <ns0:Point X="265" Y="164" /> <ns0:Point X="1064" Y="164" /> <ns0:Point X="1064" Y="866" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finishState" TargetConnectionEdge="Top" SetStateName="setStateActivity20" SourceActivity="initializeActivity" TargetConnectionIndex="0" SourceStateName="initializeActivity" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finishState"> <StateDesignerConnector.Segments> <ns0:Point X="265" Y="164" /> <ns0:Point X="1064" Y="164" /> <ns0:Point X="1064" Y="866" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finishState" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceActivity="initializeActivity" TargetConnectionIndex="0" SourceStateName="initializeActivity" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finishState"> <StateDesignerConnector.Segments> <ns0:Point X="265" Y="164" /> <ns0:Point X="1064" Y="164" /> <ns0:Point X="1064" Y="866" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finishState" TargetConnectionEdge="Top" SetStateName="setStateActivity9" SourceActivity="initializeActivity" TargetConnectionIndex="0" SourceStateName="initializeActivity" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finishState"> <StateDesignerConnector.Segments> <ns0:Point X="265" Y="164" /> <ns0:Point X="1064" Y="164" /> <ns0:Point X="1064" Y="866" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1State" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="initializeActivity" TargetConnectionIndex="0" SourceStateName="initializeActivity" SourceConnectionEdge="Left" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1State"> <StateDesignerConnector.Segments> <ns0:Point X="63" Y="164" /> <ns0:Point X="53" Y="164" /> <ns0:Point X="53" Y="253" /> <ns0:Point X="261" Y="253" /> <ns0:Point X="261" Y="265" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finishState" TargetConnectionEdge="Top" SetStateName="setStateActivity10" SourceActivity="initializeActivity" TargetConnectionIndex="0" SourceStateName="initializeActivity" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finishState"> <StateDesignerConnector.Segments> <ns0:Point X="265" Y="164" /> <ns0:Point X="1064" Y="164" /> <ns0:Point X="1064" Y="866" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="226; 126" AutoSizeMargin="16; 24" Location="447; 465" Name="step2State"> <StateDesigner.Designers> <StateInitializationDesigner Name="step2StateInitializationActivity" Size="150; 182" Location="455; 496"> <StateInitializationDesigner.Designers> <CodeDesigner Name="PrepareStep2" Size="130; 41" Location="465; 558" /> <ActivityDesigner Name="step2WizzardFormActivity" Size="130; 41" Location="465; 618" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step2_eventDrivenActivity_Previous" Size="150; 182" Location="455; 520"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="handleExternalEventActivity2" Size="130; 41" Location="465; 582" /> <SetStateDesigner Name="setStateActivity8" Size="130; 41" Location="465; 642" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step2_eventDrivenActivity_Finish" Size="381; 375" Location="455; 544"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="handleExternalEventActivity5" Size="130; 41" Location="580; 606" /> <IfElseDesigner Name="ifElseActivity__ValidateUrlTitle" Size="361; 234" Location="465; 666"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 134" Location="484; 737"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity12" Size="130; 53" Location="494; 799" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 134" Location="657; 737"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity_redoStep2" Size="130; 53" Location="667; 799" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step2_eventDrivenActivity_Cancel" Size="150; 182" Location="455; 568"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity3" Size="130; 41" Location="465; 630" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="465; 690" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="984; 866" Name="finishState" /> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" Location="580; 744" Name="finalizeActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 242" Location="588; 775"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="closeCurrentViewActivity1" Size="130; 41" Location="598; 837" /> <CodeDesigner Name="stepFinalize_codeActivity" Size="130; 41" Location="598; 897" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="598; 957" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="217; 126" AutoSizeMargin="16; 24" AutoSize="False" Location="153; 265" Name="step1State"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1StateInitializationActivity" Size="150; 122" Location="171; 135"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="step1WizzardFormActivity" Size="130; 41" Location="181; 197" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step1_eventDrivenActivity_Next" Size="381; 375" Location="171; 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="nextHandleExternalEventActivity1" Size="130; 41" Location="296; 221" /> <IfElseDesigner Name="ifFirstPageValid" Size="361; 234" Location="181; 281"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity15" Size="150; 134" Location="200; 352"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="210; 420" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity17" Size="150; 134" Location="373; 352"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity13" Size="130; 53" Location="383; 414" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1_eventDrivenActivity_Finish" Size="843; 797" Location="179; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="535; 210" /> <IfElseDesigner Name="ifElse_FirstPageValid" Size="823; 656" Location="189; 270"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity18" Size="612; 556" Location="208; 341"> <IfElseBranchDesigner.Designers> <IfElseDesigner Name="ifElseActivity_CanSkipStep2" Size="592; 475" Location="218; 403"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity3" Size="381; 375" Location="237; 474"> <IfElseBranchDesigner.Designers> <IfElseDesigner Name="ifElseActivity4_ValidateUrlTitle" Size="361; 294" Location="247; 536"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity9" Size="150; 194" Location="266; 607"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="PresetCalculatedFields" Size="130; 41" Location="276; 669" /> <SetStateDesigner Name="setStateActivity_GoToFinalize" Size="130; 53" Location="276; 729" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity10" Size="150; 194" Location="439; 607"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity7" Size="130; 41" Location="449; 705" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity4" Size="150; 375" Location="641; 474"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity_GoToStep2" Size="130; 53" Location="651; 657" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity19" Size="150; 556" Location="843; 341"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity14" Size="130; 53" Location="853; 614" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1_eventDrivenActivity_Cancel" Size="150; 182" Location="171; 207"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="181; 269" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="181; 329" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="59; 123" Name="initializeActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="1305; 1099" Location="67; 154"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="ifElseActivity1" Size="1285; 1018" Location="77; 216"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseCheckPageTypesExist" Size="1074; 918" Location="96; 287"> <IfElseBranchDesigner.Designers> <IfElseDesigner Name="ifElse_CheckTemplatesExists" Size="1054; 837" Location="106; 349"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity7" Size="843; 737" Location="125; 420"> <IfElseBranchDesigner.Designers> <IfElseDesigner Name="ifElse_CheckActiveLanguagesExists" Size="823; 656" Location="135; 482"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity5" Size="612; 556" Location="154; 553"> <IfElseBranchDesigner.Designers> <IfElseDesigner Name="ifElse_CheckPageTypesExists" Size="592; 475" Location="164; 615"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity11" Size="381; 375" Location="183; 686"> <IfElseBranchDesigner.Designers> <IfElseDesigner Name="ifElse_RulesDontAllowPageAdd" Size="361; 294" Location="193; 748"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity13" Size="150; 194" Location="212; 819"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="stepInitialize_codeActivity" Size="130; 41" Location="222; 881" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="222; 941" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity14" Size="150; 194" Location="385; 819"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="RuleDontAllowPageAddCodeActivity" Size="130; 41" Location="395; 881" /> <SetStateDesigner Name="setStateActivity10" Size="130; 53" Location="395; 941" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity12" Size="150; 375" Location="587; 686"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="MissingPageTypeCodeActivity" Size="130; 41" Location="597; 748" /> <SetStateDesigner Name="setStateActivity9" Size="130; 41" Location="597; 808" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity6" Size="150; 556" Location="789; 553"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="MissingActiveLanguageCodeActivity" Size="130; 41" Location="799; 615" /> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="799; 675" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity8" Size="150; 737" Location="991; 420"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="MissingTemplateAlertActivity" Size="130; 41" Location="1001; 482" /> <SetStateDesigner Name="setStateActivity20" Size="130; 53" Location="1001; 542" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity16" Size="150; 918" Location="1193; 287"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity11" Size="130; 53" Location="1203; 741" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 194" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity19" Size="130; 53" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/DeletePageWorkflow.Designer.cs ================================================ using System; using System.Workflow.Activities; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { partial class DeletePageWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition3 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition4 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition5 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition6 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity15 = new System.Workflow.Activities.SetStateActivity(); this.caCheckChildren = new System.Workflow.Activities.CodeActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_ShowError_InstanceCompositions = new System.Workflow.Activities.CodeActivity(); this.setStateActivity19 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity16 = new System.Workflow.Activities.SetStateActivity(); this.confirmDialogFormActivity2 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.codeActivity_SetupDeleteMultipleVersionsForm = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.wizzardFormActivity2 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity17 = new System.Workflow.Activities.SetStateActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.branchNoCompositions = new System.Workflow.Activities.IfElseBranchActivity(); this.branchHasCompositions = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity_DeleteCurrentVersion = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity_DeleteAllVersions = new System.Workflow.Activities.IfElseBranchActivity(); this.branch_HasSingleVersion = new System.Workflow.Activities.IfElseBranchActivity(); this.branch_HasMultipleVersions = new System.Workflow.Activities.IfElseBranchActivity(); this.branchRelatedDataDoesntExist = new System.Workflow.Activities.IfElseBranchActivity(); this.branchRelatedDataExist = new System.Workflow.Activities.IfElseBranchActivity(); this.branch_deletionNotConfirmed = new System.Workflow.Activities.IfElseBranchActivity(); this.branch_DeletionConfirmed = new System.Workflow.Activities.IfElseBranchActivity(); this.branch_NoSubpages = new System.Workflow.Activities.IfElseBranchActivity(); this.branch_HasSubpages = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity18 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity_DeleteCurrentVersion = new System.Workflow.Activities.CodeActivity(); this.ifElse_HasInstanceCompositions = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity14 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity5 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity_DeleteAllVersions = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity4 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.ifElse_HasMultipleVersions = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity12 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.setStateActivity13 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.conditionCheckRelatedData = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity11 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.ifElse_DeletionAlreadyConfirmed = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.codeActivity2 = new System.Workflow.Activities.CodeActivity(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity4 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity_DeletingChildrenConfirmed = new System.Workflow.Activities.CodeActivity(); this.finishHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.ifElse_HasSubpages = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.stateInitializationActivity4 = new System.Workflow.Activities.StateInitializationActivity(); this.initializeInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.versions_eventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.versions_eventDrivenActivity_Ok = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity2 = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.eventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.step2EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step2EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step2StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1InitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.stateInitializationActivity3 = new System.Workflow.Activities.StateInitializationActivity(); this.deleteCurrentVersionStateActivity = new System.Workflow.Activities.StateActivity(); this.checkForCompositionsStateActivity = new System.Workflow.Activities.StateActivity(); this.confirmDeletingAllVersionsStateActivity = new System.Workflow.Activities.StateActivity(); this.confDeletingReferencedDataStateActivity = new System.Workflow.Activities.StateActivity(); this.confirmationStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.confirmDeletingChildrenStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity15 // this.setStateActivity15.Name = "setStateActivity15"; this.setStateActivity15.TargetStateName = "confirmDeletingChildrenStateActivity"; // // caCheckChildren // this.caCheckChildren.Description = "Checking page children"; this.caCheckChildren.Name = "caCheckChildren"; this.caCheckChildren.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // initializeCodeActivity_ShowError_InstanceCompositions // this.initializeCodeActivity_ShowError_InstanceCompositions.Name = "initializeCodeActivity_ShowError_InstanceCompositions"; this.initializeCodeActivity_ShowError_InstanceCompositions.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ShowError_InstanceCompositions_ExecuteCode); // // setStateActivity19 // this.setStateActivity19.Name = "setStateActivity19"; this.setStateActivity19.TargetStateName = "deleteCurrentVersionStateActivity"; // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "checkForCompositionsStateActivity"; // // setStateActivity16 // this.setStateActivity16.Name = "setStateActivity16"; this.setStateActivity16.TargetStateName = "checkForCompositionsStateActivity"; // // confirmDialogFormActivity2 // this.confirmDialogFormActivity2.ContainerLabel = "Delete page"; this.confirmDialogFormActivity2.FormDefinitionFileName = "\\Administrative\\DeletePage_ConfirmAllVersionsDeletion.xml"; this.confirmDialogFormActivity2.Name = "confirmDialogFormActivity2"; // // codeActivity_SetupDeleteMultipleVersionsForm // this.codeActivity_SetupDeleteMultipleVersionsForm.Name = "codeActivity_SetupDeleteMultipleVersionsForm"; this.codeActivity_SetupDeleteMultipleVersionsForm.ExecuteCode += new System.EventHandler(this.SetupDeleteMultipleVersionsForm); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "confirmationStateActivity"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "\\Administrative\\DeletePageStep3.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // wizzardFormActivity2 // this.wizzardFormActivity2.ContainerLabel = null; this.wizzardFormActivity2.FormDefinitionFileName = "\\Administrative\\DeletePageStep2.xml"; this.wizzardFormActivity2.Name = "wizzardFormActivity2"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalizeStateActivity"; // // setStateActivity17 // this.setStateActivity17.Name = "setStateActivity17"; this.setStateActivity17.TargetStateName = "confDeletingReferencedDataStateActivity"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = "Delete page"; this.wizzardFormActivity1.FormDefinitionFileName = "\\Administrative\\DeletePageStep1.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // branchNoCompositions // this.branchNoCompositions.Activities.Add(this.caCheckChildren); this.branchNoCompositions.Activities.Add(this.setStateActivity15); this.branchNoCompositions.Name = "branchNoCompositions"; // // branchHasCompositions // this.branchHasCompositions.Activities.Add(this.initializeCodeActivity_ShowError_InstanceCompositions); this.branchHasCompositions.Activities.Add(this.setStateActivity6); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.HasInstanceCompositionsTest); this.branchHasCompositions.Condition = codecondition1; this.branchHasCompositions.Name = "branchHasCompositions"; // // ifElseBranchActivity_DeleteCurrentVersion // this.ifElseBranchActivity_DeleteCurrentVersion.Activities.Add(this.setStateActivity19); this.ifElseBranchActivity_DeleteCurrentVersion.Name = "ifElseBranchActivity_DeleteCurrentVersion"; // // ifElseBranchActivity_DeleteAllVersions // this.ifElseBranchActivity_DeleteAllVersions.Activities.Add(this.setStateActivity10); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ifElse_ShouldAllVersionsBeDeleted); this.ifElseBranchActivity_DeleteAllVersions.Condition = codecondition2; this.ifElseBranchActivity_DeleteAllVersions.Name = "ifElseBranchActivity_DeleteAllVersions"; // // branch_HasSingleVersion // this.branch_HasSingleVersion.Activities.Add(this.setStateActivity16); this.branch_HasSingleVersion.Name = "branch_HasSingleVersion"; // // branch_HasMultipleVersions // this.branch_HasMultipleVersions.Activities.Add(this.codeActivity_SetupDeleteMultipleVersionsForm); this.branch_HasMultipleVersions.Activities.Add(this.confirmDialogFormActivity2); codecondition3.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.PageHasMultpleVersions); this.branch_HasMultipleVersions.Condition = codecondition3; this.branch_HasMultipleVersions.Name = "branch_HasMultipleVersions"; // // branchRelatedDataDoesntExist // this.branchRelatedDataDoesntExist.Activities.Add(this.setStateActivity5); this.branchRelatedDataDoesntExist.Name = "branchRelatedDataDoesntExist"; // // branchRelatedDataExist // this.branchRelatedDataExist.Activities.Add(this.confirmDialogFormActivity1); codecondition4.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.HasDataReferences); this.branchRelatedDataExist.Condition = codecondition4; this.branchRelatedDataExist.Name = "branchRelatedDataExist"; // // branch_deletionNotConfirmed // this.branch_deletionNotConfirmed.Activities.Add(this.wizzardFormActivity2); this.branch_deletionNotConfirmed.Name = "branch_deletionNotConfirmed"; // // branch_DeletionConfirmed // this.branch_DeletionConfirmed.Activities.Add(this.setStateActivity7); codecondition5.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.HasPageDeletionBeenConfirmed); this.branch_DeletionConfirmed.Condition = codecondition5; this.branch_DeletionConfirmed.Name = "branch_DeletionConfirmed"; // // branch_NoSubpages // this.branch_NoSubpages.Activities.Add(this.setStateActivity17); this.branch_NoSubpages.Name = "branch_NoSubpages"; // // branch_HasSubpages // this.branch_HasSubpages.Activities.Add(this.wizzardFormActivity1); codecondition6.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.HasSubpages); this.branch_HasSubpages.Condition = codecondition6; this.branch_HasSubpages.Name = "branch_HasSubpages"; // // setStateActivity18 // this.setStateActivity18.Name = "setStateActivity18"; this.setStateActivity18.TargetStateName = "finalStateActivity"; // // codeActivity_DeleteCurrentVersion // this.codeActivity_DeleteCurrentVersion.Name = "codeActivity_DeleteCurrentVersion"; this.codeActivity_DeleteCurrentVersion.ExecuteCode += new System.EventHandler(this.DeleteCurrentVersion); // // ifElse_HasInstanceCompositions // this.ifElse_HasInstanceCompositions.Activities.Add(this.branchHasCompositions); this.ifElse_HasInstanceCompositions.Activities.Add(this.branchNoCompositions); this.ifElse_HasInstanceCompositions.Name = "ifElse_HasInstanceCompositions"; // // setStateActivity14 // this.setStateActivity14.Name = "setStateActivity14"; this.setStateActivity14.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity5 // this.cancelHandleExternalEventActivity5.EventName = "Cancel"; this.cancelHandleExternalEventActivity5.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity5.Name = "cancelHandleExternalEventActivity5"; // // ifElseActivity_DeleteAllVersions // this.ifElseActivity_DeleteAllVersions.Activities.Add(this.ifElseBranchActivity_DeleteAllVersions); this.ifElseActivity_DeleteAllVersions.Activities.Add(this.ifElseBranchActivity_DeleteCurrentVersion); this.ifElseActivity_DeleteAllVersions.Name = "ifElseActivity_DeleteAllVersions"; // // finishHandleExternalEventActivity4 // this.finishHandleExternalEventActivity4.EventName = "Finish"; this.finishHandleExternalEventActivity4.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity4.Name = "finishHandleExternalEventActivity4"; // // ifElse_HasMultipleVersions // this.ifElse_HasMultipleVersions.Activities.Add(this.branch_HasMultipleVersions); this.ifElse_HasMultipleVersions.Activities.Add(this.branch_HasSingleVersion); this.ifElse_HasMultipleVersions.Name = "ifElse_HasMultipleVersions"; // // setStateActivity12 // this.setStateActivity12.Name = "setStateActivity12"; this.setStateActivity12.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // setStateActivity13 // this.setStateActivity13.Name = "setStateActivity13"; this.setStateActivity13.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // conditionCheckRelatedData // this.conditionCheckRelatedData.Activities.Add(this.branchRelatedDataExist); this.conditionCheckRelatedData.Activities.Add(this.branchRelatedDataDoesntExist); this.conditionCheckRelatedData.Name = "conditionCheckRelatedData"; // // setStateActivity11 // this.setStateActivity11.Name = "setStateActivity11"; this.setStateActivity11.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // ifElse_DeletionAlreadyConfirmed // this.ifElse_DeletionAlreadyConfirmed.Activities.Add(this.branch_DeletionConfirmed); this.ifElse_DeletionAlreadyConfirmed.Activities.Add(this.branch_deletionNotConfirmed); this.ifElse_DeletionAlreadyConfirmed.Name = "ifElse_DeletionAlreadyConfirmed"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // codeActivity2 // this.codeActivity2.Name = "codeActivity2"; this.codeActivity2.ExecuteCode += new System.EventHandler(this.codeActivity2_ExecuteCode); // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity4 // this.cancelHandleExternalEventActivity4.EventName = "Cancel"; this.cancelHandleExternalEventActivity4.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity4.Name = "cancelHandleExternalEventActivity4"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "confDeletingReferencedDataStateActivity"; // // codeActivity_DeletingChildrenConfirmed // this.codeActivity_DeletingChildrenConfirmed.Name = "codeActivity_DeletingChildrenConfirmed"; this.codeActivity_DeletingChildrenConfirmed.ExecuteCode += new System.EventHandler(this.OnDeletingChildrenConfirmed); // // finishHandleExternalEventActivity3 // this.finishHandleExternalEventActivity3.EventName = "Finish"; this.finishHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity3.Name = "finishHandleExternalEventActivity3"; // // ifElse_HasSubpages // this.ifElse_HasSubpages.Activities.Add(this.branch_HasSubpages); this.ifElse_HasSubpages.Activities.Add(this.branch_NoSubpages); this.ifElse_HasSubpages.Name = "ifElse_HasSubpages"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "confirmDeletingAllVersionsStateActivity"; // // stateInitializationActivity4 // this.stateInitializationActivity4.Activities.Add(this.codeActivity_DeleteCurrentVersion); this.stateInitializationActivity4.Activities.Add(this.setStateActivity18); this.stateInitializationActivity4.Name = "stateInitializationActivity4"; // // initializeInitializationActivity // this.initializeInitializationActivity.Activities.Add(this.ifElse_HasInstanceCompositions); this.initializeInitializationActivity.Name = "initializeInitializationActivity"; // // versions_eventDrivenActivity_Cancel // this.versions_eventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity5); this.versions_eventDrivenActivity_Cancel.Activities.Add(this.setStateActivity14); this.versions_eventDrivenActivity_Cancel.Name = "versions_eventDrivenActivity_Cancel"; // // versions_eventDrivenActivity_Ok // this.versions_eventDrivenActivity_Ok.Activities.Add(this.finishHandleExternalEventActivity4); this.versions_eventDrivenActivity_Ok.Activities.Add(this.ifElseActivity_DeleteAllVersions); this.versions_eventDrivenActivity_Ok.Name = "versions_eventDrivenActivity_Ok"; // // stateInitializationActivity2 // this.stateInitializationActivity2.Activities.Add(this.ifElse_HasMultipleVersions); this.stateInitializationActivity2.Name = "stateInitializationActivity2"; // // eventDrivenActivity_Finish // this.eventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.eventDrivenActivity_Finish.Activities.Add(this.setStateActivity12); this.eventDrivenActivity_Finish.Name = "eventDrivenActivity_Finish"; // // eventDrivenActivity_Cancel // this.eventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.eventDrivenActivity_Cancel.Activities.Add(this.setStateActivity13); this.eventDrivenActivity_Cancel.Name = "eventDrivenActivity_Cancel"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.conditionCheckRelatedData); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // step2EventDrivenActivity_Cancel // this.step2EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.step2EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity11); this.step2EventDrivenActivity_Cancel.Name = "step2EventDrivenActivity_Cancel"; // // step2EventDrivenActivity_Finish // this.step2EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.step2EventDrivenActivity_Finish.Activities.Add(this.setStateActivity2); this.step2EventDrivenActivity_Finish.Name = "step2EventDrivenActivity_Finish"; // // step2StateInitializationActivity // this.step2StateInitializationActivity.Activities.Add(this.ifElse_DeletionAlreadyConfirmed); this.step2StateInitializationActivity.Name = "step2StateInitializationActivity"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeInitializationActivity // this.finalizeInitializationActivity.Activities.Add(this.codeActivity2); this.finalizeInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeInitializationActivity.Activities.Add(this.setStateActivity3); this.finalizeInitializationActivity.Name = "finalizeInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity4); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity9); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity3); this.step1EventDrivenActivity_Finish.Activities.Add(this.codeActivity_DeletingChildrenConfirmed); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity1); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1InitializationActivity // this.step1InitializationActivity.Activities.Add(this.ifElse_HasSubpages); this.step1InitializationActivity.Name = "step1InitializationActivity"; // // stateInitializationActivity3 // this.stateInitializationActivity3.Activities.Add(this.setStateActivity8); this.stateInitializationActivity3.Name = "stateInitializationActivity3"; // // deleteCurrentVersionStateActivity // this.deleteCurrentVersionStateActivity.Activities.Add(this.stateInitializationActivity4); this.deleteCurrentVersionStateActivity.Name = "deleteCurrentVersionStateActivity"; // // checkForCompositionsStateActivity // this.checkForCompositionsStateActivity.Activities.Add(this.initializeInitializationActivity); this.checkForCompositionsStateActivity.Name = "checkForCompositionsStateActivity"; // // confirmDeletingAllVersionsStateActivity // this.confirmDeletingAllVersionsStateActivity.Activities.Add(this.stateInitializationActivity2); this.confirmDeletingAllVersionsStateActivity.Activities.Add(this.versions_eventDrivenActivity_Ok); this.confirmDeletingAllVersionsStateActivity.Activities.Add(this.versions_eventDrivenActivity_Cancel); this.confirmDeletingAllVersionsStateActivity.Name = "confirmDeletingAllVersionsStateActivity"; // // confDeletingReferencedDataStateActivity // this.confDeletingReferencedDataStateActivity.Activities.Add(this.stateInitializationActivity1); this.confDeletingReferencedDataStateActivity.Activities.Add(this.eventDrivenActivity_Cancel); this.confDeletingReferencedDataStateActivity.Activities.Add(this.eventDrivenActivity_Finish); this.confDeletingReferencedDataStateActivity.Name = "confDeletingReferencedDataStateActivity"; // // confirmationStateActivity // this.confirmationStateActivity.Activities.Add(this.step2StateInitializationActivity); this.confirmationStateActivity.Activities.Add(this.step2EventDrivenActivity_Finish); this.confirmationStateActivity.Activities.Add(this.step2EventDrivenActivity_Cancel); this.confirmationStateActivity.Name = "confirmationStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity4); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // confirmDeletingChildrenStateActivity // this.confirmDeletingChildrenStateActivity.Activities.Add(this.step1InitializationActivity); this.confirmDeletingChildrenStateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.confirmDeletingChildrenStateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.confirmDeletingChildrenStateActivity.Name = "confirmDeletingChildrenStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.stateInitializationActivity3); this.initializeStateActivity.Name = "initializeStateActivity"; // // DeletePageWorkflow // this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.confirmDeletingChildrenStateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.confirmationStateActivity); this.Activities.Add(this.confDeletingReferencedDataStateActivity); this.Activities.Add(this.confirmDeletingAllVersionsStateActivity); this.Activities.Add(this.checkForCompositionsStateActivity); this.Activities.Add(this.deleteCurrentVersionStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "DeletePageWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity finalStateActivity; private SetStateActivity setStateActivity3; private StateInitializationActivity finalizeInitializationActivity; private StateActivity finalizeStateActivity; private CodeActivity codeActivity2; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private SetStateActivity setStateActivity2; private EventDrivenActivity step2EventDrivenActivity_Finish; private StateInitializationActivity step2StateInitializationActivity; private StateActivity confirmationStateActivity; private C1Console.Workflow.Activities.ConfirmDialogFormActivity wizzardFormActivity2; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity11; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private EventDrivenActivity step2EventDrivenActivity_Cancel; private StateActivity confDeletingReferencedDataStateActivity; private IfElseBranchActivity branchRelatedDataDoesntExist; private IfElseBranchActivity branchRelatedDataExist; private IfElseActivity conditionCheckRelatedData; private StateInitializationActivity stateInitializationActivity1; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity13; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity eventDrivenActivity_Cancel; private SetStateActivity setStateActivity12; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_Finish; private C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private SetStateActivity setStateActivity9; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity4; private SetStateActivity setStateActivity1; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity3; private C1Console.Workflow.Activities.ConfirmDialogFormActivity wizzardFormActivity1; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateInitializationActivity step1InitializationActivity; private StateActivity confirmDeletingChildrenStateActivity; private SetStateActivity setStateActivity14; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity5; private SetStateActivity setStateActivity10; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity4; private C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity2; private EventDrivenActivity versions_eventDrivenActivity_Cancel; private EventDrivenActivity versions_eventDrivenActivity_Ok; private StateInitializationActivity stateInitializationActivity2; private StateActivity confirmDeletingAllVersionsStateActivity; private SetStateActivity setStateActivity16; private SetStateActivity setStateActivity17; private IfElseBranchActivity branch_HasSingleVersion; private IfElseBranchActivity branch_HasMultipleVersions; private IfElseBranchActivity branch_NoSubpages; private IfElseBranchActivity branch_HasSubpages; private IfElseActivity ifElse_HasMultipleVersions; private IfElseActivity ifElse_HasSubpages; private SetStateActivity setStateActivity7; private IfElseBranchActivity branch_deletionNotConfirmed; private IfElseBranchActivity branch_DeletionConfirmed; private IfElseActivity ifElse_DeletionAlreadyConfirmed; private SetStateActivity setStateActivity15; private CodeActivity caCheckChildren; private SetStateActivity setStateActivity6; private CodeActivity initializeCodeActivity_ShowError_InstanceCompositions; private IfElseBranchActivity branchNoCompositions; private IfElseBranchActivity branchHasCompositions; private CodeActivity codeActivity_DeleteCurrentVersion; private IfElseActivity ifElse_HasInstanceCompositions; private SetStateActivity setStateActivity8; private StateInitializationActivity stateInitializationActivity4; private StateInitializationActivity initializeInitializationActivity; private StateInitializationActivity stateInitializationActivity3; private StateActivity deleteCurrentVersionStateActivity; private StateActivity checkForCompositionsStateActivity; private SetStateActivity setStateActivity19; private IfElseBranchActivity ifElseBranchActivity_DeleteCurrentVersion; private IfElseBranchActivity ifElseBranchActivity_DeleteAllVersions; private SetStateActivity setStateActivity18; private IfElseActivity ifElseActivity_DeleteAllVersions; private CodeActivity codeActivity_SetupDeleteMultipleVersionsForm; private CodeActivity codeActivity_DeletingChildrenConfirmed; private StateActivity initializeStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/DeletePageWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Workflow; using Composite.Core.Collections.Generic; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Plugins_PageElementProvider; using Composite.Core.Configuration; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { [EntityTokenLock] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeletePageWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeletePageWorkflow() { InitializeComponent(); } private static class BindingNames { public const string DeleteAllVersions = nameof(DeleteAllVersions); public const string DeleteChildrenConfirmed = nameof(DeleteChildrenConfirmed); public const string HasSubPages = nameof(HasSubPages); public const string DeleteMessageText = nameof(DeleteMessageText); public const string ReferencedData = nameof(ReferencedData); } private void HasInstanceCompositionsTest(object sender, ConditionalEventArgs e) { e.Result = false; // Ignore this test, we delete all defined folders ande metadat fields when last page (with respect to locales) are deleted } private void HasSubpages(object sender, ConditionalEventArgs e) { e.Result = this.GetBinding<bool>(BindingNames.HasSubPages); } private void HasDataReferences(object sender, ConditionalEventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; IPage selectedPage = (IPage)dataEntityToken.Data; var dataToDelete = new List<IData>(); IEnumerable<IPage> subtree = new[] { selectedPage }.Concat(selectedPage.GetSubChildren()); foreach (IPage page in subtree) { dataToDelete.Add(page); dataToDelete.AddRange(page.GetFolderData()); dataToDelete.AddRange(page.GetMetaData()); } var brokenReferences = new List<IData>(); foreach (var data in dataToDelete) { var references = DataReferenceFacade.GetReferences(data, false, (type, fp) => !fp.IsOptionalReference && type != typeof(IPagePlaceholderContent) && fp.SourcePropertyInfo.DeclaringType != typeof(IPageRelatedData)); foreach (var reference in references) { DataSourceId dataSourceId = reference.DataSourceId; if (dataToDelete.Any(elem => elem.DataSourceId.Equals(dataSourceId)) || brokenReferences.Any(brokenRef => brokenRef.DataSourceId.Equals(dataSourceId))) { continue; } brokenReferences.Add(reference); } } e.Result = brokenReferences.Count > 0; if (brokenReferences.Count > 0) { Bindings.Add(BindingNames.ReferencedData, DataReferenceFacade.GetBrokenReferencesReport(brokenReferences)); } } private void codeActivity1_ExecuteCode(object sender, EventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; IPage selectedPage = (IPage)dataEntityToken.Data; bool hasChildren = PageServices.GetSubChildren(selectedPage).Any(); this.Bindings.AddDictionary(new Dictionary<string, object> { {BindingNames.HasSubPages, hasChildren}, {BindingNames.DeleteMessageText, Texts.DeletePageStep2_Text(selectedPage.Title)} }); } private void codeActivity2_ExecuteCode(object sender, EventArgs e) { bool hasSubPages = this.GetBinding<bool>(BindingNames.HasSubPages); DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; IPage selectedPage = (IPage)dataEntityToken.Data; if (!DataFacade.WillDeleteSucceed<IPage>(selectedPage)) { this.ShowMessage( DialogType.Error, Texts.DeletePageWorkflow_CascadeDeleteErrorTitle, Texts.DeletePageWorkflow_CascadeDeleteErrorMessage ); return; } if (hasSubPages) { List<IPage> pagesToDelete = selectedPage.GetSubChildren().ToList(); if (pagesToDelete.Any(page => !DataFacade.WillDeleteSucceed<IPage>(page))) { this.ShowMessage(DialogType.Error, Texts.DeletePageWorkflow_CascadeDeleteErrorTitle, Texts.DeletePageWorkflow_CascadeDeleteErrorMessage); return; } } var parentTreeRefresher = this.CreateParentTreeRefresher(); parentTreeRefresher.PostRefreshMessages(selectedPage.GetDataEntityToken(), 2); PageServices.DeletePage(selectedPage); } private void initializeCodeActivity_ShowError_InstanceCompositions_ExecuteCode(object sender, EventArgs e) { this.ShowMessage( DialogType.Error, Texts.DeletePageWorkflow_HasCompositionsTitle, Texts.DeletePageWorkflow_HasCompositionsMessage ); } private void PageHasMultpleVersions(object sender, ConditionalEventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; IPage selectedPage = (IPage)dataEntityToken.Data; Guid pageId = selectedPage.Id; e.Result = DataFacade.GetData<IPage>().Count(p => p.Id == pageId) > 1; } private void HasPageDeletionBeenConfirmed(object sender, ConditionalEventArgs e) { bool IsTrueBinding(string bindingName) => Bindings.ContainsKey(bindingName) && (bool) Bindings[bindingName]; e.Result = IsTrueBinding(BindingNames.DeleteAllVersions) || IsTrueBinding(BindingNames.DeleteChildrenConfirmed); } private void DeleteCurrentVersion(object sender, EventArgs e) { var dataEntityToken = (DataEntityToken)this.EntityToken; IPage selectedPage = (IPage)dataEntityToken.Data; PageServices.DeletePage(selectedPage.Id, selectedPage.VersionId, selectedPage.DataSourceId.LocaleScope); Guid pageId = selectedPage.Id; var anotherVersion = DataFacade.GetData<IPage>().FirstOrDefault(p => p.Id == pageId); var parentTreeRefresher = this.CreateParentTreeRefresher(); parentTreeRefresher.PostRefreshMessages((anotherVersion ?? selectedPage).GetDataEntityToken()); if (anotherVersion != null) { SelectElement(anotherVersion.GetDataEntityToken()); } } private void ifElse_ShouldAllVersionsBeDeleted(object sender, ConditionalEventArgs e) { e.Result = (bool)Bindings[BindingNames.DeleteAllVersions]; } private void SetupDeleteMultipleVersionsForm(object sender, EventArgs e) { Bindings[BindingNames.DeleteAllVersions] = false; } private void OnDeletingChildrenConfirmed(object sender, EventArgs e) { Bindings[BindingNames.DeleteChildrenConfirmed] = true; } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/DeletePageWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1525, 885" AutoSizeMargin="16, 24" AutoSize="False" Location="30, 30" Name="DeletePageWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="DeletePageWorkflow" TargetConnectionIndex="0" SourceStateName="DeletePageWorkflow" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="74" /> <ns0:Point X="1365" Y="74" /> <ns0:Point X="1365" Y="314" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="confirmDeletingAllVersionsStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity8" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" EventHandlerName="stateInitializationActivity3" SourceConnectionIndex="0" TargetStateName="confirmDeletingAllVersionsStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="250" Y="178" /> <ns0:Point X="274" Y="178" /> <ns0:Point X="274" Y="225" /> <ns0:Point X="170" Y="225" /> <ns0:Point X="170" Y="237" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="confDeletingReferencedDataStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity17" SourceActivity="confirmDeletingChildrenStateActivity" TargetConnectionIndex="0" SourceStateName="confirmDeletingChildrenStateActivity" SourceConnectionEdge="Right" EventHandlerName="step1InitializationActivity" SourceConnectionIndex="0" TargetStateName="confDeletingReferencedDataStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="398" Y="593" /> <ns0:Point X="644" Y="593" /> <ns0:Point X="644" Y="759" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="confDeletingReferencedDataStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="confirmDeletingChildrenStateActivity" TargetConnectionIndex="0" SourceStateName="confirmDeletingChildrenStateActivity" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="confDeletingReferencedDataStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="434" Y="619" /> <ns0:Point X="644" Y="619" /> <ns0:Point X="644" Y="759" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity9" SourceActivity="confirmDeletingChildrenStateActivity" TargetConnectionIndex="0" SourceStateName="confirmDeletingChildrenStateActivity" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="439" Y="645" /> <ns0:Point X="464" Y="645" /> <ns0:Point X="464" Y="306" /> <ns0:Point X="1365" Y="306" /> <ns0:Point X="1365" Y="314" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" EventHandlerName="finalizeInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="1475" Y="598" /> <ns0:Point X="1533" Y="598" /> <ns0:Point X="1533" Y="306" /> <ns0:Point X="1365" Y="306" /> <ns0:Point X="1365" Y="314" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceActivity="confirmationStateActivity" TargetConnectionIndex="0" SourceStateName="confirmationStateActivity" SourceConnectionEdge="Right" EventHandlerName="step2StateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="1184" Y="782" /> <ns0:Point X="1213" Y="782" /> <ns0:Point X="1213" Y="546" /> <ns0:Point X="1405" Y="546" /> <ns0:Point X="1405" Y="554" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="confirmationStateActivity" TargetConnectionIndex="0" SourceStateName="confirmationStateActivity" SourceConnectionEdge="Right" EventHandlerName="step2EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="1192" Y="808" /> <ns0:Point X="1213" Y="808" /> <ns0:Point X="1213" Y="546" /> <ns0:Point X="1405" Y="546" /> <ns0:Point X="1405" Y="554" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity11" SourceActivity="confirmationStateActivity" TargetConnectionIndex="0" SourceStateName="confirmationStateActivity" SourceConnectionEdge="Right" EventHandlerName="step2EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="1197" Y="834" /> <ns0:Point X="1213" Y="834" /> <ns0:Point X="1213" Y="306" /> <ns0:Point X="1365" Y="306" /> <ns0:Point X="1365" Y="314" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="confirmationStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceActivity="confDeletingReferencedDataStateActivity" TargetConnectionIndex="0" SourceStateName="confDeletingReferencedDataStateActivity" SourceConnectionEdge="Right" EventHandlerName="stateInitializationActivity1" SourceConnectionIndex="0" TargetStateName="confirmationStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="700" Y="803" /> <ns0:Point X="785" Y="803" /> <ns0:Point X="785" Y="730" /> <ns0:Point X="1088" Y="730" /> <ns0:Point X="1088" Y="738" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity13" SourceActivity="confDeletingReferencedDataStateActivity" TargetConnectionIndex="0" SourceStateName="confDeletingReferencedDataStateActivity" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="707" Y="829" /> <ns0:Point X="785" Y="829" /> <ns0:Point X="785" Y="306" /> <ns0:Point X="1365" Y="306" /> <ns0:Point X="1365" Y="314" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity12" SourceActivity="confDeletingReferencedDataStateActivity" TargetConnectionIndex="0" SourceStateName="confDeletingReferencedDataStateActivity" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_Finish" SourceConnectionIndex="2" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="702" Y="855" /> <ns0:Point X="785" Y="855" /> <ns0:Point X="785" Y="546" /> <ns0:Point X="1405" Y="546" /> <ns0:Point X="1405" Y="554" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="checkForCompositionsStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity16" SourceActivity="confirmDeletingAllVersionsStateActivity" TargetConnectionIndex="0" SourceStateName="confirmDeletingAllVersionsStateActivity" SourceConnectionEdge="Right" EventHandlerName="stateInitializationActivity2" SourceConnectionIndex="0" TargetStateName="checkForCompositionsStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="230" Y="281" /> <ns0:Point X="302" Y="281" /> <ns0:Point X="302" Y="416" /> <ns0:Point X="182" Y="416" /> <ns0:Point X="182" Y="428" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="checkForCompositionsStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity10" SourceActivity="confirmDeletingAllVersionsStateActivity" TargetConnectionIndex="0" SourceStateName="confirmDeletingAllVersionsStateActivity" SourceConnectionEdge="Right" EventHandlerName="versions_eventDrivenActivity_Ok" SourceConnectionIndex="1" TargetStateName="checkForCompositionsStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="266" Y="307" /> <ns0:Point X="302" Y="307" /> <ns0:Point X="302" Y="416" /> <ns0:Point X="182" Y="416" /> <ns0:Point X="182" Y="428" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="deleteCurrentVersionStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity19" SourceActivity="confirmDeletingAllVersionsStateActivity" TargetConnectionIndex="0" SourceStateName="confirmDeletingAllVersionsStateActivity" SourceConnectionEdge="Right" EventHandlerName="versions_eventDrivenActivity_Ok" SourceConnectionIndex="1" TargetStateName="deleteCurrentVersionStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="266" Y="307" /> <ns0:Point X="306" Y="307" /> <ns0:Point X="306" Y="164" /> <ns0:Point X="640" Y="164" /> <ns0:Point X="640" Y="172" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity14" SourceActivity="confirmDeletingAllVersionsStateActivity" TargetConnectionIndex="0" SourceStateName="confirmDeletingAllVersionsStateActivity" SourceConnectionEdge="Right" EventHandlerName="versions_eventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="287" Y="333" /> <ns0:Point X="339" Y="333" /> <ns0:Point X="339" Y="306" /> <ns0:Point X="1365" Y="306" /> <ns0:Point X="1365" Y="314" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceActivity="checkForCompositionsStateActivity" TargetConnectionIndex="0" SourceStateName="checkForCompositionsStateActivity" SourceConnectionEdge="Right" EventHandlerName="initializeInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="265" Y="472" /> <ns0:Point X="338" Y="472" /> <ns0:Point X="338" Y="306" /> <ns0:Point X="1365" Y="306" /> <ns0:Point X="1365" Y="314" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="confirmDeletingChildrenStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity15" SourceActivity="checkForCompositionsStateActivity" TargetConnectionIndex="0" SourceStateName="checkForCompositionsStateActivity" SourceConnectionEdge="Right" EventHandlerName="initializeInitializationActivity" SourceConnectionIndex="0" TargetStateName="confirmDeletingChildrenStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="265" Y="472" /> <ns0:Point X="335" Y="472" /> <ns0:Point X="335" Y="549" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity18" SourceActivity="deleteCurrentVersionStateActivity" TargetConnectionIndex="0" SourceStateName="deleteCurrentVersionStateActivity" SourceConnectionEdge="Right" EventHandlerName="stateInitializationActivity4" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="716" Y="216" /> <ns0:Point X="1365" Y="216" /> <ns0:Point X="1365" Y="314" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="199, 80" AutoSizeMargin="16, 24" Location="66, 134" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="stateInitializationActivity3" Size="150, 146" Location="74, 167"> <StateInitializationDesigner.Designers> <SetStateDesigner Name="setStateActivity8" Size="130, 62" Location="84, 232" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160, 80" AutoSizeMargin="16, 24" Location="1285, 314" Name="finalStateActivity" /> <StateDesigner Size="234, 126" AutoSizeMargin="16, 24" AutoSize="False" Location="218, 549" Name="confirmDeletingChildrenStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1InitializationActivity" Size="381, 333" Location="478, 141"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="ifElse_HasSubpages" Size="361, 249" Location="488, 206"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="branch_HasSubpages" Size="150, 146" Location="507, 280"> <IfElseBranchDesigner.Designers> <ActivityDesigner Name="wizzardFormActivity1" Size="130, 44" Location="517, 354" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="branch_NoSubpages" Size="150, 146" Location="680, 280"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity17" Size="130, 62" Location="690, 345" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Finish" Size="150, 272" Location="512, 154"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity3" Size="130, 44" Location="522, 219" /> <CodeDesigner Name="codeActivity_DeletingChildrenConfirmed" Size="130, 44" Location="522, 282" /> <SetStateDesigner Name="setStateActivity1" Size="130, 62" Location="522, 345" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Cancel" Size="150, 209" Location="478, 193"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity4" Size="130, 44" Location="488, 258" /> <SetStateDesigner Name="setStateActivity9" Size="130, 62" Location="488, 321" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="239, 80" AutoSizeMargin="16, 24" Location="1286, 554" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeInitializationActivity" Size="150, 269" Location="1294, 587"> <StateInitializationDesigner.Designers> <CodeDesigner Name="codeActivity2" Size="130, 41" Location="1304, 652" /> <ActivityDesigner Name="closeCurrentViewActivity1" Size="130, 44" Location="1304, 712" /> <SetStateDesigner Name="setStateActivity3" Size="130, 62" Location="1304, 775" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150, 209" Location="38, 63"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130, 44" Location="48, 128" /> <SetStateDesigner Name="setStateActivity4" Size="130, 62" Location="48, 191" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="225, 126" AutoSizeMargin="16, 24" Location="976, 738" Name="confirmationStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step2StateInitializationActivity" Size="381, 333" Location="984, 771"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="ifElse_DeletionAlreadyConfirmed" Size="361, 249" Location="994, 836"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="branch_DeletionConfirmed" Size="150, 146" Location="1013, 910"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity7" Size="130, 62" Location="1023, 975" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="branch_deletionNotConfirmed" Size="150, 146" Location="1186, 910"> <IfElseBranchDesigner.Designers> <ActivityDesigner Name="wizzardFormActivity2" Size="130, 44" Location="1196, 984" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step2EventDrivenActivity_Finish" Size="150, 209" Location="984, 797"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity2" Size="130, 44" Location="994, 862" /> <SetStateDesigner Name="setStateActivity2" Size="130, 62" Location="994, 925" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step2EventDrivenActivity_Cancel" Size="150, 209" Location="984, 823"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity3" Size="130, 44" Location="994, 888" /> <SetStateDesigner Name="setStateActivity11" Size="130, 62" Location="994, 951" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="257, 126" AutoSizeMargin="16, 24" AutoSize="False" Location="516, 759" Name="confDeletingReferencedDataStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="stateInitializationActivity1" Size="381, 333" Location="524, 792"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="conditionCheckRelatedData" Size="361, 249" Location="534, 857"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="branchRelatedDataExist" Size="150, 146" Location="553, 931"> <IfElseBranchDesigner.Designers> <ActivityDesigner Name="confirmDialogFormActivity1" Size="130, 44" Location="563, 1005" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="branchRelatedDataDoesntExist" Size="150, 146" Location="726, 931"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity5" Size="130, 62" Location="736, 996" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="eventDrivenActivity_Cancel" Size="150, 209" Location="524, 818"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130, 44" Location="534, 883" /> <SetStateDesigner Name="setStateActivity13" Size="130, 62" Location="534, 946" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="eventDrivenActivity_Finish" Size="150, 209" Location="524, 844"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130, 44" Location="534, 909" /> <SetStateDesigner Name="setStateActivity12" Size="130, 62" Location="534, 972" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="248, 126" AutoSizeMargin="16, 24" Location="46, 237" Name="confirmDeletingAllVersionsStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="stateInitializationActivity2" Size="381, 378" Location="54, 270"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="ifElse_HasMultipleVersions" Size="361, 294" Location="64, 335"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="branch_HasMultipleVersions" Size="150, 191" Location="83, 409"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="codeActivity_SetupDeleteMultipleVersionsForm" Size="130, 44" Location="93, 474" /> <ActivityDesigner Name="confirmDialogFormActivity2" Size="130, 44" Location="93, 537" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="branch_HasSingleVersion" Size="150, 191" Location="256, 409"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity16" Size="130, 62" Location="266, 496" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="versions_eventDrivenActivity_Ok" Size="381, 396" Location="54, 296"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity4" Size="130, 44" Location="179, 361" /> <IfElseDesigner Name="ifElseActivity_DeleteAllVersions" Size="361, 249" Location="64, 424"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity_DeleteAllVersions" Size="150, 146" Location="83, 498"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity10" Size="130, 62" Location="93, 563" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity_DeleteCurrentVersion" Size="150, 146" Location="256, 498"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity19" Size="130, 62" Location="266, 563" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="versions_eventDrivenActivity_Cancel" Size="150, 209" Location="54, 322"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity5" Size="130, 44" Location="64, 387" /> <SetStateDesigner Name="setStateActivity14" Size="130, 62" Location="64, 450" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="224, 80" AutoSizeMargin="16, 24" Location="70, 428" Name="checkForCompositionsStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeInitializationActivity" Size="381, 396" Location="78, 461"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="ifElse_HasInstanceCompositions" Size="361, 312" Location="88, 526"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="branchHasCompositions" Size="150, 209" Location="107, 600"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_ShowError_InstanceCompositions" Size="130, 44" Location="117, 665" /> <SetStateDesigner Name="setStateActivity6" Size="130, 62" Location="117, 728" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="branchNoCompositions" Size="150, 209" Location="280, 600"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="caCheckChildren" Size="130, 41" Location="290, 665" /> <SetStateDesigner Name="setStateActivity15" Size="130, 62" Location="290, 725" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="216, 80" AutoSizeMargin="16, 24" Location="532, 172" Name="deleteCurrentVersionStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="stateInitializationActivity4" Size="150, 209" Location="540, 205"> <StateInitializationDesigner.Designers> <CodeDesigner Name="codeActivity_DeleteCurrentVersion" Size="130, 44" Location="550, 270" /> <SetStateDesigner Name="setStateActivity18" Size="130, 62" Location="550, 333" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/DeletePageWorkflow.rules ================================================  ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/EditPageWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { partial class EditPageWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition3 = new System.Workflow.Activities.CodeCondition(); this.showConsoleMessageBoxActivity1 = new Composite.C1Console.Workflow.Activities.ShowConsoleMessageBoxActivity(); this.saveCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.setToPublishCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity6 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity5 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.newPageTypeSelectedCodeActivity_UpdateView = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.ifElseActivity2 = new System.Workflow.Activities.IfElseActivity(); this.saveAndPublishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveAndPublishHandleExternalEventActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.customEvent01HandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CustomEvent01HandleExternalEventActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.editPreviewCodeActivity = new System.Workflow.Activities.CodeActivity(); this.previewHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.PreviewHandleExternalEventActivity(); this.ifElseActivity2_PageStillExists = new System.Workflow.Activities.IfElseActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.editStateCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.newPageTypeSelectedStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editEventDrivenActivity_SaveAndPublish = new System.Workflow.Activities.EventDrivenActivity(); this.editEventDrivenActivity_PageTypeChanged = new System.Workflow.Activities.EventDrivenActivity(); this.editEventDrivenActivity_Preview = new System.Workflow.Activities.EventDrivenActivity(); this.editEventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.newPageTypeSelectedStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); // // showConsoleMessageBoxActivity1 // this.showConsoleMessageBoxActivity1.DialogType = Composite.C1Console.Events.DialogType.Message; this.showConsoleMessageBoxActivity1.Message = "${Composite.Plugins.PageElementProvider, PageSaveValidationFailedMessage}"; this.showConsoleMessageBoxActivity1.Name = "showConsoleMessageBoxActivity1"; this.showConsoleMessageBoxActivity1.Title = "${Composite.Plugins.PageElementProvider, PageSaveValidationFailedTitle}"; // // saveCodeActivity // this.saveCodeActivity.Name = "saveCodeActivity"; this.saveCodeActivity.ExecuteCode += new System.EventHandler(this.saveCodeActivity_ExecuteCode); // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "finalStateActivity"; // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "saveStateActivity"; // // setToPublishCodeActivity // this.setToPublishCodeActivity.Name = "setToPublishCodeActivity"; this.setToPublishCodeActivity.ExecuteCode += new System.EventHandler(this.setToPublishCodeActivity_ExecuteCode); // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "finalStateActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "saveStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.showConsoleMessageBoxActivity1); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.saveCodeActivity); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateSave); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // ifElseBranchActivity6 // this.ifElseBranchActivity6.Activities.Add(this.setStateActivity10); this.ifElseBranchActivity6.Name = "ifElseBranchActivity6"; // // ifElseBranchActivity5 // this.ifElseBranchActivity5.Activities.Add(this.setToPublishCodeActivity); this.ifElseBranchActivity5.Activities.Add(this.setStateActivity9); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.PageStillExists); this.ifElseBranchActivity5.Condition = codecondition2; this.ifElseBranchActivity5.Name = "ifElseBranchActivity5"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity8); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.setStateActivity2); codecondition3.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.PageStillExists); this.ifElseBranchActivity3.Condition = codecondition3; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "editStateActivity"; // // newPageTypeSelectedCodeActivity_UpdateView // this.newPageTypeSelectedCodeActivity_UpdateView.Name = "newPageTypeSelectedCodeActivity_UpdateView"; this.newPageTypeSelectedCodeActivity_UpdateView.ExecuteCode += new System.EventHandler(this.newPageTypeSelectedCodeActivity_UpdateView_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "editStateActivity"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // ifElseActivity2 // this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity5); this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity6); this.ifElseActivity2.Name = "ifElseActivity2"; // // saveAndPublishHandleExternalEventActivity1 // this.saveAndPublishHandleExternalEventActivity1.EventName = "SaveAndPublish"; this.saveAndPublishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveAndPublishHandleExternalEventActivity1.Name = "saveAndPublishHandleExternalEventActivity1"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "newPageTypeSelectedStateActivity"; // // customEvent01HandleExternalEventActivity1 // this.customEvent01HandleExternalEventActivity1.EventName = "CustomEvent01"; this.customEvent01HandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.customEvent01HandleExternalEventActivity1.Name = "customEvent01HandleExternalEventActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // editPreviewCodeActivity // this.editPreviewCodeActivity.Name = "editPreviewCodeActivity"; this.editPreviewCodeActivity.ExecuteCode += new System.EventHandler(this.editPreviewCodeActivity_ExecuteCode); // // previewHandleExternalEventActivity1 // this.previewHandleExternalEventActivity1.EventName = "Preview"; this.previewHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.previewHandleExternalEventActivity1.Name = "previewHandleExternalEventActivity1"; // // ifElseActivity2_PageStillExists // this.ifElseActivity2_PageStillExists.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity2_PageStillExists.Activities.Add(this.ifElseBranchActivity4); this.ifElseActivity2_PageStillExists.Name = "ifElseActivity2_PageStillExists"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // editStateCodeActivity // this.editStateCodeActivity.Name = "editStateCodeActivity"; this.editStateCodeActivity.ExecuteCode += new System.EventHandler(this.editStateCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "editStateActivity"; // // newPageTypeSelectedStateInitializationActivity // this.newPageTypeSelectedStateInitializationActivity.Activities.Add(this.newPageTypeSelectedCodeActivity_UpdateView); this.newPageTypeSelectedStateInitializationActivity.Activities.Add(this.setStateActivity7); this.newPageTypeSelectedStateInitializationActivity.Name = "newPageTypeSelectedStateInitializationActivity"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.ifElseActivity1); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity1); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // editEventDrivenActivity_SaveAndPublish // this.editEventDrivenActivity_SaveAndPublish.Activities.Add(this.saveAndPublishHandleExternalEventActivity1); this.editEventDrivenActivity_SaveAndPublish.Activities.Add(this.ifElseActivity2); this.editEventDrivenActivity_SaveAndPublish.Name = "editEventDrivenActivity_SaveAndPublish"; // // editEventDrivenActivity_PageTypeChanged // this.editEventDrivenActivity_PageTypeChanged.Activities.Add(this.customEvent01HandleExternalEventActivity1); this.editEventDrivenActivity_PageTypeChanged.Activities.Add(this.setStateActivity6); this.editEventDrivenActivity_PageTypeChanged.Name = "editEventDrivenActivity_PageTypeChanged"; // // editEventDrivenActivity_Preview // this.editEventDrivenActivity_Preview.Activities.Add(this.previewHandleExternalEventActivity1); this.editEventDrivenActivity_Preview.Activities.Add(this.editPreviewCodeActivity); this.editEventDrivenActivity_Preview.Activities.Add(this.setStateActivity4); this.editEventDrivenActivity_Preview.Name = "editEventDrivenActivity_Preview"; // // editEventDrivenActivity_Save // this.editEventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.editEventDrivenActivity_Save.Activities.Add(this.ifElseActivity2_PageStillExists); this.editEventDrivenActivity_Save.Name = "editEventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.editStateCodeActivity); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity3); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // newPageTypeSelectedStateActivity // this.newPageTypeSelectedStateActivity.Activities.Add(this.newPageTypeSelectedStateInitializationActivity); this.newPageTypeSelectedStateActivity.Name = "newPageTypeSelectedStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity5); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.saveStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_Save); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_Preview); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_PageTypeChanged); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_SaveAndPublish); this.editStateActivity.Name = "editStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // EditPageWorkflow // this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.newPageTypeSelectedStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "EditPageWorkflow"; this.CanModifyActivities = false; } #endregion private StateInitializationActivity saveStateInitializationActivity; private EventDrivenActivity editEventDrivenActivity_Save; private StateInitializationActivity editStateInitializationActivity; private StateInitializationActivity initializeStateInitializationActivity; private StateActivity saveStateActivity; private StateActivity editStateActivity; private SetStateActivity setStateActivity1; private CodeActivity saveCodeActivity; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity4; private EventDrivenActivity editEventDrivenActivity_Preview; private C1Console.Workflow.Activities.PreviewHandleExternalEventActivity previewHandleExternalEventActivity1; private CodeActivity editPreviewCodeActivity; private SetStateActivity setStateActivity5; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateActivity finalStateActivity; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private CodeActivity editStateCodeActivity; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private C1Console.Workflow.Activities.ShowConsoleMessageBoxActivity showConsoleMessageBoxActivity1; private SetStateActivity setStateActivity7; private CodeActivity newPageTypeSelectedCodeActivity_UpdateView; private SetStateActivity setStateActivity6; private C1Console.Workflow.Activities.CustomEvent01HandleExternalEventActivity customEvent01HandleExternalEventActivity1; private StateInitializationActivity newPageTypeSelectedStateInitializationActivity; private EventDrivenActivity editEventDrivenActivity_PageTypeChanged; private StateActivity newPageTypeSelectedStateActivity; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElseActivity2_PageStillExists; private SetStateActivity setStateActivity8; private EventDrivenActivity editEventDrivenActivity_SaveAndPublish; private SetStateActivity setStateActivity10; private SetStateActivity setStateActivity9; private CodeActivity setToPublishCodeActivity; private IfElseBranchActivity ifElseBranchActivity6; private IfElseBranchActivity ifElseBranchActivity5; private IfElseActivity ifElseActivity2; private C1Console.Workflow.Activities.SaveAndPublishHandleExternalEventActivity saveAndPublishHandleExternalEventActivity1; private StateActivity initializeStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/EditPageWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web.UI; using System.Workflow.Activities; using System.Workflow.Runtime; using System.Xml.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Forms; using Composite.C1Console.Forms.DataServices; using Composite.C1Console.Forms.Flows; using Composite.C1Console.Security; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.C1Console.Workflow.Activities; using Composite.Core; using Composite.Core.Collections.Generic; using Composite.Core.Configuration; using Composite.Core.Extensions; using Composite.Core.Linq; using Composite.Core.PageTemplates; using Composite.Core.ResourceSystem; using Composite.Core.Routing.Foundation.PluginFacades; using Composite.Core.Types; using Composite.Core.WebClient.FlowMediators.FormFlowRendering; using Composite.Core.WebClient.Renderings.Page; using Composite.Core.Xml; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.Transactions; using Composite.Data.Types; using Composite.Data.Validation; using Composite.Data.Validation.ClientValidationRules; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { [EntityTokenLock] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditPageWorkflow : FormsWorkflow { [NonSerialized] private bool _doPublish; public EditPageWorkflow() { InitializeComponent(); InitializeExtensions(); } private static DataTypeDescriptorFormsHelper CreateDataTypeDescriptorFormsHelper(IPageMetaDataDefinition pageMetaDataDefinition, DataTypeDescriptor dataTypeDescriptor) { var bindingPrefix = $"{pageMetaDataDefinition.Name}:{dataTypeDescriptor.Namespace}.{dataTypeDescriptor.Name}"; var helper = new DataTypeDescriptorFormsHelper(dataTypeDescriptor, bindingPrefix); var generatedTypesHelper = new GeneratedTypesHelper(dataTypeDescriptor); helper.AddReadOnlyFields(generatedTypesHelper.NotEditableDataFieldDescriptorNames); helper.FieldGroupLabel = StringResourceSystemFacade.ParseString(pageMetaDataDefinition.Label); return helper; } private List<KeyValuePair<Guid, string>> GetSelectablePageTypes() { var selectedPage = GetBinding<IPage>("SelectedPage"); var parentPageId = selectedPage.GetParentId(); IPage parentPage = null; if (parentPageId != Guid.Empty) { parentPage = PageManager.GetPageById(parentPageId); if (parentPage == null && GlobalSettingsFacade.AllowChildPagesTranslationWithoutParent) { using (new DataScope(DataLocalizationFacade.DefaultLocalizationCulture)) { parentPage = PageManager.GetPageById(parentPageId); } } } return parentPage.GetChildPageSelectablePageTypes(selectedPage). Select(f => new KeyValuePair<Guid, string>(f.Id, f.Name)). ToList(); } private List<KeyValuePair<Guid, string>> GetSelectablePageTemplates() { var selectedPage = GetBinding<IPage>("SelectedPage"); var allPageTemplates = PageTemplateFacade.GetPageTemplates().ToList(); var templateRestrictions = DataFacade.GetData<IPageTypePageTemplateRestriction>() .Where(f => f.PageTypeId == selectedPage.PageTypeId) .Select(restriction => restriction.PageTemplateId) .ToList(); IEnumerable<PageTemplateDescriptor> result; if (templateRestrictions.Any()) { var allowedTemplatesHash = new HashSet<Guid>(templateRestrictions); var allowedTemplates = allPageTemplates .Where(template => allowedTemplatesHash.Contains(template.Id)) .ToList(); var selectedTemplateId = selectedPage.TemplateId; var selectedTemplate = allPageTemplates.FirstOrDefault(t => t.Id == selectedTemplateId); if (selectedTemplate != null & !allowedTemplates.Any(t => t.Id == selectedTemplateId)) { allowedTemplates.Add(selectedTemplate); } result = allowedTemplates; } else { result = allPageTemplates; } return result .OrderBy(template => template.Title) .Select(f => new KeyValuePair<Guid, string>(f.Id, f.Title)).ToList(); } private void editStateCodeActivity_ExecuteCode(object sender, EventArgs e) { if (!PermissionsFacade.GetPermissionsForCurrentUser(EntityToken).Contains(PermissionType.Publish)) { var formData = WorkflowFacade.GetFormData(InstanceId, true); if (formData.ExcludedEvents == null) formData.ExcludedEvents = new List<string>(); formData.ExcludedEvents.Add("SaveAndPublish"); } IPage selectedPage; if (!BindingExist("SelectedPage")) { selectedPage = GetDataItemFromEntityToken<IPage>(); if (selectedPage.PublicationStatus == GenericPublishProcessController.Published) { selectedPage.PublicationStatus = GenericPublishProcessController.Draft; } Bindings.Add("SelectedPage", selectedPage); } else { selectedPage = GetBinding<IPage>("SelectedPage"); } if (!BindingExist("UrlTitleIsRequired")) { var isRootPage = PageManager.GetParentId(selectedPage.Id) == Guid.Empty; Bindings["UrlTitleIsRequired"] = !isRootPage; Bindings["IsRootPage"] = isRootPage; } IFormMarkupProvider markupProvider = new FormDefinitionFileMarkupProvider(@"\Administrative\EditPage.xml"); XDocument formDocument; using (var reader = markupProvider.GetReader()) { formDocument = XDocument.Load(reader); } var bindingsXElement = formDocument.Root.Element(DataTypeDescriptorFormsHelper.CmsNamespace + FormKeyTagNames.Bindings); var layoutXElement = formDocument.Root.Element(DataTypeDescriptorFormsHelper.CmsNamespace + FormKeyTagNames.Layout); var tabPanelsXElement = layoutXElement.Element(DataTypeDescriptorFormsHelper.MainNamespace + "TabPanels"); IEnumerable<ICompositionContainer> compositionContainers = selectedPage.GetAllowedMetaDataContainers().Evaluate(); var compositionTabs = new Dictionary<Guid, XElement>(); foreach (var compositionContainer in compositionContainers) { var element = new XElement(Namespaces.BindingFormsStdUiControls10 + "PlaceHolder"); element.Add(new XAttribute("Label", StringResourceSystemFacade.ParseString(compositionContainer.Label))); compositionTabs.Add(compositionContainer.Id, element); } var clientValidationRules = new Dictionary<string, List<ClientValidationRule>>(); var pageMetaDataDefinitions = selectedPage.GetAllowedMetaDataDefinitions(); foreach (var pageMetaDataDefinition in pageMetaDataDefinitions) { var metaDatTypeId = pageMetaDataDefinition.MetaDataTypeId; var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(metaDatTypeId); Verify.IsNotNull(dataTypeDescriptor, "Failed to get meta data type by id '{0}'. If data type was purposely removed, in order to fix this exception you should remove IPageMetaDataDefinition records that reference this data type.", metaDatTypeId); var metaDataType = TypeManager.TryGetType(dataTypeDescriptor.TypeManagerTypeName); Verify.IsNotNull(metaDataType, "Failed to get meta data type '{0}', id: {1}. If it has been removed, references from '{2}' have to be removed as well", dataTypeDescriptor.TypeManagerTypeName, metaDatTypeId, typeof(IPageMetaDataDefinition).Name); var helper = CreateDataTypeDescriptorFormsHelper(pageMetaDataDefinition, dataTypeDescriptor); var metaData = selectedPage.GetMetaData(pageMetaDataDefinition.Name, metaDataType); if (metaData == null) { metaData = DataFacade.BuildNew(metaDataType); PageMetaDataFacade.AssignMetaDataSpecificValues(metaData, pageMetaDataDefinition.Name, selectedPage); var localizedData = metaData as ILocalizedControlled; if (localizedData != null) { localizedData.SourceCultureName = UserSettings.ActiveLocaleCultureInfo.Name; } var publishControlled = metaData as IPublishControlled; publishControlled.PublicationStatus = GenericPublishProcessController.Draft; helper.UpdateWithNewBindings(Bindings); helper.ObjectToBindings(metaData, Bindings); } else { helper.UpdateWithBindings(metaData, Bindings); } bindingsXElement.Add(helper.BindingXml.Elements()); compositionTabs[pageMetaDataDefinition.MetaDataContainerId].Add(helper.PanelXml); clientValidationRules.AddDictionary(helper.GetBindingsValidationRules(metaData)); } var previewTabPanel = tabPanelsXElement.Elements().Last(); foreach (var element in compositionTabs.Values) { previewTabPanel.AddBeforeSelf(element); } IDictionary<string, string> transitionNames = new Dictionary<string, string>(); transitionNames.Add(GenericPublishProcessController.Draft, StringResourceSystemFacade.GetString("Composite.Management", "PublishingStatus.draft")); transitionNames.Add(GenericPublishProcessController.AwaitingApproval, StringResourceSystemFacade.GetString("Composite.Management", "PublishingStatus.awaitingApproval")); var username = UserValidationFacade.GetUsername(); var userPermissionDefinitions = PermissionTypeFacade.GetUserPermissionDefinitions(username); var userGroupPermissionDefinitions = PermissionTypeFacade.GetUserGroupPermissionDefinitions(username); var currentPermissionTypes = PermissionTypeFacade.GetCurrentPermissionTypes(UserValidationFacade.GetUserToken(), EntityToken, userPermissionDefinitions, userGroupPermissionDefinitions); foreach (var permissionType in currentPermissionTypes) { if (GenericPublishProcessController.AwaitingPublicationActionPermissionType.Contains(permissionType)) { transitionNames.Add(GenericPublishProcessController.AwaitingPublication, StringResourceSystemFacade.GetString("Composite.Management", "PublishingStatus.awaitingPublication")); break; } } var contents = DataFacade.GetData<IPagePlaceholderContent>(false) .Where(f => f.PageId == selectedPage.Id && f.VersionId == selectedPage.VersionId) .ToList(); var namedXhtmlFragments = contents.ToDictionary(content => content.PlaceHolderId, content => content.Content ?? ""); UpdateBinding("SelectablePageTypeIds", GetSelectablePageTypes()); UpdateBinding("SelectableTemplateIds", GetSelectablePageTemplates()); UpdateBinding("NamedXhtmlFragments", namedXhtmlFragments); UpdateBinding("StateOptions", transitionNames); var formDefinition = formDocument.GetDocumentAsString(); DeliverFormData( selectedPage.Title, StandardUiContainerTypes.Document, formDefinition, Bindings, clientValidationRules ); } private void newPageTypeSelectedCodeActivity_UpdateView_ExecuteCode(object sender, EventArgs e) { RerenderView(); } private void saveCodeActivity_ExecuteCode(object sender, EventArgs e) { var updateTreeRefresher = CreateUpdateTreeRefresher(EntityToken); var selectedPage = GetBinding<IPage>("SelectedPage"); var originalPage = DataFacade.GetData<IPage>(f => f.Id == selectedPage.Id && f.VersionId == selectedPage.VersionId).SingleOrDefault(); var viewLabelUpdated = originalPage == null || selectedPage.MenuTitle != originalPage.MenuTitle || selectedPage.Title != originalPage.Title; var dataToAdd = new Dictionary<string, IData>(); var dataToUpdate = new Dictionary<string, IData>(); var dataValidated = true; try { using (var transactionScope = TransactionsFacade.CreateNewScope()) { dataValidated = PrepareAddUpdateMetaData(selectedPage, dataToAdd, dataToUpdate); if (dataValidated) { if (selectedPage.PageTypeId != originalPage.PageTypeId) { // Adding metadata fields var oldPageMetaDataDefinitions = originalPage.GetAllowedMetaDataDefinitions().Except(selectedPage.GetAllowedMetaDataDefinitions(), new PageMetaDataDefinitionEqualityComparer()); foreach (var pageMetaDataDefinition in oldPageMetaDataDefinitions) { var oldMetaData = selectedPage.GetMetaData(pageMetaDataDefinition.Name, pageMetaDataDefinition.MetaDataTypeId); if (oldMetaData != null) { ProcessControllerFacade.FullDelete(oldMetaData); } } PageServices.AddPageTypePageFoldersAndApplications(selectedPage); } foreach (var data in dataToAdd.Values) { DataFacade.AddNew(data); } foreach (var data in dataToUpdate.Values) { var publishControlled = data as IPublishControlled; publishControlled.PublicationStatus = GenericPublishProcessController.Draft; DataFacade.Update(data); } var contentDictionary = GetBinding<Dictionary<string, string>>("NamedXhtmlFragments"); var existingContents = DataFacade.GetData<IPagePlaceholderContent>(false) .Where(f => f.PageId == selectedPage.Id && f.VersionId == selectedPage.VersionId).ToList(); foreach (var existingContent in existingContents) { if (contentDictionary.ContainsKey(existingContent.PlaceHolderId)) { existingContent.Content = contentDictionary[existingContent.PlaceHolderId]; existingContent.PublicationStatus = GenericPublishProcessController.Draft; DataFacade.Update(existingContent); } else { DataFacade.Delete(existingContent); } } foreach (var contentDictionaryElement in contentDictionary .Where(f => !existingContents.Any(existing => existing.PlaceHolderId == f.Key))) { var newContent = DataFacade.BuildNew<IPagePlaceholderContent>(); newContent.PageId = selectedPage.Id; newContent.VersionId = selectedPage.VersionId; newContent.PlaceHolderId = contentDictionaryElement.Key; newContent.Content = contentDictionaryElement.Value; newContent.SourceCultureName = UserSettings.ActiveLocaleCultureInfo.Name; newContent.PublicationStatus = GenericPublishProcessController.Draft; DataFacade.AddNew(newContent); } // NOTE: updating originalPage object, in order to make XML & SQL provider work in the same way originalPage.TemplateId = selectedPage.TemplateId; originalPage.PageTypeId = selectedPage.PageTypeId; originalPage.Title = selectedPage.Title; originalPage.MenuTitle = selectedPage.MenuTitle; originalPage.UrlTitle = selectedPage.UrlTitle; originalPage.FriendlyUrl = selectedPage.FriendlyUrl; originalPage.Description = selectedPage.Description; originalPage.PublicationStatus = selectedPage.PublicationStatus; originalPage.SourceCultureName = selectedPage.SourceCultureName; DataFacade.Update(originalPage); } transactionScope.Complete(); } if (_doPublish) { var actionToken = new GenericPublishProcessController.PublishActionToken(); var serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); ActionExecutorFacade.Execute(EntityToken, actionToken, serviceContainer); } else { updateTreeRefresher.PostRefreshMessages(selectedPage.GetDataEntityToken()); } UpdateBinding("OldPublicationStatus", selectedPage.PublicationStatus); if (viewLabelUpdated) { RerenderView(); } } catch (Exception ex) { var mostSpecificException = ex; while (mostSpecificException.InnerException != null) mostSpecificException = mostSpecificException.InnerException; ShowMessage(DialogType.Error, "Save failed", $"Save failed: {mostSpecificException.Message}"); Log.LogError("Page save", ex); } finally { SetSaveStatus(dataValidated); } } private bool PrepareAddUpdateMetaData(IPage selectedPage, IDictionary<string, IData> dataToAdd, IDictionary<string, IData> dataToUpdate) { var isValid = ValidateBindings(); IEnumerable<IPageMetaDataDefinition> pageMetaDataDefinitions = selectedPage.GetAllowedMetaDataDefinitions().Evaluate(); foreach (var pageMetaDataDefinition in pageMetaDataDefinitions) { var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(pageMetaDataDefinition.MetaDataTypeId); var metaDataType = TypeManager.GetType(dataTypeDescriptor.TypeManagerTypeName); var helper = CreateDataTypeDescriptorFormsHelper(pageMetaDataDefinition, dataTypeDescriptor); var metaData = selectedPage.GetMetaData(pageMetaDataDefinition.Name, metaDataType); if (metaData == null) { var newData = DataFacade.BuildNew(metaDataType); PageMetaDataFacade.AssignMetaDataSpecificValues(newData, pageMetaDataDefinition.Name, selectedPage); var localizedData = newData as ILocalizedControlled; if (localizedData != null) { localizedData.SourceCultureName = UserSettings.ActiveLocaleCultureInfo.Name; } if (!BindAndValidate(helper, newData)) { isValid = false; } dataToAdd.Add(helper.BindingNamesPrefix, newData); } else { if (!BindAndValidate(helper, metaData)) { isValid = false; } dataToUpdate.Add(helper.BindingNamesPrefix, metaData); } } var pageValidationResults = ValidationFacade.Validate(selectedPage); if (!pageValidationResults.IsValid) { isValid = false; } foreach (var kvp in dataToAdd.Concat(dataToUpdate)) { var validationResults = ValidationFacade.Validate(kvp.Value); if (!validationResults.IsValid) { isValid = false; foreach (var result in validationResults) { ShowFieldMessage(DataTypeDescriptorFormsHelper.GetBindingName(kvp.Key, result.Key), result.Message); } } } return isValid; } private void editPreviewCodeActivity_ExecuteCode(object sender, EventArgs e) { var serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); var webRenderService = serviceContainer.GetService<IFormFlowWebRenderingService>(); try { var selectedPage = GetBinding<IPage>("SelectedPage"); var contents = new List<IPagePlaceholderContent>(); var namedXhtmlFragments = GetBinding<Dictionary<string, string>>("NamedXhtmlFragments"); foreach (var placeHolderContent in namedXhtmlFragments) { var content = DataFacade.BuildNew<IPagePlaceholderContent>(); content.PageId = selectedPage.Id; content.VersionId = selectedPage.VersionId; content.PlaceHolderId = placeHolderContent.Key; content.Content = placeHolderContent.Value; contents.Add(content); } var output = PagePreviewBuilder.RenderPreview(selectedPage, contents); webRenderService.SetNewPageOutput(new LiteralControl(output)); } catch (Exception ex) { // TODO: add html encoding for the exception text Control errOutput = new LiteralControl("<pre>" + ex + "</pre>"); webRenderService.SetNewPageOutput(errOutput); } } private static void TrimFieldValues(IPage page) { page.Title = page.Title.Trim(); page.MenuTitle = page.MenuTitle.Trim(); page.UrlTitle = page.UrlTitle.Trim(); page.FriendlyUrl = page.FriendlyUrl?.Trim(); } private bool FieldHasValidLength(string fieldValue, string fieldName, int maximumLength) { if (fieldValue.Length <= maximumLength) { return true; } var bindingName = "SelectedPage." + fieldName; ShowFieldMessage(bindingName, GetText("EditPage.MaxLength").FormatWith(maximumLength)); return false; } private void ValidateSave(object sender, ConditionalEventArgs e) { var selectedPage = GetBinding<IPage>("SelectedPage"); selectedPage.MenuTitle = selectedPage.MenuTitle ?? string.Empty; selectedPage.FriendlyUrl = selectedPage.FriendlyUrl ?? string.Empty; TrimFieldValues(selectedPage); if (!FieldHasValidLength(selectedPage.Title, nameof(IPage.Title), 255) || !FieldHasValidLength(selectedPage.MenuTitle, nameof(IPage.MenuTitle), 192) || !FieldHasValidLength(selectedPage.UrlTitle, nameof(IPage.UrlTitle), 192) || !FieldHasValidLength(selectedPage.FriendlyUrl, nameof(IPage.FriendlyUrl), 64)) { e.Result = false; return; } e.Result = true; var processedUrlTitle = UrlFormattersPluginFacade.FormatUrl(selectedPage.UrlTitle, true); if (selectedPage.UrlTitle != processedUrlTitle) { RerenderView(); selectedPage.UrlTitle = processedUrlTitle; ShowMessage(DialogType.Message, GetText("EditPage.UrlTitleFormattedTitle"), (GetText("EditPage.UrlTitleFormattedMessage") ?? string.Empty).FormatWith(processedUrlTitle)); } var siblingPageUrlTitles = (from page in PageServices.GetChildren(selectedPage.GetParentId()) where page.Id != selectedPage.Id select page.UrlTitle).ToList(); foreach (var siblingUrlTitle in siblingPageUrlTitles) { if (siblingUrlTitle.Equals(selectedPage.UrlTitle, StringComparison.InvariantCultureIgnoreCase)) { ShowFieldMessage("SelectedPage.UrlTitle", "${Composite.Plugins.PageElementProvider, UrlTitleNotUniqueError}"); e.Result = false; break; } } if (!string.IsNullOrEmpty(selectedPage.FriendlyUrl)) { var usedFriendlyUrls = DataFacade.GetData<IPage>(f => f.FriendlyUrl != null && f.FriendlyUrl != string.Empty && f.Id != selectedPage.Id).Select(f => f.FriendlyUrl).ToList(); if (usedFriendlyUrls.Any(f => f.Equals(selectedPage.FriendlyUrl, StringComparison.InvariantCultureIgnoreCase))) { ShowFieldMessage("SelectedPage.FriendlyUrl", "${Composite.Plugins.PageElementProvider, FriendlyUrlNotUniqueError}"); e.Result = false; } } if (string.IsNullOrEmpty(selectedPage.Title)) { ShowFieldMessage("SelectedPage.Title", "${Composite.Plugins.PageElementProvider, TitleMissingError}"); e.Result = false; } var validationResults = ValidationFacade.Validate(selectedPage); if (!validationResults.IsValid) { if (validationResults.Any(f => f.Key == "UrlTitle")) { ShowFieldMessage("SelectedPage.UrlTitle", "${Composite.Plugins.PageElementProvider, UrlTitleNotValidError}"); e.Result = false; } foreach (var validationResult in validationResults.Where(f => f.Key != "UrlTitle")) { ShowFieldMessage("SelectedPage." + validationResult.Key, validationResult.Message); } } if (!ValidateBindings()) { e.Result = false; } } private static string GetText(string key) { return StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", key); } private void PageStillExists(object sender, ConditionalEventArgs e) { var selectedPage = GetBinding<IPage>("SelectedPage"); var originalPage = DataFacade.GetData<IPage>(f => f.Id == selectedPage.Id && f.VersionId == selectedPage.VersionId).SingleOrDefault(); e.Result = originalPage != null; } private void setToPublishCodeActivity_ExecuteCode(object sender, EventArgs e) { _doPublish = true; } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/EditPageWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1199; 932" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="EditPageWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="227; 80" AutoSizeMargin="16; 24" Location="63; 105" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 146" Location="71; 138"> <StateInitializationDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130; 62" Location="81; 203" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="282; 178" AutoSizeMargin="16; 24" AutoSize="False" Location="63; 201" Name="editStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="editStateInitializationActivity" Size="150; 128" Location="431; 141"> <StateInitializationDesigner.Designers> <CodeDesigner Name="editStateCodeActivity" Size="130; 44" Location="441; 206" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="editEventDrivenActivity_Save" Size="381; 396" Location="431; 167"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130; 44" Location="556; 232" /> <IfElseDesigner Name="ifElseActivity2_PageStillExists" Size="361; 249" Location="441; 295"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity3" Size="150; 146" Location="460; 369"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity2" Size="130; 62" Location="470; 434" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity4" Size="150; 146" Location="633; 369"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity8" Size="130; 62" Location="643; 434" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="editEventDrivenActivity_Preview" Size="150; 272" Location="431; 193"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="previewHandleExternalEventActivity1" Size="130; 44" Location="441; 258" /> <CodeDesigner Name="editPreviewCodeActivity" Size="130; 44" Location="441; 321" /> <SetStateDesigner Name="setStateActivity4" Size="130; 62" Location="441; 384" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="editEventDrivenActivity_PageTypeChanged" Size="150; 209" Location="431; 219"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="customEvent01HandleExternalEventActivity1" Size="130; 44" Location="441; 284" /> <SetStateDesigner Name="setStateActivity6" Size="130; 62" Location="441; 347" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="editEventDrivenActivity_SaveAndPublish" Size="381; 459" Location="439; 154"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveAndPublishHandleExternalEventActivity1" Size="130; 44" Location="564; 219" /> <IfElseDesigner Name="ifElseActivity2" Size="361; 312" Location="449; 282"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity5" Size="150; 209" Location="468; 356"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="setToPublishCodeActivity" Size="130; 44" Location="478; 421" /> <SetStateDesigner Name="setStateActivity9" Size="130; 62" Location="478; 484" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity6" Size="150; 209" Location="641; 356"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity10" Size="130; 62" Location="651; 452" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="206; 80" AutoSizeMargin="16; 24" Location="63; 395" Name="saveStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="saveStateInitializationActivity" Size="381; 396" Location="71; 428"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="ifElseActivity1" Size="361; 231" Location="81; 493"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 128" Location="100; 567"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="saveCodeActivity" Size="130; 44" Location="110; 632" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 128" Location="273; 567"> <IfElseBranchDesigner.Designers> <ActivityDesigner Name="showConsoleMessageBoxActivity1" Size="130; 44" Location="283; 632" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> <SetStateDesigner Name="setStateActivity1" Size="130; 62" Location="196; 743" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 209" Location="38; 63"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 44" Location="48; 128" /> <SetStateDesigner Name="setStateActivity5" Size="130; 62" Location="48; 191" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="63; 491" Name="finalStateActivity" /> <StateDesigner Size="304; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="63; 587" Name="newPageTypeSelectedStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="newPageTypeSelectedStateInitializationActivity" Size="150; 209" Location="71; 620"> <StateInitializationDesigner.Designers> <CodeDesigner Name="newPageTypeSelectedCodeActivity_UpdateView" Size="130; 44" Location="81; 685" /> <SetStateDesigner Name="setStateActivity7" Size="130; 62" Location="81; 748" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity5" SourceActivity="EditPageWorkflow" TargetConnectionIndex="0" SourceStateName="EditPageWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="74" /> <ns0:Point X="143" Y="74" /> <ns0:Point X="143" Y="491" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity3" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="286" Y="149" /> <ns0:Point X="302" Y="149" /> <ns0:Point X="302" Y="190" /> <ns0:Point X="204" Y="190" /> <ns0:Point X="204" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" SetStateName="setStateActivity2" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editEventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="264" Y="271" /> <ns0:Point X="352" Y="271" /> <ns0:Point X="352" Y="390" /> <ns0:Point X="166" Y="390" /> <ns0:Point X="166" Y="395" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity8" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editEventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="264" Y="271" /> <ns0:Point X="352" Y="271" /> <ns0:Point X="352" Y="486" /> <ns0:Point X="143" Y="486" /> <ns0:Point X="143" Y="491" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity4" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Bottom" SourceConnectionEdge="Right" EventHandlerName="editEventDrivenActivity_Preview" SourceConnectionIndex="2" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="641" Y="204" /> <ns0:Point X="713" Y="204" /> <ns0:Point X="713" Y="292" /> <ns0:Point X="564" Y="292" /> <ns0:Point X="564" Y="286" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="newPageTypeSelectedStateActivity" SetStateName="setStateActivity6" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editEventDrivenActivity_PageTypeChanged" SourceConnectionIndex="3" TargetStateName="newPageTypeSelectedStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="341" Y="323" /> <ns0:Point X="357" Y="323" /> <ns0:Point X="357" Y="582" /> <ns0:Point X="215" Y="582" /> <ns0:Point X="215" Y="587" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" SetStateName="setStateActivity9" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editEventDrivenActivity_SaveAndPublish" SourceConnectionIndex="4" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="326" Y="349" /> <ns0:Point X="350" Y="349" /> <ns0:Point X="350" Y="390" /> <ns0:Point X="166" Y="390" /> <ns0:Point X="166" Y="395" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity10" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editEventDrivenActivity_SaveAndPublish" SourceConnectionIndex="4" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="326" Y="349" /> <ns0:Point X="350" Y="349" /> <ns0:Point X="350" Y="486" /> <ns0:Point X="143" Y="486" /> <ns0:Point X="143" Y="491" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity1" SourceActivity="saveStateActivity" TargetConnectionIndex="0" SourceStateName="saveStateActivity" TargetConnectionEdge="Bottom" SourceConnectionEdge="Right" EventHandlerName="saveStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="265" Y="439" /> <ns0:Point X="281" Y="439" /> <ns0:Point X="281" Y="390" /> <ns0:Point X="204" Y="390" /> <ns0:Point X="204" Y="379" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity7" SourceActivity="newPageTypeSelectedStateActivity" TargetConnectionIndex="0" SourceStateName="newPageTypeSelectedStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Left" EventHandlerName="newPageTypeSelectedStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="67" Y="631" /> <ns0:Point X="51" Y="631" /> <ns0:Point X="51" Y="191" /> <ns0:Point X="204" Y="191" /> <ns0:Point X="204" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/LocalizePageWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.Types; using Composite.Data; using Composite.Data.ProcessControlled; using Composite.Data.ProcessControlled.ProcessControllers.GenericPublishProcessController; using Composite.Data.Types; using Composite.Core.Linq; using Composite.Data.Transactions; using Composite.C1Console.Users; using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { public sealed partial class LocalizePageWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public LocalizePageWorkflow() { InitializeComponent(); } 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)) { var pageFromEntityToken = (IPage) castedEntityToken.Data; Guid sourcePageId = pageFromEntityToken.Id; Guid sourcePageVersionId = pageFromEntityToken.VersionId; using (new DataScope(DataScopeIdentifier.Administrated)) { sourcePage = DataFacade.GetData<IPage>(f => f.Id == sourcePageId && f.VersionId == sourcePageVersionId).Single(); sourcePage = sourcePage.GetTranslationSource(); using (new DataScope(sourcePage.DataSourceId.DataScopeIdentifier)) { sourcePagePlaceholders = DataFacade .GetData<IPagePlaceholderContent>(f => f.PageId == sourcePageId && f.VersionId == sourcePageVersionId) .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)); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/LocalizePageWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { partial class LocalizePageWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_Copy = new System.Workflow.Activities.CodeActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // initializeCodeActivity_Copy // this.initializeCodeActivity_Copy.Name = "initializeCodeActivity_Copy"; this.initializeCodeActivity_Copy.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_Copy_ExecuteCode); // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_Copy); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // LocalizePageWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "LocalizePageWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private CodeActivity initializeCodeActivity_Copy; private SetStateActivity setStateActivity2; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/LocalizePageWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="LocalizePageWorkflow" Location="30; 30" Size="1182; 996" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="LocalizePageWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="LocalizePageWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="1058" Y="179" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity_Copy" Location="108; 231" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="108; 291" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/UnLocalizePageWorkflow.cs ================================================ using System; using Composite.Data; using Composite.Data.Types; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { public sealed partial class UnLocalizePageWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public UnLocalizePageWorkflow() { InitializeComponent(); } private void InitializeCodeActivity_ExecuteCode(object sender, EventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; IPage selectedPage = (IPage)dataEntityToken.Data; PageServices.DeletePage(selectedPage.Id, selectedPage.VersionId, selectedPage.DataSourceId.LocaleScope, false); var parentTreeRefresher = this.CreateParentTreeRefresher(); parentTreeRefresher.PostRefreshMessages(selectedPage.GetDataEntityToken()); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/UnLocalizePageWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { partial class UnLocalizePageWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_Copy = new System.Workflow.Activities.CodeActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // initializeCodeActivity_Copy // this.initializeCodeActivity_Copy.Name = "initializeCodeActivity_Copy"; this.initializeCodeActivity_Copy.ExecuteCode += new System.EventHandler(this.InitializeCodeActivity_ExecuteCode); // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_Copy); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // UnLocalizePageWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "UnLocalizePageWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private CodeActivity initializeCodeActivity_Copy; private SetStateActivity setStateActivity2; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/UnLocalizePageWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="889, 819" AutoSizeMargin="16, 24" AutoSize="False" Location="30, 30" Name="UnLocalizePageWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="UnLocalizePageWorkflow" TargetConnectionIndex="0" SourceStateName="UnLocalizePageWorkflow" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="74" /> <ns0:Point X="256" Y="66" /> <ns0:Point X="296" Y="66" /> <ns0:Point X="296" Y="193" /> <ns0:Point X="143" Y="193" /> <ns0:Point X="143" Y="202" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="286" Y="150" /> <ns0:Point X="302" Y="150" /> <ns0:Point X="302" Y="193" /> <ns0:Point X="143" Y="193" /> <ns0:Point X="143" Y="202" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150, 209" Location="38, 63"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130, 44" Location="48, 128" /> <SetStateDesigner Name="setStateActivity1" Size="130, 62" Location="48, 191" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="227, 80" AutoSizeMargin="16, 24" AutoSize="False" Location="63, 106" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150, 209" Location="399, 154"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_Copy" Size="130, 44" Location="409, 219" /> <SetStateDesigner Name="setStateActivity2" Size="130, 62" Location="409, 282" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160, 80" AutoSizeMargin="16, 24" Location="63, 202" Name="finalStateActivity" /> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/UndoUnpublishedChangesWorkflow.cs ================================================ using System; using System.Linq; using Composite.Data; using Composite.Data.Types; using System.Collections.Generic; using System.Transactions; using Composite.Data.Transactions; using Composite.Data.ProcessControlled; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { public sealed partial class UndoUnpublishedChangesWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public UndoUnpublishedChangesWorkflow() { InitializeComponent(); } 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(); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/UndoUnpublishedChangesWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageElementProvider { partial class UndoUnpublishedChangesWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.undoCodeActivity_Undo = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.undoStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.undoStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // undoCodeActivity_Undo // this.undoCodeActivity_Undo.Name = "undoCodeActivity_Undo"; this.undoCodeActivity_Undo.ExecuteCode += new System.EventHandler(this.undoCodeActivity_Undo_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "undoStateActivity"; // // undoStateInitializationActivity // this.undoStateInitializationActivity.Activities.Add(this.undoCodeActivity_Undo); this.undoStateInitializationActivity.Activities.Add(this.setStateActivity3); this.undoStateInitializationActivity.Name = "undoStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // undoStateActivity // this.undoStateActivity.Activities.Add(this.undoStateInitializationActivity); this.undoStateActivity.Name = "undoStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // UndoUnpublishedChangesWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.undoStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "UndoUnpublishedChangesWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity3; private CodeActivity undoCodeActivity_Undo; private SetStateActivity setStateActivity2; private StateInitializationActivity undoStateInitializationActivity; private StateActivity undoStateActivity; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageElementProvider/UndoUnpublishedChangesWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="UndoUnpublishedChangesWorkflow" Location="30; 30" Size="1158; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="UndoUnpublishedChangesWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="UndoUnpublishedChangesWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="undoStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="undoStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="487" Y="179" /> <ns0:Point X="487" Y="437" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="undoStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="undoStateActivity" EventHandlerName="undoStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="581" Y="478" /> <ns0:Point X="1058" Y="478" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="108; 231" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="undoStateActivity" Location="389; 437" Size="196; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="undoStateInitializationActivity" Location="534; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="undoCodeActivity_Undo" Location="544; 210" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="544; 270" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/AddNewMasterPagePageTemplateWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { partial class AddNewMasterPagePageTemplateWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseActivity2 = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.showFieldErrorCodeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity2 = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity1 = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.finializeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.initalizeStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "step1StateActivity"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finializeStateActivity"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity7); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.setStateActivity6); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateFilePath); this.ifElseBranchActivity3.Condition = codecondition1; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // ifElseActivity2 // this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity4); this.ifElseActivity2.Name = "ifElseActivity2"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "step1StateActivity"; // // showFieldErrorCodeActivity // this.showFieldErrorCodeActivity.Name = "showFieldErrorCodeActivity"; this.showFieldErrorCodeActivity.ExecuteCode += new System.EventHandler(this.showFieldErrorCodeActivity_ExecuteCode); // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.ifElseActivity2); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.showFieldErrorCodeActivity); this.ifElseBranchActivity1.Activities.Add(this.setStateActivity5); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsTitleUsed); this.ifElseBranchActivity1.Condition = codecondition2; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // codeActivity2 // this.codeActivity2.Name = "codeActivity2"; this.codeActivity2.ExecuteCode += new System.EventHandler(this.codeActivity2_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = "Add new"; this.wizzardFormActivity1.FormDefinitionFileName = "\\Administrative\\PageTemplate\\AddNewMasterPagePageTemplate.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "step1StateActivity"; // // codeActivity1 // this.codeActivity1.Name = "codeActivity1"; this.codeActivity1.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.codeActivity2); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity4); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.ifElseActivity1); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.wizzardFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.codeActivity1); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity1); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity3); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // finializeStateActivity // this.finializeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finializeStateActivity.Name = "finializeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // initalizeStateActivity // this.initalizeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initalizeStateActivity.Name = "initalizeStateActivity"; // // AddNewMasterPagePageTemplateWorkflow // this.Activities.Add(this.initalizeStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initalizeStateActivity"; this.Name = "AddNewMasterPagePageTemplateWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity1; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateInitializationActivity step1StateInitializationActivity; private StateInitializationActivity initializeStateInitializationActivity; private StateActivity finalStateActivity; private StateActivity finializeStateActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity6; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private CodeActivity codeActivity1; private C1Console.Workflow.Activities.DataDialogFormActivity wizzardFormActivity1; private CodeActivity codeActivity2; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private CodeActivity showFieldErrorCodeActivity; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity7; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElseActivity2; private StateActivity initalizeStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/AddNewMasterPagePageTemplateWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Workflow; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.PageTemplates; using Composite.Core.PageTemplates.Foundation; using Composite.Core.PageTemplates.Foundation.PluginFacade; using Composite.Core.ResourceSystem; using Composite.Plugins.Elements.ElementProviders.Common; using Composite.Plugins.PageTemplates.MasterPages; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewMasterPagePageTemplateWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { private static readonly string Binding_Title = "Title"; private static readonly string Marker_TemplateId = "%TemplateId%"; private static readonly string Marker_TemplateTitle = "%TemplateTitle%"; private static readonly string Marker_Codebehind = "%Codebehind%"; private static readonly string NewMasterPage_Markup = PageTemplateHelper.LoadDefaultTemplateFile("MasterPage.txt"); private static readonly string NewMasterPage_Codebehind = PageTemplateHelper.LoadDefaultTemplateFile("MasterPage.cs.txt"); public AddNewMasterPagePageTemplateWorkflow() { InitializeComponent(); } private void codeActivity1_ExecuteCode(object sender, EventArgs e) { this.Bindings.Add(Binding_Title, string.Empty); List<KeyValuePair<Guid, string>> templatesOptions = (from template in PageTemplateFacade.GetPageTemplates().OfType<MasterPagePageTemplateDescriptor>() where template.IsValid && TemplateIsClonable(template) orderby template.Title select new KeyValuePair<Guid, string>(template.Id, template.Title)).ToList(); templatesOptions.Insert(0, new KeyValuePair<Guid, string>( Guid.Empty, GetText("AddNewMasterPagePageTemplate.LabelCopyFromEmptyOption"))); Guid mostUsedTemplate = PageTemplateHelper.GetTheMostUsedTemplate(templatesOptions.Select(p => p.Key)); this.Bindings.Add("CopyOfOptions", templatesOptions); this.Bindings.Add("CopyOfId", mostUsedTemplate); } private void codeActivity2_ExecuteCode(object sender, EventArgs e) { AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken); Guid newTemplateId = Guid.NewGuid(); string newTitle = this.GetBinding<string>(Binding_Title); string newPageTemplate_Markup, newPageTemplate_Codebehind, templateFolder; Guid copyOfId = this.GetBinding<Guid>("CopyOfId"); if (copyOfId == Guid.Empty) { newPageTemplate_Markup = NewMasterPage_Markup; newPageTemplate_Codebehind = NewMasterPage_Codebehind; templateFolder = GetMasterPagesRootFolder(); } else { ParseTemplateForCopying(copyOfId, out newPageTemplate_Markup, out newPageTemplate_Codebehind, out templateFolder); } string masterFilePath, codeFilePath; GenerateFileNames(templateFolder, newTitle, newTemplateId, out masterFilePath, out codeFilePath); newPageTemplate_Markup = newPageTemplate_Markup.Replace(Marker_Codebehind, Path.GetFileName(codeFilePath)); newPageTemplate_Codebehind = newPageTemplate_Codebehind .Replace(Marker_TemplateId, newTemplateId.ToString()) .Replace(Marker_TemplateTitle, CSharpEncodeString(newTitle)); C1File.WriteAllText(codeFilePath, newPageTemplate_Codebehind); C1File.WriteAllText(masterFilePath, newPageTemplate_Markup); var entityToken = new PageTemplateEntityToken(newTemplateId); PageTemplateProviderRegistry.FlushTemplates(); addNewTreeRefresher.PostRefreshMesseges(entityToken); this.ExecuteAction(entityToken, new WorkflowActionToken(typeof(EditMasterPageWorkflow))); } private static void GenerateFileNames(string root, string templateTitle, Guid templateId, out string masterFilePath, out string codeFilePath) { string baseFileName = PathUtil.CleanFileName(templateTitle, true) ?? templateId.ToString(); for(int i=0; i<100; i++) { string fileName = baseFileName + (i == 0 ? "" : "_" + i.ToString()); string _masterPageFilePath = Path.Combine(root, fileName + ".master"); string _codebehindFilePath = Path.Combine(root, fileName + ".master.cs"); if (!C1File.Exists(_masterPageFilePath) && !C1File.Exists(_codebehindFilePath)) { masterFilePath = _masterPageFilePath; codeFilePath = _codebehindFilePath; return; } } throw new InvalidOperationException("Failed to generate file name"); } private string GetMasterPagesRootFolder() { foreach(string providerName in PageTemplateProviderRegistry.ProviderNames) { var provider = PageTemplateProviderPluginFacade.GetProvider(providerName); if(provider is MasterPagePageTemplateProvider) { return (provider as MasterPagePageTemplateProvider).TemplateDirectoryPath; } } throw new InvalidOperationException("Failed to get instance of " + typeof(MasterPagePageTemplateProvider)); } private static string CSharpEncodeString(string text) { return text.Replace("\\", "\\\\").Replace("\"", "\\\""); } private void ParseTemplateForCopying( Guid templateId, out string markupTemplate, out string codebehindTemplate, out string templateFolder) { var masterTemplate = PageTemplateFacade.GetPageTemplate(templateId) as MasterPagePageTemplateDescriptor; Verify.IsNotNull(masterTemplate, "Failed to get MasterPagePageTemplateDescriptor by template id '{0}'", templateId); var provider = PageTemplateProviderRegistry.GetProviderByTemplateId(templateId) as MasterPagePageTemplateProvider; Verify.IsNotNull(provider, "Failed to get MasterPagePageTemplateProvider by template id '{0}'", templateId); string markup = C1File.ReadAllText(masterTemplate.FilePath); string codebehind = C1File.ReadAllText(masterTemplate.CodeBehindFilePath); string codebehindFileName = Path.GetFileName(masterTemplate.CodeBehindFilePath); // Parsing markup markup = markup.Replace(codebehindFileName, Marker_Codebehind); // Parsing codebehind const string quote = @""""; Verify.That(codebehind.IndexOf(templateId.ToString(), StringComparison.OrdinalIgnoreCase) > 0, "Failed to replace existing templateId '{0}'", templateId); codebehind = codebehind.Replace(templateId.ToString(), Marker_TemplateId, StringComparison.OrdinalIgnoreCase); // Replacing title, considering 2 types of encoding codebehind = codebehind.Replace("@" + quote + masterTemplate.Title.Replace(quote, quote + quote) + quote, quote + Marker_TemplateTitle + quote); codebehind = codebehind.Replace(quote + CSharpEncodeString(masterTemplate.Title) + quote, quote + Marker_TemplateTitle + quote); markupTemplate = markup; codebehindTemplate = codebehind; templateFolder = Path.GetDirectoryName(masterTemplate.CodeBehindFilePath); } private void IsTitleUsed(object sender, ConditionalEventArgs e) { string title = this.GetBinding<string>(Binding_Title); e.Result = PageTemplateFacade.GetPageTemplates() .Any(f => f.Title.Equals(title, StringComparison.InvariantCultureIgnoreCase)); } private void ValidateFilePath(object sender, ConditionalEventArgs e) { string title = this.GetBinding<string>(Binding_Title); string rootFolder = GetMasterPagesRootFolder(); string masterFilePath, csFilePath; GenerateFileNames(rootFolder, title, new Guid(), out masterFilePath, out csFilePath); const int maximumFilePathLength = 250; if (masterFilePath.Length > maximumFilePathLength || csFilePath.Length > maximumFilePathLength) { ShowFieldMessage(Binding_Title, GetText("AddNewMasterPagePageTemplateWorkflow.TitleTooLong")); e.Result = false; return; } e.Result = true; } private bool TemplateIsClonable(MasterPagePageTemplateDescriptor templateDescriptor) { string codebehindFile = templateDescriptor.CodeBehindFilePath; if(codebehindFile == null) { return false; } string masterFile = templateDescriptor.FilePath; string codebehindFileReference = "\"" + Path.GetFileName(codebehindFile) + "\""; string templateId = templateDescriptor.Id.ToString(); return C1File.ReadAllText(codebehindFile).IndexOf(templateId, StringComparison.OrdinalIgnoreCase) > 0 && C1File.ReadAllText(masterFile).IndexOf(codebehindFileReference, StringComparison.OrdinalIgnoreCase) > 0; } private void showFieldErrorCodeActivity_ExecuteCode(object sender, EventArgs e) { ShowFieldMessage(Binding_Title, GetText("AddNewMasterPagePageTemplateWorkflow.TitleInUseTitle")); } private static string GetText(string stringName) { return StringResourceSystemFacade.GetString("Composite.Plugins.MasterPagePageTemplate", stringName); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/AddNewMasterPagePageTemplateWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="941, 659" AutoSizeMargin="16, 24" AutoSize="False" Location="30, 30" Name="AddNewMasterPagePageTemplateWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="AddNewMasterPagePageTemplateWorkflow" TargetConnectionIndex="0" SourceStateName="AddNewMasterPagePageTemplateWorkflow" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="710" Y="71" /> <ns0:Point X="710" Y="502" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="initalizeStateActivity" TargetConnectionIndex="0" SourceStateName="initalizeStateActivity" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="502" Y="142" /> <ns0:Point X="518" Y="142" /> <ns0:Point X="518" Y="190" /> <ns0:Point X="397" Y="190" /> <ns0:Point X="397" Y="197" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="612" Y="169" /> <ns0:Point X="628" Y="169" /> <ns0:Point X="628" Y="97" /> <ns0:Point X="514" Y="97" /> <ns0:Point X="514" Y="104" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finializeStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finializeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="495" Y="262" /> <ns0:Point X="512" Y="262" /> <ns0:Point X="512" Y="338" /> <ns0:Point X="392" Y="338" /> <ns0:Point X="392" Y="350" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="612" Y="169" /> <ns0:Point X="628" Y="169" /> <ns0:Point X="628" Y="97" /> <ns0:Point X="514" Y="97" /> <ns0:Point X="514" Y="104" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="499" Y="286" /> <ns0:Point X="710" Y="286" /> <ns0:Point X="710" Y="502" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="finializeStateActivity" TargetConnectionIndex="0" SourceStateName="finializeStateActivity" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="491" Y="391" /> <ns0:Point X="710" Y="391" /> <ns0:Point X="710" Y="502" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="210, 80" AutoSizeMargin="16, 24" Location="296, 101" Name="initalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150, 182" Location="304, 132"> <StateInitializationDesigner.Designers> <CodeDesigner Name="codeActivity1" Size="130, 41" Location="314, 194" /> <SetStateDesigner Name="setStateActivity1" Size="130, 41" Location="314, 254" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="211, 118" AutoSizeMargin="16, 24" AutoSize="False" Location="292, 197" Name="step1StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1StateInitializationActivity" Size="150, 122" Location="425, 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizzardFormActivity1" Size="130, 41" Location="435, 210" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Finish" Size="612, 544" Location="417, 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130, 41" Location="658, 221" /> <IfElseDesigner Name="ifElseActivity1" Size="592, 403" Location="427, 281"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150, 303" Location="446, 352"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="showFieldErrorCodeActivity" Size="130, 41" Location="456, 414" /> <SetStateDesigner Name="setStateActivity5" Size="130, 41" Location="456, 474" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="381, 303" Location="619, 352"> <IfElseBranchDesigner.Designers> <IfElseDesigner Name="ifElseActivity2" Size="361, 222" Location="629, 414"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity3" Size="150, 122" Location="648, 485"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity6" Size="130, 41" Location="658, 547" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity4" Size="150, 122" Location="821, 485"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity7" Size="130, 41" Location="831, 547" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Cancel" Size="150, 182" Location="417, 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130, 41" Location="427, 245" /> <SetStateDesigner Name="setStateActivity4" Size="130, 41" Location="427, 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205, 80" AutoSizeMargin="16, 24" Location="290, 350" Name="finializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150, 242" Location="298, 381"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="closeCurrentViewActivity1" Size="130, 41" Location="308, 443" /> <CodeDesigner Name="codeActivity2" Size="130, 41" Location="308, 503" /> <SetStateDesigner Name="setStateActivity2" Size="130, 41" Location="308, 563" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160, 80" AutoSizeMargin="16, 24" Location="630, 502" Name="finalStateActivity" /> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150, 182" Location="38, 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130, 41" Location="48, 123" /> <SetStateDesigner Name="setStateActivity3" Size="130, 41" Location="48, 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/AddNewPageTemplateWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { partial class AddNewPageTemplateWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity2 = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity1 = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.finializeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.initalizeStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // codeActivity2 // this.codeActivity2.Name = "codeActivity2"; this.codeActivity2.ExecuteCode += new System.EventHandler(this.codeActivity2_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finializeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = "Add new"; this.wizzardFormActivity1.FormDefinitionFileName = "\\Administrative\\PageTemplate\\AddNewPageTemplate.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "step1StateActivity"; // // codeActivity1 // this.codeActivity1.Name = "codeActivity1"; this.codeActivity1.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.codeActivity2); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity4); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity5); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.wizzardFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.codeActivity1); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity1); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity3); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // finializeStateActivity // this.finializeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finializeStateActivity.Name = "finializeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // initalizeStateActivity // this.initalizeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initalizeStateActivity.Name = "initalizeStateActivity"; // // AddNewPageTemplateWorkflow // this.Activities.Add(this.initalizeStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initalizeStateActivity"; this.Name = "AddNewPageTemplateWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity1; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateInitializationActivity step1StateInitializationActivity; private StateInitializationActivity initializeStateInitializationActivity; private StateActivity finalStateActivity; private StateActivity finializeStateActivity; private StateActivity step1StateActivity; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private CodeActivity codeActivity1; private C1Console.Workflow.Activities.DataDialogFormActivity wizzardFormActivity1; private CodeActivity codeActivity2; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity5; private StateActivity initalizeStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/AddNewPageTemplateWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Composite.C1Console.Workflow; using Composite.Core.Extensions; using Composite.Core.PageTemplates; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewPageTemplateWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { private static readonly string Binding_TemplateTypeOptions = "TemplateTypeOptions"; private static readonly string Binding_TemplateTypeId = "TemplateTypeId"; public AddNewPageTemplateWorkflow() { InitializeComponent(); } private void codeActivity1_ExecuteCode(object sender, EventArgs e) { var templateTypes = new List<Tuple<string, string, int>>(); foreach (var providerInfo in PageTemplateFacade.GetProviders()) { var provider = providerInfo.Value; if (provider.AddNewTemplateWorkflow == null) continue; templateTypes.Add(new Tuple<string, string, int>( providerInfo.Key, !provider.AddNewTemplateLabel.IsNullOrEmpty() ? StringResourceSystemFacade.ParseString(provider.AddNewTemplateLabel) : providerInfo.Key, provider.GetPageTemplates().Count())); } Verify.That(templateTypes.Any(), "No page templates supporting adding new templates defined in configuration"); // Most used page template type will be first in the list and preselected string preseceltedTemplate = templateTypes.OrderByDescending(t => t.Item3).Select(t => t.Item1).First(); List<KeyValuePair<string, string>> options = templateTypes .OrderBy(t => t.Item2) // Sorting alphabetically by label .Select(t => new KeyValuePair<string, string>(t.Item1, t.Item2)).ToList(); this.Bindings.Add(Binding_TemplateTypeOptions, options); this.Bindings.Add(Binding_TemplateTypeId, preseceltedTemplate); } private void codeActivity2_ExecuteCode(object sender, EventArgs e) { string providerName = this.GetBinding<string>(Binding_TemplateTypeId); Type workflowType = PageTemplateFacade.GetProviders() .First(p => p.Key == providerName) .Value.AddNewTemplateWorkflow; this.ExecuteAction(new PageTemplateRootEntityToken(), new WorkflowActionToken(workflowType)); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/AddNewPageTemplateWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="923; 671" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="AddNewPageTemplateWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="AddNewPageTemplateWorkflow" TargetConnectionIndex="0" SourceStateName="AddNewPageTemplateWorkflow" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="623" Y="71" /> <ns0:Point X="623" Y="591" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="initalizeStateActivity" TargetConnectionIndex="0" SourceStateName="initalizeStateActivity" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="252" Y="142" /> <ns0:Point X="261" Y="142" /> <ns0:Point X="261" Y="279" /> <ns0:Point X="197" Y="279" /> <ns0:Point X="197" Y="291" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="299" Y="380" /> <ns0:Point X="623" Y="380" /> <ns0:Point X="623" Y="591" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="finializeStateActivity" TargetConnectionIndex="0" SourceStateName="finializeStateActivity" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="590" Y="453" /> <ns0:Point X="623" Y="453" /> <ns0:Point X="623" Y="591" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finializeStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finializeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="295" Y="356" /> <ns0:Point X="491" Y="356" /> <ns0:Point X="491" Y="412" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="46; 101" Name="initalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 182" Location="54; 132"> <StateInitializationDesigner.Designers> <CodeDesigner Name="codeActivity1" Size="130; 41" Location="64; 194" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="64; 254" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="211; 118" AutoSizeMargin="16; 24" AutoSize="False" Location="92; 291" Name="step1StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1StateInitializationActivity" Size="150; 122" Location="408; 135"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizzardFormActivity1" Size="130; 41" Location="418; 197" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Finish" Size="150; 182" Location="416; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="426; 210" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="426; 270" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Cancel" Size="150; 182" Location="408; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="418; 245" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="418; 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" Location="389; 412" Name="finializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 242" Location="397; 443"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="closeCurrentViewActivity1" Size="130; 41" Location="407; 505" /> <CodeDesigner Name="codeActivity2" Size="130; 41" Location="407; 565" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="407; 625" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="543; 591" Name="finalStateActivity" /> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/AddNewRazorPageTemplateWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { partial class AddNewRazorPageTemplateWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseActivity2 = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.showFieldErrorCodeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity2 = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity1 = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.finializeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.initalizeStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "step1StateActivity"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finializeStateActivity"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity7); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.setStateActivity6); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateFilePath); this.ifElseBranchActivity3.Condition = codecondition1; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // ifElseActivity2 // this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity4); this.ifElseActivity2.Name = "ifElseActivity2"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "step1StateActivity"; // // showFieldErrorCodeActivity // this.showFieldErrorCodeActivity.Name = "showFieldErrorCodeActivity"; this.showFieldErrorCodeActivity.ExecuteCode += new System.EventHandler(this.showFieldErrorCodeActivity_ExecuteCode); // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.ifElseActivity2); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.showFieldErrorCodeActivity); this.ifElseBranchActivity1.Activities.Add(this.setStateActivity5); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsTitleUsed); this.ifElseBranchActivity1.Condition = codecondition2; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // codeActivity2 // this.codeActivity2.Name = "codeActivity2"; this.codeActivity2.ExecuteCode += new System.EventHandler(this.codeActivity2_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = "Add new"; this.wizzardFormActivity1.FormDefinitionFileName = "\\Administrative\\PageTemplate\\AddNewRazorPageTemplate.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "step1StateActivity"; // // codeActivity1 // this.codeActivity1.Name = "codeActivity1"; this.codeActivity1.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.codeActivity2); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity4); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.ifElseActivity1); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.wizzardFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.codeActivity1); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity1); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity3); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // finializeStateActivity // this.finializeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finializeStateActivity.Name = "finializeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // initalizeStateActivity // this.initalizeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initalizeStateActivity.Name = "initalizeStateActivity"; // // AddNewRazorPageTemplateWorkflow // this.Activities.Add(this.initalizeStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initalizeStateActivity"; this.Name = "AddNewRazorPageTemplateWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity1; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateInitializationActivity step1StateInitializationActivity; private StateInitializationActivity initializeStateInitializationActivity; private StateActivity finalStateActivity; private StateActivity finializeStateActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity6; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private CodeActivity codeActivity1; private C1Console.Workflow.Activities.DataDialogFormActivity wizzardFormActivity1; private CodeActivity codeActivity2; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private CodeActivity showFieldErrorCodeActivity; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity7; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElseActivity2; private StateActivity initalizeStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/AddNewRazorPageTemplateWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Workflow; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.PageTemplates; using Composite.Core.PageTemplates.Foundation; using Composite.Core.PageTemplates.Foundation.PluginFacade; using Composite.Core.ResourceSystem; using Composite.Plugins.Elements.ElementProviders.Common; using Composite.Plugins.PageTemplates.Razor; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewRazorPageTemplateWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { private static readonly string Binding_Title = "Title"; private static readonly string Marker_TemplateId = "%TemplateId%"; private static readonly string Marker_TemplateTitle = "%TemplateTitle%"; private static readonly string DefaultRazorTemplateMarkup = PageTemplateHelper.LoadDefaultTemplateFile("RazorPageTemplate.txt"); public AddNewRazorPageTemplateWorkflow() { InitializeComponent(); } private void codeActivity1_ExecuteCode(object sender, EventArgs e) { this.Bindings.Add(Binding_Title, string.Empty); List<KeyValuePair<Guid, string>> templatesOptions = (from template in PageTemplateFacade.GetPageTemplates().OfType<RazorPageTemplateDescriptor>() where template.IsValid orderby template.Title select new KeyValuePair<Guid, string>(template.Id, template.Title)).ToList(); templatesOptions.Insert(0, new KeyValuePair<Guid, string>( Guid.Empty, GetText("AddNewRazorPageTemplate.LabelCopyFromEmptyOption"))); Guid mostUsedTemplate = PageTemplateHelper.GetTheMostUsedTemplate(templatesOptions.Select(p => p.Key)); this.Bindings.Add("CopyOfOptions", templatesOptions); this.Bindings.Add("CopyOfId", mostUsedTemplate); } private void codeActivity2_ExecuteCode(object sender, EventArgs e) { AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken); Guid newTemplateId = Guid.NewGuid(); string newTitle = this.GetBinding<string>(Binding_Title); string newPageTemplateMarkup, folderPath; Guid copyOfId = this.GetBinding<Guid>("CopyOfId"); if (copyOfId == Guid.Empty) { newPageTemplateMarkup = DefaultRazorTemplateMarkup; folderPath = GetRazorTemplatesRootFolder(); } else { ParseExistingTemplateForCopying(copyOfId, out newPageTemplateMarkup, out folderPath); } newPageTemplateMarkup = newPageTemplateMarkup .Replace(Marker_TemplateId, newTemplateId.ToString()) .Replace(Marker_TemplateTitle, CSharpEncodeString(newTitle)); string filePath = GeneratedCshtmlFileName(folderPath, newTitle, newTemplateId); C1File.WriteAllText(filePath, newPageTemplateMarkup); var entityToken = new PageTemplateEntityToken(newTemplateId); PageTemplateProviderRegistry.FlushTemplates(); addNewTreeRefresher.PostRefreshMesseges(entityToken); this.ExecuteAction(entityToken, new WorkflowActionToken(typeof(EditRazorPageTemplateWorkflow))); } private static string GeneratedCshtmlFileName(string root, string templateTitle, Guid TemplateId) { string fileName = PathUtil.CleanFileName(templateTitle, true) ?? TemplateId.ToString(); for(int i=0; i<100; i++) { string filePath = Path.Combine(root, fileName + (i == 0 ? "" : "_" + i.ToString()) + ".cshtml"); if(!C1File.Exists(filePath)) { return filePath; } } throw new InvalidOperationException("Failed to generate file name"); } private string GetRazorTemplatesRootFolder() { foreach(string providerName in PageTemplateProviderRegistry.ProviderNames) { var provider = PageTemplateProviderPluginFacade.GetProvider(providerName); if(provider is RazorPageTemplateProvider) { return (provider as RazorPageTemplateProvider).TemplateDirectoryPath; } } throw new InvalidOperationException("Failed to get instance of " + typeof(RazorPageTemplateProvider)); } private void ParseExistingTemplateForCopying(Guid templateId, out string codeTemplate, out string folderPath) { var razorTemplate = PageTemplateFacade.GetPageTemplate(templateId) as RazorPageTemplateDescriptor; Verify.IsNotNull(razorTemplate, "Failed to get razor template descriptor by id '{0}'", templateId); var provider = PageTemplateProviderRegistry.GetProviderByTemplateId(templateId) as RazorPageTemplateProvider; Verify.IsNotNull(provider, "Failed to get razor template provider by template id '{0}'", templateId); string fullPath = PathUtil.Resolve(razorTemplate.VirtualPath); string text = C1File.ReadAllText(fullPath); const string quote = @""""; Verify.That(text.IndexOf(templateId.ToString(), StringComparison.OrdinalIgnoreCase) > 0, "Failed to replace existing templateId '{0}'", templateId); text = text.Replace(templateId.ToString(), Marker_TemplateId, StringComparison.OrdinalIgnoreCase); // Replacing title text = text.Replace("@" + quote + razorTemplate.Title.Replace(quote, quote + quote) + quote, quote + Marker_TemplateTitle + quote) .Replace(quote + CSharpEncodeString(razorTemplate.Title) + quote, quote + Marker_TemplateTitle + quote); codeTemplate = text; folderPath = Path.GetDirectoryName(fullPath); } private void IsTitleUsed(object sender, ConditionalEventArgs e) { string title = this.GetBinding<string>(Binding_Title); e.Result = PageTemplateFacade.GetPageTemplates() .Any(f => f.Title.Equals(title, StringComparison.InvariantCultureIgnoreCase)); } private void ValidateFilePath(object sender, ConditionalEventArgs e) { string title = this.GetBinding<string>(Binding_Title); string rootFolder = GetRazorTemplatesRootFolder(); string cshtmlFilePath = GeneratedCshtmlFileName(rootFolder, title, new Guid()); const int maximumFilePathLength = 250; if (cshtmlFilePath.Length > maximumFilePathLength) { ShowFieldMessage(Binding_Title, GetText("AddNewRazorPageTemplateWorkflow.TitleTooLong")); e.Result = false; return; } e.Result = true; } private static string CSharpEncodeString(string text) { return text.Replace("\\", "\\\\").Replace("\"", "\\\""); } private void showFieldErrorCodeActivity_ExecuteCode(object sender, EventArgs e) { ShowFieldMessage(Binding_Title, GetText("AddNewRazorPageTemplateWorkflow.TitleInUseTitle")); } private static string GetText(string stringName) { return StringResourceSystemFacade.GetString("Composite.Plugins.RazorPageTemplate", stringName); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/AddNewRazorPageTemplateWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="941, 638" AutoSizeMargin="16, 24" AutoSize="False" Location="30, 30" Name="AddNewRazorPageTemplateWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="AddNewRazorPageTemplateWorkflow" TargetConnectionIndex="0" SourceStateName="AddNewRazorPageTemplateWorkflow" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="574" Y="71" /> <ns0:Point X="574" Y="558" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="initalizeStateActivity" TargetConnectionIndex="0" SourceStateName="initalizeStateActivity" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="445" Y="144" /> <ns0:Point X="460" Y="144" /> <ns0:Point X="460" Y="219" /> <ns0:Point X="356" Y="219" /> <ns0:Point X="356" Y="231" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="612" Y="169" /> <ns0:Point X="626" Y="169" /> <ns0:Point X="626" Y="96" /> <ns0:Point X="514" Y="96" /> <ns0:Point X="514" Y="104" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finializeStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finializeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="454" Y="296" /> <ns0:Point X="474" Y="296" /> <ns0:Point X="474" Y="390" /> <ns0:Point X="306" Y="390" /> <ns0:Point X="306" Y="402" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="612" Y="169" /> <ns0:Point X="626" Y="169" /> <ns0:Point X="626" Y="96" /> <ns0:Point X="514" Y="96" /> <ns0:Point X="514" Y="104" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="458" Y="320" /> <ns0:Point X="574" Y="320" /> <ns0:Point X="574" Y="558" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="finializeStateActivity" TargetConnectionIndex="0" SourceStateName="finializeStateActivity" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="405" Y="443" /> <ns0:Point X="574" Y="443" /> <ns0:Point X="574" Y="558" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="210, 80" AutoSizeMargin="16, 24" Location="239, 103" Name="initalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150, 182" Location="247, 134"> <StateInitializationDesigner.Designers> <CodeDesigner Name="codeActivity1" Size="130, 41" Location="257, 196" /> <SetStateDesigner Name="setStateActivity1" Size="130, 41" Location="257, 256" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="211, 118" AutoSizeMargin="16, 24" AutoSize="False" Location="251, 231" Name="step1StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1StateInitializationActivity" Size="150, 122" Location="425, 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizzardFormActivity1" Size="130, 41" Location="435, 210" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Finish" Size="612, 544" Location="417, 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130, 41" Location="658, 221" /> <IfElseDesigner Name="ifElseActivity1" Size="592, 403" Location="427, 281"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150, 303" Location="446, 352"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="showFieldErrorCodeActivity" Size="130, 41" Location="456, 414" /> <SetStateDesigner Name="setStateActivity5" Size="130, 41" Location="456, 474" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="381, 303" Location="619, 352"> <IfElseBranchDesigner.Designers> <IfElseDesigner Name="ifElseActivity2" Size="361, 222" Location="629, 414"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity3" Size="150, 122" Location="648, 485"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity6" Size="130, 41" Location="658, 547" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity4" Size="150, 122" Location="821, 485"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity7" Size="130, 41" Location="831, 547" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Cancel" Size="150, 182" Location="417, 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130, 41" Location="427, 245" /> <SetStateDesigner Name="setStateActivity4" Size="130, 41" Location="427, 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205, 80" AutoSizeMargin="16, 24" Location="204, 402" Name="finializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150, 242" Location="212, 433"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="closeCurrentViewActivity1" Size="130, 41" Location="222, 495" /> <CodeDesigner Name="codeActivity2" Size="130, 41" Location="222, 555" /> <SetStateDesigner Name="setStateActivity2" Size="130, 41" Location="222, 615" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160, 80" AutoSizeMargin="16, 24" Location="494, 558" Name="finalStateActivity" /> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150, 182" Location="38, 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130, 41" Location="48, 123" /> <SetStateDesigner Name="setStateActivity3" Size="130, 41" Location="48, 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/AddNewXmlPageTemplateWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { partial class AddNewXmlPageTemplateWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseActivity2 = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.showFieldErrorCodeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity2 = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity1 = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.finializeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.initalizeStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "step1StateActivity"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finializeStateActivity"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity7); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.setStateActivity6); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateFilePath); this.ifElseBranchActivity3.Condition = codecondition1; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // ifElseActivity2 // this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity4); this.ifElseActivity2.Name = "ifElseActivity2"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "step1StateActivity"; // // showFieldErrorCodeActivity // this.showFieldErrorCodeActivity.Name = "showFieldErrorCodeActivity"; this.showFieldErrorCodeActivity.ExecuteCode += new System.EventHandler(this.showFieldErrorCodeActivity_ExecuteCode); // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.ifElseActivity2); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.showFieldErrorCodeActivity); this.ifElseBranchActivity1.Activities.Add(this.setStateActivity5); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsTitleUsed); this.ifElseBranchActivity1.Condition = codecondition2; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // codeActivity2 // this.codeActivity2.Name = "codeActivity2"; this.codeActivity2.ExecuteCode += new System.EventHandler(this.codeActivity2_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = "Add new"; this.wizzardFormActivity1.FormDefinitionFileName = "\\Administrative\\PageTemplate\\AddNewXmlPageTemplate.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "step1StateActivity"; // // codeActivity1 // this.codeActivity1.Name = "codeActivity1"; this.codeActivity1.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.codeActivity2); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity4); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.ifElseActivity1); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.wizzardFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.codeActivity1); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity1); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity3); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // finializeStateActivity // this.finializeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finializeStateActivity.Name = "finializeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // initalizeStateActivity // this.initalizeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initalizeStateActivity.Name = "initalizeStateActivity"; // // AddNewPageTemplateWorkflow // this.Activities.Add(this.initalizeStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initalizeStateActivity"; this.Name = "AddNewPageTemplateWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity1; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateInitializationActivity step1StateInitializationActivity; private StateInitializationActivity initializeStateInitializationActivity; private StateActivity finalStateActivity; private StateActivity finializeStateActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity6; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private CodeActivity codeActivity1; private C1Console.Workflow.Activities.DataDialogFormActivity wizzardFormActivity1; private CodeActivity codeActivity2; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private CodeActivity showFieldErrorCodeActivity; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity7; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElseActivity2; private StateActivity initalizeStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/AddNewXmlPageTemplateWorkflow.cs ================================================ using System; using System.Linq; using Composite.C1Console.Actions; using Composite.Core.PageTemplates; using Composite.Core.PageTemplates.Foundation; using Composite.Data; using Composite.Data.Types; using Composite.Core.IO; using Composite.C1Console.Workflow; using Composite.Core.Localization; using System.Workflow.Activities; using Composite.Core.ResourceSystem; using System.Collections.Generic; using Composite.Core.WebClient.Renderings.Template; using System.Xml.Linq; using Composite.Plugins.Elements.ElementProviders.Common; using Composite.Plugins.PageTemplates.XmlPageTemplates; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewXmlPageTemplateWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { private static readonly string _defaultTemplateMarkup = string.Format(PageTemplateHelper.LoadDefaultTemplateFile("XmlPageTemplate.xml"), LocalizationXmlConstants.XmlNamespace); public AddNewXmlPageTemplateWorkflow() { InitializeComponent(); } private void codeActivity1_ExecuteCode(object sender, EventArgs e) { IXmlPageTemplate newPageTemplate = DataFacade.BuildNew<IXmlPageTemplate>(); newPageTemplate.Id = Guid.NewGuid(); newPageTemplate.Title = ""; this.Bindings.Add("NewPageTemplate", newPageTemplate); List<KeyValuePair<Guid, string>> templatesOptions = (from template in PageTemplateFacade.GetPageTemplates() where template is XmlPageTemplateDescriptor && template.IsValid orderby template.Title select new KeyValuePair<Guid, string>(template.Id, template.Title)).ToList(); templatesOptions.Insert(0, new KeyValuePair<Guid, string>( Guid.Empty, GetText("AddNewXmlPageTemplate.LabelCopyFromEmptyOption"))); Guid mostUsedTemplate = PageTemplateHelper.GetTheMostUsedTemplate(templatesOptions.Select(p => p.Key)); this.Bindings.Add("CopyOfOptions", templatesOptions); this.Bindings.Add("CopyOfId", mostUsedTemplate); } private void codeActivity2_ExecuteCode(object sender, EventArgs e) { AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken); IXmlPageTemplate newPageTemplate = this.GetBinding<IXmlPageTemplate>("NewPageTemplate"); string newPageTemplateMarkup = null; Guid copyOfId = this.GetBinding<Guid>("CopyOfId"); if (copyOfId == Guid.Empty) { newPageTemplateMarkup = _defaultTemplateMarkup.Replace(" ", "\t"); } else { XDocument copyDocument = TemplateInfo.GetTemplateDocument(copyOfId); newPageTemplateMarkup = copyDocument.ToString(); } IPageTemplateFile pageTemplateFile = DataFacade.BuildNew<IPageTemplateFile>(); pageTemplateFile.FolderPath = "/"; pageTemplateFile.FileName = string.Format("{0}.xml", PathUtil.CleanFileName(newPageTemplate.Title, true) ?? newPageTemplate.Id.ToString()); //if (FileNameAlreadyUsed(pageTemplateFile)) pageTemplateFile.FileName = newPageTemplate.Id.ToString() + pageTemplateFile.FileName; pageTemplateFile.SetNewContent(newPageTemplateMarkup); DataFacade.AddNew<IPageTemplateFile>(pageTemplateFile, "PageTemplateFileProvider"); newPageTemplate.PageTemplateFilePath = "/" + pageTemplateFile.FileName; newPageTemplate = DataFacade.AddNew<IXmlPageTemplate>(newPageTemplate); PageTemplateProviderRegistry.FlushTemplates(); addNewTreeRefresher.PostRefreshMesseges(newPageTemplate.GetDataEntityToken()); this.ExecuteAction(newPageTemplate.GetDataEntityToken(), new WorkflowActionToken(typeof(EditXmlPageTemplateWorkflow))); } private void IsTitleUsed(object sender, ConditionalEventArgs e) { IXmlPageTemplate newPageTemplate = this.GetBinding<IXmlPageTemplate>("NewPageTemplate"); e.Result = PageTemplateFacade.GetPageTemplates() .Any(f => f.Title.Equals(newPageTemplate.Title, StringComparison.InvariantCultureIgnoreCase)); } private void ValidateFilePath(object sender, ConditionalEventArgs e) { IXmlPageTemplate newPageTemplate = this.GetBinding<IXmlPageTemplate>("NewPageTemplate"); IPageTemplateFile pageTemplateFile = DataFacade.BuildNew<IPageTemplateFile>(); pageTemplateFile.FolderPath = "/"; pageTemplateFile.FileName = GetTemplateFileName(newPageTemplate); if (!DataFacade.ValidatePath<IPageTemplateFile>(pageTemplateFile, "PageTemplateFileProvider")) { ShowFieldMessage("NewPageTemplate.Title", GetText("AddNewXmlPageTemplateWorkflow.TitleTooLong")); e.Result = false; return; } e.Result = true; } private string GetTemplateFileName(IXmlPageTemplate xmlTemplateFile) { string name = PathUtil.CleanFileName(xmlTemplateFile.Title, true) ?? xmlTemplateFile.Id.ToString(); return name + ".xml"; } private void showFieldErrorCodeActivity_ExecuteCode(object sender, EventArgs e) { ShowFieldMessage("NewPageTemplate.Title", GetText("AddNewXmlPageTemplateWorkflow.TitleInUseTitle")); } private static string GetText(string stringId) { return StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateElementProvider", stringId); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/DeletePageTemplateWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { partial class DeletePageTemplateWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.codeActivity2 = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1InitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // codeActivity2 // this.codeActivity2.Name = "codeActivity2"; this.codeActivity2.ExecuteCode += new System.EventHandler(this.codeActivity2_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = "Delete page"; this.wizzardFormActivity1.FormDefinitionFileName = "\\Administrative\\DeletePageTemplateStep1.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "step1StateActivity"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeInitializationActivity // this.finalizeInitializationActivity.Activities.Add(this.codeActivity2); this.finalizeInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeInitializationActivity.Activities.Add(this.setStateActivity3); this.finalizeInitializationActivity.Name = "finalizeInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity5); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity2); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1InitializationActivity // this.step1InitializationActivity.Activities.Add(this.wizzardFormActivity1); this.step1InitializationActivity.Name = "step1InitializationActivity"; // // initializeInitializationActivity // this.initializeInitializationActivity.Activities.Add(this.setStateActivity1); this.initializeInitializationActivity.Name = "initializeInitializationActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity4); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1InitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // DeletePageTemplateWorkflow // this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "DeletePageTemplateWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity1; private StateInitializationActivity initializeInitializationActivity; private StateActivity finalStateActivity; private StateActivity step1StateActivity; private StateInitializationActivity step1InitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Finish; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity3; private StateInitializationActivity finalizeInitializationActivity; private StateActivity finalizeStateActivity; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity wizzardFormActivity1; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private CodeActivity codeActivity2; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private StateActivity initializeStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/DeletePageTemplateWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Logging; using Composite.Core.PageTemplates; using Composite.Core.PageTemplates.Foundation; using Composite.Core.Routing; using Composite.Data; using Composite.Data.Plugins.DataProvider.Streams; using Composite.Data.ProcessControlled; using Composite.Data.Types; using Composite.Plugins.PageTemplates.MasterPages; using Composite.Plugins.PageTemplates.Razor; using SR = Composite.Core.ResourceSystem.StringResourceSystemFacade; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeletePageTemplateWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { private static readonly string LogTitle = "DeletePageTemplateWorkflow"; public DeletePageTemplateWorkflow() { InitializeComponent(); } private void codeActivity2_ExecuteCode(object sender, EventArgs e) { var entityToken = this.EntityToken; ITemplateDeleter templateDeleter = GetPageTemplateDeleter(entityToken); string errorMessage = null; if (!templateDeleter.CanBeDeleted() || TemplateIsReferenced(templateDeleter.TemplateId, ref errorMessage)) { string message = GetStr("DeletePageTemplateWorkflow.CascadeDeleteErrorMessage"); if(errorMessage != null) { message += " " + errorMessage; } this.ShowMessage(DialogType.Error, GetStr("DeletePageTemplateWorkflow.CascadeDeleteErrorTitle"), message); return; } var parentTreeRefresher = this.CreateParentTreeRefresher(); parentTreeRefresher.PostRefreshMesseges(EntityToken); templateDeleter.DeleteTemplate(); PageTemplateProviderRegistry.FlushTemplates(); } private static bool TemplateIsReferenced(Guid templateId, ref string errorMessage) { var displayedPageReferences = new List<string>(); var pageHash = new HashSet<Guid>(); int pagesToShow = 5; // Page references foreach(var publicationScope in new [] { PublicationScope.Published, PublicationScope.Unpublished }) foreach(var locale in DataLocalizationFacade.ActiveLocalizationCultures) { using (new DataScope(publicationScope, locale)) { var pages = DataFacade.GetData<IPage>().Where(p => p.TemplateId == templateId).ToList(); foreach (IPage page in pages) { // Showing each page only once if(pageHash.Contains(page.Id)) continue; pageHash.Add(page.Id); if(pagesToShow > 0) { string pageUrl = PageUrls.BuildUrl(new PageUrlData(page), UrlKind.Public, new UrlSpace()); string pageReference = pageUrl ?? locale.Name + "/" + page.Id + "/" + page.Title; displayedPageReferences.Add(pageReference); pagesToShow--; } } } } if(pageHash.Count > 0) { var sb = new StringBuilder(); foreach (string pageReference in displayedPageReferences) { sb.Append(Environment.NewLine).Append(pageReference); } errorMessage = GetStr("DeletePageTemplateWorkflow.PageReference").FormatWith(pageHash.Count, sb); return true; } // Page type references var pageTypeReferences = new List<string>(); var pageTypes = DataFacade.GetData<IPageType>().Where(pt => pt.DefaultTemplateId == templateId).ToList(); foreach(var pageType in pageTypes) { string pageTypeReference = pageType.Name ?? pageType.Id.ToString(); pageTypeReferences.Add(pageTypeReference); } if (pageTypeReferences.Count > 0) { var sb = new StringBuilder(); foreach (string pageTypeReference in pageTypeReferences) { sb.Append(Environment.NewLine).Append("'" + pageTypeReference + "'"); } errorMessage = GetStr("DeletePageTemplateWorkflow.PageTypeReference") .FormatWith(pageTypeReferences.Count, sb); return true; } return false; } private ITemplateDeleter GetPageTemplateDeleter(EntityToken entityToken) { if (entityToken is DataEntityToken) { return new XmlPageTemplateDeleter(entityToken as DataEntityToken); } if(entityToken is PageTemplateEntityToken) { Guid pageTemplateId = (entityToken as PageTemplateEntityToken).TemplateId; var pageTemplateDescriptor = PageTemplateFacade.GetPageTemplate(pageTemplateId); if(pageTemplateDescriptor is RazorPageTemplateDescriptor) { return new RazorPageTemplateDeleter(pageTemplateDescriptor as RazorPageTemplateDescriptor); } if(pageTemplateDescriptor is MasterPagePageTemplateDescriptor) { return new MasterPagePageTemplateDeleter(pageTemplateDescriptor as MasterPagePageTemplateDescriptor); } throw new NotSupportedException("Not supported page template descriptor type '{0}'" .FormatWith(pageTemplateDescriptor.GetType().FullName)); } throw new NotSupportedException("Not supported entity token type '{0}'".FormatWith(entityToken.GetType().FullName)); } private static string GetStr(string stringName) { return SR.GetString("Composite.Plugins.PageTemplateElementProvider", stringName); } private interface ITemplateDeleter { Guid TemplateId { get; } bool CanBeDeleted(); void DeleteTemplate(); } private class XmlPageTemplateDeleter: ITemplateDeleter { private readonly IXmlPageTemplate _pageTemplate; public XmlPageTemplateDeleter(DataEntityToken entityToken) { var dataEntityToken = entityToken; _pageTemplate = (IXmlPageTemplate)dataEntityToken.Data; } public bool CanBeDeleted() { return DataFacade.WillDeleteSucceed(_pageTemplate); } public Guid TemplateId { get { return _pageTemplate.Id; } } public void DeleteTemplate() { IFile file = IFileServices.GetFile<IPageTemplateFile>(_pageTemplate.PageTemplateFilePath); ProcessControllerFacade.FullDelete(_pageTemplate); if (file != null && file is FileSystemFileBase) { FileSystemFileBase baseFile = file as FileSystemFileBase; C1File.Delete(baseFile.SystemPath); try { C1File.Delete(baseFile.SystemPath); } catch { LoggingService.LogWarning(LogTitle, "Failed to delete page template file: '{0}'".FormatWith(baseFile.SystemPath)); } } } } private class RazorPageTemplateDeleter: ITemplateDeleter { private readonly RazorPageTemplateDescriptor _templateDescriptor; public RazorPageTemplateDeleter(RazorPageTemplateDescriptor templateDescriptor) { _templateDescriptor = templateDescriptor; } public Guid TemplateId { get { return _templateDescriptor.Id; } } public bool CanBeDeleted() { return true; } public void DeleteTemplate() { string filePath = PathUtil.Resolve(_templateDescriptor.VirtualPath); C1File.Delete(filePath); } } private class MasterPagePageTemplateDeleter : ITemplateDeleter { private readonly MasterPagePageTemplateDescriptor _templateDescriptor; public MasterPagePageTemplateDeleter(MasterPagePageTemplateDescriptor templateDescriptor) { _templateDescriptor = templateDescriptor; } public Guid TemplateId { get { return _templateDescriptor.Id; } } public bool CanBeDeleted() { return true; } public void DeleteTemplate() { try { C1File.Delete(_templateDescriptor.FilePath); } catch(Exception) { throw new InvalidOperationException("Failed to delete file " + _templateDescriptor.FilePath); } try { C1File.Delete(_templateDescriptor.CodeBehindFilePath); } catch (Exception) { throw new InvalidOperationException("Failed to delete file " + _templateDescriptor.CodeBehindFilePath); } } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/DeletePageTemplateWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="DeletePageTemplateWorkflow" Location="30; 30" Size="1094; 996" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="DeletePageTemplateWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="DeletePageTemplateWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="240" Y="190" /> <ns0:Point X="126" Y="190" /> <ns0:Point X="126" Y="197" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="227" Y="142" /> <ns0:Point X="243" Y="142" /> <ns0:Point X="243" Y="286" /> <ns0:Point X="151" Y="286" /> <ns0:Point X="151" Y="293" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="249" Y="358" /> <ns0:Point X="265" Y="358" /> <ns0:Point X="265" Y="422" /> <ns0:Point X="135" Y="422" /> <ns0:Point X="135" Y="427" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="253" Y="382" /> <ns0:Point X="269" Y="382" /> <ns0:Point X="269" Y="190" /> <ns0:Point X="126" Y="190" /> <ns0:Point X="126" Y="197" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="221" Y="468" /> <ns0:Point X="269" Y="468" /> <ns0:Point X="269" Y="188" /> <ns0:Point X="126" Y="188" /> <ns0:Point X="126" Y="197" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initializeStateActivity" Location="46; 101" Size="185; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="initializeInitializationActivity" Location="54; 132"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="64; 194" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="46; 197" Size="160; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="step1StateActivity" Location="46; 293" Size="211; 118" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1InitializationActivity" Location="502; 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="wizzardFormActivity1" Location="512; 210" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Finish" Location="494; 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="504; 221" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="504; 281" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="494; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="504; 245" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="504; 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="46; 427" Size="179; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="finalizeInitializationActivity" Location="54; 458"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="codeActivity2" Location="64; 520" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="64; 580" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="64; 640" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/EditMasterPageWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Web.UI; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.PageTemplates; using Composite.Core.PageTemplates.Foundation; using Composite.Core.ResourceSystem; using Composite.Plugins.Elements.ElementProviders.Common; using Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider; using Composite.Plugins.PageTemplates.MasterPages; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { [EntityTokenLock] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditMasterPageWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { private static readonly string LogTitle = typeof (EditMasterPageWorkflow).Name; // private static readonly string HtmlMimeType = "text/html"; private string[] GetFiles() { var entityToken = this.EntityToken; if (entityToken is PageTemplateEntityToken) { var masterTemplate = GetPageTemplate(); return masterTemplate.GetFiles(); } if (entityToken is SharedCodeFileEntityToken) { var sharedFileEntityToken = (SharedCodeFileEntityToken)this.EntityToken; string relativeFilePath = sharedFileEntityToken.VirtualPath; // Security check that validates that the file is a Shared code file var sharedFiles = PageTemplateFacade.GetSharedFiles(); Verify.That(sharedFiles.Any(sharedFile => string.Compare(sharedFile.RelativeFilePath, relativeFilePath, StringComparison.OrdinalIgnoreCase) == 0), "There's no page template provider that would claim ownership over shared code file '{0}'"); string fullPath = PathUtil.Resolve(relativeFilePath); string codebehindFile = MasterPagePageTemplateProvider.GetCodebehindFilePath(fullPath); var result = new List<string>(); result.Add(fullPath); if(codebehindFile != null) { result.Add(codebehindFile); } return result.ToArray(); } throw new InvalidOperationException("Invalid entity token type '{0}'".FormatWith(entityToken.GetType().Name)); } private Guid GetTemplateId() { var entityToken = this.EntityToken; Verify.That(entityToken is PageTemplateEntityToken, "Invalid entity token type '{0}'", entityToken.GetType()); var pageTemplateEntityToken = (PageTemplateEntityToken)entityToken; return pageTemplateEntityToken.TemplateId; } private MasterPagePageTemplateDescriptor GetPageTemplate() { Guid templateId = GetTemplateId(); var template = PageTemplateFacade.GetPageTemplates().FirstOrDefault(t => t.Id == templateId); Verify.IsNotNull(template, "Faile to find page template by ID '{0}'", templateId); return (MasterPagePageTemplateDescriptor)template; } public EditMasterPageWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { var entityToken = this.EntityToken; string title; if (entityToken is PageTemplateEntityToken) { title = GetPageTemplate().Title; } else { var sharedFileEntityToken = (SharedCodeFileEntityToken)entityToken; title = Path.GetFileName(sharedFileEntityToken.VirtualPath); } this.Bindings.Add("TemplateTitle", title); string[] files = GetFiles(); // Binding all the files for(int i=0; i<files.Length; i++) { var websiteFile = new WebsiteFile(files[i]); string bindingPrefix = GetBindingPrefix(i); this.Bindings.Add(bindingPrefix + "Content", websiteFile.ReadAllText()); this.Bindings.Add(bindingPrefix + "Name", websiteFile.FileName); // Assigning "text/html" mimetype so CodeMirror will show it correctly // this.Bindings.Add(bindingPrefix + "MimeType", i == 0 ? HtmlMimeType : websiteFile.MimeType); this.Bindings.Add(bindingPrefix + "MimeType", websiteFile.MimeType); } } private void saveCodeActivity_ExecuteCode(object sender, EventArgs e) { string[] files = GetFiles(); var fileContent = new List<string>(); for (int i = 0; i < files.Length; i++) { string bindingPrefix = GetBindingPrefix(i); fileContent.Add(this.GetBinding<string>(bindingPrefix + "Content")); } // Fixing html specific escape sequences in .master file string fixedMaster = PageTemplateHelper.FixHtmlEscapeSequences(fileContent[0]); bool viewNeedsUpdating = fileContent[0] != fixedMaster; fileContent[0] = fixedMaster; EntityToken newEntityToken; if (!CompileAndValidate(files, fileContent, out newEntityToken)) { SetSaveStatus(false); return; } for (int i = 0; i < files.Length; i++) { var websiteFile = new WebsiteFile(files[i]); websiteFile.WriteAllText(fileContent[i]); } PageTemplateProviderRegistry.FlushTemplates(); if (newEntityToken != null) { SetSaveStatus(true, newEntityToken); SerializedEntityToken = EntityTokenSerializer.Serialize(newEntityToken); } else { SetSaveStatus(true); } if(viewNeedsUpdating) { UpdateBinding(GetBindingPrefix(0) + "Content", fixedMaster); RerenderView(); } this.CreateParentTreeRefresher().PostRefreshMesseges(this.EntityToken); } private static string GetBindingPrefix(int zeroBasedFileNumber) { return "File" + (zeroBasedFileNumber + 1); } private bool CompileAndValidate(string[] files, IList<string> fileContent, out EntityToken newEntityToken) { string tempMasterFile = GetTempFilePath(files[0]); string tempCodeBehindFile = null; string tempMasterFileContent = fileContent[0]; if(files.Length > 1) { tempCodeBehindFile = GetTempFilePath(files[1]); string originalCsFileName = Path.GetFileName(files[1]); string newCsFileName = Path.GetFileName(tempCodeBehindFile); // Fixing the refecence to the CS file in the temporary created .master file so it will point // to the temporary CS file. Just string.Replace, writing a sofisticated parser would be overkill int offset = tempMasterFileContent.IndexOf(originalCsFileName, StringComparison.OrdinalIgnoreCase); if(offset > 0) { tempMasterFileContent = tempMasterFileContent.Substring(0, offset) + newCsFileName + tempMasterFileContent.Substring(offset + originalCsFileName.Length); } } try { File.WriteAllText(tempMasterFile, tempMasterFileContent); if(tempCodeBehindFile != null) { File.WriteAllText(tempCodeBehindFile, fileContent[1]); } string virtualPath = "~" + PathUtil.GetWebsitePath(tempMasterFile); MasterPage masterPage; try { masterPage = CompilationHelper.CompileMasterPage(virtualPath); } catch(Exception ex) { Log.LogWarning(LogTitle, "Failed to compile master page"); Log.LogWarning(LogTitle, ex); Exception compilationException = (ex is TargetInvocationException) ? ex.InnerException : ex; // Replacing file path and temp file name from error message as it is irrelevant to the user string masterFileName = Path.GetFileName(files[0]); string errorMessage = compilationException.Message; if(errorMessage.StartsWith(tempMasterFile, StringComparison.OrdinalIgnoreCase)) { errorMessage = masterFileName + errorMessage.Substring(tempMasterFile.Length); } ShowWarning(GetText("EditTemplate.Validation.CompilationFailed") .FormatWith(errorMessage)); newEntityToken = null; return false; } return Validate(masterPage, out newEntityToken); } finally { // Deleting temporary files File.Delete(tempMasterFile); if (tempCodeBehindFile != null) { File.Delete(tempCodeBehindFile); } } } private bool Validate(MasterPage masterPage, out EntityToken newEntityToken) { newEntityToken = null; if(!(this.EntityToken is PageTemplateEntityToken)) { return true; } var pageTemplate = GetPageTemplate(); var templateDefinition = masterPage as MasterPagePageTemplate; if(templateDefinition == null) { if(!pageTemplate.IsValid) { return true; } ShowWarning(GetText("EditTemplate.Validation.IncorrectBaseClass") .FormatWith(typeof(MasterPagePageTemplate).FullName)); return false; } Guid templateId; try { templateId = templateDefinition.TemplateId; } catch (Exception ex) { ShowPropertyError("TemplateId", ex); return false; } try { string newTitle = templateDefinition.TemplateTitle; } catch (Exception ex) { ShowPropertyError("TemplateTitle", ex); return false; } if(pageTemplate.IsValid) { if (templateId != pageTemplate.Id) { ShowWarning(GetText("EditTemplate.Validation.TemplateIdChanged").FormatWith(pageTemplate.Id)); return false; } } else { newEntityToken = new PageTemplateEntityToken(templateId); } return true; } private void ShowPropertyError(string propertyName, Exception ex) { ShowWarning(GetText("EditTemplate.Validation.PropertyError") .FormatWith(propertyName, ex.Message)); } private void ShowWarning(string warning) { this.ShowMessage(DialogType.Warning, GetText("EditTemplate.Validation.DialogTitle"), warning); } private string GetText(string text) { return StringResourceSystemFacade.GetString("Composite.Plugins.MasterPagePageTemplate", text); } private string GetTempFilePath(string filePath) { string fileName = Path.GetFileName(filePath); string folderPath = Path.GetDirectoryName(filePath); return Path.Combine(folderPath, MasterPagePageTemplateProvider.TempFilePrefix + fileName); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/EditMasterPageWorkflow.designer.cs ================================================ using System.Workflow.Activities; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { partial class EditMasterPageWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.initialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // saveCodeActivity // this.saveCodeActivity.Name = "saveCodeActivity"; this.saveCodeActivity.ExecuteCode += new System.EventHandler(this.saveCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "saveStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.CustomToolbarDefinitionFileName = null; this.documentFormActivity1.FormDefinitionFileName = "/Administrative/PageTemplate/EditMasterPage.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.saveCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // eventDrivenActivity_Save // this.eventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.eventDrivenActivity_Save.Activities.Add(this.setStateActivity3); this.eventDrivenActivity_Save.Name = "eventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initialStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity1); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.eventDrivenActivity_Save); this.editStateActivity.Name = "editStateActivity"; // // initialState // this.initialState.Activities.Add(this.initialStateInitializationActivity); this.initialState.Name = "initialState"; // // EditMasterPageWorkflow // this.Activities.Add(this.initialState); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelEventDrivenActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialState"; this.Name = "EditMasterPageWorkflow"; this.CanModifyActivities = false; } #endregion private CodeActivity initializeCodeActivity; private SetStateActivity setStateActivity1; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initialStateInitializationActivity; private EventDrivenActivity cancelEventDrivenActivity; private StateActivity finalStateActivity; private StateActivity saveStateActivity; private StateActivity editStateActivity; private C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private StateInitializationActivity editStateInitializationActivity; private StateInitializationActivity finalizeStateInitializationActivity; private CodeActivity saveCodeActivity; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity eventDrivenActivity_Save; private SetStateActivity setStateActivity4; private StateActivity initialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/EditMasterPageWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="963, 837" AutoSizeMargin="16, 24" AutoSize="False" Location="30, 30" Name="EditMasterPageWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="EditMasterPageWorkflow" TargetConnectionIndex="0" SourceStateName="EditMasterPageWorkflow" SourceConnectionEdge="Right" EventHandlerName="cancelEventDrivenActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="202" Y="71" /> <ns0:Point X="202" Y="526" /> <ns0:Point X="387" Y="526" /> <ns0:Point X="387" Y="538" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="initialState" TargetConnectionIndex="0" SourceStateName="initialState" SourceConnectionEdge="Right" EventHandlerName="initialStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="475" Y="153" /> <ns0:Point X="485" Y="153" /> <ns0:Point X="485" Y="214" /> <ns0:Point X="381" Y="214" /> <ns0:Point X="381" Y="226" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="457" Y="291" /> <ns0:Point X="483" Y="291" /> <ns0:Point X="483" Y="348" /> <ns0:Point X="387" Y="348" /> <ns0:Point X="387" Y="360" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="saveStateActivity" TargetConnectionIndex="0" SourceStateName="saveStateActivity" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="486" Y="401" /> <ns0:Point X="501" Y="401" /> <ns0:Point X="501" Y="218" /> <ns0:Point X="381" Y="218" /> <ns0:Point X="381" Y="226" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="197, 80" AutoSizeMargin="16, 24" Location="282, 112" Name="initialState"> <StateDesigner.Designers> <StateInitializationDesigner Name="initialStateInitializationActivity" Size="150, 182" Location="290, 143"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity" Size="130, 41" Location="300, 205" /> <SetStateDesigner Name="setStateActivity2" Size="130, 41" Location="300, 265" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="189, 94" AutoSizeMargin="16, 24" AutoSize="False" Location="287, 226" Name="editStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="editStateInitializationActivity" Size="150, 122" Location="436, 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="documentFormActivity1" Size="130, 41" Location="446, 210" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="eventDrivenActivity_Save" Size="150, 182" Location="428, 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130, 41" Location="438, 221" /> <SetStateDesigner Name="setStateActivity3" Size="130, 41" Location="438, 281" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205, 80" AutoSizeMargin="16, 24" Location="285, 360" Name="saveStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150, 182" Location="293, 391"> <StateInitializationDesigner.Designers> <CodeDesigner Name="saveCodeActivity" Size="130, 41" Location="303, 453" /> <SetStateDesigner Name="setStateActivity4" Size="130, 41" Location="303, 513" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160, 80" AutoSizeMargin="16, 24" Location="307, 538" Name="finalStateActivity" /> <EventDrivenDesigner Name="cancelEventDrivenActivity" Size="150, 182" Location="38, 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130, 41" Location="48, 123" /> <SetStateDesigner Name="setStateActivity1" Size="130, 41" Location="48, 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/EditRazorPageTemplateWorkflow.cs ================================================ using System; using System.IO; using System.Linq; using System.Web.WebPages; using Composite.C1Console.Events; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.PageTemplates; using Composite.Core.PageTemplates.Foundation; using Composite.Core.ResourceSystem; using Composite.Plugins.Elements.ElementProviders.Common; using Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider; using Composite.Plugins.PageTemplates.Razor; using RazorPageTemplate = Composite.AspNet.Razor.RazorPageTemplate; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditRazorPageTemplateWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { private static readonly string LogTitle = "Razor Edit"; public EditRazorPageTemplateWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { string filePath = PathUtil.Resolve(GetFileVirtualPath()); WebsiteFile websiteFile = new WebsiteFile(filePath); this.Bindings.Add("FilePath", filePath); this.Bindings.Add("FileContent", websiteFile.ReadAllText()); this.Bindings.Add("FileName", websiteFile.FileName); this.Bindings.Add("FileMimeType", websiteFile.MimeType); } private void saveCodeActivity_ExecuteCode(object sender, EventArgs e) { string virtualPath = GetFileVirtualPath(); string filePath = PathUtil.Resolve(virtualPath); WebsiteFile websiteFile = new WebsiteFile(filePath); string content = this.GetBinding<string>("FileContent"); string fixedSource = PageTemplateHelper.FixHtmlEscapeSequences(content); EntityToken newEntityToken; bool isValid = ValidateMarkup(virtualPath, fixedSource, out newEntityToken); if (isValid) { websiteFile.WriteAllText(fixedSource); PageTemplateProviderRegistry.FlushTemplates(); this.CreateParentTreeRefresher().PostRefreshMesseges(this.EntityToken); } if (isValid && newEntityToken != null) { SetSaveStatus(true, newEntityToken); SerializedEntityToken = EntityTokenSerializer.Serialize(newEntityToken); } else { SetSaveStatus(isValid); } if(isValid && fixedSource != content) { UpdateBinding("FileContent", fixedSource); RerenderView(); } } private bool ValidateMarkup(string virtualPath, string content, out EntityToken newEntityToken) { newEntityToken = null; string filePath = PathUtil.Resolve(virtualPath); string fileName = Path.GetFileName(filePath); string tempFileName = RazorPageTemplateProvider.TempFilePrefix + fileName; string tempFileVirtualPath = virtualPath.Substring(0, virtualPath.Length - fileName.Length) + tempFileName; string tempFile = Path.Combine(Path.GetDirectoryName(filePath), tempFileName); try { C1File.WriteAllText(tempFile, content); WebPageBase webPageBase; try { webPageBase = WebPage.CreateInstanceFromVirtualPath(tempFileVirtualPath); } catch (Exception ex) { Log.LogWarning(LogTitle, "Compilation failed while validating changes to '{0}'", virtualPath); Log.LogWarning(LogTitle, ex); string message = ex.Message; if(message.StartsWith(tempFile, StringComparison.OrdinalIgnoreCase)) { message = fileName + message.Substring(tempFile.Length); } ShowWarning(GetText("EditTemplate.Validation.CompilationFailed") .FormatWith(message)); return false; } if (!(webPageBase is RazorPageTemplate)) { if(IsPageTemplate) { var templateDescriptor = GetPageTemplateDescriptor(); if(templateDescriptor.IsValid) { ShowWarning(GetText("EditTemplate.Validation.IncorrectBaseClass") .FormatWith(typeof(RazorPageTemplate).FullName)); return false; } newEntityToken = new SharedCodeFileEntityToken(virtualPath); return true; } return true; } Guid templateId; var pageTemplate = webPageBase as RazorPageTemplate; pageTemplate.Configure(); try { templateId = pageTemplate.TemplateId; } catch (Exception ex) { ShowPropertyError("TemplateId", ex); return false; } try { string templateTitle = pageTemplate.TemplateTitle; } catch (Exception ex) { ShowPropertyError("TemplateTitle", ex); return false; } if(!IsPageTemplate) { newEntityToken = new PageTemplateEntityToken(templateId); return true; } var pageTemplateDescriptor = GetPageTemplateDescriptor(); if (pageTemplateDescriptor.IsValid) { // Forbidding to change template id from this workflow in order to avoid mistakes if (templateId != pageTemplateDescriptor.Id) { ShowWarning(GetText("EditTemplate.Validation.TemplateIdChanged").FormatWith(pageTemplateDescriptor.Id)); return false; } } else { newEntityToken = new PageTemplateEntityToken(templateId); } } finally { C1File.Delete(tempFile); } return true; } private void ShowPropertyError(string propertyName, Exception ex) { ShowWarning(GetText("EditTemplate.Validation.PropertyError") .FormatWith(propertyName, ex.Message)); } private void ShowWarning(string warning) { this.ShowMessage(DialogType.Warning, GetText("EditTemplate.Validation.DialogTitle"), warning); } private Guid GetTemplateId() { var entityToken = this.EntityToken; Verify.That(entityToken is PageTemplateEntityToken, "Invalid entity token type '{0}'", entityToken.GetType()); var pageTemplateEntityToken = (PageTemplateEntityToken)entityToken; return pageTemplateEntityToken.TemplateId; } private string GetText(string text) { return StringResourceSystemFacade.GetString("Composite.Plugins.RazorPageTemplate", text); } private RazorPageTemplateDescriptor GetPageTemplateDescriptor() { Guid templateId = GetTemplateId(); var template = PageTemplateFacade.GetPageTemplates().FirstOrDefault(t => t.Id == templateId); Verify.IsNotNull(template, "Faile to find page template by ID '{0}'", templateId); return (PageTemplates.Razor.RazorPageTemplateDescriptor)template; } private bool IsPageTemplate { get { return this.EntityToken is PageTemplateEntityToken; } } private string GetFileVirtualPath() { if(IsPageTemplate) { return GetPageTemplateDescriptor().VirtualPath; } if(EntityToken is SharedCodeFileEntityToken) { return (EntityToken as SharedCodeFileEntityToken).VirtualPath; } throw new InvalidOperationException("Unexpected entity token type " + EntityToken.GetType().FullName); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/EditRazorPageTemplateWorkflow.designer.cs ================================================ using System.Workflow.Activities; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { partial class EditRazorPageTemplateWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.initialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // saveCodeActivity // this.saveCodeActivity.Name = "saveCodeActivity"; this.saveCodeActivity.ExecuteCode += new System.EventHandler(this.saveCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "saveStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.CustomToolbarDefinitionFileName = null; this.documentFormActivity1.FormDefinitionFileName = "/Administrative/PageTemplate/EditRazorTemplate.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.saveCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // eventDrivenActivity_Save // this.eventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.eventDrivenActivity_Save.Activities.Add(this.setStateActivity3); this.eventDrivenActivity_Save.Name = "eventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initialStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity1); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.eventDrivenActivity_Save); this.editStateActivity.Name = "editStateActivity"; // // initialState // this.initialState.Activities.Add(this.initialStateInitializationActivity); this.initialState.Name = "initialState"; // // EditRazorPageTemplateWorkflow // this.Activities.Add(this.initialState); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelEventDrivenActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialState"; this.Name = "EditRazorPageTemplateWorkflow"; this.CanModifyActivities = false; } #endregion private CodeActivity initializeCodeActivity; private SetStateActivity setStateActivity1; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initialStateInitializationActivity; private EventDrivenActivity cancelEventDrivenActivity; private StateActivity finalStateActivity; private StateActivity saveStateActivity; private StateActivity editStateActivity; private C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private StateInitializationActivity editStateInitializationActivity; private StateInitializationActivity finalizeStateInitializationActivity; private CodeActivity saveCodeActivity; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity eventDrivenActivity_Save; private SetStateActivity setStateActivity4; private StateActivity initialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/EditRazorPageTemplateWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="963, 837" AutoSizeMargin="16, 24" Location="30, 30" Name="EditRazorPageTemplateWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="EditRazorPageTemplateWorkflow" TargetConnectionIndex="0" SourceStateName="EditRazorPageTemplateWorkflow" SourceConnectionEdge="Right" EventHandlerName="cancelEventDrivenActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="202" Y="71" /> <ns0:Point X="202" Y="544" /> <ns0:Point X="329" Y="544" /> <ns0:Point X="329" Y="556" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="initialState" TargetConnectionIndex="0" SourceStateName="initialState" SourceConnectionEdge="Right" EventHandlerName="initialStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="436" Y="189" /> <ns0:Point X="448" Y="189" /> <ns0:Point X="448" Y="244" /> <ns0:Point X="344" Y="244" /> <ns0:Point X="344" Y="256" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="420" Y="321" /> <ns0:Point X="444" Y="321" /> <ns0:Point X="444" Y="384" /> <ns0:Point X="348" Y="384" /> <ns0:Point X="348" Y="396" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="saveStateActivity" TargetConnectionIndex="0" SourceStateName="saveStateActivity" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="447" Y="437" /> <ns0:Point X="456" Y="437" /> <ns0:Point X="456" Y="248" /> <ns0:Point X="344" Y="248" /> <ns0:Point X="344" Y="256" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="197, 80" AutoSizeMargin="16, 24" Location="243, 148" Name="initialState"> <StateDesigner.Designers> <StateInitializationDesigner Name="initialStateInitializationActivity" Size="150, 182" Location="251, 179"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity" Size="130, 41" Location="261, 241" /> <SetStateDesigner Name="setStateActivity2" Size="130, 41" Location="261, 301" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="189, 94" AutoSizeMargin="16, 24" Location="250, 256" Name="editStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="editStateInitializationActivity" Size="150, 122" Location="258, 287"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="documentFormActivity1" Size="130, 41" Location="268, 349" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="eventDrivenActivity_Save" Size="150, 182" Location="258, 311"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130, 41" Location="268, 373" /> <SetStateDesigner Name="setStateActivity3" Size="130, 41" Location="268, 433" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205, 80" AutoSizeMargin="16, 24" Location="246, 396" Name="saveStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150, 182" Location="254, 427"> <StateInitializationDesigner.Designers> <CodeDesigner Name="saveCodeActivity" Size="130, 41" Location="264, 489" /> <SetStateDesigner Name="setStateActivity4" Size="130, 41" Location="264, 549" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160, 80" AutoSizeMargin="16, 24" Location="249, 556" Name="finalStateActivity" /> <EventDrivenDesigner Name="cancelEventDrivenActivity" Size="150, 182" Location="38, 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130, 41" Location="48, 123" /> <SetStateDesigner Name="setStateActivity1" Size="130, 41" Location="48, 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/EditSharedCodeFileWorkflow.cs ================================================ using System; using System.Linq; using Composite.C1Console.Workflow; using Composite.Core.IO; using Composite.Core.PageTemplates; using Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditSharedCodeFileWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { private string GetFilePath() { var entityToken = (SharedCodeFileEntityToken)this.EntityToken; string relativeFilePath = entityToken.VirtualPath; // Security check that validates that the file is a Shared code file var sharedFiles = PageTemplateFacade.GetSharedFiles(); Verify.That(sharedFiles.Any(sf => string.Compare(sf.RelativeFilePath, relativeFilePath, StringComparison.OrdinalIgnoreCase) == 0), "There's no page template provider that would claim ownership over shared code file '{0}'"); return PathUtil.Resolve(relativeFilePath); } public EditSharedCodeFileWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { string filePath = GetFilePath(); WebsiteFile websiteFile = new WebsiteFile(filePath); this.Bindings.Add("FileContent", websiteFile.ReadAllText()); this.Bindings.Add("FileName", websiteFile.FileName); this.Bindings.Add("FileMimeType", websiteFile.MimeType); } private void saveCodeActivity_ExecuteCode(object sender, EventArgs e) { string filePath = GetFilePath(); WebsiteFile websiteFile = new WebsiteFile(filePath); string content = this.GetBinding<string>("FileContent"); websiteFile.WriteAllText(content); SetSaveStatus(true); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/EditSharedCodeFileWorkflow.designer.cs ================================================ using System.Workflow.Activities; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { partial class EditSharedCodeFileWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.initialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // saveCodeActivity // this.saveCodeActivity.Name = "saveCodeActivity"; this.saveCodeActivity.ExecuteCode += new System.EventHandler(this.saveCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "saveStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.CustomToolbarDefinitionFileName = null; this.documentFormActivity1.FormDefinitionFileName = "/Administrative/WebsiteFileElementProviderEditTextContentFile.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.saveCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // eventDrivenActivity_Save // this.eventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.eventDrivenActivity_Save.Activities.Add(this.setStateActivity3); this.eventDrivenActivity_Save.Name = "eventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initialStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity1); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.eventDrivenActivity_Save); this.editStateActivity.Name = "editStateActivity"; // // initialState // this.initialState.Activities.Add(this.initialStateInitializationActivity); this.initialState.Name = "initialState"; // // EditSharedCodeFileWorkflow // this.Activities.Add(this.initialState); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelEventDrivenActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialState"; this.Name = "EditSharedCodeFileWorkflow"; this.CanModifyActivities = false; } #endregion private CodeActivity initializeCodeActivity; private SetStateActivity setStateActivity1; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initialStateInitializationActivity; private EventDrivenActivity cancelEventDrivenActivity; private StateActivity finalStateActivity; private StateActivity saveStateActivity; private StateActivity editStateActivity; private C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private StateInitializationActivity editStateInitializationActivity; private StateInitializationActivity finalizeStateInitializationActivity; private CodeActivity saveCodeActivity; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity eventDrivenActivity_Save; private SetStateActivity setStateActivity4; private StateActivity initialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/EditSharedCodeFileWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="963, 837" AutoSizeMargin="16, 24" Location="30, 30" Name="EditSharedCodeFileWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="EditSharedCodeFileWorkflow" TargetConnectionIndex="0" SourceStateName="EditSharedCodeFileWorkflow" SourceConnectionEdge="Right" EventHandlerName="cancelEventDrivenActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="202" Y="71" /> <ns0:Point X="202" Y="513" /> <ns0:Point X="424" Y="513" /> <ns0:Point X="424" Y="525" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="initialState" TargetConnectionIndex="0" SourceStateName="initialState" SourceConnectionEdge="Right" EventHandlerName="initialStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="504" Y="145" /> <ns0:Point X="520" Y="145" /> <ns0:Point X="520" Y="218" /> <ns0:Point X="416" Y="218" /> <ns0:Point X="416" Y="230" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="492" Y="295" /> <ns0:Point X="520" Y="295" /> <ns0:Point X="520" Y="360" /> <ns0:Point X="424" Y="360" /> <ns0:Point X="424" Y="372" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="saveStateActivity" TargetConnectionIndex="0" SourceStateName="saveStateActivity" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="523" Y="413" /> <ns0:Point X="536" Y="413" /> <ns0:Point X="536" Y="222" /> <ns0:Point X="416" Y="222" /> <ns0:Point X="416" Y="230" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="197, 80" AutoSizeMargin="16, 24" Location="311, 104" Name="initialState"> <StateDesigner.Designers> <StateInitializationDesigner Name="initialStateInitializationActivity" Size="150, 182" Location="319, 135"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity" Size="130, 41" Location="329, 197" /> <SetStateDesigner Name="setStateActivity2" Size="130, 41" Location="329, 257" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="189, 94" AutoSizeMargin="16, 24" Location="322, 230" Name="editStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="editStateInitializationActivity" Size="150, 122" Location="330, 261"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="documentFormActivity1" Size="130, 41" Location="340, 323" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="eventDrivenActivity_Save" Size="150, 182" Location="330, 285"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130, 41" Location="340, 347" /> <SetStateDesigner Name="setStateActivity3" Size="130, 41" Location="340, 407" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205, 80" AutoSizeMargin="16, 24" Location="322, 372" Name="saveStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150, 182" Location="330, 403"> <StateInitializationDesigner.Designers> <CodeDesigner Name="saveCodeActivity" Size="130, 41" Location="340, 465" /> <SetStateDesigner Name="setStateActivity4" Size="130, 41" Location="340, 525" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160, 80" AutoSizeMargin="16, 24" Location="344, 525" Name="finalStateActivity" /> <EventDrivenDesigner Name="cancelEventDrivenActivity" Size="150, 182" Location="38, 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130, 41" Location="48, 123" /> <SetStateDesigner Name="setStateActivity1" Size="130, 41" Location="48, 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/EditXmlPageTemplateWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { partial class EditXmlPageTemplateWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.ShowMessageCodeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity1 = new System.Workflow.Activities.CodeActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editEventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "saveStateActivity"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "editStateActivity"; // // ShowMessageCodeActivity // this.ShowMessageCodeActivity.Name = "ShowMessageCodeActivity"; this.ShowMessageCodeActivity.ExecuteCode += new System.EventHandler(this.ShowMessageCodeActivity_ExecuteCode); // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity2); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.ShowMessageCodeActivity); this.ifElseBranchActivity1.Activities.Add(this.setStateActivity5); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsTitleUsed); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "editStateActivity"; // // codeActivity1 // this.codeActivity1.Name = "codeActivity1"; this.codeActivity1.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode); // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.CustomToolbarDefinitionFileName = null; this.documentFormActivity1.FormDefinitionFileName = "\\Administrative\\PageTemplate\\EditXmlPageTemplate.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "editStateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.codeActivity1); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity3); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // editEventDrivenActivity_Save // this.editEventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.editEventDrivenActivity_Save.Activities.Add(this.ifElseActivity1); this.editEventDrivenActivity_Save.Name = "editEventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity1); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity4); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.saveStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_Save); this.editStateActivity.Name = "editStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // EditPageTemplateWorkflow // this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "EditXmlPageTemplateWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity1; private EventDrivenActivity editEventDrivenActivity_Save; private StateInitializationActivity editStateInitializationActivity; private StateInitializationActivity initializeStateInitializationActivity; private StateActivity editStateActivity; private CodeActivity initializeCodeActivity; private Composite.C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private StateActivity saveStateActivity; private SetStateActivity setStateActivity3; private CodeActivity codeActivity1; private StateInitializationActivity saveStateInitializationActivity; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private StateActivity finalStateActivity; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private CodeActivity ShowMessageCodeActivity; private SetStateActivity setStateActivity5; private StateActivity initializeStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateElementProvider/EditXmlPageTemplateWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Workflow.Runtime; using System.Xml.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Workflow; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.ResourceSystem; using Composite.Core.Xml; using Composite.Data; using Composite.Data.Plugins.DataProvider.Streams; using Composite.Data.Types; using Composite.Functions; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditXmlPageTemplateWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditXmlPageTemplateWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; this.Bindings.Add("PageTemplate", dataEntityToken.Data); this.Bindings.Add("OldTitle", ((IXmlPageTemplate)dataEntityToken.Data).Title); string templatePath = ((IXmlPageTemplate)dataEntityToken.Data).PageTemplateFilePath; IPageTemplateFile file = IFileServices.TryGetFile<IPageTemplateFile>(templatePath); this.Bindings.Add("PageTemplateMarkup", file.ReadAllText()); } private void codeActivity1_ExecuteCode(object sender, EventArgs e) { IXmlPageTemplate pageTemplate = this.GetBinding<IXmlPageTemplate>("PageTemplate"); string pageTemplateMarkup = this.GetBinding<string>("PageTemplateMarkup"); bool xhtmlParseable = true; string parseError = null; try { XDocument parsedElement = XDocument.Parse(pageTemplateMarkup); ValidatePageTemplate(parsedElement); } catch (Exception ex) { xhtmlParseable = false; parseError = ex.Message; } if (!xhtmlParseable) { FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); var consoleMessageService = serviceContainer.GetService<IManagementConsoleMessageService>(); consoleMessageService.ShowMessage( DialogType.Error, GetString("EditXmlPageTemplateWorkflow.InvalidXmlTitle"), GetString("EditXmlPageTemplateWorkflow.InvalidXmlMessage").FormatWith(parseError)); return; } // Renaming related file if necessary string fileName = GetTemplateFileName(pageTemplate); if (Path.GetFileName(pageTemplate.PageTemplateFilePath) != fileName) { IPageTemplateFile file = IFileServices.GetFile<IPageTemplateFile>(pageTemplate.PageTemplateFilePath); string systemPath = (file as FileSystemFileBase).SystemPath; string newSystemPath = Path.Combine(Path.GetDirectoryName(systemPath), fileName); if (string.Compare(systemPath, newSystemPath, true) != 0 && C1File.Exists(newSystemPath)) { FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); var consoleMessageService = serviceContainer.GetService<IManagementConsoleMessageService>(); consoleMessageService.ShowMessage( DialogType.Error, GetString("EditXmlPageTemplateWorkflow.InvalidXmlTitle"), GetString("EditXmlPageTemplateWorkflow.CannotRenameFileExists").FormatWith(newSystemPath)); return; } C1File.Move(systemPath, newSystemPath); string newRelativePath = Path.Combine(Path.GetDirectoryName(pageTemplate.PageTemplateFilePath), fileName); pageTemplate.PageTemplateFilePath = newRelativePath; } IPageTemplateFile templateFile = IFileServices.GetFile<IPageTemplateFile>(pageTemplate.PageTemplateFilePath); templateFile.SetNewContent(pageTemplateMarkup); DataFacade.Update(templateFile); DataFacade.Update(pageTemplate); UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken); updateTreeRefresher.PostRefreshMesseges(pageTemplate.GetDataEntityToken()); SetSaveStatus(true); } private string GetTemplateFileName(IXmlPageTemplate xmlTemplateFile) { string name = PathUtil.CleanFileName(xmlTemplateFile.Title, true) ?? xmlTemplateFile.Id.ToString(); return name + ".xml"; } private static string GetString(string key) { return StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateElementProvider", key); } private void ValidatePageTemplate(XDocument xDocument) { // check unique id's List<XAttribute> valueOrderedIdAttributes = xDocument.Descendants().Attributes("id").OrderBy(f => f.Value).ToList(); XElement rootElement = xDocument.Root; if (rootElement.Name.LocalName.ToLowerInvariant() == "html") { if (rootElement.Name.Namespace != Namespaces.Xhtml) { throw new InvalidOperationException(string.Format("Root element 'html' must belong to the namespace '{0}'. Change the \"<html>\" tag to \"<html xmlns='{0}'>\"", Namespaces.Xhtml)); } if (rootElement.Name.LocalName != rootElement.Name.LocalName.ToLowerInvariant()) { throw new InvalidOperationException("Root element 'html' must be written in lower case."); } } for (int i = 0; i < valueOrderedIdAttributes.Count - 1; i++) { if (valueOrderedIdAttributes[i].Value == valueOrderedIdAttributes[i + 1].Value) { throw new InvalidOperationException(string.Format("The id '{0}' is used on multiple elements ('{1}' and '{2}'). Element id values must be unique.", valueOrderedIdAttributes[i].Value, valueOrderedIdAttributes[i].Parent.Name.LocalName, valueOrderedIdAttributes[i + 1].Parent.Name.LocalName)); } } foreach (XElement element in xDocument.Descendants().Where(f => f.Name.Namespace == Namespaces.AspNetControls)) { switch (element.Name.LocalName) { case "form": case "placeholder": break; default: throw new InvalidOperationException(string.Format("Unknown element '{0}' in namespace '{1}'.", element.Name.LocalName, Namespaces.AspNetControls)); } } foreach (XElement element in xDocument.Descendants().Where(f => f.Name.Namespace == Namespaces.Rendering10)) { switch (element.Name.LocalName) { case "page.title": case "page.description": case "page.metatag.description": case "placeholder": break; default: throw new InvalidOperationException(string.Format("Unknown element '{0}' in namespace '{1}'.", element.Name.LocalName, Namespaces.Rendering10)); } } if (1 < xDocument.Descendants(Namespaces.Rendering10 + "placeholder").Attributes("default").Where(f => f.Value == "true").Count()) { throw new InvalidOperationException(string.Format("Multiple '{0}' elements are set to be default. Only one element may be default.", "placeholder")); } foreach (XElement element in xDocument.Descendants(Namespaces.Function10 + "function")) { FunctionFacade.BuildTree(element); } } private void IsTitleUsed(object sender, System.Workflow.Activities.ConditionalEventArgs e) { IXmlPageTemplate newPageTemplate = this.GetBinding<IXmlPageTemplate>("PageTemplate"); if (this.GetBinding<string>("OldTitle") == newPageTemplate.Title) { e.Result = false; return; } e.Result = DataFacade.GetData<IXmlPageTemplate>().ToList() .Any(f => string.Compare(f.Title, newPageTemplate.Title, StringComparison.InvariantCultureIgnoreCase) == 0 && f.Id != newPageTemplate.Id); } private void ShowMessageCodeActivity_ExecuteCode(object sender, EventArgs e) { ShowFieldMessage("PageTemplate.Title", GetString("EditXmlPageTemplateWorkflow.TitleInUseTitle")); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateFeatureElementProvider/AddPageTemplateFeatureWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.IO; using Composite.C1Console.Workflow; using Composite.Core.Configuration; using Composite.Core.IO; using Composite.Core.ResourceSystem; using Composite.Core.Xml; using Composite.Core.WebClient.Renderings.Template; using System.Xml.Linq; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Plugins_PageTemplateFeatureElementProvider; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateFeatureElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddPageTemplateFeatureWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddPageTemplateFeatureWorkflow() { InitializeComponent(); } private void initializeCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { this.Bindings.Add("Name", ""); this.Bindings.Add("EditorType", "html"); var editorOptions = new Dictionary<string, string> { { "html", Texts.AddWorkflow_LabelTemplateFeatureEditorType_html }, { "xml", Texts.AddWorkflow_LabelTemplateFeatureEditorType_xml } }; this.Bindings.Add("EditorTypeOptions", editorOptions); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { string name = this.GetBinding<string>("Name"); string editorType = this.GetBinding<string>("EditorType"); string filename = PageTemplateFeatureFacade.GetNewPageTemplateFeaturePath(name, editorType); var template = new XhtmlDocument(); template.Head.Add(""); template.Body.Add(new XElement(Namespaces.Xhtml + "p", "")); C1File.WriteAllText(filename, template.ToString()); this.CloseCurrentView(); this.RefreshRootEntityToken(); this.ExecuteAction(PageTemplateFeatureEntityToken.BuildFeatureEntityToken(name), new WorkflowActionToken(typeof(EditPageTemplateFeatureWorkflow))); } private void IfFeatureNameFree(object sender, System.Workflow.Activities.ConditionalEventArgs e) { string name = this.GetBinding<string>("Name"); if (name.Length > 50) { e.Result = false; this.ShowFieldMessage("Name", StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "AddWorkflow.NameTooLong")); return; } if (!C1Directory.Exists(PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory))) { try { C1Directory.CreateDirectory(PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory)); } catch (Exception) { e.Result = false; this.ShowFieldMessage("Name", string.Format("Can not create directory '{0}'", GlobalSettingsFacade.PageTemplateFeaturesDirectory)); } } string xmlFilename = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory), name + ".xml"); string htmlFilename = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory), name + ".html"); e.Result = !C1File.Exists(xmlFilename) && !C1File.Exists(htmlFilename); if (!e.Result) { this.ShowFieldMessage("Name", StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "AddWorkflow.NameInUse")); return; } try { C1File.WriteAllText(xmlFilename, "tmp"); C1File.Delete(xmlFilename); } catch (Exception) { e.Result = false; this.ShowFieldMessage("Name", StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "AddWorkflow.NameNotValidInFilename")); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateFeatureElementProvider/AddPageTemplateFeatureWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateFeatureElementProvider { partial class AddPageTemplateFeatureWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.selectIfElseActivity_TreeIdFree = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizardFormActivity1 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.selectTemplateEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.selectTemplateStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.getNameStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "getNameStateActivity"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity5); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity3); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IfFeatureNameFree); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // selectIfElseActivity_TreeIdFree // this.selectIfElseActivity_TreeIdFree.Activities.Add(this.ifElseBranchActivity1); this.selectIfElseActivity_TreeIdFree.Activities.Add(this.ifElseBranchActivity2); this.selectIfElseActivity_TreeIdFree.Name = "selectIfElseActivity_TreeIdFree"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // wizardFormActivity1 // this.wizardFormActivity1.ContainerLabel = null; this.wizardFormActivity1.FormDefinitionFileName = "/Administrative/PageTemplateFeature/Add.xml"; this.wizardFormActivity1.Name = "wizardFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "getNameStateActivity"; // // initializeCodeActivity_Initialize // this.initializeCodeActivity_Initialize.Name = "initializeCodeActivity_Initialize"; this.initializeCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_Initialize_ExecuteCode); // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // selectTemplateEventDrivenActivity_Finish // this.selectTemplateEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.selectTemplateEventDrivenActivity_Finish.Activities.Add(this.selectIfElseActivity_TreeIdFree); this.selectTemplateEventDrivenActivity_Finish.Name = "selectTemplateEventDrivenActivity_Finish"; // // selectTemplateStateInitializationActivity // this.selectTemplateStateInitializationActivity.Activities.Add(this.wizardFormActivity1); this.selectTemplateStateInitializationActivity.Name = "selectTemplateStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_Initialize); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // getNameStateActivity // this.getNameStateActivity.Activities.Add(this.selectTemplateStateInitializationActivity); this.getNameStateActivity.Activities.Add(this.selectTemplateEventDrivenActivity_Finish); this.getNameStateActivity.Name = "getNameStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // AddPageTemplateFeatureWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.getNameStateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddPageTemplateFeatureWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private StateActivity getNameStateActivity; private SetStateActivity setStateActivity2; private StateInitializationActivity selectTemplateStateInitializationActivity; private C1Console.Workflow.Activities.WizardFormActivity wizardFormActivity1; private SetStateActivity setStateActivity4; private CodeActivity finalizeCodeActivity_Finalize; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity selectTemplateEventDrivenActivity_Finish; private StateActivity finalizeStateActivity; private SetStateActivity setStateActivity5; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity selectIfElseActivity_TreeIdFree; private CodeActivity initializeCodeActivity_Initialize; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateFeatureElementProvider/AddPageTemplateFeatureWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1135, 649" AutoSizeMargin="16, 24" AutoSize="False" Location="30, 30" Name="AddPageTemplateFeatureWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="AddPageTemplateFeatureWorkflow" TargetConnectionIndex="0" SourceStateName="AddPageTemplateFeatureWorkflow" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="74" /> <ns0:Point X="931" Y="74" /> <ns0:Point X="931" Y="179" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="getNameStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="getNameStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="286" Y="150" /> <ns0:Point X="352" Y="150" /> <ns0:Point X="352" Y="214" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="getNameStateActivity" TargetConnectionIndex="0" SourceStateName="getNameStateActivity" SourceConnectionEdge="Right" EventHandlerName="selectTemplateEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="484" Y="284" /> <ns0:Point X="623" Y="284" /> <ns0:Point X="623" Y="323" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="729" Y="367" /> <ns0:Point X="745" Y="367" /> <ns0:Point X="745" Y="171" /> <ns0:Point X="931" Y="171" /> <ns0:Point X="931" Y="179" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150, 209" Location="38, 63"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130, 44" Location="48, 128" /> <SetStateDesigner Name="setStateActivity1" Size="130, 62" Location="48, 191" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="227, 80" AutoSizeMargin="16, 24" Location="63, 106" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150, 209" Location="71, 139"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_Initialize" Size="130, 44" Location="81, 204" /> <SetStateDesigner Name="setStateActivity2" Size="130, 62" Location="81, 267" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160, 80" AutoSizeMargin="16, 24" Location="851, 179" Name="finalStateActivity" /> <StateDesigner Size="272, 100" AutoSizeMargin="16, 24" AutoSize="False" Location="216, 214" Name="getNameStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="selectTemplateStateInitializationActivity" Size="150, 128" Location="399, 141"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizardFormActivity1" Size="130, 44" Location="409, 206" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="selectTemplateEventDrivenActivity_Finish" Size="381, 396" Location="407, 154"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130, 44" Location="532, 219" /> <IfElseDesigner Name="selectIfElseActivity_TreeIdFree" Size="361, 249" Location="417, 282"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150, 146" Location="436, 356"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130, 62" Location="446, 421" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150, 146" Location="609, 356"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity5" Size="130, 62" Location="619, 421" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="220, 80" AutoSizeMargin="16, 24" Location="513, 323" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150, 209" Location="521, 356"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity_Finalize" Size="130, 44" Location="531, 421" /> <SetStateDesigner Name="setStateActivity4" Size="130, 62" Location="531, 484" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateFeatureElementProvider/DeletePageTemplateFeatureWorkflow.cs ================================================ using System; using Composite.C1Console.Workflow; using Composite.Core.IO; using Composite.Core.WebClient.Renderings.Template; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateFeatureElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeletePageTemplateFeatureWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeletePageTemplateFeatureWorkflow() { InitializeComponent(); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { FileUtils.Delete(this.FilePath); this.RefreshRootEntityToken(); } private string FilePath { get { PageTemplateFeatureEntityToken castedEntityToken = (PageTemplateFeatureEntityToken)this.EntityToken; return PageTemplateFeatureFacade.GetPageTemplateFeaturePath(castedEntityToken.FeatureName); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateFeatureElementProvider/DeletePageTemplateFeatureWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateFeatureElementProvider { partial class DeletePageTemplateFeatureWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity2 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.confirmEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.confirmEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.confirmStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.confirmStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // confirmDialogFormActivity2 // this.confirmDialogFormActivity2.ContainerLabel = null; this.confirmDialogFormActivity2.FormDefinitionFileName = "/Administrative/PageTemplateFeature/Delete.xml"; this.confirmDialogFormActivity2.Name = "confirmDialogFormActivity2"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "confirmStateActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // confirmEventDrivenActivity_Cancel // this.confirmEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.confirmEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity5); this.confirmEventDrivenActivity_Cancel.Name = "confirmEventDrivenActivity_Cancel"; // // confirmEventDrivenActivity_Finish // this.confirmEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.confirmEventDrivenActivity_Finish.Activities.Add(this.setStateActivity2); this.confirmEventDrivenActivity_Finish.Name = "confirmEventDrivenActivity_Finish"; // // confirmStateInitializationActivity // this.confirmStateInitializationActivity.Activities.Add(this.confirmDialogFormActivity2); this.confirmStateInitializationActivity.Name = "confirmStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity3); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // confirmStateActivity // this.confirmStateActivity.Activities.Add(this.confirmStateInitializationActivity); this.confirmStateActivity.Activities.Add(this.confirmEventDrivenActivity_Finish); this.confirmStateActivity.Activities.Add(this.confirmEventDrivenActivity_Cancel); this.confirmStateActivity.Name = "confirmStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // DeletePageTemplateFeatureWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.confirmStateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "DeletePageTemplateFeatureWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity2; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity confirmEventDrivenActivity_Finish; private StateInitializationActivity confirmStateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity confirmStateActivity; private SetStateActivity setStateActivity4; private CodeActivity finalizeCodeActivity_Finalize; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity5; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity confirmEventDrivenActivity_Cancel; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateFeatureElementProvider/DeletePageTemplateFeatureWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1234, 649" AutoSizeMargin="16, 24" AutoSize="False" Location="30, 30" Name="DeletePageTemplateFeatureWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="DeletePageTemplateFeatureWorkflow" TargetConnectionIndex="0" SourceStateName="DeletePageTemplateFeatureWorkflow" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="74" /> <ns0:Point X="1111" Y="74" /> <ns0:Point X="1111" Y="129" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="confirmStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="confirmStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="286" Y="150" /> <ns0:Point X="364" Y="150" /> <ns0:Point X="364" Y="241" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" SourceConnectionEdge="Right" EventHandlerName="confirmEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="474" Y="311" /> <ns0:Point X="525" Y="311" /> <ns0:Point X="525" Y="413" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" SourceConnectionEdge="Right" EventHandlerName="confirmEventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="479" Y="337" /> <ns0:Point X="495" Y="337" /> <ns0:Point X="495" Y="121" /> <ns0:Point X="1111" Y="121" /> <ns0:Point X="1111" Y="129" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="631" Y="457" /> <ns0:Point X="647" Y="457" /> <ns0:Point X="647" Y="121" /> <ns0:Point X="1111" Y="121" /> <ns0:Point X="1111" Y="129" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150, 209" Location="38, 63"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130, 44" Location="48, 128" /> <SetStateDesigner Name="setStateActivity1" Size="130, 62" Location="48, 191" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="227, 80" AutoSizeMargin="16, 24" Location="63, 106" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150, 146" Location="71, 139"> <StateInitializationDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130, 62" Location="81, 204" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160, 80" AutoSizeMargin="16, 24" Location="1031, 129" Name="finalStateActivity" /> <StateDesigner Size="237, 126" AutoSizeMargin="16, 24" AutoSize="False" Location="246, 241" Name="confirmStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="confirmStateInitializationActivity" Size="150, 128" Location="572, 154"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="confirmDialogFormActivity2" Size="130, 44" Location="582, 219" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="confirmEventDrivenActivity_Finish" Size="150, 209" Location="564, 167"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130, 44" Location="574, 232" /> <SetStateDesigner Name="setStateActivity2" Size="130, 62" Location="574, 295" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="confirmEventDrivenActivity_Cancel" Size="150, 209" Location="564, 193"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130, 44" Location="574, 258" /> <SetStateDesigner Name="setStateActivity5" Size="130, 62" Location="574, 321" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="220, 80" AutoSizeMargin="16, 24" Location="415, 413" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150, 209" Location="423, 446"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity_Finalize" Size="130, 44" Location="433, 511" /> <SetStateDesigner Name="setStateActivity4" Size="130, 62" Location="433, 574" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateFeatureElementProvider/EditPageTemplateFeatureWorkflow.cs ================================================ using System; using System.IO; using Composite.C1Console.Events; using Composite.C1Console.Workflow; using Composite.Core.IO; using Composite.Core.WebClient.Renderings.Template; using Composite.Core.Xml; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateFeatureElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditPageTemplateFeatureWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditPageTemplateFeatureWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { string markup; if (C1File.Exists(this.FilePath)) { markup = C1File.ReadAllText(this.FilePath); } else { // someone deleted the feature file, but that won't stop us! XhtmlDocument template = new XhtmlDocument(); template.Head.Add(""); template.Body.Add(""); markup = template.ToString(); } this.Bindings.Add("FeatureName", this.FeatureName); this.Bindings.Add("Markup", markup); if (Path.GetExtension(this.FilePath)==".html") { this.documentFormActivity1.FormDefinitionFileName = @"\Administrative\PageTemplateFeature\EditVisual.xml"; } else { this.documentFormActivity1.FormDefinitionFileName = @"\Administrative\PageTemplateFeature\EditMarkup.xml"; } } private void saveStateCodeActivity_ExecuteCode(object sender, EventArgs e) { string content = this.GetBinding<string>("Markup"); FileUtils.RemoveReadOnly(this.FilePath); C1File.WriteAllText(this.FilePath, content); this.SetSaveStatus(true); } private string FeatureName { get { PageTemplateFeatureEntityToken castedEntityToken = (PageTemplateFeatureEntityToken)this.EntityToken; return castedEntityToken.FeatureName; } } private string FilePath { get { PageTemplateFeatureEntityToken castedEntityToken = (PageTemplateFeatureEntityToken)this.EntityToken; return PageTemplateFeatureFacade.GetPageTemplateFeaturePath(castedEntityToken.FeatureName); } } private void IsMarkupValid(object sender, System.Workflow.Activities.ConditionalEventArgs e) { PageTemplateFeatureEntityToken castedEntityToken = (PageTemplateFeatureEntityToken)this.EntityToken; string content = this.GetBinding<string>("Markup"); this.UpdateBinding("Errors", ""); XhtmlDocument document = null; try { document = XhtmlDocument.Parse(content); } catch (Exception ex) { this.UpdateBinding("Errors", ex.Message); e.Result = false; return; } e.Result = true; } private void editCodeActivity_ShowErrorMessage_ExecuteCode(object sender, EventArgs e) { this.ShowMessage(DialogType.Error, "Error", this.GetBinding<string>("Errors")); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateFeatureElementProvider/EditPageTemplateFeatureWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateFeatureElementProvider { partial class EditPageTemplateFeatureWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.editCodeActivity_ShowErrorMessage = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.saveStateCodeActivity = new System.Workflow.Activities.CodeActivity(); this.editIfElseActivity_IsValidMarkup = new System.Workflow.Activities.IfElseActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editEventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "editStateActivity"; // // editCodeActivity_ShowErrorMessage // this.editCodeActivity_ShowErrorMessage.Name = "editCodeActivity_ShowErrorMessage"; this.editCodeActivity_ShowErrorMessage.ExecuteCode += new System.EventHandler(this.editCodeActivity_ShowErrorMessage_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "saveStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.editCodeActivity_ShowErrorMessage); this.ifElseBranchActivity2.Activities.Add(this.setStateActivity3); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity4); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsMarkupValid); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "editStateActivity"; // // saveStateCodeActivity // this.saveStateCodeActivity.Name = "saveStateCodeActivity"; this.saveStateCodeActivity.ExecuteCode += new System.EventHandler(this.saveStateCodeActivity_ExecuteCode); // // editIfElseActivity_IsValidMarkup // this.editIfElseActivity_IsValidMarkup.Activities.Add(this.ifElseBranchActivity1); this.editIfElseActivity_IsValidMarkup.Activities.Add(this.ifElseBranchActivity2); this.editIfElseActivity_IsValidMarkup.Name = "editIfElseActivity_IsValidMarkup"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.CustomToolbarDefinitionFileName = null; this.documentFormActivity1.FormDefinitionFileName = "\\Administrative\\PageTemplateFeature\\EditMarkup.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.saveStateCodeActivity); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity5); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // editEventDrivenActivity_Save // this.editEventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.editEventDrivenActivity_Save.Activities.Add(this.editIfElseActivity_IsValidMarkup); this.editEventDrivenActivity_Save.Name = "editEventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.saveStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_Save); this.editStateActivity.Name = "editStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // EditTreeDefinitionWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "EditTreeDefinitionWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private StateInitializationActivity editStateInitializationActivity; private StateActivity editStateActivity; private CodeActivity initializeCodeActivity; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity4; private StateInitializationActivity saveStateInitializationActivity; private EventDrivenActivity editEventDrivenActivity_Save; private StateActivity saveStateActivity; private C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private CodeActivity saveStateCodeActivity; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity editIfElseActivity_IsValidMarkup; private SetStateActivity setStateActivity3; private CodeActivity editCodeActivity_ShowErrorMessage; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateFeatureElementProvider/EditTreeDefinitionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1164; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="EditTreeDefinitionWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 182" Location="98; 169"> <StateInitializationDesigner.Designers> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="108; 231" /> <CodeDesigner Name="initializeCodeActivity" Size="130; 41" Location="108; 291" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="208; 102" AutoSizeMargin="16; 24" AutoSize="False" Location="240; 340" Name="editStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="editStateInitializationActivity" Size="150; 122" Location="413; 135"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="documentFormActivity1" Size="130; 41" Location="423; 197" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="editEventDrivenActivity_Save" Size="381; 423" Location="421; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130; 41" Location="546; 210" /> <IfElseDesigner Name="editIfElseActivity_IsValidMarkup" Size="361; 282" Location="431; 270"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 182" Location="450; 341"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="460; 433" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 182" Location="623; 341"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="editCodeActivity_ShowErrorMessage" Size="130; 41" Location="633; 403" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="633; 463" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="199; 80" AutoSizeMargin="16; 24" Location="535; 561" Name="saveStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="saveStateInitializationActivity" Size="150; 182" Location="543; 592"> <StateInitializationDesigner.Designers> <CodeDesigner Name="saveStateCodeActivity" Size="130; 41" Location="553; 654" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="553; 714" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="EditTreeDefinitionWorkflow" TargetConnectionIndex="0" SourceStateName="EditTreeDefinitionWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="344" Y="179" /> <ns0:Point X="344" Y="340" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" SetStateName="setStateActivity4" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editEventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="429" Y="405" /> <ns0:Point X="634" Y="405" /> <ns0:Point X="634" Y="561" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity5" SourceActivity="saveStateActivity" TargetConnectionIndex="0" SourceStateName="saveStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="saveStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="724" Y="602" /> <ns0:Point X="744" Y="602" /> <ns0:Point X="744" Y="332" /> <ns0:Point X="344" Y="332" /> <ns0:Point X="344" Y="340" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateFeatureElementProvider/TogglePageTemplateFeatureEditorWorkflow.cs ================================================ using System; using System.IO; using Composite.C1Console.Workflow; using Composite.Core.IO; using Composite.Core.WebClient.Renderings.Template; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateFeatureElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class TogglePageTemplateFeatureEditorWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public TogglePageTemplateFeatureEditorWorkflow() { InitializeComponent(); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { string oldPath = this.FilePath; if (oldPath != null && C1File.Exists(oldPath)) { string newPath = Path.Combine(Path.GetDirectoryName(oldPath), Path.GetFileNameWithoutExtension(oldPath)); if (Path.GetExtension(oldPath) == ".html") { newPath += ".xml"; } else { newPath += ".html"; } C1File.Move(oldPath, newPath); this.RefreshRootEntityToken(); } } private string FilePath { get { PageTemplateFeatureEntityToken castedEntityToken = (PageTemplateFeatureEntityToken)this.EntityToken; return PageTemplateFeatureFacade.GetPageTemplateFeaturePath(castedEntityToken.FeatureName); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateFeatureElementProvider/TogglePageTemplateFeatureEditorWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTemplateFeatureElementProvider { partial class TogglePageTemplateFeatureEditorWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalizeStateActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // DeletePageTemplateFeatureWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "DeletePageTemplateFeatureWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private StateInitializationActivity finalizeStateInitializationActivity; private StateActivity finalizeStateActivity; private SetStateActivity setStateActivity4; private CodeActivity finalizeCodeActivity_Finalize; private SetStateActivity setStateActivity2; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTemplateFeatureElementProvider/TogglePageTemplateFeatureEditorWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1234, 649" AutoSizeMargin="16, 24" AutoSize="False" Location="30, 30" Name="DeletePageTemplateFeatureWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="TogglePageTemplateFeatureEditorWorkflow" TargetConnectionIndex="0" SourceStateName="DeletePageTemplateFeatureWorkflow" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="74" /> <ns0:Point X="1045" Y="74" /> <ns0:Point X="1045" Y="136" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="526" Y="285" /> <ns0:Point X="542" Y="285" /> <ns0:Point X="542" Y="128" /> <ns0:Point X="1045" Y="128" /> <ns0:Point X="1045" Y="136" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="286" Y="150" /> <ns0:Point X="420" Y="150" /> <ns0:Point X="420" Y="241" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150, 209" Location="38, 63"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130, 44" Location="48, 128" /> <SetStateDesigner Name="setStateActivity1" Size="130, 62" Location="48, 191" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="227, 80" AutoSizeMargin="16, 24" Location="63, 106" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150, 146" Location="71, 139"> <StateInitializationDesigner.Designers> <SetStateDesigner Name="setStateActivity2" Size="130, 62" Location="81, 204" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160, 80" AutoSizeMargin="16, 24" Location="965, 136" Name="finalStateActivity" /> <StateDesigner Size="220, 80" AutoSizeMargin="16, 24" AutoSize="False" Location="310, 241" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150, 209" Location="572, 154"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity_Finalize" Size="130, 44" Location="582, 219" /> <SetStateDesigner Name="setStateActivity4" Size="130, 62" Location="582, 282" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/AddNewPageTypeWorkflow.cs ================================================ using System; using Composite.Data.Types; using Composite.Data; using System.Workflow.Activities; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTypeElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewPageTypeWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddNewPageTypeWorkflow() { InitializeComponent(); } private void initializeCodeActivity_UpdateBindings_ExecuteCode(object sender, EventArgs e) { IPageType pageType = DataFacade.BuildNew<IPageType>(); pageType.Id = Guid.NewGuid(); pageType.Available = true; pageType.PresetMenuTitle = true; pageType.HomepageRelation = nameof(PageTypeHomepageRelation.NoRestriction); pageType.DefaultTemplateId = Guid.Empty; pageType.DefaultChildPageType = Guid.Empty; this.Bindings.Add("NewPageType", pageType); } private void ValidateBindings(object sender, ConditionalEventArgs e) { e.Result = true; } private void finalizeCodeActivity_SavePageType_ExecuteCode(object sender, EventArgs e) { IPageType pageType = this.GetBinding<IPageType>("NewPageType"); pageType = DataFacade.AddNew<IPageType>(pageType); this.RefreshCurrentEntityToken(); this.CloseCurrentView(); this.RefreshCurrentEntityToken(); this.ExecuteWorklow(pageType.GetDataEntityToken(), WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageTypeElementProvider.EditPageTypeWorkflow")); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/AddNewPageTypeWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTypeElementProvider { partial class AddNewPageTypeWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_SavePageType = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step1IfElseActivity_ValidateBindings = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step1WizardFormActivity = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_UpdateBindings = new System.Workflow.Activities.CodeActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "step1StateActivity"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity6); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity3); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateBindings); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_SavePageType // this.finalizeCodeActivity_SavePageType.Name = "finalizeCodeActivity_SavePageType"; this.finalizeCodeActivity_SavePageType.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_SavePageType_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // step1IfElseActivity_ValidateBindings // this.step1IfElseActivity_ValidateBindings.Activities.Add(this.ifElseBranchActivity1); this.step1IfElseActivity_ValidateBindings.Activities.Add(this.ifElseBranchActivity2); this.step1IfElseActivity_ValidateBindings.Name = "step1IfElseActivity_ValidateBindings"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // step1WizardFormActivity // this.step1WizardFormActivity.ContainerLabel = null; this.step1WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PageTypeAddPageType.xml"; this.step1WizardFormActivity.Name = "step1WizardFormActivity"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "step1StateActivity"; // // initializeCodeActivity_UpdateBindings // this.initializeCodeActivity_UpdateBindings.Name = "initializeCodeActivity_UpdateBindings"; this.initializeCodeActivity_UpdateBindings.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_UpdateBindings_ExecuteCode); // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_SavePageType); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity2); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.step1IfElseActivity_ValidateBindings); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1WizardFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_UpdateBindings); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity5); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // AddNewPageTypeWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddNewPageTypeWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity4; private CodeActivity finalizeCodeActivity_SavePageType; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateInitializationActivity step1StateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private C1Console.Workflow.Activities.DataDialogFormActivity step1WizardFormActivity; private SetStateActivity setStateActivity5; private CodeActivity initializeCodeActivity_UpdateBindings; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity step1IfElseActivity_ValidateBindings; private SetStateActivity setStateActivity6; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/AddNewPageTypeWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1207; 986" AutoSizeMargin="16; 24" Location="30; 30" Name="AddNewPageTypeWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 182" Location="98; 169"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_UpdateBindings" Size="130; 41" Location="108; 231" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="108; 291" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="211; 102" AutoSizeMargin="16; 24" Location="260; 323" Name="step1StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1StateInitializationActivity" Size="150; 122" Location="268; 354"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="step1WizardFormActivity" Size="130; 41" Location="278; 416" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Finish" Size="381; 363" Location="268; 378"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="393; 440" /> <IfElseDesigner Name="step1IfElseActivity_ValidateBindings" Size="361; 222" Location="278; 500"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 122" Location="297; 571"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="307; 633" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 122" Location="470; 571"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="480; 633" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Cancel" Size="150; 182" Location="268; 402"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="278; 464" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="278; 524" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" Location="563; 534" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 182" Location="571; 565"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity_SavePageType" Size="130; 41" Location="581; 627" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="581; 687" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="AddNewPageTypeWorkflow" TargetConnectionIndex="0" SourceStateName="AddNewPageTypeWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity2" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="467" Y="412" /> <ns0:Point X="1058" Y="412" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity3" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="463" Y="388" /> <ns0:Point X="665" Y="388" /> <ns0:Point X="665" Y="534" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity4" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="764" Y="575" /> <ns0:Point X="1058" Y="575" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity5" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="365" Y="179" /> <ns0:Point X="365" Y="323" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity6" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="463" Y="388" /> <ns0:Point X="477" Y="388" /> <ns0:Point X="477" Y="315" /> <ns0:Point X="365" Y="315" /> <ns0:Point X="365" Y="323" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/AddPageTypeDefaultPageContentWorkflow.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using Composite.Core.PageTemplates; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Elements; using Composite.C1Console.Trees; using Composite.C1Console.Workflow; using RS = Composite.Core.ResourceSystem.StringResourceSystemFacade; namespace Composite.Plugins.Elements.ElementProviders.PageTypeElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddPageTypeDefaultPageContentWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddPageTypeDefaultPageContentWorkflow() { InitializeComponent(); } private void initializeCodeActivity_UpdateBindings_ExecuteCode(object sender, EventArgs e) { IPageTypeDefaultPageContent defaultPageContent = DataFacade.BuildNew<IPageTypeDefaultPageContent>(); defaultPageContent.Id = Guid.NewGuid(); this.Bindings.Add("DefaultPageContent", defaultPageContent); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { IPageTypeDefaultPageContent defaultPageContent = this.GetBinding<IPageTypeDefaultPageContent>("DefaultPageContent"); Dictionary<string, string> piggybag = PiggybagSerializer.Deserialize(this.ExtraPayload); DataEntityToken dataEntityToken = piggybag.GetParentEntityTokens().FindDataEntityToken(typeof(IPageType)); IPageType parentPageType = (IPageType)dataEntityToken.Data; var duplicate = DataFacade.GetData<IPageTypeDefaultPageContent>(f => f.PageTypeId == parentPageType.Id && f.PlaceHolderId == defaultPageContent.PlaceHolderId).FirstOrDefault(); if (duplicate == null) { defaultPageContent.PageTypeId = parentPageType.Id; defaultPageContent.Content = " "; defaultPageContent = DataFacade.AddNew<IPageTypeDefaultPageContent>(defaultPageContent); } else { defaultPageContent = duplicate; } this.CloseCurrentView(); this.RefreshCurrentEntityToken(); if (!AnyTemplatesContainingPlaceholderId()) { ShowMessage(C1Console.Events.DialogType.Message, string.Format(RS.GetString("Composite.Plugins.PageTypeElementProvider", "PageType.AddPageTypeDefaultPageContentWorkflow.NonExistingPlaceholderId.Title"), defaultPageContent.PlaceHolderId), string.Format(RS.GetString("Composite.Plugins.PageTypeElementProvider", "PageType.AddPageTypeDefaultPageContentWorkflow.NonExistingPlaceholderId.Message"), defaultPageContent.PlaceHolderId)); } this.ExecuteWorklow(defaultPageContent.GetDataEntityToken(), WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageTypeElementProvider.EditPageTypeDefaultPageContentWorkflow")); } private bool AnyTemplatesContainingPlaceholderId() { IPageTypeDefaultPageContent defaultPageContent = this.GetBinding<IPageTypeDefaultPageContent>("DefaultPageContent"); foreach (var templateDescriptor in PageTemplateFacade.GetPageTemplates()) { if(templateDescriptor.PlaceholderDescriptions .Any(placholder => placholder.Id == defaultPageContent.PlaceHolderId)) { return true; } } return false; } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/AddPageTypeDefaultPageContentWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTypeElementProvider { partial class AddPageTypeDefaultPageContentWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step1WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_UpdateBindings = new System.Workflow.Activities.CodeActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // step1WizardFormActivity // this.step1WizardFormActivity.ContainerLabel = null; this.step1WizardFormActivity.FormDefinitionFileName = "\\Administrative\\PageTypeAddPageTypeDefaultPageContent.xml"; this.step1WizardFormActivity.Name = "step1WizardFormActivity"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "step1StateActivity"; // // initializeCodeActivity_UpdateBindings // this.initializeCodeActivity_UpdateBindings.Name = "initializeCodeActivity_UpdateBindings"; this.initializeCodeActivity_UpdateBindings.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_UpdateBindings_ExecuteCode); // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity4); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity3); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1WizardFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_UpdateBindings); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity5); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // AddPageTypeDefaultPageContentWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddPageTypeDefaultPageContentWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.WizardFormActivity step1WizardFormActivity; private SetStateActivity setStateActivity5; private CodeActivity initializeCodeActivity_UpdateBindings; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateInitializationActivity step1StateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private CodeActivity finalizeCodeActivity_Finalize; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/AddPageTypeDefaultPageContentWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1207; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="AddPageTypeDefaultPageContentWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 182" Location="98; 169"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_UpdateBindings" Size="130; 41" Location="108; 231" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="108; 291" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="211; 102" AutoSizeMargin="16; 24" AutoSize="False" Location="235; 307" Name="step1StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1StateInitializationActivity" Size="150; 122" Location="550; 135"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="step1WizardFormActivity" Size="130; 41" Location="560; 197" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Finish" Size="150; 182" Location="558; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="568; 210" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="568; 270" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Cancel" Size="150; 182" Location="550; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="560; 245" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="560; 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="696; 607" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 182" Location="704; 638"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity_Finalize" Size="130; 41" Location="714; 700" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="714; 760" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="AddPageTypeDefaultPageContentWorkflow" TargetConnectionIndex="0" SourceStateName="AddPageTypeDefaultPageContentWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" SetStateName="setStateActivity5" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="340" Y="179" /> <ns0:Point X="340" Y="307" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity3" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="438" Y="372" /> <ns0:Point X="798" Y="372" /> <ns0:Point X="798" Y="607" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity4" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="442" Y="396" /> <ns0:Point X="1058" Y="396" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity2" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="897" Y="648" /> <ns0:Point X="1058" Y="648" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/AddPageTypeMetaDataFieldWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Transactions; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Elements; using Composite.C1Console.Trees; using Composite.C1Console.Workflow; using Composite.Core.Linq; using Composite.Core.ResourceSystem; using Composite.Core.Types; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.GeneratedTypes; using Composite.Data.Transactions; using Composite.Data.Types; using Composite.Data.Validation.ClientValidationRules; namespace Composite.Plugins.Elements.ElementProviders.PageTypeElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddPageTypeMetaDataFieldWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddPageTypeMetaDataFieldWorkflow() { InitializeComponent(); } private void initializeCodeActivity_UpdateBindings_ExecuteCode(object sender, EventArgs e) { IPageTypeMetaDataTypeLink pageTypeMetaDataTypeLink = DataFacade.BuildNew<IPageTypeMetaDataTypeLink>(); pageTypeMetaDataTypeLink.Id = Guid.NewGuid(); Dictionary<string, string> piggybag = PiggybagSerializer.Deserialize(this.ExtraPayload); DataEntityToken dataEntityToken = piggybag.GetParentEntityTokens().FindDataEntityToken(typeof(IPageType)); IPageType parentPageType = (IPageType)dataEntityToken.Data; pageTypeMetaDataTypeLink.PageTypeId = parentPageType.Id; this.Bindings.Add("CompositionDescriptionName", ""); this.Bindings.Add("CompositionDescriptionLabel", ""); this.Bindings.Add("NewMetaDataTypeLink", pageTypeMetaDataTypeLink); List<KeyValuePair<Guid, string>> metaDataTypeOptions = PageMetaDataFacade.GetAllMetaDataTypes(). ToList(f => new KeyValuePair<Guid, string>(f.GetImmutableTypeId(), f.GetTypeTitle())); this.Bindings.Add("MetaDataTypeOptions", metaDataTypeOptions); List<KeyValuePair<Guid, string>> metaDataContainerOptions = PageMetaDataFacade.GetAllMetaDataContainers(); this.Bindings.Add("MetaDataContainerOptions", metaDataContainerOptions); this.Bindings.Add("CompositionContainerId", metaDataContainerOptions.First().Key); this.BindingsValidationRules.Add("CompositionDescriptionName", new List<ClientValidationRule> { new NotNullClientValidationRule(), new StringLengthClientValidationRule(1, 128) }); this.BindingsValidationRules.Add("CompositionDescriptionLabel", new List<ClientValidationRule> { new NotNullClientValidationRule(), new StringLengthClientValidationRule(1, 256) }); } private void PagesUsingPageTypeExists(object sender, ConditionalEventArgs e) { IPageTypeMetaDataTypeLink metaDataTypeLink = this.GetBinding<IPageTypeMetaDataTypeLink>("NewMetaDataTypeLink"); e.Result = DataFacade.GetData<IPage>().Where(f => f.PageTypeId == metaDataTypeLink.PageTypeId).Any(); } private void ValidateMetaDataName(object sender, ConditionalEventArgs e) { IPageTypeMetaDataTypeLink pageTypeMetaDataTypeLink = this.GetBinding<IPageTypeMetaDataTypeLink>("NewMetaDataTypeLink"); string metaDataDefinitionName = this.GetBinding<string>("CompositionDescriptionName"); string metaDataDefinitionLabel = this.GetBinding<string>("CompositionDescriptionLabel"); e.Result = PageMetaDataFacade.IsDefinitionAllowed(pageTypeMetaDataTypeLink.PageTypeId, metaDataDefinitionName, metaDataDefinitionLabel, pageTypeMetaDataTypeLink.DataTypeId); if (e.Result == false) { ShowFieldMessage("CompositionDescriptionName", "${Composite.Plugins.PageTypeElementProvider, PageType.AddPageTypeMetaDataFieldWorkflow.ValidationError.MetaDataFieldNameAlreadyUsed}"); } } private void step2CodeActivity_ShowWizzard_ExecuteCode(object sender, EventArgs e) { IPageTypeMetaDataTypeLink pageTypeMetaDataTypeLink = this.GetBinding<IPageTypeMetaDataTypeLink>("NewMetaDataTypeLink"); DataTypeDescriptor dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(pageTypeMetaDataTypeLink.DataTypeId); Type metaDataType = TypeManager.GetType(dataTypeDescriptor.TypeManagerTypeName); DataTypeDescriptorFormsHelper helper = new DataTypeDescriptorFormsHelper(dataTypeDescriptor); helper.LayoutLabel = StringResourceSystemFacade.GetString("Composite.Plugins.PageTypeElementProvider", "PageType.AddPageTypeMetaDataFieldWorkflow.AddingDefaultMetaData.Title"); helper.LayoutIconHandle = "pagetype-add-metedatafield"; GeneratedTypesHelper generatedTypesHelper = new GeneratedTypesHelper(dataTypeDescriptor); helper.AddReadOnlyFields(generatedTypesHelper.NotEditableDataFieldDescriptorNames); IData newDataTemplate = DataFacade.BuildNew(metaDataType); helper.UpdateWithNewBindings(this.Bindings); helper.ObjectToBindings(newDataTemplate, this.Bindings); this.UpdateBinding("NewDataTemplate", newDataTemplate); this.DeliverFormData( metaDataType.GetTypeTitle(), StandardUiContainerTypes.Wizard, helper.GetForm(), this.Bindings, helper.GetBindingsValidationRules(newDataTemplate) ); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { IPageTypeMetaDataTypeLink pageTypeMetaDataTypeLink = this.GetBinding<IPageTypeMetaDataTypeLink>("NewMetaDataTypeLink"); IData newDataTemplate; this.TryGetBinding("NewDataTemplate", out newDataTemplate); string metaDataDefinitionName = this.GetBinding<string>("CompositionDescriptionName"); pageTypeMetaDataTypeLink.Name = metaDataDefinitionName; using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { DataFacade.AddNew<IPageTypeMetaDataTypeLink>(pageTypeMetaDataTypeLink); PageMetaDataFacade.AddDefinition( pageTypeMetaDataTypeLink.PageTypeId, metaDataDefinitionName, this.GetBinding<string>("CompositionDescriptionLabel"), pageTypeMetaDataTypeLink.DataTypeId, this.GetBinding<Guid>("CompositionContainerId") ); if (newDataTemplate != null) { IPageType pageType = DataFacade.GetData<IPageType>().Single(f => f.Id == pageTypeMetaDataTypeLink.PageTypeId); PageMetaDataFacade.AddNewMetaDataToExistingPages(pageType, metaDataDefinitionName, newDataTemplate); } transactionScope.Complete(); } this.RefreshCurrentEntityToken(); } private void DefaultValuesAreValid(object sender, ConditionalEventArgs e) { IData newDataTemplate; if (!this.TryGetBinding("NewDataTemplate", out newDataTemplate)) { e.Result = true; return; } IPageTypeMetaDataTypeLink pageTypeMetaDataTypeLink = this.GetBinding<IPageTypeMetaDataTypeLink>("NewMetaDataTypeLink"); var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(pageTypeMetaDataTypeLink.DataTypeId); var helper = new DataTypeDescriptorFormsHelper(dataTypeDescriptor); e.Result = BindAndValidate(helper, newDataTemplate); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/AddPageTypeMetaDataFieldWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTypeElementProvider { partial class AddPageTypeMetaDataFieldWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition3 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition4 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity13 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity11 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity12 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.if_notValid1 = new System.Workflow.Activities.IfElseBranchActivity(); this.if_valid1 = new System.Workflow.Activities.IfElseBranchActivity(); this.if_notValid = new System.Workflow.Activities.IfElseBranchActivity(); this.if_valid = new System.Workflow.Activities.IfElseBranchActivity(); this.if_isNotValid = new System.Workflow.Activities.IfElseBranchActivity(); this.if_isValid = new System.Workflow.Activities.IfElseBranchActivity(); this.ifNotExist = new System.Workflow.Activities.IfElseBranchActivity(); this.ifExist = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity4 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.if_defaultValuesAreValid = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step2CodeActivity_ShowWizzard = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step1ifElseActivity_Finish_ValidateMetaDataName = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step1WizardFormActivity_Finish = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.wizardFormActivity1 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step1IfElseActivity_ValidateMetaDataName = new System.Workflow.Activities.IfElseActivity(); this.nextHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.NextHandleExternalEventActivity(); this.ifPagesUsingPageTypeExist = new System.Workflow.Activities.IfElseActivity(); this.initializeCodeActivity_UpdateBindings = new System.Workflow.Activities.CodeActivity(); this.step2EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step2EventDrivenActivity_Finsih = new System.Workflow.Activities.EventDrivenActivity(); this.step2StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Finish_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish_Finsih = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity_Finish = new System.Workflow.Activities.StateInitializationActivity(); this.step1StateInitializationActivity_Next = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Next_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Next_Next = new System.Workflow.Activities.EventDrivenActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.step2_EnterDefaultValues = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1_EnterMetaDataFieldName_NoDefaultValues = new System.Workflow.Activities.StateActivity(); this.step1_EnterMetaDataFieldName = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity13 // this.setStateActivity13.Name = "setStateActivity13"; this.setStateActivity13.TargetStateName = "step2_EnterDefaultValues"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "finalizeStateActivity"; // // setStateActivity11 // this.setStateActivity11.Name = "setStateActivity11"; this.setStateActivity11.TargetStateName = "step1_EnterMetaDataFieldName_NoDefaultValues"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalizeStateActivity"; // // setStateActivity12 // this.setStateActivity12.Name = "setStateActivity12"; this.setStateActivity12.TargetStateName = "step1_EnterMetaDataFieldName"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "step2_EnterDefaultValues"; // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "step1_EnterMetaDataFieldName_NoDefaultValues"; // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "step1_EnterMetaDataFieldName"; // // if_notValid1 // this.if_notValid1.Activities.Add(this.setStateActivity13); this.if_notValid1.Name = "if_notValid1"; // // if_valid1 // this.if_valid1.Activities.Add(this.setStateActivity8); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.DefaultValuesAreValid); this.if_valid1.Condition = codecondition1; this.if_valid1.Name = "if_valid1"; // // if_notValid // this.if_notValid.Activities.Add(this.setStateActivity11); this.if_notValid.Name = "if_notValid"; // // if_valid // this.if_valid.Activities.Add(this.setStateActivity4); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateMetaDataName); this.if_valid.Condition = codecondition2; this.if_valid.Name = "if_valid"; // // if_isNotValid // this.if_isNotValid.Activities.Add(this.setStateActivity12); this.if_isNotValid.Name = "if_isNotValid"; // // if_isValid // this.if_isValid.Activities.Add(this.setStateActivity6); codecondition3.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateMetaDataName); this.if_isValid.Condition = codecondition3; this.if_isValid.Name = "if_isValid"; // // ifNotExist // this.ifNotExist.Activities.Add(this.setStateActivity10); this.ifNotExist.Name = "ifNotExist"; // // ifExist // this.ifExist.Activities.Add(this.setStateActivity9); codecondition4.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.PagesUsingPageTypeExists); this.ifExist.Condition = codecondition4; this.ifExist.Name = "ifExist"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity4 // this.cancelHandleExternalEventActivity4.EventName = "Cancel"; this.cancelHandleExternalEventActivity4.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity4.Name = "cancelHandleExternalEventActivity4"; // // if_defaultValuesAreValid // this.if_defaultValuesAreValid.Activities.Add(this.if_valid1); this.if_defaultValuesAreValid.Activities.Add(this.if_notValid1); this.if_defaultValuesAreValid.Name = "if_defaultValuesAreValid"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // step2CodeActivity_ShowWizzard // this.step2CodeActivity_ShowWizzard.Name = "step2CodeActivity_ShowWizzard"; this.step2CodeActivity_ShowWizzard.ExecuteCode += new System.EventHandler(this.step2CodeActivity_ShowWizzard_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // step1ifElseActivity_Finish_ValidateMetaDataName // this.step1ifElseActivity_Finish_ValidateMetaDataName.Activities.Add(this.if_valid); this.step1ifElseActivity_Finish_ValidateMetaDataName.Activities.Add(this.if_notValid); this.step1ifElseActivity_Finish_ValidateMetaDataName.Name = "step1ifElseActivity_Finish_ValidateMetaDataName"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // step1WizardFormActivity_Finish // this.step1WizardFormActivity_Finish.ContainerLabel = null; this.step1WizardFormActivity_Finish.FormDefinitionFileName = "/Administrative/PageTypeAddPageTypeMetaDataFieldStep1.xml"; this.step1WizardFormActivity_Finish.Name = "step1WizardFormActivity_Finish"; // // wizardFormActivity1 // this.wizardFormActivity1.ContainerLabel = null; this.wizardFormActivity1.FormDefinitionFileName = "/Administrative/PageTypeAddPageTypeMetaDataFieldStep1.xml"; this.wizardFormActivity1.Name = "wizardFormActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // step1IfElseActivity_ValidateMetaDataName // this.step1IfElseActivity_ValidateMetaDataName.Activities.Add(this.if_isValid); this.step1IfElseActivity_ValidateMetaDataName.Activities.Add(this.if_isNotValid); this.step1IfElseActivity_ValidateMetaDataName.Name = "step1IfElseActivity_ValidateMetaDataName"; // // nextHandleExternalEventActivity1 // this.nextHandleExternalEventActivity1.EventName = "Next"; this.nextHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.nextHandleExternalEventActivity1.Name = "nextHandleExternalEventActivity1"; // // ifPagesUsingPageTypeExist // this.ifPagesUsingPageTypeExist.Activities.Add(this.ifExist); this.ifPagesUsingPageTypeExist.Activities.Add(this.ifNotExist); this.ifPagesUsingPageTypeExist.Name = "ifPagesUsingPageTypeExist"; // // initializeCodeActivity_UpdateBindings // this.initializeCodeActivity_UpdateBindings.Name = "initializeCodeActivity_UpdateBindings"; this.initializeCodeActivity_UpdateBindings.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_UpdateBindings_ExecuteCode); // // step2EventDrivenActivity_Cancel // this.step2EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity4); this.step2EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity7); this.step2EventDrivenActivity_Cancel.Name = "step2EventDrivenActivity_Cancel"; // // step2EventDrivenActivity_Finsih // this.step2EventDrivenActivity_Finsih.Activities.Add(this.finishHandleExternalEventActivity2); this.step2EventDrivenActivity_Finsih.Activities.Add(this.if_defaultValuesAreValid); this.step2EventDrivenActivity_Finsih.Name = "step2EventDrivenActivity_Finsih"; // // step2StateInitializationActivity // this.step2StateInitializationActivity.Activities.Add(this.step2CodeActivity_ShowWizzard); this.step2StateInitializationActivity.Name = "step2StateInitializationActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity5); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Finish_Cancel // this.step1EventDrivenActivity_Finish_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.step1EventDrivenActivity_Finish_Cancel.Activities.Add(this.setStateActivity2); this.step1EventDrivenActivity_Finish_Cancel.Name = "step1EventDrivenActivity_Finish_Cancel"; // // step1EventDrivenActivity_Finish_Finsih // this.step1EventDrivenActivity_Finish_Finsih.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish_Finsih.Activities.Add(this.step1ifElseActivity_Finish_ValidateMetaDataName); this.step1EventDrivenActivity_Finish_Finsih.Name = "step1EventDrivenActivity_Finish_Finsih"; // // step1StateInitializationActivity_Finish // this.step1StateInitializationActivity_Finish.Activities.Add(this.step1WizardFormActivity_Finish); this.step1StateInitializationActivity_Finish.Name = "step1StateInitializationActivity_Finish"; // // step1StateInitializationActivity_Next // this.step1StateInitializationActivity_Next.Activities.Add(this.wizardFormActivity1); this.step1StateInitializationActivity_Next.Name = "step1StateInitializationActivity_Next"; // // step1EventDrivenActivity_Next_Cancel // this.step1EventDrivenActivity_Next_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Next_Cancel.Activities.Add(this.setStateActivity3); this.step1EventDrivenActivity_Next_Cancel.Name = "step1EventDrivenActivity_Next_Cancel"; // // step1EventDrivenActivity_Next_Next // this.step1EventDrivenActivity_Next_Next.Activities.Add(this.nextHandleExternalEventActivity1); this.step1EventDrivenActivity_Next_Next.Activities.Add(this.step1IfElseActivity_ValidateMetaDataName); this.step1EventDrivenActivity_Next_Next.Name = "step1EventDrivenActivity_Next_Next"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_UpdateBindings); this.initializeStateInitializationActivity.Activities.Add(this.ifPagesUsingPageTypeExist); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // step2_EnterDefaultValues // this.step2_EnterDefaultValues.Activities.Add(this.step2StateInitializationActivity); this.step2_EnterDefaultValues.Activities.Add(this.step2EventDrivenActivity_Finsih); this.step2_EnterDefaultValues.Activities.Add(this.step2EventDrivenActivity_Cancel); this.step2_EnterDefaultValues.Name = "step2_EnterDefaultValues"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1_EnterMetaDataFieldName_NoDefaultValues // this.step1_EnterMetaDataFieldName_NoDefaultValues.Activities.Add(this.step1StateInitializationActivity_Finish); this.step1_EnterMetaDataFieldName_NoDefaultValues.Activities.Add(this.step1EventDrivenActivity_Finish_Finsih); this.step1_EnterMetaDataFieldName_NoDefaultValues.Activities.Add(this.step1EventDrivenActivity_Finish_Cancel); this.step1_EnterMetaDataFieldName_NoDefaultValues.Name = "step1_EnterMetaDataFieldName_NoDefaultValues"; // // step1_EnterMetaDataFieldName // this.step1_EnterMetaDataFieldName.Activities.Add(this.step1EventDrivenActivity_Next_Next); this.step1_EnterMetaDataFieldName.Activities.Add(this.step1EventDrivenActivity_Next_Cancel); this.step1_EnterMetaDataFieldName.Activities.Add(this.step1StateInitializationActivity_Next); this.step1_EnterMetaDataFieldName.Name = "step1_EnterMetaDataFieldName"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // AddPageTypeMetaDataFieldWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1_EnterMetaDataFieldName); this.Activities.Add(this.step1_EnterMetaDataFieldName_NoDefaultValues); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.step2_EnterDefaultValues); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddPageTypeMetaDataFieldWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private C1Console.Workflow.Activities.NextHandleExternalEventActivity nextHandleExternalEventActivity1; private CodeActivity initializeCodeActivity_UpdateBindings; private EventDrivenActivity step1EventDrivenActivity_Next_Cancel; private EventDrivenActivity step1EventDrivenActivity_Next_Next; private StateActivity step1_EnterMetaDataFieldName; private IfElseBranchActivity ifNotExist; private IfElseBranchActivity ifExist; private SetStateActivity setStateActivity7; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity4; private SetStateActivity setStateActivity8; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity6; private IfElseActivity ifPagesUsingPageTypeExist; private EventDrivenActivity step2EventDrivenActivity_Cancel; private EventDrivenActivity step2EventDrivenActivity_Finsih; private StateInitializationActivity step2StateInitializationActivity; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Finish_Cancel; private EventDrivenActivity step1EventDrivenActivity_Finish_Finsih; private StateInitializationActivity step1StateInitializationActivity_Finish; private StateInitializationActivity step1StateInitializationActivity_Next; private StateActivity step2_EnterDefaultValues; private StateActivity finalizeStateActivity; private StateActivity step1_EnterMetaDataFieldName_NoDefaultValues; private SetStateActivity setStateActivity10; private SetStateActivity setStateActivity9; private C1Console.Workflow.Activities.WizardFormActivity step1WizardFormActivity_Finish; private IfElseBranchActivity if_notValid; private IfElseBranchActivity if_valid; private IfElseActivity step1ifElseActivity_Finish_ValidateMetaDataName; private SetStateActivity setStateActivity11; private SetStateActivity setStateActivity12; private IfElseBranchActivity if_isNotValid; private IfElseBranchActivity if_isValid; private IfElseActivity step1IfElseActivity_ValidateMetaDataName; private C1Console.Workflow.Activities.WizardFormActivity wizardFormActivity1; private CodeActivity step2CodeActivity_ShowWizzard; private CodeActivity finalizeCodeActivity_Finalize; private SetStateActivity setStateActivity13; private IfElseBranchActivity if_notValid1; private IfElseBranchActivity if_valid1; private IfElseActivity if_defaultValuesAreValid; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/AddPageTypeMetaDataFieldWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1146; 878" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="AddPageTypeMetaDataFieldWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="AddPageTypeMetaDataFieldWorkflow" TargetConnectionIndex="0" SourceStateName="AddPageTypeMetaDataFieldWorkflow" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="983" Y="603" /> <ns0:Point X="1058" Y="603" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1_EnterMetaDataFieldName" TargetConnectionEdge="Top" SetStateName="setStateActivity9" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1_EnterMetaDataFieldName"> <StateDesignerConnector.Segments> <ns0:Point X="271" Y="165" /> <ns0:Point X="288" Y="165" /> <ns0:Point X="288" Y="333" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="step1_EnterMetaDataFieldName" TargetConnectionIndex="0" SourceStateName="step1_EnterMetaDataFieldName" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Next_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="403" Y="422" /> <ns0:Point X="421" Y="422" /> <ns0:Point X="421" Y="786" /> <ns0:Point X="1058" Y="786" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity8" SourceActivity="step2_EnterDefaultValues" TargetConnectionIndex="0" SourceStateName="step2_EnterDefaultValues" SourceConnectionEdge="Right" EventHandlerName="step2EventDrivenActivity_Finsih" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="668" Y="626" /> <ns0:Point X="688" Y="626" /> <ns0:Point X="688" Y="554" /> <ns0:Point X="884" Y="554" /> <ns0:Point X="884" Y="562" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceActivity="step2_EnterDefaultValues" TargetConnectionIndex="0" SourceStateName="step2_EnterDefaultValues" SourceConnectionEdge="Right" EventHandlerName="step2EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="672" Y="650" /> <ns0:Point X="1058" Y="650" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step2_EnterDefaultValues" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceActivity="step1_EnterMetaDataFieldName" TargetConnectionIndex="0" SourceStateName="step1_EnterMetaDataFieldName" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Next_Next" SourceConnectionIndex="1" TargetStateName="step2_EnterDefaultValues"> <StateDesignerConnector.Segments> <ns0:Point X="393" Y="398" /> <ns0:Point X="570" Y="398" /> <ns0:Point X="570" Y="561" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1_EnterMetaDataFieldName" TargetConnectionEdge="Top" SetStateName="setStateActivity12" SourceActivity="step1_EnterMetaDataFieldName" TargetConnectionIndex="0" SourceStateName="step1_EnterMetaDataFieldName" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Next_Next" SourceConnectionIndex="1" TargetStateName="step1_EnterMetaDataFieldName"> <StateDesignerConnector.Segments> <ns0:Point X="393" Y="398" /> <ns0:Point X="416" Y="398" /> <ns0:Point X="416" Y="325" /> <ns0:Point X="288" Y="325" /> <ns0:Point X="288" Y="333" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="step1_EnterMetaDataFieldName_NoDefaultValues" TargetConnectionIndex="0" SourceStateName="step1_EnterMetaDataFieldName_NoDefaultValues" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish_Finsih" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="831" Y="403" /> <ns0:Point X="884" Y="403" /> <ns0:Point X="884" Y="562" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="step1_EnterMetaDataFieldName_NoDefaultValues" TargetConnectionIndex="0" SourceStateName="step1_EnterMetaDataFieldName_NoDefaultValues" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="835" Y="427" /> <ns0:Point X="1058" Y="427" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1_EnterMetaDataFieldName_NoDefaultValues" TargetConnectionEdge="Top" SetStateName="setStateActivity10" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1_EnterMetaDataFieldName_NoDefaultValues"> <StateDesignerConnector.Segments> <ns0:Point X="271" Y="165" /> <ns0:Point X="733" Y="165" /> <ns0:Point X="733" Y="338" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1_EnterMetaDataFieldName_NoDefaultValues" TargetConnectionEdge="Top" SetStateName="setStateActivity11" SourceActivity="step1_EnterMetaDataFieldName_NoDefaultValues" TargetConnectionIndex="0" SourceStateName="step1_EnterMetaDataFieldName_NoDefaultValues" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish_Finsih" SourceConnectionIndex="1" TargetStateName="step1_EnterMetaDataFieldName_NoDefaultValues"> <StateDesignerConnector.Segments> <ns0:Point X="831" Y="403" /> <ns0:Point X="885" Y="403" /> <ns0:Point X="885" Y="330" /> <ns0:Point X="733" Y="330" /> <ns0:Point X="733" Y="338" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="65; 124" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="381; 375" Location="73; 155"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_UpdateBindings" Size="130; 41" Location="198; 217" /> <IfElseDesigner Name="ifPagesUsingPageTypeExist" Size="361; 234" Location="83; 277"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifExist" Size="150; 134" Location="102; 348"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity9" Size="130; 41" Location="112; 416" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifNotExist" Size="150; 134" Location="275; 348"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity10" Size="130; 53" Location="285; 410" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="242; 102" AutoSizeMargin="16; 24" Location="167; 333" Name="step1_EnterMetaDataFieldName"> <StateDesigner.Designers> <EventDrivenDesigner Name="step1EventDrivenActivity_Next_Next" Size="381; 375" Location="175; 388"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="nextHandleExternalEventActivity1" Size="130; 41" Location="300; 450" /> <IfElseDesigner Name="step1IfElseActivity_ValidateMetaDataName" Size="361; 234" Location="185; 510"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="if_isValid" Size="150; 134" Location="204; 581"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="214; 649" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="if_isNotValid" Size="150; 134" Location="377; 581"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity12" Size="130; 53" Location="387; 643" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Next_Cancel" Size="150; 182" Location="175; 412"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="185; 474" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="185; 534" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateInitializationDesigner Name="step1StateInitializationActivity_Next" Size="150; 122" Location="175; 364"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizardFormActivity1" Size="130; 41" Location="185; 426" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="281; 102" AutoSizeMargin="16; 24" Location="593; 338" Name="step1_EnterMetaDataFieldName_NoDefaultValues"> <StateDesigner.Designers> <StateInitializationDesigner Name="step1StateInitializationActivity_Finish" Size="150; 122" Location="601; 369"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="step1WizardFormActivity_Finish" Size="130; 41" Location="611; 431" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Finish_Finsih" Size="381; 375" Location="601; 393"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="726; 455" /> <IfElseDesigner Name="step1ifElseActivity_Finish_ValidateMetaDataName" Size="361; 234" Location="611; 515"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="if_valid" Size="150; 134" Location="630; 586"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="640; 654" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="if_notValid" Size="150; 134" Location="803; 586"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity11" Size="130; 53" Location="813; 648" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Finish_Cancel" Size="150; 182" Location="601; 417"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity3" Size="130; 41" Location="611; 479" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="611; 539" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="782; 562" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 182" Location="790; 593"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity_Finalize" Size="130; 41" Location="800; 655" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="800; 715" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="211; 102" AutoSizeMargin="16; 24" AutoSize="False" Location="465; 561" Name="step2_EnterDefaultValues"> <StateDesigner.Designers> <StateInitializationDesigner Name="step2StateInitializationActivity" Size="150; 122" Location="381; 135"> <StateInitializationDesigner.Designers> <CodeDesigner Name="step2CodeActivity_ShowWizzard" Size="130; 41" Location="391; 197" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step2EventDrivenActivity_Finsih" Size="381; 375" Location="389; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity2" Size="130; 41" Location="514; 210" /> <IfElseDesigner Name="if_defaultValuesAreValid" Size="361; 234" Location="399; 270"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="if_valid1" Size="150; 134" Location="418; 341"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity8" Size="130; 41" Location="428; 409" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="if_notValid1" Size="150; 134" Location="591; 341"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity13" Size="130; 53" Location="601; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step2EventDrivenActivity_Cancel" Size="150; 182" Location="381; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity4" Size="130; 41" Location="391; 245" /> <SetStateDesigner Name="setStateActivity7" Size="130; 41" Location="391; 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/DeletePageTypeMetaDataFieldWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq.Expressions; using System.Transactions; using Composite.C1Console.Actions; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.Types; using Composite.Core.Linq; using Composite.Core.ResourceSystem; using Composite.Data.Transactions; using Composite.Core.Types; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTypeElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeletePageTypeMetaDataFieldWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeletePageTypeMetaDataFieldWorkflow() { InitializeComponent(); } private void initializeCodeActivity_UpdateBindings_ExecuteCode(object sender, EventArgs e) { IPageTypeMetaDataTypeLink pageTypeMetaDataTypeLink = this.GetDataItemFromEntityToken<IPageTypeMetaDataTypeLink>(); this.Bindings.Add("MessageText", string.Format(StringResourceSystemFacade.GetString("Composite.Plugins.PageTypeElementProvider", "PageType.DeletePageTypeMetaDataFieldWorkflow.Confirm.Layout.Message"), pageTypeMetaDataTypeLink.Name)); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { IPageTypeMetaDataTypeLink pageTypeMetaDataTypeLink = this.GetDataItemFromEntityToken<IPageTypeMetaDataTypeLink>(); DeleteTreeRefresher deleteTreeRefresher = this.CreateDeleteTreeRefresher(this.EntityToken); DataTypeDescriptor dataTypeDescriptor; if (DynamicTypeManager.TryGetDataTypeDescriptor(pageTypeMetaDataTypeLink.DataTypeId, out dataTypeDescriptor)) { PageMetaDataFacade.RemoveDefinition(pageTypeMetaDataTypeLink.PageTypeId, pageTypeMetaDataTypeLink.Name); } DataFacade.Delete<IPageTypeMetaDataTypeLink>(pageTypeMetaDataTypeLink); deleteTreeRefresher.PostRefreshMesseges(); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/DeletePageTypeMetaDataFieldWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTypeElementProvider { partial class DeletePageTypeMetaDataFieldWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_UpdateBindings = new System.Workflow.Activities.CodeActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.confirmEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.confirmEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.confirmStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.confirmStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "/Administrative/PageTypeDeletePageTypeMetaDataFieldConfirm.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "confirmStateActivity"; // // initializeCodeActivity_UpdateBindings // this.initializeCodeActivity_UpdateBindings.Name = "initializeCodeActivity_UpdateBindings"; this.initializeCodeActivity_UpdateBindings.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_UpdateBindings_ExecuteCode); // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // confirmEventDrivenActivity_Cancel // this.confirmEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.confirmEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity5); this.confirmEventDrivenActivity_Cancel.Name = "confirmEventDrivenActivity_Cancel"; // // confirmEventDrivenActivity_Finish // this.confirmEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.confirmEventDrivenActivity_Finish.Activities.Add(this.setStateActivity3); this.confirmEventDrivenActivity_Finish.Name = "confirmEventDrivenActivity_Finish"; // // confirmStateInitializationActivity // this.confirmStateInitializationActivity.Activities.Add(this.confirmDialogFormActivity1); this.confirmStateInitializationActivity.Name = "confirmStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_UpdateBindings); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // confirmStateActivity // this.confirmStateActivity.Activities.Add(this.confirmStateInitializationActivity); this.confirmStateActivity.Activities.Add(this.confirmEventDrivenActivity_Finish); this.confirmStateActivity.Activities.Add(this.confirmEventDrivenActivity_Cancel); this.confirmStateActivity.Name = "confirmStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // DeletePageTypeMetaDataFieldWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.confirmStateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "DeletePageTypeMetaDataFieldWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity5; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private SetStateActivity setStateActivity4; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity confirmEventDrivenActivity_Cancel; private EventDrivenActivity confirmEventDrivenActivity_Finish; private StateInitializationActivity confirmStateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity confirmStateActivity; private CodeActivity initializeCodeActivity_UpdateBindings; private CodeActivity finalizeCodeActivity_Finalize; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/DeletePageTypeMetaDataFieldWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1146; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="DeletePageTypeMetaDataFieldWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 182" Location="98; 169"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_UpdateBindings" Size="130; 41" Location="108; 231" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="108; 291" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="221; 102" AutoSizeMargin="16; 24" Location="291; 323" Name="confirmStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="confirmStateInitializationActivity" Size="150; 122" Location="299; 354"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="confirmDialogFormActivity1" Size="130; 41" Location="309; 416" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="confirmEventDrivenActivity_Finish" Size="150; 182" Location="299; 378"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="309; 440" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="309; 500" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="confirmEventDrivenActivity_Cancel" Size="150; 182" Location="299; 402"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="309; 464" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="309; 524" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="590; 493" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 182" Location="522; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity_Finalize" Size="130; 41" Location="532; 210" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="532; 270" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="DeletePageTypeMetaDataFieldWorkflow" TargetConnectionIndex="0" SourceStateName="DeletePageTypeMetaDataFieldWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity2" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="791" Y="534" /> <ns0:Point X="1058" Y="534" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity3" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="confirmEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="504" Y="388" /> <ns0:Point X="692" Y="388" /> <ns0:Point X="692" Y="493" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="confirmStateActivity" SetStateName="setStateActivity4" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="confirmStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="401" Y="179" /> <ns0:Point X="401" Y="323" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity5" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="confirmEventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="508" Y="412" /> <ns0:Point X="1058" Y="412" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/DeletePageTypeWorkflow.cs ================================================ using System; using System.Linq; using System.Workflow.Activities; using Composite.Data.Types; using Composite.C1Console.Workflow; using Composite.Data; using Composite.Core.ResourceSystem; using Composite.C1Console.Actions; using Composite.Core.Linq; using System.Collections.Generic; namespace Composite.Plugins.Elements.ElementProviders.PageTypeElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeletePageTypeWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeletePageTypeWorkflow() { InitializeComponent(); } private void IsPageReferingPageType(object sender, ConditionalEventArgs e) { IPageType pageType = (IPageType)((DataEntityToken)this.EntityToken).Data; e.Result = DataFacade.GetData<IPage>().Where(f => f.PageTypeId == pageType.Id).Any(); } private void confirmCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { IPageType pageType = (IPageType)((DataEntityToken)this.EntityToken).Data; this.Bindings.Add("MessageText", string.Format(StringResourceSystemFacade.GetString("Composite.Plugins.PageTypeElementProvider", "PageType.DeletePageTypeWorkflow.Confirm.Layout.Messeage"), pageType.Name)); } private void showPageReferingCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { IPageType pageType = (IPageType)((DataEntityToken)this.EntityToken).Data; this.Bindings.Add("MessageText", string.Format(StringResourceSystemFacade.GetString("Composite.Plugins.PageTypeElementProvider", "PageType.DeletePageTypeWorkflow.PagesRefering.Layout.Message"), pageType.Name)); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { IPageType pageType = (IPageType)((DataEntityToken)this.EntityToken).Data; DeleteTreeRefresher deleteTreeRefresher = this.CreateDeleteTreeRefresher(this.EntityToken); IEnumerable<IPageTypeMetaDataTypeLink> pageTypeMetaDataTypeLinks = DataFacade.GetData<IPageTypeMetaDataTypeLink>(). Where(f => f.PageTypeId == pageType.Id). Evaluate(); foreach (IPageTypeMetaDataTypeLink pageTypeMetaDataTypeLink in pageTypeMetaDataTypeLinks) { PageMetaDataFacade.RemoveDefinition(pageType.Id, pageTypeMetaDataTypeLink.Name); } DataFacade.Delete<IPageType>(pageType); deleteTreeRefresher.PostRefreshMesseges(); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/DeletePageTypeWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTypeElementProvider { partial class DeletePageTypeWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmConfirmDialogFormActivity = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.confirmCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.showPageReferingConfirmDialogFormActivity = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.showPageReferingCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.initializeIfElseActivity_IsPageReferingPageType = new System.Workflow.Activities.IfElseActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.confirmEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.confirmEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.confirmStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.showPageReferingEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.showPageReferingStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.confirmStateActivity = new System.Workflow.Activities.StateActivity(); this.showPageReferingStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "confirmStateActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "showPageReferingStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity3); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity2); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsPageReferingPageType); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // confirmConfirmDialogFormActivity // this.confirmConfirmDialogFormActivity.ContainerLabel = null; this.confirmConfirmDialogFormActivity.FormDefinitionFileName = "\\Administrative\\PageTypeDeletePageTypeConfirm.xml"; this.confirmConfirmDialogFormActivity.Name = "confirmConfirmDialogFormActivity"; // // confirmCodeActivity_Initialize // this.confirmCodeActivity_Initialize.Name = "confirmCodeActivity_Initialize"; this.confirmCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.confirmCodeActivity_Initialize_ExecuteCode); // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // showPageReferingConfirmDialogFormActivity // this.showPageReferingConfirmDialogFormActivity.ContainerLabel = null; this.showPageReferingConfirmDialogFormActivity.FormDefinitionFileName = "/Administrative/PageTypeDeletePageTypePagesRefering.xml"; this.showPageReferingConfirmDialogFormActivity.Name = "showPageReferingConfirmDialogFormActivity"; // // showPageReferingCodeActivity_Initialize // this.showPageReferingCodeActivity_Initialize.Name = "showPageReferingCodeActivity_Initialize"; this.showPageReferingCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.showPageReferingCodeActivity_Initialize_ExecuteCode); // // initializeIfElseActivity_IsPageReferingPageType // this.initializeIfElseActivity_IsPageReferingPageType.Activities.Add(this.ifElseBranchActivity1); this.initializeIfElseActivity_IsPageReferingPageType.Activities.Add(this.ifElseBranchActivity2); this.initializeIfElseActivity_IsPageReferingPageType.Name = "initializeIfElseActivity_IsPageReferingPageType"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity6); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // confirmEventDrivenActivity_Cancel // this.confirmEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.confirmEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity4); this.confirmEventDrivenActivity_Cancel.Name = "confirmEventDrivenActivity_Cancel"; // // confirmEventDrivenActivity_Finish // this.confirmEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.confirmEventDrivenActivity_Finish.Activities.Add(this.setStateActivity5); this.confirmEventDrivenActivity_Finish.Name = "confirmEventDrivenActivity_Finish"; // // confirmStateInitializationActivity // this.confirmStateInitializationActivity.Activities.Add(this.confirmCodeActivity_Initialize); this.confirmStateInitializationActivity.Activities.Add(this.confirmConfirmDialogFormActivity); this.confirmStateInitializationActivity.Name = "confirmStateInitializationActivity"; // // showPageReferingEventDrivenActivity_Finish // this.showPageReferingEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.showPageReferingEventDrivenActivity_Finish.Activities.Add(this.setStateActivity7); this.showPageReferingEventDrivenActivity_Finish.Name = "showPageReferingEventDrivenActivity_Finish"; // // showPageReferingStateInitializationActivity // this.showPageReferingStateInitializationActivity.Activities.Add(this.showPageReferingCodeActivity_Initialize); this.showPageReferingStateInitializationActivity.Activities.Add(this.showPageReferingConfirmDialogFormActivity); this.showPageReferingStateInitializationActivity.Name = "showPageReferingStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeIfElseActivity_IsPageReferingPageType); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // confirmStateActivity // this.confirmStateActivity.Activities.Add(this.confirmStateInitializationActivity); this.confirmStateActivity.Activities.Add(this.confirmEventDrivenActivity_Finish); this.confirmStateActivity.Activities.Add(this.confirmEventDrivenActivity_Cancel); this.confirmStateActivity.Name = "confirmStateActivity"; // // showPageReferingStateActivity // this.showPageReferingStateActivity.Activities.Add(this.showPageReferingStateInitializationActivity); this.showPageReferingStateActivity.Activities.Add(this.showPageReferingEventDrivenActivity_Finish); this.showPageReferingStateActivity.Name = "showPageReferingStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // DeletePageTypeWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.showPageReferingStateActivity); this.Activities.Add(this.confirmStateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "DeletePageTypeWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity initializeIfElseActivity_IsPageReferingPageType; private StateActivity confirmStateActivity; private StateActivity showPageReferingStateActivity; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity6; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity7; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity confirmEventDrivenActivity_Cancel; private EventDrivenActivity confirmEventDrivenActivity_Finish; private StateInitializationActivity confirmStateInitializationActivity; private EventDrivenActivity showPageReferingEventDrivenActivity_Finish; private StateInitializationActivity showPageReferingStateInitializationActivity; private StateActivity finalizeStateActivity; private C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmConfirmDialogFormActivity; private CodeActivity confirmCodeActivity_Initialize; private C1Console.Workflow.Activities.ConfirmDialogFormActivity showPageReferingConfirmDialogFormActivity; private CodeActivity showPageReferingCodeActivity_Initialize; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private CodeActivity finalizeCodeActivity_Finalize; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/DeletePageTypeWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1146; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="DeletePageTypeWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="381; 303" Location="98; 169"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="initializeIfElseActivity_IsPageReferingPageType" Size="361; 222" Location="108; 231"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 122" Location="127; 302"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="137; 364" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 122" Location="300; 302"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="310; 364" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="272; 80" AutoSizeMargin="16; 24" Location="187; 383" Name="showPageReferingStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="showPageReferingStateInitializationActivity" Size="150; 182" Location="195; 414"> <StateInitializationDesigner.Designers> <CodeDesigner Name="showPageReferingCodeActivity_Initialize" Size="130; 41" Location="205; 476" /> <ActivityDesigner Name="showPageReferingConfirmDialogFormActivity" Size="130; 41" Location="205; 536" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="showPageReferingEventDrivenActivity_Finish" Size="150; 182" Location="195; 438"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 41" Location="205; 500" /> <SetStateDesigner Name="setStateActivity7" Size="130; 41" Location="205; 560" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="221; 102" AutoSizeMargin="16; 24" Location="499; 382" Name="confirmStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="confirmStateInitializationActivity" Size="150; 182" Location="507; 413"> <StateInitializationDesigner.Designers> <CodeDesigner Name="confirmCodeActivity_Initialize" Size="130; 41" Location="517; 475" /> <ActivityDesigner Name="confirmConfirmDialogFormActivity" Size="130; 41" Location="517; 535" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="confirmEventDrivenActivity_Finish" Size="150; 182" Location="507; 437"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity2" Size="130; 41" Location="517; 499" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="517; 559" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="confirmEventDrivenActivity_Cancel" Size="150; 182" Location="507; 461"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 41" Location="517; 523" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="517; 583" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="205; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="796; 571" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="150; 182" Location="522; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Name="finalizeCodeActivity_Finalize" Size="130; 41" Location="532; 210" /> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="532; 270" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="DeletePageTypeWorkflow" TargetConnectionIndex="0" SourceStateName="DeletePageTypeWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="showPageReferingStateActivity" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="showPageReferingStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="323" Y="179" /> <ns0:Point X="323" Y="383" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="confirmStateActivity" SetStateName="setStateActivity3" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="confirmStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="609" Y="179" /> <ns0:Point X="609" Y="382" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity7" SourceActivity="showPageReferingStateActivity" TargetConnectionIndex="0" SourceStateName="showPageReferingStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="showPageReferingEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="455" Y="448" /> <ns0:Point X="471" Y="448" /> <ns0:Point X="471" Y="786" /> <ns0:Point X="1058" Y="786" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" SetStateName="setStateActivity5" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="confirmEventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="712" Y="447" /> <ns0:Point X="898" Y="447" /> <ns0:Point X="898" Y="571" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity4" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="confirmEventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="716" Y="471" /> <ns0:Point X="1058" Y="471" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity6" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="997" Y="612" /> <ns0:Point X="1058" Y="612" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/EditPageTypeDefaultPageContentWorkflow.cs ================================================ using System; using System.Linq; using Composite.Data.Types; using Composite.Data; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTypeElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditPageTypeDefaultPageContentWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditPageTypeDefaultPageContentWorkflow() { InitializeComponent(); } private void initializeCodeActivity_UpdateBindings_ExecuteCode(object sender, EventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; this.Bindings.Add("DefaultPageContent", dataEntityToken.Data); } private void saveCodeActivity_Save_ExecuteCode(object sender, EventArgs e) { IPageTypeDefaultPageContent defaultPageContent = this.GetBinding<IPageTypeDefaultPageContent>("DefaultPageContent"); DataFacade.Update(defaultPageContent); this.SetSaveStatus(true); this.CreateParentTreeRefresher().PostRefreshMesseges(this.EntityToken); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/EditPageTypeDefaultPageContentWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTypeElementProvider { partial class EditPageTypeDefaultPageContentWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity_Save = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_UpdateBindings = new System.Workflow.Activities.CodeActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editEventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // saveCodeActivity_Save // this.saveCodeActivity_Save.Name = "saveCodeActivity_Save"; this.saveCodeActivity_Save.ExecuteCode += new System.EventHandler(this.saveCodeActivity_Save_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "saveStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.CustomToolbarDefinitionFileName = null; this.documentFormActivity1.FormDefinitionFileName = "\\Administrative\\PageTypeEditPageTypeDefaultPageContent.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // initializeCodeActivity_UpdateBindings // this.initializeCodeActivity_UpdateBindings.Name = "initializeCodeActivity_UpdateBindings"; this.initializeCodeActivity_UpdateBindings.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_UpdateBindings_ExecuteCode); // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.saveCodeActivity_Save); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity4); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // editEventDrivenActivity_Save // this.editEventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.editEventDrivenActivity_Save.Activities.Add(this.setStateActivity3); this.editEventDrivenActivity_Save.Name = "editEventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_UpdateBindings); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.saveStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_Save); this.editStateActivity.Name = "editStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // EditPageTypeDefaultPageContentWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "EditPageTypeDefaultPageContentWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private SetStateActivity setStateActivity2; private StateInitializationActivity saveStateInitializationActivity; private EventDrivenActivity editEventDrivenActivity_Save; private StateInitializationActivity editStateInitializationActivity; private StateActivity saveStateActivity; private StateActivity editStateActivity; private CodeActivity initializeCodeActivity_UpdateBindings; private CodeActivity saveCodeActivity_Save; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/EditPageTypeDefaultPageContentWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1241; 878" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="EditPageTypeDefaultPageContentWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="EditPageTypeDefaultPageContentWorkflow" TargetConnectionIndex="0" SourceStateName="EditPageTypeDefaultPageContentWorkflow" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="74" /> <ns0:Point X="1058" Y="74" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="313" Y="182" /> <ns0:Point X="418" Y="182" /> <ns0:Point X="418" Y="385" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" SourceConnectionEdge="Right" EventHandlerName="editEventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="517" Y="455" /> <ns0:Point X="533" Y="455" /> <ns0:Point X="533" Y="374" /> <ns0:Point X="740" Y="374" /> <ns0:Point X="740" Y="382" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="saveStateActivity" TargetConnectionIndex="0" SourceStateName="saveStateActivity" SourceConnectionEdge="Right" EventHandlerName="saveStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="839" Y="426" /> <ns0:Point X="850" Y="426" /> <ns0:Point X="850" Y="377" /> <ns0:Point X="418" Y="377" /> <ns0:Point X="418" Y="385" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 209" Location="38; 63"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 44" Location="48; 128" /> <SetStateDesigner Name="setStateActivity1" Size="130; 62" Location="48; 191" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="227; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 209" Location="98; 171"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_UpdateBindings" Size="130; 44" Location="108; 236" /> <SetStateDesigner Name="setStateActivity2" Size="130; 62" Location="108; 299" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="205; 84" AutoSizeMargin="16; 24" AutoSize="False" Location="316; 385" Name="editStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="editStateInitializationActivity" Size="150; 128" Location="575; 154"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="documentFormActivity1" Size="130; 44" Location="585; 219" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="editEventDrivenActivity_Save" Size="150; 209" Location="567; 167"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130; 44" Location="577; 232" /> <SetStateDesigner Name="setStateActivity3" Size="130; 62" Location="577; 295" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="206; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="637; 382" Name="saveStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="saveStateInitializationActivity" Size="150; 209" Location="645; 415"> <StateInitializationDesigner.Designers> <CodeDesigner Name="saveCodeActivity_Save" Size="130; 44" Location="655; 480" /> <SetStateDesigner Name="setStateActivity4" Size="130; 62" Location="655; 543" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/EditPageTypeMetaDataFieldWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.Types; using Composite.Core.ResourceSystem; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTypeElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditPageTypeMetaDataFieldWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditPageTypeMetaDataFieldWorkflow() { InitializeComponent(); } private void ValidateTypeExistence(object sender, ConditionalEventArgs e) { e.Result = true; IPageTypeMetaDataTypeLink pageTypeMetaDataTypeLink = this.GetDataItemFromEntityToken<IPageTypeMetaDataTypeLink>(); DataTypeDescriptor dataTypeDescriptor; if (!DynamicTypeManager.TryGetDataTypeDescriptor(pageTypeMetaDataTypeLink.DataTypeId, out dataTypeDescriptor)) { e.Result = false; DeleteTreeRefresher deleteTreeRefresher = CreateDeleteTreeRefresher(this.EntityToken); DataFacade.Delete<IPageTypeMetaDataTypeLink>(pageTypeMetaDataTypeLink); this.ShowMessage( DialogType.Warning, GetText("PageType.EditPageTypeMetaDataFieldWorkflow.ValidationError.MetaDataTypeNotExisting.Title"), GetText("PageType.EditPageTypeMetaDataFieldWorkflow.ValidationError.MetaDataTypeNotExisting.Message")); deleteTreeRefresher.PostRefreshMesseges(); } } private void initializeCodeActivity_UpdateBindings_ExecuteCode(object sender, EventArgs e) { IPageTypeMetaDataTypeLink pageTypeMetaDataTypeLink = this.GetDataItemFromEntityToken<IPageTypeMetaDataTypeLink>(); IPageMetaDataDefinition pageMetaDataDefinition = PageMetaDataFacade.GetMetaDataDefinition(pageTypeMetaDataTypeLink.PageTypeId, pageTypeMetaDataTypeLink.Name); //this.UpdateBinding("CompositionDescriptionName", compositionDescription.Name); this.UpdateBinding("CompositionDescriptionLabel", pageMetaDataDefinition.Label); List<KeyValuePair<Guid, string>> metaDataContainerOptions = PageMetaDataFacade.GetAllMetaDataContainers(); this.Bindings.Add("MetaDataContainerOptions", metaDataContainerOptions); this.Bindings.Add("CompositionContainerId", pageMetaDataDefinition.MetaDataContainerId); var dataTypeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(pageTypeMetaDataTypeLink.DataTypeId); this.Bindings.Add("MetaTypeName", dataTypeDescriptor.TypeManagerTypeName); } private void ValidateBindings(object sender, ConditionalEventArgs e) { IPageTypeMetaDataTypeLink pageTypeMetaDataTypeLink = this.GetDataItemFromEntityToken<IPageTypeMetaDataTypeLink>(); IPageMetaDataDefinition pageMetaDataDefinition = PageMetaDataFacade.GetMetaDataDefinition(pageTypeMetaDataTypeLink.PageTypeId, pageTypeMetaDataTypeLink.Name); string metaDataDescriptionLabel = this.GetBinding<string>("CompositionDescriptionLabel"); Guid containerId = this.GetBinding<Guid>("CompositionContainerId"); e.Result = true; if (pageMetaDataDefinition.Label != metaDataDescriptionLabel) { if (PageMetaDataFacade.IsDefinitionAllowed(pageTypeMetaDataTypeLink.PageTypeId, pageMetaDataDefinition.Name, metaDataDescriptionLabel, pageMetaDataDefinition.MetaDataTypeId) == false) { this.ShowFieldMessage("CompositionDescriptionLabel", GetText("PageType.EditPageTypeMetaDataFieldWorkflow.ValidationError.MetaDataFieldNameAlreadyUsed")); SetSaveStatus(false); e.Result = false; } } if (pageMetaDataDefinition.MetaDataContainerId != containerId) { if (PageMetaDataFacade.IsNewContainerIdAllowed(pageTypeMetaDataTypeLink.PageTypeId, pageMetaDataDefinition.Name, containerId) == false) { this.ShowFieldMessage("CompositionContainerId", GetText("PageType.EditPageTypeMetaDataFieldWorkflow.ValidationError.MetaDataContainerChangeNotAllowed")); SetSaveStatus(false); e.Result = false; } } } private void saveCodeActivity_Save_ExecuteCode(object sender, EventArgs e) { IPageTypeMetaDataTypeLink pageTypeMetaDataTypeLink = this.GetDataItemFromEntityToken<IPageTypeMetaDataTypeLink>(); string metaDataDescriptionLabel = this.GetBinding<string>("CompositionDescriptionLabel"); Guid containerId = this.GetBinding<Guid>("CompositionContainerId"); PageMetaDataFacade.UpdateDefinition(pageTypeMetaDataTypeLink.PageTypeId, pageTypeMetaDataTypeLink.Name, metaDataDescriptionLabel, containerId); SetSaveStatus(true); this.RefreshCurrentEntityToken(); } string GetText(string key) { return StringResourceSystemFacade.GetString("Composite.Plugins.PageTypeElementProvider", key); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/EditPageTypeMetaDataFieldWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTypeElementProvider { partial class EditPageTypeMetaDataFieldWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_UpdateBindings = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity_Save = new System.Workflow.Activities.CodeActivity(); this.editIfElseActivity_ValidateBindings = new System.Workflow.Activities.IfElseActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.editDocumentFormActivity = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.initializeIfElseActivity_ValidateTypeExistence = new System.Workflow.Activities.IfElseActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editEventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "editStateActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "saveStateActivity"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // initializeCodeActivity_UpdateBindings // this.initializeCodeActivity_UpdateBindings.Name = "initializeCodeActivity_UpdateBindings"; this.initializeCodeActivity_UpdateBindings.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_UpdateBindings_ExecuteCode); // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity6); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity2); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateBindings); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity5); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.initializeCodeActivity_UpdateBindings); this.ifElseBranchActivity3.Activities.Add(this.setStateActivity4); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateTypeExistence); this.ifElseBranchActivity3.Condition = codecondition2; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "editStateActivity"; // // saveCodeActivity_Save // this.saveCodeActivity_Save.Name = "saveCodeActivity_Save"; this.saveCodeActivity_Save.ExecuteCode += new System.EventHandler(this.saveCodeActivity_Save_ExecuteCode); // // editIfElseActivity_ValidateBindings // this.editIfElseActivity_ValidateBindings.Activities.Add(this.ifElseBranchActivity1); this.editIfElseActivity_ValidateBindings.Activities.Add(this.ifElseBranchActivity2); this.editIfElseActivity_ValidateBindings.Name = "editIfElseActivity_ValidateBindings"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // editDocumentFormActivity // this.editDocumentFormActivity.ContainerLabel = null; this.editDocumentFormActivity.CustomToolbarDefinitionFileName = null; this.editDocumentFormActivity.FormDefinitionFileName = "/Administrative/PageTypeEditPageTypeMetaDataField.xml"; this.editDocumentFormActivity.Name = "editDocumentFormActivity"; // // initializeIfElseActivity_ValidateTypeExistence // this.initializeIfElseActivity_ValidateTypeExistence.Activities.Add(this.ifElseBranchActivity3); this.initializeIfElseActivity_ValidateTypeExistence.Activities.Add(this.ifElseBranchActivity4); this.initializeIfElseActivity_ValidateTypeExistence.Name = "initializeIfElseActivity_ValidateTypeExistence"; // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.saveCodeActivity_Save); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity3); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // editEventDrivenActivity_Save // this.editEventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.editEventDrivenActivity_Save.Activities.Add(this.editIfElseActivity_ValidateBindings); this.editEventDrivenActivity_Save.Name = "editEventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.editDocumentFormActivity); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeIfElseActivity_ValidateTypeExistence); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.saveStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_Save); this.editStateActivity.Name = "editStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // EditPageTypeMetaDataFieldWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "EditPageTypeMetaDataFieldWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private C1Console.Workflow.Activities.DocumentFormActivity editDocumentFormActivity; private SetStateActivity setStateActivity4; private CodeActivity initializeCodeActivity_UpdateBindings; private StateInitializationActivity saveStateInitializationActivity; private EventDrivenActivity editEventDrivenActivity_Save; private StateInitializationActivity editStateInitializationActivity; private StateActivity saveStateActivity; private StateActivity editStateActivity; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity editIfElseActivity_ValidateBindings; private SetStateActivity setStateActivity6; private CodeActivity saveCodeActivity_Save; private SetStateActivity setStateActivity5; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity initializeIfElseActivity_ValidateTypeExistence; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/EditPageTypeMetaDataFieldWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1190; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="EditPageTypeMetaDataFieldWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="381; 363" Location="434; 148"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="initializeIfElseActivity_ValidateTypeExistence" Size="361; 282" Location="444; 210"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity3" Size="150; 182" Location="463; 281"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_UpdateBindings" Size="130; 41" Location="473; 343" /> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="473; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity4" Size="150; 182" Location="636; 281"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="646; 373" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="202; 102" AutoSizeMargin="16; 24" AutoSize="False" Location="310; 397" Name="editStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="editStateInitializationActivity" Size="150; 122" Location="318; 428"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="editDocumentFormActivity" Size="130; 41" Location="328; 490" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="editEventDrivenActivity_Save" Size="381; 363" Location="318; 452"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130; 41" Location="443; 514" /> <IfElseDesigner Name="editIfElseActivity_ValidateBindings" Size="361; 222" Location="328; 574"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 122" Location="347; 645"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="357; 707" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 122" Location="520; 645"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity6" Size="130; 41" Location="530; 707" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="193; 80" AutoSizeMargin="16; 24" Location="624; 400" Name="saveStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="saveStateInitializationActivity" Size="150; 182" Location="632; 431"> <StateInitializationDesigner.Designers> <CodeDesigner Name="saveCodeActivity_Save" Size="130; 41" Location="642; 493" /> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="642; 553" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="EditPageTypeMetaDataFieldWorkflow" TargetConnectionIndex="0" SourceStateName="EditPageTypeMetaDataFieldWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity4" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="411" Y="179" /> <ns0:Point X="411" Y="397" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity5" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="1058" Y="179" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" SetStateName="setStateActivity2" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editEventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="499" Y="462" /> <ns0:Point X="546" Y="462" /> <ns0:Point X="546" Y="392" /> <ns0:Point X="720" Y="392" /> <ns0:Point X="720" Y="400" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity6" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editEventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="499" Y="462" /> <ns0:Point X="523" Y="462" /> <ns0:Point X="523" Y="389" /> <ns0:Point X="411" Y="389" /> <ns0:Point X="411" Y="397" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity3" SourceActivity="saveStateActivity" TargetConnectionIndex="0" SourceStateName="saveStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="saveStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="813" Y="441" /> <ns0:Point X="827" Y="441" /> <ns0:Point X="827" Y="321" /> <ns0:Point X="411" Y="321" /> <ns0:Point X="411" Y="397" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/EditPageTypeWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Workflow.Activities; using Composite.Core.PageTemplates; using Composite.Data; using Composite.Data.Types; using Composite.Core.Linq; using Composite.Core.ResourceSystem; using Composite.Data.Transactions; using Composite.C1Console.Trees; using Composite.C1Console.Workflow; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Plugins_PageTypeElementProvider; namespace Composite.Plugins.Elements.ElementProviders.PageTypeElementProvider { [EntityTokenLock] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditPageTypeWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditPageTypeWorkflow() { InitializeComponent(); } private void CleanDeadLinks(Guid pageTypeId) { DataFacade.GetData<IPageTypeMetaDataTypeLink>() .Where(f => f.PageTypeId == pageTypeId) .Evaluate() .RemoveDeadLinks(); DataFacade.GetData<IPageTypeDataFolderTypeLink>() .Where(f => f.PageTypeId == pageTypeId) .Evaluate() .RemoveDeadLinks(); DataFacade.GetData<IPageTypeTreeLink>() .Where(f => f.PageTypeId == pageTypeId) .Evaluate() .RemoveDeadLinks(); } private void initializeCodeActivity_UpdateBindings_ExecuteCode(object sender, EventArgs e) { IPageType pageType = (IPageType)((DataEntityToken)this.EntityToken).Data; CleanDeadLinks(pageType.Id); this.Bindings.Add("PageType", pageType); List<KeyValuePair<Guid, string>> pageTypes = DataFacade.GetData<IPageType>(). OrderBy(f => f.Name). ToList(f => new KeyValuePair<Guid, string>(f.Id, f.Name)); var defaultPageTypeOptions = new List<KeyValuePair<Guid, string>> { new KeyValuePair<Guid, string>(Guid.Empty, Texts.PageType_EditPageTypeWorkflow_DefaultChildPageTypeKeySelector_NoneSelectedLabel) }; defaultPageTypeOptions.AddRange(pageTypes); this.Bindings.Add("DefaultChildPageTypeOptions", defaultPageTypeOptions); Func<PageTypeHomepageRelation, KeyValuePair<string, string> > getOption = relation => new KeyValuePair<string, string>( relation.ToString(), GetText($"PageType.EditPageTypeWorkflow.HomepageRelationKeySelector.{relation}Label")); this.Bindings.Add("HomepageRelationOptions", new List<KeyValuePair<string, string>> { getOption(PageTypeHomepageRelation.NoRestriction), getOption(PageTypeHomepageRelation.OnlyHomePages), getOption(PageTypeHomepageRelation.OnlySubPages), }); List<KeyValuePair<Guid, string>> pageTemplates = PageTemplateFacade.GetPageTemplates(). OrderBy(f => f.Title). ToList(f => new KeyValuePair<Guid, string>(f.Id, f.Title)); var defaultPageTemplateOptions = new List<KeyValuePair<Guid, string>> { new KeyValuePair<Guid, string>(Guid.Empty, Texts.PageType_EditPageTypeWorkflow_DefaultPageTemplateKeySelector_NoneSelectedLabel) }; defaultPageTemplateOptions.AddRange(pageTemplates); this.Bindings.Add("DefaultTemplateOptions", defaultPageTemplateOptions); this.Bindings.Add("TemplateRestrictionOptions", pageTemplates); List<Guid> selectedPageTemplateIds = DataFacade.GetData<IPageTypePageTemplateRestriction>(). Where(f => f.PageTypeId == pageType.Id). Select(f => f.PageTemplateId). ToList(); this.Bindings.Add("TemplateRestrictionSelected", selectedPageTemplateIds); List<KeyValuePair<Guid, string>> parentRestrictingPageTypes = DataFacade.GetData<IPageType>(). OrderBy(f => f.Name). ToList(f => new KeyValuePair<Guid, string>(f.Id, f.Name)); this.Bindings.Add("PageTypeChildRestrictionOptions", parentRestrictingPageTypes); List<Guid> selectedPageTypeParentRestrictions = DataFacade.GetData<IPageTypeParentRestriction>(). Where(f => f.PageTypeId == pageType.Id). Select(f => f.AllowedParentPageTypeId). ToList(); this.Bindings.Add("PageTypeChildRestrictionSelected", selectedPageTypeParentRestrictions); List<KeyValuePair<Guid, string>> dataFolderTypes = PageFolderFacade.GetAllFolderTypes(). OrderBy(f => f.FullName). ToList(f => new KeyValuePair<Guid, string>(f.GetImmutableTypeId(), f.GetTypeTitle())); this.Bindings.Add("DataFolderOptions", dataFolderTypes); List<Guid> selectedDataFolderTypes = DataFacade.GetData<IPageTypeDataFolderTypeLink>(). Where(f => f.PageTypeId == pageType.Id). Select(f => f.DataTypeId). ToList(); this.Bindings.Add("DataFolderSelected", selectedDataFolderTypes); List<KeyValuePair<string, string>> applications = TreeFacade.AllTrees. Where(f => !string.IsNullOrEmpty(f.AllowedAttachmentApplicationName)). OrderBy(f => f.TreeId). ToList(f => new KeyValuePair<string, string>(f.TreeId, f.AllowedAttachmentApplicationName)); this.Bindings.Add("ApplicationOptions", applications); List<string> selectedApplications = DataFacade.GetData<IPageTypeTreeLink>(). Where(f => f.PageTypeId == pageType.Id). Select(f => f.TreeId). ToList(); this.Bindings.Add("ApplicationSelected", selectedApplications); } private void editCodeActivity_ValidateBindings(object sender, ConditionalEventArgs e) { IPageType pageType = (IPageType)((DataEntityToken)this.EntityToken).Data; List<Guid> selectedPageTemplateIds = this.GetBinding<List<Guid>>("TemplateRestrictionSelected"); List<Guid> selectedPageTypeParentRestrictions = this.GetBinding<List<Guid>>("PageTypeChildRestrictionSelected"); if (pageType.DefaultTemplateId != Guid.Empty && selectedPageTemplateIds.Count > 0 && !selectedPageTemplateIds.Contains(pageType.DefaultTemplateId)) { this.ShowFieldMessage("DefaultTemplateSelected", Texts.PageType_EditPageTypeWorkflow_ValidationError_DefaultTemplateNotInRestrictions); SetSaveStatus(false); e.Result = false; return; } if (pageType.HomepageRelation == nameof(PageTypeHomepageRelation.OnlyHomePages) && selectedPageTypeParentRestrictions.Count > 0) { this.ShowFieldMessage("PageType.HomepageRelation", Texts.PageType_EditPageTypeWorkflow_ValidationError_HomepageRelationConflictsWithParentRestrictions); SetSaveStatus(false); e.Result = false; return; } e.Result = true; } private void saveCodeActivity_Save_ExecuteCode(object sender, EventArgs e) { using (var transactionScope = TransactionsFacade.CreateNewScope()) { var args = new ConditionalEventArgs(); editCodeActivity_ValidateBindings(this, args); if (!args.Result) return; IPageType pageType = this.GetBinding<IPageType>("PageType"); UpdatePageTemplateResctrictions(pageType); UpdatePageTypeParentResctrictions(pageType); UpdatePageTypeDataFolderTypeLinks(pageType); UpdatePageTypeTreeLinks(pageType); DataFacade.Update(pageType); transactionScope.Complete(); } this.RefreshParentEntityToken(); SetSaveStatus(true); } private void UpdatePageTemplateResctrictions(IPageType pageType) { List<Guid> selectedPageTemplateIds = this.GetBinding<List<Guid>>("TemplateRestrictionSelected"); var pageTypePageTemplateRestrictions = DataFacade.GetData<IPageTypePageTemplateRestriction>() .Where(f => f.PageTypeId == pageType.Id).Evaluate(); // Remove deselected foreach (IPageTypePageTemplateRestriction restriction in pageTypePageTemplateRestrictions) { if (!selectedPageTemplateIds.Contains(restriction.PageTemplateId)) { DataFacade.Delete(restriction); } } // Add newly selected foreach (Guid templateId in selectedPageTemplateIds) { if (!pageTypePageTemplateRestrictions.Any(f => f.PageTemplateId == templateId)) { var pageTypePageTemplateRestriction = DataFacade.BuildNew<IPageTypePageTemplateRestriction>(); pageTypePageTemplateRestriction.Id = Guid.NewGuid(); pageTypePageTemplateRestriction.PageTypeId = pageType.Id; pageTypePageTemplateRestriction.PageTemplateId = templateId; DataFacade.AddNew(pageTypePageTemplateRestriction); } } } private void UpdatePageTypeParentResctrictions(IPageType pageType) { List<Guid> selectedPageTypeParentRestrictions = this.GetBinding<List<Guid>>("PageTypeChildRestrictionSelected"); var pageTypeParentRestrictions = DataFacade.GetData<IPageTypeParentRestriction>() .Where(f => f.PageTypeId == pageType.Id).Evaluate(); // Remove deselected foreach (IPageTypeParentRestriction restriction in pageTypeParentRestrictions) { if (!selectedPageTypeParentRestrictions.Contains(restriction.AllowedParentPageTypeId)) { DataFacade.Delete(restriction); } } // Add newly selected foreach (Guid templateId in selectedPageTypeParentRestrictions) { if (!pageTypeParentRestrictions.Any(f => f.AllowedParentPageTypeId == templateId)) { var pageTypeParentRestriction = DataFacade.BuildNew<IPageTypeParentRestriction>(); pageTypeParentRestriction.Id = Guid.NewGuid(); pageTypeParentRestriction.PageTypeId = pageType.Id; pageTypeParentRestriction.AllowedParentPageTypeId = templateId; DataFacade.AddNew(pageTypeParentRestriction); } } } private void UpdatePageTypeDataFolderTypeLinks(IPageType pageType) { List<Guid> selectedDataFolderTypeIds = this.GetBinding<List<Guid>>("DataFolderSelected"); var pageTypeDateFolderTypeLinks = DataFacade.GetData<IPageTypeDataFolderTypeLink>() .Where(f => f.PageTypeId == pageType.Id).Evaluate(); // Remove deselected foreach (IPageTypeDataFolderTypeLink dataFolderTypeLink in pageTypeDateFolderTypeLinks) { if (!selectedDataFolderTypeIds.Contains(dataFolderTypeLink.DataTypeId)) { DataFacade.Delete(dataFolderTypeLink); } } // Add newly selected foreach (Guid dataFolderTypeId in selectedDataFolderTypeIds) { if (!pageTypeDateFolderTypeLinks.Any(f => f.DataTypeId == dataFolderTypeId)) { IPageTypeDataFolderTypeLink pageTypeDateFolderTypeLink = DataFacade.BuildNew<IPageTypeDataFolderTypeLink>(); pageTypeDateFolderTypeLink.Id = Guid.NewGuid(); pageTypeDateFolderTypeLink.PageTypeId = pageType.Id; pageTypeDateFolderTypeLink.DataTypeId = dataFolderTypeId; DataFacade.AddNew(pageTypeDateFolderTypeLink); } } } private void UpdatePageTypeTreeLinks(IPageType pageType) { List<string> selectedTreeIds = this.GetBinding<List<string>>("ApplicationSelected"); var pageTypeTreeLinks = DataFacade.GetData<IPageTypeTreeLink>() .Where(f => f.PageTypeId == pageType.Id).Evaluate(); // Remove deselected foreach (IPageTypeTreeLink treeLink in pageTypeTreeLinks) { if (!selectedTreeIds.Contains(treeLink.TreeId)) { DataFacade.Delete<IPageTypeTreeLink>(treeLink); } } // Add newly selected foreach (string treeId in selectedTreeIds) { if (!pageTypeTreeLinks.Any(f => f.TreeId == treeId)) { IPageTypeTreeLink pageTypeTreeLink = DataFacade.BuildNew<IPageTypeTreeLink>(); pageTypeTreeLink.Id = Guid.NewGuid(); pageTypeTreeLink.PageTypeId = pageType.Id; pageTypeTreeLink.TreeId = treeId; DataFacade.AddNew<IPageTypeTreeLink>(pageTypeTreeLink); } } } private static string GetText(string key) { return StringResourceSystemFacade.GetString("Composite.Plugins.PageTypeElementProvider", key); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/EditPageTypeWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.PageTypeElementProvider { partial class EditPageTypeWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity_Save = new System.Workflow.Activities.CodeActivity(); this.editIfElseActivity_ValidateBindings = new System.Workflow.Activities.IfElseActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.initializeDocumentFormActivity = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_UpdateBindings = new System.Workflow.Activities.CodeActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editEventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "saveStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity4); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity3); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.editCodeActivity_ValidateBindings); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "editStateActivity"; // // saveCodeActivity_Save // this.saveCodeActivity_Save.Name = "saveCodeActivity_Save"; this.saveCodeActivity_Save.ExecuteCode += new System.EventHandler(this.saveCodeActivity_Save_ExecuteCode); // // editIfElseActivity_ValidateBindings // this.editIfElseActivity_ValidateBindings.Activities.Add(this.ifElseBranchActivity1); this.editIfElseActivity_ValidateBindings.Activities.Add(this.ifElseBranchActivity2); this.editIfElseActivity_ValidateBindings.Name = "editIfElseActivity_ValidateBindings"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // initializeDocumentFormActivity // this.initializeDocumentFormActivity.ContainerLabel = null; this.initializeDocumentFormActivity.CustomToolbarDefinitionFileName = null; this.initializeDocumentFormActivity.FormDefinitionFileName = "\\Administrative\\PageTypeEditPageType.xml"; this.initializeDocumentFormActivity.Name = "initializeDocumentFormActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // initializeCodeActivity_UpdateBindings // this.initializeCodeActivity_UpdateBindings.Name = "initializeCodeActivity_UpdateBindings"; this.initializeCodeActivity_UpdateBindings.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_UpdateBindings_ExecuteCode); // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.saveCodeActivity_Save); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity5); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // editEventDrivenActivity_Save // this.editEventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.editEventDrivenActivity_Save.Activities.Add(this.editIfElseActivity_ValidateBindings); this.editEventDrivenActivity_Save.Name = "editEventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.initializeDocumentFormActivity); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_UpdateBindings); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.saveStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_Save); this.editStateActivity.Name = "editStateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // EditPageTypeWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "EditPageTypeWorkflow"; this.CanModifyActivities = false; } #endregion private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity2; private StateActivity editStateActivity; private C1Console.Workflow.Activities.DocumentFormActivity initializeDocumentFormActivity; private CodeActivity initializeCodeActivity_UpdateBindings; private StateInitializationActivity editStateInitializationActivity; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity editIfElseActivity_ValidateBindings; private C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private EventDrivenActivity editEventDrivenActivity_Save; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity5; private CodeActivity saveCodeActivity_Save; private StateInitializationActivity saveStateInitializationActivity; private StateActivity saveStateActivity; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/PageTypeElementProvider/EditPageTypeWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1207; 986" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="EditPageTypeWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150; 182" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 41" Location="48; 123" /> <SetStateDesigner Name="setStateActivity1" Size="130; 41" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="210; 80" AutoSizeMargin="16; 24" Location="90; 138" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="initializeStateInitializationActivity" Size="150; 182" Location="98; 169"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity_UpdateBindings" Size="130; 41" Location="108; 231" /> <SetStateDesigner Name="setStateActivity2" Size="130; 41" Location="108; 291" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175; 80" AutoSizeMargin="16; 24" Location="971; 798" Name="finalStateActivity" /> <StateDesigner Size="193; 80" AutoSizeMargin="16; 24" AutoSize="False" Location="289; 317" Name="editStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="editStateInitializationActivity" Size="150; 122" Location="435; 135"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="initializeDocumentFormActivity" Size="130; 41" Location="445; 197" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="editEventDrivenActivity_Save" Size="381; 363" Location="443; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="saveHandleExternalEventActivity1" Size="130; 41" Location="568; 210" /> <IfElseDesigner Name="editIfElseActivity_ValidateBindings" Size="361; 222" Location="453; 270"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 122" Location="472; 341"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130; 41" Location="482; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 122" Location="645; 341"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity4" Size="130; 41" Location="655; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="193; 80" AutoSizeMargin="16; 24" Location="568; 582" Name="saveStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="saveStateInitializationActivity" Size="150; 182" Location="576; 613"> <StateInitializationDesigner.Designers> <CodeDesigner Name="saveCodeActivity_Save" Size="130; 41" Location="586; 675" /> <SetStateDesigner Name="setStateActivity5" Size="130; 41" Location="586; 735" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" SetStateName="setStateActivity1" SourceActivity="EditPageTypeWorkflow" TargetConnectionIndex="0" SourceStateName="EditPageTypeWorkflow" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="initializeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="385" Y="179" /> <ns0:Point X="385" Y="317" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="saveStateActivity" SetStateName="setStateActivity3" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editEventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="saveStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="478" Y="382" /> <ns0:Point X="664" Y="382" /> <ns0:Point X="664" Y="582" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity4" SourceActivity="editStateActivity" TargetConnectionIndex="0" SourceStateName="editStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="editEventDrivenActivity_Save" SourceConnectionIndex="1" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="616" Y="169" /> <ns0:Point X="627" Y="169" /> <ns0:Point X="627" Y="96" /> <ns0:Point X="523" Y="96" /> <ns0:Point X="523" Y="104" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="editStateActivity" SetStateName="setStateActivity5" SourceActivity="saveStateActivity" TargetConnectionIndex="0" SourceStateName="saveStateActivity" TargetConnectionEdge="Top" SourceConnectionEdge="Right" EventHandlerName="saveStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="editStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="757" Y="623" /> <ns0:Point X="769" Y="623" /> <ns0:Point X="769" Y="309" /> <ns0:Point X="385" Y="309" /> <ns0:Point X="385" Y="317" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/RazorFunctionProviderElementProvider/AddNewRazorFunctionWorkflow.Designer.cs ================================================ using System.Workflow.Activities; namespace Composite.Plugins.Elements.ElementProviders.RazorFunctionProviderElementProvider { partial class AddNewRazorFunctionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.finalizecodeActivity = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.dialogFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.validateStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.stateInitializationActivity4 = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity2 = new System.Workflow.Activities.StateInitializationActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.validateStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "step1StateActivity"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity4); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity3); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsValidData); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // finalizecodeActivity // this.finalizecodeActivity.Name = "finalizecodeActivity"; this.finalizecodeActivity.ExecuteCode += new System.EventHandler(this.finalizecodeActivity_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "validateStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // dialogFormActivity1 // this.dialogFormActivity1.ContainerLabel = "Add new"; this.dialogFormActivity1.FormDefinitionFileName = "\\Administrative\\AddNewRazorFunction.xml"; this.dialogFormActivity1.Name = "dialogFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // validateStateInitializationActivity // this.validateStateInitializationActivity.Activities.Add(this.ifElseActivity1); this.validateStateInitializationActivity.Name = "validateStateInitializationActivity"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // stateInitializationActivity4 // this.stateInitializationActivity4.Activities.Add(this.closeCurrentViewActivity1); this.stateInitializationActivity4.Activities.Add(this.finalizecodeActivity); this.stateInitializationActivity4.Activities.Add(this.setStateActivity1); this.stateInitializationActivity4.Name = "stateInitializationActivity4"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity6); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity5); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // stateInitializationActivity2 // this.stateInitializationActivity2.Activities.Add(this.dialogFormActivity1); this.stateInitializationActivity2.Name = "stateInitializationActivity2"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.initializeCodeActivity); this.stateInitializationActivity1.Activities.Add(this.setStateActivity2); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // validateStateActivity // this.validateStateActivity.Activities.Add(this.validateStateInitializationActivity); this.validateStateActivity.Name = "validateStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity7); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.stateInitializationActivity4); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.stateInitializationActivity2); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.stateInitializationActivity1); this.initializeStateActivity.Name = "initializeStateActivity"; // // AddNewRazorFunctionWorkflow // this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.validateStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddNewRazorFunctionWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity finalStateActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private StateInitializationActivity stateInitializationActivity4; private StateInitializationActivity stateInitializationActivity2; private StateInitializationActivity stateInitializationActivity1; private SetStateActivity setStateActivity1; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity5; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private CodeActivity initializeCodeActivity; private EventDrivenActivity step1EventDrivenActivity_Finish; private C1Console.Workflow.Activities.DataDialogFormActivity dialogFormActivity1; private CodeActivity finalizecodeActivity; private SetStateActivity setStateActivity7; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private SetStateActivity setStateActivity2; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private StateInitializationActivity validateStateInitializationActivity; private StateActivity validateStateActivity; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity6; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private StateActivity initializeStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/RazorFunctionProviderElementProvider/AddNewRazorFunctionWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Workflow.Activities; using System.Workflow.Runtime; using Composite.AspNet.Security; using Composite.C1Console.Actions; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.ResourceSystem; using Composite.Functions; using Composite.Functions.Foundation.PluginFacades; using Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider; using Composite.Plugins.Functions.FunctionProviders.RazorFunctionProvider; using Composite.Plugins.Elements.ElementProviders.Common; using Composite.Core.Xml; namespace Composite.Plugins.Elements.ElementProviders.RazorFunctionProviderElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewRazorFunctionWorkflow : BaseFunctionWorkflow { private static readonly string Binding_Name = "Name"; private static readonly string Binding_Namespace = "Namespace"; private static readonly string Binding_CopyFromFunctionName = "CopyFromFunctionName"; private static readonly string Binding_CopyFromOptions = "CopyFromOptions"; private static readonly string NewRazorFunction_CSHTML = @"@inherits RazorFunction @functions { public override string FunctionDescription { get { return ""Shortly describe this function here""; } } [FunctionParameter(Label = ""Heading label here..."", Help = ""Help text here..."", DefaultValue = ""Default value here..."")] public string Heading { get; set; } [FunctionParameter(Label = ""Article label here..."", Help = ""Help text here..."")] public XhtmlDocument Article { get; set; } [FunctionParameter(Label = ""Image label here..."", Help = ""Help text here..."")] public DataReference<IImageFile> Image { get; set; } } <html xmlns=""http://www.w3.org/1999/xhtml"" xmlns:f=""" + Namespaces.Function10 + @"""> <head> </head> <body> <h1>@Heading</h1> <div> <img src=""/media(@Image)"" style=""float:right"" /> @Html.Raw(@Article) </div> </body> </html>"; public AddNewRazorFunctionWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { BaseFunctionFolderElementEntityToken token = (BaseFunctionFolderElementEntityToken)this.EntityToken; string @namespace = token.FunctionNamespace ?? UserSettings.LastSpecifiedNamespace; this.Bindings.Add(Binding_Name, string.Empty); this.Bindings.Add(Binding_Namespace, @namespace); var functionProvider = GetFunctionProvider<RazorFunctionProvider>(); var copyOfOptions = new List<KeyValuePair<string, string>>(); copyOfOptions.Add(new KeyValuePair<string, string>(string.Empty, GetText("AddNewRazorFunction.LabelCopyFromEmptyOption"))); foreach (string functionName in FunctionFacade.GetFunctionNamesByProvider(functionProvider.Name)) { copyOfOptions.Add(new KeyValuePair<string, string>(functionName, functionName)); } this.Bindings.Add(Binding_CopyFromFunctionName, string.Empty); this.Bindings.Add(Binding_CopyFromOptions, copyOfOptions); } private void IsValidData(object sender, ConditionalEventArgs e) { string functionName = this.GetBinding<string>(Binding_Name); string functionNamespace = this.GetBinding<string>(Binding_Namespace); var provider = GetFunctionProvider<RazorFunctionProvider>(); e.Result = false; if (functionName == string.Empty) { ShowFieldMessage(Binding_Name, GetText("AddNewRazorFunctionWorkflow.EmptyName")); return; } if (string.IsNullOrWhiteSpace(functionNamespace)) { ShowFieldMessage(Binding_Namespace, GetText("AddNewRazorFunctionWorkflow.NamespaceEmpty")); return; } if (!functionNamespace.IsCorrectNamespace('.')) { ShowFieldMessage(Binding_Namespace, GetText("AddNewRazorFunctionWorkflow.InvalidNamespace")); return; } string functionFullName = functionNamespace + "." + functionName; bool nameIsUsed = FunctionFacade.FunctionNames.Contains(functionFullName, StringComparer.OrdinalIgnoreCase); if (nameIsUsed) { ShowFieldMessage(Binding_Namespace, GetText("AddNewRazorFunctionWorkflow.DuplicateName")); return; } if ((provider.PhysicalPath + functionNamespace + functionName).Length > 240) { ShowFieldMessage(Binding_Name, GetText("AddNewRazorFunctionWorkflow.TotalNameTooLang")); return; } e.Result = true; } private void finalizecodeActivity_ExecuteCode(object sender, EventArgs e) { var provider = GetFunctionProvider<RazorFunctionProvider>(); string functionName = this.GetBinding<string>(Binding_Name); string functionNamespace = ChangeNamespaceAccordingToExistingFolders(provider,this.GetBinding<string>(Binding_Namespace)); string functionFullName = functionNamespace + "." + functionName; AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken); string fileName = functionName + ".cshtml"; string folder = Path.Combine(provider.PhysicalPath, functionNamespace.Replace('.', '\\')); string cshtmlFilePath = Path.Combine(folder, fileName); string code; string copyFromFunction = this.GetBinding<string>(Binding_CopyFromFunctionName); if(string.IsNullOrEmpty(copyFromFunction)) { code = NewRazorFunction_CSHTML; } else { code = GetFunctionCode(copyFromFunction); } C1Directory.CreateDirectory(folder); C1File.WriteAllText(cshtmlFilePath, code); UserSettings.LastSpecifiedNamespace = functionNamespace; provider.ReloadFunctions(); var newFunctionEntityToken = new FileBasedFunctionEntityToken(provider.Name, functionFullName); addNewTreeRefresher.PostRefreshMesseges(newFunctionEntityToken); var container = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); var executionService = container.GetService<IActionExecutionService>(); executionService.Execute(newFunctionEntityToken, new WorkflowActionToken(typeof(EditRazorFunctionWorkflow)), null); } private static string ChangeNamespaceAccordingToExistingFolders(RazorFunctionProvider provider, string nameSpace) { string folder = Path.Combine(provider.PhysicalPath, nameSpace.Replace('.', '\\')); if (Directory.Exists(folder)) { return GetAlldirectoriesAndSubDirectories(provider.PhysicalPath) .Single(f=>f.Equals(folder,StringComparison.InvariantCultureIgnoreCase)) .Replace(provider.PhysicalPath + "\\", "") .Replace('\\','.'); } return nameSpace; } private static List<string> GetAlldirectoriesAndSubDirectories(string physicalPath) { var res = new List<string>(); foreach (var dir in Directory.GetDirectories(physicalPath)) { res.Add(dir); res.AddRange(GetAlldirectoriesAndSubDirectories(dir)); } return res; } private string GetFunctionCode(string copyFromFunction) { IFunction function = FunctionFacade.GetFunction(copyFromFunction); if (function is FunctionWrapper) { function = (function as FunctionWrapper).InnerFunction; } var razorFunction = (RazorBasedFunction) function; string filePath = PathUtil.Resolve(razorFunction.VirtualPath); return C1File.ReadAllText(filePath); } private static string GetText(string key) { return StringResourceSystemFacade.GetString("Composite.Plugins.RazorFunction", key); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/RazorFunctionProviderElementProvider/AddNewRazorFunctionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1011, 607" AutoSizeMargin="16, 24" AutoSize="False" Location="30, 30" Name="AddNewRazorFunctionWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceActivity="AddNewRazorFunctionWorkflow" TargetConnectionIndex="0" SourceStateName="AddNewRazorFunctionWorkflow" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="240" Y="63" /> <ns0:Point X="280" Y="63" /> <ns0:Point X="280" Y="422" /> <ns0:Point X="143" Y="422" /> <ns0:Point X="143" Y="431" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" EventHandlerName="stateInitializationActivity1" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="234" Y="146" /> <ns0:Point X="250" Y="146" /> <ns0:Point X="250" Y="190" /> <ns0:Point X="168" Y="190" /> <ns0:Point X="168" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="validateStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="validateStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="266" Y="266" /> <ns0:Point X="282" Y="266" /> <ns0:Point X="282" Y="518" /> <ns0:Point X="167" Y="518" /> <ns0:Point X="167" Y="527" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="270" Y="290" /> <ns0:Point X="286" Y="290" /> <ns0:Point X="286" Y="422" /> <ns0:Point X="143" Y="422" /> <ns0:Point X="143" Y="431" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" EventHandlerName="stateInitializationActivity4" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="234" Y="376" /> <ns0:Point X="250" Y="376" /> <ns0:Point X="250" Y="422" /> <ns0:Point X="143" Y="422" /> <ns0:Point X="143" Y="431" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="validateStateActivity" TargetConnectionIndex="0" SourceStateName="validateStateActivity" SourceConnectionEdge="Right" EventHandlerName="validateStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="268" Y="568" /> <ns0:Point X="284" Y="568" /> <ns0:Point X="284" Y="328" /> <ns0:Point X="150" Y="328" /> <ns0:Point X="150" Y="335" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="validateStateActivity" TargetConnectionIndex="0" SourceStateName="validateStateActivity" SourceConnectionEdge="Right" EventHandlerName="validateStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="268" Y="568" /> <ns0:Point X="284" Y="568" /> <ns0:Point X="284" Y="192" /> <ns0:Point X="168" Y="192" /> <ns0:Point X="168" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="175, 80" AutoSizeMargin="16, 24" Location="63, 105" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="stateInitializationActivity1" Size="150, 182" Location="71, 136"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity" Size="130, 41" Location="81, 198" /> <SetStateDesigner Name="setStateActivity2" Size="130, 41" Location="81, 258" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="211, 118" AutoSizeMargin="16, 24" AutoSize="False" Location="63, 201" Name="step1StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="stateInitializationActivity2" Size="150, 122" Location="460, 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="dialogFormActivity1" Size="130, 41" Location="470, 210" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Finish" Size="150, 182" Location="452, 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130, 41" Location="462, 221" /> <SetStateDesigner Name="setStateActivity5" Size="130, 41" Location="462, 281" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Cancel" Size="150, 182" Location="452, 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130, 41" Location="462, 245" /> <SetStateDesigner Name="setStateActivity6" Size="130, 41" Location="462, 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175, 80" AutoSizeMargin="16, 24" Location="63, 335" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="stateInitializationActivity4" Size="150, 242" Location="71, 366"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="closeCurrentViewActivity1" Size="130, 41" Location="81, 428" /> <CodeDesigner Name="finalizecodeActivity" Size="130, 41" Location="81, 488" /> <SetStateDesigner Name="setStateActivity1" Size="130, 41" Location="81, 548" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160, 80" AutoSizeMargin="16, 24" Location="63, 431" Name="finalStateActivity" /> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150, 182" Location="38, 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130, 41" Location="48, 123" /> <SetStateDesigner Name="setStateActivity7" Size="130, 41" Location="48, 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="209, 80" AutoSizeMargin="16, 24" Location="63, 527" Name="validateStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="validateStateInitializationActivity" Size="381, 303" Location="71, 558"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="ifElseActivity1" Size="361, 222" Location="81, 620"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150, 122" Location="100, 691"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130, 41" Location="110, 753" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150, 122" Location="273, 691"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity4" Size="130, 41" Location="283, 753" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/RazorFunctionProviderElementProvider/DeleteRazorFunctionWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.RazorFunctionProviderElementProvider { partial class DeleteRazorFunctionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.codeActivity1 = new System.Workflow.Activities.CodeActivity(); this.confirm_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.confirm_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.deleteStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.confirmStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.deleteStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "deleteStateActivity"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "/Administrative/DeleteRazorFunctionConfirm.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // codeActivity1 // this.codeActivity1.Name = "codeActivity1"; this.codeActivity1.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode); // // confirm_Cancel // this.confirm_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.confirm_Cancel.Activities.Add(this.setStateActivity4); this.confirm_Cancel.Name = "confirm_Cancel"; // // confirm_Finish // this.confirm_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.confirm_Finish.Activities.Add(this.setStateActivity3); this.confirm_Finish.Name = "confirm_Finish"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.confirmDialogFormActivity1); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // deleteStateInitializationActivity // this.deleteStateInitializationActivity.Activities.Add(this.codeActivity1); this.deleteStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.deleteStateInitializationActivity.Activities.Add(this.setStateActivity1); this.deleteStateInitializationActivity.Name = "deleteStateInitializationActivity"; // // confirmStateActivity // this.confirmStateActivity.Activities.Add(this.stateInitializationActivity1); this.confirmStateActivity.Activities.Add(this.confirm_Finish); this.confirmStateActivity.Activities.Add(this.confirm_Cancel); this.confirmStateActivity.Name = "confirmStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity2); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // deleteStateActivity // this.deleteStateActivity.Activities.Add(this.deleteStateInitializationActivity); this.deleteStateActivity.Name = "deleteStateActivity"; // // DeleteRazorFunctionWorkflow // this.Activities.Add(this.deleteStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.confirmStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "confirmStateActivity"; this.Name = "DeleteRazorFunctionWorkflow"; this.CanModifyActivities = false; } #endregion private CodeActivity codeActivity1; private StateInitializationActivity deleteStateInitializationActivity; private SetStateActivity setStateActivity1; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private StateActivity finalStateActivity; private C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private EventDrivenActivity confirm_Cancel; private EventDrivenActivity confirm_Finish; private StateInitializationActivity stateInitializationActivity1; private StateActivity confirmStateActivity; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private StateActivity deleteStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/RazorFunctionProviderElementProvider/DeleteRazorFunctionWorkflow.cs ================================================ using System; using Composite.AspNet.Security; using Composite.C1Console.Workflow; using Composite.Core.IO; using Composite.Plugins.Functions.FunctionProviders.FileBasedFunctionProvider; using Composite.Plugins.Elements.ElementProviders.Common; using Composite.Plugins.Functions.FunctionProviders.RazorFunctionProvider; namespace Composite.Plugins.Elements.ElementProviders.RazorFunctionProviderElementProvider { [EntityTokenLock] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteRazorFunctionWorkflow : BaseFunctionWorkflow { public DeleteRazorFunctionWorkflow() { InitializeComponent(); } private void codeActivity1_ExecuteCode(object sender, EventArgs e) { var functionEntityToken = (FileBasedFunctionEntityToken)EntityToken; FileBasedFunctionProvider<RazorBasedFunction> provider; FileBasedFunction<RazorBasedFunction> function; GetProviderAndFunction(functionEntityToken, out provider, out function); string cshtmlFilePath = PathUtil.Resolve(function.VirtualPath); C1File.Delete(cshtmlFilePath); DeleteEmptyAncestorFolders(cshtmlFilePath); provider.ReloadFunctions(); RefreshFunctionTree(); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/RazorFunctionProviderElementProvider/DeleteRazorFunctionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1011, 537" AutoSizeMargin="16, 24" AutoSize="False" Location="30, 30" Name="DeleteRazorFunctionWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="DeleteRazorFunctionWorkflow" TargetConnectionIndex="0" SourceStateName="DeleteRazorFunctionWorkflow" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="240" Y="93" /> <ns0:Point X="272" Y="93" /> <ns0:Point X="272" Y="192" /> <ns0:Point X="143" Y="192" /> <ns0:Point X="143" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="deleteStateActivity" TargetConnectionIndex="0" SourceStateName="deleteStateActivity" SourceConnectionEdge="Right" EventHandlerName="deleteStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="260" Y="146" /> <ns0:Point X="276" Y="146" /> <ns0:Point X="276" Y="190" /> <ns0:Point X="143" Y="190" /> <ns0:Point X="143" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="deleteStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" SourceConnectionEdge="Right" EventHandlerName="confirm_Finish" SourceConnectionIndex="1" TargetStateName="deleteStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="180" Y="362" /> <ns0:Point X="275" Y="362" /> <ns0:Point X="275" Y="97" /> <ns0:Point X="163" Y="97" /> <ns0:Point X="163" Y="105" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" SourceConnectionEdge="Right" EventHandlerName="confirm_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="184" Y="386" /> <ns0:Point X="248" Y="386" /> <ns0:Point X="248" Y="194" /> <ns0:Point X="143" Y="194" /> <ns0:Point X="143" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="201, 80" AutoSizeMargin="16, 24" Location="63, 105" Name="deleteStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="deleteStateInitializationActivity" Size="150, 242" Location="71, 136"> <StateInitializationDesigner.Designers> <CodeDesigner Name="codeActivity1" Size="130, 41" Location="81, 198" /> <ActivityDesigner Name="closeCurrentViewActivity1" Size="130, 41" Location="81, 258" /> <SetStateDesigner Name="setStateActivity1" Size="130, 41" Location="81, 318" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160, 80" AutoSizeMargin="16, 24" Location="63, 201" Name="finalStateActivity" /> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150, 182" Location="38, 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130, 41" Location="48, 123" /> <SetStateDesigner Name="setStateActivity2" Size="130, 41" Location="48, 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="175, 118" AutoSizeMargin="16, 24" AutoSize="False" Location="63, 297" Name="confirmStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="stateInitializationActivity1" Size="150, 122" Location="460, 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="confirmDialogFormActivity1" Size="130, 41" Location="470, 210" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="confirm_Finish" Size="150, 182" Location="452, 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity2" Size="130, 41" Location="462, 221" /> <SetStateDesigner Name="setStateActivity3" Size="130, 41" Location="462, 281" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="confirm_Cancel" Size="150, 182" Location="452, 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130, 41" Location="462, 245" /> <SetStateDesigner Name="setStateActivity4" Size="130, 41" Location="462, 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/RazorFunctionProviderElementProvider/EditRazorFunctionWorkflow.cs ================================================ using System; using System.IO; using System.Reflection; using System.Web.WebPages; using Composite.AspNet.Razor; using Composite.AspNet.Security; using Composite.C1Console.Events; using Composite.C1Console.Workflow; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.ResourceSystem; using Composite.Plugins.Elements.ElementProviders.Common; using Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider; using Composite.Plugins.Functions.FunctionProviders.FileBasedFunctionProvider; using Composite.Plugins.Functions.FunctionProviders.RazorFunctionProvider; namespace Composite.Plugins.Elements.ElementProviders.RazorFunctionProviderElementProvider { [EntityTokenLock] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditRazorFunctionWorkflow : BaseFunctionWorkflow { private static readonly string LogTitle = typeof(EditRazorFunctionWorkflow).Name; public EditRazorFunctionWorkflow() { InitializeComponent(); } private string GetFile(FileBasedFunction<RazorBasedFunction> function) { return PathUtil.Resolve(function.VirtualPath); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { FileBasedFunctionProvider<RazorBasedFunction> provider; FileBasedFunction<RazorBasedFunction> function; GetProviderAndFunction((FileBasedFunctionEntityToken)this.EntityToken, out provider, out function); string title = Path.GetFileName(function.VirtualPath); this.Bindings.Add("Title", title); string file = GetFile(function); var websiteFile = new WebsiteFile(file); this.Bindings.Add("FileContent", websiteFile.ReadAllText()); this.Bindings.Add("FileName", websiteFile.FileName); this.Bindings.Add("FileMimeType", websiteFile.MimeType); } private void saveCodeActivity_ExecuteCode(object sender, EventArgs e) { var functionEntityToken = (FileBasedFunctionEntityToken)this.EntityToken; FileBasedFunctionProvider<RazorBasedFunction> provider; FileBasedFunction<RazorBasedFunction> function; GetProviderAndFunction(functionEntityToken, out provider, out function); string file = GetFile(function); string fileContent = this.GetBinding<string>("FileContent"); string fixedFileContent = PageTemplateHelper.FixHtmlEscapeSequences(fileContent); if (!CompileAndValidate(file, fixedFileContent)) { SetSaveStatus(false); return; } var websiteFile = new WebsiteFile(file); websiteFile.WriteAllText(fixedFileContent); provider.ReloadFunctions(); this.CreateParentTreeRefresher().PostRefreshMesseges(this.EntityToken); SetSaveStatus(true); if(fixedFileContent != fileContent) { UpdateBinding("FileContent", fixedFileContent); RerenderView(); } } private bool CompileAndValidate(string file, string fileContent) { string tempMarkupFile = GetTempFilePath(file); try { File.WriteAllText(tempMarkupFile, fileContent); string tempFileVirtualPath = "~" + PathUtil.GetWebsitePath(tempMarkupFile); WebPageBase webPageBase; try { webPageBase = WebPage.CreateInstanceFromVirtualPath(tempFileVirtualPath); } catch(Exception ex) { Log.LogWarning(LogTitle, "Failed to compile CSHTML file"); Log.LogWarning(LogTitle, ex); Exception compilationException = (ex is TargetInvocationException) ? ex.InnerException : ex; // Replacing file path and temp file name from error message as it is irrelevant to the user string markupFileName = Path.GetFileName(file); string errorMessage = compilationException.Message; if (errorMessage.StartsWith(tempMarkupFile, StringComparison.OrdinalIgnoreCase)) { errorMessage = markupFileName + errorMessage.Substring(tempMarkupFile.Length); } ShowWarning(GetText("EditRazorFunctionWorkflow.Validation.CompilationFailed") .FormatWith(errorMessage)); return false; } return Validate(webPageBase); } finally { // Deleting temporary file File.Delete(tempMarkupFile); } } private bool Validate(WebPageBase webPageBase) { var razorFunction = webPageBase as RazorFunction; if (razorFunction == null) { ShowWarning(GetText("EditRazorFunctionWorkflow.Validation.IncorrectBaseClass") .FormatWith(typeof(RazorFunction).FullName)); return false; } return true; } private void ShowWarning(string warning) { this.ShowMessage(DialogType.Warning, GetText("EditRazorFunctionWorkflow.Validation.DialogTitle"), warning); } private string GetText(string text) { return StringResourceSystemFacade.GetString("Composite.Plugins.RazorFunction", text); } private string GetTempFilePath(string filePath) { string fileName = Path.GetFileName(filePath); string folderPath = Path.GetDirectoryName(filePath); return Path.Combine(folderPath, "_temp_" + fileName); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/RazorFunctionProviderElementProvider/EditRazorFunctionWorkflow.designer.cs ================================================ using System.Workflow.Activities; namespace Composite.Plugins.Elements.ElementProviders.RazorFunctionProviderElementProvider { partial class EditRazorFunctionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.initialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // saveCodeActivity // this.saveCodeActivity.Name = "saveCodeActivity"; this.saveCodeActivity.ExecuteCode += new System.EventHandler(this.saveCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "saveStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.CustomToolbarDefinitionFileName = null; this.documentFormActivity1.FormDefinitionFileName = "/Administrative/EditRazorFunction.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.saveCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // eventDrivenActivity_Save // this.eventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.eventDrivenActivity_Save.Activities.Add(this.setStateActivity3); this.eventDrivenActivity_Save.Name = "eventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initialStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity1); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.eventDrivenActivity_Save); this.editStateActivity.Name = "editStateActivity"; // // initialState // this.initialState.Activities.Add(this.initialStateInitializationActivity); this.initialState.Name = "initialState"; // // EditMasterPageWorkflow // this.Activities.Add(this.initialState); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelEventDrivenActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialState"; this.Name = "EditMasterPageWorkflow"; this.CanModifyActivities = false; } #endregion private CodeActivity initializeCodeActivity; private SetStateActivity setStateActivity1; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initialStateInitializationActivity; private EventDrivenActivity cancelEventDrivenActivity; private StateActivity finalStateActivity; private StateActivity saveStateActivity; private StateActivity editStateActivity; private C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private StateInitializationActivity editStateInitializationActivity; private StateInitializationActivity finalizeStateInitializationActivity; private CodeActivity saveCodeActivity; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity eventDrivenActivity_Save; private SetStateActivity setStateActivity4; private StateActivity initialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/AddNewSqlConnectionWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider { partial class AddNewSqlConnectionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity1 = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.stateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.initialStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // codeActivity1 // this.codeActivity1.Name = "codeActivity1"; this.codeActivity1.ExecuteCode += new System.EventHandler(this.finalizecodeActivity_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = null; this.wizzardFormActivity1.FormDefinitionFileName = "/Administrative/AddNewSqlFunctionConnection.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "step1StateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.codeActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity5); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity3); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.wizzardFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // stateInitializationActivity // this.stateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.stateInitializationActivity.Activities.Add(this.setStateActivity1); this.stateInitializationActivity.Name = "stateInitializationActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity4); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // initialStateActivity // this.initialStateActivity.Activities.Add(this.stateInitializationActivity); this.initialStateActivity.Name = "initialStateActivity"; // // AddNewSqlConnectionWorkflow // this.Activities.Add(this.initialStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialStateActivity"; this.Name = "AddNewSqlConnectionWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity finalStateActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private StateInitializationActivity step1StateInitializationActivity; private StateInitializationActivity stateInitializationActivity; private SetStateActivity setStateActivity1; private StateInitializationActivity finalizeStateInitializationActivity; private SetStateActivity setStateActivity2; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private SetStateActivity setStateActivity4; private CodeActivity initializeCodeActivity; private Composite.C1Console.Workflow.Activities.DataDialogFormActivity wizzardFormActivity1; private CodeActivity codeActivity1; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private EventDrivenActivity step1EventDrivenActivity_Finish; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private StateActivity initialStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/AddNewSqlConnectionWorkflow.cs ================================================ using System; using Composite.C1Console.Actions; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Security.Cryptography; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewSqlConnectionWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddNewSqlConnectionWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { ISqlConnection sqlConnection = DataFacade.BuildNew<ISqlConnection>(); sqlConnection.Id = Guid.NewGuid(); sqlConnection.Name = "New Sql Connection"; this.Bindings.Add("NewSqlConnection", sqlConnection); this.Bindings.Add("ConnectionString", ""); } private void finalizecodeActivity_ExecuteCode(object sender, EventArgs e) { AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken); ISqlConnection sqlConnection = this.GetBinding<ISqlConnection>("NewSqlConnection"); string connection = this.GetBinding<string>("ConnectionString"); sqlConnection.EncryptedConnectionString = connection.Encrypt(); sqlConnection = DataFacade.AddNew<ISqlConnection>(sqlConnection); addNewTreeRefresher.PostRefreshMesseges(sqlConnection.GetDataEntityToken()); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/AddNewSqlConnectionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="AddNewSqlConnectionWorkflow" Location="30; 30" Size="1146; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="AddNewSqlConnectionWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="AddNewSqlConnectionWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="873" Y="71" /> <ns0:Point X="873" Y="674" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="initialStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initialStateActivity" EventHandlerName="stateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="228" Y="146" /> <ns0:Point X="336" Y="146" /> <ns0:Point X="336" Y="281" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="434" Y="346" /> <ns0:Point X="551" Y="346" /> <ns0:Point X="551" Y="468" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="438" Y="370" /> <ns0:Point X="873" Y="370" /> <ns0:Point X="873" Y="674" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="650" Y="509" /> <ns0:Point X="873" Y="509" /> <ns0:Point X="873" Y="674" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initialStateActivity" Location="63; 105" Size="169; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="stateInitializationActivity" Location="71; 136"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity" Location="81; 198" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="81; 258" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="step1StateActivity" Location="231; 281" Size="211; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="239; 312"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="wizzardFormActivity1" Location="249; 374" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Finish" Location="239; 336"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="249; 398" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="249; 458" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="239; 360"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="249; 422" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="249; 482" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="449; 468" Size="205; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="finalizeStateInitializationActivity" Location="528; 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="538; 210" /> <CodeDesigner Size="130; 41" Name="codeActivity1" Location="538; 270" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="538; 330" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="793; 674" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/AddNewSqlFunctionProviderWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider { partial class AddNewSqlFunctionProviderWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step1WizzardFormActivity = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity1 = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.stateInitializationActivity3 = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity1 = new System.Workflow.Activities.EventDrivenActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.addNewSqlXmlProviderWorkflowInitialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeActivity_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // step1WizzardFormActivity // this.step1WizzardFormActivity.ContainerLabel = null; this.step1WizzardFormActivity.FormDefinitionFileName = "/Administrative/AddNewSqlFunction.xml"; this.step1WizzardFormActivity.Name = "step1WizzardFormActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "step1StateActivity"; // // codeActivity1 // this.codeActivity1.Name = "codeActivity1"; this.codeActivity1.ExecuteCode += new System.EventHandler(this.initializeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // stateInitializationActivity3 // this.stateInitializationActivity3.Activities.Add(this.closeCurrentViewActivity1); this.stateInitializationActivity3.Activities.Add(this.finalizeCodeActivity); this.stateInitializationActivity3.Activities.Add(this.setStateActivity4); this.stateInitializationActivity3.Name = "stateInitializationActivity3"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity5); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity2); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1WizzardFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.codeActivity1); this.stateInitializationActivity1.Activities.Add(this.setStateActivity1); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // eventDrivenActivity1 // this.eventDrivenActivity1.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity1.Activities.Add(this.setStateActivity3); this.eventDrivenActivity1.Name = "eventDrivenActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.stateInitializationActivity3); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // addNewSqlXmlProviderWorkflowInitialState // this.addNewSqlXmlProviderWorkflowInitialState.Activities.Add(this.stateInitializationActivity1); this.addNewSqlXmlProviderWorkflowInitialState.Name = "addNewSqlXmlProviderWorkflowInitialState"; // // AddNewSqlFunctionProviderWorkflow // this.Activities.Add(this.addNewSqlXmlProviderWorkflowInitialState); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.eventDrivenActivity1); this.Activities.Add(this.finalStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "addNewSqlXmlProviderWorkflowInitialState"; this.Name = "AddNewSqlFunctionProviderWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateActivity finalStateActivity; private EventDrivenActivity eventDrivenActivity1; private StateInitializationActivity stateInitializationActivity3; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateInitializationActivity step1StateInitializationActivity; private StateInitializationActivity stateInitializationActivity1; private CodeActivity codeActivity1; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity1; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity4; private CodeActivity finalizeCodeActivity; private Composite.C1Console.Workflow.Activities.DataDialogFormActivity step1WizzardFormActivity; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private StateActivity addNewSqlXmlProviderWorkflowInitialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/AddNewSqlFunctionProviderWorkflow.cs ================================================ using System; using System.Linq; using Composite.C1Console.Actions; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Users; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewSqlFunctionProviderWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddNewSqlFunctionProviderWorkflow() { InitializeComponent(); } private void initializeActivity_ExecuteCode(object sender, EventArgs e) { string namespaceName; ISqlConnection sqlConnection; if ((this.EntityToken is DataEntityToken)) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; namespaceName = UserSettings.LastSpecifiedNamespace; sqlConnection = (ISqlConnection)dataEntityToken.Data; } else if ((this.EntityToken is SqlFunctionProviderFolderEntityToken)) { Guid connectionId = new Guid(((SqlFunctionProviderFolderEntityToken)this.EntityToken).ConnectionId); namespaceName = this.EntityToken.Id; sqlConnection = DataFacade.GetData<ISqlConnection>(x => x.Id == connectionId).First(); } else { throw new NotImplementedException(); } ISqlFunctionInfo sqlFunctionInfo = DataFacade.BuildNew<ISqlFunctionInfo>(); sqlFunctionInfo.IsQuery = true; sqlFunctionInfo.ConnectionId = sqlConnection.Id; sqlFunctionInfo.Id = Guid.NewGuid(); sqlFunctionInfo.Name = ""; sqlFunctionInfo.Namespace = namespaceName; sqlFunctionInfo.Description = ""; this.Bindings.Add("NewSqlQueryInfo", sqlFunctionInfo); } private void finalizeActivity_ExecuteCode(object sender, EventArgs e) { AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken); ISqlFunctionInfo sqlFunctionInfo = this.GetBinding<ISqlFunctionInfo>("NewSqlQueryInfo"); sqlFunctionInfo = DataFacade.AddNew<ISqlFunctionInfo>(sqlFunctionInfo); UserSettings.LastSpecifiedNamespace = sqlFunctionInfo.Namespace; addNewTreeRefresher.PostRefreshMesseges(sqlFunctionInfo.GetDataEntityToken()); this.ExecuteWorklow(sqlFunctionInfo.GetDataEntityToken(), typeof(EditSqlFunctionProviderWorkflow)); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/AddNewSqlFunctionProviderWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="AddNewSqlFunctionProviderWorkflow" Location="30; 30" Size="1146; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="AddNewSqlFunctionProviderWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="AddNewSqlFunctionProviderWorkflow" EventHandlerName="eventDrivenActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="176" Y="71" /> <ns0:Point X="875" Y="71" /> <ns0:Point X="875" Y="627" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="addNewSqlXmlProviderWorkflowInitialState" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="addNewSqlXmlProviderWorkflowInitialState" EventHandlerName="stateInitializationActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="234" Y="146" /> <ns0:Point X="344" Y="146" /> <ns0:Point X="344" Y="322" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="442" Y="387" /> <ns0:Point X="651" Y="387" /> <ns0:Point X="651" Y="457" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="446" Y="411" /> <ns0:Point X="875" Y="411" /> <ns0:Point X="875" Y="627" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="stateInitializationActivity3"> <StateDesignerConnector.Segments> <ns0:Point X="735" Y="498" /> <ns0:Point X="875" Y="498" /> <ns0:Point X="875" Y="627" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="addNewSqlXmlProviderWorkflowInitialState" Location="63; 105" Size="248; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="stateInitializationActivity1" Location="71; 136"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="codeActivity1" Location="81; 198" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="81; 258" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="step1StateActivity" Location="239; 322" Size="211; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="247; 353"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step1WizzardFormActivity" Location="257; 415" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Finish" Location="247; 377"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="257; 439" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="257; 499" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="247; 401"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="257; 463" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="257; 523" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="564; 457" Size="175; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="stateInitializationActivity3" Location="528; 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="538; 210" /> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity" Location="538; 270" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="538; 330" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity1" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="finalStateActivity" Location="795; 627" Size="160; 80" AutoSizeMargin="16; 24" /> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/DeleteSqlConnectionWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider { partial class DeleteSqlConnectionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity1 = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initialStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "/Administrative/SqlFunctionElementProviderDeleteSqlConnection.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity3); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity4); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity5); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.confirmDialogFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // eventDrivenActivity1 // this.eventDrivenActivity1.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity1.Activities.Add(this.setStateActivity1); this.eventDrivenActivity1.Name = "eventDrivenActivity1"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initialStateActivity // this.initialStateActivity.Activities.Add(this.initialStateInitializationActivity); this.initialStateActivity.Name = "initialStateActivity"; // // DeleteSqlConnectionWorkflow // this.Activities.Add(this.initialStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity1); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialStateActivity"; this.Name = "DeleteSqlConnectionWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity1; private StateInitializationActivity initialStateInitializationActivity; private EventDrivenActivity eventDrivenActivity1; private StateActivity finalStateActivity; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private SetStateActivity setStateActivity3; private CodeActivity finalizeCodeActivity; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateInitializationActivity step1StateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity2; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private StateActivity initialStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/DeleteSqlConnectionWorkflow.cs ================================================ using System; using System.Linq; using System.Transactions; using Composite.C1Console.Actions; using Composite.Data; using Composite.Data.Types; using Composite.Data.Transactions; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteSqlConnectionWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeleteSqlConnectionWorkflow() { InitializeComponent(); } private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { DeleteTreeRefresher deleteTreeRefresher = this.CreateDeleteTreeRefresher(this.EntityToken); DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; ISqlConnection connection = (ISqlConnection)dataEntityToken.Data; var queries = from item in DataFacade.GetData<ISqlFunctionInfo>() where item.ConnectionId == connection.Id select item; using (TransactionScope transationScope = TransactionsFacade.CreateNewScope()) { DataFacade.Delete(connection); foreach (ISqlFunctionInfo query in queries) { DataFacade.Delete(query); } transationScope.Complete(); } deleteTreeRefresher.PostRefreshMesseges(); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/DeleteSqlConnectionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="DeleteSqlConnectionWorkflow" Location="30; 30" Size="1149; 974" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="DeleteSqlConnectionWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="DeleteSqlConnectionWorkflow" EventHandlerName="eventDrivenActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="176" Y="71" /> <ns0:Point X="910" Y="71" /> <ns0:Point X="910" Y="668" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initialStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initialStateActivity" EventHandlerName="initialStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="239" Y="142" /> <ns0:Point X="298" Y="142" /> <ns0:Point X="298" Y="269" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="396" Y="334" /> <ns0:Point X="623" Y="334" /> <ns0:Point X="623" Y="451" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="400" Y="358" /> <ns0:Point X="910" Y="358" /> <ns0:Point X="910" Y="668" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="722" Y="492" /> <ns0:Point X="910" Y="492" /> <ns0:Point X="910" Y="668" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initialStateActivity" Location="46; 101" Size="197; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="initialStateInitializationActivity" Location="54; 132"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="64; 194" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="830; 668" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity1" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="step1StateActivity" Location="193; 269" Size="211; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="201; 300"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="confirmDialogFormActivity1" Location="211; 362" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Finish" Location="201; 324"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="211; 386" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="211; 446" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="201; 348"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="211; 410" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="211; 470" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="521; 451" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="finalizeStateInitializationActivity" Location="529; 482"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity" Location="539; 544" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="539; 604" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="539; 664" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/DeleteSqlFunctionProviderWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider { partial class DeleteSqlFunctionProviderWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity1 = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.DeleteSqlXmlProviderWorkflowInitialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "/Administrative/SqlFunctionElementProviderDeleteSqlFunction.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity5); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity3); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity4); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.confirmDialogFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.setStateActivity2); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // eventDrivenActivity1 // this.eventDrivenActivity1.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity1.Activities.Add(this.setStateActivity1); this.eventDrivenActivity1.Name = "eventDrivenActivity1"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // DeleteSqlXmlProviderWorkflowInitialState // this.DeleteSqlXmlProviderWorkflowInitialState.Activities.Add(this.stateInitializationActivity1); this.DeleteSqlXmlProviderWorkflowInitialState.Name = "DeleteSqlXmlProviderWorkflowInitialState"; // // DeleteSqlFunctionProviderWorkflow // this.Activities.Add(this.DeleteSqlXmlProviderWorkflowInitialState); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity1); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "DeleteSqlXmlProviderWorkflowInitialState"; this.Name = "DeleteSqlFunctionProviderWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity stateInitializationActivity1; private EventDrivenActivity eventDrivenActivity1; private StateActivity finalStateActivity; private SetStateActivity setStateActivity1; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateInitializationActivity step1StateInitializationActivity; private StateActivity step1StateActivity; private CodeActivity finalizeCodeActivity; private SetStateActivity setStateActivity2; private StateInitializationActivity finalizeStateInitializationActivity; private StateActivity finalizeStateActivity; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private StateActivity DeleteSqlXmlProviderWorkflowInitialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/DeleteSqlFunctionProviderWorkflow.cs ================================================ using System; using System.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.Types; using Composite.Core.ResourceSystem; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteSqlFunctionProviderWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeleteSqlFunctionProviderWorkflow() { InitializeComponent(); } private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { DataEntityToken token = this.EntityToken as DataEntityToken; ISqlFunctionInfo sqlFunctionInfo = (ISqlFunctionInfo)token.Data; if (DataFacade.WillDeleteSucceed(token.Data)) { DeleteTreeRefresher treeRefresher = this.CreateDeleteTreeRefresher(this.EntityToken); DataFacade.Delete(sqlFunctionInfo); int count = (from info in DataFacade.GetData<ISqlFunctionInfo>() where info.Namespace == sqlFunctionInfo.Namespace select info).Count(); if (count == 0) { ISqlConnection sqlConnection = (from connection in DataFacade.GetData<ISqlConnection>() where connection.Id == sqlFunctionInfo.ConnectionId select connection).Single(); SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(sqlConnection.GetDataEntityToken()); } else { treeRefresher.PostRefreshMesseges(); } } else { this.ShowMessage( DialogType.Error, StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", "CascadeDeleteErrorTitle"), StringResourceSystemFacade.GetString("Composite.Plugins.SqlFunction", "CascadeDeleteErrorMessage") ); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/DeleteSqlFunctionProviderWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="DeleteSqlFunctionProviderWorkflow" Location="30; 30" Size="1149; 974" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="DeleteSqlFunctionProviderWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="DeleteSqlFunctionProviderWorkflow" EventHandlerName="eventDrivenActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="176" Y="71" /> <ns0:Point X="985" Y="71" /> <ns0:Point X="985" Y="664" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="DeleteSqlXmlProviderWorkflowInitialState" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="DeleteSqlXmlProviderWorkflowInitialState" EventHandlerName="stateInitializationActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="234" Y="146" /> <ns0:Point X="321" Y="146" /> <ns0:Point X="321" Y="302" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="423" Y="391" /> <ns0:Point X="985" Y="391" /> <ns0:Point X="985" Y="664" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="419" Y="367" /> <ns0:Point X="537" Y="367" /> <ns0:Point X="537" Y="502" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="636" Y="543" /> <ns0:Point X="985" Y="543" /> <ns0:Point X="985" Y="664" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="DeleteSqlXmlProviderWorkflowInitialState" Location="63; 105" Size="240; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="stateInitializationActivity1" Location="71; 136"> <StateInitializationDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="81; 198" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="905; 664" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity1" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="step1StateActivity" Location="216; 302" Size="211; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="224; 333"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="confirmDialogFormActivity1" Location="234; 395" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Finish" Location="224; 357"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="234; 419" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="234; 479" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="224; 381"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="234; 443" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="234; 503" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="435; 502" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="finalizeStateInitializationActivity" Location="443; 533"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity" Location="453; 595" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="453; 655" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="453; 715" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/EditSqlConnectionWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider { partial class EditSqlConnectionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity1 = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initialStateCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.saveEditEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.savestateActivity = new System.Workflow.Activities.StateActivity(); this.saveEditStateActivity = new System.Workflow.Activities.StateActivity(); this.initialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "saveEditStateActivity"; // // codeActivity1 // this.codeActivity1.Name = "codeActivity1"; this.codeActivity1.ExecuteCode += new System.EventHandler(this.saveEditStateCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "savestateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.FormDefinitionFileName = "/Administrative/EditSqlFunctionConnection.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "saveEditStateActivity"; // // initialStateCodeActivity // this.initialStateCodeActivity.Name = "initialStateCodeActivity"; this.initialStateCodeActivity.ExecuteCode += new System.EventHandler(this.initialStateCodeActivity_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.codeActivity1); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity1); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // saveEditEventDrivenActivity // this.saveEditEventDrivenActivity.Activities.Add(this.saveHandleExternalEventActivity1); this.saveEditEventDrivenActivity.Activities.Add(this.setStateActivity3); this.saveEditEventDrivenActivity.Name = "saveEditEventDrivenActivity"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.initialStateCodeActivity); this.stateInitializationActivity1.Activities.Add(this.setStateActivity2); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity4); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // savestateActivity // this.savestateActivity.Activities.Add(this.saveStateInitializationActivity); this.savestateActivity.Name = "savestateActivity"; // // saveEditStateActivity // this.saveEditStateActivity.Activities.Add(this.editStateInitializationActivity); this.saveEditStateActivity.Activities.Add(this.saveEditEventDrivenActivity); this.saveEditStateActivity.Name = "saveEditStateActivity"; // // initialState // this.initialState.Activities.Add(this.stateInitializationActivity1); this.initialState.Name = "initialState"; // // EditSqlConnectionWorkflow // this.Activities.Add(this.initialState); this.Activities.Add(this.saveEditStateActivity); this.Activities.Add(this.savestateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialState"; this.Name = "EditSqlConnectionWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity finalStateActivity; private StateActivity savestateActivity; private StateActivity saveEditStateActivity; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity4; private StateInitializationActivity saveStateInitializationActivity; private EventDrivenActivity saveEditEventDrivenActivity; private StateInitializationActivity editStateInitializationActivity; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private CodeActivity initialStateCodeActivity; private StateInitializationActivity stateInitializationActivity1; private CodeActivity codeActivity1; private Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity1; private StateActivity initialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/EditSqlConnectionWorkflow.cs ================================================ using System; using Composite.C1Console.Actions; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Security.Cryptography; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditSqlConnectionWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditSqlConnectionWorkflow() { InitializeComponent(); } private void initialStateCodeActivity_ExecuteCode(object sender, EventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; ISqlConnection connection = (ISqlConnection)dataEntityToken.Data; string decryptedConnectionString = connection.EncryptedConnectionString.Decrypt(); this.Bindings.Add("ConnectionString", decryptedConnectionString); this.Bindings.Add("SqlConnection", connection); } private void saveEditStateCodeActivity_ExecuteCode(object sender, EventArgs e) { UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken); ISqlConnection connection = this.GetBinding<ISqlConnection>("SqlConnection"); string connectionString = this.GetBinding<string>("ConnectionString"); connection.EncryptedConnectionString = connectionString.Encrypt(); DataFacade.Update(connection); SetSaveStatus(true); updateTreeRefresher.PostRefreshMesseges(connection.GetDataEntityToken()); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/EditSqlConnectionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="EditSqlConnectionWorkflow" Location="30, 30" Size="733, 520" AutoSize="False" AutoSizeMargin="16, 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="EditSqlConnectionWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="EditSqlConnectionWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="245" Y="71" /> <ns0:Point X="245" Y="63" /> <ns0:Point X="269" Y="63" /> <ns0:Point X="269" Y="397" /> <ns0:Point X="146" Y="397" /> <ns0:Point X="146" Y="403" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="saveEditStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initialState" SourceConnectionEdge="Right" TargetActivity="saveEditStateActivity" SourceActivity="initialState" EventHandlerName="stateInitializationActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="237" Y="142" /> <ns0:Point X="253" Y="142" /> <ns0:Point X="253" Y="190" /> <ns0:Point X="160" Y="190" /> <ns0:Point X="160" Y="197" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="savestateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="saveEditStateActivity" SourceConnectionEdge="Right" TargetActivity="savestateActivity" SourceActivity="saveEditStateActivity" EventHandlerName="saveEditEventDrivenActivity"> <StateDesignerConnector.Segments> <ns0:Point X="251" Y="262" /> <ns0:Point X="267" Y="262" /> <ns0:Point X="267" Y="302" /> <ns0:Point X="163" Y="302" /> <ns0:Point X="163" Y="307" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="saveEditStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="savestateActivity" SourceConnectionEdge="Right" TargetActivity="saveEditStateActivity" SourceActivity="savestateActivity" EventHandlerName="saveStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="348" /> <ns0:Point X="272" Y="348" /> <ns0:Point X="272" Y="190" /> <ns0:Point X="160" Y="190" /> <ns0:Point X="160" Y="197" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initialState" Location="66, 101" Size="175, 80" AutoSize="False" AutoSizeMargin="16, 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150, 181" Name="stateInitializationActivity1" Location="74, 132"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130, 41" Name="initialStateCodeActivity" Location="84, 193" /> <SetStateDesigner Size="130, 41" Name="setStateActivity2" Location="84, 253" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="saveEditStateActivity" Location="66, 197" Size="189, 94" AutoSize="False" AutoSizeMargin="16, 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150, 121" Name="editStateInitializationActivity" Location="321, 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130, 41" Name="documentFormActivity1" Location="331, 209" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150, 181" Name="saveEditEventDrivenActivity" Location="313, 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130, 41" Name="saveHandleExternalEventActivity1" Location="323, 220" /> <SetStateDesigner Size="130, 41" Name="setStateActivity3" Location="323, 280" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="savestateActivity" Location="66, 307" Size="194, 80" AutoSizeMargin="16, 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150, 181" Name="saveStateInitializationActivity" Location="74, 338"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130, 41" Name="codeActivity1" Location="84, 399" /> <SetStateDesigner Size="130, 41" Name="setStateActivity1" Location="84, 459" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="66, 403" Size="160, 80" AutoSizeMargin="16, 24" /> <EventDrivenDesigner Size="150, 181" Name="eventDrivenActivity_GlobalCancel" Location="38, 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130, 41" Name="cancelHandleExternalEventActivity1" Location="48, 122" /> <SetStateDesigner Size="130, 41" Name="setStateActivity4" Location="48, 182" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/EditSqlFunctionProviderWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider { partial class EditSqlFunctionProviderWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity3 = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.previewCodeActivity = new System.Workflow.Activities.CodeActivity(); this.previewHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.PreviewHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity1 = new System.Workflow.Activities.CodeActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editEventDrivenActivity_preview = new System.Workflow.Activities.EventDrivenActivity(); this.editEventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.stateActivity1 = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity1 = new System.Workflow.Activities.EventDrivenActivity(); this.initialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // codeActivity3 // this.codeActivity3.Name = "codeActivity3"; this.codeActivity3.ExecuteCode += new System.EventHandler(this.saveCodeActivity_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "editStateActivity"; // // previewCodeActivity // this.previewCodeActivity.Name = "previewCodeActivity"; this.previewCodeActivity.ExecuteCode += new System.EventHandler(this.previewCodeActivity_ExecuteCode); // // previewHandleExternalEventActivity1 // this.previewHandleExternalEventActivity1.EventName = "Preview"; this.previewHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.previewHandleExternalEventActivity1.Name = "previewHandleExternalEventActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "stateActivity1"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.FormDefinitionFileName = "/Administrative/EditSqlFunction.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // codeActivity1 // this.codeActivity1.Name = "codeActivity1"; this.codeActivity1.ExecuteCode += new System.EventHandler(this.initialize_ExecuteCode); // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.codeActivity3); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity4); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // editEventDrivenActivity_preview // this.editEventDrivenActivity_preview.Activities.Add(this.previewHandleExternalEventActivity1); this.editEventDrivenActivity_preview.Activities.Add(this.previewCodeActivity); this.editEventDrivenActivity_preview.Activities.Add(this.setStateActivity5); this.editEventDrivenActivity_preview.Name = "editEventDrivenActivity_preview"; // // editEventDrivenActivity_Save // this.editEventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.editEventDrivenActivity_Save.Activities.Add(this.setStateActivity3); this.editEventDrivenActivity_Save.Name = "editEventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.codeActivity1); this.initialStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // stateActivity1 // this.stateActivity1.Activities.Add(this.saveStateInitializationActivity); this.stateActivity1.Name = "stateActivity1"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_Save); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_preview); this.editStateActivity.Name = "editStateActivity"; // // eventDrivenActivity1 // this.eventDrivenActivity1.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity1.Activities.Add(this.setStateActivity1); this.eventDrivenActivity1.Name = "eventDrivenActivity1"; // // initialState // this.initialState.Activities.Add(this.initialStateInitializationActivity); this.initialState.Name = "initialState"; // // EditSqlFunctionProviderWorkflow // this.Activities.Add(this.initialState); this.Activities.Add(this.eventDrivenActivity1); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.stateActivity1); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialState"; this.Name = "EditSqlFunctionProviderWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity finalStateActivity; private StateActivity editStateActivity; private EventDrivenActivity eventDrivenActivity1; private CodeActivity codeActivity1; private EventDrivenActivity editEventDrivenActivity_Save; private StateInitializationActivity editStateInitializationActivity; private SetStateActivity setStateActivity1; private StateInitializationActivity initialStateInitializationActivity; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private CodeActivity codeActivity3; private StateInitializationActivity saveStateInitializationActivity; private StateActivity stateActivity1; private SetStateActivity setStateActivity4; private EventDrivenActivity editEventDrivenActivity_preview; private CodeActivity previewCodeActivity; private Composite.C1Console.Workflow.Activities.PreviewHandleExternalEventActivity previewHandleExternalEventActivity1; private SetStateActivity setStateActivity5; private StateActivity initialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/EditSqlFunctionProviderWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Workflow.Runtime; using System.Xml.Linq; using System.Xml.Serialization; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.Types; using Composite.Functions; using Composite.Functions.ManagedParameters; using Composite.Core.Logging; using Composite.Plugins.Functions.FunctionProviders.SqlFunctionProvider; using Composite.Core.WebClient; using Composite.Core.WebClient.FlowMediators.FormFlowRendering; using Composite.Core.WebClient.FunctionCallEditor; using Composite.Core.WebClient.State; using Composite.C1Console.Workflow; using Composite.C1Console.Workflow.Foundation; namespace Composite.Plugins.Elements.ElementProviders.SqlFunctionElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditSqlFunctionProviderWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditSqlFunctionProviderWorkflow() { InitializeComponent(); } private void initialize_ExecuteCode(object sender, EventArgs e) { DataEntityToken token = this.EntityToken as DataEntityToken; ISqlFunctionInfo functionInfo = (ISqlFunctionInfo)token.Data; IEnumerable<ManagedParameterDefinition> parameters = ManagedParameterManager.Load(functionInfo.Id); this.Bindings.Add("SqlQuery", functionInfo); this.Bindings.Add("Parameters", parameters); this.Bindings.Add("ParameterTypeOptions", GetParameterTypes().ToList()); // Creating a session state object Guid stateId = Guid.NewGuid(); var state = new EditSqlFunctionState { WorkflowId = WorkflowInstanceId, ConsoleIdInternal = GetCurrentConsoleId() }; SessionStateManager.DefaultProvider.AddState<IParameterEditorState>(stateId, state, DateTime.Now.AddDays(7.0)); this.Bindings.Add("SessionStateProvider", SessionStateManager.DefaultProviderName); this.Bindings.Add("SessionStateId", stateId); } private IEnumerable<Type> GetParameterTypes() { yield return typeof(string); yield return typeof(int); yield return typeof(decimal); yield return typeof(DateTime); yield return typeof(bool); yield return typeof(Guid); } private void saveCodeActivity_ExecuteCode(object sender, EventArgs e) { UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken); ISqlFunctionInfo info; try { info = this.GetBinding<ISqlFunctionInfo>("SqlQuery"); var parameters = this.GetBinding<IEnumerable<ManagedParameterDefinition>>("Parameters"); ManagedParameterManager.Save(info.Id, parameters); DataFacade.Update(info); } catch (Exception ex) { LoggingService.LogCritical("SQL Function Save", ex); FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); var consoleMsgService = serviceContainer.GetService<IManagementConsoleMessageService>(); consoleMsgService.ShowMessage(DialogType.Error, "Error", ex.Message); SetSaveStatus(false); return; } updateTreeRefresher.PostRefreshMesseges(info.GetDataEntityToken()); SetSaveStatus(true); } private void previewCodeActivity_ExecuteCode(object sender, EventArgs e) { try { ISqlFunctionInfo queryInfo = this.GetBinding<ISqlFunctionInfo>("SqlQuery"); var parameterDefinitions = this.GetBinding<IEnumerable<ManagedParameterDefinition>>("Parameters"); ParameterList parameters = ManagedParameterManager.GetParametersListForTest(parameterDefinitions); IEnumerable<ParameterProfile> parameterProfiles = ManagedParameterManager.GetParameterProfiles(parameterDefinitions); SqlFunction function = new SqlFunction(queryInfo, parameterProfiles); XElement result = function.Execute(parameters, new FunctionContextContainer()) as XElement; Page currentPage = HttpContext.Current.Handler as Page; if (currentPage == null) throw new InvalidOperationException("The Current HttpContext Handler must be a System.Web.Ui.Page"); UserControl inOutControl = (UserControl)currentPage.LoadControl(UrlUtils.ResolveAdminUrl("controls/Misc/MarkupInOutView.ascx")); inOutControl.Attributes.Add("out", result.ToString()); FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); var webRenderService = serviceContainer.GetService<IFormFlowWebRenderingService>(); webRenderService.SetNewPageOutput(inOutControl); } catch (Exception ex) { FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); Control errOutput = new LiteralControl("<pre>" + ex.ToString() + "</pre>"); var webRenderService = serviceContainer.GetService<IFormFlowWebRenderingService>(); webRenderService.SetNewPageOutput(errOutput); } } [Serializable] public sealed class EditSqlFunctionState : IParameterEditorState { public Guid WorkflowId { get; set; } public string ConsoleIdInternal { get; set; } private FormData GetFormData() { return WorkflowFacade.GetFormData(WorkflowId); } [XmlIgnore] public List<ManagedParameterDefinition> Parameters { get { return GetFormData().Bindings["Parameters"] as List<ManagedParameterDefinition>; } set { GetFormData().Bindings["Parameters"] = value; } } [XmlIgnore] public List<Type> ParameterTypeOptions { get { return (GetFormData().Bindings["ParameterTypeOptions"] as IEnumerable<Type>).ToList(); } set { GetFormData().Bindings["ParameterTypeOptions"] = value.ToList(); } } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/SqlFunctionElementProvider/EditSqlFunctionProviderWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="EditSqlFunctionProviderWorkflow" Location="30, 30" Size="790, 530" AutoSizeMargin="16, 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="EditSqlFunctionProviderWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="EditSqlFunctionProviderWorkflow" EventHandlerName="eventDrivenActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="176" Y="71" /> <ns0:Point X="176" Y="93" /> <ns0:Point X="280" Y="93" /> <ns0:Point X="280" Y="329" /> <ns0:Point X="143" Y="329" /> <ns0:Point X="143" Y="335" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initialState" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="initialState" EventHandlerName="initialStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="146" /> <ns0:Point X="272" Y="146" /> <ns0:Point X="272" Y="190" /> <ns0:Point X="168" Y="190" /> <ns0:Point X="168" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="stateActivity1" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="editStateActivity" SourceConnectionEdge="Right" TargetActivity="stateActivity1" SourceActivity="editStateActivity" EventHandlerName="editEventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="252" Y="266" /> <ns0:Point X="284" Y="266" /> <ns0:Point X="284" Y="422" /> <ns0:Point X="160" Y="422" /> <ns0:Point X="160" Y="431" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="editStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="editStateActivity" EventHandlerName="editEventDrivenActivity_preview"> <StateDesignerConnector.Segments> <ns0:Point X="267" Y="290" /> <ns0:Point X="283" Y="290" /> <ns0:Point X="283" Y="194" /> <ns0:Point X="168" Y="194" /> <ns0:Point X="168" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="stateActivity1" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="stateActivity1" EventHandlerName="saveStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="252" Y="472" /> <ns0:Point X="284" Y="472" /> <ns0:Point X="284" Y="193" /> <ns0:Point X="168" Y="193" /> <ns0:Point X="168" Y="201" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initialState" Location="63, 105" Size="197, 80" AutoSizeMargin="16, 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150, 182" Name="initialStateInitializationActivity" Location="71, 136"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130, 41" Name="codeActivity1" Location="81, 198" /> <SetStateDesigner Size="130, 41" Name="setStateActivity2" Location="81, 258" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <EventDrivenDesigner Size="150, 182" Name="eventDrivenActivity1" Location="38, 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130, 41" Name="cancelHandleExternalEventActivity1" Location="48, 123" /> <SetStateDesigner Size="130, 41" Name="setStateActivity1" Location="48, 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="editStateActivity" Location="63, 201" Size="210, 118" AutoSizeMargin="16, 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150, 122" Name="editStateInitializationActivity" Location="71, 232"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130, 41" Name="documentFormActivity1" Location="81, 294" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150, 182" Name="editEventDrivenActivity_Save" Location="71, 256"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130, 41" Name="saveHandleExternalEventActivity1" Location="81, 318" /> <SetStateDesigner Size="130, 41" Name="setStateActivity3" Location="81, 378" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150, 242" Name="editEventDrivenActivity_preview" Location="71, 280"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130, 41" Name="previewHandleExternalEventActivity1" Location="81, 342" /> <CodeDesigner Size="130, 41" Name="previewCodeActivity" Location="81, 402" /> <SetStateDesigner Size="130, 41" Name="setStateActivity5" Location="81, 462" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="63, 335" Size="160, 80" AutoSizeMargin="16, 24" /> <StateDesigner Name="stateActivity1" Location="63, 431" Size="194, 80" AutoSizeMargin="16, 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150, 182" Name="saveStateInitializationActivity" Location="71, 462"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130, 41" Name="codeActivity3" Location="81, 524" /> <SetStateDesigner Size="130, 41" Name="setStateActivity4" Location="81, 584" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserControlFunctionProviderElementProvider/AddNewUserControlFunctionWorkflow.Designer.cs ================================================ using System.Workflow.Activities; namespace Composite.Plugins.Elements.ElementProviders.UserControlFunctionProviderElementProvider { partial class AddNewUserControlFunctionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.finalizecodeActivity = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.dialogFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.validateStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.stateInitializationActivity4 = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity2 = new System.Workflow.Activities.StateInitializationActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.validateStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "step1StateActivity"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity4); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity3); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsValidData); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // finalizecodeActivity // this.finalizecodeActivity.Name = "finalizecodeActivity"; this.finalizecodeActivity.ExecuteCode += new System.EventHandler(this.finalizecodeActivity_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "validateStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // dialogFormActivity1 // this.dialogFormActivity1.ContainerLabel = "Add new"; this.dialogFormActivity1.FormDefinitionFileName = "\\Administrative\\AddNewUserControlFunction.xml"; this.dialogFormActivity1.Name = "dialogFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // validateStateInitializationActivity // this.validateStateInitializationActivity.Activities.Add(this.ifElseActivity1); this.validateStateInitializationActivity.Name = "validateStateInitializationActivity"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // stateInitializationActivity4 // this.stateInitializationActivity4.Activities.Add(this.closeCurrentViewActivity1); this.stateInitializationActivity4.Activities.Add(this.finalizecodeActivity); this.stateInitializationActivity4.Activities.Add(this.setStateActivity1); this.stateInitializationActivity4.Name = "stateInitializationActivity4"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity6); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity5); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // stateInitializationActivity2 // this.stateInitializationActivity2.Activities.Add(this.dialogFormActivity1); this.stateInitializationActivity2.Name = "stateInitializationActivity2"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.initializeCodeActivity); this.stateInitializationActivity1.Activities.Add(this.setStateActivity2); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // validateStateActivity // this.validateStateActivity.Activities.Add(this.validateStateInitializationActivity); this.validateStateActivity.Name = "validateStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity7); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.stateInitializationActivity4); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.stateInitializationActivity2); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.stateInitializationActivity1); this.initializeStateActivity.Name = "initializeStateActivity"; // // AddNewUserControlFunctionWorkflow // this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.validateStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddNewUserControlFunctionWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity finalStateActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private StateInitializationActivity stateInitializationActivity4; private StateInitializationActivity stateInitializationActivity2; private StateInitializationActivity stateInitializationActivity1; private SetStateActivity setStateActivity1; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity5; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private CodeActivity initializeCodeActivity; private EventDrivenActivity step1EventDrivenActivity_Finish; private C1Console.Workflow.Activities.DataDialogFormActivity dialogFormActivity1; private CodeActivity finalizecodeActivity; private SetStateActivity setStateActivity7; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private SetStateActivity setStateActivity2; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private StateInitializationActivity validateStateInitializationActivity; private StateActivity validateStateActivity; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity6; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private StateActivity initializeStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserControlFunctionProviderElementProvider/AddNewUserControlFunctionWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Workflow.Activities; using System.Workflow.Runtime; using Composite.AspNet.Security; using Composite.C1Console.Actions; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.ResourceSystem; using Composite.Functions; using Composite.Functions.Foundation.PluginFacades; using Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider; using Composite.Plugins.Functions.FunctionProviders.UserControlFunctionProvider; using Composite.Plugins.Elements.ElementProviders.Common; namespace Composite.Plugins.Elements.ElementProviders.UserControlFunctionProviderElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewUserControlFunctionWorkflow : BaseFunctionWorkflow { private static readonly string Binding_Name = "Name"; private static readonly string Binding_Namespace = "Namespace"; private static readonly string Binding_CopyFromFunctionName = "CopyFromFunctionName"; private static readonly string Binding_CopyFromOptions = "CopyFromOptions"; private static readonly string Marker_CodeFile = "%CodeFile%"; private static readonly string NewUserControl_Markup = @"<%@ Control Language=""C#"" AutoEventWireup=""true"" CodeFile=""%CodeFile%"" Inherits=""C1Function"" %> Hello <%= this.Name %>!"; private static readonly string NewUserControl_CodeFile = @"using System; using Composite.Functions; public partial class C1Function : Composite.AspNet.UserControlFunction { public override string FunctionDescription { get { return ""A demo function that outputs a hello message.""; } } [FunctionParameter(DefaultValue = ""World"")] public string Name { get; set; } protected void Page_Load(object sender, EventArgs e) { } }"; public AddNewUserControlFunctionWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { BaseFunctionFolderElementEntityToken token = (BaseFunctionFolderElementEntityToken)this.EntityToken; string @namespace = token.FunctionNamespace ?? UserSettings.LastSpecifiedNamespace; this.Bindings.Add(Binding_Name, string.Empty); this.Bindings.Add(Binding_Namespace, @namespace); var functionProvider = GetFunctionProvider<UserControlFunctionProvider>(); var copyOfOptions = new List<KeyValuePair<string, string>>(); copyOfOptions.Add(new KeyValuePair<string, string>(string.Empty, GetText("AddNewUserControlFunction.LabelCopyFromEmptyOption"))); foreach (string functionName in FunctionFacade.GetFunctionNamesByProvider(functionProvider.Name)) { copyOfOptions.Add(new KeyValuePair<string, string>(functionName, functionName)); } this.Bindings.Add(Binding_CopyFromFunctionName, string.Empty); this.Bindings.Add(Binding_CopyFromOptions, copyOfOptions); } private void IsValidData(object sender, ConditionalEventArgs e) { string functionName = this.GetBinding<string>(Binding_Name); string functionNamespace = this.GetBinding<string>(Binding_Namespace); var provider = GetFunctionProvider<UserControlFunctionProvider>(); e.Result = false; if (functionName == string.Empty) { ShowFieldMessage(Binding_Name, GetText("AddNewUserControlFunctionWorkflow.EmptyName")); return; } if (string.IsNullOrWhiteSpace(functionNamespace)) { ShowFieldMessage(Binding_Namespace, GetText("AddNewUserControlFunctionWorkflow.NamespaceEmpty")); return; } if (!functionNamespace.IsCorrectNamespace('.')) { ShowFieldMessage(Binding_Namespace, GetText("AddNewUserControlFunctionWorkflow.InvalidNamespace")); return; } string functionFullName = functionNamespace + "." + functionName; bool nameIsUsed = FunctionFacade.FunctionNames.Contains(functionFullName, StringComparer.OrdinalIgnoreCase); if (nameIsUsed) { ShowFieldMessage(Binding_Namespace, GetText("AddNewUserControlFunctionWorkflow.DuplicateName")); return; } if ((provider.PhysicalPath + functionNamespace + functionName).Length > 240) { ShowFieldMessage(Binding_Name, GetText("AddNewUserControlFunctionWorkflow.TotalNameTooLang")); return; } e.Result = true; } private void finalizecodeActivity_ExecuteCode(object sender, EventArgs e) { string functionName = this.GetBinding<string>(Binding_Name); string functionNamespace = this.GetBinding<string>(Binding_Namespace); string copyFromFunctionName = this.GetBinding<string>(Binding_CopyFromFunctionName); string functionFullName = functionNamespace + "." + functionName; var provider = GetFunctionProvider<UserControlFunctionProvider>(); AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken); string fileName = functionName + ".ascx"; string folder = Path.Combine(provider.PhysicalPath, functionNamespace.Replace('.', '\\')); string markupFilePath = Path.Combine(folder, fileName); string codeFilePath = markupFilePath + ".cs"; string markupTemplate = NewUserControl_Markup; string code = NewUserControl_CodeFile; if (!copyFromFunctionName.IsNullOrEmpty()) { GetFunctionCode(copyFromFunctionName, out markupTemplate, out code); } C1Directory.CreateDirectory(folder); C1File.WriteAllText(codeFilePath, code); C1File.WriteAllText(markupFilePath, markupTemplate.Replace(Marker_CodeFile, functionName + ".ascx.cs")); UserSettings.LastSpecifiedNamespace = functionNamespace; provider.ReloadFunctions(); var newFunctionEntityToken = new FileBasedFunctionEntityToken(provider.Name, functionFullName); addNewTreeRefresher.PostRefreshMesseges(newFunctionEntityToken); var container = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); var executionService = container.GetService<IActionExecutionService>(); executionService.Execute(newFunctionEntityToken, new WorkflowActionToken(typeof(EditUserControlFunctionWorkflow)), null); } private void GetFunctionCode(string copyFromFunctionName, out string markupTemplate, out string code) { IFunction function = FunctionFacade.GetFunction(copyFromFunctionName); if (function is FunctionWrapper) { function = (function as FunctionWrapper).InnerFunction; } var razorFunction = (UserControlBasedFunction)function; string filePath = PathUtil.Resolve(razorFunction.VirtualPath); string codeFilePath = filePath + ".cs"; Verify.That(C1File.Exists(codeFilePath), "Codebehind file not found: {0}", codeFilePath); markupTemplate = C1File.ReadAllText(filePath); code = C1File.ReadAllText(codeFilePath); const string quote = "\""; string codeFileReference = quote + Path.GetFileName(codeFilePath) + quote; int codeReferenceOffset = markupTemplate.IndexOf(codeFileReference, StringComparison.OrdinalIgnoreCase); Verify.That(codeReferenceOffset > 0, "Failed to find codebehind file reference '{0}'".FormatWith(codeFileReference)); markupTemplate = markupTemplate.Replace(codeFileReference, quote + Marker_CodeFile + quote, StringComparison.OrdinalIgnoreCase); } private static string GetText(string key) { return StringResourceSystemFacade.GetString("Composite.Plugins.UserControlFunction", key); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserControlFunctionProviderElementProvider/AddNewUserControlFunctionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1011, 709" AutoSizeMargin="16, 24" AutoSize="False" Location="30, 30" Name="AddNewUserControlFunctionWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceActivity="AddNewUserControlFunctionWorkflow" TargetConnectionIndex="0" SourceStateName="AddNewUserControlFunctionWorkflow" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="240" Y="617" /> <ns0:Point X="465" Y="617" /> <ns0:Point X="465" Y="629" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="initializeStateActivity" TargetConnectionIndex="0" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" EventHandlerName="stateInitializationActivity1" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="559" Y="142" /> <ns0:Point X="568" Y="142" /> <ns0:Point X="568" Y="203" /> <ns0:Point X="464" Y="203" /> <ns0:Point X="464" Y="215" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="validateStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Finish" SourceConnectionIndex="1" TargetStateName="validateStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="562" Y="280" /> <ns0:Point X="581" Y="280" /> <ns0:Point X="581" Y="351" /> <ns0:Point X="477" Y="351" /> <ns0:Point X="477" Y="363" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceActivity="step1StateActivity" TargetConnectionIndex="0" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" EventHandlerName="step1EventDrivenActivity_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="566" Y="304" /> <ns0:Point X="706" Y="304" /> <ns0:Point X="706" Y="617" /> <ns0:Point X="465" Y="617" /> <ns0:Point X="465" Y="629" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" EventHandlerName="stateInitializationActivity4" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="551" Y="529" /> <ns0:Point X="561" Y="529" /> <ns0:Point X="561" Y="617" /> <ns0:Point X="465" Y="617" /> <ns0:Point X="465" Y="629" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="validateStateActivity" TargetConnectionIndex="0" SourceStateName="validateStateActivity" SourceConnectionEdge="Right" EventHandlerName="validateStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="578" Y="404" /> <ns0:Point X="587" Y="404" /> <ns0:Point X="587" Y="476" /> <ns0:Point X="467" Y="476" /> <ns0:Point X="467" Y="488" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="step1StateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="validateStateActivity" TargetConnectionIndex="0" SourceStateName="validateStateActivity" SourceConnectionEdge="Right" EventHandlerName="validateStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="step1StateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="578" Y="404" /> <ns0:Point X="592" Y="404" /> <ns0:Point X="592" Y="207" /> <ns0:Point X="464" Y="207" /> <ns0:Point X="464" Y="215" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="175, 80" AutoSizeMargin="16, 24" Location="388, 101" Name="initializeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="stateInitializationActivity1" Size="150, 182" Location="396, 132"> <StateInitializationDesigner.Designers> <CodeDesigner Name="initializeCodeActivity" Size="130, 41" Location="406, 194" /> <SetStateDesigner Name="setStateActivity2" Size="130, 41" Location="406, 254" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="211, 118" AutoSizeMargin="16, 24" AutoSize="False" Location="359, 215" Name="step1StateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="stateInitializationActivity2" Size="150, 122" Location="460, 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="dialogFormActivity1" Size="130, 41" Location="470, 210" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Finish" Size="150, 182" Location="452, 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130, 41" Location="462, 221" /> <SetStateDesigner Name="setStateActivity5" Size="130, 41" Location="462, 281" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="step1EventDrivenActivity_Cancel" Size="150, 182" Location="452, 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130, 41" Location="462, 245" /> <SetStateDesigner Name="setStateActivity6" Size="130, 41" Location="462, 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="175, 80" AutoSizeMargin="16, 24" Location="380, 488" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="stateInitializationActivity4" Size="150, 242" Location="388, 519"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="closeCurrentViewActivity1" Size="130, 41" Location="398, 581" /> <CodeDesigner Name="finalizecodeActivity" Size="130, 41" Location="398, 641" /> <SetStateDesigner Name="setStateActivity1" Size="130, 41" Location="398, 701" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160, 80" AutoSizeMargin="16, 24" Location="385, 629" Name="finalStateActivity" /> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150, 182" Location="38, 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130, 41" Location="48, 123" /> <SetStateDesigner Name="setStateActivity7" Size="130, 41" Location="48, 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="209, 80" AutoSizeMargin="16, 24" Location="373, 363" Name="validateStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="validateStateInitializationActivity" Size="381, 303" Location="381, 394"> <StateInitializationDesigner.Designers> <IfElseDesigner Name="ifElseActivity1" Size="361, 222" Location="391, 456"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150, 122" Location="410, 527"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity3" Size="130, 41" Location="420, 589" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150, 122" Location="583, 527"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity4" Size="130, 41" Location="593, 589" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserControlFunctionProviderElementProvider/DeleteUserControlFunctionWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.UserControlFunctionProviderElementProvider { partial class DeleteUserControlFunctionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.codeActivity1 = new System.Workflow.Activities.CodeActivity(); this.confirm_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.confirm_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.deleteStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.confirmStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.deleteStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "deleteStateActivity"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "/Administrative/DeleteUserControlFunctionConfirm.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // codeActivity1 // this.codeActivity1.Name = "codeActivity1"; this.codeActivity1.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode); // // confirm_Cancel // this.confirm_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.confirm_Cancel.Activities.Add(this.setStateActivity4); this.confirm_Cancel.Name = "confirm_Cancel"; // // confirm_Finish // this.confirm_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.confirm_Finish.Activities.Add(this.setStateActivity3); this.confirm_Finish.Name = "confirm_Finish"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.confirmDialogFormActivity1); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // deleteStateInitializationActivity // this.deleteStateInitializationActivity.Activities.Add(this.codeActivity1); this.deleteStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.deleteStateInitializationActivity.Activities.Add(this.setStateActivity1); this.deleteStateInitializationActivity.Name = "deleteStateInitializationActivity"; // // confirmStateActivity // this.confirmStateActivity.Activities.Add(this.stateInitializationActivity1); this.confirmStateActivity.Activities.Add(this.confirm_Finish); this.confirmStateActivity.Activities.Add(this.confirm_Cancel); this.confirmStateActivity.Name = "confirmStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity2); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // deleteStateActivity // this.deleteStateActivity.Activities.Add(this.deleteStateInitializationActivity); this.deleteStateActivity.Name = "deleteStateActivity"; // // DeleteUserControlFunctionWorkflow // this.Activities.Add(this.deleteStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.confirmStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "confirmStateActivity"; this.Name = "DeleteUserControlFunctionWorkflow"; this.CanModifyActivities = false; } #endregion private CodeActivity codeActivity1; private StateInitializationActivity deleteStateInitializationActivity; private SetStateActivity setStateActivity1; private SetStateActivity setStateActivity2; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private StateActivity finalStateActivity; private C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private EventDrivenActivity confirm_Cancel; private EventDrivenActivity confirm_Finish; private StateInitializationActivity stateInitializationActivity1; private StateActivity confirmStateActivity; private SetStateActivity setStateActivity4; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private StateActivity deleteStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserControlFunctionProviderElementProvider/DeleteUserControlFunctionWorkflow.cs ================================================ using System; using Composite.AspNet.Security; using Composite.C1Console.Workflow; using Composite.Core.IO; using Composite.Plugins.Functions.FunctionProviders.FileBasedFunctionProvider; using Composite.Plugins.Functions.FunctionProviders.UserControlFunctionProvider; using Composite.Plugins.Elements.ElementProviders.Common; namespace Composite.Plugins.Elements.ElementProviders.UserControlFunctionProviderElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteUserControlFunctionWorkflow : BaseFunctionWorkflow { public DeleteUserControlFunctionWorkflow() { InitializeComponent(); } private void codeActivity1_ExecuteCode(object sender, EventArgs e) { var functionEntityToken = (FileBasedFunctionEntityToken)EntityToken; FileBasedFunctionProvider<UserControlBasedFunction> provider; FileBasedFunction<UserControlBasedFunction> function; GetProviderAndFunction(functionEntityToken, out provider, out function); string markupFilePath = PathUtil.Resolve(function.VirtualPath); string codeFilePath = markupFilePath + ".cs"; C1File.Delete(markupFilePath); C1File.Delete(codeFilePath); DeleteEmptyAncestorFolders(markupFilePath); provider.ReloadFunctions(); RefreshFunctionTree(); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserControlFunctionProviderElementProvider/DeleteUserControlFunctionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="1011, 603" AutoSizeMargin="16, 24" AutoSize="False" Location="30, 30" Name="DeleteUserControlFunctionWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="DeleteUserControlFunctionWorkflow" TargetConnectionIndex="0" SourceStateName="DeleteUserControlFunctionWorkflow" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity_GlobalCancel" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="288" Y="71" /> <ns0:Point X="288" Y="452" /> <ns0:Point X="248" Y="452" /> <ns0:Point X="248" Y="464" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="deleteStateActivity" TargetConnectionIndex="0" SourceStateName="deleteStateActivity" SourceConnectionEdge="Right" EventHandlerName="deleteStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="260" Y="146" /> <ns0:Point X="288" Y="146" /> <ns0:Point X="288" Y="452" /> <ns0:Point X="248" Y="452" /> <ns0:Point X="248" Y="464" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="deleteStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" SourceConnectionEdge="Right" EventHandlerName="confirm_Finish" SourceConnectionIndex="1" TargetStateName="deleteStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="218" Y="303" /> <ns0:Point X="283" Y="303" /> <ns0:Point X="283" Y="97" /> <ns0:Point X="163" Y="97" /> <ns0:Point X="163" Y="105" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="confirmStateActivity" TargetConnectionIndex="0" SourceStateName="confirmStateActivity" SourceConnectionEdge="Right" EventHandlerName="confirm_Cancel" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="222" Y="327" /> <ns0:Point X="288" Y="327" /> <ns0:Point X="288" Y="452" /> <ns0:Point X="248" Y="452" /> <ns0:Point X="248" Y="464" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="201, 80" AutoSizeMargin="16, 24" Location="63, 105" Name="deleteStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="deleteStateInitializationActivity" Size="150, 242" Location="71, 136"> <StateInitializationDesigner.Designers> <CodeDesigner Name="codeActivity1" Size="130, 41" Location="81, 198" /> <ActivityDesigner Name="closeCurrentViewActivity1" Size="130, 41" Location="81, 258" /> <SetStateDesigner Name="setStateActivity1" Size="130, 41" Location="81, 318" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="160, 80" AutoSizeMargin="16, 24" Location="168, 464" Name="finalStateActivity" /> <EventDrivenDesigner Name="eventDrivenActivity_GlobalCancel" Size="150, 182" Location="38, 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130, 41" Location="48, 123" /> <SetStateDesigner Name="setStateActivity2" Size="130, 41" Location="48, 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="175, 118" AutoSizeMargin="16, 24" AutoSize="False" Location="101, 238" Name="confirmStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="stateInitializationActivity1" Size="150, 122" Location="460, 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="confirmDialogFormActivity1" Size="130, 41" Location="470, 210" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="confirm_Finish" Size="150, 182" Location="452, 159"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity2" Size="130, 41" Location="462, 221" /> <SetStateDesigner Name="setStateActivity3" Size="130, 41" Location="462, 281" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="confirm_Cancel" Size="150, 182" Location="452, 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130, 41" Location="462, 245" /> <SetStateDesigner Name="setStateActivity4" Size="130, 41" Location="462, 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserControlFunctionProviderElementProvider/EditUserControlFunctionWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Web.UI; using Composite.AspNet; using Composite.AspNet.Security; using Composite.C1Console.Events; using Composite.C1Console.Workflow; using Composite.Core; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.ResourceSystem; using Composite.Plugins.Elements.ElementProviders.Common; using Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider; using Composite.Plugins.Functions.FunctionProviders.FileBasedFunctionProvider; using Composite.Plugins.Functions.FunctionProviders.UserControlFunctionProvider; namespace Composite.Plugins.Elements.ElementProviders.UserControlFunctionProviderElementProvider { [EntityTokenLock] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditUserControlFunctionWorkflow : BaseFunctionWorkflow { private static readonly string LogTitle = typeof(EditUserControlFunctionWorkflow).Name; public EditUserControlFunctionWorkflow() { InitializeComponent(); } private string[] GetFiles(FileBasedFunction<UserControlBasedFunction> function) { var result = new List<string>(); string markupFilePath = PathUtil.Resolve(function.VirtualPath); result.Add(markupFilePath); string codeFile = markupFilePath + ".cs"; if(C1File.Exists(codeFile)) { result.Add(codeFile); } return result.ToArray(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { FileBasedFunctionProvider<UserControlBasedFunction> provider; FileBasedFunction<UserControlBasedFunction> function; GetProviderAndFunction((FileBasedFunctionEntityToken)this.EntityToken, out provider, out function); string title = Path.GetFileName(function.VirtualPath); this.Bindings.Add("Title", title); string[] files = GetFiles(function); // Binding all the files for(int i=0; i<files.Length; i++) { var websiteFile = new WebsiteFile(files[i]); string bindingPrefix = GetBindingPrefix(i); this.Bindings.Add(bindingPrefix + "Content", websiteFile.ReadAllText()); this.Bindings.Add(bindingPrefix + "Name", websiteFile.FileName); this.Bindings.Add(bindingPrefix + "MimeType", websiteFile.MimeType); } } private void saveCodeActivity_ExecuteCode(object sender, EventArgs e) { var functionEntityToken = (FileBasedFunctionEntityToken)this.EntityToken; FileBasedFunctionProvider<UserControlBasedFunction> provider; FileBasedFunction<UserControlBasedFunction> function; GetProviderAndFunction(functionEntityToken, out provider, out function); string[] files = GetFiles(function); var fileContent = new List<string>(); for (int i = 0; i < files.Length; i++) { string bindingPrefix = GetBindingPrefix(i); fileContent.Add(this.GetBinding<string>(bindingPrefix + "Content")); } string fixedMarkup = PageTemplateHelper.FixHtmlEscapeSequences(fileContent[0]); bool viewShouldBeUpdated = fixedMarkup != fileContent[0]; fileContent[0] = fixedMarkup; if (!CompileAndValidate(files, fileContent)) { SetSaveStatus(false); return; } for (int i = 0; i < files.Length; i++) { var websiteFile = new WebsiteFile(files[i]); websiteFile.WriteAllText(fileContent[i]); } provider.ReloadFunctions(); this.CreateParentTreeRefresher().PostRefreshMesseges(this.EntityToken); SetSaveStatus(true); if(viewShouldBeUpdated) { UpdateBinding(GetBindingPrefix(0) + "Content", fileContent[0]); RerenderView(); } } private static string GetBindingPrefix(int zeroBasedFileNumber) { return "File" + (zeroBasedFileNumber + 1); } private bool CompileAndValidate(string[] files, IList<string> fileContent) { string tempMarkupFile = GetTempFilePath(files[0]); string tempCodeBehindFile = null; string tempMarkupFileContent = fileContent[0]; if(files.Length > 1) { tempCodeBehindFile = GetTempFilePath(files[1]); string originalCsFileName = Path.GetFileName(files[1]); string newCsFileName = Path.GetFileName(tempCodeBehindFile); // Fixing the refecence to the CS file in the temporary created .ascx file so it will point // to the temporary CS file. Just string.Replace(), writing a sofisticated parser would be overkill int offset = tempMarkupFileContent.IndexOf(originalCsFileName, StringComparison.OrdinalIgnoreCase); if(offset > 0) { tempMarkupFileContent = tempMarkupFileContent.Substring(0, offset) + newCsFileName + tempMarkupFileContent.Substring(offset + originalCsFileName.Length); } } try { File.WriteAllText(tempMarkupFile, tempMarkupFileContent); if(tempCodeBehindFile != null) { File.WriteAllText(tempCodeBehindFile, fileContent[1]); } string virtualPath = "~" + PathUtil.GetWebsitePath(tempMarkupFile); try { var page = new Page(); Control control = page.LoadControl(virtualPath); if (!(control is UserControl)) { ShowWarning(GetText("EditUserControlFunctionWorkflow.Validation.IncorrectBaseClass") .FormatWith(typeof(UserControl).FullName)); return false; } } catch(Exception ex) { Log.LogWarning(LogTitle, "Failed to compile ASCX file"); Log.LogWarning(LogTitle, ex); Exception compilationException = (ex is TargetInvocationException) ? ex.InnerException : ex; // Replacing file path and temp file name from error message as it is irrelevant to the user string markupFileName = Path.GetFileName(files[0]); string errorMessage = compilationException.Message; if (errorMessage.StartsWith(tempMarkupFile, StringComparison.OrdinalIgnoreCase)) { errorMessage = markupFileName + errorMessage.Substring(tempMarkupFile.Length); } ShowWarning(GetText("EditUserControlFunctionWorkflow.Validation.CompilationFailed") .FormatWith(errorMessage)); return false; } return true; } finally { // Deleting temporary files File.Delete(tempMarkupFile); if (tempCodeBehindFile != null) { File.Delete(tempCodeBehindFile); } } } private void ShowWarning(string warning) { this.ShowMessage(DialogType.Warning, GetText("EditUserControlFunctionWorkflow.Validation.DialogTitle"), warning); } private string GetText(string text) { return StringResourceSystemFacade.GetString("Composite.Plugins.UserControlFunction", text); } private string GetTempFilePath(string filePath) { string fileName = Path.GetFileName(filePath); string folderPath = Path.GetDirectoryName(filePath); return Path.Combine(folderPath, "_temp_" + fileName); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserControlFunctionProviderElementProvider/EditUserControlFunctionWorkflow.designer.cs ================================================ using System.Workflow.Activities; namespace Composite.Plugins.Elements.ElementProviders.UserControlFunctionProviderElementProvider { partial class EditUserControlFunctionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.initialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // saveCodeActivity // this.saveCodeActivity.Name = "saveCodeActivity"; this.saveCodeActivity.ExecuteCode += new System.EventHandler(this.saveCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "saveStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.CustomToolbarDefinitionFileName = null; this.documentFormActivity1.FormDefinitionFileName = "/Administrative/EditUserControlFunction.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.saveCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // eventDrivenActivity_Save // this.eventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.eventDrivenActivity_Save.Activities.Add(this.setStateActivity3); this.eventDrivenActivity_Save.Name = "eventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initialStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity1); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.eventDrivenActivity_Save); this.editStateActivity.Name = "editStateActivity"; // // initialState // this.initialState.Activities.Add(this.initialStateInitializationActivity); this.initialState.Name = "initialState"; // // EditMasterPageWorkflow // this.Activities.Add(this.initialState); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelEventDrivenActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialState"; this.Name = "EditMasterPageWorkflow"; this.CanModifyActivities = false; } #endregion private CodeActivity initializeCodeActivity; private SetStateActivity setStateActivity1; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initialStateInitializationActivity; private EventDrivenActivity cancelEventDrivenActivity; private StateActivity finalStateActivity; private StateActivity saveStateActivity; private StateActivity editStateActivity; private C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private StateInitializationActivity editStateInitializationActivity; private StateInitializationActivity finalizeStateInitializationActivity; private CodeActivity saveCodeActivity; private SetStateActivity setStateActivity3; private C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity eventDrivenActivity_Save; private SetStateActivity setStateActivity4; private StateActivity initialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserElementProvider/AddNewUserWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Workflow.Runtime; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.Data; using Composite.Data.Types; using Composite.Core.ResourceSystem; using Composite.Core.Types; using Composite.C1Console.Users; using Composite.Data.Validation; using Composite.C1Console.Workflow; using Composite.C1Console.Events; using Composite.Plugins.Security.LoginProviderPlugins.DataBasedFormLoginProvider; using Microsoft.Practices.EnterpriseLibrary.Validation; using Composite.Core.Logging; using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.UserElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewUserWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { private static class BindingNames { public const string NewUser = "NewUser"; public const string Username = "NewUser.Username"; public const string Password = "Password"; public const string UserFormLogin = "UserFormLogin"; } public AddNewUserWorkflow() { InitializeComponent(); } private void CheckActiveLanguagesExists(object sender, ConditionalEventArgs e) { e.Result = DataLocalizationFacade.ActiveLocalizationCultures.Any(); } private void IsUserValid(object sender, ConditionalEventArgs e) { IUser newUser = this.GetBinding<IUser>(BindingNames.NewUser); var bindedUserFormLogin = this.GetBinding<IUserFormLogin>(BindingNames.UserFormLogin); NormalizeUsername(newUser); ValidationResults validationResults = ValidationFacade.Validate(newUser); bool isValid = validationResults.IsValid; if (isValid) { validationResults = ValidationFacade.Validate(bindedUserFormLogin); isValid = validationResults.IsValid; } if(isValid) { IQueryable<IUser> usersWithTheSameName = from user in DataFacade.GetData<IUser>() where string.Compare(user.Username, newUser.Username, StringComparison.InvariantCultureIgnoreCase) == 0 select user; if(usersWithTheSameName.Any()) { ShowFieldMessage(BindingNames.Username, LocalizationFiles.Composite_Management.UserElementProvider_UserLoginIsAlreadyUsed); isValid = false; } string password = this.GetBinding<string>(BindingNames.Password); IList<string> validationMessages; if (!PasswordPolicyFacade.ValidatePassword(newUser, password, out validationMessages)) { foreach (var message in validationMessages) { this.ShowFieldMessage(BindingNames.Password, message); } isValid = false; } } e.Result = isValid; } private void MissingActiveLanguageCodeActivity_ExecuteCode(object sender, EventArgs e) { var flowControllerServicesContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); var managementConsoleMessageService = flowControllerServicesContainer.GetService<IManagementConsoleMessageService>(); managementConsoleMessageService.ShowMessage( DialogType.Message, LocalizationFiles.Composite_Management.UserElementProvider_MissingActiveLanguageTitle, LocalizationFiles.Composite_Management.UserElementProvider_MissingActiveLanguageMessage); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { IUser newUser = DataFacade.BuildNew<IUser>(); newUser.Id = Guid.NewGuid(); var userFormLogin = DataFacade.BuildNew<IUserFormLogin>(); userFormLogin.PasswordHash = ""; userFormLogin.PasswordHashSalt = ""; var groupEntityToken = this.EntityToken as UserElementProviderGroupEntityToken; if (groupEntityToken != null) { userFormLogin.Folder = groupEntityToken.Id; } CultureInfo userCulture = UserSettings.CultureInfo; // Copy admins settings CultureInfo c1ConsoleUiLanguage = UserSettings.C1ConsoleUiLanguage; // Copy admins settings List<KeyValuePair> regionLanguageList = StringResourceSystemFacade.GetSupportedCulturesList(); Dictionary<string, string> culturesDictionary = StringResourceSystemFacade.GetAllCultures(); this.Bindings.Add(BindingNames.NewUser, newUser); this.Bindings.Add(BindingNames.UserFormLogin, userFormLogin); this.Bindings.Add("AllCultures", culturesDictionary); this.Bindings.Add("CultureName", userCulture.Name); this.Bindings.Add("C1ConsoleUiCultures", regionLanguageList); this.Bindings.Add("C1ConsoleUiLanguageName", c1ConsoleUiLanguage.Name); } private void step1CodeActivity_ExecuteCode(object sender, EventArgs e) { IUser newUser = this.GetBinding<IUser>(BindingNames.NewUser); NormalizeUsername(newUser); ValidationResults validationResults = ValidationFacade.Validate(newUser); foreach (ValidationResult result in validationResults) { this.ShowFieldMessage($"{BindingNames.NewUser}.{result.Key}", result.Message); } IQueryable<IUser> usersWithTheSameName = from user in DataFacade.GetData<IUser>() where string.Compare(user.Username, newUser.Username, StringComparison.InvariantCultureIgnoreCase) == 0 select user; if (usersWithTheSameName.Any()) { this.ShowFieldMessage(BindingNames.Username, LocalizationFiles.Composite_Management.AddNewUserWorkflow_UsernameDuplicateError); } } private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken); IUser newUser = this.GetBinding<IUser>(BindingNames.NewUser); var bindedUserFormLogin = this.GetBinding<IUserFormLogin>(BindingNames.UserFormLogin); NormalizeUsername(newUser); string password = this.GetBinding<string>(BindingNames.Password); newUser = DataFacade.AddNew<IUser>(newUser); UserFormLoginManager.CreateUserFormLogin(newUser.Id, password, bindedUserFormLogin.Folder); string cultureName = this.GetBinding<string>("CultureName"); string c1ConsoleUiLanguageName = this.GetBinding<string>("C1ConsoleUiLanguageName"); UserSettings.SetUserCultureInfo(newUser.Username, CultureInfo.CreateSpecificCulture(cultureName)); UserSettings.SetUserC1ConsoleUiLanguage(newUser.Username, CultureInfo.CreateSpecificCulture(c1ConsoleUiLanguageName)); CultureInfo locale = DataLocalizationFacade.DefaultLocalizationCulture; UserSettings.AddActiveLocaleCultureInfo(newUser.Username, locale); UserSettings.SetCurrentActiveLocaleCultureInfo(newUser.Username, locale); UserSettings.SetForeignLocaleCultureInfo(newUser.Username, locale); this.CloseCurrentView(); addNewTreeRefresher.PostRefreshMesseges(newUser.GetDataEntityToken()); LoggingService.LogEntry("UserManagement", $"New C1 Console user '{newUser.Username}' created by '{UserValidationFacade.GetUsername()}'.", LoggingService.Category.Audit, TraceEventType.Information); this.ExecuteWorklow(newUser.GetDataEntityToken(), typeof(EditUserWorkflow)); } private static void NormalizeUsername(IUser user) { // User names are lower-cased user.Username = user.Username.Trim().ToLowerInvariant(); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserElementProvider/AddNewUserWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.UserElementProvider { partial class AddNewUserWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.step1CodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.MissingActiveLanguageCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.ifElseActivity_ActiveLanguagesExists = new System.Workflow.Activities.IfElseActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.finishState = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "step1StateActivity"; // // step1CodeActivity // this.step1CodeActivity.Name = "step1CodeActivity"; this.step1CodeActivity.ExecuteCode += new System.EventHandler(this.step1CodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finishState"; // // MissingActiveLanguageCodeActivity // this.MissingActiveLanguageCodeActivity.Name = "MissingActiveLanguageCodeActivity"; this.MissingActiveLanguageCodeActivity.ExecuteCode += new System.EventHandler(this.MissingActiveLanguageCodeActivity_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.step1CodeActivity); this.ifElseBranchActivity2.Activities.Add(this.setStateActivity4); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity3); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsUserValid); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.MissingActiveLanguageCodeActivity); this.ifElseBranchActivity4.Activities.Add(this.setStateActivity7); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.initializeCodeActivity); this.ifElseBranchActivity3.Activities.Add(this.setStateActivity2); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckActiveLanguagesExists); this.ifElseBranchActivity3.Condition = codecondition2; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finishState"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ExecuteCode); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = null; this.wizzardFormActivity1.FormDefinitionFileName = "\\Administrative\\AddNewUserStep1.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // ifElseActivity_ActiveLanguagesExists // this.ifElseActivity_ActiveLanguagesExists.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity_ActiveLanguagesExists.Activities.Add(this.ifElseBranchActivity4); this.ifElseActivity_ActiveLanguagesExists.Name = "ifElseActivity_ActiveLanguagesExists"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity5); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity6); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.ifElseActivity1); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.wizzardFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.ifElseActivity_ActiveLanguagesExists); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // finishState // this.finishState.Name = "finishState"; // // AddNewUserWorkflow // this.Activities.Add(this.finishState); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finishState"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddNewUserWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity finishState; private StateInitializationActivity initializeStateInitializationActivity; private StateActivity initializeStateActivity; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private SetStateActivity setStateActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateInitializationActivity step1StateInitializationActivity; private StateActivity step1StateActivity; private Composite.C1Console.Workflow.Activities.DataDialogFormActivity wizzardFormActivity1; private CodeActivity initializeCodeActivity; private SetStateActivity setStateActivity4; private CodeActivity step1CodeActivity; private SetStateActivity setStateActivity3; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private StateInitializationActivity finalizeStateInitializationActivity; private StateActivity finalizeStateActivity; private CodeActivity finalizeCodeActivity; private SetStateActivity setStateActivity6; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElseActivity_ActiveLanguagesExists; private SetStateActivity setStateActivity7; private CodeActivity MissingActiveLanguageCodeActivity; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserElementProvider/AddNewUserWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="AddNewUserWorkflow" Location="30; 30" Size="840; 541" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="AddNewUserWorkflow" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="AddNewUserWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="581" Y="71" /> <ns0:Point X="581" Y="139" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="275" Y="164" /> <ns0:Point X="285" Y="164" /> <ns0:Point X="285" Y="282" /> <ns0:Point X="181" Y="282" /> <ns0:Point X="181" Y="294" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="275" Y="164" /> <ns0:Point X="291" Y="164" /> <ns0:Point X="291" Y="131" /> <ns0:Point X="581" Y="131" /> <ns0:Point X="581" Y="139" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="279" Y="359" /> <ns0:Point X="519" Y="359" /> <ns0:Point X="519" Y="413" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Bottom" SetStateName="setStateActivity4" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="279" Y="359" /> <ns0:Point X="293" Y="359" /> <ns0:Point X="293" Y="404" /> <ns0:Point X="181" Y="404" /> <ns0:Point X="181" Y="396" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="283" Y="383" /> <ns0:Point X="413" Y="383" /> <ns0:Point X="413" Y="131" /> <ns0:Point X="581" Y="131" /> <ns0:Point X="581" Y="139" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="0" TargetConnectionEdge="Bottom" SetStateName="setStateActivity5" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="618" Y="454" /> <ns0:Point X="629" Y="454" /> <ns0:Point X="629" Y="231" /> <ns0:Point X="581" Y="231" /> <ns0:Point X="581" Y="219" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="finishState" Location="501; 139" Size="160; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="initializeStateActivity" Location="69; 123" Size="210; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 363" Name="initializeStateInitializationActivity" Location="77; 154"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="361; 282" Name="ifElseActivity_ActiveLanguagesExists" Location="87; 216"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity3" Location="106; 287"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity" Location="116; 349" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="116; 409" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity4" Location="279; 287"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="MissingActiveLanguageCodeActivity" Location="289; 349" /> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="289; 409" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="step1StateActivity" Location="76; 294" Size="211; 102" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="84; 325"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="wizzardFormActivity1" Location="94; 387" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="381; 423" Name="step1EventDrivenActivity_Finish" Location="84; 349"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="209; 411" /> <IfElseDesigner Size="361; 282" Name="ifElseActivity1" Location="94; 471"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity1" Location="113; 542"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="123; 634" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity2" Location="286; 542"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="step1CodeActivity" Location="296; 604" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="296; 664" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="84; 373"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="94; 435" /> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="94; 495" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="417; 413" Size="205; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="finalizeStateInitializationActivity" Location="375; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity" Location="385; 210" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="385; 270" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="385; 330" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserElementProvider/DeleteUserWorkflow.cs ================================================ using System; using System.Diagnostics; using System.Workflow.Activities; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.Types; using Composite.Core.ResourceSystem; using Composite.C1Console.Security; using Composite.C1Console.Workflow; using Composite.Core.Logging; namespace Composite.Plugins.Elements.ElementProviders.UserElementProvider { [EntityTokenLock] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteUserWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { private bool _deleteSelf; public DeleteUserWorkflow() { InitializeComponent(); } private void IsDeleteSelf(object sender, ConditionalEventArgs e) { e.Result = _deleteSelf; } private void initializeCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { var dataEntityToken = (DataEntityToken)this.EntityToken; IUser user = (IUser)dataEntityToken.Data; _deleteSelf = user.Username == UserValidationFacade.GetUsername(); } private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { var dataEntityToken = (DataEntityToken)this.EntityToken; IUser user = (IUser)dataEntityToken.Data; if (!DataFacade.WillDeleteSucceed(user)) { this.ShowMessage( DialogType.Error, LocalizationFiles.Composite_Management.DeleteUserWorkflow_CascadeDeleteErrorTitle, LocalizationFiles.Composite_Management.DeleteUserWorkflow_CascadeDeleteErrorMessage); return; } UserPerspectiveFacade.DeleteAll(user.Username); DataFacade.Delete(user); LoggingService.LogEntry("UserManagement", $"C1 Console user '{user.Username}' deleted by '{UserValidationFacade.GetUsername()}'.", LoggingService.Category.Audit, TraceEventType.Information); this.CreateParentTreeRefresher().PostRefreshMessages(dataEntityToken, 2); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserElementProvider/DeleteUserWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.UserElementProvider { partial class DeleteUserWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.showConsoleMessageBoxActivity1 = new Composite.C1Console.Workflow.Activities.ShowConsoleMessageBoxActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step1WizzardFormActivity = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.initializeCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finishState = new System.Workflow.Activities.StateActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "step1StateActivity"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finishState"; // // showConsoleMessageBoxActivity1 // this.showConsoleMessageBoxActivity1.DialogType = Composite.C1Console.Events.DialogType.Error; this.showConsoleMessageBoxActivity1.Message = "${Composite.Management, DeleteUserWorkflow.DeleteSelfErrorMessage}"; this.showConsoleMessageBoxActivity1.Name = "showConsoleMessageBoxActivity1"; this.showConsoleMessageBoxActivity1.Title = "${Composite.Management, DeleteUserWorkflow.DeleteSelfTitle}"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity3); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.showConsoleMessageBoxActivity1); this.ifElseBranchActivity1.Activities.Add(this.setStateActivity6); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsDeleteSelf); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finishState"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // step1WizzardFormActivity // this.step1WizzardFormActivity.ContainerLabel = null; this.step1WizzardFormActivity.FormDefinitionFileName = "\\Administrative\\DeleteUserStep1.xml"; this.step1WizzardFormActivity.Name = "step1WizzardFormActivity"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // initializeCodeActivity_Initialize // this.initializeCodeActivity_Initialize.Name = "initializeCodeActivity_Initialize"; this.initializeCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_Initialize_ExecuteCode); // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity5); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity2); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1WizzardFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_Initialize); this.initializeStateInitializationActivity.Activities.Add(this.ifElseActivity1); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finishState // this.finishState.Name = "finishState"; // // DeleteUserWorkflow // this.Activities.Add(this.finishState); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finishState"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "DeleteUserWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity finishState; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity initializeStateActivity; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity step1WizzardFormActivity; private StateInitializationActivity step1StateInitializationActivity; private StateActivity step1StateActivity; private CodeActivity finalizeCodeActivity; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateActivity finalizeStateActivity; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private CodeActivity initializeCodeActivity_Initialize; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private SetStateActivity setStateActivity6; private Composite.C1Console.Workflow.Activities.ShowConsoleMessageBoxActivity showConsoleMessageBoxActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserElementProvider/DeleteUserWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="DeleteUserWorkflow" Location="30; 30" Size="1146; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="DeleteUserWorkflow" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="DeleteUserWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="642" Y="71" /> <ns0:Point X="642" Y="171" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="322" Y="198" /> <ns0:Point X="338" Y="198" /> <ns0:Point X="338" Y="163" /> <ns0:Point X="642" Y="163" /> <ns0:Point X="642" Y="171" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="322" Y="198" /> <ns0:Point X="336" Y="198" /> <ns0:Point X="336" Y="255" /> <ns0:Point X="288" Y="255" /> <ns0:Point X="288" Y="267" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="386" Y="332" /> <ns0:Point X="551" Y="332" /> <ns0:Point X="551" Y="389" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="390" Y="356" /> <ns0:Point X="406" Y="356" /> <ns0:Point X="406" Y="163" /> <ns0:Point X="642" Y="163" /> <ns0:Point X="642" Y="171" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="650" Y="430" /> <ns0:Point X="730" Y="430" /> <ns0:Point X="730" Y="163" /> <ns0:Point X="642" Y="163" /> <ns0:Point X="642" Y="171" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="finishState" Location="562; 171" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="116; 157" Size="210; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 423" Name="initializeStateInitializationActivity" Location="124; 188"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity_Initialize" Location="249; 250" /> <IfElseDesigner Size="361; 282" Name="ifElseActivity1" Location="134; 310"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity1" Location="153; 381"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="showConsoleMessageBoxActivity1" Location="163; 443" /> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="163; 503" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity2" Location="326; 381"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="336; 473" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="step1StateActivity" Location="183; 267" Size="211; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="191; 298"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step1WizzardFormActivity" Location="201; 360" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Finish" Location="191; 322"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="201; 384" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="201; 444" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="191; 346"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="201; 408" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="201; 468" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="449; 389" Size="205; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="finalizeStateInitializationActivity" Location="528; 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="538; 210" /> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity" Location="538; 270" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="538; 330" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserElementProvider/EditUserWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Workflow.Runtime; using System.Xml.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.Types; using Composite.C1Console.Elements; using Composite.C1Console.Forms; using Composite.C1Console.Forms.DataServices; using Composite.C1Console.Forms.Flows; using Composite.Core.ResourceSystem; using Composite.C1Console.Security; using Composite.Data.Transactions; using Composite.Core.Types; using Composite.C1Console.Users; using Composite.Data.Validation; using Composite.Data.Validation.ClientValidationRules; using Composite.C1Console.Workflow; using Composite.Core.Xml; using Composite.Plugins.Security.LoginProviderPlugins.DataBasedFormLoginProvider; using Microsoft.Practices.EnterpriseLibrary.Validation; using Composite.Core.Logging; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Management; namespace Composite.Plugins.Elements.ElementProviders.UserElementProvider { [EntityTokenLock] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditUserWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { private static string NotPassword { get { return Uri.UnescapeDataString("%C9%AF%C7%9D%C9%A5%CA%87pu%C4%B1qo%CA%87s%C9%AF%C9%94%C7%9Duo"); } } // should be a very unlikely real life password public EditUserWorkflow() { InitializeComponent(); } private static class BindingNames { public const string User = "User"; public const string UserFormLogin = "UserFormLogin"; public const string NewPassword = "NewPassword"; public const string ActiveContentLanguage = "ActiveLocaleName"; } private void CheckActiveLanguagesExists(object sender, System.Workflow.Activities.ConditionalEventArgs e) { e.Result = DataLocalizationFacade.ActiveLocalizationCultures.Any(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { var dataEntityToken = (DataEntityToken)this.EntityToken; var user = (IUser)dataEntityToken.Data; var userFormLogin = user.GetUserFormLogin(); this.Bindings.Add(BindingNames.User, user); this.Bindings.Add(BindingNames.UserFormLogin, userFormLogin); this.Bindings.Add(BindingNames.NewPassword, NotPassword); CultureInfo userCulture = UserSettings.GetUserCultureInfo(user.Username); CultureInfo c1ConsoleUiLanguage = UserSettings.GetUserC1ConsoleUiLanguage(user.Username); List<KeyValuePair> regionLanguageList = StringResourceSystemFacade.GetSupportedCulturesList(); Dictionary<string, string> culturesDictionary = StringResourceSystemFacade.GetAllCultures(); this.Bindings.Add("AllCultures", culturesDictionary); this.Bindings.Add("CultureName", userCulture.Name); this.Bindings.Add("C1ConsoleUiCultures", regionLanguageList); this.Bindings.Add("C1ConsoleUiLanguageName", c1ConsoleUiLanguage.Name); var currentActiveCulture = UserSettings.GetCurrentActiveLocaleCultureInfo(user.Username); this.Bindings.Add("ActiveLocaleName", currentActiveCulture != null ? currentActiveCulture.Name : null); this.Bindings.Add("ActiveLocaleList", DataLocalizationFacade.ActiveLocalizationCultures.ToDictionary(f => f.Name, DataLocalizationFacade.GetCultureTitle)); var clientValidationRules = new Dictionary<string, List<ClientValidationRule>> { {"Username", ClientValidationRuleFacade.GetClientValidationRules(user, "Username")}, {"Group", ClientValidationRuleFacade.GetClientValidationRules(user, "Group")} }; IFormMarkupProvider markupProvider = new FormDefinitionFileMarkupProvider(@"\Administrative\EditUserStep1.xml"); XDocument formDocument; using (var reader = markupProvider.GetReader()) { formDocument = XDocument.Load(reader); } XElement bindingsElement = formDocument.Root.Element(DataTypeDescriptorFormsHelper.CmsNamespace + FormKeyTagNames.Bindings); XElement layoutElement = formDocument.Root.Element(DataTypeDescriptorFormsHelper.CmsNamespace + FormKeyTagNames.Layout); XElement tabPanelsElement = layoutElement.Element(DataTypeDescriptorFormsHelper.MainNamespace + "TabPanels"); List<XElement> placeHolderElements = tabPanelsElement.Elements(DataTypeDescriptorFormsHelper.MainNamespace + "PlaceHolder").ToList(); UpdateFormDefinitionWithUserGroups(user, bindingsElement, placeHolderElements[1]); UpdateFormDefinitionWithActivePerspectives(user, bindingsElement, placeHolderElements[2]); //UpdateFormDefinitionWithGlobalPermissions(user, bindingsElement, placeHolderElements[1]); if (DataLocalizationFacade.ActiveLocalizationCultures.Any()) { UpdateFormDefinitionWithActiveLocales(user, bindingsElement, placeHolderElements[1]); } string formDefinition = formDocument.GetDocumentAsString(); this.DeliverFormData( user.Username, StandardUiContainerTypes.Document, formDefinition, this.Bindings, clientValidationRules ); } private void UpdateFormDefinitionWithActivePerspectives(IUser user, XElement bindingsElement, XElement placeHolderElement) { List<string> serializedEntityToken = UserPerspectiveFacade.GetSerializedEntityTokens(user.Username).ToList(); var helper = new ActivePerspectiveFormsHelper( GetText("Website.Forms.Administrative.EditUserStep1.ActivePerspectiveFieldLabel"), GetText("Website.Forms.Administrative.EditUserStep1.ActivePerspectiveMultiSelectLabel"), GetText("Website.Forms.Administrative.EditUserStep1.ActivePerspectiveMultiSelectHelp") ); bindingsElement.Add(helper.GetBindingsMarkup()); placeHolderElement.Add(helper.GetFormMarkup()); helper.UpdateWithNewBindings(this.Bindings, serializedEntityToken); } private void UpdateFormDefinitionWithActiveLocales(IUser user, XElement bindingsElement, XElement placeHolderElement) { var helper = new ActiveLocalesFormsHelper( GetText("Website.Forms.Administrative.EditUserStep1.ActiveLocalesFieldLabel"), GetText("Website.Forms.Administrative.EditUserStep1.ActiveLocalesMultiSelectLabel"), GetText("Website.Forms.Administrative.EditUserStep1.ActiveLocalesMultiSelectHelp") ); bindingsElement.Add(helper.GetBindingsMarkup()); placeHolderElement.Add(helper.GetFormMarkup()); helper.UpdateWithNewBindings(this.Bindings, UserSettings.GetActiveLocaleCultureInfos(user.Username, false)); } private void UpdateFormDefinitionWithUserGroups(IUser user, XElement bindingsElement, XElement placeHolderElement) { var helper = new UserGroupsFormsHelper( GetText("Website.Forms.Administrative.EditUserStep1.UserGroupsFieldLabel"), GetText("Website.Forms.Administrative.EditUserStep1.UserGroupsMultiSelectHelp") ); bindingsElement.Add(helper.GetBindingsMarkup()); placeHolderElement.Add(helper.GetFormMarkup()); List<Guid> relations = DataFacade.GetData<IUserUserGroupRelation>(f => f.UserId == user.Id).Select(f => f.UserGroupId).ToList(); helper.UpdateWithNewBindings(this.Bindings, relations); } private void saveCodeActivity_ExecuteCode(object sender, EventArgs e) { IUser user = this.GetBinding<IUser>(BindingNames.User); var userFormLogin = GetBinding<IUserFormLogin>(BindingNames.UserFormLogin); var userFormLoginFromDatabase = user.GetUserFormLogin(); bool userValidated = true; ValidationResults validationResults = ValidationFacade.Validate(user); foreach (ValidationResult result in validationResults) { this.ShowFieldMessage($"{BindingNames.User}.{result.Key}", result.Message); userValidated = false; } List<CultureInfo> newActiveLocales = ActiveLocalesFormsHelper.GetSelectedLocalesTypes(this.Bindings).ToList(); List<CultureInfo> currentActiveLocales = UserSettings.GetActiveLocaleCultureInfos(user.Username, false).ToList(); string selectedActiveLocaleName = this.GetBinding<string>("ActiveLocaleName"); CultureInfo selectedActiveLocale = CultureInfo.CreateSpecificCulture(selectedActiveLocaleName); string systemPerspectiveEntityToken = EntityTokenSerializer.Serialize(AttachingPoint.SystemPerspective.EntityToken); List<Guid> newUserGroupIds = UserGroupsFormsHelper.GetSelectedUserGroupIds(this.Bindings); List<string> newSerializedEnitityTokens = ActivePerspectiveFormsHelper.GetSelectedSerializedEntityTokens(this.Bindings).ToList(); if (string.Compare(user.Username, UserSettings.Username, StringComparison.InvariantCultureIgnoreCase) == 0) { // Current user shouldn't be able to lock itself if (userFormLogin.IsLocked) { this.ShowMessage(DialogType.Message, Texts.EditUserWorkflow_EditErrorTitle, Texts.EditUserWorkflow_LockingOwnUserAccount); userValidated = false; } // Current user shouldn't be able to remove its own access to "System" perspective var groupsWithAccessToSystemPerspective = new HashSet<Guid>(GetGroupsThatHasAccessToPerspective(systemPerspectiveEntityToken)); if (!newSerializedEnitityTokens.Contains(systemPerspectiveEntityToken) && !newUserGroupIds.Any(groupsWithAccessToSystemPerspective.Contains)) { this.ShowMessage(DialogType.Message, Texts.EditUserWorkflow_EditErrorTitle, Texts.EditUserWorkflow_EditOwnAccessToSystemPerspective); userValidated = false; } } string newPassword = this.GetBinding<string>(BindingNames.NewPassword); if (newPassword == NotPassword || UserFormLoginManager.ValidatePassword(userFormLoginFromDatabase, newPassword)) { newPassword = null; } else { IList<string> validationMessages; if (!PasswordPolicyFacade.ValidatePassword(user, newPassword, out validationMessages)) { foreach (var message in validationMessages) { this.ShowFieldMessage(BindingNames.NewPassword, message); } userValidated = false; } } if (!userValidated) { return; } if (!userFormLogin.IsLocked) { userFormLogin.LockoutReason = (int)UserLockoutReason.Undefined; } else { bool wasLockedBefore = userFormLoginFromDatabase.IsLocked; if (!wasLockedBefore) { userFormLoginFromDatabase.LockoutReason = (int)UserLockoutReason.LockedByAdministrator; } } UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken); bool reloadUsersConsoles = false; using (var transactionScope = TransactionsFacade.CreateNewScope()) { DataFacade.Update(user); userFormLoginFromDatabase.Folder = userFormLogin.Folder; userFormLoginFromDatabase.IsLocked = userFormLogin.IsLocked; DataFacade.Update(userFormLoginFromDatabase); if (newPassword != null) { UserFormLoginManager.SetPassword(userFormLoginFromDatabase, newPassword); } string cultureName = this.GetBinding<string>("CultureName"); string c1ConsoleUiLanguageName = this.GetBinding<string>("C1ConsoleUiLanguageName"); UserSettings.SetUserCultureInfo(user.Username, CultureInfo.CreateSpecificCulture(cultureName)); UserSettings.SetUserC1ConsoleUiLanguage(user.Username, CultureInfo.CreateSpecificCulture(c1ConsoleUiLanguageName)); List<string> existingSerializedEntityTokens = UserPerspectiveFacade.GetSerializedEntityTokens(user.Username).ToList(); int intersectCount = existingSerializedEntityTokens.Intersect(newSerializedEnitityTokens).Count(); if ((intersectCount != newSerializedEnitityTokens.Count) || (intersectCount != existingSerializedEntityTokens.Count)) { UserPerspectiveFacade.SetSerializedEntityTokens(user.Username, newSerializedEnitityTokens); if (UserSettings.Username == user.Username) { reloadUsersConsoles = true; } } if (DataLocalizationFacade.ActiveLocalizationCultures.Any()) { foreach (CultureInfo cultureInfo in newActiveLocales) { if (!currentActiveLocales.Contains(cultureInfo)) { UserSettings.AddActiveLocaleCultureInfo(user.Username, cultureInfo); } } foreach (CultureInfo cultureInfo in currentActiveLocales) { if (!newActiveLocales.Contains(cultureInfo)) { UserSettings.RemoveActiveLocaleCultureInfo(user.Username, cultureInfo); } } if (selectedActiveLocale != null) { if (!selectedActiveLocale.Equals(UserSettings.GetCurrentActiveLocaleCultureInfo(user.Username))) { reloadUsersConsoles = true; } UserSettings.SetCurrentActiveLocaleCultureInfo(user.Username, selectedActiveLocale); } else if (UserSettings.GetActiveLocaleCultureInfos(user.Username).Any()) { UserSettings.SetCurrentActiveLocaleCultureInfo(user.Username, UserSettings.GetActiveLocaleCultureInfos(user.Username).First()); } } List<IUserUserGroupRelation> oldRelations = DataFacade.GetData<IUserUserGroupRelation>(f => f.UserId == user.Id).ToList(); IEnumerable<IUserUserGroupRelation> deleteRelations = from r in oldRelations where !newUserGroupIds.Contains(r.UserGroupId) select r; DataFacade.Delete(deleteRelations); foreach (Guid newUserGroupId in newUserGroupIds) { Guid groupId = newUserGroupId; if (oldRelations.Any(f => f.UserGroupId == groupId)) continue; var userUserGroupRelation = DataFacade.BuildNew<IUserUserGroupRelation>(); userUserGroupRelation.UserId = user.Id; userUserGroupRelation.UserGroupId = newUserGroupId; DataFacade.AddNew(userUserGroupRelation); } LoggingService.LogEntry("UserManagement", $"C1 Console user '{user.Username}' updated by '{UserValidationFacade.GetUsername()}'.", LoggingService.Category.Audit, TraceEventType.Information); transactionScope.Complete(); } if (UserSettings.GetCurrentActiveLocaleCultureInfo(user.Username) == null) { this.ShowFieldMessage(BindingNames.ActiveContentLanguage, "The user doesn't have permissions to access the language you selected here. Assign permissions so the user may access this."); this.ShowMessage(DialogType.Warning, "User missing permissions for language", "The user doesn't have permissions to access the language you selected as 'Active content language'."); } else { if (reloadUsersConsoles) { foreach (string consoleId in GetConsoleIdsOpenedByUser(user.Username)) { ConsoleMessageQueueFacade.Enqueue(new RebootConsoleMessageQueueItem(), consoleId); } } } SetSaveStatus(true); updateTreeRefresher.PostRefreshMesseges(user.GetDataEntityToken()); } private List<Guid> GetGroupsThatHasAccessToPerspective(string usersPerspectiveEntityToken) { return DataFacade.GetData<IUserGroupActivePerspective>() .Where(ug => ug.SerializedEntityToken == usersPerspectiveEntityToken) .Select(ug => ug.UserGroupId).ToList(); } private void IsUserLoggedOn(object sender, System.Workflow.Activities.ConditionalEventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; IUser user = (IUser)dataEntityToken.Data; string selectedActiveLocaleName = (user.Username != UserSettings.Username ? this.GetBinding<string>("ActiveLocaleName") : UserSettings.ActiveLocaleCultureInfo.ToString()); if (selectedActiveLocaleName != null) { CultureInfo selectedActiveLocale = CultureInfo.CreateSpecificCulture(selectedActiveLocaleName); if (!selectedActiveLocale.Equals(UserSettings.GetCurrentActiveLocaleCultureInfo(user.Username))) { e.Result = ConsoleFacade.GetConsoleIdsByUsername(user.Username).Any(); return; } } e.Result = false; } private void IsSameUser(object sender, System.Workflow.Activities.ConditionalEventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; IUser user = (IUser)dataEntityToken.Data; e.Result = user.Username == UserSettings.Username; } private void MissingActiveLanguageCodeActivity_ExecuteCode(object sender, EventArgs e) { FlowControllerServicesContainer flowControllerServicesContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); var managementConsoleMessageService = flowControllerServicesContainer.GetService<IManagementConsoleMessageService>(); managementConsoleMessageService.ShowMessage( DialogType.Message, GetText("UserElementProvider.MissingActiveLanguageTitle"), GetText("UserElementProvider.MissingActiveLanguageMessage")); } private string GetText(string key) { return StringResourceSystemFacade.GetString("Composite.Management", key); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserElementProvider/EditUserWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.UserElementProvider { partial class EditUserWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition3 = new System.Workflow.Activities.CodeCondition(); this.showConsoleMessageBoxActivity2 = new Composite.C1Console.Workflow.Activities.ShowConsoleMessageBoxActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseActivity_IsUserLoggedOn = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.MissingActiveLanguageCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity6 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity5 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.ifElseActivity_ActiveLanguagesExists = new System.Workflow.Activities.IfElseActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1SventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.initializeActivity = new System.Workflow.Activities.StateActivity(); this.finishState = new System.Workflow.Activities.StateActivity(); // // showConsoleMessageBoxActivity2 // this.showConsoleMessageBoxActivity2.DialogType = Composite.C1Console.Events.DialogType.Message; this.showConsoleMessageBoxActivity2.Message = "${Composite.Management, UserElementProvider.ChangeOtherActiveLocaleMessage}"; this.showConsoleMessageBoxActivity2.Name = "showConsoleMessageBoxActivity2"; this.showConsoleMessageBoxActivity2.Title = "${Composite.Management, UserElementProvider.ChangeOtherActiveLocaleTitle}"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.showConsoleMessageBoxActivity2); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsUserLoggedOn); this.ifElseBranchActivity3.Condition = codecondition1; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // ifElseActivity_IsUserLoggedOn // this.ifElseActivity_IsUserLoggedOn.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity_IsUserLoggedOn.Activities.Add(this.ifElseBranchActivity4); this.ifElseActivity_IsUserLoggedOn.Name = "ifElseActivity_IsUserLoggedOn"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finishState"; // // MissingActiveLanguageCodeActivity // this.MissingActiveLanguageCodeActivity.Name = "MissingActiveLanguageCodeActivity"; this.MissingActiveLanguageCodeActivity.ExecuteCode += new System.EventHandler(this.MissingActiveLanguageCodeActivity_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.ifElseActivity_IsUserLoggedOn); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsSameUser); this.ifElseBranchActivity1.Condition = codecondition2; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // ifElseBranchActivity6 // this.ifElseBranchActivity6.Activities.Add(this.MissingActiveLanguageCodeActivity); this.ifElseBranchActivity6.Activities.Add(this.setStateActivity5); this.ifElseBranchActivity6.Name = "ifElseBranchActivity6"; // // ifElseBranchActivity5 // this.ifElseBranchActivity5.Activities.Add(this.initializeCodeActivity); this.ifElseBranchActivity5.Activities.Add(this.setStateActivity2); codecondition3.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckActiveLanguagesExists); this.ifElseBranchActivity5.Condition = codecondition3; this.ifElseBranchActivity5.Name = "ifElseBranchActivity5"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "step1StateActivity"; // // saveCodeActivity // this.saveCodeActivity.Name = "saveCodeActivity"; this.saveCodeActivity.ExecuteCode += new System.EventHandler(this.saveCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "saveStateActivity"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // ifElseActivity_ActiveLanguagesExists // this.ifElseActivity_ActiveLanguagesExists.Activities.Add(this.ifElseBranchActivity5); this.ifElseActivity_ActiveLanguagesExists.Activities.Add(this.ifElseBranchActivity6); this.ifElseActivity_ActiveLanguagesExists.Name = "ifElseActivity_ActiveLanguagesExists"; // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.saveCodeActivity); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity4); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // step1SventDrivenActivity_Save // this.step1SventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.step1SventDrivenActivity_Save.Activities.Add(this.ifElseActivity1); this.step1SventDrivenActivity_Save.Activities.Add(this.setStateActivity3); this.step1SventDrivenActivity_Save.Name = "step1SventDrivenActivity_Save"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.ifElseActivity_ActiveLanguagesExists); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.saveStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1SventDrivenActivity_Save); this.step1StateActivity.Name = "step1StateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // initializeActivity // this.initializeActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeActivity.Name = "initializeActivity"; // // finishState // this.finishState.Name = "finishState"; // // EditUserWorkflow // this.Activities.Add(this.finishState); this.Activities.Add(this.initializeActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.saveStateActivity); this.CompletedStateName = "finishState"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeActivity"; this.Name = "EditUserWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity finishState; private StateInitializationActivity initializeStateInitializationActivity; private StateActivity initializeActivity; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private SetStateActivity setStateActivity1; private StateActivity saveStateActivity; private StateActivity step1StateActivity; private StateInitializationActivity saveStateInitializationActivity; private EventDrivenActivity step1SventDrivenActivity_Save; private StateInitializationActivity step1StateInitializationActivity; private CodeActivity initializeCodeActivity; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElseActivity_IsUserLoggedOn; private Composite.C1Console.Workflow.Activities.ShowConsoleMessageBoxActivity showConsoleMessageBoxActivity2; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private IfElseBranchActivity ifElseBranchActivity6; private IfElseBranchActivity ifElseBranchActivity5; private IfElseActivity ifElseActivity_ActiveLanguagesExists; private SetStateActivity setStateActivity5; private CodeActivity MissingActiveLanguageCodeActivity; private CodeActivity saveCodeActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserElementProvider/EditUserWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="EditUserWorkflow" Location="30; 30" Size="1217; 996" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="EditUserWorkflow" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="EditUserWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="790" Y="71" /> <ns0:Point X="790" Y="195" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="257" Y="142" /> <ns0:Point X="302" Y="142" /> <ns0:Point X="302" Y="253" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="initializeActivity" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="initializeActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="257" Y="142" /> <ns0:Point X="790" Y="142" /> <ns0:Point X="790" Y="195" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="saveStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Bottom" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="saveStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1SventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="397" Y="318" /> <ns0:Point X="418" Y="318" /> <ns0:Point X="418" Y="346" /> <ns0:Point X="550" Y="346" /> <ns0:Point X="550" Y="338" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="saveStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="saveStateActivity" EventHandlerName="saveStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="637" Y="299" /> <ns0:Point X="662" Y="299" /> <ns0:Point X="662" Y="245" /> <ns0:Point X="302" Y="245" /> <ns0:Point X="302" Y="253" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="finishState" Location="710; 195" Size="160; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="initializeActivity" Location="51; 101" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 363" Name="initializeStateInitializationActivity" Location="59; 132"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="361; 282" Name="ifElseActivity_ActiveLanguagesExists" Location="69; 194"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity5" Location="88; 265"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity" Location="98; 327" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="98; 387" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity6" Location="261; 265"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="MissingActiveLanguageCodeActivity" Location="271; 327" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="271; 387" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="step1StateActivity" Location="199; 253" Size="207; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 109" Name="step1StateInitializationActivity" Location="324; 135" /> <EventDrivenDesigner Size="612; 604" Name="step1SventDrivenActivity_Save" Location="332; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="saveHandleExternalEventActivity1" Location="573; 210" /> <IfElseDesigner Size="592; 403" Name="ifElseActivity1" Location="342; 270"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 303" Name="ifElseBranchActivity1" Location="361; 341" /> <IfElseBranchDesigner Size="381; 303" Name="ifElseBranchActivity2" Location="534; 341"> <IfElseBranchDesigner.Designers> <IfElseDesigner Size="361; 222" Name="ifElseActivity_IsUserLoggedOn" Location="544; 403"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity3" Location="563; 474"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="showConsoleMessageBoxActivity2" Location="573; 536" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity4" Location="736; 474" /> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="573; 692" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="saveStateActivity" Location="448; 258" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="saveStateInitializationActivity" Location="456; 289"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="saveCodeActivity" Location="466; 351" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="466; 411" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserGroupElementProvider/AddNewUserGroupWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.UserGroupElementProvider { partial class AddNewUserGroupWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.showDataValidateErrorCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.showGroupValidationErrorCodeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElseActivity2 = new System.Workflow.Activities.IfElseActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ValidateGroupName_step1IfElseBranchActivity = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Finalize = new System.Workflow.Activities.CodeActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step1WizardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.globalEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "step1StateActivity"; // // showDataValidateErrorCodeActivity // this.showDataValidateErrorCodeActivity.Name = "showDataValidateErrorCodeActivity"; this.showDataValidateErrorCodeActivity.ExecuteCode += new System.EventHandler(this.ShowDataValidateErrorCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.showDataValidateErrorCodeActivity); this.ifElseBranchActivity3.Activities.Add(this.setStateActivity6); this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity3); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateData); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "step1StateActivity"; // // showGroupValidationErrorCodeActivity // this.showGroupValidationErrorCodeActivity.Name = "showGroupValidationErrorCodeActivity"; this.showGroupValidationErrorCodeActivity.ExecuteCode += new System.EventHandler(this.ShowGroupValidationError); // // ifElseActivity2 // this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity2.Name = "ifElseActivity2"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.showGroupValidationErrorCodeActivity); this.ifElseBranchActivity2.Activities.Add(this.setStateActivity4); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ValidateGroupName_step1IfElseBranchActivity // this.ValidateGroupName_step1IfElseBranchActivity.Activities.Add(this.ifElseActivity2); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateGroupName); this.ValidateGroupName_step1IfElseBranchActivity.Condition = codecondition2; this.ValidateGroupName_step1IfElseBranchActivity.Name = "ValidateGroupName_step1IfElseBranchActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalActivity"; // // finalizeCodeActivity_Finalize // this.finalizeCodeActivity_Finalize.Name = "finalizeCodeActivity_Finalize"; this.finalizeCodeActivity_Finalize.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Finalize_ExecuteCode); // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ValidateGroupName_step1IfElseBranchActivity); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // step1WizardFormActivity // this.step1WizardFormActivity.ContainerLabel = null; this.step1WizardFormActivity.FormDefinitionFileName = "\\Administrative\\UserGroupElementProviderAddNewUserGroupStep1.xml"; this.step1WizardFormActivity.Name = "step1WizardFormActivity"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // initializeCodeActivity_Initialize // this.initializeCodeActivity_Initialize.Name = "initializeCodeActivity_Initialize"; this.initializeCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_Initialize_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Finalize); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity1); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.ifElseActivity1); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1WizardFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_Initialize); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // globalEventDrivenActivity_Cancel // this.globalEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.globalEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity5); this.globalEventDrivenActivity_Cancel.Name = "globalEventDrivenActivity_Cancel"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Name = "step1StateActivity"; // // finalActivity // this.finalActivity.Name = "finalActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // AddNewUserGroupWorkflow // this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.globalEventDrivenActivity_Cancel); this.CompletedStateName = "finalActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddNewUserGroupWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity finalActivity; private StateActivity step1StateActivity; private StateActivity finalizeStateActivity; private StateInitializationActivity initializeStateInitializationActivity; private StateInitializationActivity step1StateInitializationActivity; private StateInitializationActivity finalizeStateInitializationActivity; private SetStateActivity setStateActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity step1EventDrivenActivity_Finish; private SetStateActivity setStateActivity3; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ValidateGroupName_step1IfElseBranchActivity; private IfElseActivity ifElseActivity1; private CodeActivity showGroupValidationErrorCodeActivity; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.WizardFormActivity step1WizardFormActivity; private CodeActivity initializeCodeActivity_Initialize; private CodeActivity finalizeCodeActivity_Finalize; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity globalEventDrivenActivity_Cancel; private SetStateActivity setStateActivity5; private IfElseBranchActivity ifElseBranchActivity3; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity2; private SetStateActivity setStateActivity6; private CodeActivity showDataValidateErrorCodeActivity; private StateActivity initializeStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserGroupElementProvider/AddNewUserGroupWorkflow.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; using Composite.Data.Types; using Composite.Data; using Composite.Core.ResourceSystem; using Composite.C1Console.Actions; using Composite.Data.Validation; using Microsoft.Practices.EnterpriseLibrary.Validation; using Composite.Core.Logging; using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.UserGroupElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewUserGroupWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddNewUserGroupWorkflow() { InitializeComponent(); } private void initializeCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { IUserGroup userGroup = DataFacade.BuildNew<IUserGroup>(); userGroup.Id = Guid.NewGuid(); this.Bindings.Add("NewUserGroup", userGroup); } private void ValidateGroupName(object sender, ConditionalEventArgs e) { IUserGroup userGroup = this.GetBinding<IUserGroup>("NewUserGroup"); bool exists = (from ug in DataFacade.GetData<IUserGroup>() where ug.Name == userGroup.Name select ug).Any(); e.Result = exists == false; } private void ShowGroupValidationError(object sender, EventArgs e) { this.ShowFieldMessage( "NewUserGroup.Name", StringResourceSystemFacade.GetString("Composite.Plugins.UserGroupElementProvider", "AddNewUserGroup.AddNewUserGroupStep1.UserGroupNameAlreadyExists")); } private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e) { AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken); IUserGroup userGroup = this.GetBinding<IUserGroup>("NewUserGroup"); userGroup = DataFacade.AddNew<IUserGroup>(userGroup); this.CloseCurrentView(); LoggingService.LogEntry("UserManagement", $"New C1 Console user group '{userGroup.Name}' created by '{UserValidationFacade.GetUsername()}'.", LoggingService.Category.Audit, TraceEventType.Information); addNewTreeRefresher.PostRefreshMesseges(userGroup.GetDataEntityToken()); this.ExecuteWorklow(userGroup.GetDataEntityToken(), typeof(EditUserGroupWorkflow)); } private void ValidateData(object sender, ConditionalEventArgs e) { IUserGroup userGroup = this.GetBinding<IUserGroup>("NewUserGroup"); ValidationResults validationResults = ValidationFacade.Validate<IUserGroup>(userGroup); e.Result = validationResults.IsValid; } private void ShowDataValidateErrorCodeActivity_ExecuteCode(object sender, EventArgs e) { IUserGroup userGroup = this.GetBinding<IUserGroup>("NewUserGroup"); ValidationResults validationResults = ValidationFacade.Validate<IUserGroup>(userGroup); this.ShowFieldMessage( "NewUserGroup.Name", validationResults.First().Message); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserGroupElementProvider/AddNewUserGroupWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="AddNewUserGroupWorkflow" Location="30; 30" Size="1153; 996" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="AddNewUserGroupWorkflow" SourceConnectionEdge="Right" TargetActivity="finalActivity" SourceActivity="AddNewUserGroupWorkflow" EventHandlerName="globalEventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="239" Y="71" /> <ns0:Point X="824" Y="71" /> <ns0:Point X="824" Y="583" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="252" Y="142" /> <ns0:Point X="379" Y="142" /> <ns0:Point X="379" Y="197" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="479" Y="262" /> <ns0:Point X="661" Y="262" /> <ns0:Point X="661" Y="366" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="487" Y="169" /> <ns0:Point X="499" Y="169" /> <ns0:Point X="499" Y="96" /> <ns0:Point X="387" Y="96" /> <ns0:Point X="387" Y="104" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="760" Y="407" /> <ns0:Point X="824" Y="407" /> <ns0:Point X="824" Y="583" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initializeStateActivity" Location="46; 101" Size="227; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initializeStateInitializationActivity" Location="54; 132"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity_Initialize" Location="64; 194" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="64; 254" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalActivity" Location="744; 583" Size="160; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="step1StateActivity" Location="276; 197" Size="207; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="292; 135"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step1WizardFormActivity" Location="302; 197" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="612; 604" Name="step1EventDrivenActivity_Finish" Location="300; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="541; 210" /> <IfElseDesigner Size="592; 463" Name="ifElseActivity1" Location="310; 270"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="381; 363" Name="ValidateGroupName_step1IfElseBranchActivity" Location="329; 341"> <IfElseBranchDesigner.Designers> <IfElseDesigner Size="361; 282" Name="ifElseActivity2" Location="339; 403"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity1" Location="358; 474"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="368; 566" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity3" Location="531; 474"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="showDataValidateErrorCodeActivity" Location="541; 536" /> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="541; 596" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 363" Name="ifElseBranchActivity2" Location="733; 341"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="showGroupValidationErrorCodeActivity" Location="743; 403" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="743; 463" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="559; 366" Size="205; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="finalizeStateInitializationActivity" Location="567; 397"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity_Finalize" Location="577; 459" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="577; 519" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <EventDrivenDesigner Size="150; 182" Name="globalEventDrivenActivity_Cancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserGroupElementProvider/DeleteUserGroupWorkflow.cs ================================================ using System; using System.Diagnostics; using System.Linq; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Actions; using System.Workflow.Activities; using Composite.C1Console.Events; using Composite.Core.ResourceSystem; using Composite.Core.Logging; using Composite.C1Console.Security; namespace Composite.Plugins.Elements.ElementProviders.UserGroupElementProvider { public sealed partial class DeleteUserGroupWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeleteUserGroupWorkflow() { InitializeComponent(); } private void HasUsers(object sender, ConditionalEventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; IUserGroup userGroup = (IUserGroup)dataEntityToken.Data; e.Result = DataFacade.GetData<IUserUserGroupRelation>(f => f.UserGroupId == userGroup.Id).Any(); } private void initializeCodeActivity_ShowMessage_ExecuteCode(object sender, EventArgs e) { ShowMessage(DialogType.Message, StringResourceSystemFacade.GetString("Composite.Plugins.UserGroupElementProvider", "DeleteUserGroup.DeleteUserGroupInitialStep.UserGroupHasUsersTitle"), StringResourceSystemFacade.GetString("Composite.Plugins.UserGroupElementProvider", "DeleteUserGroup.DeleteUserGroupInitialStep.UserGroupHasUsersMessage") ); } private void finalizeCodeActivity_Delete_ExecuteCode(object sender, EventArgs e) { DeleteTreeRefresher deleteTreeRefresher = CreateDeleteTreeRefresher(this.EntityToken); DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; IUserGroup userGroup = (IUserGroup)dataEntityToken.Data; DataFacade.Delete(userGroup); LoggingService.LogEntry("UserManagement", $"C1 Console user group '{userGroup.Name}' deleted by '{UserValidationFacade.GetUsername()}'.", LoggingService.Category.Audit, TraceEventType.Information); deleteTreeRefresher.PostRefreshMesseges(); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserGroupElementProvider/DeleteUserGroupWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.UserGroupElementProvider { partial class DeleteUserGroupWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_ShowMessage = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_Delete = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.step1ConfirmDialogFormActivity = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.ifElseActivity_HasUsers = new System.Workflow.Activities.IfElseActivity(); this.finalizesStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivit_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "step1StateActivity"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // initializeCodeActivity_ShowMessage // this.initializeCodeActivity_ShowMessage.Name = "initializeCodeActivity_ShowMessage"; this.initializeCodeActivity_ShowMessage.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ShowMessage_ExecuteCode); // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity5); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.initializeCodeActivity_ShowMessage); this.ifElseBranchActivity1.Activities.Add(this.setStateActivity6); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.HasUsers); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // finalizeCodeActivity_Delete // this.finalizeCodeActivity_Delete.Name = "finalizeCodeActivity_Delete"; this.finalizeCodeActivity_Delete.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_Delete_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // step1ConfirmDialogFormActivity // this.step1ConfirmDialogFormActivity.ContainerLabel = null; this.step1ConfirmDialogFormActivity.FormDefinitionFileName = "\\Administrative\\UserGroupElementProviderDeleteUserGroupStep1.xml"; this.step1ConfirmDialogFormActivity.Name = "step1ConfirmDialogFormActivity"; // // ifElseActivity_HasUsers // this.ifElseActivity_HasUsers.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity_HasUsers.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity_HasUsers.Name = "ifElseActivity_HasUsers"; // // finalizesStateInitializationActivity // this.finalizesStateInitializationActivity.Activities.Add(this.finalizeCodeActivity_Delete); this.finalizesStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizesStateInitializationActivity.Name = "finalizesStateInitializationActivity"; // // step1EventDrivenActivit_Cancel // this.step1EventDrivenActivit_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivit_Cancel.Activities.Add(this.setStateActivity2); this.step1EventDrivenActivit_Cancel.Name = "step1EventDrivenActivit_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity3); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1ConfirmDialogFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.ifElseActivity_HasUsers); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizesStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivit_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // DeleteUserGroupWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "DeleteUserGroupWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private StateInitializationActivity finalizesStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivit_Cancel; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateInitializationActivity step1StateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity2; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity step1ConfirmDialogFormActivity; private CodeActivity finalizeCodeActivity_Delete; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity_HasUsers; private SetStateActivity setStateActivity6; private CodeActivity initializeCodeActivity_ShowMessage; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserGroupElementProvider/DeleteUserGroupWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="DeleteUserGroupWorkflow" Location="30; 30" Size="1217; 996" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="DeleteUserGroupWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="DeleteUserGroupWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="393" Y="179" /> <ns0:Point X="393" Y="353" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="493" Y="418" /> <ns0:Point X="659" Y="418" /> <ns0:Point X="659" Y="517" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivit_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="491" Y="442" /> <ns0:Point X="1058" Y="442" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizesStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="760" Y="558" /> <ns0:Point X="1058" Y="558" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 363" Name="initializeStateInitializationActivity" Location="448; 148"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="361; 282" Name="ifElseActivity_HasUsers" Location="458; 210"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity1" Location="477; 281"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity_ShowMessage" Location="487; 343" /> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="487; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity2" Location="650; 281"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="660; 373" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="step1StateActivity" Location="290; 353" Size="207; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="298; 384"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step1ConfirmDialogFormActivity" Location="308; 446" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Finish" Location="298; 408"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="308; 470" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="308; 530" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivit_Cancel" Location="298; 432"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="308; 494" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="308; 554" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="554; 517" Size="210; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="finalizesStateInitializationActivity" Location="562; 548"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity_Delete" Location="572; 610" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="572; 670" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserGroupElementProvider/EditUserGroupWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Workflow.Activities; using System.Xml.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Users; using Composite.Core.Logging; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.Types; using Composite.C1Console.Elements; using Composite.C1Console.Forms; using Composite.C1Console.Forms.DataServices; using Composite.C1Console.Forms.Flows; using Composite.C1Console.Security; using Composite.Plugins.Elements.ElementProviders.UserElementProvider; using Composite.Data.Validation; using Composite.Data.Validation.ClientValidationRules; using Composite.Core.Xml; using Microsoft.Practices.EnterpriseLibrary.Validation; using SR = Composite.Core.ResourceSystem.StringResourceSystemFacade; namespace Composite.Plugins.Elements.ElementProviders.UserGroupElementProvider { public sealed partial class EditUserGroupWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditUserGroupWorkflow() { InitializeComponent(); } private void initalizeCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; IUserGroup userGroup = (IUserGroup)dataEntityToken.Data; this.Bindings.Add("UserGroup", userGroup); this.Bindings.Add("OldName", userGroup.Name); } private void step1CodeActivity_ShowDocument_ExecuteCode(object sender, EventArgs e) { IFormMarkupProvider markupProvider = new FormDefinitionFileMarkupProvider(@"\Administrative\UserGroupElementProviderEditUserGroupStep1.xml"); XDocument formDocument; using (var reader = markupProvider.GetReader()) { formDocument = XDocument.Load(reader); } XElement bindingsElement = formDocument.Root.Element(DataTypeDescriptorFormsHelper.CmsNamespace + FormKeyTagNames.Bindings); XElement layoutElement = formDocument.Root.Element(DataTypeDescriptorFormsHelper.CmsNamespace + FormKeyTagNames.Layout); XElement placeHolderElement = layoutElement.Element(DataTypeDescriptorFormsHelper.MainNamespace + "PlaceHolder"); IUserGroup userGroup = this.GetBinding<IUserGroup>("UserGroup"); UpdateFormDefinitionWithActivePerspectives(userGroup, bindingsElement, placeHolderElement); UpdateFormDefinitionWithGlobalPermissions(userGroup, bindingsElement, placeHolderElement); UpdateFormDefinitionWithActiveLocalePermissions(userGroup, bindingsElement, placeHolderElement); var clientValidationRules = new Dictionary<string, List<ClientValidationRule>>(); clientValidationRules.Add("Name", ClientValidationRuleFacade.GetClientValidationRules(userGroup, "Name")); string formDefinition = formDocument.GetDocumentAsString(); this.DeliverFormData( userGroup.Name, StandardUiContainerTypes.Document, formDefinition, this.Bindings, clientValidationRules ); } private void ValidateGroupName(object sender, ConditionalEventArgs e) { IUserGroup userGroup = this.GetBinding<IUserGroup>("UserGroup"); if (userGroup.Name == this.GetBinding<string>("OldName")) { e.Result = true; return; } bool exists = (from ug in DataFacade.GetData<IUserGroup>() where ug.Name == userGroup.Name select ug).Any(); e.Result = !exists; } private void ShowGroupValidationError(object sender, EventArgs e) { this.ShowFieldMessage( "UserGroup.Name", SR.GetString("Composite.Plugins.UserGroupElementProvider", "EditUserGroup.EditUserGroupStep1.UserGroupNameAlreadyExists")); } private void saveCodeActivity_Save_ExecuteCode(object sender, EventArgs e) { IUserGroup userGroup = this.GetBinding<IUserGroup>("UserGroup"); List<string> newUserGroupEntityTokens = ActivePerspectiveFormsHelper.GetSelectedSerializedEntityTokens(this.Bindings).ToList(); // If current user belongs to currently edited group -> checking that user won't lost access "Users" perspective if (!ValidateUserPreservesAdminRights(userGroup, newUserGroupEntityTokens)) { return; } UpdateTreeRefresher updateTreeRefresher = CreateUpdateTreeRefresher(this.EntityToken); EntityToken rootEntityToken = ElementFacade.GetRootsWithNoSecurity().Select(f => f.ElementHandle.EntityToken).Single(); IEnumerable<PermissionType> newPermissionTypes = GlobalPermissionsFormsHelper.GetSelectedPermissionTypes(this.Bindings); UserGroupPermissionDefinition userGroupPermissionDefinition = new ConstructorBasedUserGroupPermissionDefinition( userGroup.Id, newPermissionTypes, EntityTokenSerializer.Serialize(rootEntityToken) ); PermissionTypeFacade.SetUserGroupPermissionDefinition(userGroupPermissionDefinition); UserGroupPerspectiveFacade.SetSerializedEntityTokens(userGroup.Id, newUserGroupEntityTokens); List<CultureInfo> selectedUserGroupActiveLocales = ActiveLocalesFormsHelper.GetSelectedLocalesTypes(this.Bindings).ToList(); using (var connection = new DataConnection()) { var existingLocales = connection.Get<IUserGroupActiveLocale>().Where(f=> f.UserGroupId == userGroup.Id).ToList(); var toDelete = existingLocales.Where(f => !selectedUserGroupActiveLocales.Contains(new CultureInfo(f.CultureName))); connection.Delete<IUserGroupActiveLocale>(toDelete); foreach (var localeToAdd in selectedUserGroupActiveLocales.Where(f => !existingLocales.Any(g => g.CultureName == f.Name))) { var toAdd = connection.CreateNew<IUserGroupActiveLocale>(); toAdd.Id = Guid.NewGuid(); toAdd.UserGroupId = userGroup.Id; toAdd.CultureName = localeToAdd.Name; connection.Add(toAdd); } } SetSaveStatus(true); LoggingService.LogEntry("UserManagement", $"C1 Console user group '{userGroup.Name}' updated by '{UserValidationFacade.GetUsername()}'.", LoggingService.Category.Audit, TraceEventType.Information); if (userGroup.Name != this.GetBinding<string>("OldName")) { DataFacade.Update(userGroup); this.UpdateBinding("OldName", userGroup.Name); updateTreeRefresher.PostRefreshMesseges(userGroup.GetDataEntityToken()); } } private bool ValidateUserPreservesAdminRights(IUserGroup userGroup, List<string> newUserGroupEntityTokens) { string systemPerspectiveEntityToken = EntityTokenSerializer.Serialize(AttachingPoint.SystemPerspective.EntityToken); Guid groupId = userGroup.Id; string userName = UserSettings.Username; var userGroupIds = UserGroupFacade.GetUserGroupIds(userName); HashSet<Guid> groupsWithAccessToSystemPerspective = new HashSet<Guid>(GetGroupsThatHasAccessToPerspective(systemPerspectiveEntityToken)); if (groupsWithAccessToSystemPerspective.Contains(groupId) && !newUserGroupEntityTokens.Contains(systemPerspectiveEntityToken) && !UserPerspectiveFacade.GetSerializedEntityTokens(userName).Contains(systemPerspectiveEntityToken) && !userGroupIds.Any(anotherGroupId => anotherGroupId != groupId && groupsWithAccessToSystemPerspective.Contains(anotherGroupId))) { this.ShowMessage(DialogType.Message, SR.GetString("Composite.Management", "EditUserWorkflow.EditErrorTitle"), SR.GetString("Composite.Management", "EditUserWorkflow.EditOwnAccessToSystemPerspective")); return false; } return true; } private List<Guid> GetGroupsThatHasAccessToPerspective(string usersPerspectiveEntityToken) { return DataFacade.GetData<IUserGroupActivePerspective>() .Where(ug => ug.SerializedEntityToken == usersPerspectiveEntityToken) .Select(ug => ug.UserGroupId).ToList(); } private void UpdateFormDefinitionWithGlobalPermissions(IUserGroup userGroup, XElement bindingsElement, XElement placeHolderElement) { var helper = new GlobalPermissionsFormsHelper( SR.GetString("Composite.Plugins.UserGroupElementProvider", "EditUserGroup.EditUserGroupStep1.GlobalPermissionsFieldLabel"), SR.GetString("Composite.Plugins.UserGroupElementProvider", "EditUserGroup.EditUserGroupStep1.GlobalPermissionsMultiSelectLabel"), SR.GetString("Composite.Plugins.UserGroupElementProvider", "EditUserGroup.EditUserGroupStep1.GlobalPermissionsMultiSelectHelp") ); bindingsElement.Add(helper.GetBindingsMarkup()); placeHolderElement.Add(helper.GetFormMarkup()); EntityToken rootEntityToken = ElementFacade.GetRootsWithNoSecurity().Select(f => f.ElementHandle.EntityToken).Single(); IEnumerable<PermissionType> permissionTypes = PermissionTypeFacade.GetLocallyDefinedUserGroupPermissionTypes(userGroup.Id, rootEntityToken).ToList(); helper.UpdateWithNewBindings(this.Bindings, permissionTypes); } private void UpdateFormDefinitionWithActiveLocalePermissions(IUserGroup userGroup, XElement bindingsElement, XElement placeHolderElement) { var helper = new ActiveLocalesFormsHelper( SR.GetString("Composite.Plugins.UserGroupElementProvider", "EditUserGroup.EditUserGroupStep1.ActiveLocalesFieldLabel"), SR.GetString("Composite.Plugins.UserGroupElementProvider", "EditUserGroup.EditUserGroupStep1.ActiveLocalesMultiSelectLabel"), SR.GetString("Composite.Plugins.UserGroupElementProvider", "EditUserGroup.EditUserGroupStep1.ActiveLocalesMultiSelectHelp") ); bindingsElement.Add(helper.GetBindingsMarkup()); placeHolderElement.Add(helper.GetFormMarkup()); EntityToken rootEntityToken = ElementFacade.GetRootsWithNoSecurity().Select(f => f.ElementHandle.EntityToken).Single(); using (var connection = new DataConnection()) { IEnumerable<CultureInfo> activeCultures = null; activeCultures = connection.Get<IUserGroupActiveLocale>().Where(f => f.UserGroupId == userGroup.Id).Select(f => new CultureInfo(f.CultureName)); helper.UpdateWithNewBindings(this.Bindings, activeCultures); } } private void UpdateFormDefinitionWithActivePerspectives(IUserGroup userGroup, XElement bindingsElement, XElement placeHolderElement) { List<string> serializedEntityToken = UserGroupPerspectiveFacade.GetSerializedEntityTokens(userGroup.Id).ToList(); var helper = new ActivePerspectiveFormsHelper( SR.GetString("Composite.Plugins.UserGroupElementProvider", "EditUserGroup.EditUserGroupStep1.ActivePerspectiveFieldLabel"), SR.GetString("Composite.Plugins.UserGroupElementProvider", "EditUserGroup.EditUserGroupStep1.ActivePerspectiveMultiSelectLabel"), SR.GetString("Composite.Plugins.UserGroupElementProvider", "EditUserGroup.EditUserGroupStep1.ActivePerspectiveMultiSelectHelp") ); bindingsElement.Add(helper.GetBindingsMarkup()); placeHolderElement.Add(helper.GetFormMarkup()); helper.UpdateWithNewBindings(this.Bindings, serializedEntityToken); } private void ValidateData(object sender, ConditionalEventArgs e) { IUserGroup userGroup = this.GetBinding<IUserGroup>("UserGroup"); ValidationResults validationResults = ValidationFacade.Validate<IUserGroup>(userGroup); e.Result = validationResults.IsValid; if (!validationResults.IsValid) { this.ShowFieldMessage( "UserGroup.Name", validationResults.First().Message); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserGroupElementProvider/EditUserGroupWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.UserGroupElementProvider { partial class EditUserGroupWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition3 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.step1CodeActivity_ShowErrorMessage = new System.Workflow.Activities.CodeActivity(); this.ifElseActivity2 = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity_Save = new System.Workflow.Activities.CodeActivity(); this.step1DocumentFormActivity = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.step1CodeActivity_ShowDocument = new System.Workflow.Activities.CodeActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.conditionalSetStateActivity1 = new Composite.C1Console.Workflow.Activities.ConditionalSetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.initalizeCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "step1StateActivity"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "saveStateActivity"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity7); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.setStateActivity6); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateData); this.ifElseBranchActivity3.Condition = codecondition1; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // step1CodeActivity_ShowErrorMessage // this.step1CodeActivity_ShowErrorMessage.Name = "step1CodeActivity_ShowErrorMessage"; this.step1CodeActivity_ShowErrorMessage.ExecuteCode += new System.EventHandler(this.ShowGroupValidationError); // // ifElseActivity2 // this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity4); this.ifElseActivity2.Name = "ifElseActivity2"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "saveStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.step1CodeActivity_ShowErrorMessage); this.ifElseBranchActivity2.Activities.Add(this.setStateActivity2); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity4); this.ifElseBranchActivity1.Activities.Add(this.ifElseActivity2); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateGroupName); this.ifElseBranchActivity1.Condition = codecondition2; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "step1StateActivity"; // // saveCodeActivity_Save // this.saveCodeActivity_Save.Name = "saveCodeActivity_Save"; this.saveCodeActivity_Save.ExecuteCode += new System.EventHandler(this.saveCodeActivity_Save_ExecuteCode); // // step1DocumentFormActivity // this.step1DocumentFormActivity.ContainerLabel = null; this.step1DocumentFormActivity.CustomToolbarDefinitionFileName = null; this.step1DocumentFormActivity.Enabled = false; this.step1DocumentFormActivity.FormDefinitionFileName = "\\Administrative\\UserGroupElementProviderEditUserGroupStep1.xml"; this.step1DocumentFormActivity.Name = "step1DocumentFormActivity"; // // step1CodeActivity_ShowDocument // this.step1CodeActivity_ShowDocument.Name = "step1CodeActivity_ShowDocument"; this.step1CodeActivity_ShowDocument.ExecuteCode += new System.EventHandler(this.step1CodeActivity_ShowDocument_ExecuteCode); // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // conditionalSetStateActivity1 // codecondition3.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ValidateData); this.conditionalSetStateActivity1.Condition = codecondition3; this.conditionalSetStateActivity1.FalseTargetStateName = "step1StateActivity"; this.conditionalSetStateActivity1.Name = "conditionalSetStateActivity1"; this.conditionalSetStateActivity1.TrueTargetStateName = "saveStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "step1StateActivity"; // // initalizeCodeActivity_Initialize // this.initalizeCodeActivity_Initialize.Name = "initalizeCodeActivity_Initialize"; this.initalizeCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initalizeCodeActivity_Initialize_ExecuteCode); // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.saveCodeActivity_Save); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity5); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.step1CodeActivity_ShowDocument); this.step1StateInitializationActivity.Activities.Add(this.step1DocumentFormActivity); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // step1EventDrivenActivity_Save // this.step1EventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.step1EventDrivenActivity_Save.Activities.Add(this.conditionalSetStateActivity1); this.step1EventDrivenActivity_Save.Activities.Add(this.ifElseActivity1); this.step1EventDrivenActivity_Save.Name = "step1EventDrivenActivity_Save"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initalizeCodeActivity_Initialize); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity3); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.saveStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Save); this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // EditUserGroupWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.saveStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "EditUserGroupWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private EventDrivenActivity step1EventDrivenActivity_Save; private StateActivity step1StateActivity; private CodeActivity step1CodeActivity_ShowErrorMessage; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity3; private StateInitializationActivity saveStateInitializationActivity; private StateInitializationActivity step1StateInitializationActivity; private StateActivity saveStateActivity; private Composite.C1Console.Workflow.Activities.DocumentFormActivity step1DocumentFormActivity; private CodeActivity initalizeCodeActivity_Initialize; private CodeActivity saveCodeActivity_Save; private CodeActivity step1CodeActivity_ShowDocument; private SetStateActivity setStateActivity7; private SetStateActivity setStateActivity6; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElseActivity2; private Composite.C1Console.Workflow.Activities.ConditionalSetStateActivity conditionalSetStateActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/UserGroupElementProvider/EditUserGroupWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="EditUserGroupWorkflow" Location="30; 30" Size="1153; 996" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="EditUserGroupWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="EditUserGroupWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="479" Y="179" /> <ns0:Point X="479" Y="433" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="saveStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="saveStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="576" Y="498" /> <ns0:Point X="592" Y="498" /> <ns0:Point X="592" Y="280" /> <ns0:Point X="743" Y="280" /> <ns0:Point X="743" Y="288" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="482" Y="169" /> <ns0:Point X="497" Y="169" /> <ns0:Point X="497" Y="96" /> <ns0:Point X="385" Y="96" /> <ns0:Point X="385" Y="104" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="saveStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="saveStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="576" Y="498" /> <ns0:Point X="592" Y="498" /> <ns0:Point X="592" Y="280" /> <ns0:Point X="743" Y="280" /> <ns0:Point X="743" Y="288" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="482" Y="169" /> <ns0:Point X="497" Y="169" /> <ns0:Point X="497" Y="96" /> <ns0:Point X="385" Y="96" /> <ns0:Point X="385" Y="104" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="saveStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="saveStateActivity" EventHandlerName="saveStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="836" Y="329" /> <ns0:Point X="847" Y="329" /> <ns0:Point X="847" Y="421" /> <ns0:Point X="479" Y="421" /> <ns0:Point X="479" Y="433" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initalizeCodeActivity_Initialize" Location="108; 231" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="108; 291" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="step1StateActivity" Location="378; 433" Size="202; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <EventDrivenDesigner Size="612; 664" Name="step1EventDrivenActivity_Save" Location="300; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="saveHandleExternalEventActivity1" Location="541; 210" /> <ActivityDesigner Size="130; 41" Name="conditionalSetStateActivity1" Location="541; 270" /> <IfElseDesigner Size="592; 463" Name="ifElseActivity1" Location="310; 330"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="381; 363" Name="ifElseBranchActivity1" Location="329; 401"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="454; 463" /> <IfElseDesigner Size="361; 222" Name="ifElseActivity2" Location="339; 523"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity3" Location="358; 594"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="368; 656" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity4" Location="531; 594"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="541; 656" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 363" Name="ifElseBranchActivity2" Location="733; 401"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="step1CodeActivity_ShowErrorMessage" Location="743; 463" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="743; 523" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateInitializationDesigner Size="150; 182" Name="step1StateInitializationActivity" Location="292; 135"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="step1CodeActivity_ShowDocument" Location="302; 197" /> <ActivityDesigner Size="130; 41" Name="step1DocumentFormActivity" Location="302; 257" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="saveStateActivity" Location="647; 288" Size="193; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="saveStateInitializationActivity" Location="655; 319"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="saveCodeActivity_Save" Location="665; 381" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="665; 441" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/VisualFunctionProviderElementProvider/AddNewVisualFunctionWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Workflow.Activities; using System.Xml.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.Core.PageTemplates; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.Types; using Composite.Functions; using Composite.Core.Extensions; using Composite.Core.ResourceSystem; using Composite.Core.Types; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.Core.Xml; namespace Composite.Plugins.Elements.ElementProviders.VisualFunctionProviderElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewVisualFunctionWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddNewVisualFunctionWorkflow() { InitializeComponent(); } private void CheckPageTemplatesExists(object sender, ConditionalEventArgs e) { e.Result = PageTemplateFacade.ValidTemplateExists; } private void CheckActiveLanguageExists(object sender, ConditionalEventArgs e) { e.Result = UserSettings.ActiveLocaleCultureInfo != null; } private void MissingActiveLanguageActivity_ExecuteCode(object sender, EventArgs e) { ShowMessage( DialogType.Message, StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "AddNew.MissingActiveLanguageTitle"), StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "AddNew.MissingActiveLanguageMessage")); } private void stepInitialize_codeActivity_ExecuteCode(object sender, EventArgs e) { List<Type> dataTypes = DataFacade.GetAllInterfaces(UserType.Developer); dataTypes.RemoveAll(t => t.FullName.StartsWith("Composite.Data.Types")); this.Bindings = new Dictionary<string, object> { {"SelectedType", typeof (IData)}, {"TypeOptions", dataTypes} }; } private void prepareFunctionObject_codeActivity_ExecuteCode(object sender, EventArgs e) { DataTypeDescriptor dataTypeDescriptor = GetDataTypeDescriptor(); var function = DataFacade.BuildNew<IVisualFunction>(); function.Id = Guid.NewGuid(); function.Name = FunctionFacade.BuildUniqueFunctionName(dataTypeDescriptor.Namespace, string.Format("{0}Rendering", dataTypeDescriptor.Name)); function.Namespace = dataTypeDescriptor.Namespace; function.TypeManagerName = dataTypeDescriptor.TypeManagerTypeName; function.Description = ""; this.UpdateBinding("Function", function); } private DataTypeDescriptor GetDataTypeDescriptor() { Type sourceDataType = GetSourceDataType(); DataTypeDescriptor dataTypeDescriptor = null; if (DynamicTypeManager.TryGetDataTypeDescriptor(sourceDataType, out dataTypeDescriptor) == false) { dataTypeDescriptor = DynamicTypeManager.BuildNewDataTypeDescriptor(sourceDataType); } return dataTypeDescriptor; } private Type GetSourceDataType() { return this.GetBinding<Type>("SelectedType"); } private void stepFinalize_codeActivity_ExecuteCode(object sender, EventArgs e) { AddNewTreeRefresher updateTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken); IVisualFunction newFunction = this.GetBinding<IVisualFunction>("Function"); newFunction.MaximumItemsToList = 10; newFunction.OrderbyAscending = true; newFunction.OrderbyFieldName = (GetDataTypeDescriptor().LabelFieldName ?? GetDataTypeDescriptor().Fields.First().Name); XhtmlDocument defaultDocument = BuildDefaultDocument(newFunction); newFunction.XhtmlTemplate = defaultDocument.ToString(); updateTreeRefresher.PostRefreshMesseges(this.EntityToken); var createdFunction = DataFacade.AddNew<IVisualFunction>(newFunction); this.ExecuteWorklow(createdFunction.GetDataEntityToken(), typeof(EditVisualFunctionWorkflow)); } private static XhtmlDocument BuildDefaultDocument(IVisualFunction newFunction) { XElement htmlTable = new XElement(Namespaces.Xhtml + "table"); Type interfaceType = TypeManager.GetType(newFunction.TypeManagerName); DataTypeDescriptor typeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(interfaceType); foreach (DataFieldDescriptor dataField in typeDescriptor.Fields.OrderBy(f => f.Position)) { if (!typeDescriptor.KeyPropertyNames.Contains(dataField.Name) && dataField.FormRenderingProfile != null && !string.IsNullOrEmpty(dataField.FormRenderingProfile.Label)) { string fieldMarkup = string.Format("<data:fieldreference fieldname=\"{0}\" typemanagername=\"{1}\" xmlns:data=\"{2}\" />", dataField.Name, newFunction.TypeManagerName, Namespaces.DynamicData10); htmlTable.Add(new XElement(Namespaces.Xhtml + "tr", new XElement(Namespaces.Xhtml + "td", dataField.FormRenderingProfile.Label), new XElement(Namespaces.Xhtml + "td", XElement.Parse(fieldMarkup)))); } } XhtmlDocument defaultDocument = new XhtmlDocument(); defaultDocument.Body.Add(htmlTable); return defaultDocument; } private void CheckFunctionNameIsUnique(object sender, ConditionalEventArgs e) { IVisualFunction function = this.GetBinding<IVisualFunction>("Function"); string functionFullName = $"{function.Namespace}.{function.Name}"; e.Result = !FunctionFacade.FunctionNames.Contains(functionFullName); } private void CheckDataExists(object sender, ConditionalEventArgs e) { Type type = GetSourceDataType(); e.Result = DataFacade.GetData(type).Any(); } private void CheckTypesExists(object sender, ConditionalEventArgs e) { e.Result = (this.GetBinding<List<Type>>("TypeOptions")).Count > 0; } private void CheckTypeNameIsDynamicType(object sender, ConditionalEventArgs e) { Type type = GetSourceDataType(); Guid immutableTypeId; e.Result = type != null && type.TryGetImmutableTypeId(out immutableTypeId); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/VisualFunctionProviderElementProvider/AddNewVisualFunctionWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.VisualFunctionProviderElementProvider { partial class AddNewVisualFunctionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition3 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition4 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition5 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition6 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.MissingPageActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity9 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.missingDataMessageBoxActivity = new Composite.C1Console.Workflow.Activities.ShowConsoleMessageBoxActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity1 = new System.Workflow.Activities.CodeActivity(); this.abortFlowSetStateActivity = new System.Workflow.Activities.SetStateActivity(); this.noTypesMessageBoxActivity = new Composite.C1Console.Workflow.Activities.ShowConsoleMessageBoxActivity(); this.ifElseActivity_CheckPageExists = new System.Workflow.Activities.IfElseActivity(); this.ifElseBranchActivity6 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranch_heckDataExists = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity8 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity7 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.showFieldMessageActivity2 = new Composite.C1Console.Workflow.Activities.ShowFieldMessageActivity(); this.ifElseActivity2 = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity12 = new System.Workflow.Activities.SetStateActivity(); this.showConsoleMessageBoxActivity_NoTemplate = new Composite.C1Console.Workflow.Activities.ShowConsoleMessageBoxActivity(); this.ifElseActivity3 = new System.Workflow.Activities.IfElseActivity(); this.backTostep2 = new System.Workflow.Activities.SetStateActivity(); this.showFieldMessageActivity1 = new Composite.C1Console.Workflow.Activities.ShowFieldMessageActivity(); this.setStateActivity11 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranch_CheckTypeNameIsDynamicType = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity11 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity10 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.handleExternalEventActivity1 = new System.Workflow.Activities.HandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.ifElseActivity5 = new System.Workflow.Activities.IfElseActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifNameUniqueActivity1 = new System.Workflow.Activities.IfElseActivity(); this.handleExternalEventActivity3 = new System.Workflow.Activities.HandleExternalEventActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.handleExternalEventActivity2 = new System.Workflow.Activities.HandleExternalEventActivity(); this.step2WizzardFormActivity = new Composite.C1Console.Workflow.Activities.WizardFormActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.stepFinalize_codeActivity = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.step1_eventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1_eventDrivenActivity_Next = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity19 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step2_eventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step2_eventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step2_eventDrivenActivity_Previous = new System.Workflow.Activities.EventDrivenActivity(); this.step2StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1State = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.initializeActivity = new System.Workflow.Activities.StateActivity(); this.step2State = new System.Workflow.Activities.StateActivity(); this.finalizeActivity = new System.Workflow.Activities.StateActivity(); this.finishState = new System.Workflow.Activities.StateActivity(); // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "finishState"; // // MissingPageActivity // this.MissingPageActivity.Name = "MissingPageActivity"; this.MissingPageActivity.ExecuteCode += new System.EventHandler(this.MissingActiveLanguageActivity_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "step1State"; // // ifElseBranchActivity9 // this.ifElseBranchActivity9.Activities.Add(this.MissingPageActivity); this.ifElseBranchActivity9.Activities.Add(this.setStateActivity9); this.ifElseBranchActivity9.Name = "ifElseBranchActivity9"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.setStateActivity4); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckActiveLanguageExists); this.ifElseBranchActivity3.Condition = codecondition1; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "step1State"; // // missingDataMessageBoxActivity // this.missingDataMessageBoxActivity.DialogType = Composite.C1Console.Events.DialogType.Error; this.missingDataMessageBoxActivity.Message = "${Composite.Plugins.VisualFunction,AddNew.NoDataExistsErrorMessage}"; this.missingDataMessageBoxActivity.Name = "missingDataMessageBoxActivity"; this.missingDataMessageBoxActivity.Title = "${Composite.Plugins.VisualFunction,AddNew.NoDataExistsErrorTitle}"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "step2State"; // // codeActivity1 // this.codeActivity1.Name = "codeActivity1"; this.codeActivity1.ExecuteCode += new System.EventHandler(this.prepareFunctionObject_codeActivity_ExecuteCode); // // abortFlowSetStateActivity // this.abortFlowSetStateActivity.Name = "abortFlowSetStateActivity"; this.abortFlowSetStateActivity.TargetStateName = "finishState"; // // noTypesMessageBoxActivity // this.noTypesMessageBoxActivity.DialogType = Composite.C1Console.Events.DialogType.Message; this.noTypesMessageBoxActivity.Message = "${Composite.Plugins.VisualFunction,AddNew.NoTypesExistsErrorMessage}"; this.noTypesMessageBoxActivity.Name = "noTypesMessageBoxActivity"; this.noTypesMessageBoxActivity.Title = "${Composite.Plugins.VisualFunction,AddNew.NoTypesExistsErrorTitle}"; // // ifElseActivity_CheckPageExists // this.ifElseActivity_CheckPageExists.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity_CheckPageExists.Activities.Add(this.ifElseBranchActivity9); this.ifElseActivity_CheckPageExists.Name = "ifElseActivity_CheckPageExists"; // // ifElseBranchActivity6 // this.ifElseBranchActivity6.Activities.Add(this.missingDataMessageBoxActivity); this.ifElseBranchActivity6.Activities.Add(this.setStateActivity5); this.ifElseBranchActivity6.Name = "ifElseBranchActivity6"; // // ifElseBranch_heckDataExists // this.ifElseBranch_heckDataExists.Activities.Add(this.codeActivity1); this.ifElseBranch_heckDataExists.Activities.Add(this.setStateActivity3); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckDataExists); this.ifElseBranch_heckDataExists.Condition = codecondition2; this.ifElseBranch_heckDataExists.Name = "ifElseBranch_heckDataExists"; // // ifElseBranchActivity8 // this.ifElseBranchActivity8.Activities.Add(this.noTypesMessageBoxActivity); this.ifElseBranchActivity8.Activities.Add(this.abortFlowSetStateActivity); this.ifElseBranchActivity8.Name = "ifElseBranchActivity8"; // // ifElseBranchActivity7 // this.ifElseBranchActivity7.Activities.Add(this.ifElseActivity_CheckPageExists); codecondition3.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckTypesExists); this.ifElseBranchActivity7.Condition = codecondition3; this.ifElseBranchActivity7.Name = "ifElseBranchActivity7"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1State"; // // showFieldMessageActivity2 // this.showFieldMessageActivity2.FieldBindingPath = "TypeName"; this.showFieldMessageActivity2.Message = "Specified type is not a dynamic type"; this.showFieldMessageActivity2.Name = "showFieldMessageActivity2"; // // ifElseActivity2 // this.ifElseActivity2.Activities.Add(this.ifElseBranch_heckDataExists); this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity6); this.ifElseActivity2.Name = "ifElseActivity2"; // // setStateActivity12 // this.setStateActivity12.Name = "setStateActivity12"; this.setStateActivity12.TargetStateName = "finishState"; // // showConsoleMessageBoxActivity_NoTemplate // this.showConsoleMessageBoxActivity_NoTemplate.DialogType = Composite.C1Console.Events.DialogType.Message; this.showConsoleMessageBoxActivity_NoTemplate.Message = "${Composite.Plugins.VisualFunction,AddNew.NoPageTemplatesExistsErrorMessa" + "ge}"; this.showConsoleMessageBoxActivity_NoTemplate.Name = "showConsoleMessageBoxActivity_NoTemplate"; this.showConsoleMessageBoxActivity_NoTemplate.Title = "${Composite.Plugins.VisualFunction,AddNew.NoPageTemplatesExistsErrorTitle" + "}"; // // ifElseActivity3 // this.ifElseActivity3.Activities.Add(this.ifElseBranchActivity7); this.ifElseActivity3.Activities.Add(this.ifElseBranchActivity8); this.ifElseActivity3.Name = "ifElseActivity3"; // // backTostep2 // this.backTostep2.Name = "backTostep2"; this.backTostep2.TargetStateName = "step2State"; // // showFieldMessageActivity1 // this.showFieldMessageActivity1.FieldBindingPath = "Function.Name"; this.showFieldMessageActivity1.Message = "${Composite.Plugins.VisualFunction, VisualFunctionElementProvider.Functio" + "nNameNotUniqueError}"; this.showFieldMessageActivity1.Name = "showFieldMessageActivity1"; // // setStateActivity11 // this.setStateActivity11.Name = "setStateActivity11"; this.setStateActivity11.TargetStateName = "finalizeActivity"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.showFieldMessageActivity2); this.ifElseBranchActivity4.Activities.Add(this.setStateActivity2); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranch_CheckTypeNameIsDynamicType // this.ifElseBranch_CheckTypeNameIsDynamicType.Activities.Add(this.ifElseActivity2); codecondition4.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckTypeNameIsDynamicType); this.ifElseBranch_CheckTypeNameIsDynamicType.Condition = codecondition4; this.ifElseBranch_CheckTypeNameIsDynamicType.Name = "ifElseBranch_CheckTypeNameIsDynamicType"; // // ifElseBranchActivity11 // this.ifElseBranchActivity11.Activities.Add(this.showConsoleMessageBoxActivity_NoTemplate); this.ifElseBranchActivity11.Activities.Add(this.setStateActivity12); this.ifElseBranchActivity11.Name = "ifElseBranchActivity11"; // // ifElseBranchActivity10 // this.ifElseBranchActivity10.Activities.Add(this.ifElseActivity3); codecondition5.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckPageTemplatesExists); this.ifElseBranchActivity10.Condition = codecondition5; this.ifElseBranchActivity10.Name = "ifElseBranchActivity10"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.showFieldMessageActivity1); this.ifElseBranchActivity2.Activities.Add(this.backTostep2); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity11); codecondition6.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckFunctionNameIsUnique); this.ifElseBranchActivity1.Condition = codecondition6; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranch_CheckTypeNameIsDynamicType); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity4); this.ifElseActivity1.Name = "ifElseActivity1"; // // handleExternalEventActivity1 // this.handleExternalEventActivity1.EventName = "Next"; this.handleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.handleExternalEventActivity1.Name = "handleExternalEventActivity1"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = "Add new"; this.wizzardFormActivity1.FormDefinitionFileName = "\\Administrative\\AddNewVisualFunctionStep1.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // ifElseActivity5 // this.ifElseActivity5.Activities.Add(this.ifElseBranchActivity10); this.ifElseActivity5.Activities.Add(this.ifElseBranchActivity11); this.ifElseActivity5.Name = "ifElseActivity5"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.stepInitialize_codeActivity_ExecuteCode); // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // ifNameUniqueActivity1 // this.ifNameUniqueActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifNameUniqueActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifNameUniqueActivity1.Name = "ifNameUniqueActivity1"; // // handleExternalEventActivity3 // this.handleExternalEventActivity3.EventName = "Finish"; this.handleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.handleExternalEventActivity3.Name = "handleExternalEventActivity3"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "step1State"; // // handleExternalEventActivity2 // this.handleExternalEventActivity2.EventName = "Previous"; this.handleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.handleExternalEventActivity2.Name = "handleExternalEventActivity2"; // // step2WizzardFormActivity // this.step2WizzardFormActivity.ContainerLabel = "Add new"; this.step2WizzardFormActivity.FormDefinitionFileName = "\\Administrative\\AddNewVisualFunctionStep2.xml"; this.step2WizzardFormActivity.Name = "step2WizzardFormActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finishState"; // // stepFinalize_codeActivity // this.stepFinalize_codeActivity.Name = "stepFinalize_codeActivity"; this.stepFinalize_codeActivity.ExecuteCode += new System.EventHandler(this.stepFinalize_codeActivity_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // step1_eventDrivenActivity_Cancel // this.step1_eventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1_eventDrivenActivity_Cancel.Activities.Add(this.setStateActivity7); this.step1_eventDrivenActivity_Cancel.Name = "step1_eventDrivenActivity_Cancel"; // // step1_eventDrivenActivity_Next // this.step1_eventDrivenActivity_Next.Activities.Add(this.handleExternalEventActivity1); this.step1_eventDrivenActivity_Next.Activities.Add(this.ifElseActivity1); this.step1_eventDrivenActivity_Next.Name = "step1_eventDrivenActivity_Next"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.wizzardFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // setStateActivity19 // this.setStateActivity19.Name = "setStateActivity19"; this.setStateActivity19.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initializeStateInitializationActivity.Activities.Add(this.ifElseActivity5); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // step2_eventDrivenActivity_Cancel // this.step2_eventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.step2_eventDrivenActivity_Cancel.Activities.Add(this.setStateActivity8); this.step2_eventDrivenActivity_Cancel.Name = "step2_eventDrivenActivity_Cancel"; // // step2_eventDrivenActivity_Finish // this.step2_eventDrivenActivity_Finish.Activities.Add(this.handleExternalEventActivity3); this.step2_eventDrivenActivity_Finish.Activities.Add(this.ifNameUniqueActivity1); this.step2_eventDrivenActivity_Finish.Name = "step2_eventDrivenActivity_Finish"; // // step2_eventDrivenActivity_Previous // this.step2_eventDrivenActivity_Previous.Activities.Add(this.handleExternalEventActivity2); this.step2_eventDrivenActivity_Previous.Activities.Add(this.setStateActivity6); this.step2_eventDrivenActivity_Previous.Name = "step2_eventDrivenActivity_Previous"; // // step2StateInitializationActivity // this.step2StateInitializationActivity.Activities.Add(this.step2WizzardFormActivity); this.step2StateInitializationActivity.Name = "step2StateInitializationActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.stepFinalize_codeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity1); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1State // this.step1State.Activities.Add(this.step1StateInitializationActivity); this.step1State.Activities.Add(this.step1_eventDrivenActivity_Next); this.step1State.Activities.Add(this.step1_eventDrivenActivity_Cancel); this.step1State.Name = "step1State"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity19); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // initializeActivity // this.initializeActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeActivity.Name = "initializeActivity"; // // step2State // this.step2State.Activities.Add(this.step2StateInitializationActivity); this.step2State.Activities.Add(this.step2_eventDrivenActivity_Previous); this.step2State.Activities.Add(this.step2_eventDrivenActivity_Finish); this.step2State.Activities.Add(this.step2_eventDrivenActivity_Cancel); this.step2State.Name = "step2State"; // // finalizeActivity // this.finalizeActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeActivity.Name = "finalizeActivity"; // // finishState // this.finishState.Name = "finishState"; // // AddNewVisualFunctionWorkflow // this.Activities.Add(this.finishState); this.Activities.Add(this.finalizeActivity); this.Activities.Add(this.step2State); this.Activities.Add(this.initializeActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.step1State); this.CompletedStateName = "finishState"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeActivity"; this.Name = "AddNewVisualFunctionWorkflow"; this.CanModifyActivities = false; } #endregion private StateInitializationActivity step2StateInitializationActivity; private HandleExternalEventActivity handleExternalEventActivity3; private EventDrivenActivity step2_eventDrivenActivity_Finish; private StateActivity finishState; private StateActivity finalizeActivity; private StateInitializationActivity finalizeStateInitializationActivity; private CodeActivity stepFinalize_codeActivity; private StateInitializationActivity initializeStateInitializationActivity; private StateActivity initializeActivity; private SetStateActivity setStateActivity11; private Composite.C1Console.Workflow.Activities.WizardFormActivity step2WizzardFormActivity; private SetStateActivity setStateActivity1; private SetStateActivity setStateActivity19; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifNameUniqueActivity1; private SetStateActivity backTostep2; private Composite.C1Console.Workflow.Activities.ShowFieldMessageActivity showFieldMessageActivity1; private StateActivity step1State; private StateInitializationActivity step1StateInitializationActivity; private EventDrivenActivity step1_eventDrivenActivity_Next; private HandleExternalEventActivity handleExternalEventActivity1; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranch_CheckTypeNameIsDynamicType; private IfElseActivity ifElseActivity1; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.ShowConsoleMessageBoxActivity missingDataMessageBoxActivity; private SetStateActivity setStateActivity3; private CodeActivity codeActivity1; private IfElseBranchActivity ifElseBranchActivity6; private IfElseBranchActivity ifElseBranch_heckDataExists; private IfElseActivity ifElseActivity2; private Composite.C1Console.Workflow.Activities.WizardFormActivity wizzardFormActivity1; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity6; private HandleExternalEventActivity handleExternalEventActivity2; private EventDrivenActivity step2_eventDrivenActivity_Previous; private SetStateActivity setStateActivity2; private Composite.C1Console.Workflow.Activities.ShowFieldMessageActivity showFieldMessageActivity2; private CodeActivity initializeCodeActivity; private SetStateActivity abortFlowSetStateActivity; private IfElseBranchActivity ifElseBranchActivity8; private IfElseBranchActivity ifElseBranchActivity7; private IfElseActivity ifElseActivity3; private Composite.C1Console.Workflow.Activities.ShowConsoleMessageBoxActivity noTypesMessageBoxActivity; private SetStateActivity setStateActivity7; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity8; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private EventDrivenActivity step1_eventDrivenActivity_Cancel; private EventDrivenActivity step2_eventDrivenActivity_Cancel; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private IfElseBranchActivity ifElseBranchActivity9; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElseActivity_CheckPageExists; private SetStateActivity setStateActivity9; private CodeActivity MissingPageActivity; private SetStateActivity setStateActivity12; private Composite.C1Console.Workflow.Activities.ShowConsoleMessageBoxActivity showConsoleMessageBoxActivity_NoTemplate; private IfElseBranchActivity ifElseBranchActivity11; private IfElseBranchActivity ifElseBranchActivity10; private IfElseActivity ifElseActivity5; private StateActivity step2State; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/VisualFunctionProviderElementProvider/AddNewVisualFunctionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="AddNewVisualFunctionWorkflow" Location="30; 30" Size="1145; 996" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity19" SourceStateName="AddNewVisualFunctionWorkflow" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="AddNewVisualFunctionWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="770" Y="71" /> <ns0:Point X="770" Y="177" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="0" TargetConnectionEdge="Bottom" SetStateName="setStateActivity1" SourceStateName="finalizeActivity" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="finalizeActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="638" Y="489" /> <ns0:Point X="770" Y="489" /> <ns0:Point X="770" Y="257" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1State" SourceConnectionIndex="1" TargetConnectionEdge="Bottom" SetStateName="setStateActivity6" SourceStateName="step2State" SourceConnectionEdge="Right" TargetActivity="step1State" SourceActivity="step2State" EventHandlerName="step2_eventDrivenActivity_Previous"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="531" /> <ns0:Point X="307" Y="531" /> <ns0:Point X="307" Y="422" /> <ns0:Point X="179" Y="422" /> <ns0:Point X="179" Y="410" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity11" SourceStateName="step2State" SourceConnectionEdge="Right" TargetActivity="finalizeActivity" SourceActivity="step2State" EventHandlerName="step2_eventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="283" Y="555" /> <ns0:Point X="312" Y="555" /> <ns0:Point X="312" Y="440" /> <ns0:Point X="543" Y="440" /> <ns0:Point X="543" Y="448" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step2State" SourceConnectionIndex="2" TargetConnectionEdge="Bottom" SetStateName="backTostep2" SourceStateName="step2State" SourceConnectionEdge="Right" TargetActivity="step2State" SourceActivity="step2State" EventHandlerName="step2_eventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="283" Y="555" /> <ns0:Point X="307" Y="555" /> <ns0:Point X="307" Y="600" /> <ns0:Point X="187" Y="600" /> <ns0:Point X="187" Y="592" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="3" TargetConnectionEdge="Top" SetStateName="setStateActivity8" SourceStateName="step2State" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="step2State" EventHandlerName="step2_eventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="287" Y="579" /> <ns0:Point X="312" Y="579" /> <ns0:Point X="312" Y="169" /> <ns0:Point X="770" Y="169" /> <ns0:Point X="770" Y="177" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="abortFlowSetStateActivity" SourceStateName="initializeActivity" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="initializeActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="257" Y="217" /> <ns0:Point X="273" Y="217" /> <ns0:Point X="273" Y="169" /> <ns0:Point X="770" Y="169" /> <ns0:Point X="770" Y="177" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1State" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="initializeActivity" SourceConnectionEdge="Right" TargetActivity="step1State" SourceActivity="initializeActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="257" Y="217" /> <ns0:Point X="267" Y="217" /> <ns0:Point X="267" Y="296" /> <ns0:Point X="179" Y="296" /> <ns0:Point X="179" Y="308" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity9" SourceStateName="initializeActivity" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="initializeActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="257" Y="217" /> <ns0:Point X="273" Y="217" /> <ns0:Point X="273" Y="169" /> <ns0:Point X="770" Y="169" /> <ns0:Point X="770" Y="177" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1State" SourceConnectionIndex="1" TargetConnectionEdge="Bottom" SetStateName="setStateActivity2" SourceStateName="step1State" SourceConnectionEdge="Right" TargetActivity="step1State" SourceActivity="step1State" EventHandlerName="step1_eventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="269" Y="373" /> <ns0:Point X="299" Y="373" /> <ns0:Point X="299" Y="418" /> <ns0:Point X="179" Y="418" /> <ns0:Point X="179" Y="410" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step2State" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1State" SourceConnectionEdge="Right" TargetActivity="step2State" SourceActivity="step1State" EventHandlerName="step1_eventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="269" Y="373" /> <ns0:Point X="299" Y="373" /> <ns0:Point X="299" Y="454" /> <ns0:Point X="187" Y="454" /> <ns0:Point X="187" Y="466" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1State" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step1State" SourceConnectionEdge="Right" TargetActivity="step1State" SourceActivity="step1State" EventHandlerName="step1_eventDrivenActivity_Next"> <StateDesignerConnector.Segments> <ns0:Point X="269" Y="373" /> <ns0:Point X="299" Y="373" /> <ns0:Point X="299" Y="300" /> <ns0:Point X="179" Y="300" /> <ns0:Point X="179" Y="308" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="step1State" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="step1State" EventHandlerName="step1_eventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="279" Y="397" /> <ns0:Point X="304" Y="397" /> <ns0:Point X="304" Y="169" /> <ns0:Point X="770" Y="169" /> <ns0:Point X="770" Y="177" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finishState" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity12" SourceStateName="initializeActivity" SourceConnectionEdge="Right" TargetActivity="finishState" SourceActivity="initializeActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="257" Y="217" /> <ns0:Point X="273" Y="217" /> <ns0:Point X="273" Y="169" /> <ns0:Point X="770" Y="169" /> <ns0:Point X="770" Y="177" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="finishState" Location="690; 177" Size="160; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="finalizeActivity" Location="437; 448" Size="213; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="finalizeStateInitializationActivity" Location="445; 479"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="455; 541" /> <CodeDesigner Size="130; 41" Name="stepFinalize_codeActivity" Location="455; 601" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="455; 661" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="step2State" Location="74; 466" Size="226; 126" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step2StateInitializationActivity" Location="82; 497"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="step2WizzardFormActivity" Location="92; 559" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step2_eventDrivenActivity_Previous" Location="82; 521"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="handleExternalEventActivity2" Location="92; 583" /> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="92; 643" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="381; 423" Name="step2_eventDrivenActivity_Finish" Location="82; 545"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="handleExternalEventActivity3" Location="207; 607" /> <IfElseDesigner Size="361; 282" Name="ifNameUniqueActivity1" Location="92; 667"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity1" Location="111; 738"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 53" Name="setStateActivity11" Location="121; 824" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity2" Location="284; 738"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="showFieldMessageActivity1" Location="294; 800" /> <SetStateDesigner Size="130; 41" Name="backTostep2" Location="294; 860" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step2_eventDrivenActivity_Cancel" Location="82; 569"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity3" Location="92; 631" /> <SetStateDesigner Size="130; 41" Name="setStateActivity8" Location="92; 691" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="initializeActivity" Location="51; 176" Size="210; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="843; 785" Name="initializeStateInitializationActivity" Location="181; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity" Location="537; 210" /> <IfElseDesigner Size="823; 644" Name="ifElseActivity5" Location="191; 270"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="612; 544" Name="ifElseBranchActivity10" Location="210; 341"> <IfElseBranchDesigner.Designers> <IfElseDesigner Size="592; 463" Name="ifElseActivity3" Location="220; 403"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="381; 363" Name="ifElseBranchActivity7" Location="239; 474"> <IfElseBranchDesigner.Designers> <IfElseDesigner Size="361; 282" Name="ifElseActivity_CheckPageExists" Location="249; 536"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity3" Location="268; 607"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="278; 699" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity9" Location="441; 607"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="MissingPageActivity" Location="451; 669" /> <SetStateDesigner Size="130; 41" Name="setStateActivity9" Location="451; 729" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 363" Name="ifElseBranchActivity8" Location="643; 474"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="noTypesMessageBoxActivity" Location="653; 536" /> <SetStateDesigner Size="130; 53" Name="abortFlowSetStateActivity" Location="653; 596" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 544" Name="ifElseBranchActivity11" Location="845; 341"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="showConsoleMessageBoxActivity_NoTemplate" Location="855; 403" /> <SetStateDesigner Size="130; 53" Name="setStateActivity12" Location="855; 463" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <EventDrivenDesigner Size="150; 194" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 53" Name="setStateActivity19" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="step1State" Location="66; 308" Size="226; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="74; 339"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="wizzardFormActivity1" Location="84; 401" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="612; 604" Name="step1_eventDrivenActivity_Next" Location="74; 363"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="handleExternalEventActivity1" Location="315; 425" /> <IfElseDesigner Size="592; 463" Name="ifElseActivity1" Location="84; 485"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="381; 363" Name="ifElseBranch_CheckTypeNameIsDynamicType" Location="103; 556"> <IfElseBranchDesigner.Designers> <IfElseDesigner Size="361; 282" Name="ifElseActivity2" Location="113; 618"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranch_heckDataExists" Location="132; 689"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="codeActivity1" Location="142; 751" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="142; 811" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity6" Location="305; 689"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="missingDataMessageBoxActivity" Location="315; 751" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="315; 811" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 363" Name="ifElseBranchActivity4" Location="507; 556"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="showFieldMessageActivity2" Location="517; 618" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="517; 678" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1_eventDrivenActivity_Cancel" Location="74; 387"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="84; 449" /> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="84; 509" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/VisualFunctionProviderElementProvider/DeleteVisualFunctionWorkflow.cs ================================================ using System; using System.Linq; using Composite.C1Console.Actions; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Workflow; using Composite.Plugins.Elements.ElementProviders.Common; namespace Composite.Plugins.Elements.ElementProviders.VisualFunctionProviderElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteVisualFunctionWorkflow : BaseFunctionWorkflow { public DeleteVisualFunctionWorkflow() { InitializeComponent(); } private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { DeleteTreeRefresher deleteTreeRefresher = this.CreateDeleteTreeRefresher(this.EntityToken); DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; IVisualFunction visualFunction = (IVisualFunction)dataEntityToken.Data; DataFacade.Delete<IVisualFunction>(visualFunction); int count = (from info in DataFacade.GetData<IVisualFunction>() where info.Namespace == visualFunction.Namespace select info).Count(); if (count == 0) { RefreshFunctionTree(); } else { deleteTreeRefresher.PostRefreshMesseges(); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/VisualFunctionProviderElementProvider/DeleteVisualFunctionWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.VisualFunctionProviderElementProvider { partial class DeleteVisualFunctionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity19 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.initializeActivity = new System.Workflow.Activities.StateActivity(); this.finishState = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finishState"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "/Administrative/DeleteVisualFunctionStep1.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "step1StateActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity2); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity3); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.confirmDialogFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // setStateActivity19 // this.setStateActivity19.Name = "setStateActivity19"; this.setStateActivity19.TargetStateName = "finishState"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity1); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity19); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // initializeActivity // this.initializeActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeActivity.Name = "initializeActivity"; // // finishState // this.finishState.Name = "finishState"; // // DeleteVisualFunctionWorkflow // this.Activities.Add(this.finishState); this.Activities.Add(this.initializeActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finishState"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeActivity"; this.Name = "DeleteVisualFunctionWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity finishState; private StateInitializationActivity initializeStateInitializationActivity; private StateActivity initializeActivity; private SetStateActivity setStateActivity19; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private CodeActivity finalizeCodeActivity; private SetStateActivity setStateActivity2; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateInitializationActivity step1StateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity1; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/VisualFunctionProviderElementProvider/EditVisualFunctionWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web.UI; using System.Workflow.Activities; using System.Workflow.Runtime; using System.Xml.Linq; using Composite.C1Console.Actions; using Composite.Core.PageTemplates; using Composite.Data; using Composite.Data.DynamicTypes; using Composite.Data.Types; using Composite.Functions; using Composite.Core.WebClient.Renderings.Page; using Composite.Plugins.Functions.FunctionProviders.VisualFunctionProvider; using Composite.Core.Types; using Composite.C1Console.Users; using Composite.Core.WebClient.FlowMediators.FormFlowRendering; using Composite.C1Console.Workflow; using Composite.Core.Xml; using Composite.C1Console.Events; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Elements.ElementProviders.VisualFunctionProviderElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditVisualFunctionWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditVisualFunctionWorkflow() { InitializeComponent(); } private void CheckPageTemplatesExists(object sender, ConditionalEventArgs e) { e.Result = PageTemplateFacade.ValidTemplateExists; } private void CheckActiveLanguageExists(object sender, ConditionalEventArgs e) { e.Result = UserSettings.ActiveLocaleCultureInfo != null; } private void MissingActiveLanguageActivity_ExecuteCode(object sender, EventArgs e) { ShowMessage( DialogType.Message, StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "Edit.MissingActiveLanguageTitle"), StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "Edit.MissingActiveLanguageMessage")); } private void MissingPageTemplateActivity_ExecuteCode(object sender, EventArgs e) { ShowMessage( DialogType.Message, StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "Edit.NoPageTemplatesExistsErrorTitle"), StringResourceSystemFacade.GetString("Composite.Plugins.VisualFunction", "Edit.NoPageTemplatesExistsErrorMessage")); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { DataEntityToken token = (DataEntityToken)this.EntityToken; IVisualFunction function = (IVisualFunction)token.Data; this.Bindings.Add("OriginalFullName", string.Format("{0}.{1}", function.Namespace, function.Name)); this.Bindings.Add("Function", function); this.Bindings.Add("XhtmlBody", function.XhtmlTemplate); Type interfaceType = TypeManager.GetType(function.TypeManagerName); DataTypeDescriptor typeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(interfaceType); this.Bindings.Add("EmbedableFieldsTypes", new List<Type> { interfaceType }); this.Bindings.Add("SourceTypeFullName", interfaceType.FullName); this.Bindings.Add("FieldNameList", FieldNames(typeDescriptor).ToList()); Dictionary<Guid, string> templateInfos = new Dictionary<Guid, string>(); foreach (PageTemplateDescriptor pageTemplate in PageTemplateFacade.GetPageTemplates()) { if (pageTemplate.PlaceholderDescriptions.Any()) { templateInfos.Add(pageTemplate.Id, pageTemplate.Title); } } this.Bindings.Add("PreviewTemplateId", templateInfos.First().Key); this.Bindings.Add("TemplateList", templateInfos); } private IEnumerable<string> FieldNames(DataTypeDescriptor typeDescriptor) { yield return "(random)"; foreach (DataFieldDescriptor dataField in typeDescriptor.Fields.OrderBy(f => f.Position)) { yield return dataField.Name; } } private void saveCodeActivity_ExecuteCode(object sender, EventArgs e) { UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken); XhtmlDocument templateDocument = GetTemplateDocumentFromBindings(); IVisualFunction function = this.GetBinding<IVisualFunction>("Function"); function.XhtmlTemplate = templateDocument.ToString(); DataFacade.Update(function); string functionFullName = string.Format("{0}.{1}", function.Namespace, function.Name); this.UpdateBinding("OriginalFullName", functionFullName); updateTreeRefresher.PostRefreshMesseges(function.GetDataEntityToken()); SetSaveStatus(true); } private XhtmlDocument GetTemplateDocumentFromBindings() { string html = this.GetBinding<string>("XhtmlBody"); XElement xElement = XElement.Parse(html); return new XhtmlDocument(xElement); } private void CheckFunctionReNameIsUnique(object sender, ConditionalEventArgs e) { IVisualFunction function = this.GetBinding<IVisualFunction>("Function"); string functionFullName = string.Format("{0}.{1}", function.Namespace, function.Name); string originalFullName = this.GetBinding<string>("OriginalFullName"); if (functionFullName == originalFullName) { e.Result = true; return; } if (FunctionFacade.FunctionNames.Contains(functionFullName)) { e.Result = false; } else { e.Result = true; } } private void editPreviewCodeActivity_ExecuteCode(object sender, EventArgs e) { try { XhtmlDocument templateDocument = GetTemplateDocumentFromBindings(); IVisualFunction function = this.GetBinding<IVisualFunction>("Function"); Type interfaceType = TypeManager.GetType(function.TypeManagerName); DataTypeDescriptor typeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(interfaceType); this.LogMessage(Composite.Core.Logging.LogLevel.Info, DataScopeManager.CurrentDataScope.Name); FunctionContextContainer fcc = PageRenderer.GetPageRenderFunctionContextContainer(); XhtmlDocument result = RenderingHelper.RenderCompleteDataList(function, templateDocument, typeDescriptor, fcc); IPage previewPage = DataFacade.BuildNew<IPage>(); previewPage.Id = GetRootPageId(); previewPage.Title = function.Name; previewPage.DataSourceId.DataScopeIdentifier = DataScopeIdentifier.Administrated; previewPage.DataSourceId.LocaleScope = LocalizationScopeManager.CurrentLocalizationScope; previewPage.TemplateId = this.GetBinding<Guid>("PreviewTemplateId"); var pageTemplate = PageTemplateFacade.GetPageTemplate(previewPage.TemplateId); IPagePlaceholderContent placeHolderContent = DataFacade.BuildNew<IPagePlaceholderContent>(); placeHolderContent.Content = string.Concat((result.Body.Elements().Select(b => b.ToString())).ToArray()); placeHolderContent.PlaceHolderId = pageTemplate.DefaultPlaceholderId; string output = PagePreviewBuilder.RenderPreview(previewPage, new List<IPagePlaceholderContent> { placeHolderContent }); var serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); var webRenderService = serviceContainer.GetService<IFormFlowWebRenderingService>(); webRenderService.SetNewPageOutput(new LiteralControl(output)); } catch (Exception ex) { FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); Control errOutput = new LiteralControl("<pre>" + ex + "</pre>"); var webRenderService = serviceContainer.GetService<IFormFlowWebRenderingService>(); webRenderService.SetNewPageOutput(errOutput); } } private static Guid GetRootPageId() { return PageManager.GetChildrenIDs(Guid.Empty).FirstOrDefault(pageId => PageManager.GetPageById(pageId) != null); } private void previewHandleExternalEventActivity1_Invoked(object sender, System.Workflow.Activities.ExternalDataEventArgs e) { } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/VisualFunctionProviderElementProvider/EditVisualFunctionWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.VisualFunctionProviderElementProvider { partial class EditVisualFunctionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition3 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.MissingPageTemplateActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity6 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity5 = new System.Workflow.Activities.IfElseBranchActivity(); this.noSaveSetStateActivity = new System.Workflow.Activities.SetStateActivity(); this.showFieldMessageActivity1 = new Composite.C1Console.Workflow.Activities.ShowFieldMessageActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.MissingActiveLanguageActivity = new System.Workflow.Activities.CodeActivity(); this.ifElseActivity_CheckPageTemplatesExists = new System.Workflow.Activities.IfElseActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.editPreviewCodeActivity = new System.Workflow.Activities.CodeActivity(); this.previewHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.PreviewHandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.ifElseActivity_CheckActiveLanguageExists = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_Preview = new System.Workflow.Activities.EventDrivenActivity(); this.eventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.initialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // MissingPageTemplateActivity // this.MissingPageTemplateActivity.Name = "MissingPageTemplateActivity"; this.MissingPageTemplateActivity.ExecuteCode += new System.EventHandler(this.MissingPageTemplateActivity_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // ifElseBranchActivity6 // this.ifElseBranchActivity6.Activities.Add(this.MissingPageTemplateActivity); this.ifElseBranchActivity6.Activities.Add(this.setStateActivity6); this.ifElseBranchActivity6.Name = "ifElseBranchActivity6"; // // ifElseBranchActivity5 // this.ifElseBranchActivity5.Activities.Add(this.initializeCodeActivity); this.ifElseBranchActivity5.Activities.Add(this.setStateActivity2); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckPageTemplatesExists); this.ifElseBranchActivity5.Condition = codecondition1; this.ifElseBranchActivity5.Name = "ifElseBranchActivity5"; // // noSaveSetStateActivity // this.noSaveSetStateActivity.Name = "noSaveSetStateActivity"; this.noSaveSetStateActivity.TargetStateName = "editStateActivity"; // // showFieldMessageActivity1 // this.showFieldMessageActivity1.FieldBindingPath = "Function.Name"; this.showFieldMessageActivity1.Message = "${Composite.Plugins.VisualFunction, VisualFunctionElementProvider.Functio" + "nNameNotUniqueError}"; this.showFieldMessageActivity1.Name = "showFieldMessageActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "saveStateActivity"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // MissingActiveLanguageActivity // this.MissingActiveLanguageActivity.Name = "MissingActiveLanguageActivity"; this.MissingActiveLanguageActivity.ExecuteCode += new System.EventHandler(this.MissingActiveLanguageActivity_ExecuteCode); // // ifElseActivity_CheckPageTemplatesExists // this.ifElseActivity_CheckPageTemplatesExists.Activities.Add(this.ifElseBranchActivity5); this.ifElseActivity_CheckPageTemplatesExists.Activities.Add(this.ifElseBranchActivity6); this.ifElseActivity_CheckPageTemplatesExists.Name = "ifElseActivity_CheckPageTemplatesExists"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.showFieldMessageActivity1); this.ifElseBranchActivity2.Activities.Add(this.noSaveSetStateActivity); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity3); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckFunctionReNameIsUnique); this.ifElseBranchActivity1.Condition = codecondition2; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.MissingActiveLanguageActivity); this.ifElseBranchActivity4.Activities.Add(this.setStateActivity7); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.ifElseActivity_CheckPageTemplatesExists); codecondition3.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckActiveLanguageExists); this.ifElseBranchActivity3.Condition = codecondition3; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // saveCodeActivity // this.saveCodeActivity.Name = "saveCodeActivity"; this.saveCodeActivity.ExecuteCode += new System.EventHandler(this.saveCodeActivity_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "editStateActivity"; // // editPreviewCodeActivity // this.editPreviewCodeActivity.Name = "editPreviewCodeActivity"; this.editPreviewCodeActivity.ExecuteCode += new System.EventHandler(this.editPreviewCodeActivity_ExecuteCode); // // previewHandleExternalEventActivity1 // this.previewHandleExternalEventActivity1.EventName = "Preview"; this.previewHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.previewHandleExternalEventActivity1.Name = "previewHandleExternalEventActivity1"; this.previewHandleExternalEventActivity1.Invoked += new System.EventHandler<System.Workflow.Activities.ExternalDataEventArgs>(this.previewHandleExternalEventActivity1_Invoked); // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.CustomToolbarDefinitionFileName = null; this.documentFormActivity1.FormDefinitionFileName = "/Administrative/EditVisualFunction.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // ifElseActivity_CheckActiveLanguageExists // this.ifElseActivity_CheckActiveLanguageExists.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity_CheckActiveLanguageExists.Activities.Add(this.ifElseBranchActivity4); this.ifElseActivity_CheckActiveLanguageExists.Name = "ifElseActivity_CheckActiveLanguageExists"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.saveCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // eventDrivenActivity_Preview // this.eventDrivenActivity_Preview.Activities.Add(this.previewHandleExternalEventActivity1); this.eventDrivenActivity_Preview.Activities.Add(this.editPreviewCodeActivity); this.eventDrivenActivity_Preview.Activities.Add(this.setStateActivity5); this.eventDrivenActivity_Preview.Name = "eventDrivenActivity_Preview"; // // eventDrivenActivity_Save // this.eventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.eventDrivenActivity_Save.Activities.Add(this.ifElseActivity1); this.eventDrivenActivity_Save.Name = "eventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.ifElseActivity_CheckActiveLanguageExists); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity1); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.eventDrivenActivity_Save); this.editStateActivity.Activities.Add(this.eventDrivenActivity_Preview); this.editStateActivity.Name = "editStateActivity"; // // initialState // this.initialState.Activities.Add(this.initialStateInitializationActivity); this.initialState.Name = "initialState"; // // EditVisualFunctionWorkflow // this.Activities.Add(this.initialState); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelEventDrivenActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialState"; this.Name = "EditVisualFunctionWorkflow"; this.CanModifyActivities = false; } #endregion private CodeActivity initializeCodeActivity; private SetStateActivity setStateActivity1; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initialStateInitializationActivity; private EventDrivenActivity cancelEventDrivenActivity; private StateActivity finalStateActivity; private StateActivity saveStateActivity; private StateActivity editStateActivity; private Composite.C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private StateInitializationActivity editStateInitializationActivity; private StateInitializationActivity finalizeStateInitializationActivity; private CodeActivity saveCodeActivity; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity eventDrivenActivity_Save; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity5; private EventDrivenActivity eventDrivenActivity_Preview; private CodeActivity editPreviewCodeActivity; private Composite.C1Console.Workflow.Activities.PreviewHandleExternalEventActivity previewHandleExternalEventActivity1; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private Composite.C1Console.Workflow.Activities.ShowFieldMessageActivity showFieldMessageActivity1; private SetStateActivity noSaveSetStateActivity; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElseActivity_CheckActiveLanguageExists; private SetStateActivity setStateActivity6; private CodeActivity MissingPageTemplateActivity; private IfElseBranchActivity ifElseBranchActivity6; private IfElseBranchActivity ifElseBranchActivity5; private SetStateActivity setStateActivity7; private CodeActivity MissingActiveLanguageActivity; private IfElseActivity ifElseActivity_CheckPageTemplatesExists; private StateActivity initialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/VisualFunctionProviderElementProvider/EditVisualFunctionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="EditVisualFunctionWorkflow" Location="30; 30" Size="1145; 793" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="EditVisualFunctionWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="EditVisualFunctionWorkflow" EventHandlerName="cancelEventDrivenActivity"> <StateDesignerConnector.Segments> <ns0:Point X="202" Y="71" /> <ns0:Point X="685" Y="71" /> <ns0:Point X="685" Y="117" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initialState" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="initialState" EventHandlerName="initialStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="146" /> <ns0:Point X="271" Y="146" /> <ns0:Point X="271" Y="251" /> <ns0:Point X="191" Y="251" /> <ns0:Point X="191" Y="263" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="saveStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="editStateActivity" SourceConnectionEdge="Right" TargetActivity="saveStateActivity" SourceActivity="editStateActivity" EventHandlerName="eventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="267" Y="328" /> <ns0:Point X="448" Y="328" /> <ns0:Point X="448" Y="386" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="noSaveSetStateActivity" SourceStateName="editStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="editStateActivity" EventHandlerName="eventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="267" Y="328" /> <ns0:Point X="295" Y="328" /> <ns0:Point X="295" Y="255" /> <ns0:Point X="191" Y="255" /> <ns0:Point X="191" Y="263" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="editStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="editStateActivity" EventHandlerName="eventDrivenActivity_Preview"> <StateDesignerConnector.Segments> <ns0:Point X="282" Y="352" /> <ns0:Point X="295" Y="352" /> <ns0:Point X="295" Y="255" /> <ns0:Point X="191" Y="255" /> <ns0:Point X="191" Y="263" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Bottom" SetStateName="setStateActivity4" SourceStateName="saveStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="saveStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="547" Y="427" /> <ns0:Point X="559" Y="427" /> <ns0:Point X="559" Y="477" /> <ns0:Point X="191" Y="477" /> <ns0:Point X="191" Y="381" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initialState" Location="63; 105" Size="197; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="612; 544" Name="initialStateInitializationActivity" Location="296; 148"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="592; 463" Name="ifElseActivity_CheckActiveLanguageExists" Location="306; 210"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="381; 363" Name="ifElseBranchActivity3" Location="325; 281"> <IfElseBranchDesigner.Designers> <IfElseDesigner Size="361; 282" Name="ifElseActivity_CheckPageTemplatesExists" Location="335; 343"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity5" Location="354; 414"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity" Location="364; 476" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="364; 536" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity6" Location="527; 414"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="MissingPageTemplateActivity" Location="537; 476" /> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="537; 536" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 363" Name="ifElseBranchActivity4" Location="729; 281"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="MissingActiveLanguageActivity" Location="739; 343" /> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="739; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="editStateActivity" Location="97; 263" Size="189; 118" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="editStateInitializationActivity" Location="105; 294"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="documentFormActivity1" Location="115; 356" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="381; 435" Name="eventDrivenActivity_Save" Location="105; 318"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="saveHandleExternalEventActivity1" Location="230; 380" /> <IfElseDesigner Size="361; 294" Name="ifElseActivity1" Location="115; 440"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 194" Name="ifElseBranchActivity1" Location="134; 511"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="144; 609" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 194" Name="ifElseBranchActivity2" Location="307; 511"> <IfElseBranchDesigner.Designers> <ActivityDesigner Size="130; 41" Name="showFieldMessageActivity1" Location="317; 573" /> <SetStateDesigner Size="130; 53" Name="noSaveSetStateActivity" Location="317; 633" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 242" Name="eventDrivenActivity_Preview" Location="105; 342"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="previewHandleExternalEventActivity1" Location="115; 404" /> <CodeDesigner Size="130; 41" Name="editPreviewCodeActivity" Location="115; 464" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="115; 524" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="saveStateActivity" Location="346; 386" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="finalizeStateInitializationActivity" Location="354; 417"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="saveCodeActivity" Location="364; 479" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="364; 539" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="605; 117" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="cancelEventDrivenActivity" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/AddNewWebsiteFileWorkflow.cs ================================================ using System; using System.IO; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Elements; using Composite.C1Console.Workflow; using Composite.Core.IO; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewWebsiteFileWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddNewWebsiteFileWorkflow() { InitializeComponent(); } private string GetCurrentPath() { if (this.EntityToken is WebsiteFileElementProviderRootEntityToken) { string rootPath = (string)ElementFacade.GetData(new ElementProviderHandle(this.EntityToken.Source), "RootPath"); return rootPath; } else if (this.EntityToken is WebsiteFileElementProviderEntityToken) { return (this.EntityToken as WebsiteFileElementProviderEntityToken).Path; } else { throw new NotImplementedException(); } } private void FileExists(object sender, ConditionalEventArgs e) { string currentPath = GetCurrentPath(); string newFileName = this.GetBinding<string>("NewFileName"); e.Result = C1File.Exists(Path.Combine(currentPath, newFileName)); } private void initializeCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { this.Bindings.Add("NewFileName", ""); } private void step1CodeActivity_ShowError_ExecuteCode(object sender, EventArgs e) { this.ShowFieldMessage("NewFileName", "${Composite.Plugins.WebsiteFileElementProvider, AddNewFile.Error.FileExist}"); } private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { string currentPath = GetCurrentPath(); string newFileName = this.GetBinding<string>("NewFileName"); string fullPath = Path.Combine(currentPath, newFileName); using (C1FileStream fs = C1File.Create(fullPath)) { } SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(this.EntityToken); if (this.EntityToken is WebsiteFileElementProviderEntityToken) { WebsiteFileElementProviderEntityToken folderToken = (WebsiteFileElementProviderEntityToken)this.EntityToken; var newFileToken = new WebsiteFileElementProviderEntityToken(folderToken.ProviderName, fullPath, folderToken.RootPath); SelectElement(newFileToken); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/AddNewWebsiteFileWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { partial class AddNewWebsiteFileWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.step1CodeActivity_ShowError = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.dataDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivit_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity1 = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "step1StateActivity"; // // step1CodeActivity_ShowError // this.step1CodeActivity_ShowError.Name = "step1CodeActivity_ShowError"; this.step1CodeActivity_ShowError.ExecuteCode += new System.EventHandler(this.step1CodeActivity_ShowError_ExecuteCode); // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity3); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.step1CodeActivity_ShowError); this.ifElseBranchActivity1.Activities.Add(this.setStateActivity5); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.FileExists); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // dataDialogFormActivity1 // this.dataDialogFormActivity1.ContainerLabel = null; this.dataDialogFormActivity1.FormDefinitionFileName = "/Administrative/WebsiteFileElementProviderAddNewFile.xml"; this.dataDialogFormActivity1.Name = "dataDialogFormActivity1"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "step1StateActivity"; // // initializeCodeActivity_Initialize // this.initializeCodeActivity_Initialize.Name = "initializeCodeActivity_Initialize"; this.initializeCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_Initialize_ExecuteCode); // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity2); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivit_Finish // this.step1EventDrivenActivit_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivit_Finish.Activities.Add(this.ifElseActivity1); this.step1EventDrivenActivit_Finish.Name = "step1EventDrivenActivit_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.dataDialogFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.finalizeCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity7); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_Initialize); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.step1StateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivit_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // eventDrivenActivity1 // this.eventDrivenActivity1.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity1.Activities.Add(this.setStateActivity1); this.eventDrivenActivity1.Name = "eventDrivenActivity1"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // AddNewWebsiteFileWorkflow // this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity1); this.Activities.Add(this.step1StateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddNewWebsiteFileWorkflow"; this.CanModifyActivities = false; } #endregion private StateInitializationActivity initializeStateInitializationActivity; private EventDrivenActivity eventDrivenActivity1; private StateActivity finalStateActivity; private StateActivity finalizeStateActivity; private StateInitializationActivity finalizeStateInitializationActivity; private CodeActivity finalizeCodeActivity; private SetStateActivity setStateActivity7; private SetStateActivity setStateActivity1; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private CodeActivity initializeCodeActivity_Initialize; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity4; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivit_Finish; private StateInitializationActivity step1StateInitializationActivity; private StateActivity step1StateActivity; private Composite.C1Console.Workflow.Activities.DataDialogFormActivity dataDialogFormActivity1; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private CodeActivity step1CodeActivity_ShowError; private SetStateActivity setStateActivity5; private StateActivity initializeStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/AddNewWebsiteFileWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="AddNewWebsiteFileWorkflow" Location="30; 30" Size="1174; 958" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="AddNewWebsiteFileWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="AddNewWebsiteFileWorkflow" EventHandlerName="eventDrivenActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="176" Y="71" /> <ns0:Point X="1094" Y="71" /> <ns0:Point X="1094" Y="792" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="775" Y="653" /> <ns0:Point X="1094" Y="653" /> <ns0:Point X="1094" Y="792" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="421" Y="420" /> <ns0:Point X="1094" Y="420" /> <ns0:Point X="1094" Y="792" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivit_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="411" Y="396" /> <ns0:Point X="676" Y="396" /> <ns0:Point X="676" Y="612" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="277" Y="142" /> <ns0:Point X="319" Y="142" /> <ns0:Point X="319" Y="331" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivit_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="599" Y="169" /> <ns0:Point X="619" Y="169" /> <ns0:Point X="619" Y="96" /> <ns0:Point X="507" Y="96" /> <ns0:Point X="507" Y="104" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initializeStateActivity" Location="71; 101" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initializeStateInitializationActivity" Location="79; 132"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity_Initialize" Location="89; 194" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="89; 254" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="574; 612" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="finalizeStateInitializationActivity" Location="582; 643"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity" Location="592; 705" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="592; 765" /> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="592; 825" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="1014; 792" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity1" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="step1StateActivity" Location="214; 331" Size="211; 102" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="410; 135"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="dataDialogFormActivity1" Location="420; 197" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="381; 423" Name="step1EventDrivenActivit_Finish" Location="418; 148"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="543; 210" /> <IfElseDesigner Size="361; 282" Name="ifElseActivity1" Location="428; 270"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity1" Location="447; 341"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="step1CodeActivity_ShowError" Location="457; 403" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="457; 463" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity2" Location="620; 341"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="630; 433" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="410; 183"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="420; 245" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="420; 305" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/AddNewWebsiteFolderWorkflow.cs ================================================ using System; using System.IO; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Elements; using Composite.C1Console.Workflow; using Composite.Core.IO; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewWebsiteFolderWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddNewWebsiteFolderWorkflow() { InitializeComponent(); } private string GetCurrentPath() { if (this.EntityToken is WebsiteFileElementProviderRootEntityToken) { string rootPath = (string)ElementFacade.GetData(new ElementProviderHandle(this.EntityToken.Source), "RootPath"); return rootPath; } else if (this.EntityToken is WebsiteFileElementProviderEntityToken) { return (this.EntityToken as WebsiteFileElementProviderEntityToken).Path; } else { throw new NotImplementedException(); } } private void FolderExists(object sender, ConditionalEventArgs e) { string currentPath = GetCurrentPath(); string newFolderName = this.GetBinding<string>("NewFolderName"); e.Result = C1Directory.Exists(Path.Combine(currentPath, newFolderName)); } private void initializeAddNewfolderCodeActivity_ExecuteCode(object sender, EventArgs e) { this.Bindings.Add("NewFolderName", ""); } private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { string currentPath = GetCurrentPath(); string newFolderName = this.GetBinding<string>("NewFolderName"); string newFolderPath = Path.Combine(currentPath, newFolderName); C1Directory.CreateDirectory(newFolderPath); SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(this.EntityToken); string providerName; string rootPath; switch (this.EntityToken.GetType().Name) { case nameof(WebsiteFileElementProviderRootEntityToken): WebsiteFileElementProviderRootEntityToken rootToken = (WebsiteFileElementProviderRootEntityToken)this.EntityToken; providerName = rootToken.ProviderName; rootPath = rootToken.RootPath; break; case nameof(WebsiteFileElementProviderEntityToken): WebsiteFileElementProviderEntityToken folderToken = (WebsiteFileElementProviderEntityToken)this.EntityToken; providerName = folderToken.ProviderName; rootPath = folderToken.RootPath; break; default: throw new InvalidOperationException("Unexpected EntityToken type"); } var newFileToken = new WebsiteFileElementProviderEntityToken(providerName, newFolderPath, rootPath); SelectElement(newFileToken); } private void finalizeCodeActivity_ShowError_ExecuteCode(object sender, EventArgs e) { this.ShowFieldMessage("NewFolderName", "${Composite.Plugins.WebsiteFileElementProvider, AddNewFolder.Error.FolderExist}"); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/AddNewWebsiteFolderWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { partial class AddNewWebsiteFolderWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finalizeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_ShowError = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.doesFolderExists = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeAddNewfolderCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.stateInitializationActivity3 = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity2 = new System.Workflow.Activities.StateInitializationActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.cancelActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.AddNewWebsiteFolderWorkflowInitialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // finalizeCodeActivity // this.finalizeCodeActivity.Name = "finalizeCodeActivity"; this.finalizeCodeActivity.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ExecuteCode); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "step1StateActivity"; // // finalizeCodeActivity_ShowError // this.finalizeCodeActivity_ShowError.Name = "finalizeCodeActivity_ShowError"; this.finalizeCodeActivity_ShowError.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ShowError_ExecuteCode); // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.finalizeCodeActivity); this.ifElseBranchActivity2.Activities.Add(this.closeCurrentViewActivity1); this.ifElseBranchActivity2.Activities.Add(this.setStateActivity4); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.finalizeCodeActivity_ShowError); this.ifElseBranchActivity1.Activities.Add(this.setStateActivity6); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.FolderExists); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // doesFolderExists // this.doesFolderExists.Activities.Add(this.ifElseBranchActivity1); this.doesFolderExists.Activities.Add(this.ifElseBranchActivity2); this.doesFolderExists.Description = "Folder exists?"; this.doesFolderExists.Name = "doesFolderExists"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = null; this.wizzardFormActivity1.FormDefinitionFileName = "/Administrative/WebsiteFileElementProviderAddNewFolder.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // initializeAddNewfolderCodeActivity // this.initializeAddNewfolderCodeActivity.Name = "initializeAddNewfolderCodeActivity"; this.initializeAddNewfolderCodeActivity.ExecuteCode += new System.EventHandler(this.initializeAddNewfolderCodeActivity_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // stateInitializationActivity3 // this.stateInitializationActivity3.Activities.Add(this.doesFolderExists); this.stateInitializationActivity3.Name = "stateInitializationActivity3"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity5); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity3); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // stateInitializationActivity2 // this.stateInitializationActivity2.Activities.Add(this.wizzardFormActivity1); this.stateInitializationActivity2.Name = "stateInitializationActivity2"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.initializeAddNewfolderCodeActivity); this.stateInitializationActivity1.Activities.Add(this.setStateActivity2); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // cancelActivity // this.cancelActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelActivity.Activities.Add(this.setStateActivity1); this.cancelActivity.Name = "cancelActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.stateInitializationActivity3); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.stateInitializationActivity2); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // AddNewWebsiteFolderWorkflowInitialState // this.AddNewWebsiteFolderWorkflowInitialState.Activities.Add(this.stateInitializationActivity1); this.AddNewWebsiteFolderWorkflowInitialState.Name = "AddNewWebsiteFolderWorkflowInitialState"; // // AddNewWebsiteFolderWorkflow // this.Activities.Add(this.AddNewWebsiteFolderWorkflowInitialState); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "AddNewWebsiteFolderWorkflowInitialState"; this.Name = "AddNewWebsiteFolderWorkflow"; this.CanModifyActivities = false; } #endregion private CodeActivity initializeAddNewfolderCodeActivity; private StateInitializationActivity stateInitializationActivity1; private StateActivity finalStateActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private StateInitializationActivity stateInitializationActivity3; private StateInitializationActivity stateInitializationActivity2; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.DataDialogFormActivity wizzardFormActivity1; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity1; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity step1EventDrivenActivity_Finish; private EventDrivenActivity cancelActivity; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private CodeActivity finalizeCodeActivity; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity doesFolderExists; private CodeActivity finalizeCodeActivity_ShowError; private SetStateActivity setStateActivity6; private StateActivity AddNewWebsiteFolderWorkflowInitialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/AddNewWebsiteFolderWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="AddNewWebsiteFolderWorkflow" Location="30; 30" Size="1158; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="AddNewWebsiteFolderWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="AddNewWebsiteFolderWorkflow" EventHandlerName="cancelActivity"> <StateDesignerConnector.Segments> <ns0:Point X="142" Y="71" /> <ns0:Point X="948" Y="71" /> <ns0:Point X="948" Y="599" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="AddNewWebsiteFolderWorkflowInitialState" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="AddNewWebsiteFolderWorkflowInitialState" EventHandlerName="stateInitializationActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="230" Y="142" /> <ns0:Point X="370" Y="142" /> <ns0:Point X="370" Y="263" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="468" Y="328" /> <ns0:Point X="540" Y="328" /> <ns0:Point X="540" Y="472" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="472" Y="352" /> <ns0:Point X="948" Y="352" /> <ns0:Point X="948" Y="599" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="stateInitializationActivity3"> <StateDesignerConnector.Segments> <ns0:Point X="624" Y="513" /> <ns0:Point X="948" Y="513" /> <ns0:Point X="948" Y="599" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="AddNewWebsiteFolderWorkflowInitialState" Location="59; 101" Size="245; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="stateInitializationActivity1" Location="67; 132"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeAddNewfolderCodeActivity" Location="77; 194" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="77; 254" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="step1StateActivity" Location="265; 263" Size="211; 102" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="stateInitializationActivity2" Location="273; 294"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="wizzardFormActivity1" Location="283; 356" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Finish" Location="273; 318"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="283; 380" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="283; 440" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="273; 342"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="283; 404" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="283; 464" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="453; 472" Size="175; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 423" Name="stateInitializationActivity3" Location="418; 148"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="361; 342" Name="doesFolderExists" Location="428; 210"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 242" Name="ifElseBranchActivity1" Location="447; 281"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity_ShowError" Location="457; 343" /> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="457; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 242" Name="ifElseBranchActivity2" Location="620; 281"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity" Location="630; 343" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="630; 403" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="630; 463" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="868; 599" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="cancelActivity" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/AddWebsiteFolderToWhiteListWorkflow.cs ================================================ using System; using System.Linq; using Composite.C1Console.Actions; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { public sealed partial class AddWebsiteFolderToWhiteListWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public AddWebsiteFolderToWhiteListWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken); WorkflowActionToken workflowActionToken = (WorkflowActionToken)this.ActionToken; string folderPath = null; if (this.EntityToken is WebsiteFileElementProviderRootEntityToken) { folderPath = ""; } else { WebsiteFileElementProviderEntityToken entityToken = (WebsiteFileElementProviderEntityToken)this.EntityToken; folderPath = entityToken.Path; } string keyName = workflowActionToken.Payload; string relativeFolderPath = IFolderWhiteListExtensions.GetTildePath(folderPath); if (!DataFacade.GetData<IFolderWhiteList>().Any(f => f.TildeBasedPath == relativeFolderPath && f.KeyName == keyName)) { IFolderWhiteList folderWhiteList = DataFacade.BuildNew<IFolderWhiteList>(); folderWhiteList.KeyName = keyName; folderWhiteList.TildeBasedPath = IFolderWhiteListExtensions.GetTildePath(folderPath); DataFacade.AddNew(folderWhiteList); } updateTreeRefresher.PostRefreshMesseges(this.EntityToken); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/AddWebsiteFolderToWhiteListWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { partial class AddWebsiteFolderToWhiteListWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // AddWebsiteFolderToWhiteListWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddWebsiteFolderToWhiteListWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private CodeActivity initializeCodeActivity; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/DeleteWebsiteFileWorkflow.cs ================================================ using System; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Workflow; using Composite.Core.IO; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteWebsiteFileWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeleteWebsiteFileWorkflow() { InitializeComponent(); } private void deleteCodeActivity_ExecuteCode(object sender, EventArgs e) { DeleteTreeRefresher treeRefresher = this.CreateDeleteTreeRefresher(this.EntityToken); WebsiteFileElementProviderEntityToken entityToken = (WebsiteFileElementProviderEntityToken)this.EntityToken; try { C1File.Delete(entityToken.Path); treeRefresher.PostRefreshMesseges(); } catch (Exception) { this.ShowMessage( DialogType.Error, StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "DeleteWebsiteFileWorkflow.DeleteErrorTitle"), StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "DeleteWebsiteFileWorkflow.DeleteErrorMessage") ); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/DeleteWebsiteFileWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { partial class DeleteWebsiteFileWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.deleteCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.deleteEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.initializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.deleteEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity1 = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.DeleteWebsiteFileWorkflowInitialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // deleteCodeActivity // this.deleteCodeActivity.Name = "deleteCodeActivity"; this.deleteCodeActivity.ExecuteCode += new System.EventHandler(this.deleteCodeActivity_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = null; this.wizzardFormActivity1.FormDefinitionFileName = "\\Administrative\\WebsiteFileElementProviderDeleteFile.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.deleteCodeActivity); this.stateInitializationActivity1.Activities.Add(this.closeCurrentViewActivity1); this.stateInitializationActivity1.Activities.Add(this.setStateActivity2); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // deleteEventDrivenActivity_Cancel // this.deleteEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.deleteEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity4); this.deleteEventDrivenActivity_Cancel.Name = "deleteEventDrivenActivity_Cancel"; // // initializationActivity // this.initializationActivity.Activities.Add(this.wizzardFormActivity1); this.initializationActivity.Name = "initializationActivity"; // // deleteEventDrivenActivity_Finish // this.deleteEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.deleteEventDrivenActivity_Finish.Activities.Add(this.setStateActivity3); this.deleteEventDrivenActivity_Finish.Name = "deleteEventDrivenActivity_Finish"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.stateInitializationActivity1); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // eventDrivenActivity1 // this.eventDrivenActivity1.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity1.Activities.Add(this.setStateActivity1); this.eventDrivenActivity1.Name = "eventDrivenActivity1"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // DeleteWebsiteFileWorkflowInitialState // this.DeleteWebsiteFileWorkflowInitialState.Activities.Add(this.deleteEventDrivenActivity_Finish); this.DeleteWebsiteFileWorkflowInitialState.Activities.Add(this.initializationActivity); this.DeleteWebsiteFileWorkflowInitialState.Activities.Add(this.deleteEventDrivenActivity_Cancel); this.DeleteWebsiteFileWorkflowInitialState.Name = "DeleteWebsiteFileWorkflowInitialState"; // // DeleteWebsiteFileWorkflow // this.Activities.Add(this.DeleteWebsiteFileWorkflowInitialState); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity1); this.Activities.Add(this.finalizeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "DeleteWebsiteFileWorkflowInitialState"; this.Name = "DeleteWebsiteFileWorkflow"; this.CanModifyActivities = false; } #endregion private EventDrivenActivity eventDrivenActivity1; private StateActivity finalStateActivity; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private CodeActivity deleteCodeActivity; private SetStateActivity setStateActivity1; private StateInitializationActivity stateInitializationActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity deleteEventDrivenActivity_Finish; private StateActivity finalizeStateActivity; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity wizzardFormActivity1; private StateInitializationActivity initializationActivity; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity deleteEventDrivenActivity_Cancel; private StateActivity DeleteWebsiteFileWorkflowInitialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/DeleteWebsiteFileWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="DeleteWebsiteFileWorkflow" Location="30; 30" Size="1158; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="DeleteWebsiteFileWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="DeleteWebsiteFileWorkflow" EventHandlerName="eventDrivenActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="176" Y="71" /> <ns0:Point X="860" Y="71" /> <ns0:Point X="860" Y="644" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="DeleteWebsiteFileWorkflowInitialState" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="DeleteWebsiteFileWorkflowInitialState" EventHandlerName="deleteEventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="334" Y="251" /> <ns0:Point X="463" Y="251" /> <ns0:Point X="463" Y="489" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="DeleteWebsiteFileWorkflowInitialState" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="DeleteWebsiteFileWorkflowInitialState" EventHandlerName="deleteEventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="338" Y="275" /> <ns0:Point X="860" Y="275" /> <ns0:Point X="860" Y="644" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="stateInitializationActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="547" Y="530" /> <ns0:Point X="860" Y="530" /> <ns0:Point X="860" Y="644" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="DeleteWebsiteFileWorkflowInitialState" Location="128; 186" Size="222; 102" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="deleteEventDrivenActivity_Finish" Location="136; 241"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="146; 303" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="146; 363" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateInitializationDesigner Size="150; 122" Name="initializationActivity" Location="136; 217"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="wizzardFormActivity1" Location="146; 279" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="deleteEventDrivenActivity_Cancel" Location="136; 265"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="146; 327" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="146; 387" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="780; 644" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity1" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="finalizeStateActivity" Location="376; 489" Size="175; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="stateInitializationActivity1" Location="534; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="deleteCodeActivity" Location="544; 210" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="544; 270" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="544; 330" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/DeleteWebsiteFolderWorkflow.cs ================================================ using System; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Workflow; using Composite.Core.IO; using Composite.Core.ResourceSystem; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteWebsiteFolderWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public DeleteWebsiteFolderWorkflow() { InitializeComponent(); } private void deleteCodeActivity_ExecuteCode(object sender, EventArgs e) { DeleteTreeRefresher treeRefresher = this.CreateDeleteTreeRefresher(this.EntityToken); WebsiteFileElementProviderEntityToken entityToken = (WebsiteFileElementProviderEntityToken)this.EntityToken; try { C1Directory.Delete(entityToken.Path, true); treeRefresher.PostRefreshMesseges(); } catch (Exception) { this.ShowMessage( DialogType.Error, StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "DeleteWebsiteFolderWorkflow.DeleteErrorTitle"), StringResourceSystemFacade.GetString("Composite.Plugins.WebsiteFileElementProvider", "DeleteWebsiteFolderWorkflow.DeleteErrorMessage") ); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/DeleteWebsiteFolderWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { partial class DeleteWebsiteFolderWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.deleteCodeActivity = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.deleteEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.deleteEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.step1StateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.stateActivity1 = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity1 = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "stateActivity1"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = null; this.wizzardFormActivity1.FormDefinitionFileName = "\\Administrative\\WebsiteFileElementProviderDeleteFolder.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalStateActivity"; // // deleteCodeActivity // this.deleteCodeActivity.Name = "deleteCodeActivity"; this.deleteCodeActivity.ExecuteCode += new System.EventHandler(this.deleteCodeActivity_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // deleteEventDrivenActivity_Cancel // this.deleteEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.deleteEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity4); this.deleteEventDrivenActivity_Cancel.Name = "deleteEventDrivenActivity_Cancel"; // // deleteEventDrivenActivity_Finish // this.deleteEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.deleteEventDrivenActivity_Finish.Activities.Add(this.setStateActivity2); this.deleteEventDrivenActivity_Finish.Name = "deleteEventDrivenActivity_Finish"; // // step1StateInitializationActivity // this.step1StateInitializationActivity.Activities.Add(this.wizzardFormActivity1); this.step1StateInitializationActivity.Name = "step1StateInitializationActivity"; // // finalizeActivity // this.finalizeActivity.Activities.Add(this.closeCurrentViewActivity1); this.finalizeActivity.Activities.Add(this.deleteCodeActivity); this.finalizeActivity.Activities.Add(this.setStateActivity3); this.finalizeActivity.Name = "finalizeActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.step1StateInitializationActivity); this.initializeStateActivity.Activities.Add(this.deleteEventDrivenActivity_Finish); this.initializeStateActivity.Activities.Add(this.deleteEventDrivenActivity_Cancel); this.initializeStateActivity.Name = "initializeStateActivity"; // // stateActivity1 // this.stateActivity1.Activities.Add(this.finalizeActivity); this.stateActivity1.Name = "stateActivity1"; // // eventDrivenActivity1 // this.eventDrivenActivity1.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity1.Activities.Add(this.setStateActivity1); this.eventDrivenActivity1.Name = "eventDrivenActivity1"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // DeleteWebsiteFolderWorkflow // this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity1); this.Activities.Add(this.stateActivity1); this.Activities.Add(this.initializeStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "DeleteWebsiteFolderWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity3; private CodeActivity deleteCodeActivity; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity finalizeActivity; private EventDrivenActivity eventDrivenActivity1; private StateActivity finalStateActivity; private SetStateActivity setStateActivity1; private StateActivity stateActivity1; private StateInitializationActivity step1StateInitializationActivity; private SetStateActivity setStateActivity2; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity wizzardFormActivity1; private EventDrivenActivity deleteEventDrivenActivity_Finish; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity deleteEventDrivenActivity_Cancel; private StateActivity initializeStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/DeleteWebsiteFolderWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="DeleteWebsiteFolderWorkflow" Location="30; 30" Size="1158; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="DeleteWebsiteFolderWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="DeleteWebsiteFolderWorkflow" EventHandlerName="eventDrivenActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="176" Y="71" /> <ns0:Point X="716" Y="71" /> <ns0:Point X="716" Y="485" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="stateActivity1" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="stateActivity1" EventHandlerName="finalizeActivity"> <StateDesignerConnector.Segments> <ns0:Point X="422" Y="425" /> <ns0:Point X="716" Y="425" /> <ns0:Point X="716" Y="485" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="stateActivity1" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="stateActivity1" SourceActivity="initializeStateActivity" EventHandlerName="deleteEventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="300" Y="231" /> <ns0:Point X="387" Y="231" /> <ns0:Point X="387" Y="384" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="deleteEventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="304" Y="255" /> <ns0:Point X="716" Y="255" /> <ns0:Point X="716" Y="485" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="finalStateActivity" Location="636; 485" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity1" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="stateActivity1" Location="307; 384" Size="160; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="finalizeActivity" Location="534; 148"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="544; 210" /> <CodeDesigner Size="130; 41" Name="deleteCodeActivity" Location="544; 270" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="544; 330" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="initializeStateActivity" Location="94; 166" Size="214; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="step1StateInitializationActivity" Location="102; 197"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="wizzardFormActivity1" Location="112; 259" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="deleteEventDrivenActivity_Finish" Location="102; 221"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="112; 283" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="112; 343" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="deleteEventDrivenActivity_Cancel" Location="102; 245"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="112; 307" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="112; 367" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/EditWebsiteFileTextContentWorkflow.cs ================================================ using System; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditWebsiteFileTextContentWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditWebsiteFileTextContentWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { WebsiteFileElementProviderEntityToken entityToken = (WebsiteFileElementProviderEntityToken)this.EntityToken; WebsiteFile websiteFile = new WebsiteFile(entityToken.Path); this.Bindings.Add("FileContent", websiteFile.ReadAllText()); this.Bindings.Add("FileName", websiteFile.FileName); this.Bindings.Add("FileMimeType", websiteFile.MimeType); } private void saveCodeActivity_ExecuteCode(object sender, EventArgs e) { WebsiteFileElementProviderEntityToken entityToken = (WebsiteFileElementProviderEntityToken)this.EntityToken; WebsiteFile websiteFile = new WebsiteFile(entityToken.Path); string content = this.GetBinding<string>("FileContent"); websiteFile.WriteAllText(content); SetSaveStatus(true); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/EditWebsiteFileTextContentWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { partial class EditWebsiteFileTextContentWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.eventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.initialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // saveCodeActivity // this.saveCodeActivity.Name = "saveCodeActivity"; this.saveCodeActivity.ExecuteCode += new System.EventHandler(this.saveCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "saveStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.FormDefinitionFileName = "/Administrative/WebsiteFileElementProviderEditTextContentFile.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.saveCodeActivity); this.finalizeStateInitializationActivity.Activities.Add(this.setStateActivity4); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // eventDrivenActivity_Save // this.eventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.eventDrivenActivity_Save.Activities.Add(this.setStateActivity3); this.eventDrivenActivity_Save.Name = "eventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initialStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity1); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity1); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.eventDrivenActivity_Save); this.editStateActivity.Name = "editStateActivity"; // // initialState // this.initialState.Activities.Add(this.initialStateInitializationActivity); this.initialState.Name = "initialState"; // // EditWebsiteFileTextContentWorkflow // this.Activities.Add(this.initialState); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.cancelEventDrivenActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialState"; this.Name = "EditWebsiteFileTextContentWorkflow"; this.CanModifyActivities = false; } #endregion private CodeActivity initializeCodeActivity; private SetStateActivity setStateActivity1; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initialStateInitializationActivity; private EventDrivenActivity cancelEventDrivenActivity; private StateActivity finalStateActivity; private StateActivity saveStateActivity; private StateActivity editStateActivity; private Composite.C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private StateInitializationActivity editStateInitializationActivity; private StateInitializationActivity finalizeStateInitializationActivity; private CodeActivity saveCodeActivity; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity2; private EventDrivenActivity eventDrivenActivity_Save; private SetStateActivity setStateActivity4; private StateActivity initialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/EditWebsiteFileTextContentWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="EditWebsiteFileTextContentWorkflow" Location="30; 30" Size="1158; 974" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="EditWebsiteFileTextContentWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="EditWebsiteFileTextContentWorkflow" EventHandlerName="cancelEventDrivenActivity"> <StateDesignerConnector.Segments> <ns0:Point X="202" Y="71" /> <ns0:Point X="1001" Y="71" /> <ns0:Point X="1001" Y="776" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initialState" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="initialState" EventHandlerName="initialStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="256" Y="146" /> <ns0:Point X="384" Y="146" /> <ns0:Point X="384" Y="409" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="saveStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="editStateActivity" SourceConnectionEdge="Right" TargetActivity="saveStateActivity" SourceActivity="editStateActivity" EventHandlerName="eventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="460" Y="474" /> <ns0:Point X="720" Y="474" /> <ns0:Point X="720" Y="524" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="saveStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="saveStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="819" Y="565" /> <ns0:Point X="832" Y="565" /> <ns0:Point X="832" Y="401" /> <ns0:Point X="384" Y="401" /> <ns0:Point X="384" Y="409" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initialState" Location="63; 105" Size="197; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initialStateInitializationActivity" Location="534; 148"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity" Location="544; 210" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="544; 270" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="editStateActivity" Location="290; 409" Size="189; 94" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="editStateInitializationActivity" Location="298; 440"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="documentFormActivity1" Location="308; 502" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_Save" Location="298; 464"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="saveHandleExternalEventActivity1" Location="308; 526" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="308; 586" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="saveStateActivity" Location="618; 524" Size="205; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="finalizeStateInitializationActivity" Location="626; 555"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="saveCodeActivity" Location="636; 617" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="636; 677" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="921; 776" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="cancelEventDrivenActivity" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/RemoveWebsiteFolderFromWhiteListWorkflow.cs ================================================ using System; using Composite.C1Console.Actions; using Composite.Data; using Composite.Data.Types; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { public sealed partial class RemoveWebsiteFolderFromWhiteListWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public RemoveWebsiteFolderFromWhiteListWorkflow() { InitializeComponent(); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { WorkflowActionToken workflowActionToken = (WorkflowActionToken)this.ActionToken; string folderPath = null; if (this.EntityToken is WebsiteFileElementProviderRootEntityToken) { folderPath = ""; } else { WebsiteFileElementProviderEntityToken entityToken = (WebsiteFileElementProviderEntityToken)this.EntityToken; folderPath = entityToken.Path; } UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken); string keyName = workflowActionToken.Payload; DataFacade.Delete<IFolderWhiteList>(f => f.TildeBasedPath == IFolderWhiteListExtensions.GetTildePath(folderPath) && f.KeyName == keyName); updateTreeRefresher.PostRefreshMesseges(this.EntityToken); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/RemoveWebsiteFolderFromWhiteListWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { partial class RemoveWebsiteFolderFromWhiteListWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setFinalizeState = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setFinalizeState // this.setFinalizeState.Name = "setFinalizeState"; this.setFinalizeState.TargetStateName = "finalStateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity); this.initializeStateInitializationActivity.Activities.Add(this.setFinalizeState); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // RemoveWebsiteFolderFromWhiteListWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "RemoveWebsiteFolderFromWhiteListWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setFinalizeState; private CodeActivity initializeCodeActivity; private StateInitializationActivity initializeStateInitializationActivity; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/UploadAndExtractZipFileWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { partial class UploadAndExtractZipFileWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity3 = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseActivity2 = new System.Workflow.Activities.IfElseActivity(); this.codeActivity2 = new System.Workflow.Activities.CodeActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.wizzardFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.codeActivity1 = new System.Workflow.Activities.CodeActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.cancelEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.finishEventDrivenActivity = new System.Workflow.Activities.EventDrivenActivity(); this.selectZipStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initialStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity1 = new System.Workflow.Activities.EventDrivenActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.selectZipFileStateActivity = new System.Workflow.Activities.StateActivity(); this.initialState = new System.Workflow.Activities.StateActivity(); // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "selectZipFileStateActivity"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "selectZipFileStateActivity"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // codeActivity3 // this.codeActivity3.Name = "codeActivity3"; this.codeActivity3.ExecuteCode += new System.EventHandler(this.HandleFinish_ExecuteCode); // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.setStateActivity7); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.closeCurrentViewActivity1); this.ifElseBranchActivity3.Activities.Add(this.setStateActivity4); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.ZipWasUploaded); this.ifElseBranchActivity3.Condition = codecondition1; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity5); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.codeActivity3); this.ifElseBranchActivity1.Activities.Add(this.setStateActivity3); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.HasUserUploaded); this.ifElseBranchActivity1.Condition = codecondition2; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // ifElseActivity2 // this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity2.Activities.Add(this.ifElseBranchActivity4); this.ifElseActivity2.Name = "ifElseActivity2"; // // codeActivity2 // this.codeActivity2.Name = "codeActivity2"; this.codeActivity2.ExecuteCode += new System.EventHandler(this.FinalizeCodeActivity_ExecuteCode); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // wizzardFormActivity1 // this.wizzardFormActivity1.ContainerLabel = null; this.wizzardFormActivity1.FormDefinitionFileName = "/Administrative/WebsiteFileElementProviderUploadAndExtractZipFile.xml"; this.wizzardFormActivity1.Name = "wizzardFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "selectZipFileStateActivity"; // // codeActivity1 // this.codeActivity1.Name = "codeActivity1"; this.codeActivity1.ExecuteCode += new System.EventHandler(this.InitializeCodeActivity_ExecuteCode); // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.codeActivity2); this.finalizeStateInitializationActivity.Activities.Add(this.ifElseActivity2); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // cancelEventDrivenActivity // this.cancelEventDrivenActivity.Activities.Add(this.cancelHandleExternalEventActivity2); this.cancelEventDrivenActivity.Activities.Add(this.setStateActivity6); this.cancelEventDrivenActivity.Name = "cancelEventDrivenActivity"; // // finishEventDrivenActivity // this.finishEventDrivenActivity.Activities.Add(this.finishHandleExternalEventActivity1); this.finishEventDrivenActivity.Activities.Add(this.ifElseActivity1); this.finishEventDrivenActivity.Name = "finishEventDrivenActivity"; // // selectZipStateInitializationActivity // this.selectZipStateInitializationActivity.Activities.Add(this.wizzardFormActivity1); this.selectZipStateInitializationActivity.Name = "selectZipStateInitializationActivity"; // // initialStateInitializationActivity // this.initialStateInitializationActivity.Activities.Add(this.codeActivity1); this.initialStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initialStateInitializationActivity.Name = "initialStateInitializationActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // eventDrivenActivity1 // this.eventDrivenActivity1.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity1.Activities.Add(this.setStateActivity1); this.eventDrivenActivity1.Name = "eventDrivenActivity1"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // selectZipFileStateActivity // this.selectZipFileStateActivity.Activities.Add(this.selectZipStateInitializationActivity); this.selectZipFileStateActivity.Activities.Add(this.finishEventDrivenActivity); this.selectZipFileStateActivity.Activities.Add(this.cancelEventDrivenActivity); this.selectZipFileStateActivity.Name = "selectZipFileStateActivity"; // // initialState // this.initialState.Activities.Add(this.initialStateInitializationActivity); this.initialState.Name = "initialState"; // // UploadAndExtractZipFileWorkflow // this.Activities.Add(this.initialState); this.Activities.Add(this.selectZipFileStateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.eventDrivenActivity1); this.Activities.Add(this.finalStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initialState"; this.Name = "UploadAndExtractZipFileWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity selectZipFileStateActivity; private StateActivity finalizeStateActivity; private EventDrivenActivity eventDrivenActivity1; private StateInitializationActivity initialStateInitializationActivity; private StateActivity finalStateActivity; private CodeActivity codeActivity1; private StateInitializationActivity finalizeStateInitializationActivity; private StateInitializationActivity selectZipStateInitializationActivity; private C1Console.Workflow.Activities.DataDialogFormActivity wizzardFormActivity1; private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity1; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private SetStateActivity setStateActivity4; private CodeActivity codeActivity2; private SetStateActivity setStateActivity3; private CodeActivity codeActivity3; private C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private EventDrivenActivity finishEventDrivenActivity; private SetStateActivity setStateActivity5; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity6; private C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity cancelEventDrivenActivity; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElseActivity2; private SetStateActivity setStateActivity7; private StateActivity initialState; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/UploadAndExtractZipFileWorkflow.cs ================================================ using System; using System.IO; using System.IO.Compression; using System.Linq; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Workflow; using Composite.C1Console.Workflow.Activities; using Composite.Core; using Composite.Core.IO; using Texts = Composite.Core.ResourceSystem.LocalizationFiles.Composite_Plugins_WebsiteFileElementProvider; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Never)] public sealed partial class UploadAndExtractZipFileWorkflow : FormsWorkflow { [NonSerialized] bool _zipHasBeenUploaded = false; public UploadAndExtractZipFileWorkflow() { InitializeComponent(); } private void InitializeCodeActivity_ExecuteCode(object sender, EventArgs e) { FormsWorkflow workflow = this.GetRoot<FormsWorkflow>(); string parentFolderPath; if (this.EntityToken is WebsiteFileElementProviderRootEntityToken) { parentFolderPath = PathUtil.Resolve("~/"); } else { var token = (WebsiteFileElementProviderEntityToken)this.EntityToken; parentFolderPath = token.Path; } UploadedFile file = new UploadedFile(); workflow.Bindings.Add("UploadedFile", file); workflow.Bindings.Add("OverwriteExisting", false); workflow.Bindings.Add("ParentFolderPath", parentFolderPath); } private void HandleFinish_ExecuteCode(object sender, EventArgs e) { UploadedFile uploadedFile = this.GetBinding<UploadedFile>("UploadedFile"); bool overwrite = this.GetBinding<bool>("OverwriteExisting"); string parentFolderPath = this.GetBinding<string>("ParentFolderPath"); if (uploadedFile.HasFile) { using (System.IO.Stream readStream = uploadedFile.FileStream) { ZipArchive zipArchive; try { zipArchive = new ZipArchive(readStream); } catch (Exception) { ShowUploadError(Texts.UploadAndExtractZipFile_NotZip); return; } try { foreach (var entry in zipArchive.Entries) { string fullPath = Path.Combine(parentFolderPath, entry.FullName); if (File.Exists(fullPath)) { string websiteFilePath = PathUtil.GetWebsitePath(fullPath); if (!overwrite) { ShowUploadError(Texts.UploadAndExtractZipFile_FileExistsError(websiteFilePath)); return; } var fileInfo = new FileInfo(fullPath); if (fileInfo.IsReadOnly) { ShowUploadError(Texts.UploadAndExtractZipFile_ExistingFileReadOnly(websiteFilePath)); return; } } } foreach (var entry in zipArchive.Entries.Where(f => !string.IsNullOrWhiteSpace(f.Name))) { using (var zipStream = entry.Open()) { string fullPath = Path.Combine(parentFolderPath, entry.FullName); DirectoryUtils.EnsurePath(fullPath); using (var newFile = File.Create(fullPath, 4096)) { zipStream.CopyTo(newFile); } } } _zipHasBeenUploaded = true; } catch (Exception ex) { Log.LogError(nameof(UploadAndExtractZipFileWorkflow), ex); ShowUploadError(Texts.UploadAndExtractZipFile_UnexpectedError); } } } } private void ZipWasUploaded(object sender, ConditionalEventArgs e) { e.Result = _zipHasBeenUploaded; } private void FinalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken); addNewTreeRefresher.PostRefreshMesseges(this.EntityToken); } private void HasUserUploaded(object sender, System.Workflow.Activities.ConditionalEventArgs e) { UploadedFile uploadedFile = this.GetBinding<UploadedFile>("UploadedFile"); if (!uploadedFile.HasFile) { ShowUploadError(Texts.UploadAndExtractZipFile_FileNotUploaded); e.Result = false; return; } e.Result = true; } private void ShowUploadError(string message) { this.ShowMessage(DialogType.Error, Texts.UploadAndExtractZipFile_ErrorDialogLabel, message); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/UploadAndExtractZipFileWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Size="857; 689" AutoSizeMargin="16; 24" AutoSize="False" Location="30; 30" Name="UploadAndExtractZipFileWorkflow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceActivity="UploadAndExtractZipFileWorkflow" TargetConnectionIndex="0" SourceStateName="UploadAndExtractZipFileWorkflow" SourceConnectionEdge="Right" EventHandlerName="eventDrivenActivity1" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="186" Y="74" /> <ns0:Point X="753" Y="74" /> <ns0:Point X="753" Y="439" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="selectZipFileStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceActivity="initialState" TargetConnectionIndex="0" SourceStateName="initialState" SourceConnectionEdge="Right" EventHandlerName="initialStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="selectZipFileStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="271" Y="150" /> <ns0:Point X="305" Y="150" /> <ns0:Point X="305" Y="243" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalizeStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceActivity="selectZipFileStateActivity" TargetConnectionIndex="0" SourceStateName="selectZipFileStateActivity" SourceConnectionEdge="Right" EventHandlerName="finishEventDrivenActivity" SourceConnectionIndex="1" TargetStateName="finalizeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="369" Y="313" /> <ns0:Point X="433" Y="313" /> <ns0:Point X="433" Y="301" /> <ns0:Point X="617" Y="301" /> <ns0:Point X="617" Y="309" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="selectZipFileStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceActivity="selectZipFileStateActivity" TargetConnectionIndex="0" SourceStateName="selectZipFileStateActivity" SourceConnectionEdge="Right" EventHandlerName="finishEventDrivenActivity" SourceConnectionIndex="1" TargetStateName="selectZipFileStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="546" Y="178" /> <ns0:Point X="610" Y="178" /> <ns0:Point X="610" Y="100" /> <ns0:Point X="482" Y="100" /> <ns0:Point X="482" Y="108" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceActivity="selectZipFileStateActivity" TargetConnectionIndex="0" SourceStateName="selectZipFileStateActivity" SourceConnectionEdge="Right" EventHandlerName="cancelEventDrivenActivity" SourceConnectionIndex="2" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="374" Y="339" /> <ns0:Point X="433" Y="339" /> <ns0:Point X="433" Y="427" /> <ns0:Point X="753" Y="427" /> <ns0:Point X="753" Y="439" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="finalStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="finalStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="723" Y="353" /> <ns0:Point X="753" Y="353" /> <ns0:Point X="753" Y="439" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetActivity="selectZipFileStateActivity" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceActivity="finalizeStateActivity" TargetConnectionIndex="0" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" EventHandlerName="finalizeStateInitializationActivity" SourceConnectionIndex="0" TargetStateName="selectZipFileStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="723" Y="353" /> <ns0:Point X="737" Y="353" /> <ns0:Point X="737" Y="235" /> <ns0:Point X="305" Y="235" /> <ns0:Point X="305" Y="243" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Size="212; 80" AutoSizeMargin="16; 24" Location="63; 106" Name="initialState"> <StateDesigner.Designers> <StateInitializationDesigner Name="initialStateInitializationActivity" Size="150; 206" Location="71; 139"> <StateInitializationDesigner.Designers> <CodeDesigner Name="codeActivity1" Size="130; 41" Location="81; 204" /> <SetStateDesigner Name="setStateActivity2" Size="130; 62" Location="81; 264" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="231; 126" AutoSizeMargin="16; 24" AutoSize="False" Location="190; 243" Name="selectZipFileStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="selectZipStateInitializationActivity" Size="150; 128" Location="383; 154"> <StateInitializationDesigner.Designers> <ActivityDesigner Name="wizzardFormActivity1" Size="130; 44" Location="393; 219" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Name="finishEventDrivenActivity" Size="381; 456" Location="375; 167"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="finishHandleExternalEventActivity1" Size="130; 44" Location="500; 232" /> <IfElseDesigner Name="ifElseActivity1" Size="361; 309" Location="385; 295"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity1" Size="150; 206" Location="404; 369"> <IfElseBranchDesigner.Designers> <CodeDesigner Name="codeActivity3" Size="130; 41" Location="414; 434" /> <SetStateDesigner Name="setStateActivity3" Size="130; 62" Location="414; 494" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity2" Size="150; 206" Location="577; 369"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity5" Size="130; 62" Location="587; 464" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Name="cancelEventDrivenActivity" Size="150; 209" Location="375; 193"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity2" Size="130; 44" Location="385; 258" /> <SetStateDesigner Name="setStateActivity6" Size="130; 62" Location="385; 321" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Size="220; 80" AutoSizeMargin="16; 24" Location="507; 309" Name="finalizeStateActivity"> <StateDesigner.Designers> <StateInitializationDesigner Name="finalizeStateInitializationActivity" Size="381; 456" Location="515; 342"> <StateInitializationDesigner.Designers> <CodeDesigner Name="codeActivity2" Size="130; 41" Location="640; 407" /> <IfElseDesigner Name="ifElseActivity2" Size="361; 312" Location="525; 467"> <IfElseDesigner.Designers> <IfElseBranchDesigner Name="ifElseBranchActivity3" Size="150; 209" Location="544; 541"> <IfElseBranchDesigner.Designers> <ActivityDesigner Name="closeCurrentViewActivity1" Size="130; 44" Location="554; 606" /> <SetStateDesigner Name="setStateActivity4" Size="130; 62" Location="554; 669" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Name="ifElseBranchActivity4" Size="150; 209" Location="717; 541"> <IfElseBranchDesigner.Designers> <SetStateDesigner Name="setStateActivity7" Size="130; 62" Location="727; 637" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <EventDrivenDesigner Name="eventDrivenActivity1" Size="150; 209" Location="38; 63"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Name="cancelHandleExternalEventActivity1" Size="130; 44" Location="48; 128" /> <SetStateDesigner Name="setStateActivity1" Size="130; 62" Location="48; 191" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Size="160; 80" AutoSizeMargin="16; 24" Location="673; 439" Name="finalStateActivity" /> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/UploadWebsiteFileWorkflow.cs ================================================ using System; using System.IO; using System.Workflow.Activities; using Composite.C1Console.Actions; using Composite.C1Console.Elements; using Composite.C1Console.Events; using Composite.C1Console.Forms.CoreUiControls; using Composite.C1Console.Workflow; using Composite.Core.IO; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class UploadWebsiteFileWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public UploadWebsiteFileWorkflow() { InitializeComponent(); } private string GetCurrentPath() { if (this.EntityToken is WebsiteFileElementProviderRootEntityToken) { string rootPath = (string)ElementFacade.GetData(new ElementProviderHandle(this.EntityToken.Source), "RootPath"); return rootPath; } else if (this.EntityToken is WebsiteFileElementProviderEntityToken) { return (this.EntityToken as WebsiteFileElementProviderEntityToken).Path; } else { throw new NotImplementedException(); } } private void IsUploadTypeOk(object sender, ConditionalEventArgs e) { e.Result = true; } private void FileExist(object sender, ConditionalEventArgs e) { UploadedFile file = this.GetBinding<UploadedFile>("UploadedFile"); if (file.HasFile) { string currentPath = GetCurrentPath(); e.Result = C1Directory.GetFiles(currentPath, file.FileName).Length > 0; } else { e.Result = false; } } private void initializeCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e) { UploadedFile file = new UploadedFile(); this.Bindings.Add("UploadedFile", file); } private void finalizeCodeActivity_SaveFile_ExecuteCode(object sender, EventArgs e) { UploadedFile uploadedFile = this.GetBinding<UploadedFile>("UploadedFile"); if (uploadedFile.HasFile) { string currentPath = GetCurrentPath(); string filename = uploadedFile.FileName; string fullFilename = System.IO.Path.Combine(currentPath, filename); if (C1File.Exists(fullFilename)) { FileUtils.Delete(fullFilename); } using (C1FileStream fs = new C1FileStream(fullFilename, FileMode.CreateNew)) { uploadedFile.FileStream.CopyTo(fs); } SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher(); specificTreeRefresher.PostRefreshMesseges(this.EntityToken); if (this.EntityToken is WebsiteFileElementProviderEntityToken) { WebsiteFileElementProviderEntityToken folderToken = (WebsiteFileElementProviderEntityToken)this.EntityToken; var newFileToken = new WebsiteFileElementProviderEntityToken(folderToken.ProviderName, fullFilename, folderToken.RootPath); SelectElement(newFileToken); } } } private void finalizeCodeActivity_ShowErrorMessage_ExecuteCode(object sender, EventArgs e) { this.ShowMessage( DialogType.Error, "${Composite.Plugins.WebsiteFileElementProvider, UploadFile.Error.WrongTypeTitle}", "${Composite.Plugins.WebsiteFileElementProvider, UploadFile.Error.WrongTypeMessage}" ); } //private void finalizeCodeActivity_ShowFileExistMessage_ExecuteCode(object sender, EventArgs e) //{ // this.ShowMessage( // DialogType.Error, // "${Composite.Plugins.WebsiteFileElementProvider, UploadFile.Error.FileExistTitle}", // "${Composite.Plugins.WebsiteFileElementProvider, UploadFile.Error.FileExistMessage}" // ); //} } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/UploadWebsiteFileWorkflow.designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.WebsiteFileElementProvider { partial class UploadWebsiteFileWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this� method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.finalizeCodeActivity_ShowErrorMessage = new System.Workflow.Activities.CodeActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.finalizeCodeActivity_SaveFile = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity6 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity5 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity3 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity10 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.ifElse_IsUploadTypeOk = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.dataDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity_Initialize = new System.Workflow.Activities.CodeActivity(); this.confirmOverwriteEventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.confirmOverwriteEventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.confirmOverwriteStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.finalizeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.confirmOverwriteStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "step1StateActivity"; // // finalizeCodeActivity_ShowErrorMessage // this.finalizeCodeActivity_ShowErrorMessage.Name = "finalizeCodeActivity_ShowErrorMessage"; this.finalizeCodeActivity_ShowErrorMessage.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_ShowErrorMessage_ExecuteCode); // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // finalizeCodeActivity_SaveFile // this.finalizeCodeActivity_SaveFile.Name = "finalizeCodeActivity_SaveFile"; this.finalizeCodeActivity_SaveFile.ExecuteCode += new System.EventHandler(this.finalizeCodeActivity_SaveFile_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "confirmOverwriteStateActivity"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.finalizeCodeActivity_ShowErrorMessage); this.ifElseBranchActivity2.Activities.Add(this.setStateActivity6); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.finalizeCodeActivity_SaveFile); this.ifElseBranchActivity1.Activities.Add(this.closeCurrentViewActivity1); this.ifElseBranchActivity1.Activities.Add(this.setStateActivity5); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsUploadTypeOk); this.ifElseBranchActivity1.Condition = codecondition1; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // ifElseBranchActivity6 // this.ifElseBranchActivity6.Activities.Add(this.setStateActivity3); this.ifElseBranchActivity6.Name = "ifElseBranchActivity6"; // // ifElseBranchActivity5 // this.ifElseBranchActivity5.Activities.Add(this.setStateActivity8); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.FileExist); this.ifElseBranchActivity5.Condition = codecondition2; this.ifElseBranchActivity5.Name = "ifElseBranchActivity5"; // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity3 // this.cancelHandleExternalEventActivity3.EventName = "Cancel"; this.cancelHandleExternalEventActivity3.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity3.Name = "cancelHandleExternalEventActivity3"; // // setStateActivity10 // this.setStateActivity10.Name = "setStateActivity10"; this.setStateActivity10.TargetStateName = "finalizeStateActivity"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "/Administrative/WebsiteFileElementProviderUploadNewWebsiteFileConfirm.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // ifElse_IsUploadTypeOk // this.ifElse_IsUploadTypeOk.Activities.Add(this.ifElseBranchActivity1); this.ifElse_IsUploadTypeOk.Activities.Add(this.ifElseBranchActivity2); this.ifElse_IsUploadTypeOk.Name = "ifElse_IsUploadTypeOk"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity5); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity6); this.ifElseActivity1.Name = "ifElseActivity1"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // dataDialogFormActivity1 // this.dataDialogFormActivity1.ContainerLabel = null; this.dataDialogFormActivity1.FormDefinitionFileName = "/Administrative/WebsiteFileElementProviderUploadNewWebsiteFile.xml"; this.dataDialogFormActivity1.Name = "dataDialogFormActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // initializeCodeActivity_Initialize // this.initializeCodeActivity_Initialize.Name = "initializeCodeActivity_Initialize"; this.initializeCodeActivity_Initialize.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_Initialize_ExecuteCode); // // confirmOverwriteEventDrivenActivity_Cancel // this.confirmOverwriteEventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity3); this.confirmOverwriteEventDrivenActivity_Cancel.Activities.Add(this.setStateActivity9); this.confirmOverwriteEventDrivenActivity_Cancel.Name = "confirmOverwriteEventDrivenActivity_Cancel"; // // confirmOverwriteEventDrivenActivity_Finish // this.confirmOverwriteEventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.confirmOverwriteEventDrivenActivity_Finish.Activities.Add(this.setStateActivity10); this.confirmOverwriteEventDrivenActivity_Finish.Name = "confirmOverwriteEventDrivenActivity_Finish"; // // confirmOverwriteStateInitializationActivity // this.confirmOverwriteStateInitializationActivity.Activities.Add(this.confirmDialogFormActivity1); this.confirmOverwriteStateInitializationActivity.Name = "confirmOverwriteStateInitializationActivity"; // // finalizeStateInitializationActivity // this.finalizeStateInitializationActivity.Activities.Add(this.ifElse_IsUploadTypeOk); this.finalizeStateInitializationActivity.Name = "finalizeStateInitializationActivity"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity4); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.ifElseActivity1); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // stateInitializationActivity // this.stateInitializationActivity.Activities.Add(this.dataDialogFormActivity1); this.stateInitializationActivity.Name = "stateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.initializeCodeActivity_Initialize); this.initializeStateInitializationActivity.Activities.Add(this.setStateActivity2); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // confirmOverwriteStateActivity // this.confirmOverwriteStateActivity.Activities.Add(this.confirmOverwriteStateInitializationActivity); this.confirmOverwriteStateActivity.Activities.Add(this.confirmOverwriteEventDrivenActivity_Finish); this.confirmOverwriteStateActivity.Activities.Add(this.confirmOverwriteEventDrivenActivity_Cancel); this.confirmOverwriteStateActivity.Name = "confirmOverwriteStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.finalizeStateInitializationActivity); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.stateInitializationActivity); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity1); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // UploadWebsiteFileWorkflow // this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.confirmOverwriteStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "UploadWebsiteFileWorkflow"; this.CanModifyActivities = false; } #endregion private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private StateInitializationActivity initializeStateInitializationActivity; private SetStateActivity setStateActivity1; private StateActivity finalStateActivity; private StateActivity initializeStateActivity; private SetStateActivity setStateActivity5; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private Composite.C1Console.Workflow.Activities.DataDialogFormActivity dataDialogFormActivity1; private SetStateActivity setStateActivity2; private StateInitializationActivity finalizeStateInitializationActivity; private EventDrivenActivity step1EventDrivenActivity_Cancel; private EventDrivenActivity step1EventDrivenActivity_Finish; private StateInitializationActivity stateInitializationActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private CodeActivity initializeCodeActivity_Initialize; private CodeActivity finalizeCodeActivity_SaveFile; private SetStateActivity setStateActivity6; private CodeActivity finalizeCodeActivity_ShowErrorMessage; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElse_IsUploadTypeOk; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private StateInitializationActivity confirmOverwriteStateInitializationActivity; private StateActivity confirmOverwriteStateActivity; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private IfElseBranchActivity ifElseBranchActivity6; private IfElseBranchActivity ifElseBranchActivity5; private IfElseActivity ifElseActivity1; private SetStateActivity setStateActivity8; private SetStateActivity setStateActivity9; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity3; private SetStateActivity setStateActivity10; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private EventDrivenActivity confirmOverwriteEventDrivenActivity_Cancel; private EventDrivenActivity confirmOverwriteEventDrivenActivity_Finish; private EventDrivenActivity eventDrivenActivity_GlobalCancel; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/WebsiteFileElementProvider/UploadWebsiteFileWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="UploadWebsiteFileWorkflow" Location="30; 30" Size="1153; 996" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="UploadWebsiteFileWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="UploadWebsiteFileWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="1058" Y="71" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="296" Y="179" /> <ns0:Point X="392" Y="179" /> <ns0:Point X="392" Y="380" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="490" Y="445" /> <ns0:Point X="608" Y="445" /> <ns0:Point X="608" Y="539" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="494" Y="469" /> <ns0:Point X="1058" Y="469" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="707" Y="580" /> <ns0:Point X="720" Y="580" /> <ns0:Point X="720" Y="372" /> <ns0:Point X="392" Y="372" /> <ns0:Point X="392" Y="380" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="707" Y="580" /> <ns0:Point X="720" Y="580" /> <ns0:Point X="720" Y="372" /> <ns0:Point X="392" Y="372" /> <ns0:Point X="392" Y="380" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="finalizeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="707" Y="580" /> <ns0:Point X="1058" Y="580" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="confirmOverwriteStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity8" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="confirmOverwriteStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="490" Y="445" /> <ns0:Point X="506" Y="445" /> <ns0:Point X="506" Y="373" /> <ns0:Point X="282" Y="373" /> <ns0:Point X="282" Y="668" /> <ns0:Point X="380" Y="668" /> <ns0:Point X="380" Y="680" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity9" SourceStateName="confirmOverwriteStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="confirmOverwriteStateActivity" EventHandlerName="confirmOverwriteEventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="511" Y="769" /> <ns0:Point X="1058" Y="769" /> <ns0:Point X="1058" Y="798" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity10" SourceStateName="confirmOverwriteStateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="confirmOverwriteStateActivity" EventHandlerName="confirmOverwriteEventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="507" Y="745" /> <ns0:Point X="720" Y="745" /> <ns0:Point X="720" Y="531" /> <ns0:Point X="608" Y="531" /> <ns0:Point X="608" Y="539" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="initializeStateActivity" Location="90; 138" Size="210; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="initializeStateInitializationActivity" Location="98; 169"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity_Initialize" Location="108; 231" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="108; 291" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="971; 798" Size="175; 80" AutoSizeMargin="16; 24" /> <StateDesigner Name="step1StateActivity" Location="287; 380" Size="211; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="stateInitializationActivity" Location="295; 411"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="dataDialogFormActivity1" Location="305; 473" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="381; 363" Name="step1EventDrivenActivity_Finish" Location="295; 435"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="420; 497" /> <IfElseDesigner Size="361; 222" Name="ifElseActivity1" Location="305; 557"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity5" Location="324; 628"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity8" Location="334; 690" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity6" Location="497; 628"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="507; 690" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="295; 459"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="305; 521" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="305; 581" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="506; 539" Size="205; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 423" Name="finalizeStateInitializationActivity" Location="416; 148"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="361; 342" Name="ifElse_IsUploadTypeOk" Location="426; 210"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 242" Name="ifElseBranchActivity1" Location="445; 281"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity_SaveFile" Location="455; 343" /> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="455; 403" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="455; 463" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 242" Name="ifElseBranchActivity2" Location="618; 281"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="finalizeCodeActivity_ShowErrorMessage" Location="628; 343" /> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="628; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="confirmOverwriteStateActivity" Location="245; 680" Size="270; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="confirmOverwriteStateInitializationActivity" Location="253; 711"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="confirmDialogFormActivity1" Location="263; 773" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 194" Name="confirmOverwriteEventDrivenActivity_Finish" Location="253; 735"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity2" Location="263; 797" /> <SetStateDesigner Size="130; 53" Name="setStateActivity10" Location="263; 857" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="confirmOverwriteEventDrivenActivity_Cancel" Location="253; 759"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity3" Location="263; 821" /> <SetStateDesigner Size="130; 41" Name="setStateActivity9" Location="263; 881" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/XsltBasedFunctionProviderElementProvider/AddNewXsltFunctionWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.XsltBasedFunctionProviderElementProvider { partial class AddNewXsltFunctionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition3 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.MissingPageCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity6 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity5 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.MissingActiveLanguageCodeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElseActivity_PageExists = new System.Workflow.Activities.IfElseActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.finalizecodeActivity = new System.Workflow.Activities.CodeActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.dialogFormActivity1 = new Composite.C1Console.Workflow.Activities.DataDialogFormActivity(); this.ifElseActivity_CheckActiveLanguagesExists = new System.Workflow.Activities.IfElseActivity(); this.validateStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.stateInitializationActivity4 = new System.Workflow.Activities.StateInitializationActivity(); this.step1EventDrivenActivity_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.step1EventDrivenActivity_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity2 = new System.Workflow.Activities.StateInitializationActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.validateStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.finalizeStateActivity = new System.Workflow.Activities.StateActivity(); this.step1StateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "finalStateActivity"; // // MissingPageCodeActivity // this.MissingPageCodeActivity.Name = "MissingPageCodeActivity"; this.MissingPageCodeActivity.ExecuteCode += new System.EventHandler(this.MissingPageCodeActivity_ExecuteCode); // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "step1StateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // ifElseBranchActivity6 // this.ifElseBranchActivity6.Activities.Add(this.MissingPageCodeActivity); this.ifElseBranchActivity6.Activities.Add(this.setStateActivity8); this.ifElseBranchActivity6.Name = "ifElseBranchActivity6"; // // ifElseBranchActivity5 // this.ifElseBranchActivity5.Activities.Add(this.initializeCodeActivity); this.ifElseBranchActivity5.Activities.Add(this.setStateActivity2); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckPageExists); this.ifElseBranchActivity5.Condition = codecondition1; this.ifElseBranchActivity5.Name = "ifElseBranchActivity5"; // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "step1StateActivity"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "finalizeStateActivity"; // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "finalStateActivity"; // // MissingActiveLanguageCodeActivity // this.MissingActiveLanguageCodeActivity.Name = "MissingActiveLanguageCodeActivity"; this.MissingActiveLanguageCodeActivity.ExecuteCode += new System.EventHandler(this.MissingActiveLanguageCodeActivity_ExecuteCode); // // ifElseActivity_PageExists // this.ifElseActivity_PageExists.Activities.Add(this.ifElseBranchActivity5); this.ifElseActivity_PageExists.Activities.Add(this.ifElseBranchActivity6); this.ifElseActivity_PageExists.Name = "ifElseActivity_PageExists"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity4); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity3); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsValidData); this.ifElseBranchActivity1.Condition = codecondition2; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.MissingActiveLanguageCodeActivity); this.ifElseBranchActivity4.Activities.Add(this.setStateActivity9); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.ifElseActivity_PageExists); codecondition3.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckActiveLanguagesExists); this.ifElseBranchActivity3.Condition = codecondition3; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // finalizecodeActivity // this.finalizecodeActivity.Name = "finalizecodeActivity"; this.finalizecodeActivity.ExecuteCode += new System.EventHandler(this.finalizecodeActivity_ExecuteCode); // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "validateStateActivity"; // // finishHandleExternalEventActivity1 // this.finishHandleExternalEventActivity1.EventName = "Finish"; this.finishHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity1.Name = "finishHandleExternalEventActivity1"; // // dialogFormActivity1 // this.dialogFormActivity1.ContainerLabel = "Add new"; this.dialogFormActivity1.FormDefinitionFileName = "\\Administrative\\AddNewXsltFunctionStep1.xml"; this.dialogFormActivity1.Name = "dialogFormActivity1"; // // ifElseActivity_CheckActiveLanguagesExists // this.ifElseActivity_CheckActiveLanguagesExists.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity_CheckActiveLanguagesExists.Activities.Add(this.ifElseBranchActivity4); this.ifElseActivity_CheckActiveLanguagesExists.Name = "ifElseActivity_CheckActiveLanguagesExists"; // // validateStateInitializationActivity // this.validateStateInitializationActivity.Activities.Add(this.ifElseActivity1); this.validateStateInitializationActivity.Name = "validateStateInitializationActivity"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // stateInitializationActivity4 // this.stateInitializationActivity4.Activities.Add(this.closeCurrentViewActivity1); this.stateInitializationActivity4.Activities.Add(this.finalizecodeActivity); this.stateInitializationActivity4.Activities.Add(this.setStateActivity1); this.stateInitializationActivity4.Name = "stateInitializationActivity4"; // // step1EventDrivenActivity_Cancel // this.step1EventDrivenActivity_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.step1EventDrivenActivity_Cancel.Activities.Add(this.setStateActivity6); this.step1EventDrivenActivity_Cancel.Name = "step1EventDrivenActivity_Cancel"; // // step1EventDrivenActivity_Finish // this.step1EventDrivenActivity_Finish.Activities.Add(this.finishHandleExternalEventActivity1); this.step1EventDrivenActivity_Finish.Activities.Add(this.setStateActivity5); this.step1EventDrivenActivity_Finish.Name = "step1EventDrivenActivity_Finish"; // // stateInitializationActivity2 // this.stateInitializationActivity2.Activities.Add(this.dialogFormActivity1); this.stateInitializationActivity2.Name = "stateInitializationActivity2"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.ifElseActivity_CheckActiveLanguagesExists); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // validateStateActivity // this.validateStateActivity.Activities.Add(this.validateStateInitializationActivity); this.validateStateActivity.Name = "validateStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity7); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // finalizeStateActivity // this.finalizeStateActivity.Activities.Add(this.stateInitializationActivity4); this.finalizeStateActivity.Name = "finalizeStateActivity"; // // step1StateActivity // this.step1StateActivity.Activities.Add(this.stateInitializationActivity2); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Finish); this.step1StateActivity.Activities.Add(this.step1EventDrivenActivity_Cancel); this.step1StateActivity.Name = "step1StateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.stateInitializationActivity1); this.initializeStateActivity.Name = "initializeStateActivity"; // // AddNewXsltFunctionWorkflow // this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.step1StateActivity); this.Activities.Add(this.finalizeStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.validateStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "AddNewXsltFunctionWorkflow"; this.CanModifyActivities = false; } #endregion private StateActivity finalStateActivity; private StateActivity finalizeStateActivity; private StateActivity step1StateActivity; private StateInitializationActivity stateInitializationActivity4; private StateInitializationActivity stateInitializationActivity2; private StateInitializationActivity stateInitializationActivity1; private SetStateActivity setStateActivity1; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity1; private CodeActivity initializeCodeActivity; private EventDrivenActivity step1EventDrivenActivity_Finish; private Composite.C1Console.Workflow.Activities.DataDialogFormActivity dialogFormActivity1; private CodeActivity finalizecodeActivity; private SetStateActivity setStateActivity7; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private SetStateActivity setStateActivity2; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private StateInitializationActivity validateStateInitializationActivity; private StateActivity validateStateActivity; private SetStateActivity setStateActivity4; private SetStateActivity setStateActivity3; private SetStateActivity setStateActivity6; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private EventDrivenActivity step1EventDrivenActivity_Cancel; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElseActivity_CheckActiveLanguagesExists; private CodeActivity MissingActiveLanguageCodeActivity; private IfElseBranchActivity ifElseBranchActivity6; private IfElseBranchActivity ifElseBranchActivity5; private IfElseActivity ifElseActivity_PageExists; private CodeActivity MissingPageCodeActivity; private SetStateActivity setStateActivity8; private SetStateActivity setStateActivity9; private StateActivity initializeStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/XsltBasedFunctionProviderElementProvider/AddNewXsltFunctionWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Transactions; using System.Workflow.Activities; using System.Workflow.Runtime; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.Core.Extensions; using Composite.Core.Localization; using Composite.Core.ResourceSystem; using Composite.Core.Xml; using Composite.Data; using Composite.Data.Transactions; using Composite.Data.Types; using Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider; using Composite.Plugins.Functions.FunctionProviders.XsltBasedFunctionProvider; using Microsoft.Practices.EnterpriseLibrary.Validation; using Composite.Data.Validation; namespace Composite.Plugins.Elements.ElementProviders.XsltBasedFunctionProviderElementProvider { [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class AddNewXsltFunctionWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { private static readonly string Binding_CopyFromFunctionId = "CopyFromFunctionId"; private static readonly string Binding_CopyFromOptions = "CopyFromOptions"; private static string _newXsltMarkup = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?> <xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" xmlns:in=""{0}"" xmlns:lang=""{1}"" xmlns:f=""{2}"" xmlns=""http://www.w3.org/1999/xhtml"" exclude-result-prefixes=""xsl in lang f""> <xsl:template match=""/""> <html> <head> <!-- markup placed here will be shown in the head section of the rendered page --> </head> <body> <!-- markup placed here will be the output of this rendering --> <div> Value of input parameter 'TestParam': <xsl:value-of select=""/in:inputs/in:param[@name='Input parameter name']"" /> </div> <div> Value of function call 'TestCall': <xsl:value-of select=""/in:inputs/in:result[@name='Function call local name']"" /> </div> </body> </html> </xsl:template> </xsl:stylesheet> ", RenderHelper.XsltInput10, LocalizationXmlConstants.XmlNamespace, Namespaces.Function10); public AddNewXsltFunctionWorkflow() { InitializeComponent(); } private void CheckActiveLanguagesExists(object sender, ConditionalEventArgs e) { e.Result = UserSettings.ActiveLocaleCultureInfo != null; } private void CheckPageExists(object sender, ConditionalEventArgs e) { e.Result = DataFacade.GetData<IPage>().Any(); } private void MissingActiveLanguageCodeActivity_ExecuteCode(object sender, EventArgs e) { ShowMessage(DialogType.Message, GetText("AddNewXsltFunctionWorkflow.MissingActiveLanguageTitle"), GetText("AddNewXsltFunctionWorkflow.MissingActiveLanguageMessage")); } private void MissingPageCodeActivity_ExecuteCode(object sender, EventArgs e) { ShowMessage( DialogType.Message, GetText("AddNewXsltFunctionWorkflow.MissingPageTitle"), GetText("AddNewXsltFunctionWorkflow.MissingPageMessage")); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { IXsltFunction xsltFunction = DataFacade.BuildNew<IXsltFunction>(); xsltFunction.Id = Guid.NewGuid(); xsltFunction.Name = ""; xsltFunction.OutputXmlSubType = "XHTML"; xsltFunction.Description = ""; BaseFunctionFolderElementEntityToken folderToken = (BaseFunctionFolderElementEntityToken)this.EntityToken; xsltFunction.Namespace = folderToken.FunctionNamespace ?? UserSettings.LastSpecifiedNamespace; this.Bindings.Add("NewXslt", xsltFunction); var copyOfOptions = new List<KeyValuePair<Guid, string>>(); foreach (IXsltFunction function in DataFacade.GetData<IXsltFunction>()) { string fullName = function.Namespace + "." + function.Name; copyOfOptions.Add(new KeyValuePair<Guid, string>(function.Id, fullName)); } // Sorting alphabetically by function's full name copyOfOptions.Sort((a, b) => a.Value.CompareTo(b.Value)); copyOfOptions.Insert(0, new KeyValuePair<Guid, string>(Guid.Empty, GetText("AddNewXsltFunctionStep1.LabelCopyFromEmptyOption"))); this.Bindings.Add(Binding_CopyFromFunctionId, Guid.Empty); this.Bindings.Add(Binding_CopyFromOptions, copyOfOptions); } private void IsValidData(object sender, ConditionalEventArgs e) { IXsltFunction function = this.GetBinding<IXsltFunction>("NewXslt"); e.Result = false; if (function.Name == string.Empty) { this.ShowFieldMessage("NewXslt.Name", GetText("AddNewXsltFunctionWorkflow.MethodEmpty")); return; } if (string.IsNullOrWhiteSpace(function.Namespace)) { this.ShowFieldMessage("NewXslt.Namespace", GetText("AddNewXsltFunctionWorkflow.NamespaceEmpty")); return; } if (!function.Namespace.IsCorrectNamespace('.')) { this.ShowFieldMessage("NewXslt.Namespace", GetText("AddNewXsltFunctionWorkflow.InvalidNamespace")); return; } string functionName = function.Name; string functionNamespace = function.Namespace; bool nameIsReserved = DataFacade.GetData<IXsltFunction>() .Where(func => string.Compare(func.Name, functionName, true) == 0 && string.Compare(func.Namespace, functionNamespace, true) == 0) .Any(); if (nameIsReserved) { this.ShowFieldMessage("NewXslt.Name", GetText("AddNewXsltFunctionWorkflow.DuplicateName")); return; } function.XslFilePath = function.CreateXslFilePath(); ValidationResults validationResults = ValidationFacade.Validate<IXsltFunction>(function); if (!validationResults.IsValid) { foreach (ValidationResult result in validationResults) { this.ShowFieldMessage(string.Format("{0}.{1}", "NewXslt", result.Key), result.Message); } return; } if (!function.ValidateXslFilePath()) { this.ShowFieldMessage("NewXslt.Name", GetText("AddNewXsltFunctionWorkflow.TotalNameTooLang")); return; } IXsltFile xsltfile = DataFacade.BuildNew<IXsltFile>(); xsltfile.FolderPath = System.IO.Path.GetDirectoryName(function.XslFilePath); xsltfile.FileName = System.IO.Path.GetFileName(function.XslFilePath); if (!DataFacade.ValidatePath(xsltfile, "XslFileProvider")) { this.ShowFieldMessage("NewXslt.Name", GetText("AddNewXsltFunctionWorkflow.TotalNameTooLang")); return; } e.Result = true; } private void finalizecodeActivity_ExecuteCode(object sender, EventArgs e) { AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken); IXsltFunction xslt = this.GetBinding<IXsltFunction>("NewXslt"); Guid copyFromFunctionId = this.GetBinding<Guid>(Binding_CopyFromFunctionId); IXsltFunction copyFromFunction = null; if(copyFromFunctionId != Guid.Empty) { copyFromFunction = DataFacade.GetData<IXsltFunction>().First(f => f.Id == copyFromFunctionId); } xslt.XslFilePath = xslt.CreateXslFilePath(); IFile file = IFileServices.TryGetFile<IXsltFile>(xslt.XslFilePath); using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { if (file == null) { IXsltFile xsltfile = DataFacade.BuildNew<IXsltFile>(); xsltfile.FolderPath = System.IO.Path.GetDirectoryName(xslt.XslFilePath); xsltfile.FileName = System.IO.Path.GetFileName(xslt.XslFilePath); string xslTemplate = _newXsltMarkup; if (copyFromFunction != null) { IFile copyFromFile = IFileServices.GetFile<IXsltFile>(copyFromFunction.XslFilePath); xslTemplate = copyFromFile.ReadAllText(); } xsltfile.SetNewContent(xslTemplate); DataFacade.AddNew<IXsltFile>(xsltfile, "XslFileProvider"); } xslt = DataFacade.AddNew<IXsltFunction>(xslt); UserSettings.LastSpecifiedNamespace = xslt.Namespace; if (copyFromFunction != null) { CloneFunctionParameters(copyFromFunction, xslt); CloneFunctionCalls(copyFromFunction, xslt); } transactionScope.Complete(); } addNewTreeRefresher.PostRefreshMesseges(xslt.GetDataEntityToken()); FlowControllerServicesContainer container = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); var executionService = container.GetService<IActionExecutionService>(); executionService.Execute(xslt.GetDataEntityToken(), new WorkflowActionToken(typeof(EditXsltFunctionWorkflow)), null); } private void CloneFunctionParameters(IXsltFunction sourceFunction, IXsltFunction copyTo) { var parameters = DataFacade.GetData<IParameter>(p => p.OwnerId == sourceFunction.Id).ToList(); foreach (IParameter parameter in parameters) { var clonedFunctionParameter = DataFacade.BuildNew<IParameter>(); clonedFunctionParameter.OwnerId = copyTo.Id; clonedFunctionParameter.ParameterId = Guid.NewGuid(); clonedFunctionParameter.Name = parameter.Name; clonedFunctionParameter.TypeManagerName = parameter.TypeManagerName; clonedFunctionParameter.HelpText = parameter.HelpText; clonedFunctionParameter.Label = parameter.Label; clonedFunctionParameter.DefaultValueFunctionMarkup = parameter.DefaultValueFunctionMarkup; clonedFunctionParameter.Position = parameter.Position; clonedFunctionParameter.TestValueFunctionMarkup = parameter.TestValueFunctionMarkup; clonedFunctionParameter.WidgetFunctionMarkup = parameter.WidgetFunctionMarkup; DataFacade.AddNew(clonedFunctionParameter); } } private void CloneFunctionCalls(IXsltFunction sourceFunction, IXsltFunction copyTo) { var namedFunctionCalls = DataFacade.GetData<INamedFunctionCall>(nfc => nfc.XsltFunctionId == sourceFunction.Id).ToList(); foreach (INamedFunctionCall namedFunctionCall in namedFunctionCalls) { var clonedFunctionCall = DataFacade.BuildNew<INamedFunctionCall>(); clonedFunctionCall.XsltFunctionId = copyTo.Id; clonedFunctionCall.Name = namedFunctionCall.Name; clonedFunctionCall.SerializedFunction = namedFunctionCall.SerializedFunction; DataFacade.AddNew(clonedFunctionCall); } } private static string GetText(string key) { return StringResourceSystemFacade.GetString("Composite.Plugins.XsltBasedFunction", key); } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/XsltBasedFunctionProviderElementProvider/AddNewXsltFunctionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="AddNewXsltFunctionWorkflow" Location="30; 30" Size="1145; 996" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="AddNewXsltFunctionWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="AddNewXsltFunctionWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="996" Y="71" /> <ns0:Point X="996" Y="713" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="initializeStateActivity" EventHandlerName="stateInitializationActivity1"> <StateDesignerConnector.Segments> <ns0:Point X="234" Y="146" /> <ns0:Point X="243" Y="146" /> <ns0:Point X="243" Y="394" /> <ns0:Point X="235" Y="394" /> <ns0:Point X="235" Y="406" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="validateStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="validateStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Finish"> <StateDesignerConnector.Segments> <ns0:Point X="333" Y="471" /> <ns0:Point X="353" Y="471" /> <ns0:Point X="353" Y="423" /> <ns0:Point X="558" Y="423" /> <ns0:Point X="558" Y="431" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Bottom" SetStateName="setStateActivity6" SourceStateName="step1StateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="step1StateActivity" EventHandlerName="step1EventDrivenActivity_Cancel"> <StateDesignerConnector.Segments> <ns0:Point X="337" Y="495" /> <ns0:Point X="353" Y="495" /> <ns0:Point X="353" Y="873" /> <ns0:Point X="996" Y="873" /> <ns0:Point X="996" Y="793" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Bottom" SetStateName="setStateActivity1" SourceStateName="finalizeStateActivity" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="finalizeStateActivity" EventHandlerName="stateInitializationActivity4"> <StateDesignerConnector.Segments> <ns0:Point X="819" Y="825" /> <ns0:Point X="996" Y="825" /> <ns0:Point X="996" Y="793" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalizeStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="validateStateActivity" SourceConnectionEdge="Right" TargetActivity="finalizeStateActivity" SourceActivity="validateStateActivity" EventHandlerName="validateStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="659" Y="472" /> <ns0:Point X="735" Y="472" /> <ns0:Point X="735" Y="784" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="step1StateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Bottom" SetStateName="setStateActivity4" SourceStateName="validateStateActivity" SourceConnectionEdge="Right" TargetActivity="step1StateActivity" SourceActivity="validateStateActivity" EventHandlerName="validateStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="659" Y="472" /> <ns0:Point X="675" Y="472" /> <ns0:Point X="675" Y="516" /> <ns0:Point X="235" Y="516" /> <ns0:Point X="235" Y="508" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initializeStateActivity" Location="63; 105" Size="175; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="612; 544" Name="stateInitializationActivity1" Location="296; 148"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="592; 463" Name="ifElseActivity_CheckActiveLanguagesExists" Location="306; 210"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="381; 363" Name="ifElseBranchActivity3" Location="325; 281"> <IfElseBranchDesigner.Designers> <IfElseDesigner Size="361; 282" Name="ifElseActivity_PageExists" Location="335; 343"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity5" Location="354; 414"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity" Location="364; 476" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="364; 536" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity6" Location="527; 414"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="MissingPageCodeActivity" Location="537; 476" /> <SetStateDesigner Size="130; 41" Name="setStateActivity8" Location="537; 536" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 363" Name="ifElseBranchActivity4" Location="729; 281"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="MissingActiveLanguageCodeActivity" Location="739; 343" /> <SetStateDesigner Size="130; 41" Name="setStateActivity9" Location="739; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="step1StateActivity" Location="130; 406" Size="211; 102" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="stateInitializationActivity2" Location="138; 437"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="dialogFormActivity1" Location="148; 499" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Finish" Location="138; 461"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="finishHandleExternalEventActivity1" Location="148; 523" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="148; 583" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 182" Name="step1EventDrivenActivity_Cancel" Location="138; 485"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity2" Location="148; 547" /> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="148; 607" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalizeStateActivity" Location="648; 784" Size="175; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 242" Name="stateInitializationActivity4" Location="656; 815"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="closeCurrentViewActivity1" Location="666; 877" /> <CodeDesigner Size="130; 41" Name="finalizecodeActivity" Location="666; 937" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="666; 997" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="916; 713" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="validateStateActivity" Location="454; 431" Size="209; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 303" Name="validateStateInitializationActivity" Location="462; 462"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="361; 222" Name="ifElseActivity1" Location="472; 524"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity1" Location="491; 595"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="501; 657" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity2" Location="664; 595"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="674; 657" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/XsltBasedFunctionProviderElementProvider/Common.cs ================================================ using Composite.Data.Types; namespace Composite.Plugins.Elements.ElementProviders.XsltBasedFunctionProviderElementProvider { internal static class Common { internal static string CreateXslFilePath(this IXsltFunction xsltFunction) { return string.Format("/{0}/{1}.xsl", xsltFunction.Namespace.Replace(".", "/"), xsltFunction.Name).Replace("//", "/").Replace('\\', '/'); } internal static bool ValidateXslFilePath(this IXsltFunction xsltFunction) { if (xsltFunction.XslFilePath == null) return false; if (xsltFunction.XslFilePath.Length > 240) return false; return true; } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/XsltBasedFunctionProviderElementProvider/DeleteXsltFunctionWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; namespace Composite.Plugins.Elements.ElementProviders.XsltBasedFunctionProviderElementProvider { partial class DeleteXsltFunctionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.finishHandleExternalEventActivity2 = new Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity(); this.confirmDialogFormActivity1 = new Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.closeCurrentViewActivity1 = new Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity(); this.codeActivity1 = new System.Workflow.Activities.CodeActivity(); this.confirm_Cancel = new System.Workflow.Activities.EventDrivenActivity(); this.confirm_Finish = new System.Workflow.Activities.EventDrivenActivity(); this.stateInitializationActivity1 = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.deleteStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.confirmStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.deleteStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity2 // this.cancelHandleExternalEventActivity2.EventName = "Cancel"; this.cancelHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity2.Name = "cancelHandleExternalEventActivity2"; // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "deleteStateActivity"; // // finishHandleExternalEventActivity2 // this.finishHandleExternalEventActivity2.EventName = "Finish"; this.finishHandleExternalEventActivity2.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.finishHandleExternalEventActivity2.Name = "finishHandleExternalEventActivity2"; // // confirmDialogFormActivity1 // this.confirmDialogFormActivity1.ContainerLabel = null; this.confirmDialogFormActivity1.FormDefinitionFileName = "/Administrative/DeleteXsltFunctionConfirm.xml"; this.confirmDialogFormActivity1.Name = "confirmDialogFormActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "finalStateActivity"; // // closeCurrentViewActivity1 // this.closeCurrentViewActivity1.Name = "closeCurrentViewActivity1"; // // codeActivity1 // this.codeActivity1.Name = "codeActivity1"; this.codeActivity1.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode); // // confirm_Cancel // this.confirm_Cancel.Activities.Add(this.cancelHandleExternalEventActivity2); this.confirm_Cancel.Activities.Add(this.setStateActivity4); this.confirm_Cancel.Name = "confirm_Cancel"; // // confirm_Finish // this.confirm_Finish.Activities.Add(this.finishHandleExternalEventActivity2); this.confirm_Finish.Activities.Add(this.setStateActivity3); this.confirm_Finish.Name = "confirm_Finish"; // // stateInitializationActivity1 // this.stateInitializationActivity1.Activities.Add(this.confirmDialogFormActivity1); this.stateInitializationActivity1.Name = "stateInitializationActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // deleteStateInitializationActivity // this.deleteStateInitializationActivity.Activities.Add(this.codeActivity1); this.deleteStateInitializationActivity.Activities.Add(this.closeCurrentViewActivity1); this.deleteStateInitializationActivity.Activities.Add(this.setStateActivity1); this.deleteStateInitializationActivity.Name = "deleteStateInitializationActivity"; // // confirmStateActivity // this.confirmStateActivity.Activities.Add(this.stateInitializationActivity1); this.confirmStateActivity.Activities.Add(this.confirm_Finish); this.confirmStateActivity.Activities.Add(this.confirm_Cancel); this.confirmStateActivity.Name = "confirmStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity2); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // deleteStateActivity // this.deleteStateActivity.Activities.Add(this.deleteStateInitializationActivity); this.deleteStateActivity.Name = "deleteStateActivity"; // // DeleteXsltFunctionWorkflow // this.Activities.Add(this.deleteStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.confirmStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "confirmStateActivity"; this.Name = "DeleteXsltFunctionWorkflow"; this.CanModifyActivities = false; } #endregion private CodeActivity codeActivity1; private StateInitializationActivity deleteStateInitializationActivity; private SetStateActivity setStateActivity1; private SetStateActivity setStateActivity2; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private StateActivity finalStateActivity; private Composite.C1Console.Workflow.Activities.ConfirmDialogFormActivity confirmDialogFormActivity1; private EventDrivenActivity confirm_Cancel; private EventDrivenActivity confirm_Finish; private StateInitializationActivity stateInitializationActivity1; private StateActivity confirmStateActivity; private SetStateActivity setStateActivity4; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity2; private SetStateActivity setStateActivity3; private Composite.C1Console.Workflow.Activities.FinishHandleExternalEventActivity finishHandleExternalEventActivity2; private Composite.C1Console.Workflow.Activities.CloseCurrentViewActivity closeCurrentViewActivity1; private StateActivity deleteStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/XsltBasedFunctionProviderElementProvider/DeleteXsltFunctionWorkflow.cs ================================================ using System; using System.Linq; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Workflow; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Logging; using Composite.Core.ResourceSystem; using Composite.Data; using Composite.Data.Plugins.DataProvider.Streams; using Composite.Data.Types; using Composite.Plugins.Elements.ElementProviders.Common; namespace Composite.Plugins.Elements.ElementProviders.XsltBasedFunctionProviderElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class DeleteXsltFunctionWorkflow : BaseFunctionWorkflow { public DeleteXsltFunctionWorkflow() { InitializeComponent(); } private void DeleteFile(IFile file) { FileSystemFileBase baseFile = file as FileSystemFileBase; if(baseFile == null) return; string filePath = baseFile.SystemPath; try { C1File.Delete(filePath); } catch { LoggingService.LogWarning(typeof(DeleteXsltFunctionWorkflow).Name, "Failed to delete file '{0}'".FormatWith(filePath)); } } private void codeActivity1_ExecuteCode(object sender, EventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; IXsltFunction xsltFunction = (IXsltFunction)dataEntityToken.Data; if (DataFacade.WillDeleteSucceed<IXsltFunction>(xsltFunction)) { DeleteTreeRefresher deleteTreeRefresher = this.CreateDeleteTreeRefresher(this.EntityToken); IFile file = IFileServices.TryGetFile<IXsltFile>(xsltFunction.XslFilePath); DataFacade.Delete<IParameter>(f => f.OwnerId == xsltFunction.Id); DataFacade.Delete<INamedFunctionCall>(f => f.XsltFunctionId == xsltFunction.Id); DataFacade.Delete(xsltFunction); DeleteFile(file); int count = (from info in DataFacade.GetData<IXsltFunction>() where info.Namespace == xsltFunction.Namespace select info).Count(); if (count == 0) { RefreshFunctionTree(); } else { deleteTreeRefresher.PostRefreshMesseges(); } } else { this.ShowMessage( DialogType.Error, StringResourceSystemFacade.GetString("Composite.Plugins.XsltBasedFunction", "DeleteXsltFunctionWorkflow.CascadeDeleteErrorTitle"), StringResourceSystemFacade.GetString("Composite.Plugins.XsltBasedFunction", "DeleteXsltFunctionWorkflow.CascadeDeleteErrorMessage") ); } } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/XsltBasedFunctionProviderElementProvider/EditXsltFunctionWorkflow.Designer.cs ================================================ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Drawing; using System.Reflection; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Activities; using System.Workflow.Activities.Rules; using Composite.C1Console.Workflow; namespace Composite.Plugins.Elements.ElementProviders.XsltBasedFunctionProviderElementProvider { partial class EditXsltFunctionWorkflow { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private void InitializeComponent() { this.CanModifyActivities = true; System.Workflow.Activities.CodeCondition codecondition1 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition2 = new System.Workflow.Activities.CodeCondition(); System.Workflow.Activities.CodeCondition codecondition3 = new System.Workflow.Activities.CodeCondition(); this.setStateActivity8 = new System.Workflow.Activities.SetStateActivity(); this.MissingPageCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity3 = new System.Workflow.Activities.SetStateActivity(); this.initializeCodeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElseBranchActivity6 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity5 = new System.Workflow.Activities.IfElseBranchActivity(); this.setStateActivity7 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity6 = new System.Workflow.Activities.SetStateActivity(); this.setStateActivity9 = new System.Workflow.Activities.SetStateActivity(); this.MissingActiveLanguageCodeActivity = new System.Workflow.Activities.CodeActivity(); this.ifElseActivity_CheckPageExists = new System.Workflow.Activities.IfElseActivity(); this.ifElseBranchActivity2 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity1 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity4 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseBranchActivity3 = new System.Workflow.Activities.IfElseBranchActivity(); this.ifElseActivity1 = new System.Workflow.Activities.IfElseActivity(); this.setStateActivity2 = new System.Workflow.Activities.SetStateActivity(); this.saveCodeActivity = new System.Workflow.Activities.CodeActivity(); this.setStateActivity4 = new System.Workflow.Activities.SetStateActivity(); this.editPreviewActivity = new System.Workflow.Activities.CodeActivity(); this.previewHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.PreviewHandleExternalEventActivity(); this.setStateActivity1 = new System.Workflow.Activities.SetStateActivity(); this.saveHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity(); this.documentFormActivity1 = new Composite.C1Console.Workflow.Activities.DocumentFormActivity(); this.ifElseActivity_CheckActiveLanguagesExists = new System.Workflow.Activities.IfElseActivity(); this.validateInitializeStateActivity = new System.Workflow.Activities.StateInitializationActivity(); this.setStateActivity5 = new System.Workflow.Activities.SetStateActivity(); this.cancelHandleExternalEventActivity1 = new Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity(); this.saveStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.editEventDrivenActivity_Preview = new System.Workflow.Activities.EventDrivenActivity(); this.saveEventDrivenActivity_Save = new System.Workflow.Activities.EventDrivenActivity(); this.editStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.initializeStateInitializationActivity = new System.Workflow.Activities.StateInitializationActivity(); this.validateStateActivity = new System.Workflow.Activities.StateActivity(); this.eventDrivenActivity_GlobalCancel = new System.Workflow.Activities.EventDrivenActivity(); this.finalStateActivity = new System.Workflow.Activities.StateActivity(); this.saveStateActivity = new System.Workflow.Activities.StateActivity(); this.editStateActivity = new System.Workflow.Activities.StateActivity(); this.initializeStateActivity = new System.Workflow.Activities.StateActivity(); // // setStateActivity8 // this.setStateActivity8.Name = "setStateActivity8"; this.setStateActivity8.TargetStateName = "finalStateActivity"; // // MissingPageCodeActivity // this.MissingPageCodeActivity.Name = "MissingPageCodeActivity"; this.MissingPageCodeActivity.ExecuteCode += new System.EventHandler(this.MissingPageCodeActivity_ExecuteCode); // // setStateActivity3 // this.setStateActivity3.Name = "setStateActivity3"; this.setStateActivity3.TargetStateName = "editStateActivity"; // // initializeCodeActivity // this.initializeCodeActivity.Name = "initializeCodeActivity"; this.initializeCodeActivity.ExecuteCode += new System.EventHandler(this.initializeCodeActivity_ExecuteCode); // // ifElseBranchActivity6 // this.ifElseBranchActivity6.Activities.Add(this.MissingPageCodeActivity); this.ifElseBranchActivity6.Activities.Add(this.setStateActivity8); this.ifElseBranchActivity6.Name = "ifElseBranchActivity6"; // // ifElseBranchActivity5 // this.ifElseBranchActivity5.Activities.Add(this.initializeCodeActivity); this.ifElseBranchActivity5.Activities.Add(this.setStateActivity3); codecondition1.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckPageExists); this.ifElseBranchActivity5.Condition = codecondition1; this.ifElseBranchActivity5.Name = "ifElseBranchActivity5"; // // setStateActivity7 // this.setStateActivity7.Name = "setStateActivity7"; this.setStateActivity7.TargetStateName = "editStateActivity"; // // setStateActivity6 // this.setStateActivity6.Name = "setStateActivity6"; this.setStateActivity6.TargetStateName = "saveStateActivity"; // // setStateActivity9 // this.setStateActivity9.Name = "setStateActivity9"; this.setStateActivity9.TargetStateName = "finalStateActivity"; // // MissingActiveLanguageCodeActivity // this.MissingActiveLanguageCodeActivity.Name = "MissingActiveLanguageCodeActivity"; this.MissingActiveLanguageCodeActivity.ExecuteCode += new System.EventHandler(this.MissingActiveLanguageCodeActivity_ExecuteCode); // // ifElseActivity_CheckPageExists // this.ifElseActivity_CheckPageExists.Activities.Add(this.ifElseBranchActivity5); this.ifElseActivity_CheckPageExists.Activities.Add(this.ifElseBranchActivity6); this.ifElseActivity_CheckPageExists.Name = "ifElseActivity_CheckPageExists"; // // ifElseBranchActivity2 // this.ifElseBranchActivity2.Activities.Add(this.setStateActivity7); this.ifElseBranchActivity2.Name = "ifElseBranchActivity2"; // // ifElseBranchActivity1 // this.ifElseBranchActivity1.Activities.Add(this.setStateActivity6); codecondition2.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.IsValidData); this.ifElseBranchActivity1.Condition = codecondition2; this.ifElseBranchActivity1.Name = "ifElseBranchActivity1"; // // ifElseBranchActivity4 // this.ifElseBranchActivity4.Activities.Add(this.MissingActiveLanguageCodeActivity); this.ifElseBranchActivity4.Activities.Add(this.setStateActivity9); this.ifElseBranchActivity4.Name = "ifElseBranchActivity4"; // // ifElseBranchActivity3 // this.ifElseBranchActivity3.Activities.Add(this.ifElseActivity_CheckPageExists); codecondition3.Condition += new System.EventHandler<System.Workflow.Activities.ConditionalEventArgs>(this.CheckActiveLanguagesExists); this.ifElseBranchActivity3.Condition = codecondition3; this.ifElseBranchActivity3.Name = "ifElseBranchActivity3"; // // ifElseActivity1 // this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity1); this.ifElseActivity1.Activities.Add(this.ifElseBranchActivity2); this.ifElseActivity1.Name = "ifElseActivity1"; // // setStateActivity2 // this.setStateActivity2.Name = "setStateActivity2"; this.setStateActivity2.TargetStateName = "editStateActivity"; // // saveCodeActivity // this.saveCodeActivity.Name = "saveCodeActivity"; this.saveCodeActivity.ExecuteCode += new System.EventHandler(this.saveCodeActivity_ExecuteCode); // // setStateActivity4 // this.setStateActivity4.Name = "setStateActivity4"; this.setStateActivity4.TargetStateName = "editStateActivity"; // // editPreviewActivity // this.editPreviewActivity.Name = "editPreviewActivity"; this.editPreviewActivity.ExecuteCode += new System.EventHandler(this.editPreviewActivity_ExecuteCode); // // previewHandleExternalEventActivity1 // this.previewHandleExternalEventActivity1.EventName = "Preview"; this.previewHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.previewHandleExternalEventActivity1.Name = "previewHandleExternalEventActivity1"; // // setStateActivity1 // this.setStateActivity1.Name = "setStateActivity1"; this.setStateActivity1.TargetStateName = "validateStateActivity"; // // saveHandleExternalEventActivity1 // this.saveHandleExternalEventActivity1.EventName = "Save"; this.saveHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.saveHandleExternalEventActivity1.Name = "saveHandleExternalEventActivity1"; // // documentFormActivity1 // this.documentFormActivity1.ContainerLabel = null; this.documentFormActivity1.CustomToolbarDefinitionFileName = null; this.documentFormActivity1.FormDefinitionFileName = "\\Administrative\\EditXsltFunction.xml"; this.documentFormActivity1.Name = "documentFormActivity1"; // // ifElseActivity_CheckActiveLanguagesExists // this.ifElseActivity_CheckActiveLanguagesExists.Activities.Add(this.ifElseBranchActivity3); this.ifElseActivity_CheckActiveLanguagesExists.Activities.Add(this.ifElseBranchActivity4); this.ifElseActivity_CheckActiveLanguagesExists.Name = "ifElseActivity_CheckActiveLanguagesExists"; // // validateInitializeStateActivity // this.validateInitializeStateActivity.Activities.Add(this.ifElseActivity1); this.validateInitializeStateActivity.Name = "validateInitializeStateActivity"; // // setStateActivity5 // this.setStateActivity5.Name = "setStateActivity5"; this.setStateActivity5.TargetStateName = "finalStateActivity"; // // cancelHandleExternalEventActivity1 // this.cancelHandleExternalEventActivity1.EventName = "Cancel"; this.cancelHandleExternalEventActivity1.InterfaceType = typeof(Composite.C1Console.Workflow.IFormsWorkflowEventService); this.cancelHandleExternalEventActivity1.Name = "cancelHandleExternalEventActivity1"; // // saveStateInitializationActivity // this.saveStateInitializationActivity.Activities.Add(this.saveCodeActivity); this.saveStateInitializationActivity.Activities.Add(this.setStateActivity2); this.saveStateInitializationActivity.Name = "saveStateInitializationActivity"; // // editEventDrivenActivity_Preview // this.editEventDrivenActivity_Preview.Activities.Add(this.previewHandleExternalEventActivity1); this.editEventDrivenActivity_Preview.Activities.Add(this.editPreviewActivity); this.editEventDrivenActivity_Preview.Activities.Add(this.setStateActivity4); this.editEventDrivenActivity_Preview.Name = "editEventDrivenActivity_Preview"; // // saveEventDrivenActivity_Save // this.saveEventDrivenActivity_Save.Activities.Add(this.saveHandleExternalEventActivity1); this.saveEventDrivenActivity_Save.Activities.Add(this.setStateActivity1); this.saveEventDrivenActivity_Save.Name = "saveEventDrivenActivity_Save"; // // editStateInitializationActivity // this.editStateInitializationActivity.Activities.Add(this.documentFormActivity1); this.editStateInitializationActivity.Name = "editStateInitializationActivity"; // // initializeStateInitializationActivity // this.initializeStateInitializationActivity.Activities.Add(this.ifElseActivity_CheckActiveLanguagesExists); this.initializeStateInitializationActivity.Name = "initializeStateInitializationActivity"; // // validateStateActivity // this.validateStateActivity.Activities.Add(this.validateInitializeStateActivity); this.validateStateActivity.Name = "validateStateActivity"; // // eventDrivenActivity_GlobalCancel // this.eventDrivenActivity_GlobalCancel.Activities.Add(this.cancelHandleExternalEventActivity1); this.eventDrivenActivity_GlobalCancel.Activities.Add(this.setStateActivity5); this.eventDrivenActivity_GlobalCancel.Name = "eventDrivenActivity_GlobalCancel"; // // finalStateActivity // this.finalStateActivity.Name = "finalStateActivity"; // // saveStateActivity // this.saveStateActivity.Activities.Add(this.saveStateInitializationActivity); this.saveStateActivity.Name = "saveStateActivity"; // // editStateActivity // this.editStateActivity.Activities.Add(this.editStateInitializationActivity); this.editStateActivity.Activities.Add(this.saveEventDrivenActivity_Save); this.editStateActivity.Activities.Add(this.editEventDrivenActivity_Preview); this.editStateActivity.Name = "editStateActivity"; // // initializeStateActivity // this.initializeStateActivity.Activities.Add(this.initializeStateInitializationActivity); this.initializeStateActivity.Name = "initializeStateActivity"; // // EditXsltFunctionWorkflow // this.Activities.Add(this.initializeStateActivity); this.Activities.Add(this.editStateActivity); this.Activities.Add(this.saveStateActivity); this.Activities.Add(this.finalStateActivity); this.Activities.Add(this.eventDrivenActivity_GlobalCancel); this.Activities.Add(this.validateStateActivity); this.CompletedStateName = "finalStateActivity"; this.DynamicUpdateCondition = null; this.InitialStateName = "initializeStateActivity"; this.Name = "EditXsltFunctionWorkflow"; this.CanModifyActivities = false; } #endregion private SetStateActivity setStateActivity2; private SetStateActivity setStateActivity1; private Composite.C1Console.Workflow.Activities.SaveHandleExternalEventActivity saveHandleExternalEventActivity1; private SetStateActivity setStateActivity3; private CodeActivity initializeCodeActivity; private StateInitializationActivity saveStateInitializationActivity; private EventDrivenActivity saveEventDrivenActivity_Save; private StateInitializationActivity editStateInitializationActivity; private StateInitializationActivity initializeStateInitializationActivity; private StateActivity saveStateActivity; private StateActivity editStateActivity; private CodeActivity saveCodeActivity; private Composite.C1Console.Workflow.Activities.DocumentFormActivity documentFormActivity1; private Composite.C1Console.Workflow.Activities.PreviewHandleExternalEventActivity previewHandleExternalEventActivity1; private EventDrivenActivity editEventDrivenActivity_Preview; private SetStateActivity setStateActivity4; private CodeActivity editPreviewActivity; private SetStateActivity setStateActivity5; private Composite.C1Console.Workflow.Activities.CancelHandleExternalEventActivity cancelHandleExternalEventActivity1; private EventDrivenActivity eventDrivenActivity_GlobalCancel; private StateActivity finalStateActivity; private StateInitializationActivity validateInitializeStateActivity; private StateActivity validateStateActivity; private SetStateActivity setStateActivity7; private SetStateActivity setStateActivity6; private IfElseBranchActivity ifElseBranchActivity2; private IfElseBranchActivity ifElseBranchActivity1; private IfElseActivity ifElseActivity1; private SetStateActivity setStateActivity8; private CodeActivity MissingPageCodeActivity; private IfElseBranchActivity ifElseBranchActivity6; private IfElseBranchActivity ifElseBranchActivity5; private SetStateActivity setStateActivity9; private CodeActivity MissingActiveLanguageCodeActivity; private IfElseActivity ifElseActivity_CheckPageExists; private IfElseBranchActivity ifElseBranchActivity4; private IfElseBranchActivity ifElseBranchActivity3; private IfElseActivity ifElseActivity_CheckActiveLanguagesExists; private StateActivity initializeStateActivity; } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/XsltBasedFunctionProviderElementProvider/EditXsltFunctionWorkflow.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Transactions; using System.Web; using System.Web.UI; using System.Workflow.Activities; using System.Workflow.Runtime; using System.Xml; using System.Xml.Linq; using System.Xml.Serialization; using System.Xml.Xsl; using Composite.C1Console.Actions; using Composite.C1Console.Events; using Composite.C1Console.Users; using Composite.C1Console.Workflow; using Composite.C1Console.Workflow.Foundation; using Composite.Core.Extensions; using Composite.Core.IO; using Composite.Core.Localization; using Composite.Core.Logging; using Composite.Core.ResourceSystem; using Composite.Core.Threading; using Composite.Core.WebClient; using Composite.Core.WebClient.FlowMediators.FormFlowRendering; using Composite.Core.WebClient.FunctionCallEditor; using Composite.Core.WebClient.Renderings.Page; using Composite.Core.WebClient.State; using Composite.Core.Xml; using Composite.Data; using Composite.Data.Plugins.DataProvider.Streams; using Composite.Data.Transactions; using Composite.Data.Types; using Composite.Data.Validation; using Composite.Functions; using Composite.Functions.ManagedParameters; using Composite.Plugins.Elements.ElementProviders.BaseFunctionProviderElementProvider; using Composite.Plugins.Functions.FunctionProviders.XsltBasedFunctionProvider; using Microsoft.Practices.EnterpriseLibrary.Validation; namespace Composite.Plugins.Elements.ElementProviders.XsltBasedFunctionProviderElementProvider { [EntityTokenLock()] [AllowPersistingWorkflow(WorkflowPersistingType.Idle)] public sealed partial class EditXsltFunctionWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow { public EditXsltFunctionWorkflow() { InitializeComponent(); } private void CheckActiveLanguagesExists(object sender, ConditionalEventArgs e) { e.Result = UserSettings.ActiveLocaleCultureInfo != null; } private void CheckPageExists(object sender, ConditionalEventArgs e) { e.Result = DataFacade.GetData<IPage>().Any(); } private void MissingActiveLanguageCodeActivity_ExecuteCode(object sender, EventArgs e) { ShowMessage(DialogType.Message, GetString("EditXsltFunctionWorkflow.MissingActiveLanguageTitle"), GetString("EditXsltFunctionWorkflow.MissingActiveLanguageMessage")); } private void MissingPageCodeActivity_ExecuteCode(object sender, EventArgs e) { ShowMessage( DialogType.Message, GetString("EditXsltFunctionWorkflow.MissingPageTitle"), GetString("EditXsltFunctionWorkflow.MissingPageMessage")); } private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e) { DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken; IXsltFunction xsltFunction = (IXsltFunction)dataEntityToken.Data; IFile file = IFileServices.GetFile<IXsltFile>(xsltFunction.XslFilePath); IEnumerable<ManagedParameterDefinition> parameters = ManagedParameterManager.Load(xsltFunction.Id); this.Bindings.Add("CurrentXslt", dataEntityToken.Data); this.Bindings.Add("Parameters", parameters); // popular type widgets List<Type> popularTypes = DataFacade.GetAllInterfaces(UserType.Developer); var popularWidgetTypes = FunctionFacade.WidgetFunctionSupportedTypes.Where(f => f.GetGenericArguments().Any(g => popularTypes.Any(h => h.IsAssignableFrom(g)))); IEnumerable<Type> parameterTypeOptions = FunctionFacade.FunctionSupportedTypes.Union(popularWidgetTypes).Union(FunctionFacade.WidgetFunctionSupportedTypes); // At the moment we don't have functions that return IEnumerable<XNode>, so we're hardcoding this type for now parameterTypeOptions = parameterTypeOptions.Union(new [] { typeof (IEnumerable<XNode>) }); this.Bindings.Add("ParameterTypeOptions", parameterTypeOptions.ToList()); string xsltDocumentString = file.ReadAllText(); this.Bindings.Add("XslTemplate", xsltDocumentString); this.Bindings.Add("XslTemplateLastSaveHash", xsltDocumentString.GetHashCode()); List<string> functionErrors; List<NamedFunctionCall> FunctionCalls = RenderHelper.GetValidFunctionCalls(xsltFunction.Id, out functionErrors).ToList(); if ((functionErrors != null) && (functionErrors.Any())) { foreach (string error in functionErrors) { this.ShowMessage(DialogType.Error, "A function call has been dropped", error); } } this.Bindings.Add("FunctionCalls", FunctionCalls); this.Bindings.Add("PageId", PageManager.GetChildrenIDs(Guid.Empty).FirstOrDefault()); if (UserSettings.ActiveLocaleCultureInfo != null) { List<KeyValuePair<string, string>> activeCulturesDictionary = UserSettings.ActiveLocaleCultureInfos.Select(f => new KeyValuePair<string, string>(f.Name,DataLocalizationFacade.GetCultureTitle(f))).ToList(); this.Bindings.Add("ActiveCultureName", UserSettings.ActiveLocaleCultureInfo.Name); this.Bindings.Add("ActiveCulturesList", activeCulturesDictionary); } this.Bindings.Add("PageDataScopeName", DataScopeIdentifier.AdministratedName); this.Bindings.Add("PageDataScopeList", new Dictionary<string, string> { { DataScopeIdentifier.AdministratedName, GetString("EditXsltFunction.LabelAdminitrativeScope") }, { DataScopeIdentifier.PublicName, GetString("EditXsltFunction.LabelPublicScope") } }); // Creating a session state object Guid stateId = Guid.NewGuid(); var state = new FunctionCallDesignerState { WorkflowId = WorkflowInstanceId, ConsoleIdInternal = GetCurrentConsoleId() }; SessionStateManager.DefaultProvider.AddState<IFunctionCallEditorState>(stateId, state, DateTime.Now.AddDays(7.0)); this.Bindings.Add("SessionStateProvider", SessionStateManager.DefaultProviderName); this.Bindings.Add("SessionStateId", stateId); } private void IsValidData(object sender, ConditionalEventArgs e) { IXsltFunction function = this.GetBinding<IXsltFunction>("CurrentXslt"); if (function.Name == string.Empty) { this.ShowFieldMessage("CurrentXslt.Name", GetString("EditXsltFunctionWorkflow.EmptyMethodName")); e.Result = false; return; } if (string.IsNullOrWhiteSpace(function.Namespace)) { this.ShowFieldMessage("CurrentXslt.Namespace", GetString("EditXsltFunctionWorkflow.NamespaceEmpty")); return; } if (!function.Namespace.IsCorrectNamespace('.')) { this.ShowFieldMessage("CurrentXslt.Namespace", GetString("EditXsltFunctionWorkflow.InvalidNamespace")); e.Result = false; return; } if (!(function.XslFilePath.StartsWith("\\") || function.XslFilePath.StartsWith("/"))) { this.ShowFieldMessage("CurrentXslt.Name", GetString("EditXsltFunctionWorkflow.InvalidFileName")); e.Result = false; return; } function.XslFilePath = function.CreateXslFilePath(); ValidationResults validationResults = ValidationFacade.Validate<IXsltFunction>(function); if (!validationResults.IsValid) { foreach (ValidationResult result in validationResults) { this.ShowFieldMessage(string.Format("{0}.{1}", "CurrentXslt", result.Key), result.Message); } return; } if (!function.ValidateXslFilePath()) { this.ShowFieldMessage("NewXslt.Name", GetString("AddNewXsltFunctionWorkflow.TotalNameTooLang")); return; } IXsltFile xsltfile = DataFacade.BuildNew<IXsltFile>(); xsltfile.FolderPath = System.IO.Path.GetDirectoryName(function.XslFilePath); xsltfile.FileName = System.IO.Path.GetFileName(function.XslFilePath); if (!DataFacade.ValidatePath(xsltfile, "XslFileProvider")) { this.ShowFieldMessage("CurrentXslt.Name", GetString("EditXsltFunctionWorkflow.TotalNameTooLang")); return; } e.Result = true; } private void editPreviewActivity_ExecuteCode(object sender, EventArgs e) { Stopwatch functionCallingStopwatch = null; long millisecondsToken = 0; CultureInfo oldCurrentCulture = Thread.CurrentThread.CurrentCulture; CultureInfo oldCurrentUICulture = Thread.CurrentThread.CurrentUICulture; try { IXsltFunction xslt = this.GetBinding<IXsltFunction>("CurrentXslt"); string xslTemplate = this.GetBinding<string>("XslTemplate"); IFile persistemTemplateFile = IFileServices.TryGetFile<IXsltFile>(xslt.XslFilePath); if (persistemTemplateFile != null) { string persistemTemplate = persistemTemplateFile.ReadAllText(); if (this.GetBinding<int>("XslTemplateLastSaveHash") != persistemTemplate.GetHashCode()) { xslTemplate = persistemTemplate; ConsoleMessageQueueFacade.Enqueue(new LogEntryMessageQueueItem { Level = LogLevel.Fine, Message = "XSLT file on file system was used. It has been changed by another process.", Sender = this.GetType() }, this.GetCurrentConsoleId()); } } List<NamedFunctionCall> namedFunctions = this.GetBinding<IEnumerable<NamedFunctionCall>>("FunctionCalls").ToList(); // If preview is done multiple times in a row, with no postbacks an object reference to BaseFunctionRuntimeTreeNode may be held // If the function in the BaseFunctionRuntimeTreeNode have ben unloaded / reloaded, this preview will still run on the old instance // We force refresh by serializing / deserializing foreach (NamedFunctionCall namedFunction in namedFunctions) { namedFunction.FunctionCall = (BaseFunctionRuntimeTreeNode)FunctionFacade.BuildTree(namedFunction.FunctionCall.Serialize()); } List<ManagedParameterDefinition> parameterDefinitions = this.GetBinding<IEnumerable<ManagedParameterDefinition>>("Parameters").ToList(); Guid pageId = this.GetBinding<Guid>("PageId"); string dataScopeName = this.GetBinding<string>("PageDataScopeName"); string cultureName = this.GetBinding<string>("ActiveCultureName"); CultureInfo cultureInfo = null; if (cultureName != null) { cultureInfo = CultureInfo.CreateSpecificCulture(cultureName); } IPage page; TransformationInputs transformationInput; using (new DataScope(DataScopeIdentifier.Deserialize(dataScopeName), cultureInfo)) { Thread.CurrentThread.CurrentCulture = cultureInfo; Thread.CurrentThread.CurrentUICulture = cultureInfo; page = DataFacade.GetData<IPage>(f => f.Id == pageId).FirstOrDefault(); if (page != null) { PageRenderer.CurrentPage = page; } functionCallingStopwatch = Stopwatch.StartNew(); transformationInput = RenderHelper.BuildInputDocument(namedFunctions, parameterDefinitions, true); functionCallingStopwatch.Stop(); Thread.CurrentThread.CurrentCulture = oldCurrentCulture; Thread.CurrentThread.CurrentUICulture = oldCurrentUICulture; } string output = ""; string error = ""; try { Thread.CurrentThread.CurrentCulture = cultureInfo; Thread.CurrentThread.CurrentUICulture = cultureInfo; var styleSheet = XElement.Parse(xslTemplate); XsltBasedFunctionProvider.ResolveImportIncludePaths(styleSheet); LocalizationParser.Parse(styleSheet); XDocument transformationResult = new XDocument(); using (XmlWriter writer = new LimitedDepthXmlWriter(transformationResult.CreateWriter())) { XslCompiledTransform xslTransformer = new XslCompiledTransform(); xslTransformer.Load(styleSheet.CreateReader(), XsltSettings.TrustedXslt, new XmlUrlResolver()); XsltArgumentList transformArgs = new XsltArgumentList(); XslExtensionsManager.Register(transformArgs); if (transformationInput.ExtensionDefinitions != null) { foreach (IXsltExtensionDefinition extensionDef in transformationInput.ExtensionDefinitions) { transformArgs.AddExtensionObject(extensionDef.ExtensionNamespace.ToString(), extensionDef.EntensionObjectAsObject); } } Exception exception = null; HttpContext httpContext = HttpContext.Current; Thread thread = new Thread(delegate() { Thread.CurrentThread.CurrentCulture = cultureInfo; Thread.CurrentThread.CurrentUICulture = cultureInfo; Stopwatch transformationStopwatch = Stopwatch.StartNew(); try { using (ThreadDataManager.Initialize()) using (new DataScope(DataScopeIdentifier.Deserialize(dataScopeName), cultureInfo)) { HttpContext.Current = httpContext; var reader = transformationInput.InputDocument.CreateReader(); xslTransformer.Transform(reader, transformArgs, writer); } } catch (ThreadAbortException ex) { exception = ex; Thread.ResetAbort(); } catch (Exception ex) { exception = ex; } transformationStopwatch.Stop(); millisecondsToken = transformationStopwatch.ElapsedMilliseconds; }); thread.Start(); bool res = thread.Join(1000); // sadly, this needs to be low enough to prevent StackOverflowException from fireing. if (res == false) { if (thread.ThreadState == System.Threading.ThreadState.Running) { thread.Abort(); } throw new XslLoadException("Transformation took more than 1000 milliseconds to complete. This could be due to a never ending recursive call. Execution aborted to prevent fatal StackOverflowException."); } if (exception != null) { throw exception; } } if (xslt.OutputXmlSubType == "XHTML") { XhtmlDocument xhtmlDocument = new XhtmlDocument(transformationResult); output = xhtmlDocument.Root.ToString(); } else { output = transformationResult.Root.ToString(); } } catch (Exception ex) { output = "<error/>"; error = string.Format("{0}\n{1}", ex.GetType().Name, ex.Message); Exception inner = ex.InnerException; string indent = ""; while (inner != null) { indent = indent + " - "; error = error + "\n" + indent + inner.Message; inner = inner.InnerException; } } finally { Thread.CurrentThread.CurrentCulture = oldCurrentCulture; Thread.CurrentThread.CurrentUICulture = oldCurrentUICulture; } Page currentPage = HttpContext.Current.Handler as Page; if (currentPage == null) throw new InvalidOperationException("The Current HttpContext Handler must be a System.Web.Ui.Page"); UserControl inOutControl = (UserControl)currentPage.LoadControl(UrlUtils.ResolveAdminUrl("controls/Misc/MarkupInOutView.ascx")); inOutControl.Attributes.Add("in", transformationInput.InputDocument.ToString()); inOutControl.Attributes.Add("out", output); inOutControl.Attributes.Add("error", error); inOutControl.Attributes.Add("statusmessage", string.Format("Execution times: Total {0} ms. Functions: {1} ms. XSLT: {2} ms.", millisecondsToken + functionCallingStopwatch.ElapsedMilliseconds, functionCallingStopwatch.ElapsedMilliseconds, millisecondsToken)); FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); var webRenderService = serviceContainer.GetService<IFormFlowWebRenderingService>(); webRenderService.SetNewPageOutput(inOutControl); } catch (Exception ex) { FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); Control errOutput = new LiteralControl("<pre>" + ex.ToString() + "</pre>"); var webRenderService = serviceContainer.GetService<IFormFlowWebRenderingService>(); webRenderService.SetNewPageOutput(errOutput); } } private IEnumerable<INamedFunctionCall> ConvertFunctionCalls(IEnumerable<NamedFunctionCall> FunctionCalls, Guid xsltId) { foreach (NamedFunctionCall namedFunctionCall in FunctionCalls) { INamedFunctionCall newNamedFunctionCall = DataFacade.BuildNew<INamedFunctionCall>(); newNamedFunctionCall.XsltFunctionId = xsltId; newNamedFunctionCall.Name = namedFunctionCall.Name; newNamedFunctionCall.SerializedFunction = namedFunctionCall.FunctionCall.Serialize().ToString(SaveOptions.DisableFormatting); yield return newNamedFunctionCall; } } private void saveCodeActivity_ExecuteCode(object sender, EventArgs e) { try { IXsltFunction xslt = this.GetBinding<IXsltFunction>("CurrentXslt"); IXsltFunction previousXslt = DataFacade.GetData<IXsltFunction>(f => f.Id == xslt.Id).SingleOrDefault(); IFile persistemTemplateFile = IFileServices.TryGetFile<IXsltFile>(xslt.XslFilePath); if (persistemTemplateFile != null) { string persistemTemplate = (persistemTemplateFile != null ? persistemTemplateFile.ReadAllText() : ""); if (this.GetBinding<int>("XslTemplateLastSaveHash") != persistemTemplate.GetHashCode()) { this.Bindings["XslTemplate"] = persistemTemplate; this.RerenderView(); ConsoleMessageQueueFacade.Enqueue(new LogEntryMessageQueueItem { Level = LogLevel.Fine, Message = "XSLT file on file system has been changed by another process. In-browser editor updated to reflect file on file system.", Sender = this.GetType() }, this.GetCurrentConsoleId()); } } string xslTemplate = this.GetBinding<string>("XslTemplate"); var parameters = this.GetBinding<IEnumerable<ManagedParameterDefinition>>("Parameters"); IEnumerable<NamedFunctionCall> FunctionCalls = this.GetBinding<IEnumerable<NamedFunctionCall>>("FunctionCalls"); if (FunctionCalls.Select(f => f.Name).Distinct().Count() != FunctionCalls.Count()) { ShowMessage(DialogType.Error, GetString("EditXsltFunctionWorkflow.SameLocalFunctionNameClashTitle"), GetString("EditXsltFunctionWorkflow.SameLocalFunctionNameClashMessage")); return; } using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { // Renaming related file if necessary string oldRelativePath = previousXslt.XslFilePath.Replace('\\', '/'); // This replace takes care of old paths having \ in them string newRelativePath = xslt.CreateXslFilePath(); if (string.Compare(oldRelativePath, newRelativePath, true) != 0) { var xlsFile = IFileServices.GetFile<IXsltFile>(previousXslt.XslFilePath); string systemPath = (xlsFile as FileSystemFileBase).SystemPath; // Implement it in another way? string xsltFilesRoot = systemPath.Substring(0, systemPath.Length - previousXslt.XslFilePath.Length); string newSystemPath = (xsltFilesRoot + newRelativePath).Replace('\\', '/'); if ((string.Compare(systemPath, newSystemPath, true) != 0) && C1File.Exists(newSystemPath)) { FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); var consoleMessageService = serviceContainer.GetService<IManagementConsoleMessageService>(); consoleMessageService.ShowMessage( DialogType.Error, GetString("EditXsltFunctionWorkflow.InvalidName"), GetString("EditXsltFunctionWorkflow.CannotRenameFileExists").FormatWith(newSystemPath)); return; } string directoryPath = Path.GetDirectoryName(newSystemPath); if (!C1Directory.Exists(directoryPath)) { C1Directory.CreateDirectory(directoryPath); } C1File.Move(systemPath, newSystemPath); xslt.XslFilePath = newRelativePath; // TODO: Implement removing empty Xslt directories } IFile file = IFileServices.GetFile<IXsltFile>(xslt.XslFilePath); file.SetNewContent(xslTemplate); ManagedParameterManager.Save(xslt.Id, parameters); DataFacade.Update(xslt); DataFacade.Update(file); this.Bindings["XslTemplateLastSaveHash"] = xslTemplate.GetHashCode(); DataFacade.Delete<INamedFunctionCall>(f => f.XsltFunctionId == xslt.Id); DataFacade.AddNew<INamedFunctionCall>(ConvertFunctionCalls(FunctionCalls, xslt.Id)); transactionScope.Complete(); } if (previousXslt.Namespace != xslt.Namespace || previousXslt.Name != xslt.Name || previousXslt.Description != xslt.Description) { // This is a some what nasty hack. Due to the nature of the BaseFunctionProviderElementProvider, this hack is needed BaseFunctionFolderElementEntityToken entityToken = new BaseFunctionFolderElementEntityToken("ROOT:XsltBasedFunctionProviderElementProvider"); RefreshEntityToken(entityToken); } SetSaveStatus(true); } catch (Exception ex) { LoggingService.LogCritical("XSLT Save", ex); FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId); var consoleMsgService = serviceContainer.GetService<IManagementConsoleMessageService>(); consoleMsgService.ShowMessage(DialogType.Error, "Error", ex.Message); SetSaveStatus(false); } } private static string GetString(string key) { return StringResourceSystemFacade.GetString("Composite.Plugins.XsltBasedFunction", key); } // This is for propergating error message with never ending recursive calls private sealed class XslLoadException : Exception { public XslLoadException(string message) : base(message) { } } [Serializable] public sealed class FunctionCallDesignerState : IFunctionCallEditorState { public Guid WorkflowId { get; set; } public string ConsoleIdInternal { get; set; } private FormData GetFormData() { var formData = WorkflowFacade.GetFormData(WorkflowId); Verify.IsNotNull(formData, "Failed to get form data, workflow may have been aborted!"); return formData; } #region IFunctionCallEditorState Members [XmlIgnore] public List<NamedFunctionCall> FunctionCalls { get { return GetFormData().Bindings["FunctionCalls"] as List<NamedFunctionCall>; } set { GetFormData().Bindings["FunctionCalls"] = value; } } [XmlIgnore] public List<ManagedParameterDefinition> Parameters { get { return GetFormData().Bindings["Parameters"] as List<ManagedParameterDefinition>; } set { GetFormData().Bindings["Parameters"] = value; } } [XmlIgnore] public List<Type> ParameterTypeOptions { get { return (GetFormData().Bindings["ParameterTypeOptions"] as IEnumerable<Type>).ToList(); } set { GetFormData().Bindings["ParameterTypeOptions"] = value.ToList(); } } public bool WidgetFunctionSelection { get { return false; } } public bool ShowLocalFunctionNames { get { return true; } } public bool AllowLocalFunctionNameEditing { get { return true; } } public bool AllowSelectingInputParameters { get { return true; } } public Type[] AllowedResultTypes { get { return new[] { typeof (XDocument), typeof (XElement), typeof (IEnumerable<XElement>), typeof(bool), typeof(int), typeof(decimal), typeof(string), typeof(DateTime), typeof(Guid), typeof(CultureInfo), typeof(IDataReference), typeof(IXsltExtensionDefinition)}; } } public int MaxFunctionAllowed { get { return 1000; } } string IFunctionCallEditorState.ConsoleId { get { return ConsoleIdInternal; } } #endregion } } } ================================================ FILE: Composite.Workflows/Plugins/Elements/ElementProviders/XsltBasedFunctionProviderElementProvider/EditXsltFunctionWorkflow.layout ================================================ <StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="EditXsltFunctionWorkflow" Location="30; 30" Size="1145; 996" AutoSize="False" AutoSizeMargin="16; 24" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"> <StateMachineWorkflowDesigner.DesignerConnectors> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="finalStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity5" SourceStateName="EditXsltFunctionWorkflow" SourceConnectionEdge="Right" TargetActivity="finalStateActivity" SourceActivity="EditXsltFunctionWorkflow" EventHandlerName="eventDrivenActivity_GlobalCancel"> <StateDesignerConnector.Segments> <ns0:Point X="240" Y="71" /> <ns0:Point X="901" Y="71" /> <ns0:Point X="901" Y="673" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity3" SourceStateName="initializeStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="initializeStateActivity" EventHandlerName="initializeStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="269" Y="146" /> <ns0:Point X="418" Y="146" /> <ns0:Point X="418" Y="259" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="validateStateActivity" SourceConnectionIndex="1" TargetConnectionEdge="Top" SetStateName="setStateActivity1" SourceStateName="editStateActivity" SourceConnectionEdge="Right" TargetActivity="validateStateActivity" SourceActivity="editStateActivity" EventHandlerName="saveEventDrivenActivity_Save"> <StateDesignerConnector.Segments> <ns0:Point X="507" Y="324" /> <ns0:Point X="534" Y="324" /> <ns0:Point X="534" Y="515" /> <ns0:Point X="158" Y="515" /> <ns0:Point X="158" Y="527" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="2" TargetConnectionEdge="Top" SetStateName="setStateActivity4" SourceStateName="editStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="editStateActivity" EventHandlerName="editEventDrivenActivity_Preview"> <StateDesignerConnector.Segments> <ns0:Point X="518" Y="348" /> <ns0:Point X="530" Y="348" /> <ns0:Point X="530" Y="251" /> <ns0:Point X="418" Y="251" /> <ns0:Point X="418" Y="259" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity2" SourceStateName="saveStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="saveStateActivity" EventHandlerName="saveStateInitializationActivity"> <StateDesignerConnector.Segments> <ns0:Point X="612" Y="675" /> <ns0:Point X="626" Y="675" /> <ns0:Point X="626" Y="251" /> <ns0:Point X="418" Y="251" /> <ns0:Point X="418" Y="259" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="saveStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity6" SourceStateName="validateStateActivity" SourceConnectionEdge="Right" TargetActivity="saveStateActivity" SourceActivity="validateStateActivity" EventHandlerName="validateInitializeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="249" Y="568" /> <ns0:Point X="519" Y="568" /> <ns0:Point X="519" Y="634" /> </StateDesignerConnector.Segments> </StateDesignerConnector> <StateDesignerConnector TargetConnectionIndex="0" TargetStateName="editStateActivity" SourceConnectionIndex="0" TargetConnectionEdge="Top" SetStateName="setStateActivity7" SourceStateName="validateStateActivity" SourceConnectionEdge="Right" TargetActivity="editStateActivity" SourceActivity="validateStateActivity" EventHandlerName="validateInitializeStateActivity"> <StateDesignerConnector.Segments> <ns0:Point X="249" Y="568" /> <ns0:Point X="265" Y="568" /> <ns0:Point X="265" Y="251" /> <ns0:Point X="418" Y="251" /> <ns0:Point X="418" Y="259" /> </StateDesignerConnector.Segments> </StateDesignerConnector> </StateMachineWorkflowDesigner.DesignerConnectors> <StateMachineWorkflowDesigner.Designers> <StateDesigner Name="initializeStateActivity" Location="63; 105" Size="210; 80" AutoSize="False" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="612; 544" Name="initializeStateInitializationActivity" Location="296; 148"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="592; 463" Name="ifElseActivity_CheckActiveLanguagesExists" Location="306; 210"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="381; 363" Name="ifElseBranchActivity3" Location="325; 281"> <IfElseBranchDesigner.Designers> <IfElseDesigner Size="361; 282" Name="ifElseActivity_CheckPageExists" Location="335; 343"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity5" Location="354; 414"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="initializeCodeActivity" Location="364; 476" /> <SetStateDesigner Size="130; 41" Name="setStateActivity3" Location="364; 536" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 182" Name="ifElseBranchActivity6" Location="527; 414"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="MissingPageCodeActivity" Location="537; 476" /> <SetStateDesigner Size="130; 41" Name="setStateActivity8" Location="537; 536" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 363" Name="ifElseBranchActivity4" Location="729; 281"> <IfElseBranchDesigner.Designers> <CodeDesigner Size="130; 41" Name="MissingActiveLanguageCodeActivity" Location="739; 343" /> <SetStateDesigner Size="130; 41" Name="setStateActivity9" Location="739; 403" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="editStateActivity" Location="314; 259" Size="208; 118" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 122" Name="editStateInitializationActivity" Location="322; 290"> <StateInitializationDesigner.Designers> <ActivityDesigner Size="130; 41" Name="documentFormActivity1" Location="332; 352" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> <EventDrivenDesigner Size="150; 182" Name="saveEventDrivenActivity_Save" Location="322; 314"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="saveHandleExternalEventActivity1" Location="332; 376" /> <SetStateDesigner Size="130; 41" Name="setStateActivity1" Location="332; 436" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <EventDrivenDesigner Size="150; 242" Name="editEventDrivenActivity_Preview" Location="322; 338"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="previewHandleExternalEventActivity1" Location="332; 400" /> <CodeDesigner Size="130; 41" Name="editPreviewActivity" Location="332; 460" /> <SetStateDesigner Size="130; 41" Name="setStateActivity4" Location="332; 520" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="saveStateActivity" Location="423; 634" Size="193; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="150; 182" Name="saveStateInitializationActivity" Location="431; 665"> <StateInitializationDesigner.Designers> <CodeDesigner Size="130; 41" Name="saveCodeActivity" Location="441; 727" /> <SetStateDesigner Size="130; 41" Name="setStateActivity2" Location="441; 787" /> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> <StateDesigner Name="finalStateActivity" Location="821; 673" Size="160; 80" AutoSizeMargin="16; 24" /> <EventDrivenDesigner Size="150; 182" Name="eventDrivenActivity_GlobalCancel" Location="38; 61"> <EventDrivenDesigner.Designers> <HandleExternalEventActivityDesigner Size="130; 41" Name="cancelHandleExternalEventActivity1" Location="48; 123" /> <SetStateDesigner Size="130; 41" Name="setStateActivity5" Location="48; 183" /> </EventDrivenDesigner.Designers> </EventDrivenDesigner> <StateDesigner Name="validateStateActivity" Location="63; 527" Size="190; 80" AutoSizeMargin="16; 24"> <StateDesigner.Designers> <StateInitializationDesigner Size="381; 303" Name="validateInitializeStateActivity" Location="71; 558"> <StateInitializationDesigner.Designers> <IfElseDesigner Size="361; 222" Name="ifElseActivity1" Location="81; 620"> <IfElseDesigner.Designers> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity1" Location="100; 691"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity6" Location="110; 753" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> <IfElseBranchDesigner Size="150; 122" Name="ifElseBranchActivity2" Location="273; 691"> <IfElseBranchDesigner.Designers> <SetStateDesigner Size="130; 41" Name="setStateActivity7" Location="283; 753" /> </IfElseBranchDesigner.Designers> </IfElseBranchDesigner> </IfElseDesigner.Designers> </IfElseDesigner> </StateInitializationDesigner.Designers> </StateInitializationDesigner> </StateDesigner.Designers> </StateDesigner> </StateMachineWorkflowDesigner.Designers> </StateMachineWorkflowDesigner> ================================================ FILE: Composite.Workflows/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. See also Composite SharedAssemblyInfo.cs [assembly: AssemblyDescription("C1 CMS Workflow Foundation classes")] [assembly: AssemblyConfiguration("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("88dc8435-878f-482a-8def-bcc6c7210f3e")] [assembly: InternalsVisibleTo("UpgradePackage")] ================================================ FILE: Composite.Workflows/packages.config ================================================ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="Microsoft.AspNet.Razor" version="3.2.3" targetFramework="net45" /> <package id="Microsoft.AspNet.WebPages" version="3.2.3" targetFramework="net45" /> <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" /> </packages> ================================================ FILE: CompositeC1.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.25123.0 MinimumVisualStudioVersion = 14.0.0.0 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{44113BBC-CB18-41CF-AB26-6D190BA4E117}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebSite", "Website\WebSite.csproj", "{D0A3D7D5-1D1F-40BC-89C1-93CDCEDF262C}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Composite.Workflows", "Composite.Workflows\Composite.Workflows.csproj", "{1FE08476-346A-4053-813D-8807C0E0FC36}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Composite", "Composite\Composite.csproj", "{F8D87A5F-D090-4D24-80C1-DBCD938C6CAB}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|.NET = Debug|.NET Debug|Any CPU = Debug|Any CPU Debug|Mixed Platforms = Debug|Mixed Platforms Release|.NET = Release|.NET Release|Any CPU = Release|Any CPU Release|Mixed Platforms = Release|Mixed Platforms EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {D0A3D7D5-1D1F-40BC-89C1-93CDCEDF262C}.Debug|.NET.ActiveCfg = Debug|Any CPU {D0A3D7D5-1D1F-40BC-89C1-93CDCEDF262C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D0A3D7D5-1D1F-40BC-89C1-93CDCEDF262C}.Debug|Any CPU.Build.0 = Debug|Any CPU {D0A3D7D5-1D1F-40BC-89C1-93CDCEDF262C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {D0A3D7D5-1D1F-40BC-89C1-93CDCEDF262C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {D0A3D7D5-1D1F-40BC-89C1-93CDCEDF262C}.Release|.NET.ActiveCfg = Release|Any CPU {D0A3D7D5-1D1F-40BC-89C1-93CDCEDF262C}.Release|Any CPU.ActiveCfg = Release|Any CPU {D0A3D7D5-1D1F-40BC-89C1-93CDCEDF262C}.Release|Any CPU.Build.0 = Release|Any CPU {D0A3D7D5-1D1F-40BC-89C1-93CDCEDF262C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {D0A3D7D5-1D1F-40BC-89C1-93CDCEDF262C}.Release|Mixed Platforms.Build.0 = Release|Any CPU {1FE08476-346A-4053-813D-8807C0E0FC36}.Debug|.NET.ActiveCfg = Debug|Any CPU {1FE08476-346A-4053-813D-8807C0E0FC36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1FE08476-346A-4053-813D-8807C0E0FC36}.Debug|Any CPU.Build.0 = Debug|Any CPU {1FE08476-346A-4053-813D-8807C0E0FC36}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {1FE08476-346A-4053-813D-8807C0E0FC36}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {1FE08476-346A-4053-813D-8807C0E0FC36}.Release|.NET.ActiveCfg = Release|Any CPU {1FE08476-346A-4053-813D-8807C0E0FC36}.Release|Any CPU.ActiveCfg = Release|Any CPU {1FE08476-346A-4053-813D-8807C0E0FC36}.Release|Any CPU.Build.0 = Release|Any CPU {1FE08476-346A-4053-813D-8807C0E0FC36}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {1FE08476-346A-4053-813D-8807C0E0FC36}.Release|Mixed Platforms.Build.0 = Release|Any CPU {F8D87A5F-D090-4D24-80C1-DBCD938C6CAB}.Debug|.NET.ActiveCfg = Debug|Any CPU {F8D87A5F-D090-4D24-80C1-DBCD938C6CAB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F8D87A5F-D090-4D24-80C1-DBCD938C6CAB}.Debug|Any CPU.Build.0 = Debug|Any CPU {F8D87A5F-D090-4D24-80C1-DBCD938C6CAB}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {F8D87A5F-D090-4D24-80C1-DBCD938C6CAB}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {F8D87A5F-D090-4D24-80C1-DBCD938C6CAB}.Release|.NET.ActiveCfg = Release|Any CPU {F8D87A5F-D090-4D24-80C1-DBCD938C6CAB}.Release|Any CPU.ActiveCfg = Release|Any CPU {F8D87A5F-D090-4D24-80C1-DBCD938C6CAB}.Release|Any CPU.Build.0 = Release|Any CPU {F8D87A5F-D090-4D24-80C1-DBCD938C6CAB}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {F8D87A5F-D090-4D24-80C1-DBCD938C6CAB}.Release|Mixed Platforms.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: Install.ps1 ================================================ param($installPath, $toolsPath, $package, $project) $asms = $package.AssemblyReferences | %{$_.Name} foreach ($reference in $project.Object.References) { if ($asms -contains $reference.Name + ".dll") { $reference.CopyLocal = $false; } } ================================================ FILE: Package.ConsoleComponents.nuspec ================================================ <?xml version="1.0"?> <package > <metadata> <id>C1CMS.ConsoleComponents</id> <title>C1 CMS Console Components $version$ Orckestra A/S Orckestra A/S https://c1.orckestra.com/MPL11 https://github.com/Orckestra/C1-CMS-Foundation true Contains React components distributed with C1 CMS. Copyright 2017 C1CMS cms ================================================ FILE: Package.nuspec ================================================ C1CMS.Assemblies C1 CMS Assemblies $version$ Orckestra A/S Orckestra A/S https://c1.orckestra.com/MPL11 https://github.com/Orckestra/C1-CMS-Foundation true Contains dll-s distributed with C1 CMS. Copyright 2018 C1CMS OrckestraCMS CompositeC1 cms ================================================ FILE: README.md ================================================ # C1 CMS Foundation[![Reviews here...!](http://hackathon.composite.net/maw/github/reviews.png)](https://www.facebook.com/pg/C1CMS/reviews) C1 CMS Foundation - a .NET based Web Content Management System, open source and a bundle of joy! [![screen shots from the new C1 user interface (the C1 Console)](http://hackathon.composite.net/maw/github/6-pack-screenshots-small.png)](http://hackathon.composite.net/maw/github/6-pack-screenshots.png) [![Join the chat at https://gitter.im/Orckestra/C1-CMS](https://badges.gitter.im/Orckestra/C1-CMS.svg)](https://gitter.im/Orckestra/C1-CMS?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) ## Getting started ## Visit http://docs.c1.orckestra.com/Getting-started/Guide ## Download ## Download binaries from https://github.com/Orckestra/CMS-Foundation/releases/latest ## Forums ## Head over to https://gitter.im/Orckestra/C1-CMS or add an issue ## Who are we? ## Orckestra is the company driving the development of C1 CMS Foundation. We have a team working full time on this CMS and on other cool stuff you can add to it. We are situated in Montreal, Copenhagen and Kiev. We specialize in enterprise omni channel commerce software. You can visit us at http://c1.orckestra.com and http://www.orckestra.com/ ================================================ FILE: Website/.bowerrc ================================================ { "directory": "bower_components" } ================================================ FILE: Website/.eslintignore ================================================ jspm.config.js jspm.production.js Website/Composite/console.js gruntfile.js ================================================ FILE: Website/.eslintrc.json ================================================ { "env": { "browser": true, "es6": true, "node": true, "mocha": true }, "extends": ["eslint:recommended", "plugin:react/recommended"], "parserOptions": { "ecmaFeatures": { "experimentalObjectRestSpread": true, "jsx": true }, "sourceType": "module" }, "plugins": [ "react", "mocha" ], "rules": { "indent": [ "error", "tab" ], "linebreak-style": [ "error", "windows" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ] } } ================================================ FILE: Website/.npmignore ================================================ * *.* */*.* !/Composite/console/**/* ================================================ FILE: Website/Composite/CompileScripts.xml ================================================ ================================================ FILE: Website/Composite/Login.aspx.cs ================================================ using System; using System.Web.Hosting; using Composite.C1Console.Security; using Composite.Core.Configuration; public partial class Composite_Management_Login : System.Web.UI.Page { protected void Page_Init(object sender, EventArgs e) { if (!SystemSetupFacade.IsSystemFirstTimeInitialized) { Response.Redirect("/Composite"); return; } if (UserValidationFacade.IsLoggedIn()) { RedirectToReturnUrl(); return; } if (Request.RequestType == "POST") { OnPost(); } } private void RedirectToReturnUrl() { var returnUrl = Request.QueryString["ReturnUrl"]; try { Uri uri = new Uri(returnUrl); if (uri.Host != Request.Url.Host) { returnUrl = null; // prevent "Arbitrary Redirection" attacks } } catch (Exception) { } if (!string.IsNullOrEmpty(returnUrl)) { Response.Redirect(returnUrl, false); return; } Response.Redirect(HostingEnvironment.ApplicationVirtualPath, false); } private void OnPost() { bool isValid = true; string username = Request.Form["txtUsername"]; string password = Request.Form["txtPassword"]; if (string.IsNullOrEmpty(username)) { isValid = false; txtUsername.Attributes["class"] = "error"; } if (string.IsNullOrEmpty(password)) { isValid = false; txtPassword.Attributes["class"] = "error"; } txtUsername.Attributes.Add("value", username); if(isValid) { if(UserValidationFacade.FormValidateUser(username, password) == LoginResult.Success) { RedirectToReturnUrl(); return; } divLoginFailed.Visible = true; } } } ================================================ FILE: Website/Composite/Login.aspx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ public partial class Composite_Management_Login { /// /// divLoginFailed control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlGenericControl divLoginFailed; /// /// txtUsername control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlInputText txtUsername; /// /// txtPassword control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlInputPassword txtPassword; } ================================================ FILE: Website/Composite/Welcome.js ================================================ var Welcome = new function () { var TIME = 750; var setup = null; var clone = null; var hasSetup = false; var hasLanguages = false; var hasBlock = false; var hasLength = false; var tabindex = 0; var progressNotchIndex = 1; var progressLoading = null; /** * @type {String} */ this.params = new String(""); /** * Results are real. UI is fake ;) */ this.test = function () { EventBroadcaster.subscribe(BroadcastMessages.KEY_TAB, this); EventBroadcaster.subscribe(BroadcastMessages.KEY_ENTER, this); var ul = document.getElementById("introtest"); var lis = ul.getElementsByTagName("li"); var result = {}; var response = new List(SetupService.CheckRequirements(true)); response.each(function (res) { var li = document.createElement("li"); if (!ul.hasChildNodes()) { li.className = "on"; } li.rel = res.Key; li.appendChild(document.createTextNode(res.Title)); ul.appendChild(li); result[res.Key] = res.Success; }) var i = 0; var isSuccess = true; setTimeout(function () { doit(result); }, TIME * 2); function doit(res) { var li = lis.item(i); var rel = li.rel; li.className += res[rel] ? " ok" : " bad"; var is = res[rel]; if (!is) { Welcome.params += (Welcome.params.length > 0 ? ";" : "") + li.rel; } if (isSuccess) { isSuccess = is; } var next = lis.item(i + 1); if (next != null) { next.className = "on"; } var wait = TIME * Math.random(); if (i++ < lis.length - 1) { setTimeout(function () { doit(res); }, wait); } else { setTimeout(function () { Welcome.result(isSuccess); }, wait); } } } /** * Test result. */ this.result = function (isSuccess) { var successtext = document.getElementById("introtestsuccess"); var failuretext = document.getElementById("introtestfailure"); var successbutton = bindingMap.introtestsuccessbutton; var failurebutton = bindingMap.introtestfailurebutton; if (isSuccess) { successtext.style.visibility = "visible"; successbutton.getBindingElement().style.visibility = "visible"; } else { successtext.style.display = "none"; failuretext.style.display = "block"; successbutton.hide(); failurebutton.setURL(failurebutton.getURL() + Welcome.params); failurebutton.show(); } } /** * Switch to deck. * @param {String} id */ this.switchTo = function (id) { switch (id) { case "test": break; case "license": var doc = SetupService.GetLicenseHtml(true); var markup = DOMSerializer.serialize(doc); document.getElementById("licensetext").innerHTML = markup; break; case "setup": if (!hasSetup) { getSetup(); hasSetup = true; } break; case "language": updateSetup(); if (!hasLanguages) { getLanguages(); hasLanguages = true; } prepareForm("languageform"); break; case "login": var form = document.getElementById("loginform"); prepareForm("loginform"); setConsoleLanguage(); break; } bindingMap.introdecks.select(id); bindingMap.navdecks.select("nav" + id); var p = document.getElementById("crumbs"); var spans = new List(p.getElementsByTagName("span")); spans.each(function (span) { if (span.id == "crumb" + id) { span.className = "text-primary"; } else { span.className = ""; } }); } function setConsoleLanguage() { document.getElementById("consolelanguage").value = document.getElementById("websitelanguage").value; } function getLanguages() { var langs = new List(SetupService.GetLanguages(true)); var markup = ""; langs.each(function (lang) { markup += ""; }); var selector = document.getElementById("websitelanguage"); selector.innerHTML = markup; selector = document.getElementById("consolelanguage"); selector.innerHTML = markup; } /** * @param {String} id */ function prepareForm(id) { var form = document.getElementById(id); var elements = new List(form.elements); if (!form.isPrepared) { form.isPrepared = true; elements.each(function (element, index) { element.onfocus = function () { window.standardEventHandler.enableNativeKeys(); tabindex = index; if (this.type == "text" || this.type == "password") { var input = this; setTimeout(function () { if (Client.isExplorer) { var range = input.createTextRange(); range.moveStart("character", 0); range.moveEnd("character", input.value.length); range.select(); } else { input.setSelectionRange(0, input.value.length); } }, 0); } } element.onblur = function () { window.standardEventHandler.disableNativeKeys(); switch (this.id) { case "password": if (this.value != "" && this.value.length < 6) { badPassLength(true); } else if (hasLength) { badPassLength(false); } break; case "passcheck": var password = document.getElementById("password"); if (password.value != "") { if (password.value != this.value) { noneShallPass(true); } else if (hasBlock) { noneShallPass(false); } } break; } } if (id == "loginform") { element.onkeyup = function () { validate(); } if (element.id == "newsletter") { element.onclick = function () { validate(); } } } }); } elements.get(0).focus(); } // isRFC822ValidEmail function by Ross Kendall, http://rosskendall.com/ - added '.' check. function isRFC822ValidEmail(sEmail) { var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'; var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'; var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'; var sQuotedPair = '\\x5c[\\x00-\\x7f]'; var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d'; var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22'; var sDomain_ref = sAtom; var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')'; var sWord = '(' + sAtom + '|' + sQuotedString + ')'; var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*'; var sLocalPart = sWord + '(\\x2e' + sWord + ')*'; var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec var sValidEmail = '^' + sAddrSpec + '$'; // as whole string var reValidEmail = new RegExp(sValidEmail); if (reValidEmail.test(sEmail) && sEmail.indexOf('.') != -1) { return true; } return false; } function validate() { var username = document.getElementById("username"); var password = document.getElementById("password"); var passcheck = document.getElementById("passcheck"); var email = document.getElementById("email"); var newsletter = document.getElementById("newsletter"); var isValid = false; if (username.value != "") { if (password.value.length >= 6 && passcheck.value.length >= 6) { if (password.value == passcheck.value) { if (isRFC822ValidEmail(email.value)) { isValid = true; } } } } if (isValid) { bindingMap.startbutton.enable(); if (hasBlock) { noneShallPass(false); } } else { bindingMap.startbutton.disable(); } return isValid; } /** * @param {boolean} isBad */ function badPassLength(isBad) { if (hasBlock) { noneShallPass(false); } var p = document.getElementById("lengthbad"); if (isBad) { p.style.display = "block"; } else { p.style.display = "none"; } hasLength = isBad; } /** * @param {boolean} isBlock */ function noneShallPass(isBlock) { if (hasLength) { badPassLength(false); } var p = document.getElementById("loginbad"); if (isBlock) { p.style.display = "block"; } else { p.style.display = "none"; } hasBlock = isBlock; } /** * @implements {IBroadcastListener} * @param {String} broadcast */ this.handleBroadcast = function (broadcast) { var decks = bindingMap.introdecks; var deck = decks.getSelectedDeckBinding(); var id = deck.getID() if (id == "language" || id == "login") { switch (broadcast) { case BroadcastMessages.KEY_TAB: var form = document.getElementById(id + "form"); var elements = form.elements; var index = 0; if (Keyboard.isShiftPressed) { if (tabindex == 0) { index = elements.length - 1; } else { index = --tabindex; } } else { if (tabindex != elements.length - 1) { index = ++tabindex; } } elements[index].focus(); tabindex = index; break; case BroadcastMessages.KEY_ENTER: if (id == "login") { if (validate()) { this.login(); } } break; } } } /** * Mount setup options. */ function getSetup() { var transformer = new XSLTransformer(); transformer.importStylesheet("${root}/welcome.xsl"); setup = SetupService.GetSetupDescription(true); var html = transformer.transformToString(setup, true); html = Client.fixUI(html); var target = document.getElementById("setuptext"); target.innerHTML = setup.documentElement.getAttribute("desc"); target = document.getElementById("setupfields"); target.innerHTML = html.replace(/xmlns:ui=\"urn:HACKED\"/g, "").replace('',""); DocumentManager.attachBindings(target); } function updateSetup() { // reset setup result if (Client.isWebKit) { // huh? Cannot clone document node? var xml = DOMSerializer.serialize(setup); clone = XMLParser.parse(xml); } else { clone = setup.cloneNode(true); } var keys = {}; var radios = new List(); var elements = new List(clone.getElementsByTagName("*")); elements.each(function (element) { // IE no speak getElementsByTagName ( "radio" )! if (element.nodeName == "radio") { radios.add(element); } }); radios.each(function (radio) { radio.removeAttribute("selected"); keys[radio.getAttribute("key")] = radio; }); var target = document.getElementById("setupfields"); var groups = new List(DOMUtil.getElementsByTagName (target, "radiodatagroup")); // update setup result groups.each(function (group) { group = UserInterface.getBinding(group); var key = group.getValue(); var radio = keys[key]; radio.setAttribute("selected", "true"); }); // remove unselected elements radios.each(function (radio) { if (radio.getAttribute("selected") == null) { radio.parentNode.removeChild(radio); } else { radio.removeAttribute("selected"); } }); } this.update = function (binding) { switch (binding.constructor) { case RadioDataBinding: updateRadio(binding); break; } } function updateRadio(binding) { var parent = binding.bindingElement.parentNode; var group = UserInterface.getBinding(parent); var radios = group.getChildBindingsByLocalName("radio"); setTimeout(function () { radios.each(function (radio) { var id = "div" + radio.getProperty("value"); var div = document.getElementById(id); if (div != null) { if (radio.isChecked) { CSSUtil.attachClassName(div, "visible"); } else { CSSUtil.detachClassName(div, "visible"); } } }); }, 0); } /** * @param {HTMLInputElement} input */ this.acceptLicense = function (input) { var button = bindingMap.setupbutton; if (input.checked) { button.enable(); } else { button.disable(); } } /** * Login! */ this.login = function () { var self = this; var serial = DOMSerializer.serialize(clone, true); var username = document.getElementById("username").value; var password = document.getElementById("password").value; var email = document.getElementById("email").value; var newsletter = document.getElementById("newsletter").checked; var select = document.getElementById("websitelanguage"); var websitelanguage = select.options[select.selectedIndex].value; select = document.getElementById("consolelanguage"); var consolelanguage = select.options[select.selectedIndex].value; self.loading(); SetupService.SetUp(serial, username, email, password, websitelanguage, consolelanguage, newsletter, function (response) { if (response) { Application.reload(true); } else { clearInterval(progressLoading); alert("An unfortunate error has occurred."); } } ); } /** * Show Loading Deck with progress bar * Progress bar goes from 0 to 100 in 45 seconds - and then restart after 5 seconds (if things are still working). */ this.loading = function () { bindingMap.introdecks.select("loading"); bindingMap.cover.attachClassName("loading-cover"); bindingMap.navdecks.hide(); var current = new Date().getTime(); var end = current + 50000; // total 45 seconds + wait 5 seconds ProgressBarBinding.notch(1); progressLoading = setInterval(function () { if (current > end) { ProgressBarBinding.reload(); progressNotchIndex = 0; end = current + 50000; } ProgressBarBinding.notch(1); current = new Date().getTime(); progressNotchIndex++; }, 2250); // 20 notches * 2.25 seconds = 45 seconds } } ================================================ FILE: Website/Composite/app.aspx ================================================  <%@ Page Language="C#" %> Composite.Management.App <%-- --%> <%-- --%> <%-- --%>
brand
brand
brand